Python math.fabs() Examples

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

Example 1
Project: AnomalyDetection   Author: JayZhuCoding   File: Monitor.py    (Apache License 2.0) View Source Project 10 votes vote down vote up
def optimize_training_parameters(self, n):
        # data
        from_timestamp = self.min_timestamp
        to_timestamp = self.min_timestamp + datetime.timedelta(days=365) + datetime.timedelta(hours=1)
        train_timestamps, train_values = self.load_monitor_data(from_timestamp, to_timestamp, "1")
        train_data = np.array(train_values)[:, 0:5]

        # parameters
        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
        fw = open("training_param.csv", "w")
        fw.write("nu,gamma,diff\n")
        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(train_data)
                label = classifier.predict(train_data)
                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]
                fw.write(",".join([str(nu[i]), str(gamma[j]), str(diff)]) + "\n")
        fw.close()
        return opt_nu, opt_gamma 
Example 2
Project: astrobase   Author: waqasbhatti   File: coordutils.py    (MIT License) View Source Project 7 votes vote down vote up
def decimal_to_dms(decimal_value):
    '''
    This converts from decimal degrees to DD:MM:SS, returned as a tuple.

    '''

    if decimal_value < 0:
        negative = True
        dec_val = fabs(decimal_value)
    else:
        negative = False
        dec_val = decimal_value

    degrees = trunc(dec_val)
    minutes_deg = dec_val - degrees

    minutes_mm = minutes_deg * 60.0
    minutes_out = trunc(minutes_mm)
    seconds = (minutes_mm - minutes_out)*60.0

    if negative:
        degrees = degrees
        return '-', degrees, minutes_out, seconds
    else:
        return '+', degrees, minutes_out, seconds 
Example 3
Project: astrobase   Author: waqasbhatti   File: coordutils.py    (MIT License) View Source Project 6 votes vote down vote up
def dms_to_decimal(sign, degrees, minutes, seconds):
    '''
    Converts from DD:MM:SS to a decimal value. Returns decimal degrees.

    '''

    dec_deg = fabs(degrees) + fabs(minutes)/60.0 + fabs(seconds)/3600.0

    if sign == '-':
        return -dec_deg
    else:
        return dec_deg


############################
## DISTANCE AND XMATCHING ##
############################ 
Example 4
Project: nxt-sketcher   Author: simondolle   File: printer.py    (MIT License) View Source Project 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 5
Project: tnt   Author: pytorch   File: test_meters.py    (license) View Source Project 6 votes vote down vote up
def testAUCMeter(self):
        mtr = meter.AUCMeter()

        test_size = 1000
        mtr.add(torch.rand(test_size), torch.zeros(test_size))
        mtr.add(torch.rand(test_size), torch.Tensor(test_size).fill_(1))

        val, tpr, fpr = mtr.value()
        self.assertTrue(math.fabs(val - 0.5) < 0.1, msg="AUC Meter fails")

        mtr.reset()
        mtr.add(torch.Tensor(test_size).fill_(0), torch.zeros(test_size))
        mtr.add(torch.Tensor(test_size).fill_(0.1), torch.zeros(test_size))
        mtr.add(torch.Tensor(test_size).fill_(0.2), torch.zeros(test_size))
        mtr.add(torch.Tensor(test_size).fill_(0.3), torch.zeros(test_size))
        mtr.add(torch.Tensor(test_size).fill_(0.4), torch.zeros(test_size))
        mtr.add(torch.Tensor(test_size).fill_(1),
                torch.Tensor(test_size).fill_(1))
        val, tpr, fpr = mtr.value()

        self.assertEqual(val, 1.0, msg="AUC Meter fails") 
Example 6
Project: ns3-rdma   Author: bobzhuyb   File: hud.py    (license) View Source Project 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 7
Project: fem   Author: mlp6   File: GaussExc.py    (license) View Source Project 6 votes vote down vote up
def sym_scale_amp(fields, nodeGaussAmp, sym, search_tol=0.0001):
    """scale point load amplitude on symmetry faces / edges

    :param fields: list (node ID, x, y, z)
    :param nodeGaussAmp: amplitude of point load
    :param sym: type of mesh symmetry (none, qsym, hsym)
    :param search_tol: spatial tolerance to find nearby nodes
    :returns nodeGaussAmp: symmetry-scaled point load amplitude
    """
    from math import fabs
    import sys

    if sym == 'qsym':
        if (fabs(fields[1]) < search_tol and fabs(fields[2]) < search_tol):
            nodeGaussAmp = nodeGaussAmp / 4
        elif (fabs(fields[1]) < search_tol or fabs(fields[2]) < search_tol):
            nodeGaussAmp = nodeGaussAmp / 2
    elif sym == 'hsym':
        if fabs(fields[1]) < search_tol:
            nodeGaussAmp = nodeGaussAmp / 2
    elif sym != 'none':
        sys.exit('ERROR: Invalid symmetry option specified.')

    return nodeGaussAmp 
