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
python类fabs()的实例源码
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
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 ##
############################
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)
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")
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
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
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)
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)
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)
# )
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
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)
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.
dual_quaternion_hand_eye_calibration.py 文件源码
项目:hand_eye_calibration
作者: ethz-asl
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
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)
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())
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')
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
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
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.
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
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
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()
read_data.py 文件源码
项目:human-pose-estimation-by-deep-learning
作者: HYPJUDY
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
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)
move_to_home.py 文件源码
项目:master_robot_strage
作者: nwpu-basketball-robot
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
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
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
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
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")
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
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
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")