Skip to content

Commit

Permalink
PEP: Add yapf config and format geometry module
Browse files Browse the repository at this point in the history
  • Loading branch information
carterbox committed Mar 22, 2019
1 parent 6884477 commit fe3319a
Show file tree
Hide file tree
Showing 7 changed files with 152 additions and 114 deletions.
8 changes: 8 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,11 @@ cover-package=xdesign
verbosity=2
with-coverage=1
where=tests

[yapf]
based_on_style = pep8
spaces_before_comment = 2
split_before_logical_operator = true
column_limit = 80
dedent_closing_brackets = true
coalesce_brackets = True
1 change: 0 additions & 1 deletion src/xdesign/geometry/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Define geometric objects for compuational geometry operations.
.. moduleauthor:: Doga Gursoy <[email protected]>
Expand Down
35 changes: 20 additions & 15 deletions src/xdesign/geometry/algorithms.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import numpy as np

from xdesign.geometry.point import *
from math import asin, sqrt

import logging
logger = logging.getLogger(__name__)
"""Define algorithms to support intersection calculation."""

__author__ = "Daniel Ching, Doga Gursoy"
__copyright__ = "Copyright (c) 2016, UChicago Argonne, LLC."
__docformat__ = 'restructuredtext en'
__all__ = [
'clip_SH',
'halfspacecirc',
]
'clip_SH',
'halfspacecirc',
]

import logging
from math import asin, sqrt

import numpy as np

from xdesign.geometry.point import *

logger = logging.getLogger(__name__)


def halfspacecirc(d, r):
Expand Down Expand Up @@ -44,13 +47,14 @@ def halfspacecirc(d, r):
if d >= r: # The line is too far away to overlap!
return 0

f = 0.5 - d*sqrt(r**2 - d**2)/(np.pi*r**2) - asin(d/r)/np.pi
f = 0.5 - d * sqrt(r**2 - d**2) / (np.pi * r**2) - asin(d / r) / np.pi

# Returns the smaller fraction of the circle, so it can be at most 1/2.
if f < 0 or 0.5 < f:
if f < -1e-16: # f will often be less than 0 due to rounding errors
warnings.warn("halfspacecirc was out of bounds, {}".format(f),
RuntimeWarning)
warnings.warn(
"halfspacecirc was out of bounds, {}".format(f), RuntimeWarning
)
f = 0

return f
Expand Down Expand Up @@ -103,8 +107,9 @@ def clip_SH(clipEdges, polygon):

if not halfspace_has_point(clipEdge[0], clipEdge[1], S):
A, b = calc_standard(np.stack([S._x, E._x], axis=0))
new_vert = two_lines_intersect(A, b,
clipEdge[0], clipEdge[1])
new_vert = two_lines_intersect(
A, b, clipEdge[0], clipEdge[1]
)
outputList.append(Point(new_vert))

outputList.append(E)
Expand Down
148 changes: 84 additions & 64 deletions src/xdesign/geometry/area.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
import numpy as np
"""Define two dimensional geometric entities."""

__author__ = "Daniel Ching, Doga Gursoy"
__copyright__ = "Copyright (c) 2016, UChicago Argonne, LLC."
__docformat__ = 'restructuredtext en'
__all__ = [
'Curve',
'Circle',
'Polygon',
'Triangle',
'Rectangle',
'Square',
'Mesh',
]

from copy import deepcopy
import logging
import warnings

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from numbers import Number
from cached_property import cached_property
import copy
from math import sqrt, asin
from copy import deepcopy

from xdesign.geometry.entity import *
from xdesign.geometry.point import *
from xdesign.geometry.line import *
from xdesign.geometry.point import *

logger = logging.getLogger(__name__)

__author__ = "Daniel Ching, Doga Gursoy"
__copyright__ = "Copyright (c) 2016, UChicago Argonne, LLC."
__docformat__ = 'restructuredtext en'
__all__ = [
'Curve',
'Circle',
'Polygon',
'Triangle',
'Rectangle',
'Square',
'Mesh',
]


class Curve(Entity):
"""The base class for closed manifolds defined by a single equation. e.g.
Expand All @@ -37,6 +37,7 @@ class Curve(Entity):
----------
center : Point
"""

