Python math.fabs() Examples

The following are code examples for showing how to use math.fabs(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: spacesense   Author: spacesense-ai   File: utils.py    GNU Lesser General Public License v3.0 8 votes vote down vote up
def optimize_OneClassSVM(X, n):
    print('searching for optimal hyperparameters...')
    nu = np.linspace(start=1e-5, stop=1e-2, num=n)
    gamma = np.linspace(start=1e-6, stop=1e-3, num=n)
    opt_diff = 1.0
    opt_nu = None
    opt_gamma = None
    for i in range(len(nu)):
        for j in range(len(gamma)):
            classifier = svm.OneClassSVM(kernel="rbf", nu=nu[i], gamma=gamma[j])
            classifier.fit(X)
            label = classifier.predict(X)
            p = 1 - float(sum(label == 1.0)) / len(label)
            diff = math.fabs(p - nu[i])
            if diff < opt_diff:
                opt_diff = diff
                opt_nu = nu[i]
                opt_gamma = gamma[j]
    return opt_nu, opt_gamma 
Example 2
Project: UR5_Controller   Author: tsinghua-rll   File: quaternion.py    MIT License 6 votes vote down vote up
def to_euler(q):
    # rpy
    sinr = 2.0 * (q[0] * q[1] + q[2] * q[3])
    cosr = 1.0 - 2.0 * (q[1] * q[1] + q[2] * q[2])
    roll = math.atan2(sinr, cosr)

    sinp = 2.0 * (q[0] * q[2] - q[3] * q[1])
    if math.fabs(sinp) >= 1.:
        pitch = math.copysign(np.pi / 2., sinp)
    else:
        pitch = math.asin(sinp)

    siny = 2.0 * (q[0] * q[3] + q[1] * q[2])
    cosy = 1.0 - 2.0 * (q[2] * q[2] + q[3] * q[3])
    yaw = math.atan2(siny, cosy)

    return np.asarray((roll, pitch, yaw), np.float32) 
Example 3
Project: CozmoCommander   Author: cozmobotics   File: CozmoCommander.py    Apache License 2.0 6 votes vote down vote up
def angle360 (DeltaX, DeltaY):
	if (math.fabs(DeltaX) > 0.01):			# avoid division by 0
		Angle = math.fabs(DeltaY)/math.fabs(DeltaX)
		Angle = math.atan(Angle)
		Angle = math.degrees (Angle)
		# print (Angle)
	else:
		Angle = 90.0
	
	if   ((DeltaX > 0) and (DeltaY > 0)):
		pass
	elif ((DeltaX > 0) and (DeltaY < 0)):
		Angle = 360.0 - Angle
	elif ((DeltaX < 0) and (DeltaY > 0)):
		Angle = 180.0 - Angle
	elif ((DeltaX < 0) and (DeltaY < 0)):
		Angle = 180.0 + Angle
	return (Angle)
	
# ------------------------------------------------------------------- 
Example 4
Project: NAO   Author: AISTLAB   File: kickState.py    MIT License 6 votes vote down vote up
def do(self,nv,nm):
        print "finding."
        direct=-1
        delta=50
        while True:
            x,y,r=nv._ballImageInfo
            if math.fabs(y-nv.IMGH/2)>delta:
              nm.headRelativePitch(0.2*direct)
              time.sleep(0.5)
              if nm.getHeadPitchAngle()<nm.MIN_HEADPITCH:
                direct=1
              elif nm.getHeadPitchAngle()>nm.MAX_HEADPITCH:
                direct=-1
            else:
                self.ballLocation=0
                if x<140:self.ballLocation=-1
                if x>180:self.ballLocation=1
                break
        print self.ballLocation
        self.__class__=self.nextstate 
Example 5
Project: NAO   Author: AISTLAB   File: kickState.py    MIT License 6 votes vote down vote up
def do(self,nv,nm):
        print "kicking."
        nm.poseInit()
        nm.headPitchTo(nm.MAX_HEADPITCH)
        time.sleep(1)
        dety=5
        x,y=nv.getGroundBallDistance(nm.getHeadPitchAngle())
        print x,y
        if math.fabs(y-dety)<1 and (math.fabs(x-5)<2 or math.fabs(x+5)<2):
            nm.poseInit()
            nm.kick(x>0)
            self.__class__=self.nextstate
        if y>-1:
            if x>0:
                nm._motion.walkTo((y-dety)/100.0,-x/100.0+0.05,0,\
                [["MaxStepFrequency", 0.1]])
            else:
               nm._motion.walkTo((y-dety)/100.0,-x/100.0-0.05,0,\
                [["MaxStepFrequency", 0.1]]) 
Example 6
Project: nxt-sketcher   Author: simondolle   File: printer.py    MIT License 6 votes vote down vote up
def compute_circle_intersection(x0, y0, x1, y1, r0, r1):
    d = compute_distance(x0, y0, x1, y1)
    if d < math.fabs(r0 - r1) or r0 +r1 < d:
        return None

    a = (math.pow(r0, 2) - math.pow(r1, 2) + math.pow(d, 2))/float(2 * d)
    h = math.sqrt(math.pow(r0, 2) - math.pow(a, 2))

    x2 = x0 + a * (x1 - x0)/float(d)
    y2 = y0 + a * (y1 - y0)/float(d)

    x3 = x2 + h * (y1 - y0)/ d
    y3 = y2 - h * (x1 - x0)/ d

    x3_prime = x2 - h * (y1 - y0)/ d
    y3_prime = y2 + h * (x1 - x0)/ d
    return (x3, y3), (x3_prime, y3_prime) 
Example 7
Project: ngo-addons-backport   Author: camptocamp   File: graph.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def rev_edges(self, tree):
        """reverse the direction of the edges whose source-node-partail_order> destination-node-partail_order
        to make the graph acyclic
        """
        Is_Cyclic = False
        i=0
        for link in self.links:
            src = link[0]
            des = link[1]
            edge_len = self.partial_order[des]['level'] - self.partial_order[src]['level']
            if edge_len < 0:
                del self.links[i]
                self.links.insert(i, (des, src))
                self.transitions[src].remove(des)
                self.transitions.setdefault(des, []).append(src)
                Is_Cyclic = True
            elif math.fabs(edge_len) > 1:
                Is_Cyclic = True
            i += 1

        return Is_Cyclic 
Example 8
Project: xia2   Author: xia2   File: AutoindexHelpers.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_distance(detector, distance):
    panel = detector[0]
    d_normal = matrix.col(panel.get_normal())
    d_origin = matrix.col(panel.get_origin())
    d_distance = math.fabs(d_origin.dot(d_normal) - panel.get_directed_distance())
    assert d_distance < 0.001, d_distance
    translation = d_normal * (distance - panel.get_directed_distance())
    new_origin = d_origin + translation
    d_distance = math.fabs(new_origin.dot(d_normal) - distance)
    assert d_distance < 0.001, d_distance
    fast = panel.get_fast_axis()
    slow = panel.get_slow_axis()
    panel.set_frame(panel.get_fast_axis(), panel.get_slow_axis(), new_origin.elems)
    d_fast = matrix.col(panel.get_fast_axis()).angle(matrix.col(fast), deg=True)
    assert d_fast < 1e-4, d_fast
    d_slow = matrix.col(panel.get_slow_axis()).angle(matrix.col(slow), deg=True)
    assert d_slow < 1e-4, d_slow
    d_distance = math.fabs(panel.get_directed_distance() - distance)
    assert d_distance < 0.001, d_distance 
Example 9
Project: ns3   Author: KyleBenson   File: hud.py    GNU General Public License v2.0 6 votes vote down vote up
def _compute_divisions(self, xi, xf):
        assert xf > xi
        dx = xf - xi
        size = dx
        ndiv = 5
        text_width = dx/ndiv/2

        def rint(x):
            return math.floor(x+0.5)
        
        dx_over_ndiv = dx / ndiv
        for n in range(5): # iterate 5 times to find optimum division size
            #/* div: length of each division */
            tbe = math.log10(dx_over_ndiv)#;   /* looking for approx. 'ndiv' divisions in a length 'dx' */
            div = pow(10, rint(tbe))#;	/* div: power of 10 closest to dx/ndiv */
            if math.fabs(div/2 - dx_over_ndiv) < math.fabs(div - dx_over_ndiv): #/* test if div/2 is closer to dx/ndiv */
                div /= 2
            elif math.fabs(div*2 - dx_over_ndiv) < math.fabs(div - dx_over_ndiv):
                div *= 2 #			/* test if div*2 is closer to dx/ndiv */
            x0 = div*math.ceil(xi / div) - div
            if n > 1:
                ndiv = rint(size / text_width)
        return x0, div 
Example 10
Project: ns3   Author: bvamanan   File: hud.py    GNU General Public License v2.0 6 votes vote down vote up
def _compute_divisions(self, xi, xf):
        assert xf > xi
        dx = xf - xi
        size = dx
        ndiv = 5
        text_width = dx/ndiv/2

        def rint(x):
            return math.floor(x+0.5)
        
        dx_over_ndiv = dx / ndiv
        for n in range(5): # iterate 5 times to find optimum division size
            #/* div: length of each division */
            tbe = math.log10(dx_over_ndiv)#;   /* looking for approx. 'ndiv' divisions in a length 'dx' */
            div = pow(10, rint(tbe))#;	/* div: power of 10 closest to dx/ndiv */
            if math.fabs(div/2 - dx_over_ndiv) < math.fabs(div - dx_over_ndiv): #/* test if div/2 is closer to dx/ndiv */
                div /= 2
            elif math.fabs(div*2 - dx_over_ndiv) < math.fabs(div - dx_over_ndiv):
                div *= 2 #			/* test if div*2 is closer to dx/ndiv */
            x0 = div*math.ceil(xi / div) - div
            if n > 1:
                ndiv = rint(size / text_width)
        return x0, div 
Example 11
Project: mptcp_with_machine_learning   Author: JamesRaynor67   File: hud.py    GNU General Public License v2.0 6 votes vote down vote up
def _compute_divisions(self, xi, xf):
        assert xf > xi
        dx = xf - xi
        size = dx
        ndiv = 5
        text_width = dx/ndiv/2

        def rint(x):
            return math.floor(x+0.5)
        
        dx_over_ndiv = dx / ndiv
        for n in range(5): # iterate 5 times to find optimum division size
            #/* div: length of each division */
            tbe = math.log10(dx_over_ndiv)#;   /* looking for approx. 'ndiv' divisions in a length 'dx' */
            div = pow(10, rint(tbe))#;	/* div: power of 10 closest to dx/ndiv */
            if math.fabs(div/2 - dx_over_ndiv) < math.fabs(div - dx_over_ndiv): #/* test if div/2 is closer to dx/ndiv */
                div /= 2
            elif math.fabs(div*2 - dx_over_ndiv) < math.fabs(div - dx_over_ndiv):
                div *= 2 #			/* test if div*2 is closer to dx/ndiv */
            x0 = div*math.ceil(xi / div) - div
            if n > 1:
                ndiv = rint(size / text_width)
        return x0, div 
Example 12
Project: wechat_jump_ai   Author: michaelfeng   File: agent.py    MIT License 6 votes vote down vote up
def is_over(self):
        is_over = False
        # check if the game is over
        time.sleep(random.uniform(0.7, 1.1)) 
        #print("snapchat!!!")
        self.pull_screenshot()
        im = Image.open("./1.png")
        ts = int(time.time())
        piece_x, piece_y, board_x, board_y = map(int, self.find_piece_and_board(im))
        self.save_debug_creenshot(ts, im, piece_x, piece_y, board_x, board_y)
        self.backup_screenshot(ts)
        bias = int(math.sqrt(math.fabs(board_x - self.x) ** 2 + math.fabs(board_y - self.y) ** 2)/100)
        print("bias: ", bias)
        #print("last x: ",self.x)
        #print("last y: ", self.y)
        if (piece_x == 0 and piece_y == 0) or bias > 10:
            is_over = True
        self.x = piece_x
        self.y = piece_y
        '''
        print("new x:",piece_x)
        print("new y:",piece_y)
        print("new target x:", board_x)
        print("new target y:" ,board_y)'''
        return is_over, bias 
Example 13
Project: HEG_ESP32   Author: moothyknight   File: simplegraphs.py    MIT License 6 votes vote down vote up
def UpdateMovie(self, data, times):
        self.midplot.Update(data[-320:], numpy.array(times[-320:]) - times[0], zero_x=False)
        
        delta = mean(data[-5:]) - mean(data[-50:])
        sigma = numpy.std(data[-300:])
        
        contrast = 1./(1+math.e**(-delta/sigma*5.))*100. - 85.
        zoom     = 1./(1+math.e**(-delta/sigma*2.))
        
        trend = 1./(1+math.e**(-delta/sigma)) * 2 - 1

        r = int((1-max(-trend, 0))*64)
        g = int((1-math.fabs(trend))*64)
        b = int((1-max( trend, 0))*64)
        if trend < 0:
            b = 95 + int(-trend*160)
        else:
            r = 95 + int(trend*160)
        self.trendmeter.SetColor(wx.Color(r,g,b))
        self.trendmeter.SetValue(trend)
        
        InstrumentsPanel.UpdateMovie(self, data, times) 
Example 14
Project: BlueLightMeter   Author: chripell   File: blm_client.py    Apache License 2.0 5 votes vote down vote up
def find_nearer(self, val, l):
        min = 1e10
        ret = l[0]
        for i in l:
            diff = math.fabs(self.make_float(i) - val)
            if diff < min:
                ret = i
                min = diff
        return ret 
Example 15
Project: pyblish-win   Author: pyblish   File: test_math.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testFabs(self):
        self.assertRaises(TypeError, math.fabs)
        self.ftest('fabs(-1)', math.fabs(-1), 1)
        self.ftest('fabs(0)', math.fabs(0), 0)
        self.ftest('fabs(1)', math.fabs(1), 1) 
Example 16
Project: CozmoCommander   Author: cozmobotics   File: CozmoCommander.py    Apache License 2.0 5 votes vote down vote up
def check_tol(charger: cozmo.objects.Charger,dist_charger=40):
    # Check if the position tolerance in front of the charger is respected
    global RobotGlobal
    robot = RobotGlobal
    global PI

    distance_tol = 5 # mm, tolerance for placement error
    angle_tol = 5*PI/180 # rad, tolerance for orientation error

    try: 
        charger = robot.world.wait_for_observed_charger(timeout=2,include_existing=True)
    except:
        debug (1,'WARNING: Cannot see the charger to verify the position.')

    # Calculate positions
    r_coord = [0,0,0]
    c_coord = [0,0,0]
    # Coordonates of robot and charger
    r_coord[0] = robot.pose.position.x #.x .y .z, .rotation otherwise
    r_coord[1] = robot.pose.position.y
    r_coord[2] = robot.pose.position.z
    r_zRot = robot.pose_angle.radians # .degrees or .radians
    c_coord[0] = charger.pose.position.x
    c_coord[1] = charger.pose.position.y
    c_coord[2] = charger.pose.position.z
    c_zRot = charger.pose.rotation.angle_z.radians

    # Create target position 
    # dist_charger in mm, distance if front of charger
    c_coord[0] -=  dist_charger*math.cos(c_zRot)
    c_coord[1] -=  dist_charger*math.sin(c_zRot)

    # Direction and distance to target position (in front of charger)
    distance = math.sqrt((c_coord[0]-r_coord[0])**2 + (c_coord[1]-r_coord[1])**2 + (c_coord[2]-r_coord[2])**2)

    if(distance < distance_tol and math.fabs(r_zRot-c_zRot) < angle_tol):
    	return 1
    else: 
    	return 0 
Example 17
Project: CozmoCommander   Author: cozmobotics   File: CozmoCommander.py    Apache License 2.0 5 votes vote down vote up
def goToCharger(robot: cozmo.robot.Robot):
	
	# +++ todo: go_to_pose is not accurate enough. Therefore, stop in front of the charger looking to it, find the charger, adjust robot position, and then back up. 
	# +++ todo: When on charger, drive off chager contacts. 

	if (robot.is_on_charger):
		robot.drive_off_charger_contacts(robot).wait_for_completed()
		robot.drive_straight(distance_mm(100), speed_mmps(100))
	else:
		get_on_charger()
	
		# robot.go_to_pose(Pose(150, 0, 0, angle_z=degrees(180))).wait_for_completed()
		# Charger = robot.world.wait_for_observed_charger(timeout=2, include_existing=True)
		# if (Charger):
			
			# YPos = robot.world.charger.pose.position.y
			# AngleZ = robot.world.charger.pose.rotation.angle_z.degrees
			# print ("Charger Y:" + str(round(YPos)) + " Angle:" + str(round(AngleZ)) )
			
			# # if (math.fabs(YPos) > 15): 
				# # pass # adjust position
			
			# robot.go_to_pose(Pose(100, YPos, 0, angle_z=degrees(AngleZ-180))).wait_for_completed()
			
			# robot.backup_onto_charger(max_drive_time=5)
			# if (robot.is_on_charger):
				# print ("Success!")
			
		# else: 
			# print ("Sorry, cannot see the charger. Have you moved it away?")


#---------------------------------------------------------------- 
Example 18
Project: kipet   Author: salvadorgarciamunoz   File: Simulator.py    GNU General Public License v3.0 5 votes vote down vote up
def find_nearest(array,value):
    idx = np.searchsorted(array, value, side="left")
    if idx == len(array) or idx==len(array)-1 or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx]):
        return idx-1
    else:
        return idx 