Example 8
Project: desert-mirage   Author: valentour   File: desert_mirage_lib.py    (license) View Source Project 6 votes vote down vote up
def euclidean_distance(x1, y1, x2, y2, prec_calc=2, prec_out=2):
    """
    Calculates euclidean distance between a pair of cartesian points.
    Includes parameter to apply a cutoff precision.

    Parameters
    ----------
    x1, y1: float coordinates of first point.
    x2, y2: float coordinates of second point.
    prec_calc: int (default: 3)
        decimal precision for calculations.
    prec_out: int (default: 2)
        output decimal precision.
    """
    x1, y1 = float(x1), float(y1)
    x2, y2 = float(x2), float(y2)
    x_off = dec_round(math.fabs(x1-x2), prec_calc, 'down')
    y_off = dec_round(math.fabs(y1-y2), prec_calc, 'down')
    dist = math.sqrt((x_off**2)+(y_off**2))
    return dec_round(dist, prec_out, 'down', True) 
Example 9
Project: arithmancer   Author: google   File: main.py    (license) View Source Project 6 votes vote down vote up
def GetUserByAuth():
  """Returns current users profile."""
  user_key = users.get_current_user().user_id()
  user_key = ndb.Key('Profile', user_key)
  profile = user_key.get()
  for ledger in profile.user_ledger:
    try:
      price = GetPriceByPredictionId(ledger.prediction_id)
      ledger.value = math.fabs((price * ledger.contract_one) - (
          price * ledger.contract_two))
      ledger.prediction_statement = ndb.Key(
          urlsafe=ledger.prediction_id).get().statement
    except:
      ledger.value = 404
      ledger.prediction_statement = 'ERROR'
  return render_template('profile.html', profile=profile) 
Example 10
Project: django-example   Author: gen1us2k   File: models.py    (license) View Source Project 6 votes vote down vote up
def update_balance(self, reason, money, **kwargs):
        from billing.models import MoneyLog
        ml_filter = {}
        task = kwargs.get('task', None)
        ml_filter['reason'] = reason
        ml_filter['user'] = self
        ml_filter['debit'] = math.fabs(money) if money < 0 else 0
        ml_filter['credit'] = math.fabs(money) if money > 0 else 0
        ml_filter['money'] = money
        ml_filter['task'] = task
        current_balance = User.objects.select_for_update().get(pk=self.pk).balance
        ml_filter['balance'] = current_balance + Decimal(money)

        try:
            ml = MoneyLog.objects.get(**ml_filter)
        except MoneyLog.DoesNotExist:
            try:
                ml = MoneyLog.objects.create(**ml_filter)
            except IntegrityError:
                ml = MoneyLog.objects.get(**ml_filter)

            # User.objects.select_for_update().filter(pk=self.pk).update(
            #     balance=F('balance') + Decimal(money)
            # ) 
Example 11
Project: bpy_lambda   Author: bcongdon   File: geodesic_classes_271.py    (license) View Source Project 6 votes vote down vote up
def ellipsecomp(self, efactor, theta):
        if theta == self.a90:
            result = self.a90
        elif theta == self.a270:
            result = self.a270
        else:
            result = atan(tan(theta) / efactor**0.5)
            if result >= 0.0:
                x = result
                y = self.a180 + result
                if fabs(x - theta) <= fabs(y - theta):
                    result = x
                else:
                    result = y
            else:
                x = self.a180 + result
                y = result

                if fabs(x - theta) <= fabs(y - theta):
                    result = x
                else:
                    result = y
        return result 
Example 12
Project: Houston   Author: squaresLab   File: util.py    (license) View Source Project 6 votes vote down vote up
def BodyRatesToEarthRates(dcm, gyro):
    """Convert the angular velocities from body frame to
    earth frame.

    all inputs and outputs are in radians/s

    returns a earth rate vector.
    """
    from math import sin, cos, tan, fabs

    p      = gyro.x
    q      = gyro.y
    r      = gyro.z

    (phi, theta, psi) = dcm.to_euler()

    phiDot   = p + tan(theta) * (q * sin(phi) + r * cos(phi))
    thetaDot = q * cos(phi) - r * sin(phi)
    if fabs(cos(theta)) < 1.0e-20:
        theta += 1.0e-10
    psiDot   = (q * sin(phi) + r * cos(phi)) / cos(theta)
    return Vector3(phiDot, thetaDot, psiDot) 
Example 13
Project: Houston   Author: squaresLab   File: util.py    (license) View Source Project 6 votes vote down vote up
def current(self, deltat=None):
        """Return current wind speed and direction as a tuple
        speed is in m/s, direction in degrees."""
        if deltat is None:
            tnow = time.time()
            deltat = tnow - self.tlast
            self.tlast = tnow

        # update turbulance random walk
        w_delta = math.sqrt(deltat) * (1.0 - random.gauss(1.0, self.turbulance))
        w_delta -= (self.turbulance_mul - 1.0) * (deltat / self.turbulance_time_constant)
        self.turbulance_mul += w_delta
        speed = self.speed * math.fabs(self.turbulance_mul)
        return (speed, self.direction)

    # Calculate drag. 
