Skip to content

Commit

Permalink
[geom] Compatibility with Python 3.8
Browse files Browse the repository at this point in the history
  • Loading branch information
Philipp Holl committed Jan 22, 2025
1 parent 1d5cf18 commit 62ce1ee
Show file tree
Hide file tree
Showing 12 changed files with 33 additions and 29 deletions.
2 changes: 1 addition & 1 deletion phi/geom/_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ def lies_inside(self, location: Tensor) -> Tensor:
return bool_inside


def bounding_box(geometry: Geometry | Tensor, reduce=non_batch) -> Box:
def bounding_box(geometry: Union[Geometry, Tensor], reduce=non_batch) -> Box:
"""
Builds a bounding box around `geometry` or a collection of points.
Expand Down
2 changes: 1 addition & 1 deletion phi/geom/_cylinder.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ def cylinder(center: Union[Tensor, float] = None,
radius: Union[float, Tensor] = None,
depth: Union[float, Tensor] = None,
rotation: Optional[Tensor] = None,
axis: int | str | Tensor = -1,
axis: Union[int, str, Tensor] = -1,
variables=('center', 'radius', 'depth', 'rotation'),
**center_: Union[float, Tensor]) -> Cylinder:
"""
Expand Down
8 changes: 4 additions & 4 deletions phi/geom/_functions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Sequence, Union, Optional
from typing import Sequence, Union, Optional, Tuple

from phiml import math
from phiml.math import Tensor, channel, Shape, normalize, vec, sqrt, maximum, clip, vec_squared, norm, where, stack, dual, argmin, safe_div, arange, wrap, to_float, rename_dims
Expand Down Expand Up @@ -231,7 +231,7 @@ def orthogonal_vector(vector: Tensor):
raise NotImplementedError


def rotation_matrix(x: float | math.Tensor | None, matrix_dim=channel('vector'), none_to_unit=False) -> Optional[Tensor]:
def rotation_matrix(x: Union[float, math.Tensor, None], matrix_dim=channel('vector'), none_to_unit=False) -> Optional[Tensor]:
"""
Create a 2D or 3D rotation matrix from the corresponding angle(s).
Expand Down Expand Up @@ -329,7 +329,7 @@ def rotation_matrix_from_directions(source_dir: Tensor, target_dir: Tensor, vec_
raise NotImplementedError


def axis_angle_from_directions(source_dir: Tensor, target_dir: Tensor, vec_dim: str = 'vector', epsilon=None) -> tuple[Tensor, Tensor]:
def axis_angle_from_directions(source_dir: Tensor, target_dir: Tensor, vec_dim: str = 'vector', epsilon=None) -> Tuple[Tensor, Tensor]:
if source_dir.vector.size == 3:
source_dir = normalize(source_dir, vec_dim, epsilon=epsilon)
target_dir = normalize(target_dir, vec_dim, epsilon=epsilon)
Expand All @@ -340,7 +340,7 @@ def axis_angle_from_directions(source_dir: Tensor, target_dir: Tensor, vec_dim:
raise NotImplementedError


def rotation_matrix_from_axis_and_angle(axis: Tensor, angle: float | Tensor, vec_dim='vector', is_axis_normalized=False, epsilon=1e-5) -> Tensor:
def rotation_matrix_from_axis_and_angle(axis: Tensor, angle: Union[float, Tensor], vec_dim='vector', is_axis_normalized=False, epsilon=1e-5) -> Tensor:
"""
Computes a rotation matrix that rotates by `angle` around `axis`.
Expand Down
4 changes: 2 additions & 2 deletions phi/geom/_geom_functions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import warnings
from typing import Tuple, Optional
from typing import Tuple, Optional, Union

from phiml import math
from phiml.math import Tensor, stack, instance, wrap, shape
Expand All @@ -8,7 +8,7 @@
from ._geom import Geometry