Example 19
Project: MODS_ConvNet   Author: santiagolopezg   File: dataset_MODS.py    MIT License 5 votes vote down vote up
def Dset(self, ndataset=7, name='MODS_data.pkl'):
         '''
         function to build datasets. ndataset: number of datasets wanted; 
         name: pkl file where the data from DSetGlobal is stored. Code makes sure
         that there is the same ratio of positive/negative images in each dataset.
         This is done, setting a lmda. If you set a really low lmda, you might have
         to stop the program and rerun it a few times.
         Returns a pkl with a segmented dataset. seg_data is a list of n lists, where n
         is the number of datasets desired. These n lists consist of 2 lists: the data
         and its corresponding labels.
         '''
         f = file(name, 'rb')
         datapapa = cPickle.load(f)
         f.close()    
         w = datapapa[0]
         x = datapapa[1]
         y = range(len(x))
         seg_data = []
         counter = 0
         size = int(len(y)/float(ndataset))
         while counter < ndataset:
             z = random.sample(y, size)
             lmda = 0.0005
             ratio = float(sum([x[i] for i in z]))/(len([x[i] for i in z if x[i]==0]))
             print(ratio)
             dif = math.fabs(ratio-1) #ratio of positive to negatives
             if dif < lmda:
                 print('BINGO!', counter, dif)
                 y = [i for i in y if i not in z]
                 current_label = [x[i] for i in z]
                 current_data = [w[i] for i in z]
                 seg_data.append([current_data, current_label])
                 counter+=1
             else:
                 #print('Does not have a acceptable ratio', ratio, dif)
                 #fun+= 1
                 pass 
         f = file('seg_MODS_data.pkl', 'wb')
         cPickle.dump(seg_data, f, protocol=cPickle.HIGHEST_PROTOCOL)
         f.close() 
Example 20
Project: MODS_ConvNet   Author: santiagolopezg   File: dataset_MODS.py    MIT License 5 votes vote down vote up
def Dset(self, ndataset=7, name='MODS_data.pkl'):
         '''
         function to build datasets. ndataset: number of datasets wanted; 
         name: pkl file where the data from DSetGlobal is stored. Code makes sure
         that there is the same ratio of positive/negative images in each dataset.
         This is done, setting a lmda. If you set a really low lmda, you might have
         to stop the program and rerun it a few times.
         Returns a pkl with a segmented dataset. seg_data is a list of n lists, where n
         is the number of datasets desired. These n lists consist of 2 lists: the data
         and its corresponding labels.
         '''
         f = file(name, 'rb')
         datapapa = cPickle.load(f)
         f.close()    
         w = datapapa[0]
         x = datapapa[1]
         y = range(len(x))
         seg_data = []
         counter = 0
         size = int(len(y)/float(ndataset))
         while counter < ndataset:
             z = random.sample(y, size)
             lmda = 0.0005
             ratio = float(sum([x[i] for i in z]))/(len([x[i] for i in z if x[i]==0]))
             print(ratio)
             dif = math.fabs(ratio-1) #ratio of positive to negatives
             if dif < lmda:
                 print('BINGO!', counter, dif)
                 y = [i for i in y if i not in z]
                 current_label = [x[i] for i in z]
                 current_data = [w[i] for i in z]
                 seg_data.append([current_data, current_label])
                 counter+=1
             else:
                 #print('Does not have a acceptable ratio', ratio, dif)
                 #fun+= 1
                 pass 
         f = file('seg_MODS_data.pkl', 'wb')
         cPickle.dump(seg_data, f, protocol=cPickle.HIGHEST_PROTOCOL)
         f.close() 
Example 21
Project: tensorflow_generate_headlines   Author: FanWan   File: textrank_word2vec.py    GNU General Public License v3.0 5 votes vote down vote up
def different(scores, old_scores):
    """
    判断前后分数有无变化
    :param scores:
    :param old_scores:
    :return:
    """
    flag = False
    for i in range(len(scores)):
        if math.fabs(scores[i] - old_scores[i]) >= max_textrank_error:
            flag = True
            break
    return flag 