Example 14
Project: hand_eye_calibration   Author: ethz-asl   File: dual_quaternion_hand_eye_calibration.py    (license) View Source Project 6 votes vote down vote up
def compute_pose_error(pose_A, pose_B):
  """
  Compute the error norm of position and orientation.
  """
  error_position = np.linalg.norm(pose_A[0:3] - pose_B[0:3], ord=2)

  # Construct quaternions to compare.
  quaternion_A = Quaternion(q=pose_A[3:7])
  quaternion_A.normalize()
  if quaternion_A.w < 0:
    quaternion_A.q = -quaternion_A.q
  quaternion_B = Quaternion(q=pose_B[3:7])
  quaternion_B.normalize()
  if quaternion_B.w < 0:
    quaternion_B.q = -quaternion_B.q

  # Sum up the square of the orientation angle error.
  error_angle_rad = angle_between_quaternions(
      quaternion_A, quaternion_B)
  error_angle_degrees = math.degrees(error_angle_rad)
  if error_angle_degrees > 180.0:
    error_angle_degrees = math.fabs(360.0 - error_angle_degrees)

  return (error_position, error_angle_degrees) 
Example 15
Project: Workplane   Author: BenjaminSauder   File: update.py    (license) View Source Project 6 votes vote down vote up
def get_orientation_constraints_and_matrix(cls, rv3d):
        view_rotation = rv3d.view_rotation.to_matrix()
        view_dir = view_rotation * Z
        
        M = workplane.data.get_matrix().to_3x3()
                        
        x = math.fabs((M*X).dot(view_dir))
        y = math.fabs((M*Y).dot(view_dir))
        z = math.fabs((M*Z).dot(view_dir))
        
        #print("-------------")
        #print("x: " + str(x))
        #print("y: " + str(y))
        #print("z: " + str(z))
        #print("-------------")
        
        enable_x = x < y or x < z
        enable_y = y < x or y < z
        enable_z = z < x or z < y
        constraints = (enable_x,enable_y,enable_z)    
        
        return (constraints, M.to_4x4()) 
Example 16
Project: arlpy   Author: org-arl   File: geo.py    (license) View Source Project 6 votes vote down vote up
def str(latlong):
    """Convert latitude/longitude information in various formats into a pretty printable Unicode string."""
    if len(latlong) == 2:
        return u'{0:f}\N{DEGREE SIGN}{1:s}, {2:f}\N{DEGREE SIGN}{3:s}'.format(_fabs(latlong[0]), _ns(latlong[0]), _fabs(latlong[1]), _ew(latlong[1]))
    elif len(latlong) == 3:
        return u'{0:f}\N{DEGREE SIGN}{1:s}, {2:f}\N{DEGREE SIGN}{3:s}, {4:.3f}m'.format(_fabs(latlong[0]), _ns(latlong[0]), _fabs(latlong[1]), _ew(latlong[1]), latlong[2])
    elif len(latlong) == 4:
        return u'{0:.0f}\N{DEGREE SIGN}{1:.4f}\'{2:s}, {3:.0f}\N{DEGREE SIGN}{4:.4f}\'{5:s}'.format(_fabs(latlong[0]), latlong[1], _ns(latlong[0]), _fabs(latlong[2]), latlong[3], _ew(latlong[2]))
    elif len(latlong) == 5:
        return u'{0:.0f}\N{DEGREE SIGN}{1:.4f}\'{2:s}, {3:.0f}\N{DEGREE SIGN}{4:.4f}\'{5:s}, {6:.3f}m'.format(_fabs(latlong[0]), latlong[1], _ns(latlong[0]), _fabs(latlong[2]), latlong[3], _ew(latlong[2]), latlong[4])
    elif len(latlong) == 6:
        return u'{0:.0f}\N{DEGREE SIGN}{1:.0f}\'{2:.2f}"{3:s}, {4:.0f}\N{DEGREE SIGN}{5:.0f}\'{6:.2f}"{7:s}'.format(_fabs(latlong[0]), latlong[1], latlong[2], _ns(latlong[0]), _fabs(latlong[3]), latlong[4], latlong[5], _ew(latlong[3]))
    elif len(latlong) == 7:
        return u'{0:.0f}\N{DEGREE SIGN}{1:.0f}\'{2:.2f}"{3:s}, {4:.0f}\N{DEGREE SIGN}{5:.0f}\'{6:.2f}"{7:s}, {8:.3f}m'.format(_fabs(latlong[0]), latlong[1], latlong[2], _ns(latlong[0]), _fabs(latlong[3]), latlong[4], latlong[5], _ew(latlong[3]), latlong[6])
    else:
        raise ValueError('Incorrect format for latitude/longitude data') 
Example 17
Project: SO-2017-2   Author: flaviovdf   File: disk-precise.py    (license) View Source Project 6 votes vote down vote up
def DoSSTF(self, rList):
        minDist   = MAXTRACKS
        minBlock  = -1
        trackList = []  # all the blocks on a track

        for (block, index) in rList:
            if self.requestState[index] == STATE_DONE:
                continue
            track = self.blockToTrackMap[block]
            dist  = int(math.fabs(self.armTrack - track))
            if dist < minDist:
                trackList = []
                trackList.append((block, index))
                minDist = dist
            elif dist == minDist:
                trackList.append((block, index))
        assert(trackList != [])
        return trackList 