def __init__(self, center):
if not isinstance(center, Point):
raise TypeError("center must be a Point.")
Expand Down Expand Up @@ -76,10 +77,9 @@ def __init__(self, center, a, b, n):
self.n = float(n)

def __repr__(self):
return "Superellipse(center={}, a={}, b={}, n={})".format(repr(self.center),
repr(self.a),
repr(self.b),
repr(self.n))
return "Superellipse(center={}, a={}, b={}, n={})".format(
repr(self.center), repr(self.a), repr(self.b), repr(self.n)
)

@property
def list(self):
Expand All @@ -106,9 +106,9 @@ def __init__(self, center, a, b):
super(Ellipse, self).__init__(center, a, b, 2)

def __repr__(self):
return "Ellipse(center={}, a={}, b={})".format(repr(self.center),
repr(self.a),
repr(self.b))
return "Ellipse(center={}, a={}, b={})".format(
repr(self.center), repr(self.a), repr(self.b)
)

@property
def list(self):
Expand Down Expand Up @@ -147,16 +147,18 @@ def __init__(self, center, radius, sign=1):

def __repr__(self):
return "Circle(center={}, radius={}, sign={})".format(
repr(self.center), repr(self.radius), repr(self.sign))
repr(self.center), repr(self.radius), repr(self.sign)
)

def __str__(self):
"""Return the analytical equation."""
return "(x-%s)^2 + (y-%s)^2 = %s^2" % (self.center.x, self.center.y,
self.radius)
return "(x-%s)^2 + (y-%s)^2 = %s^2" % (
self.center.x, self.center.y, self.radius
)

def __eq__(self, circle):
return ((self.x, self.y, self.radius) ==
(circle.x, circle.y, circle.radius))
return ((self.x, self.y,
self.radius) == (circle.x, circle.y, circle.radius))

def __neg__(self):
copE = deepcopy(self)
Expand Down Expand Up @@ -226,8 +228,10 @@ def contains(self, other):
assert other.sign is 1
# other is within A
if isinstance(other, Circle):
return (other.center.distance(self.center)
+ other.radius < self.radius)
return (
other.center.distance(self.center) + other.radius <
self.radius
)
elif isinstance(other, Polygon):
x = _points_to_array(other.vertices)
return np.all(self.contains(x))
Expand All @@ -236,19 +240,25 @@ def contains(self, other):
if other.sign is 1:
# other is outside A and not around
if isinstance(other, Circle):
return (other.center.distance(self.center)
- other.radius > self.radius)
return (
other.center.distance(self.center) - other.radius >
self.radius
)
elif isinstance(other, Polygon):
x = _points_to_array(other.vertices)
return (np.all(self.contains(x)) and
not other.contains(-self))
return (
np.all(self.contains(x))
and not other.contains(-self)
)

else:
assert other.sign is -1
# other is around A
if isinstance(other, Circle):
return (other.center.distance(self.center)
+ self.radius < other.radius)
return (
other.center.distance(self.center) + self.radius <
other.radius
)
elif isinstance(other, Polygon):
return (-other).contains(-self)

Expand Down Expand Up @@ -292,8 +302,9 @@ def __init__(self, vertices, sign=1):
self.sign = sign

def __repr__(self):
return "Polygon(vertices={}, sign={})".format(repr(self.vertices),
repr(self.sign))
return "Polygon(vertices={}, sign={})".format(
repr(self.vertices), repr(self.sign)
)

def __str__(self):
return "{}({})".format(type(self).__name__, str(self.numpy))
Expand Down Expand Up @@ -353,8 +364,11 @@ def edges(self):
edges = []

for i in range(self.numverts):
edges.append(Segment(self.vertices[i],
self.vertices[(i+1) % self.numverts]))
edges.append(
Segment(
self.vertices[i], self.vertices[(i + 1) % self.numverts]
)
)

return edges

Expand All @@ -370,7 +384,7 @@ def area(self):
a = _points_to_array(self.vertices)
x = a[:, 0]
y = a[:, 1]
return 0.5*np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))

@cached_property
def perimeter(self):
Expand Down Expand Up @@ -402,12 +416,14 @@ def radius(self):
@cached_property
def half_space(self):
"""Returns the half space polytope respresentation of the polygon."""
assert(self.dim > 0), self.dim
assert (self.dim > 0), self.dim
A = np.ndarray((self.numverts, self.dim))
B = np.ndarray(self.numverts)