Example 22
Project: spqrel_tools   Author: LCAS   File: gotopos.py    MIT License 5 votes vote down vote up
def plannerstatus_cb(value):
    global tts_service 
    global goal_reached
    global memory_service
    print "NAOqi Planner status: ",value # GoalReached, PathFound, PathNotFound, WaitingForGoal
    if (value=='GoalReached'):
        goal_reached = True
    elif (value=='PathNotFound'):
        mem_key_execstatus = "NAOqiPlanner/ExecutionStatus"
        try:
            #v = memory_service.getData(mem_key_execstatus)
            v = [9,9]
            print "NAOqiPlanner/ExecutionStatus = ",v
        except:
            return

        print "Goto:: distance and angle to goal: ", v
        distToGoal = v[0]
        angleToGoal = v[1]
        
        if (math.fabs(angleToGoal)<0.1 and distToGoal<3.0):
            dist = int(distToGoal * 10) / 10.0
            tts_service.say("I cannot reach the goal, but I know that it is quite close in front of me. Can you please push me ahead for about "+str(dist)+" meters?")

        set_condition(memory_service,'pathnotfound','true')
        time.sleep(1)
        set_condition(memory_service,'pathnotfound','false')

        if (distToGoal<1.0):
            set_condition(memory_service,'closetotarget','true')
            time.sleep(1)
            set_condition(memory_service,'closetotarget','false') 
Example 23
Project: spqrel_tools   Author: LCAS   File: storecentralperson.py    MIT License 5 votes vote down vote up
def find_center_person(plist, memory_service):
    min_y = 1e8
    p_id = None
    try:
        for p in plist:
            positionInRobotFrame = memory_service.getData(
                "PeoplePerception/Person/" + str(p) +
                "/PositionInRobotFrame"
            )
            if fabs(positionInRobotFrame[1]) < min_y:
                min_y = fabs(positionInRobotFrame[1])
                px = positionInRobotFrame[0]
                py = positionInRobotFrame[1]

                p_id = p
        if p_id is not None:
            w_px, w_py = point2world(
                memory_service,
                [px - 1.5, py]
            )
            return p_id, w_px, w_py
        else:
            return -1, 0, 0

    except Exception as e:
        print '*** FAILED TO FIND CENTER PERSON: %s' % str(e)
        return -1, 0, 0 
Example 24
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_trotting_env.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def is_fallen(self):
    """Decide whether the minitaur has fallen.

    Returns:
      Boolean value that indicates whether the minitaur has fallen.
    """
    roll, pitch, _ = self.minitaur.GetTrueBaseRollPitchYaw()
    is_fallen = math.fabs(roll) > 0.3 or math.fabs(pitch) > 0.3
    return is_fallen 
Example 25
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_reactive_env.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def is_fallen(self):
    """Decides whether the minitaur is in a fallen state.

    If the roll or the pitch of the base is greater than 0.3 radians, the
    minitaur is considered fallen.

    Returns:
      Boolean value that indicates whether the minitaur has fallen.
    """
    roll, pitch, _ = self.minitaur.GetTrueBaseRollPitchYaw()
    return math.fabs(roll) > 0.3 or math.fabs(pitch) > 0.3 
Example 26
Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_four_leg_stand_env.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _reward(self):
    roll, pitch, _ = self.minitaur.GetBaseRollPitchYaw()
    return 1.0 / (0.001 + math.fabs(roll) + math.fabs(pitch)) 
Example 27
Project: NAO   Author: AISTLAB   File: mLongRun.py    MIT License 5 votes vote down vote up
def getLineInfo(p1,p2):
  t=0
  if p1[1]!=p2[1]:
    t=(p1[0]-p2[0])/float(p1[1]-p2[1])
  if math.fabs(t)<0.1:t=0
  return math.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2),t 
Example 28
Project: FPStalker   Author: Spirals-Team   File: fingerprint.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def getTimeDifference(self, fp):
        try:
            diff = self.getStartTime() - fp.getStartTime()
            return mt.fabs(diff.days + diff.seconds / (3600.0 * 24))
        except:  # for the case where we try to link blink's fingerprints
            return self.getCounter() - fp.getCounter() 
Example 29
Project: nxt-sketcher   Author: simondolle   File: printer.py    MIT License 5 votes vote down vote up
def area(ll, ur):
    return math.fabs((ll.x - ur.x) * (ll.y - ur.y)) 
Example 30
Project: rtreelib   Author: sergkr   File: guttman.py    MIT License 5 votes vote down vote up
def _pick_next(remaining_entries: List[RTreeEntry[T]],
               group1_rect: Rect,
               group1_area: float,
               group2_rect: Rect,
               group2_area: float) -> RTreeEntry[T]:
    max_diff = None
    result = None
    for e in remaining_entries:
        d1 = group1_rect.union(e.rect).area() - group1_area
        d2 = group2_rect.union(e.rect).area() - group2_area
        diff = math.fabs(d1 - d2)
        if max_diff is None or diff > max_diff:
            max_diff = diff
            result = e
    return result 
Example 31
Project: xia2   Author: xia2   File: LatticeExpert.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ComputeBDistortion(cell1, cell2):
    """Compute the distortion required to get from cell1 to cell2."""

    return sum(math.fabs(cell2[j] - cell1[j]) for j in range(6)) 
Example 32
Project: xia2   Author: xia2   File: BackstopMask.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def line_intersect_rectangle(o, d, nx, ny):
    """Calculate where a line starting at origin o and heading in direction d
    intersects rectangle bounded by (0,0), (nx, 0), (nx, ny), (0, ny)."""

    # requirements are:
    #
    # direction not perpendicular to axis:
    #  intersection is within range:
    #    direction to intersection point is positive:
    #      return this

    assert math.fabs(dot(d, d) - 1) < 0.001

    if d[0] != 0.0:
        intersection = o[1] - (o[0] / d[0]) * d[1]
        if 0 <= intersection <= ny:
            if dot((0.0 - o[0], intersection - o[1]), d) > 0.0:
                return (0.0, intersection)

        intersection = o[1] - ((o[0] - nx) / d[0]) * d[1]
        if 0 <= intersection <= ny:
            if dot((nx - o[0], intersection - o[1]), d) > 0.0:
                return (nx, intersection)

    if d[1] != 0.0:
        intersection = o[0] - (o[1] / d[1]) * d[0]
        if 0 <= intersection <= nx:
            if dot((intersection - o[0], 0.0 - o[1]), d) > 0.0:
                return (intersection, 0.0)

        intersection = o[0] - ((o[1] - ny) / d[1]) * d[0]
        if 0 <= intersection <= nx:
            if dot((intersection - o[0], ny - o[1]), d) > 0.0:
                return (intersection, ny)

    raise RuntimeError("intersection not found") 
Example 33
Project: xia2   Author: xia2   File: DialsIndexer.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _compare_cell(self, c_ref, c_test):
        """Compare two sets of unit cell constants: if they differ by
        less than 5% / 5 degrees return True, else False."""

        for j in range(3):
            if math.fabs((c_test[j] - c_ref[j]) / c_ref[j]) > 0.05:
                return False

        for j in range(3, 6):
            if math.fabs(c_test[j] - c_ref[j]) > 5:
                return False

        return True 
Example 34
Project: pymoku   Author: liquidinstruments   File: _specan.py    MIT License 5 votes vote down vote up
def _calculate_cic_freq_resp(self, f, dec, order):
        """
        Calculate the CIC filter droop correction.
        In this case 'f' is the frequency (Hz) relative to the demodulation
        frequency.
        """
        freq = f / _SA_ADC_SMPS

        correction = 1.0 if (freq == 0.0) else math.pow(
            math.fabs(math.sin(math.pi * freq * dec) / (
                      math.sin(math.pi * freq) * dec)), order)

        return correction 
Example 35
Project: razzy-spinner   Author: rafasashi   File: vader.py    GNU General Public License v3.0 5 votes vote down vote up
def _sift_sentiment_scores(self, sentiments):
        # want separate positive versus negative sentiment scores
        pos_sum = 0.0
        neg_sum = 0.0
        neu_count = 0
        for sentiment_score in sentiments:
            if sentiment_score > 0:
                pos_sum += (float(sentiment_score) +1) # compensates for neutral words that are counted as 1
            if sentiment_score < 0:
                neg_sum += (float(sentiment_score) -1) # when used with math.fabs(), compensates for neutrals
            if sentiment_score == 0:
                neu_count += 1
        return pos_sum, neg_sum, neu_count 
Example 36
Project: razzy-spinner   Author: rafasashi   File: vader.py    GNU General Public License v3.0 5 votes vote down vote up
def score_valence(self, sentiments, text):
        if sentiments:
            sum_s = float(sum(sentiments))
            # compute and add emphasis from punctuation in text
            punct_emph_amplifier = self._punctuation_emphasis(sum_s, text)
            if sum_s > 0:
                sum_s += punct_emph_amplifier
            elif  sum_s < 0:
                sum_s -= punct_emph_amplifier

            compound = normalize(sum_s)
            # discriminate between positive, negative and neutral sentiment scores
            pos_sum, neg_sum, neu_count = self._sift_sentiment_scores(sentiments)

            if pos_sum > math.fabs(neg_sum):
                pos_sum += (punct_emph_amplifier)
            elif pos_sum < math.fabs(neg_sum):
                neg_sum -= (punct_emph_amplifier)

            total = pos_sum + math.fabs(neg_sum) + neu_count
            pos = math.fabs(pos_sum / total)
            neg = math.fabs(neg_sum / total)
            neu = math.fabs(neu_count / total)

        else:
            compound = 0.0
            pos = 0.0
            neg = 0.0
            neu = 0.0

        sentiment_dict = \
            {"neg" : round(neg, 3),
             "neu" : round(neu, 3),
             "pos" : round(pos, 3),
             "compound" : round(compound, 4)}

        return sentiment_dict 
Example 37
Project: RTX   Author: RTXteam   File: wvector.py    MIT License 5 votes vote down vote up
def __len__(self):
        """ non-zero length """
        return sum(map(len, self.values())) if not FLAGS.nonzerolen else \
            sum(len(filter(lambda v: math.fabs(v.first) > 1e-3, feats.values()))
                for feats in self.values()) 
Example 38
Project: zed-python-api   Author: stereolabs   File: tracking_viewer.py    MIT License 5 votes vote down vote up
def get_color(num_segments, i):
    r = math.fabs(1. - (float(i) * 2.) / float(num_segments))
    c1 = 0.1 * r
    c2 = 0.3 * r
    c3 = 0.8 * r
    return c1, c2, c3 