Example 18
Project: SO-2017-2   Author: flaviovdf   File: disk.py    (license) View Source Project 6 votes vote down vote up
def DoSSTF(self, rList):
        minDist   = MAXTRACKS
        minBlock  = -1
        trackList = []  # all the blocks on a track

        for (block, index) in rList:
            if self.requestState[index] == STATE_DONE:
                continue
            track = self.blockToTrackMap[block]
            dist  = int(math.fabs(self.armTrack - track))
            if dist < minDist:
                trackList = []
                trackList.append((block, index))
                minDist = dist
            elif dist == minDist:
                trackList.append((block, index))
        assert(trackList != [])
        return trackList 
Example 19
Project: pyall   Author: pktrigg   File: geodetic.py    (license) View Source Project 6 votes vote down vote up
def est_dist(  latitude1,  longitude1,  latitude2,  longitude2 ) :
        """ 

        Returns an estimate of the distance between two geographic points
        This is a quick and dirty vinc_dist 
        which will generally estimate the distance to within 1%
        Returns distance in metres

        """
        f = 1.0 / 298.257223563		# WGS84
        a = 6378137.0 			# metres

        piD4   = 0.785398163397 

        latitude1    = latitude1 * piD4 / 45.0
        longitude1 = longitude1 * piD4 / 45.0
        latitude2    = latitude2 * piD4 / 45.0
        longitude2 = longitude2 * piD4 / 45.0

        c = math.cos((latitude2+latitude1)/2.0)

        return math.sqrt( pow(math.fabs(latitude2-latitude1), 2) + \
                pow(math.fabs(longitude2-longitude1)*c, 2) ) * a * ( 1.0 - f + f * c )
   # END of rough estimate of the distance. 
Example 20
Project: krpc-library   Author: krpc   File: rendezvous.py    (license) View Source Project 6 votes vote down vote up
def time_transfer(vessel, target, ut, phase_angle):
    '''
    Performs an iterative search for the next time vessel and target
    have the given relative phase_angle after ut
    '''
    print("Doing Coarse Search for Transfer Time...")
    #coarse unbound search
    while True:        
        v_pos = orbital_progress(vessel, ut)
        t_pos =  orbital_progress(target, ut)
        angle_error = math.fabs(t_pos - (v_pos - math.pi) - phase_angle)
        if  angle_error < .01:
            break
        ut += 10
    ut -= 10
    #fine unbound search
    print("Doing Fine Search for Transfer Time...")
    while True:        
        v_pos = orbital_progress(vessel, ut)
        t_pos =  orbital_progress(target, ut)
        angle_error = math.fabs(t_pos - (v_pos - math.pi) - phase_angle)
        if  angle_error < .001:
            break
        ut += 1
    return ut 
Example 21
Project: RaiWalletBot   Author: SergiySW   File: raiwalletbot.py    (license) View Source Project 6 votes vote down vote up
def block_count_callback(bot, update):
	user_id = update.message.from_user.id
	count = rpc({"action": "block_count"}, 'count')
	text_reply(update, "{:,}".format(int(count)))
#	default_keyboard(bot, update.message.chat_id, r)
	# Admin block count check from raiblockscommunity.net
	if (user_id in admin_list):
		http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',ca_certs=certifi.where())
		response = http.request('GET', summary_url, headers=header, timeout=20.0)
		json_data = json.loads(response.data)
		community_count = json_data['blocks']
		if (math.fabs(int(community_count) - int(count)) > block_count_difference_threshold):
			text_reply(update, 'Community: {0}'.format("{:,}".format(int(community_count))))
			reference_count = int(reference_block_count())
			sleep(1)
			text_reply(update, 'Reference: {0}'.format("{:,}".format(reference_count)))
			response = http.request('GET', 'https://raiwallet.info/api/block_count.php', headers=header, timeout=20.0)
			raiwallet_count = int(response.data)
			sleep(1)
			text_reply(update, 'raiwallet.info: {0}'.format("{:,}".format(raiwallet_count)))


# broadcast 
Example 22
Project: RaiWalletBot   Author: SergiySW   File: monitoring.py    (license) View Source Project 6 votes vote down vote up
def monitoring_block_count():
	# set bot
	bot = Bot(api_key)
	count = int(rpc({"action": "block_count"}, 'count'))
	reference_count = int(reference_block_count())
	
	http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',ca_certs=certifi.where())
	response = http.request('GET', summary_url, headers=header, timeout=20.0)
	try:
		json_data = json.loads(response.data)
		community_count = int(json_data['blocks'])
	except ValueError as e:
		community_count = reference_count
	difference = int(math.fabs(community_count - count))
	
	response = http.request('GET', block_count_url, headers=header, timeout=20.0)
	raiwallet_count = int(response.data)
	
	if (difference > block_count_difference_threshold):
		# Warning to admins
		for user_id in admin_list:
			push(bot, user_id, 'Block count: {0}\nCommunity: {1}\nDifference: *{2}*\nReference: {3}\nraiwallet.info: {4}'.format(count, community_count, difference, reference_count, raiwallet_count))
		# trying to fix
		bootstrap_multi() 
