def test_perpendicular(p1, p2, p3):
assume(p1 != p2)
l = Line(p1, p2)
foot = l.foot(p3)
perp = l.perpendicular(p3)
print(foot)
print(perp)
# Property: foot should be on l.
assert line_collinear(p1, p2, foot)
# Property: foot should be on perp.
assert line_collinear(perp.p1, perp.p2, foot)
# Property: perp's angle should be 90 degrees from l's.
angle_between = l.angle() - perp.angle()
assert math.isclose(angle_between % 180, 90)
# Segments
python类isclose()的实例源码
def test_combine_paths(paths):
combined = combine_paths(paths)
# Property: the points in the combined paths should all have been in the
# original paths.
assert point_set(paths) >= point_set(combined)
# Property: the combined paths should have no duplicate endpoints.
the_ends = endpoints(combined)
assert len(the_ends) == len(set(the_ends))
# Property: the combined paths should have the same or fewer segments as
# the original paths.
assert num_segments(paths) >= num_segments(combined)
# Property: the combined paths should have the same total length as the
# original paths.
assert math.isclose(paths_length(paths), paths_length(combined))
# Property: there should be no collinear triples in any path.
assert not any(path.any_collinear() for path in combined)
def test_from_regular_center(self):
for i in range(3, 13):
_poly = polygon2.Polygon2.from_regular(i, 1)
foundx0 = False
foundy0 = False
for p in _poly.points:
if math.isclose(p.x, 0, abs_tol=1e-07):
foundx0 = True
if foundy0:
break
if math.isclose(p.y, 0, abs_tol=1e-07):
foundy0 = True
if foundx0:
break
helpmsg = "\ni={}\nfoundx0={}, foundy0={}, center={}\nrepr={}\n\nstr={}".format(i, foundx0, foundy0, _poly.center, repr(_poly), str(_poly))
self.assertTrue(foundx0, msg=helpmsg)
self.assertTrue(foundy0, msg=helpmsg)
def test_contains_point_regressions(self):
# the fuzzer actually caught an error. put them in here to ensure they don't
# come back. The first issue was math.isclose without abs_tol on values close
# to 0 is too strict
poly = polygon2.Polygon2([ (2, 3), (3, 5), (5, 4), (3, 2) ])
regression_tests = [ (poly.points, vector2.Vector2(4, 3), True, False, vector2.Vector2(-509.47088031477625, 57.99699262312129)) ]
for regression in regression_tests:
points = regression[0]
point = regression[1]
expected_edge = regression[2]
expected_contains = regression[3]
offset = regression[4]
new_points = []
for pt in points:
new_points.append(pt - offset)
new_poly = polygon2.Polygon2(new_points)
edge, cont = polygon2.Polygon2.contains_point(new_poly, offset, point)
help_msg = "regression failed.\n\npoints={}, point={}, offset={}, expected_edge={}, expected_contains={}, edge={}, contains={}".format(points, point, offset, expected_edge, expected_contains, edge, cont)
self.assertEqual(expected_edge, edge, msg=help_msg)
self.assertEqual(expected_contains, cont, msg=help_msg)
def are_parallel(line1, line2):
"""
Determine if the two lines are parallel.
Two lines are parallel if they have the same or opposite slopes.
:param line1: the first line
:type line1: :class:`pygorithm.geometry.line2.Line2`
:param line2: the second line
:type line2: :class:`pygorithm.geometry.line2.Line2`
:returns: if the lines are parallel
:rtype: bool
"""
if line1.vertical and line2.vertical:
return True
return math.isclose(line1.slope, line2.slope)
def contains_point(line, point):
"""
Determine if the line contains the specified point.
The point must be defined the same way as min and max.
.. tip::
It is not possible for both returned booleans to be `True`.
:param line: the line
:type line: :class:`pygorithm.geometry.axisall.AxisAlignedLine`
:param point: the point
:type point: :class:`numbers.Number`
:returns: (if the point is an edge of the line, if the point is contained by the line)
:rtype: (bool, bool)
"""
if math.isclose(line.min, point) or math.isclose(line.max, point):
return True, False
elif point < line.min or point > line.max:
return False, False
else:
return False, True
def get_request_state_from_pond_blocks(request_state, acceptability_threshold, request_blocks):
active_blocks = False
future_blocks = False
now = timezone.now()
for block in request_blocks:
start_time = dateutil.parser.parse(block['start']).replace(tzinfo=timezone.utc)
end_time = dateutil.parser.parse(block['end']).replace(tzinfo=timezone.utc)
# mark a block as complete if a % of the total exposures of all its molecules are complete
completion_percent = exposure_completion_percentage_from_pond_block(block)
if isclose(acceptability_threshold, completion_percent) or completion_percent >= acceptability_threshold:
return 'COMPLETED'
if (not block['canceled'] and not any(molecule['failed'] for molecule in block['molecules'])
and start_time < now < end_time):
active_blocks = True
if now < start_time:
future_blocks = True
if not (future_blocks or active_blocks):
return 'FAILED'
return request_state
def test_sloping_line():
''' a simple linear function '''
def line(x):
return 2 + 3*x
# I got 159.99999999999 rather than 160
# hence the need for isclose()
assert isclose(trapz(line, 2, 10), 160)
m, B = 3, 2
a, b = 0, 5
assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))
a, b = 5, 10
assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))
a, b = -10, 5
assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))
def compare_as_floats(xs, ys, error):
def f(x):
try:
y = float(x)
if not math.isfinite(y):
log.warning('not an real number found: %f', y)
return y
except ValueError:
return x
xs = list(map(f, xs.split()))
ys = list(map(f, ys.split()))
if len(xs) != len(ys):
return False
for x, y in zip(xs, ys):
if isinstance(x, float) and isinstance(y, float):
if not math.isclose(x, y, rel_tol=error, abs_tol=error):
return False
else:
if x != y:
return False
return True
def getPointsBtwnVertices(v1, v2, dx):
"""
accepts:
v1: the position of one vertex
v2: the position of the other vertex
dx: stride length
returns:
points: ordered list of points between v1 and v2 at which to take a photo
"""
points = []
v1x, v2x = v1[0], v2[0]
v1y, v2y = v1[1], v2[1]
if np.isclose(v1x, v2x):
return getPointsonVerticalLine(v1x, v1y, v2y, dx)
if v2x-v1x<0: dx = -dx
xPoints = int((v2x - v1x) / dx)
dy = (v2y - v1y) / (v2x - v1x) * dx
x, y = v1x, v1y
for pointNo in range(xPoints):
points.append((x, y))
x += dx
y += dy
return points
def test_sample_images():
variables = ['x', 'nt']
with open('sample_img/tests.csv', 'r') as csvfile:
# filename, x, y, w, h
testreader = csv.reader(csvfile, delimiter=',')
for sample in testreader:
image = cv2.imread('sample_img/' + sample[0])
# Rescale if necessary
height, width, channels = image.shape
x, img, num_targets, target_sep = find_target(image)
assert num_targets == int(sample[2])
if num_targets == 0:
x = None
continue
if x != None and sample[1] != None:
sample[1] = 2 * float(sample[1]) / width - 1
assert math.isclose(x, sample[1], abs_tol=0.1)
def test_projection(self):
x, y = sphere._py_from4326_to3857(p_minsk)
assert math.isclose(x, 3068168.9922502628, rel_tol=1e-06)
assert math.isclose(y, 7151666.629430503, rel_tol=1e-06)
x, y = _sphere._from4326_to3857(p_minsk)
assert math.isclose(x, 3068168.9922502628, rel_tol=1e-06)
assert math.isclose(y, 7151666.629430503, rel_tol=1e-06)
lon, lat = sphere._py_from3857_to4326(
sphere._py_from4326_to3857(p_minsk))
assert math.isclose(lon, p_minsk[0], rel_tol=1e-06)
assert math.isclose(lat, p_minsk[1], rel_tol=1e-06)
lon, lat = _sphere._from3857_to4326(
_sphere._from4326_to3857(p_minsk))
assert math.isclose(lon, p_minsk[0], rel_tol=1e-06)
assert math.isclose(lat, p_minsk[1], rel_tol=1e-06)
def test_projection(self):
assert (
ellipsoid._py_from4326_to3395(p_minsk) ==
(3068168.9922502623, 7117115.955611216)
)
rp_minsk = ellipsoid._py_from3395_to4326(
ellipsoid._py_from4326_to3395(p_minsk))
assert math.isclose(rp_minsk[0], p_minsk[0], rel_tol=1e-06)
assert math.isclose(rp_minsk[1], p_minsk[1], rel_tol=1e-06)
assert (
_ellipsoid._from4326_to3395(p_minsk) ==
(3068168.9922502623, 7117115.955611216)
)
rp_minsk = _ellipsoid._from3395_to4326(
_ellipsoid._from4326_to3395(p_minsk))
assert math.isclose(rp_minsk[0], p_minsk[0], rel_tol=1e-06)
assert math.isclose(rp_minsk[1], p_minsk[1], rel_tol=1e-06)
def test_large_pop_tree():
ROOT = Population(name='ROOT')
AB = Population(name='AB', father=ROOT)
A = Population(name='A', father=AB)
B = Population(name='B', father=AB)
CD = Population(name='CD', father=ROOT)
C = Population(name='C', father=CD)
D = Population(name='D', father=CD)
a = Event(time=0.0, lca_pop=A)
b = Event(time=0.0, lca_pop=B)
ab = Event(time=0.5, left=a, right=b)
c = Event(time=0.0, lca_pop=C)
d = Event(time=0.0, lca_pop=D)
cd = Event(time=0.6, left=c, right=d)
r = Event(time=1.0, left=ab, right=cd)
tau_bounds = find_tau_bounds(r)
for pop, event in ((A, a), (B, b), (C, c), (D, d), (AB, ab), (CD, cd), (ROOT, r)):
assert isclose(tau_bounds[pop], event.time)
def test_multiple_bounders():
AB = Population(name='AB')
A = Population(name='A', father=AB)
B = Population(name='B', father=AB)
a = Event(time=0.0, lca_pop=A)
b = Event(time=0.0, lca_pop=B)
c = Event(time=0.0, lca_pop=B)
d = Event(time=0.0, lca_pop=B)
ab = Event(time=0.5, left=a, right=b)
abc = Event(time=0.6, left=ab, right=c)
abcd = Event(time=0.7, left=abc, right=d)
tau_bounds = find_tau_bounds(abcd)
assert isclose(tau_bounds[AB], ab.time)
def test_bounder_bounds_multiple_pops():
ABC = Population(name='ABC')
AB = Population(name='AB', father=ABC)
C = Population(name='C', father=ABC)
A = Population(name='A', father=AB)
B = Population(name='B', father=AB)
AB.left, AB.right = A, B
ABC.left, ABC.right = AB, C
a = Event(time=0.0, lca_pop=A)
c = Event(time=0.0, lca_pop=C)
ac = Event(time=0.5, left=a, right=c)
tau_bounds = find_tau_bounds(ac)
assert isclose(tau_bounds[AB], ac.time)
assert isclose(tau_bounds[ABC], ac.time)
def test_sloping_line():
''' a simple linear function '''
def line(x):
return 2 + 3*x
# I got 159.99999999999 rather than 160
# hence the need for isclose()
assert isclose(trapz(line, 2, 10), 160)
m, B = 3, 2
a, b = 0, 5
assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))
a, b = 5, 10
assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))
a, b = -10, 5
assert isclose(trapz(line, a, b), 1/2*m*(b**2 - a**2) + B*(b-a))
def test_shrink_and_sort(frame=None):
if not frame:
frame = DATA + '/vectors/glove12-840B.h5'
vectors = load_any_embeddings(frame)
n, k = 10, 20
shrank = shrink_and_sort(vectors, n, k)
# Check the size of the frame
ok_(shrank.shape == (n, k))
# Check if the frame is l2 normalized
lengths = np.sqrt(np.sum(np.power(shrank, 2), axis='columns'))
ok_(all(isclose(length, 1.0, rel_tol=1e-04) for length in lengths))
# Check if the index is sorted
ok_(shrank.index.is_monotonic_increasing)
def test_point_distance(p1, p2, result):
assert math.isclose(Point(*p1).distance(Point(*p2)), result)
def test_line_angle(p1, p2, angle):
l = Line(Point(*p1), Point(*p2))
assert math.isclose(l.angle(), angle)
def isclose(a, b):
"""Are two floats close together, even near zero."""
return math.isclose(a, b, abs_tol=1e-8)
def has_changed(self, to_value=None):
if len(self._shift_register) > 1:
if to_value is not None:
# if we are comparing to a given value (that matches the data class)...
if to_value.__class__ != self._data_class:
return None
if self._data_class == float:
# compare with isclose, for floats
return math.isclose(self._shift_register[-1], to_value, rel_tol=1.0e-6) and self.has_changed()
else:
# compare with equality, otherwise
return (self._shift_register[-1] == to_value) and self.has_changed()
else:
# if we are just checking if the latest value changed at all
if self._data_class == float:
# compare with isclose, for floats
return not math.isclose(self._shift_register[-1], self._shift_register[-2])
else:
# compare with equality, otherwise
return (self._shift_register[-1] != self._shift_register[-2])
else:
return False
#--- Basic PID controller class
#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-
def isclose(a, b, rel_tol=1e-09, abs_tol=0):
"""
Python 2 implementation of Python 3.5 math.isclose()
https://hg.python.org/cpython/file/v3.5.2/Modules/mathmodule.c#l1993
"""
# sanity check on the inputs
if rel_tol < 0 or abs_tol < 0:
raise ValueError("tolerances must be non-negative")
# short circuit exact equality -- needed to catch two infinities of
# the same sign. And perhaps speeds things up a bit sometimes.
if a == b:
return True
# This catches the case of two infinities of opposite sign, or
# one infinity and one finite number. Two infinities of opposite
# sign would otherwise have an infinite relative tolerance.
# Two infinities of the same sign are caught by the equality check
# above.
if _isinf(a) or _isinf(b):
return False
# Cast to float to allow decimal.Decimal arguments
if not isinstance(a, float):
a = float(a)
if not isinstance(b, float):
b = float(b)
# now do the regular computation
# this is essentially the "weak" test from the Boost library
diff = _fabs(b - a)
result = ((diff <= _fabs(rel_tol * a)) or
(diff <= _fabs(rel_tol * b)) or
(diff <= abs_tol))
return result
def __eq__(self, other):
return math.isclose(self[0], other[0], abs_tol=self.abs_tol) and math.isclose(self[1], other[1], abs_tol=self.abs_tol)
def contains_point(rect, point):
"""
Determine if the rect contains the point
Distinguish between points that are on the edge of the
rect and those that are not.
.. tip::
This will never return ``True, True``
:param rect: the rect
:type rect: :class:`pygorithm.geometry.rect2.Rect2`
:param point: the point
:type point: :class:`pygorithm.geometry.vector2.Vector2`
:returns: point on edge, point inside
:rtype: bool, bool
"""
edge_x = math.isclose(rect.mincorner.x, point.x, abs_tol=1e-07) or math.isclose(rect.mincorner.x + rect.width, point.x, abs_tol=1e-07)
edge_y = math.isclose(rect.mincorner.y, point.y, abs_tol=1e-07) or math.isclose(rect.mincorner.y + rect.height, point.y, abs_tol=1e-07)
if edge_x and edge_y:
return True, False
contains = (edge_x or (point.x > rect.mincorner.x and point.x < rect.mincorner.x + rect.width)) and \
(edge_y or (point.y > rect.mincorner.y and point.y < rect.mincorner.y + rect.height))
if not contains:
return False, False
elif edge_x or edge_y:
return True, False
else:
return False, True
def contains_point(polygon, offset, point):
"""
Determine if the polygon at offset contains point.
Distinguish between points that are on the edge of the polygon and
points that are completely contained by the polygon.
.. tip::
This can never return True, True
This finds the cross product of this point and the two points comprising
every line on this polygon. If any are 0, this is an edge. Otherwise,
they must all be negative (when traversed clockwise).
:param polygon: the polygon
:type polygon: :class:`pygorithm.geometry.polygon2.Polygon2`
:param offset: the offset of the polygon
:type offset: :class:`pygorithm.geometry.vector2.Vector2` or None
:param point: the point to check
:type point: :class:`pygorithm.geometry.vector2.Vector2`
:returns: on edge, contained
:rtype: bool, bool
"""
_previous = polygon.points[0]
for i in range(1, len(polygon.points) + 1):
curr = polygon.points[i % len(polygon.points)]
vec1 = _previous + offset - point
vec2 = curr + offset - point
cross = vec1.cross(vec2)
_previous = curr
if math.isclose(cross, 0, abs_tol=1e-07):
return True, False
if cross > 0:
return False, False
return False, True
rand_moving_stationary_generator.py 文件源码
项目:pygorithm
作者: OmkarPathak
项目源码
文件源码
阅读 50
收藏 0
点赞 0
评论 0
def test_collinear(pt1, pt2, pt3):
Ax = pt1[0]
Ay = pt1[1]
Bx = pt2[0]
By = pt2[1]
Cx = pt3[0]
Cy = pt3[1]
return math.isclose(Ax * (By - Cy) + Bx * (Cy - Ay) + Cx * (Ay - By), 0, abs_tol=1e-07)
def normalize(self):
"""
Returns a new distribution with the probabilities normalized so that
their total sums to 1.
"""
if math.isclose(self.total, 1) or self.total == 0:
return self
return Distribution(*((v, p/self.total) for v, p in self), force_flatten=self.force_flatten, force_merge=self.force_merge)
def draw(self, cr, pos, text_width):
self.strip()
width = sum([box.width for box in self.boxes])
# Center lines not equal to text width.
if not math.isclose(width, text_width):
pos.x -= (text_width - width)/2
for box in self.boxes:
# We start drawing from the right edge of the text block,
# and move to the left, thus the subtraction instead of
# addition below.
pos.x -= box.width
box.draw(cr, pos)
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
"""
Determine whether two floating point numbers are close in value.
rel_tol
maximum difference for being considered "close", relative to the
magnitude of the input values
abs_tol
maximum difference for being considered "close", regardless of the
magnitude of the input values
Return True if a is close in value to b, and False otherwise.
For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances.
-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.
"""
if rel_tol < 0.0 or abs_tol < 0.0:
raise ValueError('error tolerances must be non-negative')
if a == b: # short-circuit exact equality
return True
if math.isinf(a) or math.isinf(b):
# This includes the case of two infinities of opposite sign, or
# one infinity and one finite number. Two infinities of opposite sign
# would otherwise have an infinite relative tolerance.
return False
diff = abs(b - a)
return (((diff <= abs(rel_tol * b)) and
(diff <= abs(rel_tol * a))) or
(diff <= abs_tol))