Example 39
Project: pykaldi   Author: pykaldi   File: kaldi-math-test.py    Apache License 2.0 5 votes vote down vote up
def testDefines(self):
        self.assertAlmostEqual(0.0, kaldi_math.exp(kaldi_math.LOG_ZERO_FLOAT))
        self.assertAlmostEqual(0.0, kaldi_math.exp(kaldi_math.LOG_ZERO_DOUBLE))

        # TODO:
        # How to test these in Python?

        # den = 0.0
        # self.assertTrue(kaldi_math.KALDI_ISNAN(0.0 / den))
        # self.assertFalse(kaldi_math.KALDI_ISINF(0.0 / den))
        # self.assertFalse(kaldi_math.KALDI_ISFINITE(0.0 / den))
        # self.assertFalse(kaldi_math.KALDI_ISNAN(1.0 / den))
        # self.assertTrue(kaldi_math.KALDI_ISINF(1.0 / den))
        # self.assertFalse(kaldi_math.KALDI_ISFINITE(1.0 / den))
        # self.assertTrue(kaldi_math.KALDI_ISFINITE(0.0))
        # self.assertFalse(kaldi_math.KALDI_ISINF(0.0))
        # self.assertFalse(kaldi_math.KALDI_ISNAN(0.0))


        self.assertTrue(1.0 != 1.0 + kaldi_math.DBL_EPSILON)
        self.assertTrue(1.0 == 1.0 + 0.5 * kaldi_math.DBL_EPSILON)
        # self.assertNotAlmostEqual(1.0, 1.0 + kaldi_math.FLT_EPSILON, places = 7)
        # self.assertAlmostEqual(1.0, 1.0 + 0.5 * kaldi_math.FLT_EPSILON, places = 6)

        self.assertAlmostEqual(0.0, math.fabs(math.sin(kaldi_math.M_PI)))
        self.assertAlmostEqual(1.0, math.fabs(math.cos(kaldi_math.M_PI)))
        self.assertAlmostEqual(0.0, math.fabs(math.sin(kaldi_math.M_2PI)))
        self.assertAlmostEqual(1.0, math.fabs(math.cos(kaldi_math.M_2PI)))

        self.assertAlmostEqual(0.0, math.fabs(math.sin(kaldi_math.exp(kaldi_math.M_LOG_2PI))), places = 5)
        self.assertAlmostEqual(1.0, math.fabs(math.cos(kaldi_math.exp(kaldi_math.M_LOG_2PI))), places = 5) 
Example 40
Project: robot-navigation   Author: ronaldahmed   File: decisiontree.py    MIT License 5 votes vote down vote up
def _flip(self, sx, nsx, xs, ys, prob, last = None):
        if self._trace: print 'flip', sx, nsx, last, ys
        table = []
        for y in ys:
            p1y = self._sum_probs(prob, sx, [y])
            p2y = self._sum_probs(prob, nsx, [y])
            if p1y + p2y != 0:
                table.append((p1y / (p1y + p2y), y))
            else:
                table.append((0, y))

        table.sort()
        if self._trace: print 'flip -- table', table
        max = None
        for i in range(1, len(table)):
            sy = map(lambda x: x[1], table[:i])
            nsy = map(lambda x: x[1], table[i:])
            sy.sort()
            nsy.sort()
            
            I = self._mutual_information(sx, sy, nsx, nsy, prob)
            if max == None or I > max[0]:
                    max = (I, (sy, nsy))

        if self._trace: print 'flip -- max', max
        if max == None:
            return (((sx, nsx), (ys, [])), 0.0)

        if last != None and math.fabs(max[0] - last) < 1e-6:
            return (((sx, nsx), max[1]), max[0])
        else:
            return self._flop(max[1][0], max[1][1], xs, ys, prob, max[0]) 
Example 41
Project: robot-navigation   Author: ronaldahmed   File: decisiontree.py    MIT License 5 votes vote down vote up
def _flop(self, sy, nsy, xs, ys, prob, last = None):
        if self._trace: print 'flop', sy, nsy, last, xs
        table = []
        for x in xs:
            px1 = self._sum_probs(prob, [x], ys)
            px2 = self._sum_probs(prob, [x], nsy)
            if px1 + px2 != 0:
                table.append((px1 / (px1 + px2), x))
            else:
                table.append((0, x))

        table.sort()
        if self._trace: print 'flop -- table', table
        max = None
        for i in range(1, len(table)):
            sx = map(lambda x: x[1], table[:i])
            nsx = map(lambda x: x[1], table[i:])
            sx.sort()
            nsx.sort()
            
            I = self._mutual_information(sx, sy, nsx, nsy, prob)
            if max == None or I > max[0]:
                max = (I, (sx, nsx))

        if self._trace: print 'flop -- max', max
        if max == None:
            return (((xs, []), (sy, nsy)), 0.0)

        if last != None and math.fabs(max[0] - last) < 1e-6:
            return ((max[1], (sy, nsy)), max[0])
        else:
            return self._flip(max[1][0], max[1][1], xs, ys, prob, max[0]) 
Example 42
Project: DRCOG_Urbansim   Author: apdjustino   File: pstat.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def zprob(z):
    """
    Returns the area under the normal curve 'to the left of' the given z value.
    Thus, 
    for z<0, zprob(z) = 1-tail probability
    for z>0, 1.0-zprob(z) = 1-tail probability
    for any z, 2.0*(1.0-zprob(abs(z))) = 2-tail probability
    Adapted from z.c in Gary Perlman's |Stat.

Usage:   zprob(z)
"""
    Z_MAX = 6.0    # maximum meaningful z-value
    if z == 0.0:
        x = 0.0
    else:
        y = 0.5 * math.fabs(z)
        if y >= (Z_MAX*0.5):
            x = 1.0
        elif (y < 1.0):
            w = y*y
            x = ((((((((0.000124818987 * w
                        -0.001075204047) * w +0.005198775019) * w
                      -0.019198292004) * w +0.059054035642) * w
                    -0.151968751364) * w +0.319152932694) * w
                  -0.531923007300) * w +0.797884560593) * y * 2.0
        else:
            y = y - 2.0
            x = (((((((((((((-0.000045255659 * y
                             +0.000152529290) * y -0.000019538132) * y
                           -0.000676904986) * y +0.001390604284) * y
                         -0.000794620820) * y -0.002034254874) * y
                       +0.006549791214) * y -0.010557625006) * y
                     +0.011630447319) * y -0.009279453341) * y
                   +0.005353579108) * y -0.002141268741) * y
                 +0.000535310849) * y +0.999936657524
    if z > 0.0:
        prob = ((x+1.0)*0.5)
    else:
        prob = ((1.0-x)*0.5)
    return prob 
Example 43
Project: OpenBottle   Author: xiaozhuchacha   File: vader.py    MIT License 5 votes vote down vote up
def _sift_sentiment_scores(self, sentiments):
        # want separate positive versus negative sentiment scores
        pos_sum = 0.0
        neg_sum = 0.0
        neu_count = 0
        for sentiment_score in sentiments:
            if sentiment_score > 0:
                pos_sum += (float(sentiment_score) +1) # compensates for neutral words that are counted as 1
            if sentiment_score < 0:
                neg_sum += (float(sentiment_score) -1) # when used with math.fabs(), compensates for neutrals
            if sentiment_score == 0:
                neu_count += 1
        return pos_sum, neg_sum, neu_count 
Example 44
Project: OpenBottle   Author: xiaozhuchacha   File: vader.py    MIT License 5 votes vote down vote up
def score_valence(self, sentiments, text):
        if sentiments:
            sum_s = float(sum(sentiments))
            # compute and add emphasis from punctuation in text
            punct_emph_amplifier = self._punctuation_emphasis(sum_s, text)
            if sum_s > 0:
                sum_s += punct_emph_amplifier
            elif  sum_s < 0:
                sum_s -= punct_emph_amplifier

            compound = normalize(sum_s)
            # discriminate between positive, negative and neutral sentiment scores
            pos_sum, neg_sum, neu_count = self._sift_sentiment_scores(sentiments)

            if pos_sum > math.fabs(neg_sum):
                pos_sum += (punct_emph_amplifier)
            elif pos_sum < math.fabs(neg_sum):
                neg_sum -= (punct_emph_amplifier)

            total = pos_sum + math.fabs(neg_sum) + neu_count
            pos = math.fabs(pos_sum / total)
            neg = math.fabs(neg_sum / total)
            neu = math.fabs(neu_count / total)

        else:
            compound = 0.0
            pos = 0.0
            neg = 0.0
            neu = 0.0

        sentiment_dict = \
            {"neg" : round(neg, 3),
             "neu" : round(neu, 3),
             "pos" : round(pos, 3),
             "compound" : round(compound, 4)}

        return sentiment_dict 
Example 45
Project: OpenBottle   Author: xiaozhuchacha   File: vader.py    MIT License 5 votes vote down vote up
def _sift_sentiment_scores(self, sentiments):
        # want separate positive versus negative sentiment scores
        pos_sum = 0.0
        neg_sum = 0.0
        neu_count = 0
        for sentiment_score in sentiments:
            if sentiment_score > 0:
                pos_sum += (float(sentiment_score) +1) # compensates for neutral words that are counted as 1
            if sentiment_score < 0:
                neg_sum += (float(sentiment_score) -1) # when used with math.fabs(), compensates for neutrals
            if sentiment_score == 0:
                neu_count += 1
        return pos_sum, neg_sum, neu_count 
Example 46
Project: OpenBottle   Author: xiaozhuchacha   File: vader.py    MIT License 5 votes vote down vote up
def score_valence(self, sentiments, text):
        if sentiments:
            sum_s = float(sum(sentiments))
            # compute and add emphasis from punctuation in text
            punct_emph_amplifier = self._punctuation_emphasis(sum_s, text)
            if sum_s > 0:
                sum_s += punct_emph_amplifier
            elif  sum_s < 0:
                sum_s -= punct_emph_amplifier

            compound = normalize(sum_s)
            # discriminate between positive, negative and neutral sentiment scores
            pos_sum, neg_sum, neu_count = self._sift_sentiment_scores(sentiments)

            if pos_sum > math.fabs(neg_sum):
                pos_sum += (punct_emph_amplifier)
            elif pos_sum < math.fabs(neg_sum):
                neg_sum -= (punct_emph_amplifier)

            total = pos_sum + math.fabs(neg_sum) + neu_count
            pos = math.fabs(pos_sum / total)
            neg = math.fabs(neg_sum / total)
            neu = math.fabs(neu_count / total)

        else:
            compound = 0.0
            pos = 0.0
            neg = 0.0
            neu = 0.0

        sentiment_dict = \
            {"neg" : round(neg, 3),
             "neu" : round(neu, 3),
             "pos" : round(pos, 3),
             "compound" : round(compound, 4)}

        return sentiment_dict 
Example 47
Project: PyMICAPS   Author: flashlxy   File: Micaps11Data.py    GNU General Public License v2.0 5 votes vote down vote up
def TransposeYaxis(self):
        self.beginlat, self.endlat = self.endlat, self.beginlat
        self.deltalat = math.fabs(self.deltalat)
        self.y = np.arange(self.beginlat, self.endlat + self.deltalat, self.deltalat)
        self.X, self.Y = np.meshgrid(self.x, self.y)
        self.U = self.U[::-1, ::]
        self.V = self.V[::-1, ::]
        self.Z = self.Z[::-1, ::] 
Example 48
Project: PyMICAPS   Author: flashlxy   File: Main.py    GNU General Public License v2.0 5 votes vote down vote up
def equal(value1, value2):
    return math.fabs(value1 - value2) < 10e-5 