Example 23
Project: human-pose-estimation-by-deep-learning   Author: HYPJUDY   File: read_data.py    (license) View Source Project 6 votes vote down vote up
def label2sm_fm(self, label):
        def get_point(a_list, idx):
            w, h = a_list[idx * 2: idx * 2 + 2]
            return int(w * self.fm_width), int(h * self.fm_height)

        def p8_distance(h1, h2, w1, w2):
            return max(math.fabs(h1 - h2), math.fabs(w1 - w2))

        def p4_distance(h1, h2, w1, w2):
            return math.fabs(h1 - h2) + math.fabs(w1 - w2)

        def draw(img, center, idx):
            w0, h0 = center
            height, width = img.shape
            for w in xrange(max(0, w0-self.radius), min(width, w0+self.radius+1)):
                for h in xrange(max(0, h0-self.radius), min(height, h0+self.radius+1)):
                    if(p8_distance(h, h0, w, w0) < self.radius):
                        img[h, w] = idx + 1
        fm_label = np.zeros((label.shape[0], self.fm_height, self.fm_width))
        for batch_idx in xrange(len(fm_label)):
            for ii in xrange(self.points_num):
                w, h = get_point(label[batch_idx], ii)
                draw(fm_label[batch_idx], (w, h), ii)
        # fm_label = fm_label.astype(np.int32)
        return fm_label.astype(np.int32) 
Example 24
Project: master_robot_strage   Author: nwpu-basketball-robot   File: move_to_home.py    (license) View Source Project 6 votes vote down vote up
def start_run(self, at_home_door, distance, angular):
        if at_home_door == True:
            self.brake()
            self.robot_move.move_to(x=self.last_move_goal)
            return True
        if distance > (self.line_distance + self.distance_tolerance):
            self.vel.linear.x = self.x_speed
            self.vel.linear.y = math.copysign(self.y_speed, self.move_direction)
        elif distance < (self.line_distance - self.distance_tolerance):
            self.vel.linear.x = self.x_speed * -1
            self.vel.linear.y = self.y_speed
        else:
            self.vel.linear.x = 0
            self.vel.linear.y = self.y_speed
        if math.fabs(angular) < self.angular_tolerance:
            self.vel.angular.z = 0
        elif angular > 0:
            self.vel.angular.z = -1 * self.z_speed
        else:
            self.vel.angular.z = self.z_speed
        self.cmd_move_pub.publish(self.vel)

        return False 
Example 25
Project: retinal-exudates-detection   Author: getsanjeev   File: testing.py    (license) View Source Project 6 votes vote down vote up
def get_DistanceFromOD_data(image, centre):
	my_image = image.copy()
	x_cor = centre[0]
	y_cor = centre[1]
	feature_5 = np.reshape(image, (image.size,1))
	k = 0
	i = 0
	j = 0
	while i < image.shape[0]:
		j = 0
		while j < image.shape[1]:
			feature_5[k] = math.fabs(x_cor-i) + math.fabs(y_cor-j)
			j = j+1
			k = k+1
		i = i+1
	return feature_5 
Example 26
Project: retinal-exudates-detection   Author: getsanjeev   File: training.py    (license) View Source Project 6 votes vote down vote up
def get_DistanceFromOD_data(image, centre):
	my_image = image.copy()
	x_cor = centre[0]
	y_cor = centre[1]
	feature_5 = np.reshape(image, (image.size,1))
	k = 0
	i = 0
	j = 0
	while i < image.shape[0]:
		j = 0
		while j < image.shape[1]:
			feature_5[k] = math.fabs(x_cor-i) + math.fabs(y_cor-j)
			j = j+1
			k = k+1
		i = i+1
	return feature_5 
Example 27
Project: retinal-exudates-detection   Author: getsanjeev   File: rough_copy.py    (license) View Source Project 6 votes vote down vote up
def get_DistanceFromOD_data(image, centre):
	my_image = image.copy()
	x_cor = centre[0]
	y_cor = centre[1]
	feature_5 = np.reshape(image, (image.size,1))
	k = 0
	i = 0
	j = 0
	while i < image.shape[0]:
		j = 0
		while j < image.shape[1]:
			feature_5[k] = math.fabs(x_cor-i) + math.fabs(y_cor-j)
			j = j+1
			k = k+1
		i = i+1
	print(np.reshape(feature_5,(10,10)))
	return feature_5


#os.remove("model.sh") 
Example 28
Project: vrep-maze-solver   Author: youralien   File: Lab2Program.py    (license) View Source Project 6 votes vote down vote up
def angle_diff(a, b):
    """ Calculates the difference between angle a and angle b (both should be in radians)
        the difference is always based on the closest rotation from angle a to angle b
        examples:
            angle_diff(.1,.2) -> -.1
            angle_diff(.1, 2*math.pi - .1) -> .2
            angle_diff(.1, .2+2*math.pi) -> -.1
    """
    a = ThetaRange.normalize_angle(a)
    b = ThetaRange.normalize_angle(b)
    d1 = a-b
    d2 = 2*math.pi - math.fabs(d1)
    if d1 > 0:
        d2 *= -1.0
    if math.fabs(d1) < math.fabs(d2):
        return d1
    else:
        return d2 
