Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement a more robust rounding algorithm (no magic number) #157

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 8 additions & 10 deletions phidl/device_layout.py
Expand Up @@ -36,6 +36,7 @@


import hashlib
import math
import warnings
from copy import deepcopy as _deepcopy

Expand Down Expand Up @@ -1856,20 +1857,11 @@ def hash_geometry(self, precision=1e-4):
layers = np.array(list(polygons_by_spec.keys()))
sorted_layers = layers[np.lexsort((layers[:, 0], layers[:, 1]))]

# A random offset which fixes common rounding errors intrinsic
# to floating point math. Example: with a precision of 0.1, the
# floating points 7.049999 and 7.050001 round to different values
# (7.0 and 7.1), but offset values (7.220485 and 7.220487) don't
magic_offset = 0.17048614

final_hash = hashlib.sha1()
for layer in sorted_layers:
layer_hash = hashlib.sha1(layer.astype(np.int64)).digest()
polygons = polygons_by_spec[tuple(layer)]
polygons = [
np.ascontiguousarray((p / precision) + magic_offset, dtype=np.int64)
for p in polygons
]
polygons = [_rnd(p, precision) for p in polygons]
polygon_hashes = np.sort([hashlib.sha1(p).digest() for p in polygons])
final_hash.update(layer_hash)
for ph in polygon_hashes:
Expand All @@ -1878,6 +1870,12 @@ def hash_geometry(self, precision=1e-4):
return final_hash.hexdigest()


def _rnd(arr, precision=1e-4):
arr = np.ascontiguousarray(arr)
ndigits = round(-math.log10(precision))
return np.ascontiguousarray(arr.round(ndigits) / precision, dtype=np.int64)


class DeviceReference(gdspy.CellReference, _GeometryHelper):
"""Simple reference to an existing Device.

Expand Down