Example 49
Project: Traffic-Light   Author: team-know-name   File: geomhelper.py    MIT License 5 votes vote down vote up
def isWithin(pos, shape):
    angle = 0.
    for i in range(0, len(shape) - 1):
        p1 = ((shape[i][0] - pos[0]), (shape[i][1] - pos[1]))
        p2 = ((shape[i + 1][0] - pos[0]), (shape[i + 1][1] - pos[1]))
        angle = angle + angle2D(p1, p2)
    i = len(shape) - 1
    p1 = ((shape[i][0] - pos[0]), (shape[i][1] - pos[1]))
    p2 = ((shape[0][0] - pos[0]), (shape[0][1] - pos[1]))
    angle = angle + angle2D(p1, p2)
    return math.fabs(angle) >= math.pi 
Example 50
Project: LaserTOF   Author: kyleuckert   File: _base.py    MIT License 5 votes vote down vote up
def get_data_ratio(self):
        """
        Returns the aspect ratio of the raw data.

        This method is intended to be overridden by new projection
        types.
        """
        xmin, xmax = self.get_xbound()
        ymin, ymax = self.get_ybound()

        xsize = max(math.fabs(xmax - xmin), 1e-30)
        ysize = max(math.fabs(ymax - ymin), 1e-30)

        return ysize / xsize 
Example 51
Project: LaserTOF   Author: kyleuckert   File: _base.py    MIT License 5 votes vote down vote up
def get_data_ratio_log(self):
        """
        Returns the aspect ratio of the raw data in log scale.
        Will be used when both axis scales are in log.
        """
        xmin, xmax = self.get_xbound()
        ymin, ymax = self.get_ybound()

        xsize = max(math.fabs(math.log10(xmax) - math.log10(xmin)), 1e-30)
        ysize = max(math.fabs(math.log10(ymax) - math.log10(ymin)), 1e-30)

        return ysize / xsize 
Example 52
Project: RouteOptimization   Author: andre-le   File: geomath.py    MIT License 5 votes vote down vote up
def copysign(x, y):
    """return x with the sign of y (missing from python 2.5.2)"""

    if sys.version_info > (2, 6):
      return math.copysign(x, y)

    return math.fabs(x) * (-1 if y < 0 or (y == 0 and 1/y < 0) else 1) 
Example 53
Project: NiujiaoDebugger   Author: MrSrc   File: test_math.py    GNU General Public License v3.0 5 votes vote down vote up
def testFabs(self):
        self.assertRaises(TypeError, math.fabs)
        self.ftest('fabs(-1)', math.fabs(-1), 1)
        self.ftest('fabs(0)', math.fabs(0), 0)
        self.ftest('fabs(1)', math.fabs(1), 1) 
Example 54
Project: Health-Checker   Author: KriAga   File: vader.py    MIT License 5 votes vote down vote up
def _sift_sentiment_scores(self, sentiments):
        # want separate positive versus negative sentiment scores
        pos_sum = 0.0
        neg_sum = 0.0
        neu_count = 0
        for sentiment_score in sentiments:
            if sentiment_score > 0:
                pos_sum += (float(sentiment_score) +1) # compensates for neutral words that are counted as 1
            if sentiment_score < 0:
                neg_sum += (float(sentiment_score) -1) # when used with math.fabs(), compensates for neutrals
            if sentiment_score == 0:
                neu_count += 1
        return pos_sum, neg_sum, neu_count 
Example 55
Project: Health-Checker   Author: KriAga   File: vader.py    MIT License 5 votes vote down vote up
def score_valence(self, sentiments, text):
        if sentiments:
            sum_s = float(sum(sentiments))
            # compute and add emphasis from punctuation in text
            punct_emph_amplifier = self._punctuation_emphasis(sum_s, text)
            if sum_s > 0:
                sum_s += punct_emph_amplifier
            elif  sum_s < 0:
                sum_s -= punct_emph_amplifier

            compound = normalize(sum_s)
            # discriminate between positive, negative and neutral sentiment scores
            pos_sum, neg_sum, neu_count = self._sift_sentiment_scores(sentiments)

            if pos_sum > math.fabs(neg_sum):
                pos_sum += (punct_emph_amplifier)
            elif pos_sum < math.fabs(neg_sum):
                neg_sum -= (punct_emph_amplifier)

            total = pos_sum + math.fabs(neg_sum) + neu_count
            pos = math.fabs(pos_sum / total)
            neg = math.fabs(neg_sum / total)
            neu = math.fabs(neu_count / total)

        else:
            compound = 0.0
            pos = 0.0
            neg = 0.0
            neu = 0.0

        sentiment_dict = \
            {"neg" : round(neg, 3),
             "neu" : round(neu, 3),
             "pos" : round(pos, 3),
             "compound" : round(compound, 4)}

        return sentiment_dict 
Example 56
Project: py-adxl345   Author: alexismeneses   File: base.py    MIT License 5 votes vote down vote up
def calibrate(self):
    """ Auto calibrate the device offset. Put the device so as one axe is parallel to the gravity field (usually, put the device on a flat surface) """
    self.set_offset(0, 0, 0)
    samples = self.get_axes()

    x = samples['x']
    y = samples['y']
    z = samples['z']
    
    abs_x = math.fabs(x)
    abs_y = math.fabs(y)
    abs_z = math.fabs(z)

    # Find which axe is in the field of gravity and set its expected value to 1g absolute value
    if self._equal(abs_x, 1) and self._equal(abs_y, 0) and self._equal(abs_z, 0):
      cal_x = 1 if x > 0 else -1
      cal_y = 0
      cal_z = 0
    elif self._equal(abs_x, 0) and self._equal(abs_y, 1) and self._equal(abs_z, 0):
      cal_x = 0
      cal_y = 1 if y > 0 else -1
      cal_z = 0
    elif self._equal(abs_x, 0) and self._equal(abs_y, 0) and self._equal(abs_z, 1):
      cal_x = 0
      cal_y = 0
      cal_z = 1 if z > 0 else -1
    else:
      raise ValueError("Could not determine ADXL position. One axe should be set in field of gravity")

    offset_x = cal_x - x
    offset_y = cal_y - y
    offset_z = cal_z - z
    
    self.set_offset(offset_x, offest_y, offset_z)
    
    return {'x': offset_x,
            'y': offset_y,
            'z': offset_z} 
Example 57
Project: BotDigger   Author: hanzhang0116   File: BotDigger.py    GNU General Public License v3.0 5 votes vote down vote up
def increaseCUSUM(host, localMax, threshold, fpOutput):
	first = -1
	indexIncrease = 0
	indexDecrease = 0
	count = 0
	sumLast = 0
	sumCurrent = 0
	counterList = list()
	sorted2LDList = sorted(host.suspiciousNXDOMAIN2LDDict.items(), key=operator.itemgetter(1))
	if len(sorted2LDList) < 1:
		return (-1, -1, -1)
	timestampFirst = sorted2LDList[0][1]
	for item in sorted2LDList:
		# record the number of suspicious 2LD every 60 seconds
		if item[1] < timestampFirst + 60:
			count += 1
		else:
			counterList.append(count)
			count = 1
			timestampFirst = item[1]
	counterList.append(count)
	for i in range(0, len(counterList)):
		sumLast = 0
		sumCurrent = 0
		# check whether the number of suspicious 2LD increases in 5 minutes
		for j in range(0, 5):
			if i+j >= len(counterList):
				break
			sumCurrent = sumLast + math.fabs(counterList[i+j] - localMax)
			if (counterList[i+j] > localMax) and (first == -1):
				first = i+j
			if sumCurrent > threshold:
				if enableVerbose:
					fpOutput.write("increase change detected: offset %d-%d\n" % (first, i+j))
				return (first, i+j, sorted2LDList[0][1]+60*first)
			sumLast = sumCurrent
	return (-1, -1, -1) 
Example 58
Project: BotDigger   Author: hanzhang0116   File: BotDigger.py    GNU General Public License v3.0 5 votes vote down vote up
def decreaseCUSUM(host, localMax, threshold, increaseEnd, fpOutput):
	indexIncrease = 0
	indexDecrease = 0
	decreaseStart = 0
	decreaseEnd = 0
	count = 0
	sumCurrent = 0
	timestampLastDomain = 0
	counterList = list()
	sorted2LDList = sorted(host.suspiciousNXDOMAIN2LDDict.items(), key=operator.itemgetter(1))
	if len(sorted2LDList) < 1:
		return (-1, -1, -1)
	timestampFirst = sorted2LDList[0][1]
	for item in sorted2LDList:
		timestampLastDomain = item[1]
		if item[1] < timestampFirst + 60:
			count += 1
		else:
			counterList.append(count)
			count = 1
			timestampFirst = item[1]
	counterList.append(count)
	if timestampPeriodBegin + timeInterval > timestampLastDomain:
		counterList.append(0)
	for i in range(increaseEnd+1, len(counterList)):
		sumCurrent = 0
		for j in range(0, temporalWindow):
			if i+j >= len(counterList):
				break
			sumCurrent = sumCurrent + math.fabs(counterList[i+j] - counterList[i+j-1])
			if sumCurrent > threshold:
				if enableVerbose == 1:
					fpOutput.write("decrease change detected: offset %d-%d\n" % (i, i+j))
				return (i, i+j, sorted2LDList[0][1]+60*(i+j))
	return (-1, -1, -1) 
Example 59
Project: whatsapp-chat-analysis   Author: ravikiranj   File: datelib.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def date_diff(dateobj1, dateobj2):
    import math
    delta = dateobj2 - dateobj1
    return int(math.fabs(delta.days)) 
Example 60
Project: midca   Author: COLAB2   File: clear_block_monitor.py    MIT License 5 votes vote down vote up
def m_callback(data):
    print("got data!")
    strMsg = str(data.data).strip()
    color_locations = strMsg.split(";")
    color_location_dic = {}
    for msg in color_locations:
            
        color_location = msg.split(":");
            
        pointstr = color_location[1].split(",")
        p = Point(x = int(pointstr[0]), y = int(pointstr[1]), z = int(pointstr[2]))
        color_location_dic.update({color_location[0]: p})
            
    
    
    if len(color_location) >= 2:
            pos_green = 'table'
            pos_red = 'table'
            clear_green = 'clear'
            clear_red = 'clear'
            for obj in color_location.keys():
                if obj != block_name:
                    if math.fabs(color_location[block_name].x - color_location[obj].x) < 12:
                        if color_location[block_name].y> color_location[obj].y:
                             #print block_name + " is not clear"
                             return obj 
Example 61
Project: 2018-1-OSS-E7   Author: 18-1-SKKU-OSS   File: jigsaw.py    MIT License 5 votes vote down vote up
def __eq__(self, other):
		if 0. in (self.r, other.r):
			return False
		if math.fabs(self.y - other.y) <= self._eq_threshold:
			return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2 + (self.r - other.r)**2) < self._eq_threshold
		else:
			return False 