Example 29
Project: StatisKit   Author: StatisKit   File: intelc.py    (license) View Source Project 6 votes vote down vote up
def get_version_from_list(v, vlist):
    """See if we can match v (string) in vlist (list of strings)
    Linux has to match in a fuzzy way."""
    if is_windows:
        # Simple case, just find it in the list
        if v in vlist: return v
        else: return None
    else:
        # Fuzzy match: normalize version number first, but still return
        # original non-normalized form.
        fuzz = 0.001
        for vi in vlist:
            if math.fabs(linux_ver_normalize(vi) - linux_ver_normalize(v)) < fuzz:
                return vi
        # Not found
        return None 
Example 30
Project: bitshares-pricefeed   Author: xeroc   File: pricefeed.py    (license) View Source Project 6 votes vote down vote up
def obtain_flags(self, symbol):
        """ This will add attributes to price_result and indicate the results
            of a couple testsin the `flags` key
        """
        # Test flags
        self.price_result[symbol]["flags"] = []

        # Check max price change
        if fabs(self.price_result[symbol]["priceChange"]) > fabs(self.assetconf(symbol, "min_change")):
            self.price_result[symbol]["flags"].append("min_change")

        # Check max price change
        if fabs(self.price_result[symbol]["priceChange"]) > fabs(self.assetconf(symbol, "warn_change")):
            self.price_result[symbol]["flags"].append("over_warn_change")

        # Check max price change
        if fabs(self.price_result[symbol]["priceChange"]) > fabs(self.assetconf(symbol, "skip_change")):
            self.price_result[symbol]["flags"].append("skip_change")

        # Feed too old
        feed_age = self.price_result[symbol]["current_feed"]["date"] if self.price_result[symbol]["current_feed"] else datetime.min
        if (datetime.utcnow() - feed_age).total_seconds() > self.assetconf(symbol, "maxage"):
            self.price_result[symbol]["flags"].append("over_max_age") 
Example 31
Project: MagicWand   Author: GianlucaSilvestri   File: color_conversions.py    (license) View Source Project 6 votes vote down vote up
def Lab_to_LCHab(cobj, *args, **kwargs):
    """
    Convert from CIE Lab to LCH(ab).
    """

    lch_l = cobj.lab_l
    lch_c = math.sqrt(math.pow(float(cobj.lab_a), 2) + math.pow(float(cobj.lab_b), 2))
    lch_h = math.atan2(float(cobj.lab_b), float(cobj.lab_a))

    if lch_h > 0:
        lch_h = (lch_h / math.pi) * 180
    else:
        lch_h = 360 - (math.fabs(lch_h) / math.pi) * 180

    return LCHabColor(
        lch_l, lch_c, lch_h, observer=cobj.observer, illuminant=cobj.illuminant)


# noinspection PyPep8Naming,PyUnusedLocal 
Example 32
Project: MagicWand   Author: GianlucaSilvestri   File: color_conversions.py    (license) View Source Project 6 votes vote down vote up
def Luv_to_LCHuv(cobj, *args, **kwargs):
    """
    Convert from CIE Luv to LCH(uv).
    """

    lch_l = cobj.luv_l
    lch_c = math.sqrt(math.pow(cobj.luv_u, 2.0) + math.pow(cobj.luv_v, 2.0))
    lch_h = math.atan2(float(cobj.luv_v), float(cobj.luv_u))

    if lch_h > 0:
        lch_h = (lch_h / math.pi) * 180
    else:
        lch_h = 360 - (math.fabs(lch_h) / math.pi) * 180
    return LCHuvColor(
        lch_l, lch_c, lch_h, observer=cobj.observer, illuminant=cobj.illuminant)


# noinspection PyPep8Naming,PyUnusedLocal 
Example 33
Project: vehicle_detection   Author: AuzanMuh   File: math_operation.py    (license) View Source Project 6 votes vote down vote up
def centeroidPinHoleMode(height, focal, altitude, theta, yCoordinate):
    # height : jumlah baris (piksel)
    # focal -> |A'O| : focal length (piksel)
    # altitude -> |O'O| : tinggi kamera (m)
    # theta : sudut kemiringan kamera (derajat)
    # yCoordinate : indeks piksel Y object
    height = float(height)
    focal = float(focal)
    theta = float(theta)
    yCoordinate = float(yCoordinate)

    delta = math.degrees(math.atan(math.fabs(yCoordinate - (height / 2)) / focal))

    if yCoordinate >= height / 2:
        lCentroid = altitude * math.tan(math.radians(theta + delta))
    else:
        lCentroid = altitude * math.tan(math.radians(theta - delta))

    lCentroid = round(lCentroid, 4)
    delta = round(delta, 4)

    # print "delta: {0} | lCentroid: {1}".format(delta, lCentroid)
    return lCentroid 
Example 34
Project: SHIP   Author: duncan-r   File: bridgeunit.py    (license) View Source Project 6 votes vote down vote up
def area(self):
        """Returns the cross sectional area of the bridge openings.    
        
        Return:
            Dict - containing the area of the opening(s). keys = 'total', then
                '1', '2', 'n' for all openings found.
        """
        return 0
