def pdistance(self, p):
"""Perpendicular distance between this Segment and a given Point p"""
if not isinstance(p, Point):
return NotImplemented
if self.start == self.end:
# Distance from a Point to another Point is length of a segment
return Segment(self.start, p).length()
s = self.end - self.start
if s.x == 0:
# Vertical Segment => pdistance is the difference of abscissa
return abs(self.start.x - p.x)
else:
# That's 2-D perpendicular distance formulae (ref: Wikipedia)
slope = s.y / s.x
# intercept: Crossing with ordinate y-axis
intercept = self.start.y - (slope * self.start.x)
return abs(slope * p.x - p.y + intercept) / math.sqrt(
slope ** 2 + 1)
python类sqrt()的实例源码
def distance(ptsA, ptsB):
"""Function computing the Euclidian distance between two points.
Can be 2D or 3D coordinates.
Args:
ptsA: (list/numpy.array) - 2D/3D coordinates of point A;
ptsB: (list/numpy.array) - 2D/3D coordinates of point B;
Returns:
The Euclidian distance between points A & B.
"""
if len(ptsA) != len(ptsB):
warnings.warn("It seems that the points are not in the same space!")
return None
if len(ptsA) == 2:
return math.sqrt( (ptsA[0]-ptsB[0])**2+(ptsA[1]-ptsB[1])**2 )
if len(ptsA) == 3:
return math.sqrt( (ptsA[0]-ptsB[0])**2+(ptsA[1]-ptsB[1])**2+(ptsA[2]-ptsB[2])**2 )
def confidence_interval_dichotomous(
point_estimate, sample_size, confidence=.95, bias=False,
percentage=True, **kwargs):
"""Dichotomous confidence interval from sample size and maybe a bias"""
alpha = ppf((confidence + 1) / 2, sample_size - 1)
p = point_estimate
if percentage:
p /= 100
margin = sqrt(p * (1 - p) / sample_size)
if bias:
margin += .5 / sample_size
if percentage:
margin *= 100
return (point_estimate - alpha * margin, point_estimate + alpha * margin)
def _squares(self):
n_series_ = len(self.series)
i = 2
if sqrt(n_series_).is_integer():
_x = int(sqrt(n_series_))
_y = int(sqrt(n_series_))
else:
while i * i < n_series_:
while n_series_ % i == 0:
n_series_ = n_series_ / i
i = i + 1
_y = int(n_series_)
_x = int(n_series_ / len(self.series))
if len(self.series) == 5:
_x, _y = 2, 3
if abs(_x - _y) > 2:
_sq = 3
while (_x * _y) - 1 < len(self.series):
_x, _y = _sq, _sq
_sq += 1
return (_x, _y)
def compute(obj, client, task=None):
# obj is an instance of C
import math
# this task and client can use message passing
print('process at %s received: %s' % (task.location, obj.n))
yield task.sleep(obj.n)
obj.n = math.sqrt(obj.n)
# send result back to client
yield client.deliver(obj, timeout=5)
def compute(obj, client, task=None):
# obj is an instance of C
import math
# this task and client can use message passing
print('process at %s received: %s' % (task.location, obj.n))
yield task.sleep(obj.n)
obj.n = math.sqrt(obj.n)
# send result back to client
yield client.deliver(obj, timeout=5)
def compute(obj, client, task=None):
# obj is an instance of C
import math
# this task and client can use message passing
print('process at %s received: %s' % (task.location, obj.n))
yield task.sleep(obj.n)
obj.n = math.sqrt(obj.n)
# send result back to client
yield client.deliver(obj, timeout=5)
def getDist(self, other):
ox, oy = other.getCoords()
xDist = self.x - ox
yDist = self.y - oy
return math.sqrt(xDist**2+yDist**2)
def normalise_word_vectors(word_vectors, norm=1.0):
"""
This method normalises the collection of word vectors provided in the word_vectors dictionary.
"""
for word in word_vectors:
word_vectors[word] /= math.sqrt((word_vectors[word]**2).sum() + 1e-6)
word_vectors[word] = word_vectors[word] * norm
return word_vectors
def _init_gradients(self, vec_magnitude):
"""Initialize all gradient vectors to be in random directions with the same magnitude.
Args:
vec_magnitude (float): Magnitude of all gradient vectors.
"""
self._grad_vecs = [[(0, 0) for _ in range(self._width_in_squares+1)] for _ in range(self._length_in_squares+1)]
"""list[list[tuple(float, float)]]: Grid of gradient vectors."""
for x in range(self._width_in_squares+1):
for y in range(self._length_in_squares+1):
x_val = (random.random() - 0.5) * 2 * vec_magnitude
y_val = math.sqrt(vec_magnitude**2 - x_val**2) * random.choice([1, -1])
self._grad_vecs[y][x] = (x_val, y_val)
def weightVariable(shape,std=1.0,name=None):
# Create a set of weights initialized with truncated normal random values
name = 'weights' if name is None else name
return tf.get_variable(name,shape,initializer=tf.truncated_normal_initializer(stddev=std/math.sqrt(shape[0])))
def plotFields(layer,fieldShape=None,channel=None,figOffset=1,cmap=None,padding=0.01):
# Receptive Fields Summary
try:
W = layer.W
except:
W = layer
wp = W.eval().transpose();
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
else: # Convolutional layer already has shape
features, channels, iy, ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fig = mpl.figure(figOffset); mpl.clf()
# Using image grid
from mpl_toolkits.axes_grid1 import ImageGrid
grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
for i in range(0,np.shape(fields)[0]):
im = grid[i].imshow(fields[i],cmap=cmap);
grid.cbar_axes[0].colorbar(im)
mpl.title('%s Receptive Fields' % layer.name)
# old way
# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
# tiled = []
# for i in range(0,perColumn*perRow,perColumn):
# tiled.append(np.hstack(fields2[i:i+perColumn]))
#
# tiled = np.vstack(tiled)
# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
mpl.figure(figOffset+1); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
def plotOutput(layer,feed_dict,fieldShape=None,channel=None,figOffset=1,cmap=None):
# Output summary
try:
W = layer.output
except:
W = layer
wp = W.eval(feed_dict=feed_dict);
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
temp = np.zeros(np.product(fieldShape)); temp[0:np.shape(wp.ravel())[0]] = wp.ravel()
fields = np.reshape(temp,[1]+fieldShape)
else: # Convolutional layer already has shape
wp = np.rollaxis(wp,3,0)
features, channels, iy,ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
perRow = int(math.floor(math.sqrt(fields.shape[0])))
perColumn = int(math.ceil(fields.shape[0]/float(perRow)))
fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
tiled = []
for i in range(0,perColumn*perRow,perColumn):
tiled.append(np.hstack(fields2[i:i+perColumn]))
tiled = np.vstack(tiled)
if figOffset is not None:
mpl.figure(figOffset); mpl.clf();
mpl.imshow(tiled,cmap=cmap); mpl.title('%s Output' % layer.name); mpl.colorbar();
def weightVariable(shape,std=1.0,name=None):
# Create a set of weights initialized with truncated normal random values
name = 'weights' if name is None else name
return tf.get_variable(name,shape,initializer=tf.truncated_normal_initializer(stddev=std/math.sqrt(shape[0])))
def plotFields(layer,fieldShape=None,channel=None,maxFields=25,figName='ReceptiveFields',cmap=None,padding=0.01):
# Receptive Fields Summary
W = layer.W
wp = W.eval().transpose();
if len(np.shape(wp)) < 4: # Fully connected layer, has no shape
fields = np.reshape(wp,list(wp.shape[0:-1])+fieldShape)
else: # Convolutional layer already has shape
features, channels, iy, ix = np.shape(wp)
if channel is not None:
fields = wp[:,channel,:,:]
else:
fields = np.reshape(wp,[features*channels,iy,ix])
fieldsN = min(fields.shape[0],maxFields)
perRow = int(math.floor(math.sqrt(fieldsN)))
perColumn = int(math.ceil(fieldsN/float(perRow)))
fig = mpl.figure(figName); mpl.clf()
# Using image grid
from mpl_toolkits.axes_grid1 import ImageGrid
grid = ImageGrid(fig,111,nrows_ncols=(perRow,perColumn),axes_pad=padding,cbar_mode='single')
for i in range(0,fieldsN):
im = grid[i].imshow(fields[i],cmap=cmap);
grid.cbar_axes[0].colorbar(im)
mpl.title('%s Receptive Fields' % layer.name)
# old way
# fields2 = np.vstack([fields,np.zeros([perRow*perColumn-fields.shape[0]] + list(fields.shape[1:]))])
# tiled = []
# for i in range(0,perColumn*perRow,perColumn):
# tiled.append(np.hstack(fields2[i:i+perColumn]))
#
# tiled = np.vstack(tiled)
# mpl.figure(figOffset); mpl.clf(); mpl.imshow(tiled,cmap=cmap); mpl.title('%s Receptive Fields' % layer.name); mpl.colorbar();
mpl.figure(figName+' Total'); mpl.clf(); mpl.imshow(np.sum(np.abs(fields),0),cmap=cmap); mpl.title('%s Total Absolute Input Dependency' % layer.name); mpl.colorbar()
def dist(p1, p2):
return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
def dist(self, p1, p2):
return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
def declination(self):
"""Calculate declination of vector in degrees"""
return math.degrees(math.atan2(math.sqrt(self.x ** 2 + self.y ** 2), self.z))
def points_for_floor_split(self):
"""Calculate Poissonly distributed points for stem start points"""
array = []
# calculate approx spacing radius for dummy stem
self.tree_scale = self.param.g_scale + self.param.g_scale_v
stem = Stem(0, None)
stem.length = self.calc_stem_length(stem)
rad = 2.5 * self.calc_stem_radius(stem)
# generate points
for _ in range(self.param.floor_splits + 1):
point_ok = False
while not point_ok:
# distance from center proportional for number of splits, tree scale and stem radius
dis = sqrt(rand_in_range(0, 1) * self.param.floor_splits / 2.5 * self.param.g_scale * self.param.ratio)
# angle random in circle
theta = rand_in_range(0, 2 * pi)
pos = Vector([dis * cos(theta), dis * sin(theta), 0])
# test point against those already in array to ensure it will not intersect
point_m_ok = True
for point in array:
if (point[0] - pos).magnitude < rad:
point_m_ok = False
break
if point_m_ok:
point_ok = True
array.append((pos, theta))
return array
def radius_at_offset(self, stem, z_1):
""" calculate radius of stem at offset z_1 along it """
n_taper = self.param.taper[stem.depth]
if n_taper < 1:
unit_taper = n_taper
elif n_taper < 2:
unit_taper = 2 - n_taper
else:
unit_taper = 0
taper = stem.radius * (1 - unit_taper * z_1)
if n_taper < 1:
radius = taper
else:
z_2 = (1 - z_1) * stem.length
if n_taper < 2 or z_2 < taper:
depth = 1
else:
depth = n_taper - 2
if n_taper < 2:
z_3 = z_2
else:
z_3 = abs(z_2 - 2 * taper * int(z_2 / (2 * taper) + 0.5))
if n_taper < 2 and z_3 >= taper:
radius = taper
else:
radius = (1 - depth) * taper + depth * sqrt(pow(taper, 2) - pow((z_3 - taper), 2))
if stem.depth == 0:
y_val = max(0, 1 - 8 * z_1)
flare = self.param.flare * ((pow(100, y_val) - 1) / 100) + 1
radius *= flare
return radius