Example 62
Project: Gesture-Research   Author: s9k96   File: LedByGesture_Rpi.py    MIT License 5 votes vote down vote up
def angle(x,y):
	if x == 0: return None
	return math.fabs(math.degrees(math.atan(y/float(x)))) 
Example 63
Project: wechat_jump_ai   Author: michaelfeng   File: agent.py    MIT License 5 votes vote down vote up
def build_state(self):
        # the distance between start point and target point
        self.pull_screenshot()
        im = Image.open("./1.png")
        piece_x, piece_y, board_x, board_y = map(int, self.find_piece_and_board(im))
        self.x = board_x
        self.y = board_y
        print('location: ', piece_x, piece_y, board_x, board_y)
        state = math.sqrt(math.fabs(piece_x - board_x) ** 2 + math.fabs(piece_y - board_y) ** 2)
        state = int(state)
        return state 
Example 64
Project: Frank-the-Science-Bot   Author: ViktorWase   File: ann.py    Apache License 2.0 5 votes vote down vote up
def sigmoidFunc(x):
        return x/(1.0+fabs(x)) 
Example 65
Project: iMapper   Author: amonszpart   File: one_euro_filter.py    Apache License 2.0 5 votes vote down vote up
def __call__(self, x, timestamp=None):
        # ---- update the sampling frequency based on timestamps
        if self.__lasttime and timestamp:
            self.__freq = 1.0 / (timestamp - self.__lasttime)
        self.__lasttime = timestamp
        # ---- estimate the current variation per second
        prev_x = self.__x.last_value()
        dx = 0.0 if prev_x is None else (x-prev_x) * self.__freq  # FIXME: 0.0 or value?
        edx = self.__dx(dx, timestamp, alpha=self.__alpha(self.__dcutoff))
        # ---- use it to update the cutoff frequency
        cutoff = self.__mincutoff + self.__beta*math.fabs(edx)
        # ---- filter the given value
        return self.__x(x, timestamp, alpha=self.__alpha(cutoff))

# ---------------------------------------------------------------------------- 
Example 66
Project: MODS_ConvNet   Author: santiagolopezg   File: dataset_labs_MODS.py    MIT License 4 votes vote down vote up
def Dset(self, v, ndataset=5, name='MODS_data.pkl'):
         '''
         function to build datasets. ndataset: number of datasets wanted; 
         name: pkl file where the data from DSetGlobal is stored. Code makes sure
         that there is the same ratio of positive/negative images in each dataset.
         This is done, setting a lmda. If you set a really low lmda, you might have
         to stop the program and rerun it a few times.
         Returns a pkl with a segmented dataset. seg_data is a list of n lists, where n
         is the number of datasets desired. These n lists consist of 2 lists: the data
         and its corresponding labels.
         '''
	 ratios = {'train_1': 0.62234,
		'train_2': 0.8499,
		'train_3': 0.53817,
		'test_1': 0.8881987,
		'test_2': 0.51543,
		'test_3': 0.84473
		   }
         f = file(name, 'rb')
         datapapa = cPickle.load(f)
         f.close()    
         w = datapapa[0]
         x = datapapa[1]
         y = range(len(x))
         seg_data = []
         counter = 0
         size = int(len(y)/float(ndataset))
	 print size, 'gamboozle'
         while counter < ndataset:
             z = random.sample(y, size)
             lmda = 0.02
             ratio = float(sum([x[i] for i in z]))/(len([x[i] for i in z if x[i]==0]))
             print(ratio), v
	     #exit()
             dif = math.fabs(ratio-ratios[v]) #ratio of positive to negatives
             if dif < lmda:
                 print('BINGO!', counter, dif)
                 y = [i for i in y if i not in z]
                 current_label = [x[i] for i in z]
                 current_data = [w[i] for i in z]
                 seg_data.append([current_data, current_label])
                 counter+=1
             else:
                 #print('Does not have a acceptable ratio', ratio, dif)
                 #fun+= 1
                 pass 
         f = file('seg_MODS_data_{0}.pkl'.format(v), 'wb')
         cPickle.dump(seg_data, f, protocol=cPickle.HIGHEST_PROTOCOL)
         f.close() 
Example 67
Project: MODS_ConvNet   Author: santiagolopezg   File: dataset_labs_MODS.py    MIT License 4 votes vote down vote up
def Dset(self, v, ndataset=5, name='MODS_data.pkl'):
         '''
         function to build datasets. ndataset: number of datasets wanted; 
         name: pkl file where the data from DSetGlobal is stored. Code makes sure
         that there is the same ratio of positive/negative images in each dataset.
         This is done, setting a lmda. If you set a really low lmda, you might have
         to stop the program and rerun it a few times.
         Returns a pkl with a segmented dataset. seg_data is a list of n lists, where n
         is the number of datasets desired. These n lists consist of 2 lists: the data
         and its corresponding labels.
         '''
	 ratios = {'train_1': 0.62234,
		'train_2': 0.8499,
		'train_3': 0.53817,
		'test_1': 0.8881987,
		'test_2': 0.51543,
		'test_3': 0.84473
		   }
         f = file(name, 'rb')
         datapapa = cPickle.load(f)
         f.close()    
         w = datapapa[0]
         x = datapapa[1]
         y = range(len(x))
         seg_data = []
         counter = 0
         size = int(len(y)/float(ndataset))
	 print size, 'gamboozle'
         while counter < ndataset:
             z = random.sample(y, size)
             lmda = 0.02
             ratio = float(sum([x[i] for i in z]))/(len([x[i] for i in z if x[i]==0]))
             print(ratio), v
	     #exit()
             dif = math.fabs(ratio-ratios[v]) #ratio of positive to negatives
             if dif < lmda:
                 print('BINGO!', counter, dif)
                 y = [i for i in y if i not in z]
                 current_label = [x[i] for i in z]
                 current_data = [w[i] for i in z]
                 seg_data.append([current_data, current_label])
                 counter+=1
             else:
                 #print('Does not have a acceptable ratio', ratio, dif)
                 #fun+= 1
                 pass 
         f = file('seg_MODS_data_{0}.pkl'.format(v), 'wb')
         cPickle.dump(seg_data, f, protocol=cPickle.HIGHEST_PROTOCOL)
         f.close() 
Example 68
Project: spqrel_tools   Author: LCAS   File: turntosoundsource.py    MIT License 4 votes vote down vote up
def onSoundLocalized(self, motion, value):
        """
        :param motion: motion service
        :param value: output of sounddetected
                        [ [time(sec), time(usec)],
                        [azimuth(rad), elevation(rad), confidence, energy],
                        [Head Position[6D]] in FRAME_TORSO
                        [Head Position[6D]] in FRAME_ROBOT
                        ]
        :return:
        """

        confidence = value[1][2]
        # print confidence

        if confidence > 0.5:
            sound_azimuth = value[1][0]
            sound_elevation = value[1][1]
            x = math.sin(sound_elevation) * math.cos(sound_azimuth)
            y = math.sin(sound_elevation) * math.sin(sound_azimuth)
            z = math.cos(sound_elevation)
            head_pitch = value[2][4]
            head_yaw = value[2][5]
            azimuth = sound_azimuth + head_yaw
            elevation = sound_elevation + head_pitch
            turn = 0
            if azimuth > self.HEAD_YAW_MAX:
                turn = azimuth
                azimuth = 0.
            if azimuth < self.HEAD_YAW_MIN:
                turn = azimuth
                azimuth = 0.
            if elevation > self.HEAD_PITCH_MAX:
                elevation = self.HEAD_PITCH_MAX
            if elevation < self.HEAD_PITCH_MIN:
                elevation = self.HEAD_PITCH_MIN
            target_angles = [azimuth, 0]  # [azimuth, elevation]
            print "Current Head Yaw: ", head_yaw, "Current Head Pitch", head_pitch
            print "Sound Detected Azimuth: ", sound_azimuth, "Sound Detected Elevation: ", sound_elevation
            print "Sound Detected Coordinate: ", [x, y, z]
            print "Target Head Yaw: ", azimuth, "Target Head Pitch: ", elevation
            print "Turn: ", turn
            print "------------------------------------------------------------------"
            motion.angleInterpolationWithSpeed(self.NAMES, target_angles, self.MAX_SPEED_FRACTION)
            if math.fabs(turn) > 0.01:
                motion.moveTo(0, 0, turn)
            # print a 
Example 69
Project: iceaddr   Author: sveinbjornt   File: add_placename_data.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def isnet93_to_wgs84(xx, yy):
    x = xx
    y = yy
    a = 6378137.0
    f = 1 / 298.257222101
    lat1 = 64.25
    lat2 = 65.75
    latc = 65.00
    lonc = 19.00
    eps = 0.00000000001

    def fx(p):
        return a * math.cos(p / rho) / math.sqrt(1 - math.pow(e * math.sin(p / rho), 2))

    def f1(p):
        return math.log((1 - p) / (1 + p))

    def f2(p):
        return f1(p) - e * f1(e * p)

    def f3(p):
        return pol1 * math.exp((f2(math.sin(p / rho)) - f2sin1) * sint / 2)

    rho = 45 / math.atan2(1.0, 1.0)
    e = math.sqrt(f * (2 - f))
    dum = f2(math.sin(lat1 / rho)) - f2(math.sin(lat2 / rho))
    sint = 2 * (math.log(fx(lat1)) - math.log(fx(lat2))) / dum
    f2sin1 = f2(math.sin(lat1 / rho))
    pol1 = fx(lat1) / sint
    polc = f3(latc) + 500000.0
    peq = (
        a
        * math.cos(latc / rho)
        / (sint * math.exp(sint * math.log((45 - latc / 2) / rho)))
    )
    pol = math.sqrt(math.pow(x - 500000, 2) + math.pow(polc - y, 2))
    lat = 90 - 2 * rho * math.atan(math.exp(math.log(pol / peq) / sint))
    lon = 0
    fact = rho * math.cos(lat / rho) / sint / pol
    fact = rho * math.cos(lat / rho) / sint / pol
    delta = 1.0
    while math.fabs(delta) > eps:
        delta = (f3(lat) - pol) * fact
        lat += delta
    lon = -(lonc + rho * math.atan((500000 - x) / (polc - y)) / sint)

    return {"lat": round(lat, 7), "lng": round(lon, 7)} 