#         areas = []
#         opening_data = self.additional_row_collections['Opening']
#         x_vals = self.row_collection.getRowDataAsList(rdt.CHAINAGE)
#         y_vals = self.row_collection.getRowDataAsList(rdt.ELEVATION)
#         
#         start_vals = opening_data.getRowDataAsList(rdt.OPEN_START)
#         end_vals = opening_data.getRowDataAsList(rdt.OPEN_END)
#         soffit_vals = opening_data.getRowDataAsList(rdt.SOFFIT_LEVEL)
#         springing_vals = opening_data.getRowDataAsList(rdt.SPRINGING_LEVEL)
#         openings = zip(start_vals, end_vals, soffit_vals, springing_vals)
#         
#         for i, x in enumerate(x_vals):
#             
#             if math.fabs(x - ) 
#         
#         
#         i=0 
Example 35
Project: options   Author: mcmachado   File: Learning.py    (license) View Source Project 6 votes vote down vote up
def _improvePolicy(self):
		''' Policy improvement step. '''
		policy_stable = True
		for s in xrange(self.numStates):
			old_action = self.pi[s]
			tempV = [0.0] * len(self.actionSet)
			# I first get all value-function estimates
			for i in xrange(len(self.actionSet)):
				nextS, nextR = self.environment.getNextStateAndReward(
					s, self.actionSet[i])
				tempV[i] = nextR + self.gamma * self.V[nextS]

			# Now I take the argmax
			self.pi[s] = np.argmax(tempV)
			# I break ties always choosing to terminate:
			if math.fabs(tempV[self.pi[s]] - tempV[(len(self.actionSet) - 1)]) < 0.001:
				self.pi[s] = (len(self.actionSet) - 1)
			if old_action != self.pi[s]:
				policy_stable = False

		return policy_stable 
Example 36
Project: MLLearning   Author: buptdjd   File: DFP.py    (license) View Source Project 6 votes vote down vote up
def hessian_dfp(self, c, delta_w, delta_g, epsilon):
        n = delta_w.size
        d = delta_g.dot(delta_w)
        if fabs(d) < epsilon:
            return np.identity(n)
        a = np.zeros((n, n))
        a = delta_w.dot(delta_w)
        a /= d
        b = np.zeros((n, n))
        w2 = c.dot(delta_g)
        b = w2.dot(w2)
        d = delta_g.dot(w2)
        if fabs(d) < epsilon:
            return np.identity(n)
        b /= d
        return c+a-b 
Example 37
Project: zipline-chinese   Author: zhanghan1990   File: math_utils.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def tolerant_equals(a, b, atol=10e-7, rtol=10e-7):
    return math.fabs(a - b) <= (atol + rtol * math.fabs(b)) 
Example 38
Project: PyPPSPP   Author: justas-   File: LEDBAT.py    (GNU Lesser General Public License v3.0) View Source Project 5 votes vote down vote up
def _update_cto(self):
        # JP: One big WTF
        if self._first_est:
            self._srtt = self._qd
            self._rttvar = self._qd / 2
            self._cto = self._srtt + max([self._qd, LEDBAT.K * self._rttvar])
        else:
            self._rttvar = (1 - LEDBAT.BETA) * self._rttvar + LEDBAT.BETA * math.fabs(self._srtt - self._qd)
            self._srtt = (1 - LEDBAT.ALPHA) * self._srtt + LEDBAT.ALPHA * self._qd
            self._cto = self._srtt + max([self._g, LEDBAT.K * self._rttvar]) 
Example 39
Project: lung-cancer-detector   Author: YichenGong   File: luna.py    (MIT License) View Source Project 5 votes vote down vote up
def _construct_mask_values(self, ids):
		mask_vals = {}
		print("Creating Mask Values...")

		size = len(self._annotations)
		for idx, annotation in enumerate(self._annotations):
			print(str(idx) + "/" + str(size))
			series, z, y, x, d = annotation #Order as given in the tutorial for LUNA-16
			r = d/2.0
			try:
				img, o, s = p.load(open(os.path.join(self._target_directory, series + ".pick"), "rb"))
			except:
				continue
			if series not in mask_vals:
				mask_vals[series] = {}
			voxelCenter = dp.world_to_voxel_coord(np.array([x, y, z]), o, s)
			x, y, z = voxelCenter
			y = int(y)
			z = int(z)
			sliceRange = range(max(0, int(x - r/s[0])), int(x + r/s[0] + 1)) #1 so that we don't loose any information
			for sliceIdx in sliceRange:
				center = (z, y)
				radius = math.sqrt(max(0, r*r - ((s[0] * math.fabs(x - sliceIdx))**2)))
				if sliceIdx not in mask_vals[series]:
					mask_vals[series][sliceIdx] = []
				mask_vals[series][sliceIdx].append((center, max(radius/s[1], radius/s[2])))
		
		print("Mask values created!")
		return mask_vals 