for i in range(0, self.numverts):
edge = Line(self.vertices[i], self.vertices[(i+1) % self.numverts])
edge = Line(
self.vertices[i], self.vertices[(i + 1) % self.numverts]
)
A[i, :], B[i] = edge.standard

# test for positive or negative side of line
Expand Down Expand Up @@ -496,8 +512,10 @@ def contains(self, other):
return False
elif isinstance(other, Polygon):
x = _points_to_array(other.vertices)
return (np.all(self.contains(x)) and
not other.contains(-self))
return (
np.all(self.contains(x))
and not other.contains(-self)
)

else:
assert other.sign is -1
Expand All @@ -523,9 +541,9 @@ def __init__(self, p1, p2, p3):
super(Triangle, self).__init__([p1, p2, p3])

def __repr__(self):
return "Triangle({}, {}, {})".format(self.vertices[0],
self.vertices[1],
self.vertices[2])
return "Triangle({}, {}, {})".format(
self.vertices[0], self.vertices[1], self.vertices[2]
)

@cached_property
def center(self):
Expand All @@ -538,7 +556,7 @@ def center(self):
def area(self):
A = self.vertices[0] - self.vertices[1]
B = self.vertices[0] - self.vertices[2]
return self.sign * 1/2 * np.abs(np.cross([A.x, A.y], [B.x, B.y]))
return self.sign * 1 / 2 * np.abs(np.cross([A.x, A.y], [B.x, B.y]))


class Rectangle(Polygon):
Expand All @@ -565,13 +583,16 @@ def __init__(self, center, side_lengths):
super(Rectangle, self).__init__([p1, p2, p3, p4])

def __repr__(self):
return "Rectangle({}, {})".format(repr(self.center),
repr(self.side_lengths.tolist()))
return "Rectangle({}, {})".format(
repr(self.center), repr(self.side_lengths.tolist())
)

@cached_property
def area(self):
return self.sign * (self.vertices[0].distance(self.vertices[1]) *
self.vertices[1].distance(self.vertices[2]))
return self.sign * (
self.vertices[0].distance(self.vertices[1]) *
self.vertices[1].distance(self.vertices[2])
)


class Square(Rectangle):
Expand Down Expand Up @@ -632,12 +653,9 @@ def import_triangle(self, obj):
"""Loads mesh data from a Python Triangle dict.
"""
for face in obj['triangles']:
p0 = Point(obj['vertices'][face[0], 0],
obj['vertices'][face[0], 1])
p1 = Point(obj['vertices'][face[1], 0],
obj['vertices'][face[1], 1])
p2 = Point(obj['vertices'][face[2], 0],
obj['vertices'][face[2], 1])
p0 = Point(obj['vertices'][face[0], 0], obj['vertices'][face[0], 1])
p1 = Point(obj['vertices'][face[1], 0], obj['vertices'][face[1], 1])
p2 = Point(obj['vertices'][face[2], 0], obj['vertices'][face[2], 1])
t = Triangle(p0, p1, p2)
self.append(t)

Expand Down Expand Up @@ -675,8 +693,10 @@ def append(self, t):
for v in t.vertices:
self.radius = max(self.radius, self.center.distance(v))
else:
self.radius = max(self.radius,
self.center.distance(t.center) + t.radius)
self.radius = max(
self.radius,
self.center.distance(t.center) + t.radius
)

self.faces.append(t)

Expand Down
8 changes: 4 additions & 4 deletions src/xdesign/geometry/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,17 @@
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE #
# POSSIBILITY OF SUCH DAMAGE. #
# #########################################################################

"""Define a base clase for all geometric entities."""

import logging
logger = logging.getLogger(__name__)

__author__ = "Daniel Ching, Doga Gursoy"
__copyright__ = "Copyright (c) 2016, UChicago Argonne, LLC."
__docformat__ = 'restructuredtext en'
__all__ = ['Entity']

import logging

logger = logging.getLogger(__name__)


class Entity(object):
"""Define a base class for all geometric entities.
Expand Down
Loading

0 comments on commit fe3319a

Please sign in to comment.