Example 70
Project: Cheapest-Flights-bot   Author: PhoenixDD   File: Flight Analysis.py    MIT License 4 votes vote down vote up
def task_4_dbscan(flight_data):
    flight_data['day'] = flight_data['Date_of_Flight'].dt.day
    X = StandardScaler().fit_transform(flight_data[['day', 'Price']])
    db = DBSCAN(eps=.404, min_samples=3).fit(X)
    labels = db.labels_
    clusters = len(set(labels))
    unique_labels = set(labels)
    colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))
    plt.subplots(figsize=(12, 8))
    for k, c in zip(unique_labels, colors):
        class_member_mask = (labels == k)
        xy = X[class_member_mask]
        plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=c,
                 markeredgecolor='k', markersize=14)

    plt.title("Total Clusters: {}".format(clusters), fontsize=14, y=1.01)
    flight_data['dbscan_labels'] = db.labels_
    unique_labels=[]
    for index,rows in flight_data.groupby('dbscan_labels').count().iterrows():
        if rows['Price']>=5:
            unique_labels.append(index)
    list_of_5_same_label=[]
    for label in unique_labels:
        count=0
        for index,rows in flight_data.iterrows():
            if rows['dbscan_labels']!=label:
                count = 0
                continue
            count+=1
            if count==5:
                list_of_5_same_label.append(rows['Date_of_Flight'])
                count=0
    for i in list_of_5_same_label:
        flag=1
        for index,rows in flight_data.loc[flight_data['Date_of_Flight'].isin([i,i-timedelta(days=1),i-timedelta(days=2),i-timedelta(days=3),i-timedelta(days=4)])].iterrows():
            for ind, row in flight_data.loc[flight_data['Date_of_Flight'].isin([i, i - timedelta(days=1), i - timedelta(days=2), i - timedelta(days=3), i - timedelta(days=4)])].iterrows():
                if math.fabs(rows['Price']-row['Price'])>20:
                    flag=0
                    list_of_5_same_label.remove(i)
                    break
            if flag==0:
                break
    min=float('inf')
    for i in list_of_5_same_label:
        temp=flight_data.loc[flight_data['Date_of_Flight'].isin([i, i - timedelta(days=1), i - timedelta(days=2), i - timedelta(days=3), i - timedelta(days=4)])]
        if temp[['Price']].mean()[0].item()<min:
            min=temp[['Price']].mean().item()
            date=i
    clean_data=[]
    for index,rows in flight_data.loc[flight_data['Date_of_Flight'].isin([date, date - timedelta(days=1), date - timedelta(days=2), date - timedelta(days=3), date - timedelta(days=4)])].iterrows():
        clean_data.append([rows['Price'], rows['Date_of_Flight']])
    return pd.DataFrame(clean_data,columns=['Price','Date_of_Flight']) 
Example 71
Project: openrocketdoc   Author: open-aerospace   File: writers.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, rocket, page='A4'):

        if page == 'A4':
            self.paper = self.A4
        else:
            self.paper = self.A4

        # DPI:
        self.MM2PX = self.paper['px'][0] / float(self.paper['mm'][0])

        # determine scale
        scalefactor = 0.240 / (rocket.length + 0.001)  # avoid divide by 0
        self.scalefactor = min(self.SCALES, key=lambda x: fabs(x-scalefactor))

        # SVG header
        self.svg = ET.Element('svg')
        self.svg.attrib['xmlns:dc'] = "http://purl.org/dc/elements/1.1/"
        self.svg.attrib['xmlns:rdf'] = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        self.svg.attrib['xmlns:svg'] = "http://www.w3.org/2000/svg"
        self.svg.attrib['xmlns'] = "http://www.w3.org/2000/svg"
        self.svg.attrib['version'] = "1.1"
        self.svg.attrib['id'] = "svg2"

        # Paper size
        self.svg.attrib['viewBox'] = "0 0 %d %d" % (self.paper['px'][0], self.paper['px'][1])
        self.svg.attrib['width'] = "%dmm" % self.paper['mm'][0]
        self.svg.attrib['height'] = "%dmm" % self.paper['mm'][1]

        # Marker definitions
        defs = ET.SubElement(self.svg, 'defs')
        defs.attrib['id'] = "definitions"

        arrow_end = ET.SubElement(defs, 'marker')
        arrow_end.attrib['style'] = "overflow:visible;"
        arrow_end.attrib['id'] = "Arrow1Mend"
        arrow_end.attrib['refX'] = "0.0"
        arrow_end.attrib['refY'] = "0.0"
        arrow_end.attrib['orient'] = "auto"

        arrow_end_path = ET.SubElement(arrow_end, 'path')
        arrow_end_path.attrib['transform'] = "scale(0.4) rotate(180) translate(30,0)"
        arrow_end_path.attrib['style'] = "fill-rule:evenodd;stroke:#4c71d7;stroke-width:1pt;stroke-opacity:1;fill:#4c71d7;fill-opacity:1"
        arrow_end_path.attrib['d'] = "M 0.0,0.0 L 15.0,-15.0 L -30,0.0 L 15.0,15.0 L 0.0,0.0 z "

        arrow_begin = ET.SubElement(defs, 'marker')
        arrow_begin.attrib['style'] = "overflow:visible;"
        arrow_begin.attrib['id'] = "Arrow1Mbegin"
        arrow_begin.attrib['refX'] = "0.0"
        arrow_begin.attrib['refY'] = "0.0"
        arrow_begin.attrib['orient'] = "auto"

        arrow_begin_path = ET.SubElement(arrow_begin, 'path')
        arrow_begin_path.attrib['transform'] = "scale(0.4) translate(30,0)"
        arrow_begin_path.attrib['style'] = "fill-rule:evenodd;stroke:#4c71d7;stroke-width:1pt;stroke-opacity:1;fill:#4c71d7;fill-opacity:1"
        arrow_begin_path.attrib['d'] = "M 0.0,0.0 L 15.0,-15.0 L -30,0.0 L 15.0,15.0 L 0.0,0.0 z " 
Example 72
Project: graph-keyword-search   Author: usc-isi-i2   File: wordSimilarity.py    Apache License 2.0 4 votes vote down vote up
def isPredicateSimilar(word1,word2):
		#score = math.fabs(WordSimilarity.getEasyESAScore(word1,word2))
		        
	    esaThread = Thread(target=WordSimilarity.getEasyESAScore, args=(word1,word2,))
	    swoogleThread = Thread(target=WordSimilarity.getSwoogleScore, args=(word1,word2,))

	    esaThread.start()
	    swoogleThread.start()
	    esaThread.join()
	    swoogleThread.join()

	    ESAscore = WordSimilarity.scoreDictionary['esa'] 
	    #WordSimilarity.getEasyESAScore(word1,word2)
	    ESAScaledScore = 0
	    if(ESAscore>0 and ESAscore<=0.04):
	    	ESAScaledScore = 1
	    elif(ESAscore>0.04 and ESAscore<=0.06):
	    	ESAScaledScore = 2
	    elif(ESAscore>0.07):
	    	ESAScaledScore = 3
	    else:
	    	ESAScaledScore = 0

	    SwoogleScore = WordSimilarity.scoreDictionary['swoogle'] 
	    # WordSimilarity.getSwoogleScore(word1,word2)
	    SwoogleScaledScore = 0
	    if(SwoogleScore>0 and SwoogleScore<0.6):
	    	SwoogleScaledScore = 1
	    elif(SwoogleScore>=0.6 and SwoogleScore<0.7):
	    	SwoogleScaledScore = 2
	    elif(SwoogleScore>=0.7):
	    	SwoogleScaledScore = 3
	    else:
	    	SwoogleScaledScore = 0

	    if(ESAScaledScore>SwoogleScaledScore):
	    	score = ESAScaledScore
	    else:
	    	score = SwoogleScaledScore

	    if(score>=2):
	    	return score
	    else:
	    	return -1 
Example 73
Project: graph-keyword-search   Author: usc-isi-i2   File: wordSimilarity.py    Apache License 2.0 4 votes vote down vote up
def isPredicateSimilar(word1,word2):
		#score = math.fabs(WordSimilarity.getEasyESAScore(word1,word2))
		        
	    esaThread = Thread(target=WordSimilarity.getEasyESAScore, args=(word1,word2,))
	    swoogleThread = Thread(target=WordSimilarity.getSwoogleScore, args=(word1,word2,))

	    esaThread.start()
	    swoogleThread.start()
	    esaThread.join()
	    swoogleThread.join()

	    ESAscore = WordSimilarity.scoreDictionary['esa'] 
	    #WordSimilarity.getEasyESAScore(word1,word2)
	    ESAScaledScore = 0
	    if(ESAscore>0 and ESAscore<=0.04):
	    	ESAScaledScore = 1
	    elif(ESAscore>0.04 and ESAscore<=0.06):
	    	ESAScaledScore = 2
	    elif(ESAscore>0.07):
	    	ESAScaledScore = 3
	    else:
	    	ESAScaledScore = 0

	    SwoogleScore = WordSimilarity.scoreDictionary['swoogle'] 
	    # WordSimilarity.getSwoogleScore(word1,word2)
	    SwoogleScaledScore = 0
	    if(SwoogleScore>0 and SwoogleScore<0.6):
	    	SwoogleScaledScore = 1
	    elif(SwoogleScore>=0.6 and SwoogleScore<0.7):
	    	SwoogleScaledScore = 2
	    elif(SwoogleScore>=0.7):
	    	SwoogleScaledScore = 3
	    else:
	    	SwoogleScaledScore = 0

	    if(ESAScaledScore>SwoogleScaledScore):
	    	print("Using ESA")
	    	score = ESAScaledScore
	    else:
	    	print("Using Swoogle")
	    	score = SwoogleScaledScore

	    if(score>=2):
	    	return score
	    else:
	    	return -1 
Example 74
Project: geoscience   Author: rolandhill   File: SectionManager.py    GNU General Public License v3.0 4 votes vote down vote up
def sectionThroughElevation(self, layers):
        #Create new layers for the section based on the requested plan layers
        elevationLayers = []
        
        for layer in layers:
            #Try and match the layer to be created with one already under the section.group, else create a new layer
            newName = self.createSectionLayerName(layer, self.name)
            elevLayer = self.matchLayer(newName)
            usingNewLayer = False
            if elevLayer == None:
                elevLayer = self.createSectionElevationLayer(layer, newName)
                usingNewLayer = True
            else:
                clearLayer(elevLayer)

            # List of points to represent the portion of the line within the section
            pointList = []

            dp = layer.dataProvider()
            steps =  math.ceil(self.sectionLength / min(math.fabs(layer.rasterUnitsPerPixelX()), math.fabs(layer.rasterUnitsPerPixelY())))
            dx = (self.endX - self.startX) / float(steps)
            dy = (self.endY - self.startY) / float(steps)
            step = math.sqrt(dx * dx + dy * dy)
            x = self.startX
            y = self.startY
            dist = 0.0
            for i in range(steps + 1):
                ht, ok = dp.sample(QgsPointXY(x, y), 1)
                if ok:
                    pointList.append(QgsPoint(dist, ht, 0.0))
                x = x + dx
                y = y + dy
                dist = dist + step
                
            if len(pointList) > 1:
                # Variable to hold a feature
                feature = QgsFeature()
                feature.setGeometry(QgsGeometry.fromPolyline(pointList))
        
                # Add the new feature to the new Trace_ layer
                elevLayer.startEditing()
                elevLayer.addFeature(feature)
                elevLayer.commitChanges()

                elevationLayers.append(elevLayer)

                if usingNewLayer:
                    # Set the line style
                    r = elevLayer.renderer()
                    r.symbol().setColor(QtGui.QColor('black'))
                    r.symbol().setWidth(0.5)

                    QgsProject.instance().addMapLayer(elevLayer, False)
                    self.group.addLayer(elevLayer)
            
        return elevationLayers 