def length(obj: Geometry | Tensor, epsilon=1e-5) -> Tensor:
def length(obj: Union[Geometry, Tensor], epsilon=1e-5) -> Tensor:
"""
Returns the length of a vector `Tensor` or geometric object with a length-like property.
Expand Down
2 changes: 1 addition & 1 deletion phi/geom/_geom_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def approximate_signed_distance(self, location: math.Tensor):
if self._set_op == 'intersection':
return math.max(dist, instance(self._geometries))

def approximate_fraction_inside(self, other_geometry: Geometry, balance: Tensor | Number = 0.5) -> Tensor:
def approximate_fraction_inside(self, other_geometry: Geometry, balance: Union[Tensor, float] = 0.5) -> Tensor:
if self._set_op == 'intersection':
assert isinstance(other_geometry, Geometry)
radius = other_geometry.bounding_radius()
Expand Down
2 changes: 1 addition & 1 deletion phi/geom/_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def __init__(self,
boundary: Dict[str, Dict[str, slice]],
deltas: Optional[Tensor] = None,
distances: Optional[Tensor] = None,
bounding_distance: Tensor | float | None = None):
bounding_distance: Union[Tensor, float, None] = None):
"""
Create a graph where `nodes` are connected by `edges`.
Expand Down
10 changes: 5 additions & 5 deletions phi/geom/_mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,7 +470,7 @@ def shifted(self, delta: Tensor) -> 'Mesh':
def rotated(self, angle: Union[float, Tensor]) -> 'Geometry':
raise NotImplementedError

def scaled(self, factor: float | Tensor) -> 'Geometry':
def scaled(self, factor: Union[float, Tensor]) -> 'Geometry':
pivot = self.bounds.center
vertices = scale(self.vertices, factor, pivot)
# center = scale(Point(self.center), factor, pivot).center
Expand Down Expand Up @@ -595,7 +595,7 @@ def load_stl(file: str, face_dim=instance('faces')) -> Mesh:

def mesh_from_numpy(points: Sequence[Sequence],
polygons: Sequence[Sequence],
boundaries: str | Dict[str, List[Sequence]] | None = None,
boundaries: Union[str, Dict[str, List[Sequence]], None] = None,
element_rank: int = None,
periodic: str = None,
cell_dim: Shape = instance('cells'),
Expand Down Expand Up @@ -634,9 +634,9 @@ def mesh_from_numpy(points: Sequence[Sequence],


@broadcast(dims=batch)
def mesh(vertices: Geometry | Tensor,
def mesh(vertices: Union[Geometry, Tensor],
elements: Tensor,
boundaries: str | Dict[str, List[Sequence]] | None = None,
boundaries: Union[str, Dict[str, List[Sequence]], None] = None,
element_rank: int = None,
periodic: str = None,
face_format: str = 'csc',
Expand Down Expand Up @@ -970,7 +970,7 @@ def save_tri_mesh(file: str, mesh: Mesh, **extra_data):


@broadcast
def load_tri_mesh(file: str, convert=False, load_extra=()) -> Mesh | Tuple[Mesh, ...]:
def load_tri_mesh(file: str, convert=False, load_extra=()) -> Union[Mesh, Tuple[Mesh, ...]]:
data = np.load(file, allow_pickle=bool(load_extra))
f_dim = instance(str(data['f_dim']))
vertex_dim = instance(str(data['vertex_dim']))
Expand Down
12 changes: 7 additions & 5 deletions phi/geom/_mesh_builder.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Union, Dict

import numpy as np

from phiml.math import Tensor, range_tensor, non_spatial, spatial, instance
Expand All @@ -9,8 +11,8 @@ def __init__(self, element_rank: int = None):
self.element_rank = element_rank
self.axes = None
self.v_buffer = np.empty((0, 3))
self.v_positions = dict[str, Tensor]()
self.v_indices = dict[str, Tensor]()
self.v_positions: Dict[str, Tensor] = {}
self.v_indices: Dict[str, Tensor] = {}
self.elements = []

def build_mesh(self, element_dim=instance('elements')) -> Mesh:
Expand All @@ -32,12 +34,12 @@ def vertices(self, name: str) -> Tensor:
def vertex_indices(self, name: str) -> Tensor:
return self.v_indices[name]

def new_quads(self, name: str, points: Tensor, /, flip: Tensor | bool = False):
def new_quads(self, name: str, points: Tensor, /, flip: Union[Tensor, bool] = False):
indices = self.add_vertices(name, points)
self.add_quads(indices, flip=flip)
return indices

def add_quads(self, indices2d: Tensor, /, flip: Tensor | bool = False):
def add_quads(self, indices2d: Tensor, /, flip: Union[Tensor, bool] = False):
if self.element_rank is None:
self.element_rank = 2
result = []
Expand All @@ -53,7 +55,7 @@ def add_quads(self, indices2d: Tensor, /, flip: Tensor | bool = False):
self.elements.extend(result)
return result

def add_tris(self, index0: Tensor, indices1d: Tensor, /, flip: Tensor | bool = False):
def add_tris(self, index0: Tensor, indices1d: Tensor, /, flip: Union[Tensor, bool] = False):
if self.element_rank is None:
self.element_rank = 2
result = []
Expand Down
2 changes: 1 addition & 1 deletion phi/geom/_sdf_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def downsample2x(self):


def sample_sdf(geometry: Geometry,
bounds: BaseBox | UniformGrid = None,
bounds: Union[BaseBox, UniformGrid] = None,
resolution: Shape = math.EMPTY_SHAPE,
approximate_outside=False,
rebuild: Optional[str] = None,
Expand Down
4 changes: 2 additions & 2 deletions phi/geom/_spline.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Sequence, Union
from typing import Sequence, Union, Dict

from phiml import math
from phiml.math import Tensor, spatial, dual, stack, clip, channel, to_int32, meshgrid, unstack, cpack
Expand Down Expand Up @@ -32,7 +32,7 @@ def spline_eval(order, points, uv: Tensor, get: Sequence[str] = ('position', 'ta
return [result[t] for t in get] # re-order output to match input+


def closest_param(order: Union[int, dict[str, int]], points, location: Tensor, dist_iter=3):
def closest_param(order: Union[int, Dict[str, int]], points, location: Tensor, dist_iter=3):
assert order == 1 or isinstance(order, dict) and all(v == 1 for v in order.values())
assert dist_iter > 0
idx = to_int32(math.find_closest(points, location, index_dim=channel('spline')))
Expand Down
8 changes: 4 additions & 4 deletions phi/geom/_spline_solid.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ class SplineSolid(Geometry):
"""2D spatial tensor of points"""
thickness: Tensor
"""2D spatial tensor matching vertices"""
fillet: dict[str, Tensor]
fillet: Dict[str, Tensor]
"""Roundness by vertex by boundary, such as 'u-', 'u+', 'v-', 'v+'. 1 puts a full cylinder at the edge, 0 is a sharp edge."""
order: dict[str, int]
order: Dict[str, int]
"""Spline order along each axis, e.g. {'u': 1, 'v': 2}"""

variable_attrs: tuple[str, ...] = ('points', 'thickness', 'fillet')
value_attrs: tuple[str, ...] = ()
variable_attrs: Tuple[str, ...] = ('points', 'thickness', 'fillet')
value_attrs: Tuple[str, ...] = ()

def __post_init__(self):
assert 'vector' in self.points.shape
Expand Down
6 changes: 4 additions & 2 deletions phi/geom/_transform.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from typing import Union

from phiml.math import Tensor

from phiml.math import Tensor
from ._functions import rotate_vector
from ._geom import Geometry, GeometricType


def scale(obj: GeometricType, scale: float | Tensor, pivot: Tensor = None, dim='vector') -> GeometricType:
def scale(obj: GeometricType, scale: Union[float, Tensor], pivot: Tensor = None, dim='vector') -> GeometricType:
"""
Scale a `Geometry` or vector `Tensor` about a pivot point.
Expand All @@ -32,7 +34,7 @@ def scale(obj: GeometricType, scale: float | Tensor, pivot: Tensor = None, dim='
raise ValueError(obj)


def rotate(obj: GeometricType, rot: float | Tensor | None, invert=False, pivot: Tensor | str = 'bounds') -> GeometricType:
def rotate(obj: GeometricType, rot: Union[float, Tensor, None], invert=False, pivot: Union[Tensor, str] = 'bounds') -> GeometricType:
"""
Rotate a vector or `Geometry` about the `pivot`.
Expand Down

0 comments on commit 62ce1ee

Please sign in to comment.