tum-pbs/PhiFlow

Custom Geometry class for Polygon

Opened this issue · 2 comments

I'm trying to write a custom Geometry class for Polygon that would convert a shapely polygon to a geometry for phi flow, but I am getting a bit stuck on what methods and properties need to be implemented, my class is below:

from phi.jax.flow import *

import shapely

class Polygon(geom.Geometry):
    def __init__(self, base_poly: shapely.Polygon):

        self.base_poly = base_poly
        self.space = 'x,y'

    @property
    def shape(self):
        pointlist = list(self.base_poly.exterior.coords)
        return math.shape(pointlist)
   
    @property
    def center(self):
        p = self.base_poly.centroid
        # xs, ys = zip(*self.pointlist)
        return math.tensor([p.x, p.y])
   
    @property
    def size(self):
        return self.base_poly.area
   
    @property
    def half_size(self):
        return self.size * 0.5
   
    def bounding_half_extent(self):
        bnds = self.base_poly.bounds
        x_half_distance = (bnds[2] - bnds[0])/2
        y_half_distance = (bnds[3] - bnds[1])/2
        return math.tensor([x_half_distance, y_half_distance])

Now when I try to plot a group of polygons I get the following error:

File "/Users/will/miniconda3/envs/grow/lib/python3.9/site-packages/phi/vis/_vis.py", line 385, in
subplots = {pos: _space(*fields, ignore_dims=animate, log_dims=log_dims, errs=[err[i] for i in indices[pos]]) for pos, fields in positioning.items()}
File "/Users/will/miniconda3/envs/grow/lib/python3.9/site-packages/phi/vis/_vis.py", line 498, in _space
for dim in get_default_limits(f, None, log_dims, e).vector.item_names:
File "/Users/will/miniconda3/envs/grow/lib/python3.9/site-packages/phi/vis/_vis_base.py", line 538, in get_default_limits
center = f.center
File "/Users/will/miniconda3/envs/grow/lib/python3.9/site-packages/phi/field/_field.py", line 133, in center
return slice_off_constant_faces(self._geometry.center, self._geometry.boundary_elements, self.extrapolation)
File "/Users/will/miniconda3/envs/grow/lib/python3.9/site-packages/phi/geom/_geom.py", line 99, in boundary_elements
raise NotImplementedError(self.class)
NotImplementedError: <class 'main.Polygon'>

Any help is greatly appreciated!

Hey, that's a great idea! We might integrate this with the Mesh class from Φ-Flow which allows for cells (polygons) with arbitrarily many points.

Here is some example code to create a 2D triangle:

from phi.flow import *

points = [(0, 0), (1, 0), (0, 1)]
polygons = [(0, 1, 2)]
boundaries = {'outer': [(0, 1), (1, 2), (2, 0)]}
mesh = geom.mesh_from_numpy(points, polygons, boundaries)
show(mesh)

Having a simple interface with shapely would be neat. What functions specifically would you need?

Honestly just being able to pass a polygon to generate a geometry for use in phiflow would be fantastic, let me try to use mesh_from_numpy as you've shown above and see if that does the trick.