Example 75
Project: midca   Author: COLAB2   File: monitor.py    MIT License 4 votes vote down vote up
def monitor_clear_block(block_name='green block', topic='clear_block'):
    print 'monitoring...'
    
    #rospy.init_node('clear_block_monitor', anonymous=True)
    baxter.enable()
    boundaries = {'blue block':([100,150,0], [140,255,255]),
                 'green block': ([30,100,50], [80,255,255]),
                 'red block':([0,150,50], [10,255,255])
                }
   
    while(1):
        # Take each frame
        #_, frame = cap.read()
        color_location = {}
        image = baxter.getImageFromRightHandCamera()
        frame = baxter.getLastCvImage()
        #send_image_to_screen(frame)
    
        # Convert BGR to HSV
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        for color_name in boundaries:
            (lower, upper) = boundaries[color_name]
            mask = Getmask(hsv, lower, upper)
            
                
            p = findContour(frame, mask)
            if(p != None):
                color_location.update({color_name : (p[0], p[1], 0)})
        time.sleep(3)
        if len(color_location) == 2:
            pos_green = 'table'
            pos_red = 'table'
            clear_green = 'clear'
            clear_red = 'clear'
            for obj in color_location.keys():
                if obj != block_name:
                    if math.fabs(color_location[block_name][0] - color_location[obj][0]) < 10:
                        if color_location[block_name][1] > color_location[obj][1]:
                             print block_name + " is not clear"
                             publish(block_name + ' is not clear', topic)
                             return
                        else:
                            print block_name + "is clear" 
Example 76
Project: midca   Author: COLAB2   File: clear_block_monitor.py    MIT License 4 votes vote down vote up
def monitor_clear_block2(block_name='red block', topic='clear_block'):
    print 'monitoring clear...'
    
    #rospy.init_node('clear_block_monitor', anonymous=True)
    baxter.enable()
    boundaries = {'blue block':([90,120,60], [120,255,255]),
                 'green block': ([50,100,50], [80,255,255]),
                 'red block':([0,150,50], [10,255,255])
                }
   
    while(1):
        # Take each frame
        #_, frame = cap.read()
        color_location = {}
        image = baxter.getImageFromRightHandCamera()
        frame = baxter.getLastCvImage()
        #send_image_to_screen(frame)
    
        # Convert BGR to HSV
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        for color_name in boundaries:
            (lower, upper) = boundaries[color_name]
            mask = Getmask(hsv, lower, upper)
            
                
            p = findContour(frame, mask)
            if(p != None):
                color_location.update({color_name : (p[0], p[1], 0)})
        time.sleep(2)
        if len(color_location) == 3:
            pos_green = 'table'
            pos_red = 'table'
            pos_blue = 'table'
            clear_green = 'clear'
            clear_red = 'clear'
            clear_blue = 'clear'
            for obj in color_location.keys():
                if obj != block_name:
                    if math.fabs(color_location[block_name][0] - color_location[obj][0]) < 12:
                        if color_location[block_name][1] > color_location[obj][1]:
                             #print block_name + " is not clear"
                             return obj
#                         else:
#                             print block_name + "is clear" 
Example 77
Project: midca   Author: COLAB2   File: pos_block_monitor.py    MIT License 4 votes vote down vote up
def monitor_pos_block(block_name='green block', pos='table'):
    print 'monitoring pos'
    
    #rospy.init_node('clear_block_monitor', anonymous=True)
    baxter.enable()
    boundaries = {'blue block':([100,150,0], [140,255,255]),
                 'green block': ([30,100,50], [80,255,255]),
                 'red block':([0,150,50], [10,255,255])
                }
   
    while(1):
        # Take each frame
        #_, frame = cap.read()
        color_location = {}
        image = baxter.getImageFromRightHandCamera()
        frame = baxter.getLastCvImage()
        #send_image_to_screen(frame)
    
        # Convert BGR to HSV
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        for color_name in boundaries:
            (lower, upper) = boundaries[color_name]
            mask = Getmask(hsv, lower, upper)
            
                
            p = findContour(frame, mask)
            if(p != None):
                color_location.update({color_name : (p[0], p[1], 0)})
        time.sleep(2)
        pos_block = pos
        if len(color_location) >= 2:
            
            pos_green = 'table'
            pos_red = 'table'
            clear_green = 'clear'
            clear_red = 'clear'
            for obj in color_location.keys():
                if obj != block_name:
                    if math.fabs(color_location[block_name][0] - color_location[obj][0]) < 12:
                        if color_location[block_name][1] < color_location[obj][1]:
                            #print("1")
                            pos_block = obj
                        else:
                            #print("2")
                            pos_block = 'table'    
                    else:
                            #print("3")
                            pos_block = 'table'        
        else:
            pos_block = 'table'
        #print(pos_block)
        
        if pos_block != pos:
            print("state changed")
            return pos_block 
Example 78
Project: midca   Author: COLAB2   File: rosrun.py    MIT License 4 votes vote down vote up
def store_locations(self, data):
        if not self.mem:
            rospy.logerr("Trying to store data to a nonexistent MIDCA object.")
        
        strMsg = str(data.data).strip()
        color_locations = strMsg.split(";")
        color_location_dic = {}
        for msg in color_locations:
            
            color_location = msg.split(":");
            
            pointstr = color_location[1].split(",")
            p = Point(x = int(pointstr[0]), y = int(pointstr[1]), z = int(pointstr[2]))
            color_location_dic.update({color_location[0]: p})
            
                
            self.mem.add(self.memKey, world_repr.DetectionEvent(id = color_location[0], 
        loc = p))
        
        if color_location_dic and ('red block' in color_location_dic.keys()) and ('green block' in color_location_dic.keys()):
            pos_green = 'table'
            pos_red = 'table'
            clear_green = 'clear'
            clear_red = 'clear'
            if math.fabs(color_location_dic['red block'].x - color_location_dic['green block'].x) < 12:
                if color_location_dic['red block'].y > color_location_dic['green block'].y:
                    pos_green = "red block"
                    clear_red = 'not clear'
                else:
                    pos_red = "green block"
                    clear_green = 'not clear'     
                
                self.mem.add(self.mem.ROS_OBJS_STATE, world_repr.pos_block(id = "red block", position = pos_red, isclear = clear_red))
                self.mem.add(self.mem.ROS_OBJS_STATE, world_repr.pos_block(id = "green block", position = pos_green, isclear = clear_green)) 
        
        elif len(color_location) == 1:
            color_block = color_location_dic.keys()[0]
            pos = 'table'
            clear = 'clear'
            self.mem.add(self.mem.ROS_OBJS_STATE, world_repr.pos_block(id = color_block, position = pos, isclear = clear))
        
#         if 'red block' in color_location_dic.keys() and color_location_dic['red block']:
#             if 'green block' in color_location_dic.keys() and color_location_dic['green block']:
#                 pos_green = 'table'
#                 pos_red = 'table'
#                 clear_green = 'clear'
#                 clear_red = 'clear'
#                 if math.fabs(color_location_dic['red block'].x - color_location_dic['green block'].x) < 10:
#                     if color_location_dic['red block'].y > color_location_dic['green block'].y:
#                         pos_green = "red block"
#                         clear_red = 'not clear'
#                     else:
#                         pos_red = "green block"
#                         clear_green = 'not clear'     
#                 
#                 self.mem.add(self.mem.ROS_OBJS_STATE, world_repr.pos_block(id = "red block", position = pos_red, isclear = clear_red))
#                 self.mem.add(self.mem.ROS_OBJS_STATE, world_repr.pos_block(id = "green block", position = pos_green, isclear = clear_green)) 
Example 79
Project: pymine   Author: joedeller   File: drawpic.py    MIT License 4 votes vote down vote up
def colormap(pixel):
    white = (221, 221, 221)
    orange = (219, 125, 62)
    magenta = (179, 80, 188)
    lightblue = (107, 138, 201)
    yellow = (177, 166, 39)
    lime = (65, 174, 56)
    pink = (208, 132, 153)
    gray = (64, 64, 64)
    lightgray = (154, 161, 161)
    cyan = (46, 110, 137)
    purple = (126, 61, 181)
    blue = (46, 56, 141)
    brown = (79, 50, 31)
    green = (53, 70, 27)
    red = (150, 52, 48)
    black = (25, 22, 22)
    colors = (
        white,
        orange,
        magenta,
        lightblue,
        yellow,
        lime,
        pink,
        gray,
        lightgray,
        cyan,
        purple,
        blue,
        brown,
        green,
        red,
        black)
    thecolor = 0
    finalresult = 256 * 256 * 256
    for idx, color in enumerate(colors):
        result = math.fabs(
            color[0] - pixel[0]) + math.fabs(color[1] - pixel[1]) + math.fabs(color[2] - pixel[2])
        if result < finalresult:
            finalresult = result
            thecolor = idx
    return thecolor

# LOAD IMAGE FILE 
Example 80
Project: OF_Plugin-PyMesh   Author: TinyTinni   File: test_trimesh_others.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_is_estimated_feature_edge(self):
        # Test setup:
        #  1 -- 2
        #  |  / |
        #  | /  |
        #  0 -- 3

        # Add some vertices
        self.vhandle.append(self.mesh.add_vertex(np.array([0, 0, 0])))
        self.vhandle.append(self.mesh.add_vertex(np.array([0, 1, 0])))
        self.vhandle.append(self.mesh.add_vertex(np.array([1, 1, 0])))
        self.vhandle.append(self.mesh.add_vertex(np.array([1, 0, 0])))

        # Add two faces
        face_vhandles = []

        face_vhandles.append(self.vhandle[0])
        face_vhandles.append(self.vhandle[1])
        face_vhandles.append(self.vhandle[2])
        self.mesh.add_face(face_vhandles)

        face_vhandles = []

        face_vhandles.append(self.vhandle[0])
        face_vhandles.append(self.vhandle[2])
        face_vhandles.append(self.vhandle[3])
        self.mesh.add_face(face_vhandles)

        # ===============================================
        # Setup complete
        # ===============================================

        he = self.mesh.halfedge_handle(4)

        self.assertEqual(self.mesh.to_vertex_handle(he).idx(), 0)
        self.assertEqual(self.mesh.from_vertex_handle(he).idx(), 2)
        self.assertEqual(self.mesh.edge_handle(he).idx(), 2)

        eh = self.mesh.edge_handle(he)
        self.assertEqual(self.mesh.calc_dihedral_angle(eh), 0.0)

        # Modify point
        tmp = (np.array([0.0, 0.0, -1.0]) + np.array([1.0, 1.0, -1.0])) * 0.5
        self.mesh.set_point(self.vhandle[2], tmp)

        difference = fabs(1.36944 - self.mesh.calc_dihedral_angle(eh))

        self.assertTrue(difference < 0.00001)