Example 40
Project: astrobase   Author: waqasbhatti   File: coordutils.py    (MIT License) View Source Project 5 votes vote down vote up
def decimal_to_hms(decimal_value):
    '''
    This converts from decimal degrees to HH:MM:SS, returned as a
    tuple. Negative values of degrees are wrapped to 360.0.

    '''

    # wrap to 360.0
    if decimal_value < 0:
        dec_wrapped = 360.0 + decimal_value
    else:
        dec_wrapped = decimal_value

    # convert to decimal hours first
    dec_hours = dec_wrapped/15.0

    if dec_hours < 0:
        negative = True
        dec_val = fabs(dec_hours)
    else:
        negative = False
        dec_val = dec_hours

    hours = trunc(dec_val)
    minutes_hrs = dec_val - hours

    minutes_mm = minutes_hrs * 60.0
    minutes_out = trunc(minutes_mm)
    seconds = (minutes_mm - minutes_out)*60.0

    if negative:
        hours = -hours
        return hours, minutes_out, seconds
    else:
        return hours, minutes_out, seconds 
Example 41
Project: astrobase   Author: waqasbhatti   File: coordutils.py    (MIT License) View Source Project 5 votes vote down vote up
def hms_to_decimal(hours, minutes, seconds, returndeg=True):
    '''
    Converts from HH:MM:SS to a decimal value.

    if returndeg is True: returns decimal degrees
    if returndeg is False: returns decimal hours

    '''

    if hours > 24:

        return None

    else:

        dec_hours = fabs(hours) + fabs(minutes)/60.0 + fabs(seconds)/3600.0

        if returndeg:

            dec_deg = dec_hours*15.0

            if dec_deg < 0:
                dec_deg = dec_deg + 360.0
            dec_deg = dec_deg % 360.0
            return dec_deg
        else:
            return dec_hours 
Example 42
Project: code   Author: ActiveState   File: recipe-577113.py    (MIT License) View Source Project 5 votes vote down vote up
def adjust(xa, ya, x, y, xb, yb):
    global image
    if(image.getpixel((x,y)) == 0):
      d=math.fabs(xa-xb) + math.fabs(ya-yb)
      v=(image.getpixel((xa,ya)) + image.getpixel((xb,yb)))/2.0 \
         + (random.random()-0.5) * d * roughness
      c=int(math.fabs(v) % 256)
      image.putpixel((x,y), c) 
Example 43
Project: s2sphere   Author: sidewalklabs   File: sphere.py    (license) View Source Project 5 votes vote down vote up
def abs(self):
        return self.__class__(math.fabs(self.__point[0]),
                              math.fabs(self.__point[1]),
                              math.fabs(self.__point[2])) 
Example 44
Project: s2sphere   Author: sidewalklabs   File: sphere.py    (license) View Source Project 5 votes vote down vote up
def approx_equals(self, other, max_error=1e-15):
        return (math.fabs(self.lat().radians -
                          other.lat().radians) < max_error and
                math.fabs(self.lng().radians -
                          other.lng().radians) < max_error) 
Example 45
Project: s2sphere   Author: sidewalklabs   File: sphere.py    (license) View Source Project 5 votes vote down vote up
def approx_equals(self, other, max_error=1e-14):
        return ((self.axis().angle(other.axis()) <= max_error and
                 math.fabs(self.height() - other.height()) <= max_error) or
                (self.is_empty() and other.height() <= max_error) or
                (other.is_empty() and self.height() <= max_error) or
                (self.is_full() and other.height() >= 2 - max_error) or
                (other.is_full() and self.height() >= 2 - max_error)) 
Example 46
Project: s2sphere   Author: sidewalklabs   File: sphere.py    (license) View Source Project 5 votes vote down vote up
def is_valid(self):
        return (math.fabs(self.lat().lo()) <= math.pi / 2.0 and
                math.fabs(self.lat().hi()) <= math.pi / 2.0 and
                self.lng().is_valid() and
                self.lat().is_empty() == self.lng().is_empty()) 
Example 47
Project: s2sphere   Author: sidewalklabs   File: sphere.py    (license) View Source Project 5 votes vote down vote up
def area(self):
        """Area in steradians."""
        if self.is_empty():
            return 0.0

        return self.lng().get_length() * math.fabs(
            math.sin(self.lat_hi().radians) -
            math.sin(self.lat_lo().radians)
        ) 
Example 48
Project: s2sphere   Author: sidewalklabs   File: sphere.py    (license) View Source Project 5 votes vote down vote up
def is_unit_length(p):
    return math.fabs(p.norm() * p.norm() - 1) <= 1e-15 
Example 49
Project: s2sphere   Author: sidewalklabs   File: sphere.py    (license) View Source Project 5 votes vote down vote up
def approx_equals(self, other, max_error=1e-15):
        if self.is_empty():
            return other.get_length() <= max_error
        if other.is_empty():
            return self.get_length() <= max_error
        return (math.fabs(other.lo() - self.lo()) +
                math.fabs(other.hi() - self.hi()) <= max_error) 
Example 50
Project: s2sphere   Author: sidewalklabs   File: sphere.py    (license) View Source Project 5 votes vote down vote up
def from_point_pair(cls, a, b):
        assert math.fabs(a) <= math.pi
        assert math.fabs(b) <= math.pi
        if a == -math.pi:
            a = math.pi
        if b == -math.pi:
            b = math.pi
        if cls.positive_distance(a, b) <= math.pi:
            return cls(a, b, args_checked=True)
        else:
            return cls(b, a, args_checked=True)