Migrated from GitHub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +24 -0
- data/PDE2D/BoundaryShape/__init__.py +8 -0
- data/PDE2D/BoundaryShape/bezierquadratic.py +613 -0
- data/PDE2D/BoundaryShape/boundary_shape.py +108 -0
- data/PDE2D/BoundaryShape/boundarywithdirichlets.py +290 -0
- data/PDE2D/BoundaryShape/circle.py +463 -0
- data/PDE2D/BoundaryShape/circlewithelectrodes.py +320 -0
- data/PDE2D/BoundaryShape/interaction.py +186 -0
- data/PDE2D/BoundaryShape/sdf_grid.py +491 -0
- data/PDE2D/BoundaryShape/sdf_utils.py +322 -0
- data/PDE2D/BoundaryShape/shape_utils.py +248 -0
- data/PDE2D/Coefficient/__init__.py +7 -0
- data/PDE2D/Coefficient/coefficient.py +41 -0
- data/PDE2D/Coefficient/coefficient_utils.py +52 -0
- data/PDE2D/Coefficient/concentric_disk_map.py +39 -0
- data/PDE2D/Coefficient/constant.py +51 -0
- data/PDE2D/Coefficient/disk_texture.py +132 -0
- data/PDE2D/Coefficient/elliptic_disk_map.py +64 -0
- data/PDE2D/Coefficient/function.py +75 -0
- data/PDE2D/Coefficient/gaussian.py +104 -0
- data/PDE2D/Coefficient/texture.py +149 -0
- data/PDE2D/GreenModels/green_2d_12.model +3 -0
- data/PDE2D/GreenModels/green_2d_8.model +3 -0
- data/PDE2D/GreenModels/green_3d_12.model +3 -0
- data/PDE2D/GreenModels/green_3d_8.model +3 -0
- data/PDE2D/GreenModels/green_grad_2d_12.model +3 -0
- data/PDE2D/GreenModels/green_grad_2d_8.model +3 -0
- data/PDE2D/GreenModels/green_grad_3d_12.model +3 -0
- data/PDE2D/GreenModels/green_grad_3d_8.model +3 -0
- data/PDE2D/Sampling/__init__.py +5 -0
- data/PDE2D/Sampling/green.py +41 -0
- data/PDE2D/Sampling/green_analytic.py +207 -0
- data/PDE2D/Sampling/green_polynomial.py +219 -0
- data/PDE2D/Sampling/sampling_wos.py +168 -0
- data/PDE2D/Sampling/special.py +346 -0
- data/PDE2D/Solver/__init__.py +7 -0
- data/PDE2D/Solver/constant/wos_constant.py +240 -0
- data/PDE2D/Solver/constant/wos_constant_rejection.py +116 -0
- data/PDE2D/Solver/constant/wost_constant.py +190 -0
- data/PDE2D/Solver/data_holder.py +643 -0
- data/PDE2D/Solver/variable/wos_variable.py +736 -0
- data/PDE2D/Solver/variable/wos_variable_rejection.py +153 -0
- data/PDE2D/Solver/variable/wost_variable.py +232 -0
- data/PDE2D/__init__.py +49 -0
- data/PDE2D/utils/__init__.py +7 -0
- data/PDE2D/utils/animation.py +127 -0
- data/PDE2D/utils/common.py +173 -0
- data/PDE2D/utils/helpers.py +237 -0
- data/PDE2D/utils/imageUtils.py +123 -0
- data/PDE2D/utils/optimization.py +63 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,27 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
data/eit-data/matlab-code/data/mesh.mat filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
data/figures/diff_majorant/diff_majorant_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
data/figures/fd-sdf/fd-sdf_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 64 |
+
data/figures/fd-sphere/fd-sphere_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 65 |
+
data/figures/fd_2D/fd_2D_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 66 |
+
data/figures/fd_3D/fd_3D_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 67 |
+
data/figures/green/green_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 68 |
+
data/figures/normal-der/normal-der_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 69 |
+
data/figures/opt-discrete-circle/opt-discrete-circle.pdf filter=lfs diff=lfs merge=lfs -text
|
| 70 |
+
data/figures/opt-discrete-circle/opt-discrete-circle_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 71 |
+
data/figures/opt-discrete-sdf/opt-discrete-sdf.pdf filter=lfs diff=lfs merge=lfs -text
|
| 72 |
+
data/figures/opt-discrete-sdf/opt-discrete-sdf_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 73 |
+
data/figures/opt-discrete-sphere-real/opt-discrete-sphere-real.pdf filter=lfs diff=lfs merge=lfs -text
|
| 74 |
+
data/figures/opt-discrete-sphere-real/opt-discrete-sphere-real_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 75 |
+
data/figures/opt_coeff_3D/opt_coeff_3D.pdf filter=lfs diff=lfs merge=lfs -text
|
| 76 |
+
data/figures/opt_coeff_3D/opt_coeff_3D_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 77 |
+
data/figures/path_length/path_length_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 78 |
+
data/figures/radius_decrease/radius_decrease_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 79 |
+
data/figures/sdf-field/sdf-field_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 80 |
+
data/figures/sdf-field-zoomed/sdf-field-zoomed_uc.pdf filter=lfs diff=lfs merge=lfs -text
|
| 81 |
+
data/notebooks-2D/solvers/wos/variable/accel/cond.pdf filter=lfs diff=lfs merge=lfs -text
|
| 82 |
+
data/notebooks-2D/solvers/wos/variable/accel/sampling.pdf filter=lfs diff=lfs merge=lfs -text
|
| 83 |
+
data/notebooks-3D/visualization/fd_3D.pdf filter=lfs diff=lfs merge=lfs -text
|
| 84 |
+
data/notebooks-3D/visualization/opt_coeff_3D.pdf filter=lfs diff=lfs merge=lfs -text
|
data/PDE2D/BoundaryShape/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .boundary_shape import *
|
| 2 |
+
from .circle import CircleShape
|
| 3 |
+
from .boundarywithdirichlets import BoundaryWithDirichlets
|
| 4 |
+
from .circlewithelectrodes import CircleWithElectrodes
|
| 5 |
+
from .bezierquadratic import QuadraticBezierShape
|
| 6 |
+
from .sdf_grid import SDFGrid
|
| 7 |
+
from .sdf_utils import *
|
| 8 |
+
from .shape_utils import load_bunny, load_boundary_data
|
data/PDE2D/BoundaryShape/bezierquadratic.py
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import mitsuba as mi
|
| 2 |
+
from mitsuba import Point2f, Bool, Float
|
| 3 |
+
from PDE2D.BoundaryShape.interaction import BoundaryInfo
|
| 4 |
+
from .boundary_shape import *
|
| 5 |
+
from ..utils.helpers import *
|
| 6 |
+
from ..utils.sketch import *
|
| 7 |
+
from .interaction import *
|
| 8 |
+
from ..Coefficient import *
|
| 9 |
+
from matplotlib.patches import PathPatch
|
| 10 |
+
from matplotlib.path import Path as mpath
|
| 11 |
+
|
| 12 |
+
class QuadraticBezierShape(Shape):
|
| 13 |
+
''' Defines the quadratic bezier curve. The neumann boundary part needs to be convex
|
| 14 |
+
otherwise you will get incorrect results. '''
|
| 15 |
+
def __init__(self, vertex_positions : np.array, vertex_normals : np.array = None,
|
| 16 |
+
dirichlet_map: np.array = None,
|
| 17 |
+
vertex_dirichlet_vals : list[Float] = None, vertex_neumann_vals : np.array = None,
|
| 18 |
+
dirichlet: list[Coefficient] = None,
|
| 19 |
+
neumann: list[Coefficient] = None,
|
| 20 |
+
epsilon=1e-4, name = "boundary", normal_derivative_dist = 0.01,
|
| 21 |
+
inside = True, newton_steps = 5, n_segment = 50):
|
| 22 |
+
super().__init__(np.all(dirichlet_map), single_closed_shape=True, epsilon=epsilon,
|
| 23 |
+
inside = inside, derivative_dist=normal_derivative_dist)
|
| 24 |
+
self.epsilon_neumann = 1e-5
|
| 25 |
+
self.name = name
|
| 26 |
+
|
| 27 |
+
self.v_p = Point2f(vertex_positions)
|
| 28 |
+
self.npoints = dr.width(self.v_p)
|
| 29 |
+
|
| 30 |
+
if vertex_normals is None:
|
| 31 |
+
indices = dr.arange(UInt32, self.npoints)
|
| 32 |
+
p1 = dr.gather(Point2f, self.v_p, (indices-1) % self.npoints)
|
| 33 |
+
p = dr.gather(Point2f, self.v_p, (indices) % self.npoints)
|
| 34 |
+
p2 = dr.gather(Point2f, self.v_p, (indices+1) % self.npoints)
|
| 35 |
+
vec1 = p2-p
|
| 36 |
+
vec2 = p1-p
|
| 37 |
+
self.v_n = -dr.normalize(vec1 + vec2)
|
| 38 |
+
else:
|
| 39 |
+
assert len(vertex_positions) == len(vertex_normals)
|
| 40 |
+
self.v_n = Point2f(vertex_normals)
|
| 41 |
+
|
| 42 |
+
dr.make_opaque(self.v_p)
|
| 43 |
+
dr.make_opaque(self.v_n)
|
| 44 |
+
|
| 45 |
+
#self.bbox = [[np.min(vertex_positions[0]), np.min(vertex_positions[1])],
|
| 46 |
+
# [np.max(vertex_positions[0]), np.max(vertex_positions[1])]]
|
| 47 |
+
self.bbox = [[-1, -1],[1,1]]
|
| 48 |
+
self.bbox_center = Point2f(float(self.bbox[0][0] + self.bbox[1][0]) / 2, float(self.bbox[0][1] + self.bbox[1][1]) / 2)
|
| 49 |
+
dr.make_opaque(self.bbox_center)
|
| 50 |
+
|
| 51 |
+
if dirichlet_map is None:
|
| 52 |
+
self.dirichlet_map = dr.ones(Bool, self.npoints)
|
| 53 |
+
else:
|
| 54 |
+
self.dirichlet_map = Bool(dirichlet_map)
|
| 55 |
+
dr.make_opaque(self.dirichlet_map)
|
| 56 |
+
|
| 57 |
+
self.is_full_dirichlet = dr.all(self.dirichlet_map)
|
| 58 |
+
self.is_full_neumann = dr.all(~self.dirichlet_map)
|
| 59 |
+
self.newton_steps = newton_steps
|
| 60 |
+
self.n_segment = n_segment
|
| 61 |
+
self.NEE = NEE.BruteForce
|
| 62 |
+
self.inside = True
|
| 63 |
+
|
| 64 |
+
# Number of segments
|
| 65 |
+
self.n_dirichlet = np.sum(dirichlet_map == True)
|
| 66 |
+
self.n_neumann = np.sum(dirichlet_map == False)
|
| 67 |
+
|
| 68 |
+
if not self.is_full_dirichlet:
|
| 69 |
+
if (neumann is None) and (vertex_neumann_vals is None):
|
| 70 |
+
raise Exception("Please specify either a function or vertex neumann values.")
|
| 71 |
+
elif(neumann is None):
|
| 72 |
+
self.num_conf_n = len(vertex_neumann_vals)
|
| 73 |
+
self.v_neumann = dr.zeros(ArrayXf, shape = (self.num_conf_n, self.npoints))
|
| 74 |
+
for i in range(self.num_conf_n):
|
| 75 |
+
assert len(vertex_neumann_vals[i]) == self.npoints
|
| 76 |
+
self.v_neumann[i] = Float(vertex_neumann_vals[i])
|
| 77 |
+
self.neumann = None
|
| 78 |
+
dr.make_opaque(self.v_neumann)
|
| 79 |
+
elif vertex_neumann_vals is None:
|
| 80 |
+
self.num_conf_n = len(neumann)
|
| 81 |
+
self.neumann = neumann
|
| 82 |
+
self.v_neumann = None
|
| 83 |
+
else:
|
| 84 |
+
raise Exception("Please only specify either a function, or vertex neumann vals, not both.")
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if not self.is_full_neumann:
|
| 88 |
+
if (dirichlet is None) and (vertex_dirichlet_vals is None):
|
| 89 |
+
raise Exception("Please specify either a function or vertex dirichlet values.")
|
| 90 |
+
elif(dirichlet is None):
|
| 91 |
+
self.num_conf_d = len(vertex_dirichlet_vals)
|
| 92 |
+
self.v_dirichlet = dr.zeros(ArrayXf, shape = (self.num_conf_d, self.npoints))
|
| 93 |
+
for i in range(self.num_conf_n):
|
| 94 |
+
assert len(vertex_dirichlet_vals[i]) == self.npoints
|
| 95 |
+
self.v_dirichlet[i] = Float(vertex_dirichlet_vals[i])
|
| 96 |
+
self.dirichlet = None
|
| 97 |
+
dr.make_opaque(self.v_dirichlet)
|
| 98 |
+
elif vertex_dirichlet_vals is None:
|
| 99 |
+
self.num_conf_d = len(dirichlet)
|
| 100 |
+
self.dirichlet = dirichlet
|
| 101 |
+
self.v_dirichlet = None
|
| 102 |
+
else:
|
| 103 |
+
raise Exception("Please only specify either a function, or vertex dirichlet vals, not both.")
|
| 104 |
+
|
| 105 |
+
if (not self.is_full_dirichlet) and (not self.is_full_neumann):
|
| 106 |
+
assert (self.num_conf_n == self.num_conf_d) or (self.num_conf_n == 1) or (self.num_conf_d == 1)
|
| 107 |
+
|
| 108 |
+
if self.is_full_dirichlet:
|
| 109 |
+
self.num_conf = self.num_conf_d
|
| 110 |
+
elif self.is_full_neumann:
|
| 111 |
+
self.num_conf = self.num_conf_n
|
| 112 |
+
else:
|
| 113 |
+
self.num_conf = max(self.num_conf_d, self.num_conf_n)
|
| 114 |
+
self.max_distance = 10
|
| 115 |
+
self.hasNEE = False
|
| 116 |
+
self.measureCurrent = False
|
| 117 |
+
|
| 118 |
+
# Find the control points of the curve using the normals.
|
| 119 |
+
self.c_p = dr.zeros(Point2f, self.npoints)
|
| 120 |
+
for i in range(self.npoints):
|
| 121 |
+
p1 = dr.gather(Point2f, self.v_p, i)
|
| 122 |
+
p2 = dr.gather(Point2f, self.v_p, (i+1) % self.npoints)
|
| 123 |
+
n1 = dr.gather(Point2f, self.v_n, i)
|
| 124 |
+
n2 = dr.gather(Point2f, self.v_n, (i+1) % self.npoints)
|
| 125 |
+
t = (n2[1] * (p2[1]-p1[1]) + n2[0] * (p2[0] - p1[0])) / (n2[1]*n1[0] - n1[1]*n2[0])
|
| 126 |
+
c_p = Point2f(-n1[1] * t + p1[0], n1[0] * t + p1[1])
|
| 127 |
+
dr.scatter(self.c_p, c_p, i)
|
| 128 |
+
|
| 129 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 130 |
+
pass
|
| 131 |
+
|
| 132 |
+
def update(self, optimizer):
|
| 133 |
+
pass
|
| 134 |
+
|
| 135 |
+
def zero_grad(self):
|
| 136 |
+
pass
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def inside_closed_surface(self, points : Point2f, L : Float, conf_numbers : list[UInt32] = None):
|
| 140 |
+
return self.inside_closed_surface_mask(points), L
|
| 141 |
+
|
| 142 |
+
@dr.syntax
|
| 143 |
+
def inside_closed_surface_mask(self, points : Point2f):
|
| 144 |
+
dist_min, bpoint, boundary_normal, k_min, t_min = self.get_closest_dist(points)
|
| 145 |
+
bdir = dr.normalize(bpoint - points)
|
| 146 |
+
threshold = dr.maximum(self.epsilon, 100 * dr.epsilon(Float))
|
| 147 |
+
return (dist_min > threshold) & (dr.dot(boundary_normal, bdir) < 0)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def get_interpolation_points(self, n) -> tuple[Point2f, Point2f, Point2f]:
|
| 152 |
+
p1 = dr.gather(Point2f, self.v_p, n)
|
| 153 |
+
p2 = dr.gather(Point2f, self.v_p, (n+1) % self.npoints)
|
| 154 |
+
c = dr.gather(Point2f, self.c_p, n)
|
| 155 |
+
return p1, p2, c
|
| 156 |
+
|
| 157 |
+
def get_normals(self, n)-> Point2f:
|
| 158 |
+
return dr.gather(Point2f, self.v_n, n)
|
| 159 |
+
|
| 160 |
+
def interpolate(self, p1 : Point2f, p2 : Point2f, c : Point2f, t : Float) -> Point2f:
|
| 161 |
+
p1c = dr.lerp(p1, c, t)
|
| 162 |
+
p2c = dr.lerp(c, p2, t)
|
| 163 |
+
return dr.lerp(p1c, p2c, t)
|
| 164 |
+
|
| 165 |
+
def interpolate_derivative(self, p1: Point2f, p2 : Point2f, c : Point2f, t: Float) -> Point2f:
|
| 166 |
+
"Compute derivative with respect to t."
|
| 167 |
+
return -2 * (1 - t) * p1 + 2 * c - 4*c*t + 2 * p2 * t
|
| 168 |
+
|
| 169 |
+
def interpolate_derivative2(self, p1 : Point2f, p2 : Point2f, c:Point2f, t:Float) -> Point2f:
|
| 170 |
+
return 2 * p1 + 2 * p2 - 4 * c
|
| 171 |
+
|
| 172 |
+
def get_distance2(self, p : Point2f, p1 : Point2f, p2 : Point2f, c : Point2f, t : Float) -> tuple[Float, Float]:
|
| 173 |
+
"Compute the distance squared to a given t and derivative and 2nd derivative of it."
|
| 174 |
+
p_t = self.interpolate(p1, p2, c, t)
|
| 175 |
+
p_t_der = self.interpolate_derivative(p1, p2, c, t)
|
| 176 |
+
p_t_der2 = self.interpolate_derivative2(p1, p2, c, t)
|
| 177 |
+
p_diff = p - p_t
|
| 178 |
+
dist2 = dr.squared_norm(p_diff)
|
| 179 |
+
dist2_der = -2 * p_diff * p_t_der
|
| 180 |
+
dist2_der = dist2_der[0] + dist2_der[1]
|
| 181 |
+
dist2_der2 = -2 * p_diff * p_t_der2 + 2 * dr.square(p_t_der)
|
| 182 |
+
dist2_der2 = dist2_der2[0] + dist2_der2[1]
|
| 183 |
+
return dist2, dist2_der, dist2_der2
|
| 184 |
+
|
| 185 |
+
def min_segment(self, p : Point2f, p1 : Point2f, p2 : Point2f, c : Point2f, i_segment : UInt32, n_segment : UInt32) -> Float:
|
| 186 |
+
t1 = Float(i_segment) / n_segment
|
| 187 |
+
t2 = Float(i_segment + 1) / n_segment
|
| 188 |
+
|
| 189 |
+
pl1 = self.interpolate(p1, p2, c, t1)
|
| 190 |
+
pl2 = self.interpolate(p1, p2, c, t2)
|
| 191 |
+
vec_edge = pl2 - pl1
|
| 192 |
+
t = dr.clamp(dr.dot((p - pl1), vec_edge) / dr.squared_norm(vec_edge), 0, 1)
|
| 193 |
+
min_point = dr.lerp(pl1, pl2, t)
|
| 194 |
+
return dr.norm(min_point - p), t / n_segment + t1
|
| 195 |
+
|
| 196 |
+
@dr.syntax
|
| 197 |
+
def get_closest_dist_polyline_k(self, p : Point2f, k : UInt32):
|
| 198 |
+
p1, p2, c = self.get_interpolation_points(k)
|
| 199 |
+
# First find the intersection point if it was linearly interpolated.
|
| 200 |
+
i = UInt32(0)
|
| 201 |
+
dist_min = Float(dr.inf)
|
| 202 |
+
t = Float(1)
|
| 203 |
+
i_selected = UInt32(0)
|
| 204 |
+
while i < self.n_segment:
|
| 205 |
+
min, t_ = self.min_segment(p, p1, p2, c, i, self.n_segment)
|
| 206 |
+
if min < dist_min:
|
| 207 |
+
dist_min = min
|
| 208 |
+
t = t_
|
| 209 |
+
i_selected = UInt32(i)
|
| 210 |
+
i += 1
|
| 211 |
+
return dist_min, t, i_selected
|
| 212 |
+
|
| 213 |
+
@dr.syntax
|
| 214 |
+
def get_closest_dist_polyline(self, p : Point2f):
|
| 215 |
+
i = UInt32(0)
|
| 216 |
+
dist_min = Float(dr.inf)
|
| 217 |
+
n_min = UInt32(0)
|
| 218 |
+
t_min = Float(dr.inf)
|
| 219 |
+
|
| 220 |
+
while i < self.npoints:
|
| 221 |
+
dist, t, _ = self.get_closest_dist_polyline_k(p, i)
|
| 222 |
+
if dist < dist_min:
|
| 223 |
+
n_min = i
|
| 224 |
+
dist_min = dist
|
| 225 |
+
t_min = t
|
| 226 |
+
i+=1
|
| 227 |
+
return dist_min, n_min, t_min
|
| 228 |
+
|
| 229 |
+
@dr.syntax
|
| 230 |
+
def get_closest_dist_k(self, p : Point2f, k : UInt32):
|
| 231 |
+
dist_min, t_min, i_min = self.get_closest_dist_polyline_k(p, k)
|
| 232 |
+
p1, p2, c = self.get_interpolation_points(k)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
a1, a2 = Float(i_min) / self.n_segment, Float(i_min + 1) / self.n_segment
|
| 236 |
+
# Start to apply Newton's algorithm to set the derivative to zero.
|
| 237 |
+
i = UInt32(0)
|
| 238 |
+
dist2 = Float(dr.inf)
|
| 239 |
+
while i < self.newton_steps:
|
| 240 |
+
dist2, val, deriv = self.get_distance2(p, p1, p2, c, t_min)
|
| 241 |
+
dist_min = dr.sqrt(dist2)
|
| 242 |
+
t_min = t_min - val / deriv
|
| 243 |
+
|
| 244 |
+
# Newton-Bisection: potentially reject the Newton step
|
| 245 |
+
bad_step = ~((t_min >= a1) & (t_min <= a2))
|
| 246 |
+
t_min = dr.select(bad_step, (a1 + a2) / 2, t_min)
|
| 247 |
+
|
| 248 |
+
# Update bracketing interval
|
| 249 |
+
is_neg = self.get_distance2(p, p1, p2, c, t_min)[1] < 0
|
| 250 |
+
a1 = dr.select(is_neg, t_min, a1)
|
| 251 |
+
a2 = dr.select(is_neg, a2, t_min)
|
| 252 |
+
|
| 253 |
+
t_min = dr.clamp(t_min, 0, 1)
|
| 254 |
+
i += 1
|
| 255 |
+
bpoint = self.interpolate(p1, p2, c, t_min)
|
| 256 |
+
|
| 257 |
+
boundary_normal = self.interpolate_derivative(p1, p2, c, t_min)
|
| 258 |
+
boundary_normal = dr.normalize(Point2f(-boundary_normal[1], boundary_normal[0]))
|
| 259 |
+
|
| 260 |
+
aprox_n1 = self.get_normals(k)
|
| 261 |
+
aprox_n2 = self.get_normals((k + 1) % self.npoints)
|
| 262 |
+
aprox_n = dr.lerp(aprox_n1, aprox_n2, t_min)
|
| 263 |
+
if dr.dot(aprox_n, boundary_normal) < 0:
|
| 264 |
+
boundary_normal = -boundary_normal
|
| 265 |
+
|
| 266 |
+
if dr.hint(self.inside, mode = "scalar"):
|
| 267 |
+
boundary_normal = -boundary_normal
|
| 268 |
+
|
| 269 |
+
return dist_min, bpoint, boundary_normal, t_min
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
@dr.syntax
|
| 273 |
+
def get_closest_dist(self, p : Point2f):
|
| 274 |
+
# First get the closest point if it was linearly interpolated and find t.
|
| 275 |
+
dist_min, k_min, t_min = self.get_closest_dist_polyline(p)
|
| 276 |
+
p1, p2, c = self.get_interpolation_points(k_min)
|
| 277 |
+
|
| 278 |
+
# Start to apply Newton's algorithm to set the derivative to zero.
|
| 279 |
+
i = UInt32(0)
|
| 280 |
+
dist2 = Float(dr.inf)
|
| 281 |
+
while i < self.newton_steps:
|
| 282 |
+
dist2, val, deriv = self.get_distance2(p, p1, p2, c, t_min)
|
| 283 |
+
dist_min = dr.sqrt(dist2)
|
| 284 |
+
t_min = t_min - val / deriv
|
| 285 |
+
t_min = dr.clamp(t_min, 0, 1)
|
| 286 |
+
# if t is smaller than 0 or greater than one, it means we changed the segment.
|
| 287 |
+
if t_min<0:
|
| 288 |
+
k_min = (k_min-1) % self.npoints
|
| 289 |
+
t_min = Float(1)
|
| 290 |
+
p1, p2, c = self.get_interpolation_points(k_min)
|
| 291 |
+
elif t_min>1:
|
| 292 |
+
k_min = (k_min+1) % self.npoints
|
| 293 |
+
t_min = Float(0)
|
| 294 |
+
p1, p2, c = self.get_interpolation_points(k_min)
|
| 295 |
+
i += 1
|
| 296 |
+
bpoint = self.interpolate(p1, p2, c, t_min)
|
| 297 |
+
boundary_normal = self.interpolate_derivative(p1, p2, c, t_min)
|
| 298 |
+
boundary_normal = dr.normalize(Point2f(-boundary_normal[1], boundary_normal[0]))
|
| 299 |
+
|
| 300 |
+
aprox_n1 = self.get_normals(k_min)
|
| 301 |
+
aprox_n2 = self.get_normals((k_min + 1) % self.npoints)
|
| 302 |
+
aprox_n = dr.lerp(aprox_n1, aprox_n2, t_min)
|
| 303 |
+
if dr.dot(aprox_n, boundary_normal) < 0:
|
| 304 |
+
boundary_normal = -boundary_normal
|
| 305 |
+
|
| 306 |
+
if dr.hint(self.inside, mode = "scalar"):
|
| 307 |
+
boundary_normal = -boundary_normal
|
| 308 |
+
return dist_min, bpoint, boundary_normal, k_min, t_min
|
| 309 |
+
|
| 310 |
+
@dr.syntax
|
| 311 |
+
def boundary_interaction(self, points: Point2f, radius_fnc: callable = None,
|
| 312 |
+
max_radius=Float(dr.inf) , star_generation=True,
|
| 313 |
+
conf_numbers : list[UInt32] = [UInt32(0)]) -> BoundaryInfo:
|
| 314 |
+
if dr.hint(self.is_full_dirichlet, mode = "scalar"):
|
| 315 |
+
closest_dist, closest_bpoint, closest_bnormal, k_all, t_min_all = self.get_closest_dist(points)
|
| 316 |
+
k_dirichlet, t_min_dirichlet = Float(k_all), Float(t_min_all)
|
| 317 |
+
closest_bpoint_dirichlet = closest_bpoint
|
| 318 |
+
closest_dirichlet = closest_dist
|
| 319 |
+
is_dirichlet = Bool(True)
|
| 320 |
+
is_neumann = Bool(False)
|
| 321 |
+
elif dr.hint(self.is_full_neumann, mode = "scalar"):
|
| 322 |
+
closest_dist, closest_bpoint, closest_bnormal, k_all, t_min_all = self.get_closest_dist(points)
|
| 323 |
+
closest_dirichlet = Point2f(dr.inf)
|
| 324 |
+
closest_bpoint_dirichlet = Point2f(dr.nan)
|
| 325 |
+
is_dirichlet = Bool(False)
|
| 326 |
+
is_neumann = Bool(True)
|
| 327 |
+
else:
|
| 328 |
+
is_dirichlet = Bool(True)
|
| 329 |
+
i = UInt32(0)
|
| 330 |
+
k_dirichlet = UInt32(0)
|
| 331 |
+
k_all = UInt32(0)
|
| 332 |
+
closest_dist = Float(dr.inf)
|
| 333 |
+
closest_dirichlet = Float(dr.inf)
|
| 334 |
+
closest_bpoint = Point2f(dr.nan)
|
| 335 |
+
closest_bpoint_dirichlet = Point2f(dr.nan)
|
| 336 |
+
closest_bnormal = Point2f(dr.nan)
|
| 337 |
+
t_min_dirichlet = Float(dr.inf)
|
| 338 |
+
t_min_all = Float(dr.inf)
|
| 339 |
+
while i < self.npoints:
|
| 340 |
+
d, bpoint, bnormal, t = self.get_closest_dist_k(points, i)
|
| 341 |
+
if d<closest_dist:
|
| 342 |
+
closest_dist = d
|
| 343 |
+
closest_bpoint = bpoint
|
| 344 |
+
closest_bnormal = bnormal
|
| 345 |
+
k_all = i
|
| 346 |
+
t_min_all = t
|
| 347 |
+
is_dirichlet = dr.gather(Bool, self.dirichlet_map, i)
|
| 348 |
+
if (d < closest_dirichlet) & dr.gather(Bool, self.dirichlet_map, i):
|
| 349 |
+
closest_dirichlet = d
|
| 350 |
+
closest_bpoint_dirichlet = bpoint
|
| 351 |
+
t_min_dirichlet = t
|
| 352 |
+
k_dirichlet = i
|
| 353 |
+
|
| 354 |
+
#if closest_dist < closest_dirichlet:
|
| 355 |
+
# is_dirichlet = Bool(False)
|
| 356 |
+
i += 1
|
| 357 |
+
|
| 358 |
+
merge_dirichlet = (closest_dirichlet < (100*dr.epsilon(Float)))
|
| 359 |
+
is_dirichlet |= merge_dirichlet
|
| 360 |
+
is_neumann = ~is_dirichlet
|
| 361 |
+
|
| 362 |
+
num_conf = len(conf_numbers)
|
| 363 |
+
nearest_dirichlet_val = dr.zeros(ArrayXf, shape = (num_conf, dr.width(points)))
|
| 364 |
+
if dr.hint(not self.is_full_neumann, mode = "scalar"):
|
| 365 |
+
if dr.hint(self.v_dirichlet is None, mode = "scalar"):
|
| 366 |
+
if dr.hint(self.num_conf_d == 1, mode = 'scalar'):
|
| 367 |
+
dirichlet = self.dirichlet[0].get_value(closest_bpoint_dirichlet)
|
| 368 |
+
for i in range(num_conf):
|
| 369 |
+
nearest_dirichlet_val[i] = dirichlet
|
| 370 |
+
else:
|
| 371 |
+
for i in range(self.num_conf_d):
|
| 372 |
+
for j, conf in enumerate(conf_numbers):
|
| 373 |
+
if i == conf:
|
| 374 |
+
nearest_dirichlet_val[j] = self.dirichlet[i].get_value(closest_bpoint_dirichlet)
|
| 375 |
+
else:
|
| 376 |
+
nearest_dirichlet_all = self.get_dirichlet_vertices(k_dirichlet, t_min_dirichlet)
|
| 377 |
+
if dr.hint(self.num_conf_d == 1, mode = 'scalar'):
|
| 378 |
+
nearest_dirichlet_val = nearest_dirichlet_all
|
| 379 |
+
else:
|
| 380 |
+
for i in range(self.num_conf_d):
|
| 381 |
+
for j, conf in enumerate(conf_numbers):
|
| 382 |
+
if i == conf:
|
| 383 |
+
nearest_dirichlet_val[j] = nearest_dirichlet_all[i]
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
boundary_dir = dr.normalize(closest_bpoint - points)
|
| 387 |
+
radius = closest_dirichlet if radius_fnc is None else radius_fnc(closest_dirichlet)
|
| 388 |
+
radius = dr.minimum(radius, max_radius)
|
| 389 |
+
|
| 390 |
+
is_epsilon_shell = ((closest_dist < self.epsilon))
|
| 391 |
+
on_boundary = (closest_dist < self.epsilon_neumann)
|
| 392 |
+
is_far = (self.inf_distance < closest_dist) & (dr.dot(boundary_dir, closest_bnormal) > 0)
|
| 393 |
+
|
| 394 |
+
# Curvature computation
|
| 395 |
+
# We computed some stuff here, but whatever.
|
| 396 |
+
p1, p2, c = self.get_interpolation_points(k_all)
|
| 397 |
+
pd = self.interpolate_derivative(p1, p2, c, t_min_all)
|
| 398 |
+
pd2 = self.interpolate_derivative2(p1, p2, c, t_min_all)
|
| 399 |
+
pd_sqr = dr.sum(dr.square(pd))
|
| 400 |
+
curvature = -(pd[0] * pd2[1] - pd[1] * pd2[0]) / dr.sqrt(dr.square(pd_sqr) * pd_sqr)
|
| 401 |
+
bi = BoundaryInfo(points, on_boundary, radius, closest_dist, is_far, closest_bpoint, curvature, closest_dirichlet, nearest_dirichlet_val,
|
| 402 |
+
closest_bpoint_dirichlet, boundary_dir, closest_bnormal, is_dirichlet, is_neumann, is_epsilon_shell,
|
| 403 |
+
UInt32(0), UInt32(0), is_star = ~is_dirichlet)
|
| 404 |
+
return bi
|
| 405 |
+
|
| 406 |
+
def star_generation(self, bi):
|
| 407 |
+
bi.is_star = bi.is_n & (bi.r > bi.d)
|
| 408 |
+
return bi
|
| 409 |
+
|
| 410 |
+
@dr.syntax
|
| 411 |
+
def ray_intersect(self, bi : BoundaryInfo, direction : Point2f, conf_numbers : list[UInt32] = None):
|
| 412 |
+
|
| 413 |
+
origin = Point2f(bi.origin)
|
| 414 |
+
if bi.on_boundary:
|
| 415 |
+
origin = Point2f(bi.bpoint) + bi.bn * self.epsilon_neumann/50
|
| 416 |
+
|
| 417 |
+
#o_b = 1/bi.curvature * bi.bn
|
| 418 |
+
#cos_angle = dr.dot(o_b, direction)
|
| 419 |
+
#aprox_mask = (bi.curvature > 0) & bi.on_boundary & cos_angle < 1e-2
|
| 420 |
+
#if aprox_mask:
|
| 421 |
+
# t_min = 2 * cos_angle / bi.curvature
|
| 422 |
+
|
| 423 |
+
epsilon = 0
|
| 424 |
+
i = UInt32(0)
|
| 425 |
+
# First find which ray segment we should search for by assuming it is linearly interpolated.
|
| 426 |
+
n = UInt32(0)
|
| 427 |
+
t_min = Float(dr.inf)
|
| 428 |
+
t_min_ = Float(dr.nan)
|
| 429 |
+
while i < self.npoints:
|
| 430 |
+
p1, p2, co = self.get_interpolation_points(i)
|
| 431 |
+
a_ = p1 + p2 - 2 * co
|
| 432 |
+
b_ = 2 * (co - p1)
|
| 433 |
+
c_ = p1 - origin
|
| 434 |
+
a = direction[0] * a_[1] - direction[1] * a_[0]
|
| 435 |
+
b = direction[0] * b_[1] - direction[1] * b_[0]
|
| 436 |
+
c = direction[0] * c_[1] - direction[1] * c_[0]
|
| 437 |
+
t1_ = (-b - dr.sqrt(dr.square(b) - 4 * a * c)) / (2 * a)
|
| 438 |
+
t2_ = (-b + dr.sqrt(dr.square(b) - 4 * a * c)) / (2 * a)
|
| 439 |
+
|
| 440 |
+
t1 = Float(0)
|
| 441 |
+
t2 = Float(0)
|
| 442 |
+
if dr.abs(direction[0]) < 0.7:
|
| 443 |
+
t1 = (a_[1] * dr.square(t1_) + b_[1] * t1_ + c_[1]) / direction[1]
|
| 444 |
+
t2 = (a_[1] * dr.square(t2_) + b_[1] * t2_ + c_[1]) / direction[1]
|
| 445 |
+
else:
|
| 446 |
+
t1 = (a_[0] * dr.square(t1_) + b_[0] * t1_ + c_[0]) / direction[0]
|
| 447 |
+
t2 = (a_[0] * dr.square(t2_) + b_[0] * t2_ + c_[0]) / direction[0]
|
| 448 |
+
if dr.isfinite(t1) & dr.isfinite(t1_) & (t1 < t_min) & (t1> epsilon) & (t1_ >= 0) & (t1_ <= 1):
|
| 449 |
+
t_min = t1
|
| 450 |
+
t_min_ = t1_
|
| 451 |
+
n = UInt32(i)
|
| 452 |
+
if dr.isfinite(t2) & dr.isfinite(t2_) & (t2 < t_min) & (t2> epsilon) & (t2_ >= 0) & (t2_ <= 1):
|
| 453 |
+
t_min = t2
|
| 454 |
+
t_min_ = t2_
|
| 455 |
+
n = UInt32(i)
|
| 456 |
+
i+=1
|
| 457 |
+
#if self.inside & (t_min == dr.inf) & bi.on_boundary:
|
| 458 |
+
# t_min = Float(0)
|
| 459 |
+
|
| 460 |
+
intersected = origin + direction * t_min
|
| 461 |
+
p1, p2, co = self.get_interpolation_points(n)
|
| 462 |
+
normal = self.interpolate_derivative(p1, p2, co, t_min_)
|
| 463 |
+
normal = Point2f(-normal[1], normal[0])
|
| 464 |
+
if dr.dot(direction, normal) > 0:
|
| 465 |
+
normal = -normal
|
| 466 |
+
|
| 467 |
+
# Get the boundary condition at the hit point.
|
| 468 |
+
is_dirichlet = dr.gather(Bool, self.dirichlet_map, n)
|
| 469 |
+
|
| 470 |
+
neumann_vals = None
|
| 471 |
+
if dr.hint(conf_numbers is not None, mode = 'scalar'):
|
| 472 |
+
num_conf = len(conf_numbers)
|
| 473 |
+
neumann_vals = dr.zeros(ArrayXf, shape = (num_conf, dr.width(bi.origin)))
|
| 474 |
+
if not self.is_full_dirichlet:
|
| 475 |
+
if dr.hint(self.v_neumann is None, mode = "scalar"):
|
| 476 |
+
if dr.hint(self.num_conf_n == 1, mode = 'scalar'):
|
| 477 |
+
neumann = self.neumann[0].get_value(intersected)
|
| 478 |
+
for i in range(num_conf):
|
| 479 |
+
if ~is_dirichlet:
|
| 480 |
+
neumann_vals[i] = neumann
|
| 481 |
+
else:
|
| 482 |
+
for i in range(self.num_conf_n):
|
| 483 |
+
for j, conf in enumerate(conf_numbers):
|
| 484 |
+
if (i == conf) & ~is_dirichlet:
|
| 485 |
+
neumann_vals[j] = self.neumann[i].get_value(intersected)
|
| 486 |
+
else:
|
| 487 |
+
neumann_all = self.get_neumann_vertices(n, t_min_)
|
| 488 |
+
if dr.hint(self.num_conf_n == 1, mode = 'scalar'):
|
| 489 |
+
for i in range(num_conf):
|
| 490 |
+
if ~is_dirichlet:
|
| 491 |
+
neumann_vals = Float(neumann_all)
|
| 492 |
+
else:
|
| 493 |
+
for i in range(self.num_conf_n):
|
| 494 |
+
for j, conf in enumerate(conf_numbers):
|
| 495 |
+
if i == conf & ~is_dirichlet:
|
| 496 |
+
neumann_vals[j] = Float(neumann_all[i])
|
| 497 |
+
|
| 498 |
+
ri = RayInfo(origin, direction, t_min, intersected, normal, is_dirichlet, neumann_vals)
|
| 499 |
+
return ri
|
| 500 |
+
|
| 501 |
+
def get_diriclet_value(self, points) -> Float:
|
| 502 |
+
self.get_closest_dist(points,)
|
| 503 |
+
|
| 504 |
+
def sketch(self, ax, bbox, resolution, colors = ["red", "green"], sketch_center = False, sketch_in_boundaries = False, lw = None):
|
| 505 |
+
for i in range(self.npoints):
|
| 506 |
+
color = colors[0] if self.dirichlet_map[i]==True else colors[1]
|
| 507 |
+
p1, p2, c = self.get_interpolation_points(i)
|
| 508 |
+
p1_s = point2sketch(p1, bbox, resolution).numpy().squeeze()
|
| 509 |
+
p2_s = point2sketch(p2, bbox, resolution).numpy().squeeze()
|
| 510 |
+
c_s = point2sketch(c, bbox, resolution).numpy().squeeze()
|
| 511 |
+
pp = PathPatch(mpath([p1_s, c_s, p2_s], [mpath.MOVETO, mpath.CURVE3, mpath.CURVE3]), facecolor='none', edgecolor = color, linewidth = lw, capstyle = "round")
|
| 512 |
+
ax.add_patch(pp)
|
| 513 |
+
|
| 514 |
+
def sketch_points(self, ax, bbox, resolution, colors = ['green', 'orange'], control_points : bool = False):
|
| 515 |
+
for i in range(self.npoints):
|
| 516 |
+
p1, p2, c = self.get_interpolation_points(i)
|
| 517 |
+
p1_s = point2sketch(p1, bbox, resolution).numpy().squeeze()
|
| 518 |
+
p2_s = point2sketch(p2, bbox, resolution).numpy().squeeze()
|
| 519 |
+
c_s = point2sketch(c, bbox, resolution).numpy().squeeze()
|
| 520 |
+
ax.scatter(p1_s[0], p1_s[1], color = colors[0])
|
| 521 |
+
if control_points:
|
| 522 |
+
ax.scatter(c_s[0], c_s[1], color = colors[1])
|
| 523 |
+
|
| 524 |
+
def sketch_curvature(self, bi : BoundaryInfo, ax, bbox, resolution):
|
| 525 |
+
radius = 1/bi.curvature
|
| 526 |
+
center = bi.bpoint + bi.bn * radius
|
| 527 |
+
bpoint_s = point2sketch(bi.bpoint, bbox, resolution).numpy()
|
| 528 |
+
center_s = point2sketch(center, bbox, resolution).numpy()
|
| 529 |
+
radius_s = dist2sketch(radius, bbox, resolution)[0].numpy()
|
| 530 |
+
ax.scatter(bpoint_s[0], bpoint_s[1], color = 'red')
|
| 531 |
+
ax.scatter(center_s[0], center_s[1])
|
| 532 |
+
for c, r in zip(center_s.T, radius_s):
|
| 533 |
+
sphere = patches.Ellipse(c, r * 2, r * 2, linewidth= 1,
|
| 534 |
+
fill = False, color = "purple")
|
| 535 |
+
ax.add_patch(sphere)
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def sketch_normals(self, ax, bbox, resolution, color = "blue", length_vector = 0.2):
|
| 539 |
+
for i in range(self.npoints):
|
| 540 |
+
p1, _, c = self.get_interpolation_points(i)
|
| 541 |
+
p1_s = point2sketch(p1, bbox, resolution).numpy().squeeze()
|
| 542 |
+
c_s = point2sketch(c, bbox, resolution).numpy().squeeze()
|
| 543 |
+
l_s, _, _ = dist2sketch(length_vector, bbox, resolution)
|
| 544 |
+
v_n = self.get_normals(i)
|
| 545 |
+
n_s = dir2sketch(v_n, bbox, resolution).numpy().squeeze()
|
| 546 |
+
arrow = patches.FancyArrow(p1_s[0], p1_s[1], n_s[0] * l_s, n_s[1] * l_s,
|
| 547 |
+
width = 2 / 512 * resolution[0], length_includes_head=True, color = color)
|
| 548 |
+
ax.add_patch(arrow)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def sketch_polyline(self, ax, bbox, resolution, color = "blue"):
|
| 552 |
+
for i in range(self.npoints):
|
| 553 |
+
p1, p2, c = self.get_interpolation_points(i)
|
| 554 |
+
t = dr.arange(Float, self.n_segment + 1) / self.n_segment
|
| 555 |
+
p = self.interpolate(p1, p2, c, t)
|
| 556 |
+
p_s = point2sketch(p, bbox, resolution).numpy().squeeze()
|
| 557 |
+
pp = PathPatch(mpath(p_s.T), facecolor='none', edgecolor = color)
|
| 558 |
+
ax.add_patch(pp)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
def get_dirichlet_vertices(self, k : UInt32, t :UInt32):
|
| 562 |
+
d1 = dr.gather(Float, self.v_dirichlet, k)
|
| 563 |
+
d2 = dr.gather(Float, self.v_dirichlet, (k + 1) % self.npoints)
|
| 564 |
+
return dr.lerp(d1, d2, t)
|
| 565 |
+
|
| 566 |
+
def get_neumann_vertices(self, k : UInt32, t :UInt32):
|
| 567 |
+
n1 = dr.gather(Float, self.v_neumann, k)
|
| 568 |
+
n2 = dr.gather(Float, self.v_neumann, (k + 1) % self.npoints)
|
| 569 |
+
return dr.lerp(n1, n2, t)
|
| 570 |
+
|
| 571 |
+
@dr.syntax
|
| 572 |
+
def create_neumann_points(self, resolution : int, spp : int):
|
| 573 |
+
n = resolution * spp
|
| 574 |
+
points = dr.zeros(Point2f, self.n_neumann * n)
|
| 575 |
+
sampler = PCG32(initstate=dr.arange(UInt32, n))
|
| 576 |
+
indices = dr.arange(UInt32, n)
|
| 577 |
+
j = UInt32(0)
|
| 578 |
+
for i in range(self.npoints):
|
| 579 |
+
is_d = dr.gather(Bool, self.dirichlet_map, i)
|
| 580 |
+
if ~is_d:
|
| 581 |
+
p1, p2, c = self.get_interpolation_points(i)
|
| 582 |
+
t = dr.arange(Float, n) / n + sampler.next_float32() / n
|
| 583 |
+
p_iter = self.interpolate(p1, p2, c, t)
|
| 584 |
+
dr.scatter(points, p_iter, indices + j)
|
| 585 |
+
j += n
|
| 586 |
+
return points
|
| 587 |
+
|
| 588 |
+
def create_boundary_points(self, resolution : int, spp : int):
|
| 589 |
+
n = resolution * spp
|
| 590 |
+
points = dr.zeros(Point2f, self.n_segment * n)
|
| 591 |
+
sampler = PCG32(initstate=dr.arange(UInt32, n))
|
| 592 |
+
indices = dr.arange(UInt32, n)
|
| 593 |
+
j = UInt32(0)
|
| 594 |
+
for i in range(self.npoints):
|
| 595 |
+
p1, p2, c = self.get_interpolation_points(i)
|
| 596 |
+
t = dr.arange(Float, n) / n + sampler.next_float32() / n
|
| 597 |
+
p_iter = self.interpolate(p1, p2, c, t)
|
| 598 |
+
dr.scatter(points, p_iter, indices + j)
|
| 599 |
+
j += n
|
| 600 |
+
return points
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
|
data/PDE2D/BoundaryShape/boundary_shape.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import drjit as dr
|
| 2 |
+
from matplotlib import pyplot as plt
|
| 3 |
+
from matplotlib import patches as patches
|
| 4 |
+
from ..Coefficient import *
|
| 5 |
+
from ..utils.helpers import *
|
| 6 |
+
from .interaction import *
|
| 7 |
+
from mitsuba import Float, Point2f, Bool
|
| 8 |
+
from enum import IntEnum
|
| 9 |
+
|
| 10 |
+
class NEE(IntEnum):
|
| 11 |
+
Normal = 0,
|
| 12 |
+
Special = 1,
|
| 13 |
+
BruteForce = 2
|
| 14 |
+
|
| 15 |
+
class Shape(object):
|
| 16 |
+
def __init__(self, is_full_dirichlet = False, is_full_neumann = False, single_closed_shape = True,
|
| 17 |
+
epsilon=1e-5, inside = True, derivative_dist = 1e-2, inf_distance = 10):
|
| 18 |
+
self.is_full_dirichlet = is_full_dirichlet
|
| 19 |
+
self.is_full_neumann = is_full_neumann
|
| 20 |
+
self.single_closed = single_closed_shape
|
| 21 |
+
self.epsilon = epsilon
|
| 22 |
+
self.min_star_radius = self.epsilon * 2 # Check the paper for better min distance!
|
| 23 |
+
self.name = "boundary"
|
| 24 |
+
self.inside = inside
|
| 25 |
+
self.normal_derivative_dist = derivative_dist
|
| 26 |
+
self.measured_current = False # If the Boundary condition given as currents or normal derivatives.
|
| 27 |
+
self.has_continuous_neumann = True
|
| 28 |
+
self.has_delta = False
|
| 29 |
+
self.NEE = NEE.Normal
|
| 30 |
+
self.inf_distance = inf_distance
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def star_generation(self, bi: BoundaryInfo) -> BoundaryInfo:
|
| 34 |
+
return bi
|
| 35 |
+
|
| 36 |
+
def inside_closed_surface(self, points, L, conf_numbers):
|
| 37 |
+
return Bool(False), dr.zeros(ArrayXf, shape = (len(conf_numbers), dr.width(points)))
|
| 38 |
+
|
| 39 |
+
def inside_closed_surface_mask(self, L):
|
| 40 |
+
return Bool(False)
|
| 41 |
+
|
| 42 |
+
def ray_intersect(self, bi : BoundaryInfo, direction : Point2f, conf_numbers : list[UInt32] = None) -> RayInfo:
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
def boundary_interaction(points : Point2f,
|
| 46 |
+
radius_fnc : callable = None, max_radius = None,
|
| 47 |
+
star_generation = True, conf_numbers : list[UInt32] = [UInt32[0]]) -> BoundaryInfo:
|
| 48 |
+
pass
|
| 49 |
+
|
| 50 |
+
def get_opt_params_shape(self, param_dict: dict, opt_params: list):
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
def update_shape(self, optimizer):
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
def zero_grad_shape(self):
|
| 57 |
+
pass
|
| 58 |
+
|
| 59 |
+
def sketch(self,ax, bbox, resolution, colors = ['red'], fill = False):
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
def sketch_image(self,ax, bbox, resolution, channel= 0, colors = ["red"], image = None, color_factor = 0.6):
|
| 63 |
+
pass
|
| 64 |
+
|
| 65 |
+
def create_boundary_points(self, distance : float, resolution : int, spp : int):
|
| 66 |
+
pass
|
| 67 |
+
|
| 68 |
+
def create_neumann_points(self, resolution : int, spp : int):
|
| 69 |
+
pass
|
| 70 |
+
|
| 71 |
+
def create_boundary_result(self, result, resolution):
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
def create_boundary_coefficient(self, tensor_mi, name = "boundary-val"):
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
def set_normal_derivative(self, tensor_mi, name = "normal-derivative"):
|
| 78 |
+
pass
|
| 79 |
+
|
| 80 |
+
def normal_derivative_from_result(self, result : Float, film_points : Point2f, resolution : int):
|
| 81 |
+
pass
|
| 82 |
+
|
| 83 |
+
def create_normal_der_coefficient(self, tensor_mi):
|
| 84 |
+
pass
|
| 85 |
+
|
| 86 |
+
def jakobian_to_boundary(self, bi : BoundaryInfo, distance : Float):
|
| 87 |
+
pass
|
| 88 |
+
|
| 89 |
+
def get_max_intersection_dist(self, bi : BoundaryInfo):
|
| 90 |
+
pass
|
| 91 |
+
|
| 92 |
+
def get_distance_correction(self, points):
|
| 93 |
+
pass
|
| 94 |
+
def get_point_neumann(self, bi : BoundaryInfo, conf_number : UInt32) -> tuple[list[Float], list[Float], list[Float], list[Point2f]]:
|
| 95 |
+
return [], [], [], []
|
| 96 |
+
|
| 97 |
+
def sampleNEE(self, bi : BoundaryInfo, sample : Float, conf_number : UInt32) -> tuple[Float, Float, Float, Point2f]:
|
| 98 |
+
return Float(0), Float(0), Float(0), Point2f(0)
|
| 99 |
+
|
| 100 |
+
def create_volume_points(self, resolution = [256, 256], spp = 1):
|
| 101 |
+
points = create_image_points(self.bbox, resolution, spp, centered = True)
|
| 102 |
+
active = self.inside_closed_surface_mask(points)
|
| 103 |
+
indices = dr.compress(active)
|
| 104 |
+
points = dr.gather(type(points), points, indices)
|
| 105 |
+
return points
|
| 106 |
+
|
| 107 |
+
def accum_tput(self, tput : Float, bi : BoundaryInfo):
|
| 108 |
+
pass
|
data/PDE2D/BoundaryShape/boundarywithdirichlets.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PDE2D.BoundaryShape.interaction import BoundaryInfo
|
| 2 |
+
from PDE2D.BoundaryShape import CircleShape
|
| 3 |
+
from .boundary_shape import *
|
| 4 |
+
from ..utils.helpers import *
|
| 5 |
+
from ..utils.sketch import *
|
| 6 |
+
from .interaction import *
|
| 7 |
+
from scipy.spatial import Voronoi
|
| 8 |
+
|
| 9 |
+
from ..utils.imageUtils import create_circle_from_result, create_circle_points
|
| 10 |
+
from ..Coefficient import *
|
| 11 |
+
class BoundaryWithDirichlets(Shape):
|
| 12 |
+
def __init__(self, out_boundary : Shape,
|
| 13 |
+
dirichlet_boundaries : list[Shape] = [], dirichlet_values : list[list] = None,
|
| 14 |
+
epsilon = 1e-5, name : str = "DirichletShapes"):
|
| 15 |
+
#assert len(dirichlet_values) == len(dirichlet_boundaries)
|
| 16 |
+
|
| 17 |
+
self.single_shape_closed = True
|
| 18 |
+
self.name = name
|
| 19 |
+
self.out_boundary = out_boundary
|
| 20 |
+
self.in_boundaries = dirichlet_boundaries
|
| 21 |
+
self.out_boundary.inside = True
|
| 22 |
+
self.is_full_dirichlet = self.out_boundary.is_full_dirichlet
|
| 23 |
+
self.max_distance = self.out_boundary.max_distance
|
| 24 |
+
self.single_closed = True
|
| 25 |
+
self.neumann = self.out_boundary.neumann # Only neumann is the out boundary
|
| 26 |
+
# If the shape has some NEE structure.
|
| 27 |
+
self.NEE = self.out_boundary.NEE
|
| 28 |
+
self.has_continuous_neumann = self.out_boundary.has_continuous_neumann
|
| 29 |
+
self.has_delta = self.out_boundary.has_delta
|
| 30 |
+
# If the boundary condition given as currents or normal derivatives.
|
| 31 |
+
self.measured_current = self.out_boundary.measured_current
|
| 32 |
+
self.epsilon = epsilon
|
| 33 |
+
self.out_boundary.epsilon = epsilon
|
| 34 |
+
self.bbox = self.out_boundary.bbox
|
| 35 |
+
self.bbox_length = max(self.bbox[1][1] - self.bbox[0][1], self.bbox[1][0] - self.bbox[0][0])
|
| 36 |
+
self.update_in_boundaries(dirichlet_boundaries, dirichlet_values)
|
| 37 |
+
|
| 38 |
+
def update_in_boundaries(self, in_boundaries : list[Shape], dirichlet_values : list[list] = None):
|
| 39 |
+
self.num_shapes = len(in_boundaries)
|
| 40 |
+
if dirichlet_values is None:
|
| 41 |
+
dirichlet_values = [[0] for i in range(self.num_shapes)]
|
| 42 |
+
|
| 43 |
+
#if self.num_shapes > 0:
|
| 44 |
+
# self.num_conf_d = len(dirichlets[0])
|
| 45 |
+
#else:
|
| 46 |
+
# self.num_conf_d = 1
|
| 47 |
+
|
| 48 |
+
self.in_boundaries = in_boundaries
|
| 49 |
+
self.is_full_neumann = (self.num_shapes == 0) & self.out_boundary.is_full_neumann
|
| 50 |
+
for i, d_shape in enumerate(self.in_boundaries):
|
| 51 |
+
assert d_shape.is_full_dirichlet
|
| 52 |
+
#assert len(dirichlet_values[i]) == self.num_conf_d
|
| 53 |
+
d_shape.inside = False
|
| 54 |
+
d_shape.epsilon = self.epsilon
|
| 55 |
+
|
| 56 |
+
self.update_in_boundary_dirichlets(dirichlet_values)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_origins(self):
|
| 60 |
+
origins = []
|
| 61 |
+
for d_shape in self.in_boundaries:
|
| 62 |
+
origins.append(d_shape.origin.numpy().squeeze())
|
| 63 |
+
return np.array(origins)
|
| 64 |
+
|
| 65 |
+
def update_in_boundaries_circle(self, origins : list, radius : float = 0.01, dirichlet_values : list[list] = None):
|
| 66 |
+
in_boundaries = []
|
| 67 |
+
for origin in origins:
|
| 68 |
+
in_boundaries.append(CircleShape(origin = origin, radius = radius))
|
| 69 |
+
self.update_in_boundaries(in_boundaries, dirichlet_values)
|
| 70 |
+
|
| 71 |
+
@dr.syntax
|
| 72 |
+
def update_in_boundary_dirichlets(self, dirichlet_values : list[list]):
|
| 73 |
+
self.dirichlets = []
|
| 74 |
+
for i in range(self.num_shapes):
|
| 75 |
+
self.dirichlets.append(ArrayXf(dirichlet_values[i]))
|
| 76 |
+
dr.make_opaque(self.dirichlets)
|
| 77 |
+
|
| 78 |
+
@dr.syntax
|
| 79 |
+
def ray_intersect(self, bi : BoundaryInfo, direction : Point2f, conf_numbers : list [UInt32] = None): # change this for outside!
|
| 80 |
+
ri = self.out_boundary.ray_intersect(bi, direction, conf_numbers)
|
| 81 |
+
for boundary in self.in_boundaries:
|
| 82 |
+
ri_in = boundary.ray_intersect(bi, direction, conf_numbers)
|
| 83 |
+
if (ri_in.t < ri.t) & (ri_in.t >= 0):
|
| 84 |
+
ri.t = Float(ri_in.t)
|
| 85 |
+
ri.intersected = Point2f(ri_in.intersected)
|
| 86 |
+
ri.normal = Point2f(ri_in.normal)
|
| 87 |
+
ri.is_dirichlet = Bool(ri_in.is_dirichlet)
|
| 88 |
+
if dr.hint(conf_numbers is not None):
|
| 89 |
+
num_conf = len(conf_numbers)
|
| 90 |
+
if dr.hint(num_conf == 1):
|
| 91 |
+
ri.neumann[0] = Float(0)
|
| 92 |
+
else:
|
| 93 |
+
for j in range(num_conf):
|
| 94 |
+
ri.neumann[j] = Float(0)
|
| 95 |
+
return ri
|
| 96 |
+
|
| 97 |
+
@dr.syntax
|
| 98 |
+
def boundary_interaction(self, points,
|
| 99 |
+
radius_fnc : callable = None, star_generation = True,
|
| 100 |
+
max_radius = Float(dr.inf), conf_numbers : list[UInt32] = [UInt32(0)]):
|
| 101 |
+
num_conf = len(conf_numbers)
|
| 102 |
+
assert len(self.dirichlets) == self.num_shapes
|
| 103 |
+
if self.num_shapes>0:
|
| 104 |
+
assert (num_conf == dr.width(self.dirichlets[0])) or (dr.width(self.dirichlets[0]) == 1)
|
| 105 |
+
bi = self.out_boundary.boundary_interaction(points, radius_fnc, star_generation = False, conf_numbers = conf_numbers)
|
| 106 |
+
for (i,boundary) in enumerate(self.in_boundaries):
|
| 107 |
+
bi_in = boundary.boundary_interaction(points, radius_fnc, star_generation = False, conf_numbers = conf_numbers)
|
| 108 |
+
bi_in.shape = UInt32(i+1)
|
| 109 |
+
bi_in.d_shape = UInt32(i+1)
|
| 110 |
+
bi_in.dval = ArrayXf(self.dirichlets[i])
|
| 111 |
+
bi = merge_boundary_info(bi, bi_in)
|
| 112 |
+
|
| 113 |
+
bi.r = dr.minimum(max_radius, bi.r)
|
| 114 |
+
|
| 115 |
+
if dr.hint(not self.is_full_dirichlet, mode = 'scalar'):
|
| 116 |
+
if dr.hint(star_generation, mode = 'scalar'):
|
| 117 |
+
bi = self.star_generation(bi)
|
| 118 |
+
return bi
|
| 119 |
+
|
| 120 |
+
def star_generation(self, bi):
|
| 121 |
+
return self.out_boundary.star_generation(bi)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def sampleNEE(self, bi : BoundaryInfo, sample : Float, conf_number : UInt32) -> tuple[Float, Float, Float, Point2f]:
|
| 125 |
+
return self.out_boundary.sampleNEE(bi, sample, conf_number)
|
| 126 |
+
|
| 127 |
+
def get_point_neumann(self, bi : BoundaryInfo, conf_number : UInt32) -> tuple[list[Float], list[Float], list[Float], list[Point2f]]:
|
| 128 |
+
return self.out_boundary.get_point_neumann(bi, conf_number)
|
| 129 |
+
|
| 130 |
+
@dr.syntax
|
| 131 |
+
def inside_closed_surface(self, points : Point2f, L : ArrayXf, conf_numbers = list[UInt32]):
|
| 132 |
+
num_conf = len(conf_numbers)
|
| 133 |
+
if self.num_shapes>0:
|
| 134 |
+
assert (num_conf == dr.width(self.dirichlets[0])) or (dr.width(self.dirichlets[0]) == 1)
|
| 135 |
+
|
| 136 |
+
active, L = self.out_boundary.inside_closed_surface(points, L)
|
| 137 |
+
for i, boundary in enumerate(self.in_boundaries):
|
| 138 |
+
mask, L = boundary.inside_closed_surface(points, L)
|
| 139 |
+
active &= ~mask
|
| 140 |
+
if mask:
|
| 141 |
+
L += ArrayXf(self.dirichlets[i])
|
| 142 |
+
return active, L
|
| 143 |
+
|
| 144 |
+
@dr.syntax
|
| 145 |
+
def inside_closed_surface_mask(self, points : Point2f):
|
| 146 |
+
active = self.out_boundary.inside_closed_surface_mask(points)
|
| 147 |
+
for i, boundary in enumerate(self.in_boundaries):
|
| 148 |
+
mask = boundary.inside_closed_surface_mask(points)
|
| 149 |
+
active &= ~mask
|
| 150 |
+
return active
|
| 151 |
+
|
| 152 |
+
def get_opt_params_shape(self, param_dict: dict, opt_params: list):
|
| 153 |
+
self.out_boundary.get_opt_params_shape(param_dict, opt_params)
|
| 154 |
+
for boundary in self.in_boundaries:
|
| 155 |
+
boundary.get_opt_params_shape(param_dict, opt_params)
|
| 156 |
+
|
| 157 |
+
def update_shape(self, optimizer):
|
| 158 |
+
#if post_process is not None:
|
| 159 |
+
# post_process(optimizer)
|
| 160 |
+
#self.out_boundary.update_shape(optimizer)
|
| 161 |
+
#for boundary in self.in_boundaries:
|
| 162 |
+
# boundary.update_shape(optimizer)
|
| 163 |
+
self.in_boundaries[0].update_shape(optimizer)
|
| 164 |
+
|
| 165 |
+
def zero_grad_shape(self):
|
| 166 |
+
self.out_boundary.zero_grad_shape()
|
| 167 |
+
for boundary in self.in_boundaries:
|
| 168 |
+
boundary.zero_grad_shape()
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def sketch_image(self, ax, bbox, resolution, channel = 0, colors = ["orange", "green"], image = None,
|
| 172 |
+
color_factor = 0.6):
|
| 173 |
+
image = np.zeros([resolution[0], resolution[1], 3])
|
| 174 |
+
for shape in self.in_boundaries:
|
| 175 |
+
image = shape.sketch_image(ax, bbox, resolution, channel = channel,
|
| 176 |
+
image =image, color_factor=color_factor)
|
| 177 |
+
ax.imshow(image)
|
| 178 |
+
|
| 179 |
+
self.out_boundary.sketch(ax, bbox, resolution, colors = colors)
|
| 180 |
+
return image
|
| 181 |
+
|
| 182 |
+
def sketch(self, ax, bbox, resolution, colors = ["orange","green", "red"], fill = False, sketch_center = False, sketch_in_boundaries = True):
|
| 183 |
+
if sketch_in_boundaries:
|
| 184 |
+
for shape in self.in_boundaries:
|
| 185 |
+
shape.sketch(ax, bbox, resolution, colors = [colors[2], colors[0]], fill = fill, sketch_center = sketch_center)
|
| 186 |
+
self.out_boundary.sketch(ax, bbox, resolution, colors = colors[0:2])
|
| 187 |
+
|
| 188 |
+
def create_boundary_points(self, distance: float, res: int, spp: int, discrete_points : bool = True):
|
| 189 |
+
with dr.suspend_grad():
|
| 190 |
+
points = []
|
| 191 |
+
normals = []
|
| 192 |
+
s_points = []
|
| 193 |
+
p, s_p, n = self.out_boundary.create_boundary_points(distance, res, spp, discrete_points)
|
| 194 |
+
points.append(p)
|
| 195 |
+
normals.append(n)
|
| 196 |
+
s_points.append(s_p)
|
| 197 |
+
for boundary in self.in_boundaries:
|
| 198 |
+
p, s_p, n = boundary.create_boundary_points(distance, res, spp, discrete_points)
|
| 199 |
+
points.append(p)
|
| 200 |
+
s_points.append(s_p)
|
| 201 |
+
normals.append(n)
|
| 202 |
+
return points, s_p, normals
|
| 203 |
+
|
| 204 |
+
def create_boundary_result(self, result, resolution):
|
| 205 |
+
with dr.suspend_grad():
|
| 206 |
+
tensor = []
|
| 207 |
+
tensor_mi = []
|
| 208 |
+
t, t_mi = self.out_boundary.create_boundary_result(result[0], resolution)
|
| 209 |
+
tensor.append(t)
|
| 210 |
+
tensor_mi.append(t_mi)
|
| 211 |
+
for i, boundary in enumerate(self.in_boundaries):
|
| 212 |
+
t, t_mi = boundary.create_boundary_result(result[i+1], resolution)
|
| 213 |
+
tensor.append(t)
|
| 214 |
+
tensor_mi.append(t_mi)
|
| 215 |
+
return tensor, tensor_mi
|
| 216 |
+
|
| 217 |
+
def create_boundary_coefficient(self, tensor_mi, name = "boundary-val"):
|
| 218 |
+
with dr.suspend_grad():
|
| 219 |
+
self.boundary_coeff = []
|
| 220 |
+
self.boundary_coeff.append(self.out_boundary.create_boundary_coefficient(tensor_mi[0], f'{name}-0'))
|
| 221 |
+
for i, boundary in enumerate(self.in_boundaries):
|
| 222 |
+
self.boundary_coeff.append(boundary.create_boundary_coefficient(tensor_mi[i+1], f'{name}-{i}'))
|
| 223 |
+
return self.boundary_coeff
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
#def set_normal_derivative(self, tensor_mi, name = "normal-derivative"):
|
| 227 |
+
# self.normal_derivative = []
|
| 228 |
+
# self.normal_derivative.append(self.out_boundary.set_normal_derivative(tensor_mi[0], f"{name}-0"))
|
| 229 |
+
# for i, boundary in enumerate(self.in_boundaries):
|
| 230 |
+
# self.normal_derivative.append(boundary.set_normal_derivative(tensor_mi[i+1], f'{name}-{i}'))
|
| 231 |
+
# return self.normal_derivative
|
| 232 |
+
|
| 233 |
+
#@dr.syntax
|
| 234 |
+
#def jakobian_to_boundary(self, bi : BoundaryInfo, distance = None):
|
| 235 |
+
# This one computes the minimum of the distances to compute the boundary result.
|
| 236 |
+
# jak = Float(0)
|
| 237 |
+
# for i, shape in enumerate(self.in_boundaries):
|
| 238 |
+
# if bi.d_shape == UInt32(i+1):
|
| 239 |
+
# jak = shape.jakobian_to_boundary(bi, max_distance)
|
| 240 |
+
# return jak
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def get_normal_derivative(self, points : Point2f):
|
| 244 |
+
return self.in_boundaries[0].get_normal_derivative(points)
|
| 245 |
+
|
| 246 |
+
def get_jacobian_factor(self, bi : BoundaryInfo, distance : float):
|
| 247 |
+
ri = self.ray_intersect(bi, bi.bn)
|
| 248 |
+
distance = dr.minimum(distance, 0.3 * ri.t)
|
| 249 |
+
return self.in_boundaries[0].jakobian_to_boundary(bi, distance)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 253 |
+
self.in_boundaries[0].get_opt_params_shape(param_dict, opt_params)
|
| 254 |
+
|
| 255 |
+
def update(self, optimizer):
|
| 256 |
+
self.out_boundary.update(optimizer)
|
| 257 |
+
for shape in self.in_boundaries:
|
| 258 |
+
shape.update(optimizer)
|
| 259 |
+
|
| 260 |
+
def zero_grad(self):
|
| 261 |
+
self.out_boundary.zero_grad()
|
| 262 |
+
for shape in self.in_boundaries:
|
| 263 |
+
shape.zero_grad()
|
| 264 |
+
|
| 265 |
+
def merge_boundary_info(bi1, bi2, radius_fnc : callable = None):
|
| 266 |
+
# merges 2 boundary informations created with different shapes.
|
| 267 |
+
# it does not handle the star generation!
|
| 268 |
+
# Here bi2 must be only dirichlet, it is created for circlewithdirichletsshape
|
| 269 |
+
mask = bi1.d < bi2.d
|
| 270 |
+
mask_d = bi1.dd < bi2.dd
|
| 271 |
+
bi = BoundaryInfo()
|
| 272 |
+
bi.origin = Point2f(bi1.origin)
|
| 273 |
+
#bi.on_boundary = dr.select(mask, bi1.on_boundary, bi2.on_boundary)
|
| 274 |
+
bi.on_boundary = bi1.on_boundary
|
| 275 |
+
bi.d = dr.select(mask, bi1.d, bi2.d)
|
| 276 |
+
bi.is_far = dr.select(mask, bi1.is_far, bi2.is_far)
|
| 277 |
+
bi.dd = dr.select(mask_d, bi1.dd, bi2.dd)
|
| 278 |
+
bi.r = bi.dd
|
| 279 |
+
bi.bpoint = dr.select(mask, bi1.bpoint, bi2.bpoint)
|
| 280 |
+
bi.curvature = dr.select(mask, bi1.curvature, bi2.curvature)
|
| 281 |
+
bi.dval = dr.select(mask_d, bi1.dval, bi2.dval)
|
| 282 |
+
bi.dpoint = dr.select(mask_d, bi1.dpoint, bi2.dpoint)
|
| 283 |
+
bi.bdir = dr.select(mask, bi1.bdir, bi2.bdir)
|
| 284 |
+
bi.bn = dr.select(mask, bi1.bn, bi2.bn)
|
| 285 |
+
bi.is_d = dr.select(mask, bi1.is_d, bi2.is_d)
|
| 286 |
+
bi.is_n = dr.select(mask, bi1.is_n, bi2.is_n)
|
| 287 |
+
bi.is_e = dr.select(mask, bi1.is_e, bi2.is_e)
|
| 288 |
+
bi.shape = dr.select(mask, bi1.shape, bi2.shape)
|
| 289 |
+
bi.d_shape = dr.select(mask_d, bi1.d_shape, bi2.d_shape)
|
| 290 |
+
return bi
|
data/PDE2D/BoundaryShape/circle.py
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .boundary_shape import *
|
| 2 |
+
from ..utils.helpers import *
|
| 3 |
+
from ..utils.sketch import *
|
| 4 |
+
from .interaction import *
|
| 5 |
+
from mitsuba import UInt
|
| 6 |
+
from ..utils.imageUtils import create_circle_from_result, create_circle_points
|
| 7 |
+
from ..Coefficient import *
|
| 8 |
+
from .sdf_grid import SDFGrid
|
| 9 |
+
class CircleShape(Shape):
|
| 10 |
+
def __init__(self, origin=[0, 0], radius=1,
|
| 11 |
+
angle_partition=np.array([0]),
|
| 12 |
+
dirichlet_map: np.array = np.array([True]),
|
| 13 |
+
dirichlet: list[Coefficient] = [ConstantCoefficient("dirichlet", 0)],
|
| 14 |
+
neumann: list[Coefficient] = [ConstantCoefficient("neumann", 0)],
|
| 15 |
+
epsilon=1e-4, name = "boundary", normal_derivative_dist = 0.01,
|
| 16 |
+
inside = True):
|
| 17 |
+
super().__init__(np.all(dirichlet_map), single_closed_shape=True, epsilon=epsilon,
|
| 18 |
+
inside = inside, derivative_dist=normal_derivative_dist)
|
| 19 |
+
self.name = name
|
| 20 |
+
self.origin = Point2f(origin)
|
| 21 |
+
self.radius = Float(radius)
|
| 22 |
+
dr.make_opaque(self.origin)
|
| 23 |
+
dr.make_opaque(self.radius)
|
| 24 |
+
# check if there is no neumann boundary
|
| 25 |
+
self.dirichlet_map = Bool(dirichlet_map)
|
| 26 |
+
dr.make_opaque(self.dirichlet_map)
|
| 27 |
+
self.is_full_dirichlet = dr.all(self.dirichlet_map)
|
| 28 |
+
self.is_full_neumann = dr.all(~self.dirichlet_map)
|
| 29 |
+
|
| 30 |
+
# Create interval vector of size (n_interval, 2)
|
| 31 |
+
# The first angle partition
|
| 32 |
+
self.init_angle_partition = Float(float(angle_partition[0]))
|
| 33 |
+
angle_partition = np.append(
|
| 34 |
+
angle_partition, angle_partition[0] + 2 * np.pi)
|
| 35 |
+
angle_intervals = np.stack([angle_partition[:-1],
|
| 36 |
+
angle_partition[1:]], axis=0)
|
| 37 |
+
self.angle_partition = Point2f(angle_intervals)
|
| 38 |
+
dr.make_opaque(angle_partition)
|
| 39 |
+
self.num_intervals = dr.width(self.angle_partition)
|
| 40 |
+
|
| 41 |
+
# Get the dirichlet and neumann intervals
|
| 42 |
+
self.dirichlet_angles = Point2f(angle_intervals[:, np.array(dirichlet_map, dtype = bool)])
|
| 43 |
+
self.neumann_angles = Point2f(angle_intervals[:, ~np.array(dirichlet_map, dtype = bool)])
|
| 44 |
+
|
| 45 |
+
self.bbox = [[self.origin[0] - radius, self.origin[1] - radius],
|
| 46 |
+
[self.origin[0] + radius, self.origin[1] + radius]]
|
| 47 |
+
|
| 48 |
+
# Dirichlet and neumann boundary values (instance of Coefficient).
|
| 49 |
+
self.dirichlet = dirichlet
|
| 50 |
+
self.neumann = neumann
|
| 51 |
+
|
| 52 |
+
self.num_conf_d = len(dirichlet)
|
| 53 |
+
self.num_conf_n = len(neumann)
|
| 54 |
+
assert (self.num_conf_d == self.num_conf_n) or (self.num_conf_n == 1) or (self.num_conf_d == 1)
|
| 55 |
+
|
| 56 |
+
self.max_distance = self.radius
|
| 57 |
+
self.measureCurrent = False
|
| 58 |
+
|
| 59 |
+
@dr.syntax
|
| 60 |
+
def ray_intersect(self, bi : BoundaryInfo, direction : Point2f, conf_numbers : list[UInt32] = None): # change this for outside!
|
| 61 |
+
|
| 62 |
+
# if outside due to numerical errors (we always assume that we compute solution inside!)
|
| 63 |
+
# origin = dr.select(dr.norm(o_b) >= self.radius - 1e-1,
|
| 64 |
+
# self.origin - o_b * (self.radius - 1e-1) / dr.norm(o_b),
|
| 65 |
+
# origin)
|
| 66 |
+
# Solve second order polynomial
|
| 67 |
+
origin = Point2f(bi.origin)
|
| 68 |
+
on_boundary = Bool(bi.on_boundary)
|
| 69 |
+
o_b = Point2f(0)
|
| 70 |
+
if on_boundary & self.inside:
|
| 71 |
+
o_b = dr.normalize(self.origin - origin)
|
| 72 |
+
cos_angle = dr.dot(o_b, direction)
|
| 73 |
+
t = 2 * cos_angle * self.radius
|
| 74 |
+
else:
|
| 75 |
+
o_b = origin - self.origin
|
| 76 |
+
a = dr.dot(direction, direction)
|
| 77 |
+
b = 2 * dr.dot(o_b, direction)
|
| 78 |
+
c = dr.dot(o_b, o_b) - dr.sqr(self.radius)
|
| 79 |
+
sign = dr.select(self.inside, 1, -1)
|
| 80 |
+
t = (- b + sign * dr.sqrt(dr.sqr(b) - 4 * a * c)) / (2 * a)
|
| 81 |
+
|
| 82 |
+
intersected = mi.Point2f(origin + direction * t)
|
| 83 |
+
# if intersected point is outside the domain, put it back in!
|
| 84 |
+
diff = intersected -self.origin
|
| 85 |
+
normals = dr.normalize(diff)
|
| 86 |
+
normals = -normals if self.inside else normals
|
| 87 |
+
|
| 88 |
+
angles = correct_angle(dr.atan2(diff[0], diff[1]))
|
| 89 |
+
is_dirichlet = self.is_dirichlet_boundary(angles, Bool(True))
|
| 90 |
+
|
| 91 |
+
neumann_vals = None
|
| 92 |
+
if dr.hint(conf_numbers is not None, mode = 'scalar'):
|
| 93 |
+
num_conf = len(conf_numbers)
|
| 94 |
+
neumann_vals = dr.zeros(ArrayXf, shape = (num_conf, dr.width(intersected)))
|
| 95 |
+
if not dr.hint(self.is_full_dirichlet, mode = "scalar"):
|
| 96 |
+
if ~is_dirichlet:
|
| 97 |
+
if dr.hint(self.num_conf_n == 1, mode = "scalar"):
|
| 98 |
+
neumann = self.neumann[0].get_value(intersected)
|
| 99 |
+
for i in range(num_conf):
|
| 100 |
+
neumann_vals[i] = neumann
|
| 101 |
+
else:
|
| 102 |
+
for i in range(self.num_conf_n):
|
| 103 |
+
for j, conf in enumerate(conf_numbers):
|
| 104 |
+
neumann_vals[j] = dr.select(i == conf, self.neumann[i].get_value(intersected), neumann_vals[j])
|
| 105 |
+
return RayInfo(origin, direction, t, intersected, normals, is_dirichlet, neumann_vals)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@dr.syntax
|
| 110 |
+
def get_nearest_distances(self, points, active):
|
| 111 |
+
# active mask needs to be the points where we have nearest neumann boundary!
|
| 112 |
+
# otherwise we need to check the closest point to the boundary, too!
|
| 113 |
+
npoints = dr.width(points)
|
| 114 |
+
min_distance, angles, boundary_points =self.closest_points(points)
|
| 115 |
+
if dr.hint(self.is_full_neumann, mode = 'scalar'):
|
| 116 |
+
return min_distance, boundary_points, dr.full(Bool, False, npoints), dr.inf, Point2f(dr.inf)
|
| 117 |
+
if dr.hint(self.is_full_dirichlet, mode = 'scalar'):
|
| 118 |
+
return min_distance, boundary_points, dr.full(Bool, True, npoints), min_distance, boundary_points
|
| 119 |
+
|
| 120 |
+
is_dirichlet = self.is_dirichlet_boundary(angles, dr.copy(active))
|
| 121 |
+
if is_dirichlet:
|
| 122 |
+
nearest_dirichlet_dist = Float(min_distance)
|
| 123 |
+
nearest_dirichlet_point = boundary_points
|
| 124 |
+
else:
|
| 125 |
+
nearest_dirichlet_dist = Float(dr.inf)
|
| 126 |
+
nearest_dirichlet_point = Point2f(dr.inf)
|
| 127 |
+
|
| 128 |
+
i = dr.zeros(UInt, npoints)
|
| 129 |
+
num_dirichlet_arcs = dr.width(self.dirichlet_angles)
|
| 130 |
+
|
| 131 |
+
while active & (i < num_dirichlet_arcs):
|
| 132 |
+
interval = dr.gather(Point2f, self.dirichlet_angles, i)
|
| 133 |
+
|
| 134 |
+
points1 = self.origin + self.radius * \
|
| 135 |
+
Point2f(dr.sin(interval[0]), dr.cos(interval[0]))
|
| 136 |
+
points2 = self.origin + self.radius * \
|
| 137 |
+
Point2f(dr.sin(interval[1]), dr.cos(interval[1]))
|
| 138 |
+
|
| 139 |
+
distance1 = dr.norm(points1 - points)
|
| 140 |
+
distance2 = dr.norm(points2 - points)
|
| 141 |
+
dist_mask1 = distance1 < distance2
|
| 142 |
+
nearest_point_temp = dr.select(dist_mask1, points1, points2)
|
| 143 |
+
dist_to_arc = dr.minimum(distance1, distance2)
|
| 144 |
+
dist_mask2 = dist_to_arc < nearest_dirichlet_dist
|
| 145 |
+
nearest_dirichlet_point = Point2f(dr.select(dist_mask2, nearest_point_temp, nearest_dirichlet_point))
|
| 146 |
+
nearest_dirichlet_dist = dr.select(dist_mask2, dist_to_arc, nearest_dirichlet_dist)
|
| 147 |
+
i += 1
|
| 148 |
+
return min_distance, boundary_points, is_dirichlet, nearest_dirichlet_dist, nearest_dirichlet_point
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@dr.syntax
|
| 152 |
+
def is_dirichlet_boundary(self, angles: Float, active: Bool = Bool(True)):
|
| 153 |
+
num_angles = dr.width(angles)
|
| 154 |
+
if dr.hint(self.is_full_dirichlet, mode = "scalar"):
|
| 155 |
+
return Bool(True)
|
| 156 |
+
elif dr.hint(self.is_full_neumann, mode = 'scalar'):
|
| 157 |
+
return Bool(False)
|
| 158 |
+
else:
|
| 159 |
+
if angles < self.init_angle_partition:
|
| 160 |
+
angles += 2 *dr.pi
|
| 161 |
+
i = dr.zeros(UInt, num_angles)
|
| 162 |
+
is_dirichlet = dr.zeros(Bool, num_angles)
|
| 163 |
+
num_dirichlet = dr.width(self.dirichlet_angles)
|
| 164 |
+
while active & (i < num_dirichlet):
|
| 165 |
+
interval = dr.gather(Point2f, self.dirichlet_angles, i)
|
| 166 |
+
interval_found = (angles >= interval[0]) & (
|
| 167 |
+
angles < interval[1])
|
| 168 |
+
is_dirichlet |= (interval_found & active)
|
| 169 |
+
active &= ~interval_found
|
| 170 |
+
i += 1
|
| 171 |
+
return is_dirichlet
|
| 172 |
+
|
| 173 |
+
@dr.syntax
|
| 174 |
+
def boundary_interaction(self, points,
|
| 175 |
+
radius_fnc : callable = None, star_generation = True,
|
| 176 |
+
max_radius = Float(dr.inf), conf_numbers : list[UInt32] = [UInt32(0)]):
|
| 177 |
+
min_distance, boundary_point, is_dirichlet, nearest_dirichlet_d, nearest_dirichlet_p = self.get_nearest_distances(points, Bool(True))
|
| 178 |
+
|
| 179 |
+
if dr.hint(self.is_full_neumann, mode = "scalar"):
|
| 180 |
+
merge_dirichlet = Bool(False)
|
| 181 |
+
is_neumann = Bool(True)
|
| 182 |
+
nearest_dirichlet_d = Float(self.radius)
|
| 183 |
+
elif dr.hint(self.is_full_dirichlet, mode = "scalar"):
|
| 184 |
+
merge_dirichlet = Bool(False)
|
| 185 |
+
is_neumann = Bool(False)
|
| 186 |
+
else:
|
| 187 |
+
merge_dirichlet = (nearest_dirichlet_d < (5*dr.epsilon(Float)))
|
| 188 |
+
is_dirichlet |= merge_dirichlet
|
| 189 |
+
is_neumann = ~is_dirichlet
|
| 190 |
+
|
| 191 |
+
radius = nearest_dirichlet_d if radius_fnc is None else radius_fnc(nearest_dirichlet_d)
|
| 192 |
+
radius = dr.minimum(radius, max_radius)
|
| 193 |
+
boundary_dir = dr.normalize(boundary_point - points)
|
| 194 |
+
# boundary normal defined to the outside of the shape, be careful with this
|
| 195 |
+
boundary_normal = dr.normalize(boundary_point - self.origin) # be careful with inside outside cases
|
| 196 |
+
boundary_normal = -boundary_normal if self.inside else boundary_normal
|
| 197 |
+
is_epsilon_shell = ((min_distance < self.epsilon))
|
| 198 |
+
on_boundary = (is_neumann & (min_distance < 200 * dr.epsilon(Float)))
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# Set the dirichlet_values to the correct channels.
|
| 202 |
+
num_conf = len(conf_numbers)
|
| 203 |
+
nearest_dirichlet_val = dr.zeros(ArrayXf, shape = (num_conf, dr.width(points)))
|
| 204 |
+
if dr.hint(not self.is_full_neumann, mode = "scalar"):
|
| 205 |
+
if dr.hint(self.num_conf_d == 1, mode = 'scalar'):
|
| 206 |
+
dirichlet = self.dirichlet[0].get_value(boundary_point)
|
| 207 |
+
for i in range(num_conf):
|
| 208 |
+
nearest_dirichlet_val[i] = dirichlet
|
| 209 |
+
else:
|
| 210 |
+
for i in range(self.num_conf_d):
|
| 211 |
+
for j, conf in enumerate(conf_numbers):
|
| 212 |
+
nearest_dirichlet_val[j] = dr.select(i == conf,
|
| 213 |
+
self.dirichlet[i].get_value(boundary_point),
|
| 214 |
+
nearest_dirichlet_val[j])
|
| 215 |
+
|
| 216 |
+
is_far = min_distance > self.inf_distance
|
| 217 |
+
curvature = 1/self.radius
|
| 218 |
+
|
| 219 |
+
bi = BoundaryInfo(points, on_boundary, radius, min_distance, is_far, boundary_point, curvature, nearest_dirichlet_d,
|
| 220 |
+
nearest_dirichlet_val, nearest_dirichlet_p, boundary_dir, boundary_normal, is_dirichlet,
|
| 221 |
+
is_neumann, is_epsilon_shell, UInt32(0), UInt32(0))
|
| 222 |
+
|
| 223 |
+
if dr.hint(not self.is_full_dirichlet, mode = 'scalar'):
|
| 224 |
+
if dr.hint(star_generation, mode = 'scalar'):
|
| 225 |
+
bi = self.star_generation(bi)
|
| 226 |
+
return bi
|
| 227 |
+
|
| 228 |
+
def star_generation(self, bi):
|
| 229 |
+
bi.is_star = bi.is_n & (bi.r > bi.d)
|
| 230 |
+
# If we are very close to the boundary, we will stamp it to the boundary
|
| 231 |
+
diff_centers = bi.origin - self.origin
|
| 232 |
+
diff_dist = dr.norm(diff_centers)
|
| 233 |
+
# only works for strictly convex boundaries
|
| 234 |
+
angle_centers = correct_angle(dr.atan2(diff_centers[0], diff_centers[1]))
|
| 235 |
+
# cosine theorem
|
| 236 |
+
cos_alpha = (-dr.sqr(bi.r) + dr.sqr(self.radius) + dr.sqr(diff_dist)) / (2 * self.radius * diff_dist)
|
| 237 |
+
angle_diff = dr.acos(cos_alpha)
|
| 238 |
+
angle1 = correct_angle(angle_centers - angle_diff)
|
| 239 |
+
angle2 = correct_angle(angle_centers + angle_diff)
|
| 240 |
+
n1 = - Point2f(dr.sin(angle1), dr.cos(angle1))
|
| 241 |
+
n2 = - Point2f(dr.sin(angle2), dr.cos(angle2))
|
| 242 |
+
bi.x1 = self.origin - self.radius * n1
|
| 243 |
+
bi.x2 = self.origin - self.radius * n2
|
| 244 |
+
vec_c1 = bi.x1 - bi.origin
|
| 245 |
+
vec_c2 = bi.x2 - bi.origin
|
| 246 |
+
bi.angle1 = correct_angle(dr.atan2(vec_c1[0], vec_c1[1]))
|
| 247 |
+
bi.angle2 = correct_angle(dr.atan2(vec_c2[0], vec_c2[1]))
|
| 248 |
+
bi.angle1_adj = dr.copy(bi.angle1)
|
| 249 |
+
bi.angle2_adj = dr.copy(bi.angle2)
|
| 250 |
+
bi.gamma1 = angle1 - bi.angle1
|
| 251 |
+
bi.gamma2 = angle2 - bi.angle2
|
| 252 |
+
return bi
|
| 253 |
+
|
| 254 |
+
def closest_points(self, points):
|
| 255 |
+
vecs = points - self.origin
|
| 256 |
+
min_distance = dr.norm(vecs) - self.radius
|
| 257 |
+
angles = correct_angle(dr.atan2(vecs[0], vecs[1]))
|
| 258 |
+
boundary_points = self.origin + self.radius * Point2f(dr.sin(angles), dr.cos(angles))
|
| 259 |
+
min_distance *= -1 if self.inside else 1
|
| 260 |
+
return dr.abs(min_distance), angles, boundary_points
|
| 261 |
+
|
| 262 |
+
def get_closest_dist(self, points):
|
| 263 |
+
min_distance, _, _ =self.closest_points(points)
|
| 264 |
+
return min_distance
|
| 265 |
+
|
| 266 |
+
def get_distance_correction(self, points):
|
| 267 |
+
return mi.Float(1)
|
| 268 |
+
|
| 269 |
+
def inside_closed_surface(self, points : Point2f, L : Float, conf_numbers : list[UInt32] = None):
|
| 270 |
+
vecs = points - self.origin
|
| 271 |
+
return (dr.norm(vecs) <= self.radius), L
|
| 272 |
+
|
| 273 |
+
def inside_closed_surface_mask(self, points : Point2f):
|
| 274 |
+
vecs = points - self.origin
|
| 275 |
+
return (dr.norm(vecs) <= self.radius)
|
| 276 |
+
|
| 277 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 278 |
+
#self.dirichlet.get_opt_params(param_dict, opt_params)
|
| 279 |
+
#self.neumann.get_opt_params(param_dict, opt_params)
|
| 280 |
+
pass
|
| 281 |
+
|
| 282 |
+
def get_opt_params_shape(self, param_dict: dict, opt_params: list):
|
| 283 |
+
for key in opt_params:
|
| 284 |
+
vals = key.split(".")
|
| 285 |
+
boundary_name = vals[0]
|
| 286 |
+
boundary_type = vals[1]
|
| 287 |
+
param = vals[2]
|
| 288 |
+
if (param == "radius") and (boundary_type == "dirichlet") and (boundary_name == self.name):
|
| 289 |
+
param_dict[f"{self.name}.dirichlet.radius"] = self.radius
|
| 290 |
+
elif (param == "origin") and (boundary_type == "dirichlet") and (boundary_name == self.name):
|
| 291 |
+
param_dict[f"{self.name}.dirichlet.origin"] = self.origin
|
| 292 |
+
elif (boundary_name == self.name):
|
| 293 |
+
raise Exception(
|
| 294 |
+
f"CircleShape ({self.name}) does not have a parameter called \"{param}\"")
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def update(self, optimizer):
|
| 298 |
+
#self.dirichlet.update(optimizer)
|
| 299 |
+
#self.neumann.update(optimizer)
|
| 300 |
+
pass
|
| 301 |
+
def update_shape(self, optimizer):
|
| 302 |
+
for key in optimizer.keys():
|
| 303 |
+
vals = key.split(".")
|
| 304 |
+
name = vals[0]
|
| 305 |
+
type = vals[1]
|
| 306 |
+
param = vals[2]
|
| 307 |
+
if (name == self.name) & (param == "radius") & (type == "dirichlet"):
|
| 308 |
+
self.radius = optimizer[key]
|
| 309 |
+
elif (name == self.name) & (param == "origin") & (type == "dirichlet"):
|
| 310 |
+
self.origin = optimizer[key]
|
| 311 |
+
|
| 312 |
+
def zero_grad(self):
|
| 313 |
+
self.dirichlet.zero_grad()
|
| 314 |
+
self.neumann.zero_grad()
|
| 315 |
+
|
| 316 |
+
def zero_grad_shape(self):
|
| 317 |
+
if dr.grad_enabled(self.radius):
|
| 318 |
+
dr.set_grad(self.radius, 0.0)
|
| 319 |
+
if dr.grad_enabled(self.origin):
|
| 320 |
+
dr.set_grad(self.origin, 0)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def create_result_on_boundary(self, result, film_points, resolution=1024):
|
| 324 |
+
return create_circle_from_result(result, resolution=resolution)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def sketch_image(self, ax, bbox, resolution, channel = 1, image = None, color_factor = 0.8):
|
| 328 |
+
points = create_image_points(bbox, resolution, spp = 1, centered=True)
|
| 329 |
+
result = dr.select(self.inside_closed_surface_mask(points), 1.0, 0.0)
|
| 330 |
+
image_i, tensor = create_image_from_result(result=result, resolution = resolution)
|
| 331 |
+
|
| 332 |
+
image = np.zeros([resolution[0], resolution[1], 3]) if image is None else image
|
| 333 |
+
image[:,:,channel] += image_i[0] * color_factor
|
| 334 |
+
#image_b = self.get_boundary_image(bbox, resolution)
|
| 335 |
+
#image += image_b
|
| 336 |
+
ax.imshow(image)
|
| 337 |
+
ax.set_axis_off()
|
| 338 |
+
return image
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def sketch(self, ax, bbox, resolution, colors = ["red", "orange"], fill = False, sketch_center = False, lw = 3):
|
| 342 |
+
origin_s = point2sketch(self.origin, bbox, resolution)
|
| 343 |
+
origin_s = np.array([origin_s[0][0] - 0.5, origin_s[1][0] - 0.5])
|
| 344 |
+
if sketch_center:
|
| 345 |
+
ax.scatter(origin_s[0], origin_s[1], color = colors[0], s = 5)
|
| 346 |
+
return
|
| 347 |
+
radius_x, radius_y, radius = dist2sketch(self.radius, bbox, resolution)
|
| 348 |
+
radius_x = radius_x[0]
|
| 349 |
+
radius_y = radius_y[0]
|
| 350 |
+
angles1 = self.neumann_angles[0].numpy() * 180 / np.pi
|
| 351 |
+
angles2 = self.neumann_angles[1].numpy() * 180 / np.pi
|
| 352 |
+
sphere = patches.Ellipse(origin_s, radius_x * 2, radius_y * 2, linewidth= lw,
|
| 353 |
+
fill = fill, color = colors[0], label = self.name)
|
| 354 |
+
ax.add_patch(sphere)
|
| 355 |
+
for angle1, angle2 in zip(angles1, angles2):
|
| 356 |
+
neumann_arc = patches.Arc(origin_s, 2 * radius_x, 2 * radius_y, angle = -90, theta1=angle1, theta2=angle2, linewidth= lw, color=colors[1])
|
| 357 |
+
ax.add_patch(neumann_arc)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def create_boundary_points(self, distance: float, res: int, spp: int, discrete_points : bool = True):
|
| 362 |
+
with dr.suspend_grad():
|
| 363 |
+
distance = -distance if self.inside else distance
|
| 364 |
+
points = create_circle_points(
|
| 365 |
+
self.origin, self.radius + distance, res, spp, discrete_points=discrete_points)
|
| 366 |
+
normal_dir = dr.normalize(points - self.origin)
|
| 367 |
+
return points, points, normal_dir
|
| 368 |
+
|
| 369 |
+
def create_boundary_result(self, result, points = None, resolution = 256):
|
| 370 |
+
with dr.suspend_grad():
|
| 371 |
+
tensor, tensor_mi = create_circle_from_result(result, resolution)
|
| 372 |
+
return tensor, tensor_mi
|
| 373 |
+
|
| 374 |
+
def create_boundary_coefficient(self, tensor_mi, name = "boundary-val"):
|
| 375 |
+
def boundary_val(points, parameters):
|
| 376 |
+
resolution = dr.width(parameters["bval"].array)
|
| 377 |
+
vec = points - self.origin
|
| 378 |
+
angles = correct_angle(dr.atan2(vec[0], vec[1]))
|
| 379 |
+
angles = correct_angle(angles)
|
| 380 |
+
angles = dr.select(angles<0, angles + 2 * dr.pi, angles)
|
| 381 |
+
indices = angles / (2 * dr.pi) * resolution
|
| 382 |
+
index0 = UInt32(dr.floor(indices)) % resolution
|
| 383 |
+
index1 = (index0 + 1) % resolution
|
| 384 |
+
residual = indices - Float(index0)
|
| 385 |
+
vals0 = dr.gather(Float, parameters["bval"].array, index0)
|
| 386 |
+
vals1 = dr.gather(Float, parameters["bval"].array, index1)
|
| 387 |
+
return vals0 * (1-residual) + vals1 * residual
|
| 388 |
+
|
| 389 |
+
coeffs = []
|
| 390 |
+
for i in range(tensor_mi.shape[0]):
|
| 391 |
+
parameters = {}
|
| 392 |
+
parameters["bval"] = Float(tensor_mi[i])
|
| 393 |
+
coeffs.append(FunctionCoefficient(name, dict(parameters), boundary_val))
|
| 394 |
+
return coeffs
|
| 395 |
+
|
| 396 |
+
def set_normal_derivative(self, tensor_mi):
|
| 397 |
+
self.normal_derivatives = self.create_boundary_coefficient(tensor_mi, "normal-derivative")
|
| 398 |
+
return self.normal_derivatives
|
| 399 |
+
|
| 400 |
+
def jakobian_to_boundary(self, bi : BoundaryInfo, distance : Float):
|
| 401 |
+
return 1 + distance / self.radius
|
| 402 |
+
|
| 403 |
+
def get_normal_derivative(self, points : Point2f):
|
| 404 |
+
num_conf = len(self.normal_derivatives)
|
| 405 |
+
normal_ders = dr.zeros(ArrayXf, shape = [num_conf, dr.width(points)])
|
| 406 |
+
for i in range(num_conf):
|
| 407 |
+
normal_ders[i] = self.normal_derivatives[i].get_value(points)
|
| 408 |
+
return normal_ders
|
| 409 |
+
|
| 410 |
+
def get_max_intersection_dist(self, bi : BoundaryInfo):
|
| 411 |
+
return 2 * self.radius
|
| 412 |
+
|
| 413 |
+
def generate_sdf_grid(self, resolution, box_length = 2, box_center = [0,0],
|
| 414 |
+
wrapping = "clamp", interpolation = "cubic", redistance = True, high_res = 2048):
|
| 415 |
+
bbox = [[box_center[0] - box_length/2, box_center[1] - box_length/2],
|
| 416 |
+
[box_center[0] + box_length/2, box_center[1] + box_length/2]]
|
| 417 |
+
points = create_image_points(bbox = bbox, resolution = resolution, spp = 1, centered = True)
|
| 418 |
+
inside = self.inside_closed_surface_mask(points)
|
| 419 |
+
min_d, a, b = self.closest_points(points)
|
| 420 |
+
distance = dr.select(inside, -min_d, min_d)
|
| 421 |
+
image_np, image_mi = create_image_from_result(distance, resolution)
|
| 422 |
+
return SDFGrid(image_np[0], box_length, box_center, self.dirichlet, self.epsilon, self.inf_distance,
|
| 423 |
+
self.inside, self.name,
|
| 424 |
+
normal_derivative_dist= self.normal_derivative_dist, wrapping = wrapping, interpolation=interpolation,
|
| 425 |
+
redistance = redistance, high_res = high_res, low_res=resolution[0])
|
| 426 |
+
|
| 427 |
+
'''
|
| 428 |
+
def generate_sdf_grid(self, resolution, box_length = 2, box_center = [0,0],
|
| 429 |
+
wrapping = "clamp", interpolation = "cubic", redistance = True, high_res = 2048):
|
| 430 |
+
bbox = [[box_center[0] - box_length/2, box_center[1] - box_length/2],
|
| 431 |
+
[box_center[0] + box_length/2, box_center[1] + box_length/2]]
|
| 432 |
+
points, film_points = create_image_points(bbox = bbox, resolution = resolution, spp = 1, centered = True)
|
| 433 |
+
inside = self.inside_closed_surface(points)
|
| 434 |
+
min_d, a, b = self.closest_points(points)
|
| 435 |
+
distance = dr.select(inside, -min_d, min_d)
|
| 436 |
+
image_np, image_mi = create_image_from_result(distance, resolution)
|
| 437 |
+
return SDFGrid(image_np, box_length, box_center, self.dirichlet, self.epsilon, self.inf_distance, self.inf_boundary,
|
| 438 |
+
self.inside, self.name,
|
| 439 |
+
normal_derivative_dist= self.normal_derivative_dist, wrapping = wrapping, interpolation=interpolation,
|
| 440 |
+
redistance = redistance, high_res = high_res, low_res=resolution[0])
|
| 441 |
+
'''
|
| 442 |
+
|
| 443 |
+
def move_circle_fd(self, fd_step, type = "x"):
|
| 444 |
+
origin1 = [self.origin[0], self.origin[1]]
|
| 445 |
+
origin2 = [self.origin[0], self.origin[1]]
|
| 446 |
+
radius1 = self.radius[0]
|
| 447 |
+
radius2 = self.radius[0]
|
| 448 |
+
if type == "x":
|
| 449 |
+
origin1 = [origin1[0] + fd_step / 2, origin1[1]]
|
| 450 |
+
origin2 = [origin2[0] - fd_step / 2, origin2[1]]
|
| 451 |
+
elif type == "y":
|
| 452 |
+
origin1 = [origin1[0], origin1[1] + fd_step / 2]
|
| 453 |
+
origin2 = [origin2[0], origin2[1] - fd_step / 2]
|
| 454 |
+
elif type == "r":
|
| 455 |
+
radius1 = radius1 + fd_step/2
|
| 456 |
+
radius2 = radius2 - fd_step/2
|
| 457 |
+
else:
|
| 458 |
+
raise Exception("There is no such type.")
|
| 459 |
+
|
| 460 |
+
circle1 = CircleShape(origin1, radius1, dirichlet = self.dirichlet, neumann = self.neumann, epsilon = self.epsilon)
|
| 461 |
+
circle2 = CircleShape(origin2, radius2, dirichlet = self.dirichlet, neumann = self.neumann, epsilon = self.epsilon)
|
| 462 |
+
return circle1, circle2
|
| 463 |
+
|
data/PDE2D/BoundaryShape/circlewithelectrodes.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import drjit as dr
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PDE2D.Coefficient import *
|
| 5 |
+
from PDE2D.BoundaryShape import *
|
| 6 |
+
from PDE2D.utils import *
|
| 7 |
+
from PDE2D import ArrayXb, ArrayXu
|
| 8 |
+
from mitsuba import Point2i
|
| 9 |
+
import scipy
|
| 10 |
+
|
| 11 |
+
class CircleWithElectrodes(CircleShape):
|
| 12 |
+
def __init__(self, origin = [0.0, 0.0], radius = 1.0, name = "electrodeCircle", epsilon = 1e-5,
|
| 13 |
+
num_electrodes = 16, is_delta = False, electrode_length = 0.01,
|
| 14 |
+
injection_confs = [[0,1]], injected_current = 1.0, electrode_potentials = None,
|
| 15 |
+
offset_angle = 0.0, centered = False, fileset = None, injection_set = None, delete_injection = True):
|
| 16 |
+
self.name = name
|
| 17 |
+
super().__init__(origin, radius, dirichlet_map = np.array([False]), epsilon = epsilon, name = self.name)
|
| 18 |
+
if fileset is not None:
|
| 19 |
+
mat = scipy.io.loadmat(fileset)
|
| 20 |
+
range_exp = self.get_injection_range_file_all(fileset=fileset, injection_sets=injection_set)
|
| 21 |
+
self.measured_current = True
|
| 22 |
+
self.voltages_first = mat["Uel"].T[range_exp]
|
| 23 |
+
self.num_confs = self.voltages_first.shape[0]
|
| 24 |
+
self.num_electrodes = self.voltages_first.shape[1]
|
| 25 |
+
self.voltages_first = np.hstack([np.zeros([self.num_confs,1]), self.voltages_first])
|
| 26 |
+
self.voltages_first = self.voltages_first.cumsum(axis = 1)[:, :16]
|
| 27 |
+
self.currents = mat["CurrentPattern"].T[range_exp]
|
| 28 |
+
nonzeros = np.nonzero(self.currents)
|
| 29 |
+
if delete_injection:
|
| 30 |
+
self.voltages = self.voltages_first
|
| 31 |
+
self.voltages[self.currents!=0] = 0
|
| 32 |
+
self.voltages = self.voltages - (np.sum(self.voltages, axis = 1))[:,np.newaxis] / (num_electrodes - 2)
|
| 33 |
+
self.voltages[self.currents!=0] = 0
|
| 34 |
+
else:
|
| 35 |
+
self.voltages = self.voltages_first
|
| 36 |
+
self.voltages = self.voltages - (np.mean(self.voltages, axis = 1))[:,np.newaxis]
|
| 37 |
+
#self.voltages = self.voltages.astype(np.float32)
|
| 38 |
+
self.voltages_std = np.zeros(num_electrodes)
|
| 39 |
+
positive_inj = nonzeros[1][np.nonzero((self.currents[nonzeros] > 0).astype(np.int16) )]
|
| 40 |
+
negative_inj = nonzeros[1][np.nonzero((self.currents[nonzeros] < 0).astype(np.int16) )]
|
| 41 |
+
current_confs = np.vstack([positive_inj, negative_inj]).T
|
| 42 |
+
self.electrode_length = 0.025
|
| 43 |
+
self.injected_current = np.abs(self.currents[nonzeros][0])
|
| 44 |
+
self.injections = current_confs
|
| 45 |
+
self.injection_confs = Point2i(current_confs.T)
|
| 46 |
+
else:
|
| 47 |
+
self.num_electrodes = num_electrodes
|
| 48 |
+
|
| 49 |
+
if injection_set is None:
|
| 50 |
+
if injection_confs is not None:
|
| 51 |
+
self.injections = injection_confs
|
| 52 |
+
else:
|
| 53 |
+
raise Exception("Either specify an injection set or injection configuration.")
|
| 54 |
+
else:
|
| 55 |
+
self.injections = self.create_injection_set_all(injection_set, num_electrodes)
|
| 56 |
+
self.num_confs = len(self.injections)
|
| 57 |
+
self.injection_confs = Point2i(np.array(self.injections).T) # The first one is injected, the second one is received.
|
| 58 |
+
|
| 59 |
+
self.injected_current = injected_current
|
| 60 |
+
self.voltages = electrode_potentials
|
| 61 |
+
self.electrode_length = electrode_length
|
| 62 |
+
|
| 63 |
+
self.is_delta = is_delta
|
| 64 |
+
self.has_delta = is_delta
|
| 65 |
+
self.NEE = NEE.Special
|
| 66 |
+
self.has_continuous_neumann = not is_delta
|
| 67 |
+
self.el_diff_angle = 2 * dr.pi / self.num_electrodes
|
| 68 |
+
self.el_center_angles = correct_angle(offset_angle + dr.arange(Float, self.num_electrodes) * self.el_diff_angle)
|
| 69 |
+
|
| 70 |
+
self.normal_ders = {}
|
| 71 |
+
if not is_delta:
|
| 72 |
+
self.el_angle = self.electrode_length / self.radius
|
| 73 |
+
if not centered:
|
| 74 |
+
self.el_center_angles += self.el_angle/2
|
| 75 |
+
self.el_center_angles = correct_angle(self.el_center_angles)
|
| 76 |
+
el_ending1 = correct_angle(self.el_center_angles - self.el_angle/2)
|
| 77 |
+
el_ending2 = correct_angle(self.el_center_angles + self.el_angle/2)
|
| 78 |
+
self.el_endings = Point2f(el_ending1, el_ending2)
|
| 79 |
+
dr.make_opaque(self.el_endings)
|
| 80 |
+
|
| 81 |
+
dr.make_opaque(self.el_center_angles)
|
| 82 |
+
self.num_conf_n = self.num_confs
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def create_injection_set_all(self, injection_sets, num_electrodes):
|
| 86 |
+
sets = injection_sets.split("-")
|
| 87 |
+
final_set = []
|
| 88 |
+
for set in sets:
|
| 89 |
+
final_set.extend(self.create_injection_set(set, num_electrodes))
|
| 90 |
+
return final_set
|
| 91 |
+
|
| 92 |
+
def create_injection_set(self, injection_set, num_electrodes):
|
| 93 |
+
if injection_set == "adjacent":
|
| 94 |
+
set = [[i, (i + 1) % num_electrodes] for i in range(num_electrodes)]
|
| 95 |
+
elif injection_set[:4] == "skip":
|
| 96 |
+
try:
|
| 97 |
+
skip = int(injection_set[4:])
|
| 98 |
+
except:
|
| 99 |
+
print("You need to specify a number after skip.")
|
| 100 |
+
set = [[i, (i + skip + 1) % num_electrodes] for i in range(num_electrodes)]
|
| 101 |
+
elif injection_set[:7] == "against":
|
| 102 |
+
try:
|
| 103 |
+
against = int(injection_set[7:])
|
| 104 |
+
except:
|
| 105 |
+
print("You need to specify a number after against.")
|
| 106 |
+
set = [[against, (against + i) % num_electrodes] for i in range(num_electrodes - 1)]
|
| 107 |
+
else:
|
| 108 |
+
raise Exception("There is no such injection set.")
|
| 109 |
+
return set
|
| 110 |
+
|
| 111 |
+
def get_injection_range_file_all(self, fileset, injection_sets):
|
| 112 |
+
sets = injection_sets.split("-")
|
| 113 |
+
range_all = []
|
| 114 |
+
for set in sets:
|
| 115 |
+
range_all.extend(self.get_injection_range_file(fileset, set))
|
| 116 |
+
return range_all
|
| 117 |
+
|
| 118 |
+
def get_injection_range_file(self, fileset, injection_set : str):
|
| 119 |
+
if injection_set == "adjacent":
|
| 120 |
+
range_exp = [i for i in range(0, 16)]
|
| 121 |
+
elif injection_set == "skip1":
|
| 122 |
+
range_exp = [i for i in range(16, 32)]
|
| 123 |
+
elif injection_set == "skip2":
|
| 124 |
+
range_exp = [i for i in range(32, 48)]
|
| 125 |
+
elif injection_set == "skip3":
|
| 126 |
+
range_exp = [i for i in range(48, 64)]
|
| 127 |
+
elif injection_set == "against1":
|
| 128 |
+
range_exp = [i for i in range(64, 79)]
|
| 129 |
+
elif injection_set == "all":
|
| 130 |
+
range_exp = [i for i in range(0, 79)]
|
| 131 |
+
else:
|
| 132 |
+
raise Exception("There is no such injection!")
|
| 133 |
+
return range_exp
|
| 134 |
+
|
| 135 |
+
def get_injection_confs(self, allsets : str, vis_set, num_electrodes : int):
|
| 136 |
+
sets = allsets.split("-")
|
| 137 |
+
range_all = []
|
| 138 |
+
begin = 0
|
| 139 |
+
end = 0
|
| 140 |
+
found = False
|
| 141 |
+
for set in sets:
|
| 142 |
+
if set == vis_set:
|
| 143 |
+
set = self.create_injection_set(set, num_electrodes)
|
| 144 |
+
found = True
|
| 145 |
+
begin = len(range_all)
|
| 146 |
+
end = begin + len(set)
|
| 147 |
+
else:
|
| 148 |
+
range_all.extend(self.create_injection_set(set, num_electrodes))
|
| 149 |
+
if not found:
|
| 150 |
+
raise Exception("Such set does not exist")
|
| 151 |
+
else:
|
| 152 |
+
return [dr.opaque(UInt32, i, shape = (1)) for i in range(begin, end)]
|
| 153 |
+
|
| 154 |
+
@dr.syntax
|
| 155 |
+
def sampleNEE(self, bi : BoundaryInfo, sample : Float, conf_number : UInt32) -> tuple[Float, Float, Float, Point2f]:
|
| 156 |
+
d, n, pdf_r, sampled = (Float(0), Float(0), Float(0), Point2f(0))
|
| 157 |
+
if dr.hint(self.has_continuous_neumann, mode = 'scalar'):
|
| 158 |
+
d, n, pdf_r, sampled = (Float(0), Float(0), Float(0) , Point2f(0))
|
| 159 |
+
if sample < 0.5:
|
| 160 |
+
sample *= 2
|
| 161 |
+
d, n, pdf_r, sampled = self.sample_electrode(bi, sample, conf_number, injected = True)
|
| 162 |
+
else:
|
| 163 |
+
sample = 2 * (sample - 0.5)
|
| 164 |
+
d, n, pdf_r, sampled = self.sample_electrode(bi, sample, conf_number, injected = False)
|
| 165 |
+
return d, n, pdf_r/2, sampled
|
| 166 |
+
|
| 167 |
+
def get_point_neumann(self, bi : BoundaryInfo, conf_number : UInt32) -> tuple[list[Float], list[Float], list[Float], list[Point2f]]:
|
| 168 |
+
if self.has_delta:
|
| 169 |
+
d1, n1, pdf1_r, sampled1 = self.sample_electrode(bi, Float(0), conf_number, injected = True)
|
| 170 |
+
d2, n2, pdf2_r, sampled2 = self.sample_electrode(bi, Float(0), conf_number, injected = False)
|
| 171 |
+
return [d1, d2], [n1, n2], [pdf1_r, pdf2_r], [sampled1, sampled2]
|
| 172 |
+
|
| 173 |
+
def sample_electrode(self, bi : BoundaryInfo, sample : Float, conf_number : UInt32 , injected = True):
|
| 174 |
+
sign = 1 if injected else -1
|
| 175 |
+
electrode_num = 0 if injected else 1
|
| 176 |
+
# This function assumes there is only 2 electrode injection
|
| 177 |
+
current_conf = dr.gather(Point2i, self.injection_confs, conf_number)
|
| 178 |
+
diff1 = bi.x1 - self.origin
|
| 179 |
+
diff2 = bi.x2 - self.origin
|
| 180 |
+
star_angle1 = correct_angle(dr.atan2(diff1[0], diff1[1]))
|
| 181 |
+
star_angle2 = correct_angle(dr.atan2(diff2[0], diff2[1]))
|
| 182 |
+
if self.is_delta:
|
| 183 |
+
s = dr.gather(Float, self.el_center_angles, current_conf[electrode_num])
|
| 184 |
+
valid = self.inside_range(star_angle1, star_angle2, s)
|
| 185 |
+
neumann = dr.select(valid & bi.is_star, self.injected_current, 0) * sign
|
| 186 |
+
sampled_point = self.origin + self.radius * Point2f(dr.sin(s), dr.cos(s))
|
| 187 |
+
distance = dr.norm(sampled_point - bi.origin)
|
| 188 |
+
pdf_r = 2 * dr.pi * distance # actual pdf is "1", we multiply everything by 2 pi r, (cancels out Green's function computation)
|
| 189 |
+
else: # either one of the electrode ends are inside the star or the whole electrode covers the star.
|
| 190 |
+
el_end1 = dr.gather(Float, self.el_endings[0], current_conf[electrode_num])
|
| 191 |
+
el_end2 = dr.gather(Float, self.el_endings[1], current_conf[electrode_num])
|
| 192 |
+
el_end1_inside = self.inside_range(star_angle1, star_angle2, el_end1)
|
| 193 |
+
el_end2_inside = self.inside_range(star_angle1, star_angle2, el_end2)
|
| 194 |
+
el_active = bi.is_star & (el_end1_inside | el_end2_inside | self.inside_range(el_end1, el_end2, star_angle1))
|
| 195 |
+
sample_range1 = dr.select(el_end1_inside, el_end1, star_angle1)
|
| 196 |
+
sample_range2 = dr.select(el_end2_inside, el_end2, star_angle2)
|
| 197 |
+
current_flux = self.injected_current / self.electrode_length
|
| 198 |
+
neumann = dr.select(el_active, current_flux, 0) * sign
|
| 199 |
+
# We are going to sample an angle from the star center! So we find the range of angles first
|
| 200 |
+
sample_p_range1 = self.origin + self.radius * Point2f(dr.sin(sample_range1), dr.cos(sample_range1))
|
| 201 |
+
sample_p_range2 = self.origin + self.radius * Point2f(dr.sin(sample_range2), dr.cos(sample_range2))
|
| 202 |
+
range_vec1 = sample_p_range1 - bi.origin
|
| 203 |
+
range_vec2 = sample_p_range2 - bi.origin
|
| 204 |
+
angle1 = correct_angle(dr.atan2(range_vec1[0], range_vec1[1]))
|
| 205 |
+
angle2 = correct_angle(dr.atan2(range_vec2[0], range_vec2[1]))
|
| 206 |
+
bi.update_angles(angle1, angle2)
|
| 207 |
+
# We also need to change on_boundary value. We sample as if we are on the boundary only
|
| 208 |
+
# if the star origin is on the boundary and inside electrode!
|
| 209 |
+
angle_n = correct_angle(dr.atan2(bi.bn[0], bi.bn[1]))
|
| 210 |
+
star_origin_angle = correct_angle(angle_n + dr.pi)
|
| 211 |
+
on_boundary_electrode = bi.on_boundary & self.inside_range(el_end1, el_end2, star_origin_angle)
|
| 212 |
+
direction, pdf = bi.sample_neumann(sample, on_boundary_electrode)
|
| 213 |
+
# distance, sampled_point, normals = self.ray_intersect(bi.origin, direction, bi.on_boundary)
|
| 214 |
+
ri = self.ray_intersect(bi, direction)
|
| 215 |
+
pdf_r = pdf * dr.abs(dr.dot(direction, ri.normal)) * 2 * dr.pi # pdf with respect to area and also multiplied with 2 pi r
|
| 216 |
+
distance = ri.t
|
| 217 |
+
sampled_point = ri.intersected
|
| 218 |
+
return distance, neumann, pdf_r, sampled_point
|
| 219 |
+
|
| 220 |
+
def inside_range(self, angle1, angle2, angle):
|
| 221 |
+
electrode_start = angle1 > angle2
|
| 222 |
+
normal_case = (angle1 < angle) & (angle2 > angle)
|
| 223 |
+
start_case = (angle1 < angle) | (angle2 > angle)
|
| 224 |
+
return dr.select(electrode_start, start_case, normal_case)
|
| 225 |
+
|
| 226 |
+
def create_neumann_function(self, conf_numbers : list[UInt32]):
|
| 227 |
+
if self.is_delta:
|
| 228 |
+
raise NotImplementedError
|
| 229 |
+
confs = []
|
| 230 |
+
for conf_number in conf_numbers:
|
| 231 |
+
params = {}
|
| 232 |
+
params["conf"] = conf_number
|
| 233 |
+
def neumann_val(point, params):
|
| 234 |
+
injections = dr.gather(Point2i, self.injection_confs, params["conf"])
|
| 235 |
+
el1_ending1 = dr.gather(Float, self.el_endings[0], injections[0])
|
| 236 |
+
el1_ending2 = dr.gather(Float, self.el_endings[1], injections[0])
|
| 237 |
+
el2_ending1 = dr.gather(Float, self.el_endings[0], injections[1])
|
| 238 |
+
el2_ending2 = dr.gather(Float, self.el_endings[1], injections[1])
|
| 239 |
+
diff = point - self.origin
|
| 240 |
+
angle_point = correct_angle(dr.atan2(diff[0], diff[1]))
|
| 241 |
+
inside_el1 = self.inside_range(el1_ending1, el1_ending2, angle_point)
|
| 242 |
+
inside_el2 = self.inside_range(el2_ending1, el2_ending2, angle_point)
|
| 243 |
+
neumann_val = self.injected_current / self.electrode_length
|
| 244 |
+
result = dr.select(inside_el1, neumann_val, 0)
|
| 245 |
+
result = dr.select(inside_el2, -neumann_val, result)
|
| 246 |
+
return result
|
| 247 |
+
neumann_coeff = FunctionCoefficient(f"neumann-{conf_number}", params, neumann_val)
|
| 248 |
+
confs.append(neumann_coeff)
|
| 249 |
+
return confs
|
| 250 |
+
|
| 251 |
+
def create_electrode_points(self, spe, conf_numbers : list[UInt32], delete_injection : bool = True):
|
| 252 |
+
|
| 253 |
+
angles = Float(self.el_center_angles)
|
| 254 |
+
points = self.origin + self.radius * Point2f(dr.sin(angles), dr.cos(angles))
|
| 255 |
+
dr.make_opaque(points)
|
| 256 |
+
points = dr.repeat(points, spe)
|
| 257 |
+
|
| 258 |
+
electrode_nums = dr.zeros(ArrayXu, shape = (len(conf_numbers), self.num_electrodes))
|
| 259 |
+
active_confs = dr.zeros(ArrayXb, shape=(len(conf_numbers), self.num_electrodes))
|
| 260 |
+
for i, conf_number in enumerate(conf_numbers):
|
| 261 |
+
electrode_num = np.arange(self.num_electrodes)
|
| 262 |
+
active_conf = np.zeros(self.num_electrodes, dtype = bool)
|
| 263 |
+
if delete_injection:
|
| 264 |
+
current_conf = dr.gather(Point2i, self.injection_confs, conf_number)
|
| 265 |
+
electrode_num = np.delete(electrode_num, current_conf.numpy())
|
| 266 |
+
active_conf[electrode_num] = True
|
| 267 |
+
electrode_nums[i] = UInt32(electrode_num)
|
| 268 |
+
active_confs[i] = Bool(active_conf)
|
| 269 |
+
|
| 270 |
+
dr.make_opaque(active_confs)
|
| 271 |
+
active_confs = dr.repeat(active_confs, spe)
|
| 272 |
+
dr.make_opaque(electrode_nums)
|
| 273 |
+
return points, active_confs, electrode_nums
|
| 274 |
+
|
| 275 |
+
def sketch(self, ax, bbox, resolution, colors = ["orange", "green"], lw = 3, e_size = None):
|
| 276 |
+
origin_s = point2sketch(self.origin, bbox, resolution)
|
| 277 |
+
origin_s = np.array([origin_s[0][0], origin_s[1][0]])
|
| 278 |
+
radius_x, radius_y, radius = dist2sketch(self.radius, bbox, resolution)
|
| 279 |
+
radius_x = radius_x.numpy()[0]
|
| 280 |
+
radius_y = radius_y.numpy()[0]
|
| 281 |
+
sphere = patches.Ellipse(origin_s, radius_x * 2, radius_y * 2, linewidth= lw,
|
| 282 |
+
fill = False, color = colors[0], label = self.name)
|
| 283 |
+
ax.add_patch(sphere)
|
| 284 |
+
|
| 285 |
+
origin_s = point2sketch(self.origin, bbox, resolution)
|
| 286 |
+
origin_s = np.array([origin_s[0][0] - 0.5, origin_s[1][0] - 0.5])
|
| 287 |
+
radius_x, radius_y, radius = dist2sketch(self.radius, bbox, resolution)
|
| 288 |
+
radius_x = radius_x.numpy()[0]
|
| 289 |
+
radius_y = radius_y.numpy()[0]
|
| 290 |
+
if self.is_delta:
|
| 291 |
+
el_points = point2sketch(self.origin + self.radius * Point2f(dr.sin(self.el_center_angles), dr.cos(self.el_center_angles)),
|
| 292 |
+
bbox, resolution).numpy().squeeze()
|
| 293 |
+
if e_size is None:
|
| 294 |
+
ax.scatter(el_points[0,:] -0.5, el_points[1,:]-0.5, color = colors[1])
|
| 295 |
+
else:
|
| 296 |
+
ax.scatter(el_points[0,:] -0.5, el_points[1,:]-0.5, color = colors[1], s = e_size)
|
| 297 |
+
else:
|
| 298 |
+
angles1 = self.el_endings.numpy()[0, :] * 180 / np.pi
|
| 299 |
+
angles2 = self.el_endings.numpy()[1, :] * 180 / np.pi
|
| 300 |
+
for angle1, angle2 in zip(angles1, angles2):
|
| 301 |
+
neumann_arc = patches.Arc(origin_s, 2 * radius_x, 2 * radius_y, angle = -90, theta1=angle1,
|
| 302 |
+
theta2=angle2, linewidth = lw, color = colors[1])
|
| 303 |
+
ax.add_patch(neumann_arc)
|
| 304 |
+
|
| 305 |
+
def sketch_electrode_input(self, ax, bbox, resolution, conf_number = UInt32(0), color = "red"):
|
| 306 |
+
current_conf = dr.gather(Point2i, self.injection_confs, conf_number)
|
| 307 |
+
angle1 = dr.gather(Float, self.el_center_angles, current_conf[0])
|
| 308 |
+
angle2 = dr.gather(Float, self.el_center_angles, current_conf[1])
|
| 309 |
+
point1_start = point2sketch(self.origin + self.radius * 1.1 * Point2f(dr.sin(angle1), dr.cos(angle1)), bbox, resolution).numpy().squeeze()
|
| 310 |
+
point1_diff = dir2sketch(-0.08 * self.radius * Point2f(dr.sin(angle1), dr.cos(angle1)), bbox, resolution).numpy().squeeze()
|
| 311 |
+
point2_start = point2sketch(self.origin + self.radius * 1.02 * Point2f(dr.sin(angle2), dr.cos(angle2)), bbox, resolution).numpy().squeeze()
|
| 312 |
+
point2_diff = dir2sketch(self.radius * 0.08 * Point2f(dr.sin(angle2), dr.cos(angle2)), bbox, resolution).numpy().squeeze()
|
| 313 |
+
arrow_1 = patches.FancyArrow(point1_start[0] - 0.5, point1_start[1] - 0.5, point1_diff[0], point1_diff[1],
|
| 314 |
+
width=2 / 512 * resolution[0], length_includes_head=True, color = color)
|
| 315 |
+
arrow_2 = patches.FancyArrow(point2_start[0] - 0.5, point2_start[1] - 0.5, point2_diff[0], point2_diff[1],
|
| 316 |
+
width=2 / 512 * resolution[0], length_includes_head=True, color = color)
|
| 317 |
+
ax.add_patch(arrow_1)
|
| 318 |
+
ax.add_patch(arrow_2)
|
| 319 |
+
|
| 320 |
+
|
data/PDE2D/BoundaryShape/interaction.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import drjit as dr
|
| 2 |
+
from ..utils.helpers import *
|
| 3 |
+
from ..utils.sketch import *
|
| 4 |
+
from matplotlib import patches as patches
|
| 5 |
+
from mitsuba import Point2f, Vector2f, Bool, Float, UInt32
|
| 6 |
+
from PDE2D import ArrayXf
|
| 7 |
+
from ..Sampling import sample_star_direction, sample_sec_direction, pdf_sec_direction
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class BoundaryInfo:
|
| 11 |
+
DRJIT_STRUCT = {
|
| 12 |
+
'origin' : Point2f,
|
| 13 |
+
'on_boundary': Bool,
|
| 14 |
+
'r' : Float,
|
| 15 |
+
'd' : Float,
|
| 16 |
+
'is_far' : Bool,
|
| 17 |
+
'bpoint' : Point2f,
|
| 18 |
+
'dd' : Float,
|
| 19 |
+
'dval' : ArrayXf,
|
| 20 |
+
'dpoint' : Point2f,
|
| 21 |
+
'bdir' : Vector2f,
|
| 22 |
+
'bn' : Vector2f,
|
| 23 |
+
'is_d' : Bool,
|
| 24 |
+
'is_n' : Bool,
|
| 25 |
+
'is_e' : Bool,
|
| 26 |
+
'shape' : UInt32, # Index of the closest boundary
|
| 27 |
+
'd_shape' : UInt32, # Index of the closest dirichlet boundary
|
| 28 |
+
'is_star' : Bool,
|
| 29 |
+
'x1' : Point2f,
|
| 30 |
+
'x2' : Point2f,
|
| 31 |
+
'angle1' : Float,
|
| 32 |
+
'angle2' : Float,
|
| 33 |
+
'angle1_adj': Float,
|
| 34 |
+
'angle2_adj' : Float,
|
| 35 |
+
'gamma1' : Float,
|
| 36 |
+
'gamma2' : Float,
|
| 37 |
+
}
|
| 38 |
+
def __init__(self, origin = None, on_boundary = None, r = None, d = None, is_far = None,
|
| 39 |
+
bpoint = None, curvature = None,
|
| 40 |
+
dd = None, dval = None, dpoint = None, bdir = None, bn = None,
|
| 41 |
+
is_d = None, is_n = None, is_e = None, shape = None, d_shape = None,
|
| 42 |
+
is_star = None, x1 = None, x2 = None, angle1 = None, angle2 = None,
|
| 43 |
+
angle1_adj = None, angle2_adj = None, gamma1 = None, gamma2 = None):
|
| 44 |
+
self.origin = origin
|
| 45 |
+
self.on_boundary = on_boundary
|
| 46 |
+
self.r = r
|
| 47 |
+
self.d = d
|
| 48 |
+
self.is_far = is_far
|
| 49 |
+
self.bpoint = bpoint
|
| 50 |
+
self.curvature = curvature
|
| 51 |
+
self.dd = dd
|
| 52 |
+
self.dval = dval
|
| 53 |
+
self.dpoint = dpoint
|
| 54 |
+
self.bdir = bdir
|
| 55 |
+
self.bn = bn
|
| 56 |
+
self.is_d = is_d
|
| 57 |
+
self.is_n = is_n
|
| 58 |
+
self.is_e = is_e
|
| 59 |
+
self.shape = shape
|
| 60 |
+
self.d_shape = d_shape
|
| 61 |
+
self.is_star = is_star
|
| 62 |
+
self.x1 = x1
|
| 63 |
+
self.x2 = x2
|
| 64 |
+
self.angle1 = angle1
|
| 65 |
+
self.angle2 = angle2
|
| 66 |
+
self.angle1_adj = angle1_adj
|
| 67 |
+
self.angle2_adj = angle2_adj
|
| 68 |
+
self.gamma1 = gamma1
|
| 69 |
+
self.gamma2 = gamma2
|
| 70 |
+
|
| 71 |
+
def sample_recursive(self, sample : Float): # samples the full star
|
| 72 |
+
direction, pdf = sample_star_direction(sample, self.on_boundary & self.is_star, self.bn)
|
| 73 |
+
sphere_points = self.origin + self.r * direction
|
| 74 |
+
return direction, sphere_points, pdf
|
| 75 |
+
|
| 76 |
+
def pdf_recursive(self):
|
| 77 |
+
return dr.select(self.on_boundary & self.is_star, 1/dr.pi, 1/(2 * dr.pi))
|
| 78 |
+
|
| 79 |
+
@dr.syntax
|
| 80 |
+
def sample_brute_force(self, sample : Float, mis_rate : Float = Float(0.5), threshold : Float = Float(0.49 * dr.pi)):
|
| 81 |
+
"Applies a bit more sophisticated sampling scheme, mis between uniform and secant weighted distribution if we are near the boundary."
|
| 82 |
+
sampled_dir = Point2f(0)
|
| 83 |
+
pdf = Float(0)
|
| 84 |
+
if self.on_boundary | (self.d < (dr.abs(dr.rcp(self.curvature)) / 10)):
|
| 85 |
+
direction = dr.select(self.on_boundary, self.bn, self.bdir)
|
| 86 |
+
sec_mask = sample < mis_rate
|
| 87 |
+
sample = dr.select(sec_mask, sample / mis_rate, (sample - mis_rate) / (1.0-mis_rate))
|
| 88 |
+
if sec_mask:
|
| 89 |
+
sampled_dir = sample_sec_direction(sample, direction, threshold)
|
| 90 |
+
else:
|
| 91 |
+
sampled_dir, _, _ = self.sample_recursive(sample)
|
| 92 |
+
|
| 93 |
+
pdf_sec = pdf_sec_direction(sampled_dir, direction, threshold)
|
| 94 |
+
pdf_rec = self.pdf_recursive()
|
| 95 |
+
pdf = mis_rate * pdf_sec + (1.0-mis_rate) * pdf_rec
|
| 96 |
+
else:
|
| 97 |
+
sampled_dir, _, pdf = self.sample_recursive(sample)
|
| 98 |
+
|
| 99 |
+
return sampled_dir, pdf
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def sample_neumann(self, sample : Float, on_boundary : Bool): # samples only the boundary part
|
| 103 |
+
# inside case
|
| 104 |
+
angle_diff = correct_angle(self.angle2_adj - self.angle1_adj)
|
| 105 |
+
angle_in = correct_angle(self.angle1_adj + angle_diff * sample)
|
| 106 |
+
direction_in = Vector2f(dr.sin(angle_in), dr.cos(angle_in))
|
| 107 |
+
# on-boundary case
|
| 108 |
+
angle_n = correct_angle(dr.atan2(self.bn[0], self.bn[1]))
|
| 109 |
+
angle_n1 = dr.pi/2 - correct_angle(self.angle1_adj - angle_n)
|
| 110 |
+
angle_n2 = dr.pi/2 - correct_angle(angle_n - self.angle2_adj)
|
| 111 |
+
angle_sum = angle_n1 + angle_n2
|
| 112 |
+
angle_diff_b = dr.pi - angle_sum
|
| 113 |
+
angle_boundary = sample * angle_sum
|
| 114 |
+
angle_boundary += dr.select(angle_boundary > angle_n2, angle_diff_b, 0)
|
| 115 |
+
angle_boundary -= dr.pi/2
|
| 116 |
+
dir_n = Vector2f(dr.sin(angle_boundary), dr.cos(angle_boundary))
|
| 117 |
+
direction_boundary = to_world_direction(dir_n, self.bn)
|
| 118 |
+
direction = dr.select(on_boundary, direction_boundary, direction_in)
|
| 119 |
+
pdf = dr.select(on_boundary, 1/angle_sum, 1/(angle_diff))
|
| 120 |
+
return direction, pdf
|
| 121 |
+
|
| 122 |
+
def pdf_neumann():
|
| 123 |
+
pass
|
| 124 |
+
|
| 125 |
+
def update_angles(self, angle1, angle2):
|
| 126 |
+
# this is done if we do not want to sample the whole Neumann part of the star
|
| 127 |
+
self.angle1_adj = angle1
|
| 128 |
+
self.angle2_adj = angle2
|
| 129 |
+
|
| 130 |
+
def sketch_stars(self, ax, indices, bbox, resolution, color_star = "green", color_critical = "blue"):
|
| 131 |
+
actives = self.is_star.numpy()[indices]
|
| 132 |
+
origins = point2sketch(self.origin, bbox, resolution).numpy()[:, indices]
|
| 133 |
+
radii_x, radii_y, radii = dist2sketch(self.r, bbox, resolution)
|
| 134 |
+
radii_x = radii_x.numpy()[indices]
|
| 135 |
+
radii_y = radii_y.numpy()[indices]
|
| 136 |
+
x1s = point2sketch(self.x1, bbox, resolution).numpy()[:, indices]
|
| 137 |
+
x2s = point2sketch(self.x2, bbox, resolution).numpy()[:, indices]
|
| 138 |
+
angles1 = self.angle1.numpy()[indices] * 180 / np.pi
|
| 139 |
+
angles2 = self.angle2.numpy()[indices] * 180 / np.pi
|
| 140 |
+
for origin, radius_x, radius_y, x1, x2, angle1, angle2, active \
|
| 141 |
+
in zip(origins, radii_x, radii_y, x1s, x2s, angles1, angles2, actives):
|
| 142 |
+
if active:
|
| 143 |
+
#star = patches.Ellipse(origin,
|
| 144 |
+
# radius_x * 2, radius_y * 2,
|
| 145 |
+
# fill = False, color = color_star)
|
| 146 |
+
star = patches.Arc(origin, 2 * radius_x, 2 * radius_y, angle = -90,
|
| 147 |
+
theta1=angle2, theta2=angle1, linewidth=2.5, color=color_star)
|
| 148 |
+
center = patches.Ellipse(origin, 4, 4,
|
| 149 |
+
fill = True, color = color_star)
|
| 150 |
+
critical1 = patches.Ellipse([x1[0], x1[1]], 4, 4,
|
| 151 |
+
fill = True, color = color_critical)
|
| 152 |
+
critical2 = patches.Ellipse([x2[0], x2[1]], 4, 4,
|
| 153 |
+
fill = True, color = color_critical)
|
| 154 |
+
#ax.arrow(x1[0], x1[1], n1[0], n1[1], color = color_critical,
|
| 155 |
+
# edgecolor = "none", width = 0.03)
|
| 156 |
+
#ax.arrow(x2[0], x2[1], n2[0], n2[1], color = color_critical,
|
| 157 |
+
# edgecolor = "none", width = 0.03)
|
| 158 |
+
ax.add_patch(star)
|
| 159 |
+
ax.add_patch(center)
|
| 160 |
+
ax.add_patch(critical1)
|
| 161 |
+
ax.add_patch(critical2)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class RayInfo:
|
| 165 |
+
DRJIT_STRUCT = {
|
| 166 |
+
'origin' : Point2f,
|
| 167 |
+
'direction' : Vector2f,
|
| 168 |
+
't' : Float,
|
| 169 |
+
'intersected' : Point2f,
|
| 170 |
+
'normal' : Vector2f,
|
| 171 |
+
'is_dirichlet' : Bool,
|
| 172 |
+
'neumann' : ArrayXf # We want to get multiple neumann values at once.
|
| 173 |
+
}
|
| 174 |
+
def __init__(self, origin = None, direction = None, t = None, intersected = None, normal = None, is_dirichlet = None, neumann = None):
|
| 175 |
+
self.origin = origin
|
| 176 |
+
self.direction = direction
|
| 177 |
+
self.t = t
|
| 178 |
+
self.intersected = intersected
|
| 179 |
+
self.normal = normal
|
| 180 |
+
self.is_dirichlet = is_dirichlet
|
| 181 |
+
self.neumann = neumann
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
|
data/PDE2D/BoundaryShape/sdf_grid.py
ADDED
|
@@ -0,0 +1,491 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from .boundary_shape import *
|
| 3 |
+
from ..utils.helpers import *
|
| 4 |
+
from ..utils.sketch import *
|
| 5 |
+
from ..Coefficient import ConstantCoefficient
|
| 6 |
+
import skfmm
|
| 7 |
+
from scipy import optimize
|
| 8 |
+
from .interaction import *
|
| 9 |
+
|
| 10 |
+
class SDFGrid(Shape):
|
| 11 |
+
def __init__(self, tensor_np = np.zeros([16, 16]), box_length = 2.1, box_center = [0,0], dirichlet : list[Coefficient] = [],
|
| 12 |
+
epsilon=1e-5, inf_distance=10, inside = False, name = "boundary", type = "sdf",
|
| 13 |
+
normal_derivative_dist = 0.01, wrapping = "clamp", interpolation = "cubic", redistance = True,
|
| 14 |
+
translation = [0,0], low_res = None, high_res = 2048):
|
| 15 |
+
super().__init__(True, single_closed_shape=True, epsilon=epsilon,
|
| 16 |
+
inf_distance=inf_distance, inside = inside)
|
| 17 |
+
low_res = tensor_np.shape[0] if low_res is None else low_res
|
| 18 |
+
tensor_np = tensor_np.squeeze()
|
| 19 |
+
if not (tensor_np.shape[0] == tensor_np.shape[1]):
|
| 20 |
+
raise Exception("You need to specify a square image.")
|
| 21 |
+
self.name = name
|
| 22 |
+
self.res = low_res
|
| 23 |
+
self.resolution = [low_res, low_res]
|
| 24 |
+
self.high_res_factor = int(high_res / self.res)
|
| 25 |
+
self.res_high = high_res
|
| 26 |
+
self.type = type
|
| 27 |
+
self.box_center = mi.Point2f(box_center)
|
| 28 |
+
self.box_length = mi.Float(box_length)
|
| 29 |
+
self.bbox = [[box_center[0] - box_length/2, box_center[1] - box_length/2],
|
| 30 |
+
[box_center[0] + box_length/2, box_center[1] + box_length/2]]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
#self.dx = box_length / self.res
|
| 34 |
+
self.dx_high = box_length / self.res_high
|
| 35 |
+
#self.threshold = self.dx * 0.25
|
| 36 |
+
# SDF shape only supports dirichlet boundary conditions.
|
| 37 |
+
self.is_full_dirichlet = True
|
| 38 |
+
# Dirichlet Boundary Values
|
| 39 |
+
self.dirichlet = dirichlet
|
| 40 |
+
self.normal_derivative_dist = normal_derivative_dist
|
| 41 |
+
self.redistance = redistance
|
| 42 |
+
self.translation_x = mi.Float(translation[0])
|
| 43 |
+
self.translation_y = mi.Float(translation[1])
|
| 44 |
+
self.tensor = mi.TensorXf(tensor_np[..., np.newaxis])
|
| 45 |
+
|
| 46 |
+
dr.make_opaque(self.translation_x)
|
| 47 |
+
dr.make_opaque(self.translation_y)
|
| 48 |
+
dr.make_opaque(self.tensor)
|
| 49 |
+
self.wrapping = wrapping
|
| 50 |
+
self.interpolation = interpolation
|
| 51 |
+
|
| 52 |
+
if redistance:
|
| 53 |
+
self.tensor = self.redistance_tensor(self.tensor)
|
| 54 |
+
self.texture = self.update_texture(self.tensor)
|
| 55 |
+
dr.make_opaque(self.texture)
|
| 56 |
+
|
| 57 |
+
self.num_conf_d = len(dirichlet)
|
| 58 |
+
self.num_conf_n = 1
|
| 59 |
+
assert (self.num_conf_d == self.num_conf_n) or (self.num_conf_n == 1) or (self.num_conf_d == 1)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def redist(self):
|
| 63 |
+
self.tensor = self.redistance_tensor(self.tensor)
|
| 64 |
+
self.texture = self.update_texture(self.tensor)
|
| 65 |
+
|
| 66 |
+
def update_texture(self, tensor):
|
| 67 |
+
# Creating the texture!
|
| 68 |
+
wrap_mode = None
|
| 69 |
+
if self.wrapping == "clamp":
|
| 70 |
+
wrap_mode = dr.WrapMode.Clamp
|
| 71 |
+
elif self.wrapping == "mirror":
|
| 72 |
+
wrap_mode = dr.WrapMode.Mirror
|
| 73 |
+
elif self.wrapping == "repeat":
|
| 74 |
+
wrap_mode = dr.WrapMode.Repeat
|
| 75 |
+
else:
|
| 76 |
+
raise Exception("Such wrapping is not defined.")
|
| 77 |
+
|
| 78 |
+
texture = mi.Texture2f(
|
| 79 |
+
tensor, wrap_mode=wrap_mode, use_accel=False, migrate=False, filter_mode=dr.FilterMode.Linear)
|
| 80 |
+
return texture
|
| 81 |
+
|
| 82 |
+
def rasterize_tensor(self, res, texture):
|
| 83 |
+
resolution = [res, res]
|
| 84 |
+
points = create_image_points(self.bbox, resolution, spp = 1, centered = True)
|
| 85 |
+
vals = self.get_texture_value(points, texture)
|
| 86 |
+
image, _ = create_image_from_result(vals, resolution)
|
| 87 |
+
return image[0]
|
| 88 |
+
|
| 89 |
+
def get_texture_value(self, points: mi.Point2f, texture):
|
| 90 |
+
points_bbox = self.get_position(points)
|
| 91 |
+
if (self.interpolation == "cubic"):
|
| 92 |
+
texture_val = texture.eval_cubic(points_bbox)[0]
|
| 93 |
+
elif (self.interpolation == "linear"):
|
| 94 |
+
texture_val = texture.eval(points_bbox)[0]
|
| 95 |
+
else:
|
| 96 |
+
raise Exception(
|
| 97 |
+
f"There is no interpolation called \"{self.interpolation}\"")
|
| 98 |
+
return texture_val
|
| 99 |
+
|
| 100 |
+
def redistance_tensor(self, tensor):
|
| 101 |
+
texture_low = self.update_texture(tensor)
|
| 102 |
+
high_array = self.rasterize_tensor(self.res_high, texture_low)
|
| 103 |
+
high_array = skfmm.distance(high_array.astype(np.float64), dx = self.dx_high)
|
| 104 |
+
|
| 105 |
+
tensor_high = mi.TensorXf(high_array[..., np.newaxis])
|
| 106 |
+
texture_high = self.update_texture(tensor_high)
|
| 107 |
+
low_array = self.rasterize_tensor(self.res, texture_high)
|
| 108 |
+
tensor_low = mi.TensorXf(low_array[..., np.newaxis])
|
| 109 |
+
return tensor_low
|
| 110 |
+
|
| 111 |
+
def update(self, optimizer : mi.ad.Optimizer):
|
| 112 |
+
for key in optimizer.keys():
|
| 113 |
+
vals = key.split(".")
|
| 114 |
+
name = vals[0]
|
| 115 |
+
type = vals[1]
|
| 116 |
+
param = vals[2]
|
| 117 |
+
if (name == self.name) & (param == "tensor") & (type == "dirichlet"):
|
| 118 |
+
# Apply redistancing.
|
| 119 |
+
optimizer[key] = self.redistance_tensor(optimizer[key])
|
| 120 |
+
self.tensor = optimizer[key]
|
| 121 |
+
dr.make_opaque(self.tensor)
|
| 122 |
+
self.texture = self.update_texture(self.tensor)
|
| 123 |
+
|
| 124 |
+
if (name == self.name) & (param == "translation_x") & (type == "dirichlet"):
|
| 125 |
+
self.translation_x = optimizer[key]
|
| 126 |
+
dr.make_opaque(self.translation_x)
|
| 127 |
+
|
| 128 |
+
if (name == self.name) & (param == "translation_y") & (type == "dirichlet"):
|
| 129 |
+
self.translation_y = optimizer[key]
|
| 130 |
+
dr.make_opaque(self.translation_y)
|
| 131 |
+
|
| 132 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 133 |
+
self.dirichlet.get_opt_params(param_dict, opt_params)
|
| 134 |
+
|
| 135 |
+
def get_opt_params_shape(self, param_dict: dict, opt_params: list):
|
| 136 |
+
for key in opt_params:
|
| 137 |
+
vals = key.split(".")
|
| 138 |
+
boundary_name = vals[0]
|
| 139 |
+
boundary_type = vals[1]
|
| 140 |
+
param = vals[2]
|
| 141 |
+
if (param == "tensor") and (boundary_type == "dirichlet") and (boundary_name == self.name):
|
| 142 |
+
param_dict[f"{self.name}.dirichlet.tensor"] = self.tensor
|
| 143 |
+
elif (param == "translation_x") and (boundary_type == "dirichlet") and (boundary_name == self.name):
|
| 144 |
+
param_dict[f"{self.name}.dirichlet.translation_x"] = self.translation_x
|
| 145 |
+
elif (param == "translation_y") and (boundary_type == "dirichlet") and (boundary_name == self.name):
|
| 146 |
+
param_dict[f"{self.name}.dirichlet.translation_y"] = self.translation_y
|
| 147 |
+
elif (boundary_name == self.name):
|
| 148 |
+
raise Exception(
|
| 149 |
+
f"SDFGrid ({self.name}) does not have a parameter called \"{param}\"")
|
| 150 |
+
|
| 151 |
+
def get_position(self, points_ : mi.Point2f):
|
| 152 |
+
points = points_ - mi.Point2f(self.translation_x, self.translation_y)
|
| 153 |
+
"Get the new positions of the points normalized for the bbox."
|
| 154 |
+
x = (points[0] - self.bbox[0][0]) / (self.bbox[1][0] - self.bbox[0][0])
|
| 155 |
+
y = 1.0 - (points[1] - self.bbox[0][1]) / (self.bbox[1][1] - self.bbox[0][1])
|
| 156 |
+
return mi.Point2f(x, y)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def get_closest_dist(self, points : mi.Point2f):
|
| 160 |
+
dist = self.get_texture_value(points, self.texture)
|
| 161 |
+
return dist
|
| 162 |
+
|
| 163 |
+
@dr.syntax
|
| 164 |
+
def ray_intersect(self, bi : BoundaryInfo, direction, on_boundary : mi.Bool, max_step = 100):
|
| 165 |
+
with dr.suspend_grad():
|
| 166 |
+
dist = self.get_closest_dist(bi.origin)
|
| 167 |
+
close_mask = dist < 100 * dr.epsilon(mi.Float)
|
| 168 |
+
normal = self.get_normal(bi.origin)
|
| 169 |
+
point = dr.select(close_mask & (dr.dot(normal, direction) > 0),
|
| 170 |
+
bi.origin + normal * 200 * dr.epsilon(mi.Float),
|
| 171 |
+
bi.origin)
|
| 172 |
+
active = mi.Bool(True)
|
| 173 |
+
i = mi.UInt(0)
|
| 174 |
+
while (active & (i < max_step)):
|
| 175 |
+
i += 1
|
| 176 |
+
dist = self.get_closest_dist(point)
|
| 177 |
+
close_mask = dist < 10 * dr.epsilon(mi.Float)
|
| 178 |
+
far_mask = dist > self.inf_distance
|
| 179 |
+
active &= (~far_mask & ~close_mask)
|
| 180 |
+
point = dr.select(active, point + direction * mi.Point2f(dist, dist), point)
|
| 181 |
+
point = dr.select(far_mask, dr.inf, point)
|
| 182 |
+
point = dr.select(active, dr.inf, point)
|
| 183 |
+
t = dr.norm(point - bi.origin)
|
| 184 |
+
normals = self.get_normal(point)
|
| 185 |
+
|
| 186 |
+
return RayInfo(bi.origin, direction, t, point, normals, mi.Bool(True), mi.Float(0))
|
| 187 |
+
|
| 188 |
+
def get_distance_correction(self, points):
|
| 189 |
+
grad = self.get_grad(points)
|
| 190 |
+
return dr.norm(grad)
|
| 191 |
+
|
| 192 |
+
def get_grad_hessian(self, points : mi.Point2f):
|
| 193 |
+
# We are not using high res texture here as we only compute
|
| 194 |
+
# gradient at the boundary
|
| 195 |
+
dilate_x = self.bbox[1][0] - self.bbox[0][0]
|
| 196 |
+
dilate_y = self.bbox[1][1] - self.bbox[0][1]
|
| 197 |
+
points_bbox = self.get_position(points)
|
| 198 |
+
eval_result = self.texture.eval_cubic_hessian(points_bbox)
|
| 199 |
+
grad = eval_result[1][0] / mi.Point2f(dilate_x, -dilate_y)
|
| 200 |
+
hessian_ = eval_result[2][0]
|
| 201 |
+
hessian_x = hessian_[0, 0] / (dilate_x ** 2)
|
| 202 |
+
hessian_y = hessian_[1, 1] / (dilate_y ** 2)
|
| 203 |
+
hessian_xy = hessian_[0, 1] / (-dilate_x * dilate_y)
|
| 204 |
+
hessian = mi.Matrix2f([[hessian_x, hessian_xy],
|
| 205 |
+
[hessian_xy, hessian_y]])
|
| 206 |
+
return grad, hessian
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def get_grad(self, points: mi.Point2f):
|
| 210 |
+
dilate_x = self.bbox[1][0] - self.bbox[0][0]
|
| 211 |
+
dilate_y = self.bbox[1][1] - self.bbox[0][1]
|
| 212 |
+
points_bbox = self.get_position(points)
|
| 213 |
+
eval_result = self.texture.eval_cubic_grad(points_bbox)
|
| 214 |
+
grad = eval_result[1][0] / mi.Point2f(dilate_x, -dilate_y)
|
| 215 |
+
return mi.Point2f(grad)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def get_normal(self, points : mi.Point2f):
|
| 219 |
+
grad = self.get_grad(points)
|
| 220 |
+
return dr.normalize(grad)
|
| 221 |
+
|
| 222 |
+
def get_boundary_distance(self, points : mi.Point2f):
|
| 223 |
+
dist0 = self.get_texture_value(points, self.texture)
|
| 224 |
+
grad0 = self.get_grad(points)
|
| 225 |
+
norm0 = dr.norm(grad0)
|
| 226 |
+
normal_dir = dr.detach(grad0 / norm0)
|
| 227 |
+
|
| 228 |
+
# We first take a step in the sphere direction.
|
| 229 |
+
# Now we are most probably in the problematic region where norm of
|
| 230 |
+
# the gradient is not 1.
|
| 231 |
+
points1 = dr.detach(points - normal_dir * dist0)
|
| 232 |
+
dist1 = self.get_texture_value(points1, self.texture)
|
| 233 |
+
grad1 = self.get_grad(points1)
|
| 234 |
+
norm1 = dr.norm(grad1)
|
| 235 |
+
normal1 = dr.detach(grad1 / norm1)
|
| 236 |
+
|
| 237 |
+
# Now we will take another step.
|
| 238 |
+
points2 = dr.detach(points1 - normal1 * dist1)
|
| 239 |
+
dist2 = self.get_texture_value(points2, self.texture)
|
| 240 |
+
grad2 = self.get_grad(points2)
|
| 241 |
+
norm2 = dr.norm(grad2)
|
| 242 |
+
|
| 243 |
+
# Now we linearly approximate the norm of the gradient in the direction of the normal dir.
|
| 244 |
+
# We set the loc of points2 to 0 and points1 to dist1.
|
| 245 |
+
x2 = mi.Float(0)
|
| 246 |
+
x1 = mi.Float(dist1)
|
| 247 |
+
# The norm of the gradient along the line will be ax + b near the boundary.
|
| 248 |
+
a = (norm1 - norm2) / (x1 - x2)
|
| 249 |
+
b = norm2
|
| 250 |
+
|
| 251 |
+
# Now the texture value near the boundary in the normal direction is the integral of this.
|
| 252 |
+
# axˆ2/2 + bx + dist2
|
| 253 |
+
# Zero crossing value (the root) of this function is the following.
|
| 254 |
+
x_zero = (-b + dr.sqrt((dr.sqr(b) - 2 * a * dist2))) / a
|
| 255 |
+
return dist0 + dist1 - x_zero
|
| 256 |
+
|
| 257 |
+
# Now this value is wrong
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def boundary_interaction(self, points: mi.Point2f, radius_fnc : callable = None,
|
| 261 |
+
star_generation = False, max_radius = Float(dr.inf), conf_numbers : list[mi.UInt32] = [mi.UInt32(0)]) -> BoundaryInfo:
|
| 262 |
+
|
| 263 |
+
min_distance = self.get_closest_dist(points)
|
| 264 |
+
bpoints = mi.Point2f(points)
|
| 265 |
+
radius = mi.Float(min_distance)
|
| 266 |
+
if radius_fnc is not None:
|
| 267 |
+
radius = radius_fnc(radius)
|
| 268 |
+
radius = dr.minimum(radius, max_radius)
|
| 269 |
+
is_epsilon_shell = (min_distance < self.epsilon)
|
| 270 |
+
boundary_normal = self.get_normal(bpoints)
|
| 271 |
+
|
| 272 |
+
num_conf = len(conf_numbers)
|
| 273 |
+
dirichlet = dr.zeros(ArrayXf, shape = (num_conf, dr.width(points)))
|
| 274 |
+
|
| 275 |
+
if dr.hint(self.num_conf_d == 1, mode = 'scalar'):
|
| 276 |
+
dirichletval = self.dirichlet[0].get_value(bpoints)
|
| 277 |
+
for i in range(num_conf):
|
| 278 |
+
dirichlet[i] = dirichletval
|
| 279 |
+
else:
|
| 280 |
+
for i in range(self.num_conf_d):
|
| 281 |
+
for j, conf in enumerate(conf_numbers):
|
| 282 |
+
dirichlet[j] = dr.select(i == conf,
|
| 283 |
+
self.dirichlet[i].get_value(bpoints),
|
| 284 |
+
dirichlet[j])
|
| 285 |
+
|
| 286 |
+
curvature = self.compute_curvature(points)
|
| 287 |
+
return BoundaryInfo(points, mi.Bool(False), radius, min_distance, min_distance > self.inf_distance,
|
| 288 |
+
bpoints, curvature, min_distance, dirichlet, bpoints, -boundary_normal, boundary_normal,
|
| 289 |
+
mi.Bool(True), mi.Bool(False), is_epsilon_shell, UInt32(0), UInt32(0))
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
@dr.syntax
|
| 293 |
+
def get_touch_point(self, points, num_steps = 16, active_ = mi.Bool(True)):
|
| 294 |
+
with dr.suspend_grad():
|
| 295 |
+
active = Bool(active_)
|
| 296 |
+
touch_point = mi.Point2f(points)
|
| 297 |
+
d = mi.Float(dr.inf)
|
| 298 |
+
i = mi.UInt(0)
|
| 299 |
+
while (active & (i < num_steps)):
|
| 300 |
+
i+=1
|
| 301 |
+
d = mi.Float(self.get_closest_dist(touch_point))
|
| 302 |
+
active &= dr.abs(d) > dr.epsilon(mi.Float) * 10
|
| 303 |
+
normal = self.get_normal(touch_point)
|
| 304 |
+
touch_point = mi.Point2f(dr.select(active, touch_point - normal * mi.Point2f(d,d) * 0.99, touch_point))
|
| 305 |
+
return touch_point, d
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def compute_curvature(self, points):
|
| 309 |
+
grad, hessian = self.get_grad_hessian(points)
|
| 310 |
+
norm_grad = dr.norm(grad)
|
| 311 |
+
grad_ = mi.Point2f(-grad[1], grad[0])
|
| 312 |
+
return -(grad_ @ hessian @ grad_) / (norm_grad * dr.sqr(norm_grad))
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def get_boundary_indices(self, resolution):
|
| 316 |
+
x_length = self.bbox[1][0] - self.bbox[0][0]
|
| 317 |
+
y_length = self.bbox[1][1] - self.bbox[0][1]
|
| 318 |
+
dx = x_length / resolution[0]
|
| 319 |
+
dy = y_length / resolution[1]
|
| 320 |
+
x, y = dr.meshgrid(dr.arange(mi.Float, resolution[0]),
|
| 321 |
+
dr.arange(mi.Float, resolution[1]), indexing='xy')
|
| 322 |
+
|
| 323 |
+
film_points = mi.Point2f(x, y)
|
| 324 |
+
p = mi.Point2f(self.bbox[0][0], self.bbox[1][1]) + film_points / mi.Point2f(resolution) * mi.Point2f(x_length, -y_length)
|
| 325 |
+
p_x = p + mi.Point2f(dx, 0)
|
| 326 |
+
p_y = p + mi.Point2f(0, -dy)
|
| 327 |
+
p_xy = p + mi.Point2f(dx, -dy)
|
| 328 |
+
|
| 329 |
+
p_pos = self.get_closest_dist(p) > 0
|
| 330 |
+
p_x_pos = self.get_closest_dist(p_x) > 0
|
| 331 |
+
p_y_pos = self.get_closest_dist(p_y) > 0
|
| 332 |
+
p_xy_pos = self.get_closest_dist(p_xy) > 0
|
| 333 |
+
|
| 334 |
+
non_boundary_mask = (p_pos & p_x_pos & p_y_pos & p_xy_pos) | (~p_pos & ~p_x_pos & ~p_y_pos & ~p_xy_pos)
|
| 335 |
+
boundary_mask = ~non_boundary_mask
|
| 336 |
+
boundary_mask_np = boundary_mask.numpy()
|
| 337 |
+
film_points_np = film_points.numpy().astype(np.int16).T
|
| 338 |
+
return mi.Point2f((film_points_np[boundary_mask_np].T).astype(np.float32))
|
| 339 |
+
|
| 340 |
+
def create_boundary_points(self, distance: float, res: int, spp: int, discrete_points : bool = True, seed : int = 42):
|
| 341 |
+
with dr.suspend_grad():
|
| 342 |
+
resolution = [res, res]
|
| 343 |
+
film_points = self.get_boundary_indices(resolution)
|
| 344 |
+
film_points = dr.repeat(film_points, spp) + mi.Point2f(0.5, 0.5)
|
| 345 |
+
|
| 346 |
+
if not discrete_points:
|
| 347 |
+
sampler = mi.load_dict({'type': 'independent'})
|
| 348 |
+
sampler.seed(seed, dr.width(film_points))
|
| 349 |
+
film_points_ = film_points + sampler.next_2d() - 1/2
|
| 350 |
+
else:
|
| 351 |
+
film_points_ = film_points
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
points_ = (mi.Point2f(self.bbox[0][0], self.bbox[1][1]) +
|
| 355 |
+
film_points_ / mi.Point2f(resolution) *
|
| 356 |
+
(mi.Point2f(self.bbox[1][0], self.bbox[0][1]) - mi.Point2f(self.bbox[0][0], self.bbox[1][1])))
|
| 357 |
+
|
| 358 |
+
boundary_points, d = self.get_touch_point(points_)
|
| 359 |
+
normal_dir = self.get_normal(boundary_points)
|
| 360 |
+
points = boundary_points + mi.Point2f(distance, distance) * normal_dir
|
| 361 |
+
return points, points_, normal_dir
|
| 362 |
+
|
| 363 |
+
def create_boundary_result(self, result, points = None, res = 256):
|
| 364 |
+
if points is None:
|
| 365 |
+
raise Exception("Specify the points corresponding to the estimates in result.")
|
| 366 |
+
with dr.suspend_grad():
|
| 367 |
+
resolution = [res, res]
|
| 368 |
+
i2, i1 = get_position_bbox(points, self.bbox)
|
| 369 |
+
i2 = dr.minimum(mi.UInt(resolution[1] * i2), resolution[1] - 1)
|
| 370 |
+
i1 = dr.minimum(mi.UInt(resolution[0] * i1), resolution[0] - 1)
|
| 371 |
+
|
| 372 |
+
dim = 1 if result.ndim == 1 else result.shape[0]
|
| 373 |
+
tensor = dr.zeros(mi.TensorXf, shape = (dim, resolution[0], resolution[1]))
|
| 374 |
+
index = dr.zeros(mi.TensorXu, shape = (resolution[0], resolution[1]))
|
| 375 |
+
n = resolution[0] * resolution[1]
|
| 376 |
+
dr.scatter_add(index.array, mi.UInt(1), i1 * resolution[1] + i2)
|
| 377 |
+
#if dim == 1:
|
| 378 |
+
# dr.scatter_add(tensor.array, i1 * resolution[1] + i2, result)
|
| 379 |
+
for i in range(dim):
|
| 380 |
+
dr.scatter_add(tensor.array, result[i], i * n + i1 * resolution[1] + i2)
|
| 381 |
+
|
| 382 |
+
index = dr.select(index.array == 0, 1, index.array)
|
| 383 |
+
index = dr.reshape(mi.TensorXu, index, shape = (resolution[0], resolution[1]))
|
| 384 |
+
tensor /= index
|
| 385 |
+
return tensor.numpy(), tensor
|
| 386 |
+
|
| 387 |
+
def create_boundary_coefficient(self, tensor_mi, name = "boundary-val"):
|
| 388 |
+
coeffs = []
|
| 389 |
+
for i in range(tensor_mi.shape[0]):
|
| 390 |
+
coeffs.append(TextureCoefficient(name, self.bbox, tensor_mi[i].numpy().squeeze(), interpolation = "nearest"))
|
| 391 |
+
return coeffs
|
| 392 |
+
|
| 393 |
+
def set_normal_derivative(self, tensor_mi, name = "normal-derivative"):
|
| 394 |
+
self.normal_derivatives = self.create_boundary_coefficient(tensor_mi, name = "normal-derivative")
|
| 395 |
+
return self.normal_derivatives
|
| 396 |
+
|
| 397 |
+
def get_normal_derivative(self, points : Point2f):
|
| 398 |
+
#points_, _ = self.get_touch_point(points)
|
| 399 |
+
num_conf = len(self.normal_derivatives)
|
| 400 |
+
normal_ders = dr.zeros(ArrayXf, shape = [num_conf, dr.width(points)])
|
| 401 |
+
for i in range(num_conf):
|
| 402 |
+
normal_ders[i] = self.normal_derivatives[i].get_value(points)
|
| 403 |
+
return normal_ders
|
| 404 |
+
|
| 405 |
+
def jakobian_to_boundary(self, bi : BoundaryInfo, distance = None, max_distance : mi.Float = dr.inf):
|
| 406 |
+
distance = self.normal_derivative_dist if distance is None else distance
|
| 407 |
+
distance = dr.minimum(distance, max_distance)
|
| 408 |
+
comp_points = dr.detach(bi.bpoint + bi.bn * distance)
|
| 409 |
+
distance = self.get_closest_dist(comp_points)
|
| 410 |
+
curvature = self.compute_curvature(dr.detach(bi.bpoint))
|
| 411 |
+
return 1 - distance * curvature
|
| 412 |
+
|
| 413 |
+
def sketch_image(self, ax, bbox, resolution, image = None, channel = 1, color_factor = 0.6):
|
| 414 |
+
points = create_image_points(bbox, resolution, spp = 1, centered=True)
|
| 415 |
+
result = dr.select(self.get_closest_dist(points) < 0, 1.0, 0.0)
|
| 416 |
+
image_i, tensor = create_image_from_result(result=result, resolution = resolution)
|
| 417 |
+
|
| 418 |
+
image = np.zeros([resolution[0], resolution[1], 3]) if image is None else image
|
| 419 |
+
image[:,:,channel] = image_i * 0.6
|
| 420 |
+
#image_b = self.get_boundary_image(bbox, resolution)
|
| 421 |
+
#image += image_b
|
| 422 |
+
ax.imshow(image * color_factor)
|
| 423 |
+
ax.set_axis_off()
|
| 424 |
+
return image
|
| 425 |
+
|
| 426 |
+
def get_boundary_image(self, bbox, resolution, channel = 0):
|
| 427 |
+
indices = self.get_boundary_indices(bbox, resolution)
|
| 428 |
+
image = np.zeros([resolution[0], resolution[1], 3])
|
| 429 |
+
image[indices[:,1], indices[:,0], channel] += 1
|
| 430 |
+
#ax.imshow(image)
|
| 431 |
+
return image
|
| 432 |
+
|
| 433 |
+
def inside_closed_surface(self, points, L):
|
| 434 |
+
return self.get_closest_dist(points) < 0, L
|
| 435 |
+
|
| 436 |
+
def inside_closed_surface_mask(self, points):
|
| 437 |
+
return self.get_closest_dist(points) < 0
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def get_boundary_polyline(self, start = [0,0], step = 0.01):
|
| 441 |
+
points = []
|
| 442 |
+
point, d = self.get_touch_point(mi.Point2f(start))
|
| 443 |
+
points.append(point.numpy())
|
| 444 |
+
first = True
|
| 445 |
+
while True:
|
| 446 |
+
normal = self.get_normal(mi.Point2f(points[-1]))
|
| 447 |
+
tangent = mi.Point2f(normal[1], -normal[0])
|
| 448 |
+
if first:
|
| 449 |
+
tangent_first = mi.Point2f(tangent)
|
| 450 |
+
next_point = mi.Point2f(points[-1]) + tangent * step
|
| 451 |
+
next_point, d = self.get_touch_point(next_point)
|
| 452 |
+
if (not first) and (dr.norm(next_point - point)[0] < 1.1 * step) and dr.dot(dr.normalize(next_point - point), tangent_first)[0] < 0.1:
|
| 453 |
+
break
|
| 454 |
+
else:
|
| 455 |
+
points.append(next_point.numpy())
|
| 456 |
+
first = False
|
| 457 |
+
points = np.array(points).squeeze()
|
| 458 |
+
self.polyline = mi.Point2f(points.T)
|
| 459 |
+
return points
|
| 460 |
+
|
| 461 |
+
def sketch_boundary_polyline(self, ax, bbox, resolution, esize = 0.2):
|
| 462 |
+
points = self.polyline.numpy().T
|
| 463 |
+
sketch_points = []
|
| 464 |
+
xscale = bbox[1][0] - bbox[0][0]
|
| 465 |
+
yscale = bbox[1][1] - bbox[0][1]
|
| 466 |
+
pointsx = (points[:, 0]-bbox[0][0])/xscale*resolution[1]
|
| 467 |
+
pointsy = resolution[0] - (points[:, 1]-bbox[0][1])/yscale*resolution[0]
|
| 468 |
+
pointsx = np.append(pointsx, pointsx[0])
|
| 469 |
+
pointsy = np.append(pointsy, pointsy[0])
|
| 470 |
+
sketch_points = np.vstack([pointsx, pointsy])
|
| 471 |
+
ax.plot(sketch_points[0,:], sketch_points[1,:], zorder = 0)
|
| 472 |
+
ax.scatter(sketch_points[0,0], sketch_points[1,0], color = "red", zorder = 1, s = 0.1)
|
| 473 |
+
return np.array(sketch_points).T
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def vis_images(self, bbox, resolution = [1024, 1024], spp = 16):
|
| 477 |
+
points = create_image_points(bbox, resolution = resolution, spp = spp, centered = False)
|
| 478 |
+
d = self.get_closest_dist(points)
|
| 479 |
+
crossing = dr.select(d<0, 1.0, 0.0)
|
| 480 |
+
grad = self.get_grad(points)
|
| 481 |
+
norm_grad = dr.norm(grad)
|
| 482 |
+
|
| 483 |
+
d_im, _ = create_image_from_result(d, resolution)
|
| 484 |
+
crossing_im, _ = create_image_from_result(crossing, resolution)
|
| 485 |
+
gradx_im, _ = create_image_from_result(grad[0], resolution)
|
| 486 |
+
grady_im, _ = create_image_from_result(grad[1], resolution)
|
| 487 |
+
normgrad_im, _ = create_image_from_result(norm_grad, resolution)
|
| 488 |
+
return d_im[0], crossing_im[0], gradx_im[0], grady_im[0], normgrad_im[0]
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
|
data/PDE2D/BoundaryShape/sdf_utils.py
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import drjit as dr
|
| 3 |
+
import mitsuba as mi
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
from ..Coefficient import TextureCoefficient
|
| 6 |
+
from PDE2D.utils.sketch import *
|
| 7 |
+
from PDE2D.Solver import *
|
| 8 |
+
from .boundary_shape import *
|
| 9 |
+
import skfmm
|
| 10 |
+
from .sdf_grid import *
|
| 11 |
+
import matplotlib.gridspec as gridspec
|
| 12 |
+
import matplotlib.ticker as ticker
|
| 13 |
+
from PDE2D.utils.common import *
|
| 14 |
+
|
| 15 |
+
def disable_ticks(ax):
|
| 16 |
+
"""Disable ticks around plot (useful for displaying images)"""
|
| 17 |
+
ax.axes.get_xaxis().set_ticklabels([])
|
| 18 |
+
ax.axes.get_yaxis().set_ticklabels([])
|
| 19 |
+
ax.axes.get_xaxis().set_ticks([])
|
| 20 |
+
ax.axes.get_yaxis().set_ticks([])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def disable_border(ax):
|
| 24 |
+
"""Disable border around plot"""
|
| 25 |
+
ax.spines['top'].set_visible(False)
|
| 26 |
+
ax.spines['right'].set_visible(False)
|
| 27 |
+
ax.spines['bottom'].set_visible(False)
|
| 28 |
+
ax.spines['left'].set_visible(False)
|
| 29 |
+
|
| 30 |
+
def get_image_shape(image_name, image_center, image_length_x, sdf_res, sdf_center, sdf_length, square = False, high_res = 2048):
|
| 31 |
+
image = plt.imread(image_name)
|
| 32 |
+
image = image[...,:3].sum(axis = 2)/3
|
| 33 |
+
ratio = image.shape[0] / image.shape[1]
|
| 34 |
+
image_length_y = image_length_x if square else image_length_x * ratio
|
| 35 |
+
image[image > 0.5] = 1
|
| 36 |
+
image[image<0.5] = -1
|
| 37 |
+
image_bbox = [[image_center[0] - image_length_x/2, image_center[1] - image_length_y/2],
|
| 38 |
+
[image_center[0] + image_length_x/2, image_center[1] + image_length_y/2]]
|
| 39 |
+
bbox = [[sdf_center[0] - sdf_length/2, sdf_center[1] - sdf_length/2],
|
| 40 |
+
[sdf_center[0] + sdf_length/2, sdf_center[1] + sdf_length/2]]
|
| 41 |
+
tex = TextureCoefficient("a", image_bbox, image)
|
| 42 |
+
res_high = [high_res, high_res]
|
| 43 |
+
upsample = int(high_res / sdf_res)
|
| 44 |
+
points = create_image_points(bbox = bbox, resolution = res_high,
|
| 45 |
+
spp = 1, centered = True)
|
| 46 |
+
vals = tex.get_value(points)
|
| 47 |
+
image, _= create_image_from_result(vals, resolution = res_high)
|
| 48 |
+
image = skfmm.distance(image, dx = sdf_length/high_res)
|
| 49 |
+
image = image[int(upsample/2-1)::upsample, int(upsample/2-1)::upsample]
|
| 50 |
+
return SDFGrid(image, box_length = sdf_length, box_center = sdf_center, redistance = False)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_intersection_tensor(shape1 : Shape, shape2 : Shape, resolution, bbox):
|
| 54 |
+
points = create_image_points(bbox, resolution, spp = 1, centered = True)
|
| 55 |
+
vals1 = shape1.get_closest_dist(points)
|
| 56 |
+
vals2 = shape2.get_closest_dist(points)
|
| 57 |
+
new = dr.maximum(vals1, vals2)
|
| 58 |
+
image, _ = create_image_from_result(new, resolution)
|
| 59 |
+
return image
|
| 60 |
+
|
| 61 |
+
def visualize1(bbox, resolution, sdf1, sdf2, bpoints = None, name1 = "Old", name2 = "Optimized", res_angle = 32, max = None):
|
| 62 |
+
d1, c1, gx1, gy1, ng1 = sdf1.vis_images(bbox = bbox, resolution = resolution)
|
| 63 |
+
d2, c2, gx2, gy2, ng2 = sdf2.vis_images(bbox = bbox, resolution = resolution)
|
| 64 |
+
fig, ax = plt.subplots(4, 3, figsize = (13, 16))
|
| 65 |
+
ax[0][0].set_title(name1)
|
| 66 |
+
ax[0][1].set_title(name2)
|
| 67 |
+
ax[0][2].set_title("Difference")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# distance
|
| 71 |
+
ax[0][0].set_ylabel("Distance")
|
| 72 |
+
d_range = get_common_range(d1, d2)
|
| 73 |
+
plot_image(d1, ax[0][0], input_range = d_range)
|
| 74 |
+
plot_image(d2, ax[0][1], input_range = d_range)
|
| 75 |
+
plot_image(np.abs(d1 - d2), ax[0][2], input_range = [None, max])
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# grad_norm
|
| 79 |
+
ax[1][0].set_ylabel("|Grad|")
|
| 80 |
+
ng_range = get_common_range(ng1, ng2)
|
| 81 |
+
plot_image(ng1, ax[1][0], input_range = ng_range)
|
| 82 |
+
plot_image(ng2, ax[1][1], input_range = ng_range)
|
| 83 |
+
plot_image(ng1 - ng2, ax[1][2])
|
| 84 |
+
|
| 85 |
+
# modified grad_norm
|
| 86 |
+
ax[2][0].set_ylabel("||grad|-1|")
|
| 87 |
+
ng1_modified = ng1.copy()
|
| 88 |
+
ng2_modified = ng2.copy()
|
| 89 |
+
#ng1_modified[d1 < -0.1] = np.nan
|
| 90 |
+
#ng2_modified[d2 < -0.1] = np.nan
|
| 91 |
+
ng1_modified = np.abs(ng1_modified - 1)
|
| 92 |
+
ng2_modified = np.abs(ng2_modified - 1)
|
| 93 |
+
ng_modified_range = get_common_range(ng1_modified, ng2_modified)
|
| 94 |
+
plot_image(ng1_modified, ax[2][0], input_range = ng_modified_range)
|
| 95 |
+
plot_image(ng2_modified, ax[2][1], input_range = ng_modified_range)
|
| 96 |
+
plot_image(ng1_modified - ng2_modified, ax[2][2])
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# grad direction
|
| 100 |
+
ax[3][2].set_axis_off()
|
| 101 |
+
ax[3,0].set_ylabel("Direction Grad")
|
| 102 |
+
|
| 103 |
+
gx1_tex = TextureCoefficient("gx1", bbox, gx1, "nearest")
|
| 104 |
+
gx2_tex = TextureCoefficient("gx2", bbox, gx2, "nearest")
|
| 105 |
+
gy1_tex = TextureCoefficient("gy1", bbox, gy1, "nearest")
|
| 106 |
+
gy2_tex = TextureCoefficient("gy2", bbox, gy2, "nearest")
|
| 107 |
+
|
| 108 |
+
plot_image(c1, ax[3][0])
|
| 109 |
+
plot_image(c2, ax[3][1])
|
| 110 |
+
|
| 111 |
+
xlength = bbox[1][0] - bbox[0][0]
|
| 112 |
+
ylength = bbox[1][1] - bbox[0][1]
|
| 113 |
+
scale = mi.Point2f(xlength/res_angle, ylength/res_angle)
|
| 114 |
+
|
| 115 |
+
points = create_image_points(bbox, resolution = [res_angle, res_angle], spp = 1, centered = True)
|
| 116 |
+
|
| 117 |
+
dx1 = dr.normalize(mi.Point2f(gx1_tex.get_value(points), gy1_tex.get_value(points))) * scale * 0.48
|
| 118 |
+
dx2 = dr.normalize(mi.Point2f(gx2_tex.get_value(points), gy2_tex.get_value(points))) * scale * 0.48
|
| 119 |
+
|
| 120 |
+
points_sketch = point2sketch(points, bbox, resolution = resolution).numpy().T
|
| 121 |
+
dir1_sketch = dir2sketch(dx1, bbox, resolution = resolution).numpy().T
|
| 122 |
+
dir2_sketch = dir2sketch(dx2, bbox, resolution = resolution).numpy().T
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
for point, dir1, dir2 in zip(points_sketch, dir1_sketch, dir2_sketch):
|
| 127 |
+
ax[3][0].arrow(point[0], point[1], dir1[0], dir1[1])
|
| 128 |
+
ax[3][1].arrow(point[0], point[1], dir2[0], dir2[1])
|
| 129 |
+
|
| 130 |
+
if bpoints is not None:
|
| 131 |
+
bpoints_sketch = point2sketch(bpoints, bbox, resolution).numpy()
|
| 132 |
+
for aa in ax:
|
| 133 |
+
for a in aa:
|
| 134 |
+
a.scatter(bpoints_sketch[0] - 0.5, bpoints_sketch[1] - 0.5, s = 0.4, color ="white")
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def plot_shape_sdf(out_boundary, in_boundary, ax, bbox, resolution, linewidth = 3, e_size = 5):
|
| 138 |
+
image = in_boundary.sketch_image(ax, bbox = bbox, resolution = resolution, channel = 2)
|
| 139 |
+
black_region = image.sum(axis = 2) < 0.1
|
| 140 |
+
image[black_region] = 1
|
| 141 |
+
ax.imshow(image)
|
| 142 |
+
ax.axis("on")
|
| 143 |
+
out_boundary.sketch(ax, bbox = bbox, resolution = resolution, lw = linewidth, e_size = e_size)
|
| 144 |
+
|
| 145 |
+
def visualize2(wos, bbox, curvature_distance = 0.0,
|
| 146 |
+
resolution = [1024, 1024], num_points = 10, step = 0.03, spp = 18,
|
| 147 |
+
distances = None, color_points = "green", colors = None, lw = 1, e_size = 2, image_width = 3.36):
|
| 148 |
+
|
| 149 |
+
fig = plt.figure(figsize= (image_width, image_width))
|
| 150 |
+
pad1 = 3
|
| 151 |
+
pad2 = 3
|
| 152 |
+
s = 3
|
| 153 |
+
imsize= 20
|
| 154 |
+
g = gridspec.GridSpec(2 * imsize + pad2 + s, 2 * imsize + pad1 + s, figure = fig, wspace = 0, hspace=0)
|
| 155 |
+
ax = fig.add_subplot(g[:,:])
|
| 156 |
+
disable_ticks(ax)
|
| 157 |
+
plt.setp(ax.spines.values(), color="white")
|
| 158 |
+
ax1 = fig.add_subplot(g[pad1 : pad1 + imsize, pad2 : pad2 + imsize])
|
| 159 |
+
ax2 = fig.add_subplot(g[pad1 : pad1 + imsize, pad2 + imsize + s : pad2 + 2 * imsize + s])
|
| 160 |
+
ax3 = fig.add_subplot(g[pad1 + s + imsize : pad1 + 2 * imsize + s, pad2 : pad2 + imsize])
|
| 161 |
+
ax4 = fig.add_subplot(g[pad1 + imsize + s : pad1 + 2 * imsize + s, pad2 + imsize + s : pad2 + 2 * imsize + s])
|
| 162 |
+
#fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2,2,figsize = (8,8))
|
| 163 |
+
plot_shape_sdf(wos.input.shape.out_boundary, wos.input.shape.in_boundaries[0], ax1, bbox, resolution, linewidth=lw, e_size=e_size)
|
| 164 |
+
points_polyline = wos.input.shape.in_boundaries[0].get_boundary_polyline(step = step)
|
| 165 |
+
sketch_points = wos.input.shape.in_boundaries[0].sketch_boundary_polyline(ax1, bbox, resolution, esize = e_size)
|
| 166 |
+
sketch_points_plot = sketch_points[::num_points]
|
| 167 |
+
disable_border(ax1)
|
| 168 |
+
disable_ticks(ax1)
|
| 169 |
+
|
| 170 |
+
indices = np.arange(dr.width(wos.input.shape.in_boundaries[0].polyline))
|
| 171 |
+
normal = wos.input.shape.in_boundaries[0].get_normal(wos.input.shape.in_boundaries[0].polyline)
|
| 172 |
+
points_curvature = wos.input.shape.in_boundaries[0].polyline + curvature_distance * normal
|
| 173 |
+
curvature = wos.input.shape.in_boundaries[0].compute_curvature(points_curvature).numpy()
|
| 174 |
+
ax2.plot(indices, curvature, label = f"Curvature")
|
| 175 |
+
|
| 176 |
+
spp = 2 ** spp
|
| 177 |
+
distances = [1e-2, 5e-2, 1e-1] if distances is None else distances
|
| 178 |
+
colors = ["cyan", "green", "blue"] if colors is None else colors
|
| 179 |
+
points_normalders = []
|
| 180 |
+
range_all = [np.nan, -np.nan]
|
| 181 |
+
for distance, color in zip(distances, colors):
|
| 182 |
+
print(f"distance = {distance}")
|
| 183 |
+
normal = wos.input.shape.in_boundaries[0].get_normal(wos.input.shape.in_boundaries[0].polyline)
|
| 184 |
+
points_normal_der = wos.input.shape.in_boundaries[0].polyline + distance * normal
|
| 185 |
+
points_normalders.append(points_normal_der)
|
| 186 |
+
points_polyline = dr.repeat(points_normal_der, spp)
|
| 187 |
+
normals = dr.repeat(normal, spp)
|
| 188 |
+
L, _ = wos.solve(conf_numbers = [mi.UInt32(0)], points_in = points_polyline, derivative_dir = normals)
|
| 189 |
+
result = dr.block_sum(L, spp) / spp
|
| 190 |
+
result = result.numpy()
|
| 191 |
+
|
| 192 |
+
result_corrected = result * (1 - distance * curvature)
|
| 193 |
+
|
| 194 |
+
range_ = get_common_range(result_corrected, result)
|
| 195 |
+
range_all = get_common_range(np.array(range_all), range_)
|
| 196 |
+
|
| 197 |
+
ax3.plot(indices, result[0], label = f"t = {distance}", color = color, linewidth = 1)
|
| 198 |
+
ax4.plot(indices, result_corrected[0], label = f"t = {distance}", color = color, linewidth = 1)
|
| 199 |
+
|
| 200 |
+
range_all[0] -= 1
|
| 201 |
+
range_all[1] += 1
|
| 202 |
+
ax3.set_ylim(range_all)
|
| 203 |
+
ax4.set_ylim(range_all)
|
| 204 |
+
|
| 205 |
+
#ax2.legend()
|
| 206 |
+
ax3.legend(framealpha = 1)
|
| 207 |
+
ax4.legend(framealpha = 1)
|
| 208 |
+
|
| 209 |
+
ax2.axhline(0, lw = 0.5, color = "black")
|
| 210 |
+
ax3.axhline(0, lw = 0.5, color = "black")
|
| 211 |
+
ax4.axhline(0, lw = 0.5, color = "black")
|
| 212 |
+
|
| 213 |
+
ax2.axvline(0, lw = 0.5, color = "red")
|
| 214 |
+
ax3.axvline(0, lw = 0.5, color = "red")
|
| 215 |
+
ax4.axvline(0, lw = 0.5, color = "red")
|
| 216 |
+
ax2.set_xticks([])
|
| 217 |
+
ax3.set_xticks([])
|
| 218 |
+
ax4.set_xticks([])
|
| 219 |
+
|
| 220 |
+
ax2.set_xlim([-1, sketch_points.shape[0]])
|
| 221 |
+
ax3.set_xlim([-1, sketch_points.shape[0]])
|
| 222 |
+
ax4.set_xlim([-1, sketch_points.shape[0]])
|
| 223 |
+
|
| 224 |
+
for i in range(num_points, sketch_points.shape[0], num_points):
|
| 225 |
+
ax2.axvline(i, lw = 0.5, color = color_points)
|
| 226 |
+
ax3.axvline(i, lw = 0.5, color = color_points)
|
| 227 |
+
ax4.axvline(i, lw = 0.5, color = color_points)
|
| 228 |
+
pad = 4
|
| 229 |
+
ax1.set_title("(a) Shape", pad = pad, fontsize = DEFAULT_FONTSIZE_SMALL)
|
| 230 |
+
ax3.set_title("(c) Normal derivatives", pad = pad, fontsize = DEFAULT_FONTSIZE_SMALL)
|
| 231 |
+
ax2.set_title(f"(b) Curvatures", pad = pad, fontsize = DEFAULT_FONTSIZE_SMALL)
|
| 232 |
+
ax4.set_title("(d) Corrected normal deriv.", pad = pad, fontsize = DEFAULT_FONTSIZE_SMALL)
|
| 233 |
+
|
| 234 |
+
ax1.scatter(sketch_points_plot[0,0], sketch_points_plot[0,1], color = "red", zorder = 1, s = e_size)
|
| 235 |
+
ax1.scatter(sketch_points_plot[1:,0], sketch_points_plot[1:,1], color = color_points, zorder = 1, s = e_size)
|
| 236 |
+
|
| 237 |
+
#fig.tight_layout()
|
| 238 |
+
|
| 239 |
+
def visualize_grad(sdf, bbox, resolution, bpoints = None, res_angle = 32, range_d =None, range = 1e-2, norm =True, cmap = "coolwarm", col_width_image = 3.36):
|
| 240 |
+
xlength = bbox[1][0] - bbox[0][0]
|
| 241 |
+
ylength = bbox[1][1] - bbox[0][1]
|
| 242 |
+
d, c, gx, gy, ng = sdf.vis_images(bbox = bbox, resolution = resolution)
|
| 243 |
+
imsize = 250
|
| 244 |
+
num_images = 3
|
| 245 |
+
cbar_offset = 15
|
| 246 |
+
pre_cbar_offset = 10
|
| 247 |
+
post_cbar_offset = 60
|
| 248 |
+
total_cbar_offset = cbar_offset + pre_cbar_offset + post_cbar_offset
|
| 249 |
+
scale = col_width_image / (num_images * imsize + 2 * total_cbar_offset)
|
| 250 |
+
cbar_b = 1
|
| 251 |
+
fig = plt.figure(figsize = ((num_images * imsize + 2 * total_cbar_offset) * scale, imsize * scale))
|
| 252 |
+
g = gridspec.GridSpec(imsize, imsize * num_images + total_cbar_offset * 2, wspace = 0.0, hspace=0.0)
|
| 253 |
+
ax = fig.add_subplot(g[:,:])
|
| 254 |
+
disable_ticks(ax)
|
| 255 |
+
plt.setp(ax.spines.values(), color="white")
|
| 256 |
+
ax1 = fig.add_subplot(g[:, :imsize])
|
| 257 |
+
ax2 = fig.add_subplot(g[:, imsize + total_cbar_offset :2 * imsize + total_cbar_offset])
|
| 258 |
+
ax3 = fig.add_subplot(g[:, 2 * imsize + 2 * total_cbar_offset :3 * imsize + 2 * total_cbar_offset])
|
| 259 |
+
|
| 260 |
+
ax1_cbar = fig.add_subplot(g[cbar_b: -cbar_b, imsize + pre_cbar_offset : imsize + pre_cbar_offset + cbar_offset])
|
| 261 |
+
ax2_cbar = fig.add_subplot(g[cbar_b: -cbar_b, 2 * imsize + total_cbar_offset + pre_cbar_offset : 2*imsize+ total_cbar_offset+ cbar_offset + pre_cbar_offset])
|
| 262 |
+
|
| 263 |
+
if range_d is not None:
|
| 264 |
+
im1 = plot_image(d, ax1, input_range = [-range_d, range_d], colorbar= False, cmap = cmap)
|
| 265 |
+
else:
|
| 266 |
+
im1 = plot_image(d, ax1, colorbar = False, cmap = cmap)
|
| 267 |
+
if norm:
|
| 268 |
+
im2 = plot_image(ng, ax2, input_range = [1-range, 1+range], cmap = cmap, colorbar = False)
|
| 269 |
+
else:
|
| 270 |
+
im2 = plot_image(np.abs(ng-1), ax2, input_range = [0, range], colorbar = False)
|
| 271 |
+
|
| 272 |
+
cbar1 = plt.colorbar(im1, cax = ax1_cbar)
|
| 273 |
+
tick_locator = ticker.MaxNLocator(nbins=3)
|
| 274 |
+
cbar1.locator = tick_locator
|
| 275 |
+
cbar1.formatter.set_powerlimits((0, 0))
|
| 276 |
+
cbar1.ax.yaxis.set_offset_position('left')
|
| 277 |
+
cbar1.update_ticks()
|
| 278 |
+
cbar2 = plt.colorbar(im2, cax = ax2_cbar)
|
| 279 |
+
tick_locator = ticker.MaxNLocator(nbins=3)
|
| 280 |
+
cbar2.locator = tick_locator
|
| 281 |
+
cbar2.formatter.set_powerlimits((0, 0))
|
| 282 |
+
cbar2.ax.yaxis.set_offset_position('right')
|
| 283 |
+
cbar2.update_ticks()
|
| 284 |
+
#if bpoints is not None:
|
| 285 |
+
# mask = (bpoints[0] > bbox[0][0]) & (bpoints[0] < bbox[1][0]) & (bpoints[1] > bbox[0][1]) & (bpoints[1] < bbox[1][1])
|
| 286 |
+
# mask = mask.numpy().squeeze()
|
| 287 |
+
# if len(mask) > 0:
|
| 288 |
+
# bpoints_np = bpoints.numpy().squeeze()
|
| 289 |
+
# bpoints_ = mi.Point2f(bpoints_np[mask])
|
| 290 |
+
# bpoints_sketch = point2sketch(bpoints_, bbox, resolution).numpy()
|
| 291 |
+
# ax2.scatter(bpoints_sketch[:,0], bpoints_sketch[:,1], s = ps, color = "green")
|
| 292 |
+
# ax1.scatter(bpoints_sketch[:,0], bpoints_sketch[:,1], s = ps, color = "white")
|
| 293 |
+
|
| 294 |
+
x = (np.arange(resolution[0]) + 0.5) / 1024 * d.shape[0]
|
| 295 |
+
y = (np.arange(resolution[1]) + 0.5) / 1024 * d.shape[0]
|
| 296 |
+
X, Y = np.meshgrid(x, y)
|
| 297 |
+
# Creating contour plot
|
| 298 |
+
ax1.contour(X, Y, d, colors = ["white"], lw = 5, levels = np.array([0]))
|
| 299 |
+
ax2.contour(X, Y, d, colors = ["white"], lw = 5, levels = np.array([0]))
|
| 300 |
+
|
| 301 |
+
gx_tex = TextureCoefficient("gx", bbox, gx, "nearest")
|
| 302 |
+
gy_tex = TextureCoefficient("gy", bbox, gy, "nearest")
|
| 303 |
+
plot_image(-2 * c+1, ax3, colorbar = False, cmap = "coolwarm", input_range = [-2, 2])
|
| 304 |
+
scale = mi.Point2f(xlength/res_angle, ylength/res_angle)
|
| 305 |
+
points = create_image_points(bbox, resolution = [res_angle, res_angle], spp = 1, centered = True)
|
| 306 |
+
dx = dr.normalize(mi.Point2f(gx_tex.get_value(points), gy_tex.get_value(points))) * scale * 0.48
|
| 307 |
+
|
| 308 |
+
points_sketch = point2sketch(points, bbox, resolution = resolution).numpy().T
|
| 309 |
+
dir_sketch = dir2sketch(dx, bbox, resolution = resolution).numpy().T
|
| 310 |
+
|
| 311 |
+
for point, dir, in zip(points_sketch, dir_sketch):
|
| 312 |
+
ax3.arrow(point[0], point[1], dir[0], dir[1])
|
| 313 |
+
pad = 4
|
| 314 |
+
ax1.set_title("$d(x)$", fontsize = DEFAULT_FONTSIZE_SMALL, pad = pad)
|
| 315 |
+
if norm:
|
| 316 |
+
ax2.set_title("$||\\nabla d(x)||$", fontsize = DEFAULT_FONTSIZE_SMALL, pad = pad)
|
| 317 |
+
else:
|
| 318 |
+
ax2.set_title("$||\\nabla d(x)|| - 1|$", fontsize = DEFAULT_FONTSIZE_SMALL, pad = pad)
|
| 319 |
+
ax3.set_title("Direction", fontsize = DEFAULT_FONTSIZE_SMALL, pad = pad)
|
| 320 |
+
#fig.tight_layout()
|
| 321 |
+
|
| 322 |
+
|
data/PDE2D/BoundaryShape/shape_utils.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .bezierquadratic import *
|
| 2 |
+
from PDE2D.Coefficient import *
|
| 3 |
+
|
| 4 |
+
def load_bunny(scale = 1, dirichlet = None, neumann = None, all_dirichlet = False, epsilon = 1e-5, conf : int = 1):
|
| 5 |
+
points = np.array([[ 36.0, -28.6],
|
| 6 |
+
[ 49.9, -25.2],
|
| 7 |
+
[ 66.6, -38.7],
|
| 8 |
+
[ 67.2, -47.3],
|
| 9 |
+
[ 71.2, -52.8],
|
| 10 |
+
[ 65.1, -55.7],
|
| 11 |
+
[ 61.7, -56.0],
|
| 12 |
+
[ 40.7, -57.0],
|
| 13 |
+
[ 14.2, -56.8],
|
| 14 |
+
[ 12.0, -54.3],
|
| 15 |
+
[ 14.3, -50.4],
|
| 16 |
+
[ 13.6, -44.4],
|
| 17 |
+
[ 12.9, -41.0],
|
| 18 |
+
[ 11.0, -40.0],
|
| 19 |
+
[ 9.0, -38.9],
|
| 20 |
+
[ 8.2, -29.0],
|
| 21 |
+
[ 18.3, -20.9],
|
| 22 |
+
[ 25.5, -9.2],
|
| 23 |
+
[ 32.7, -5.2],
|
| 24 |
+
[ 33.5, -13.0],
|
| 25 |
+
[ 29.9, -20.5],
|
| 26 |
+
[ 31.1, -27.6]]) / 38 + np.array([-1 ,0.9])
|
| 27 |
+
|
| 28 |
+
normals = np.array([[ -3.3, 9.3],
|
| 29 |
+
[ 0.4, 10.0],
|
| 30 |
+
[ 7.5, -0.0],
|
| 31 |
+
[ 1.5, 4.6],
|
| 32 |
+
[ 5.8, -1.4],
|
| 33 |
+
[ -1.6, -6.1],
|
| 34 |
+
[ 1.8, -6.2],
|
| 35 |
+
[ 0.0, -6.2],
|
| 36 |
+
[ -0.8, -5.0],
|
| 37 |
+
[ -4.1, 3.9],
|
| 38 |
+
[ -7.3, 0.5],
|
| 39 |
+
[ -7.3, -0.8],
|
| 40 |
+
[ -2.0, -1.0],
|
| 41 |
+
[ -0.4, -3.0],
|
| 42 |
+
[ -3.1, -4.5],
|
| 43 |
+
[ -7.3, 5.0],
|
| 44 |
+
[ -3.2, 8.1],
|
| 45 |
+
[ -8.3, 1.9],
|
| 46 |
+
[ 0.2, 1.0],
|
| 47 |
+
[ 7.9, -3.8],
|
| 48 |
+
[ 7.9, -2.8],
|
| 49 |
+
[ 4.7, 5.1]])
|
| 50 |
+
|
| 51 |
+
if conf == 1:
|
| 52 |
+
dirichlet_map = np.array([False,
|
| 53 |
+
False,
|
| 54 |
+
True,
|
| 55 |
+
True,
|
| 56 |
+
False,
|
| 57 |
+
True,
|
| 58 |
+
True,
|
| 59 |
+
False,
|
| 60 |
+
True,
|
| 61 |
+
True,
|
| 62 |
+
True,
|
| 63 |
+
True,
|
| 64 |
+
True,
|
| 65 |
+
True,
|
| 66 |
+
True,
|
| 67 |
+
False,
|
| 68 |
+
True,
|
| 69 |
+
False,
|
| 70 |
+
False,
|
| 71 |
+
True,
|
| 72 |
+
True,
|
| 73 |
+
True])
|
| 74 |
+
|
| 75 |
+
elif conf == 2:
|
| 76 |
+
dirichlet_map = np.array([True,
|
| 77 |
+
True,
|
| 78 |
+
False,
|
| 79 |
+
True,
|
| 80 |
+
True,
|
| 81 |
+
True,
|
| 82 |
+
False,
|
| 83 |
+
False,
|
| 84 |
+
True,
|
| 85 |
+
True,
|
| 86 |
+
True,
|
| 87 |
+
True,
|
| 88 |
+
True,
|
| 89 |
+
True,
|
| 90 |
+
False,
|
| 91 |
+
False,
|
| 92 |
+
True,
|
| 93 |
+
False,
|
| 94 |
+
False,
|
| 95 |
+
False,
|
| 96 |
+
True,
|
| 97 |
+
True])
|
| 98 |
+
elif conf == 3:
|
| 99 |
+
dirichlet_map = np.array([True,
|
| 100 |
+
True,
|
| 101 |
+
True,
|
| 102 |
+
True,
|
| 103 |
+
False,
|
| 104 |
+
True,
|
| 105 |
+
True,
|
| 106 |
+
True,
|
| 107 |
+
False,
|
| 108 |
+
True,
|
| 109 |
+
True,
|
| 110 |
+
True,
|
| 111 |
+
True,
|
| 112 |
+
True,
|
| 113 |
+
False,
|
| 114 |
+
True,
|
| 115 |
+
True,
|
| 116 |
+
False,
|
| 117 |
+
False,
|
| 118 |
+
True,
|
| 119 |
+
True,
|
| 120 |
+
True])
|
| 121 |
+
elif conf == 4:
|
| 122 |
+
dirichlet_map = np.array([False,
|
| 123 |
+
False,
|
| 124 |
+
True,
|
| 125 |
+
False,
|
| 126 |
+
False,
|
| 127 |
+
True,
|
| 128 |
+
False,
|
| 129 |
+
False,
|
| 130 |
+
True,
|
| 131 |
+
True,
|
| 132 |
+
False,
|
| 133 |
+
True,
|
| 134 |
+
True,
|
| 135 |
+
True,
|
| 136 |
+
False,
|
| 137 |
+
False,
|
| 138 |
+
True,
|
| 139 |
+
False,
|
| 140 |
+
False,
|
| 141 |
+
False,
|
| 142 |
+
True,
|
| 143 |
+
True])
|
| 144 |
+
|
| 145 |
+
elif conf == 5:
|
| 146 |
+
dirichlet_map = np.array([False,
|
| 147 |
+
False,
|
| 148 |
+
True,
|
| 149 |
+
False,
|
| 150 |
+
False,
|
| 151 |
+
True,
|
| 152 |
+
False,
|
| 153 |
+
False,
|
| 154 |
+
True,
|
| 155 |
+
True,
|
| 156 |
+
True,
|
| 157 |
+
True,
|
| 158 |
+
True,
|
| 159 |
+
True,
|
| 160 |
+
False,
|
| 161 |
+
True,
|
| 162 |
+
True,
|
| 163 |
+
True,
|
| 164 |
+
False,
|
| 165 |
+
False,
|
| 166 |
+
True,
|
| 167 |
+
True])
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
if all_dirichlet:
|
| 172 |
+
dirichlet_map = np.ones_like(dirichlet_map, dtype=np.bool_)
|
| 173 |
+
points = Point2f(points.T)
|
| 174 |
+
normals = dr.normalize(Point2f(normals.T))
|
| 175 |
+
return QuadraticBezierShape(points.numpy(), normals.numpy(), dirichlet = dirichlet,
|
| 176 |
+
neumann = neumann, epsilon = epsilon,
|
| 177 |
+
dirichlet_map = dirichlet_map, n_segment = 20, newton_steps = 5)
|
| 178 |
+
|
| 179 |
+
def load_boundary_data(only_dirichlet = False, constant = False, zero = False):
|
| 180 |
+
dirichlet_coeffs = []
|
| 181 |
+
neumann_coeffs = []
|
| 182 |
+
|
| 183 |
+
if zero:
|
| 184 |
+
return [ConstantCoefficient("coeff", 0)], [ConstantCoefficient("coeff", 0)]
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
if only_dirichlet:
|
| 188 |
+
constant_values = [0, 2, -2]
|
| 189 |
+
for c in constant_values:
|
| 190 |
+
dirichlet_coeffs.append(ConstantCoefficient("coeff", c))
|
| 191 |
+
else:
|
| 192 |
+
constant_values = [0, 2, 20, -2, -20]
|
| 193 |
+
for c1 in constant_values:
|
| 194 |
+
for c2 in constant_values:
|
| 195 |
+
dirichlet_coeffs.append(ConstantCoefficient("coeff", c1))
|
| 196 |
+
neumann_coeffs.append(ConstantCoefficient("coeff", c2))
|
| 197 |
+
|
| 198 |
+
if constant:
|
| 199 |
+
return dirichlet_coeffs, neumann_coeffs
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def ramp(points, parameters):
|
| 203 |
+
direction = dr.normalize(parameters["direction"])
|
| 204 |
+
z = dr.dot(points, direction)
|
| 205 |
+
return z * parameters["ramp"] + parameters["bias"]
|
| 206 |
+
|
| 207 |
+
def freq(points, parameters):
|
| 208 |
+
direction = dr.normalize(parameters["direction"])
|
| 209 |
+
z = dr.dot(points, direction)
|
| 210 |
+
return parameters["power"] * dr.cos(2 * dr.pi * parameters["freq"] * z) + parameters["bias"]
|
| 211 |
+
|
| 212 |
+
directions = [[0., 1.], [1, 0], [1., 1]]
|
| 213 |
+
ramp_values = [1, 3, 10]
|
| 214 |
+
for direction in directions:
|
| 215 |
+
for ramp_v in ramp_values:
|
| 216 |
+
for bias in [-ramp_v, 0, ramp_v]:
|
| 217 |
+
p_ramp = {}
|
| 218 |
+
dir = Point2f(direction)
|
| 219 |
+
dr.make_opaque(dir)
|
| 220 |
+
p_ramp["direction"] = dir
|
| 221 |
+
p_ramp["ramp"] = dr.opaque(Float, ramp_v, shape = (1))
|
| 222 |
+
p_ramp["bias"] = dr.opaque(Float, bias, shape = (1))
|
| 223 |
+
dirichlet_coeffs.append(FunctionCoefficient("coeff", dict(p_ramp), ramp))
|
| 224 |
+
if not only_dirichlet:
|
| 225 |
+
neumann_coeffs.append(FunctionCoefficient("coeff", dict(p_ramp), ramp))
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
freqs = [2, 4, 8]
|
| 229 |
+
powers = [1, 10]
|
| 230 |
+
for direction in directions:
|
| 231 |
+
for f in freqs:
|
| 232 |
+
for power in powers:
|
| 233 |
+
for bias in [-power, 0, power]:
|
| 234 |
+
p_freq = {}
|
| 235 |
+
dir = Point2f(direction)
|
| 236 |
+
dr.make_opaque(dir)
|
| 237 |
+
p_freq["direction"] = dir
|
| 238 |
+
p_freq["power"] = dr.opaque(Float, power, shape = (1))
|
| 239 |
+
p_freq["freq"] = dr.opaque(Float, f, shape = (1))
|
| 240 |
+
p_freq["bias"] = dr.opaque(Float, bias, shape = (1))
|
| 241 |
+
dirichlet_coeffs.append(FunctionCoefficient("coeff", dict(p_freq), freq))
|
| 242 |
+
if not only_dirichlet:
|
| 243 |
+
neumann_coeffs.append(FunctionCoefficient("coeff", dict(p_freq), freq))
|
| 244 |
+
|
| 245 |
+
if len(neumann_coeffs) == 0:
|
| 246 |
+
neumann_coeffs.append(ConstantCoefficient("coeff", 0))
|
| 247 |
+
|
| 248 |
+
return dirichlet_coeffs, neumann_coeffs
|
data/PDE2D/Coefficient/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .coefficient import *
|
| 2 |
+
from .constant import ConstantCoefficient
|
| 3 |
+
from .texture import TextureCoefficient
|
| 4 |
+
from .function import FunctionCoefficient
|
| 5 |
+
from .gaussian import GaussianMixtureCoefficient
|
| 6 |
+
from .disk_texture import DiskTextureCoefficient
|
| 7 |
+
from .coefficient_utils import *
|
data/PDE2D/Coefficient/coefficient.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import drjit as dr
|
| 3 |
+
import mitsuba as mi
|
| 4 |
+
from ..utils.sketch import plot_function
|
| 5 |
+
|
| 6 |
+
class Coefficient(object):
|
| 7 |
+
def __init__(self, name):
|
| 8 |
+
self.name = name
|
| 9 |
+
self.type = ""
|
| 10 |
+
self.is_zero = False
|
| 11 |
+
self.constant_thickness = 0
|
| 12 |
+
|
| 13 |
+
def get_value(self, points):
|
| 14 |
+
pass
|
| 15 |
+
def get_grad_laplacian(self, points):
|
| 16 |
+
pass
|
| 17 |
+
def get_opt_params(self, param_dict : dict, opt_params : list["str"]):
|
| 18 |
+
pass
|
| 19 |
+
def update(self, optimizer):
|
| 20 |
+
pass
|
| 21 |
+
def zero_grad(self):
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
def copy(self):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
def visualize(self, ax, bbox, resolution = [1024, 1024], spp = 4, colorbar = True, input_range = [None, None], cmap = "viridis"):
|
| 28 |
+
return plot_function(ax, self.get_value, bbox, resolution, spp, colorbar, input_range, cmap)
|
| 29 |
+
|
| 30 |
+
def visualize_grad(self):
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
def upsample2(self):
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
|
data/PDE2D/Coefficient/coefficient_utils.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from matplotlib.patches import Polygon
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
def build_grid_squares(points_per_edge, resolution, bbox, ax=None):
|
| 5 |
+
xscale = bbox[1][0] - bbox[0][0]
|
| 6 |
+
yscale = bbox[1][1] - bbox[0][1]
|
| 7 |
+
binx = xscale / resolution[0]
|
| 8 |
+
biny = yscale / resolution[1]
|
| 9 |
+
stepx = binx / points_per_edge
|
| 10 |
+
stepy = biny / points_per_edge
|
| 11 |
+
points = np.zeros([0, 2])
|
| 12 |
+
for i in range(resolution[0]):
|
| 13 |
+
for j in range(resolution[1]):
|
| 14 |
+
vec = np.zeros([4 * points_per_edge + 1, 2])
|
| 15 |
+
vec[0:points_per_edge, 0] = np.arange(
|
| 16 |
+
i * binx, (i+1) * binx, stepx)[0:points_per_edge]
|
| 17 |
+
vec[0:points_per_edge, 1] = -j * biny
|
| 18 |
+
vec[points_per_edge: 2 * points_per_edge, 0] = (i+1) * binx
|
| 19 |
+
vec[points_per_edge: 2 * points_per_edge,
|
| 20 |
+
1] = np.arange(-j * biny, -(j+1) * biny, -stepy)[0:points_per_edge]
|
| 21 |
+
vec[2 * points_per_edge: 3 * points_per_edge,
|
| 22 |
+
0] = np.arange((i+1) * binx, i * binx, -stepx)[0:points_per_edge]
|
| 23 |
+
vec[2 * points_per_edge: 3 * points_per_edge, 1] = - (j + 1) * biny
|
| 24 |
+
vec[3 * points_per_edge: 4 * points_per_edge, 0] = i * binx
|
| 25 |
+
vec[3 * points_per_edge: 4 * points_per_edge,
|
| 26 |
+
1] = np.arange(-(j+1) * biny, -j * biny, stepy)[0:points_per_edge]
|
| 27 |
+
vec[-1] = vec[0]
|
| 28 |
+
vec += np.array([bbox[0][0], bbox[1][1]])
|
| 29 |
+
points = np.vstack([points, vec])
|
| 30 |
+
if (ax is not None):
|
| 31 |
+
color = 'red' if (i+j) % 2 == 1 else "blue"
|
| 32 |
+
polygon = Polygon(vec, edgecolor=None, facecolor=color)
|
| 33 |
+
ax.add_patch(polygon)
|
| 34 |
+
return points.T
|
| 35 |
+
|
| 36 |
+
def sketch_grid_squares(points, points_per_edge, resolution, ax):
|
| 37 |
+
num_points = points.shape[0] // (4 * points_per_edge + 1)
|
| 38 |
+
for i in range(num_points):
|
| 39 |
+
p = points[i * (4 * points_per_edge + 1): (i+1)
|
| 40 |
+
* (4 * points_per_edge + 1)]
|
| 41 |
+
color = 'red' if (
|
| 42 |
+
((i // resolution[0]) + (i % resolution[1])) % 2 == 0) else "blue"
|
| 43 |
+
polygon = Polygon(p, edgecolor=None, facecolor=color)
|
| 44 |
+
ax.add_patch(polygon)
|
| 45 |
+
disable_ticks(ax)
|
| 46 |
+
|
| 47 |
+
def disable_ticks(ax):
|
| 48 |
+
"""Disable ticks around plot (useful for displaying images)"""
|
| 49 |
+
ax.axes.get_xaxis().set_ticklabels([])
|
| 50 |
+
ax.axes.get_yaxis().set_ticklabels([])
|
| 51 |
+
ax.axes.get_xaxis().set_ticks([])
|
| 52 |
+
ax.axes.get_yaxis().set_ticks([])
|
data/PDE2D/Coefficient/concentric_disk_map.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import drjit as dr
|
| 2 |
+
import mitsuba as mi
|
| 3 |
+
# Peter Shirley and Kenneth Chiu in 1997 derived an area preserving map between square to disc.
|
| 4 |
+
|
| 5 |
+
@dr.syntax
|
| 6 |
+
def square_to_disk(point : mi.Point2f):
|
| 7 |
+
if dr.abs(point[0]) > dr.abs(point[1]):
|
| 8 |
+
u = point[0] * dr.cos(dr.pi/4 * point[1] / point[0])
|
| 9 |
+
v = point[0] * dr.sin(dr.pi/4 * point[1] / point[0])
|
| 10 |
+
else:
|
| 11 |
+
u = point[1] * dr.sin(dr.pi/4 * point[0] / point[1])
|
| 12 |
+
v = point[1] * dr.cos(dr.pi/4 * point[0] / point[1])
|
| 13 |
+
return mi.Point2f(u, v)
|
| 14 |
+
|
| 15 |
+
@dr.syntax
|
| 16 |
+
def disk_to_square(point : mi.Point2f):
|
| 17 |
+
r = dr.norm(point)
|
| 18 |
+
if dr.abs(point[0]) >= dr.abs(point[1]):
|
| 19 |
+
p = r * mi.Point2f(dr.sign(point[0]), 4 / dr.pi * dr.atan2(point[1], dr.abs(point[0])))
|
| 20 |
+
else:
|
| 21 |
+
p = r * mi.Point2f(4 / dr.pi * dr.atan2(point[0], (dr.abs(point[1]) + dr.epsilon(mi.Float))), dr.sign(point[1]))
|
| 22 |
+
return p
|
| 23 |
+
|
| 24 |
+
@dr.syntax
|
| 25 |
+
def jakobian(point: mi.Point2f):
|
| 26 |
+
|
| 27 |
+
if dr.abs(point[0]) > dr.abs(point[1]):
|
| 28 |
+
A = dr.pi * point[1] / (4 * point[0])
|
| 29 |
+
cos_A = dr.cos(A)
|
| 30 |
+
sin_A = dr.sin(A)
|
| 31 |
+
mat = mi.Matrix2f(cos_A + A * sin_A, -dr.pi/4 * sin_A,
|
| 32 |
+
sin_A - A * cos_A, dr.pi/4 * cos_A)
|
| 33 |
+
else:
|
| 34 |
+
B = dr.pi * point[0] / (4 * point[1])
|
| 35 |
+
cos_B = dr.cos(dr.pi / 4 + B)
|
| 36 |
+
sin_B = dr.sin(dr.pi / 4 + B)
|
| 37 |
+
mat = mi.Matrix2f(dr.pi/4 * cos_B, sin_B - B * cos_B,
|
| 38 |
+
-dr.pi/4 * sin_B, cos_B + B * sin_B)
|
| 39 |
+
return mat
|
data/PDE2D/Coefficient/constant.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .coefficient import *
|
| 2 |
+
|
| 3 |
+
class ConstantCoefficient(Coefficient):
|
| 4 |
+
DRJIT_STRUCT = {
|
| 5 |
+
'value' : mi.Float
|
| 6 |
+
}
|
| 7 |
+
|
| 8 |
+
def __init__(self, name: str, value: float = 0):
|
| 9 |
+
self.is_zero = (value == 0)
|
| 10 |
+
self.value = mi.Float(value)
|
| 11 |
+
self.name = name
|
| 12 |
+
self.type = "constant"
|
| 13 |
+
self.constant_thickness = dr.inf
|
| 14 |
+
dr.make_opaque(self.value)
|
| 15 |
+
|
| 16 |
+
def get_value(self, points : mi.Point2f):
|
| 17 |
+
return self.value
|
| 18 |
+
|
| 19 |
+
def get_grad_laplacian(self, points: mi.Point2f): # type: ignore
|
| 20 |
+
return dr.zeros(mi.Point2f, dr.width(points)), dr.zeros(mi.Float, dr.width(points))
|
| 21 |
+
|
| 22 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 23 |
+
for key in opt_params:
|
| 24 |
+
vals = key.split(".")
|
| 25 |
+
name = vals[0]
|
| 26 |
+
type = vals[1]
|
| 27 |
+
param = vals[2]
|
| 28 |
+
if name == self.name and type == self.type:
|
| 29 |
+
if param == "value":
|
| 30 |
+
param_dict[key] = self.value
|
| 31 |
+
else:
|
| 32 |
+
raise Exception(
|
| 33 |
+
f"ConstantCoefficient ({self.name}) does not have a parameter called \"{param}\"")
|
| 34 |
+
|
| 35 |
+
def update(self, optimizer):
|
| 36 |
+
for key in optimizer.keys():
|
| 37 |
+
vals = key.split(".")
|
| 38 |
+
name = vals[0]
|
| 39 |
+
type = vals[1]
|
| 40 |
+
param = vals[2]
|
| 41 |
+
if (name == self.name) & (type == self.type) & (param == "value"):
|
| 42 |
+
self.value = optimizer[key]
|
| 43 |
+
|
| 44 |
+
def zero_grad(self):
|
| 45 |
+
if dr.grad_enabled(self.value):
|
| 46 |
+
dr.set_grad(self.value, 0.0)
|
| 47 |
+
|
| 48 |
+
def copy(self):
|
| 49 |
+
new = ConstantCoefficient(self.name, self.value)
|
| 50 |
+
new.zero_grad()
|
| 51 |
+
return new
|
data/PDE2D/Coefficient/disk_texture.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .coefficient import *
|
| 2 |
+
from .elliptic_disk_map import *
|
| 3 |
+
from PDE2D.utils.helpers import get_position_bbox
|
| 4 |
+
from mitsuba import TensorXf
|
| 5 |
+
|
| 6 |
+
class DiskTextureCoefficient(Coefficient):
|
| 7 |
+
def __init__(self, name: str, tensor_np: np.array,
|
| 8 |
+
origin : list = [0, 0], radius : float = 1, constant_thickness = 0.1,
|
| 9 |
+
out_val = 1, interpolation: str = "cubic"):
|
| 10 |
+
self.is_zero = False
|
| 11 |
+
self.interpolation = interpolation
|
| 12 |
+
self.tensor = TensorXf(tensor_np.squeeze()[..., np.newaxis])
|
| 13 |
+
self.name = name
|
| 14 |
+
self.type = "disktexture"
|
| 15 |
+
self.origin = mi.Point2f(origin)
|
| 16 |
+
self.radius = mi.Float(radius)
|
| 17 |
+
self.constant_thickness = constant_thickness
|
| 18 |
+
self.inner_radius = self.radius - self.constant_thickness
|
| 19 |
+
self.bbox = [[origin[0] - self.inner_radius, origin[1] - self.inner_radius],
|
| 20 |
+
[origin[0] + self.inner_radius, origin[1] + self.inner_radius]]
|
| 21 |
+
self.out_val = mi.Float(out_val)
|
| 22 |
+
dr.make_opaque(self.out_val)
|
| 23 |
+
dr.make_opaque(self.tensor)
|
| 24 |
+
self.update_texture()
|
| 25 |
+
|
| 26 |
+
def create_tensor(self, tensor : TensorXf, expand = 2):
|
| 27 |
+
# Creating the texture!
|
| 28 |
+
nx = tensor.shape[0] + 2 * expand
|
| 29 |
+
ny = tensor.shape[1] + 2 * expand
|
| 30 |
+
nz = tensor.shape[2]
|
| 31 |
+
new_tensor = TensorXf(dr.repeat(self.out_val, nx * ny * nz))
|
| 32 |
+
new_tensor = dr.reshape(TensorXf, new_tensor, shape = (nx, ny, nz))
|
| 33 |
+
# Get middle indices to scatter
|
| 34 |
+
i = dr.arange(mi.UInt32, expand, nx - expand)
|
| 35 |
+
j = dr.arange(mi.UInt32, expand, ny - expand)
|
| 36 |
+
ii, jj = dr.meshgrid(i, j)
|
| 37 |
+
indices = (jj - expand) * tensor.shape[1] + (ii - expand)
|
| 38 |
+
indices2 = jj * ny + ii
|
| 39 |
+
|
| 40 |
+
scatter_vals = dr.gather(mi.Float, tensor.array, mi.UInt32(indices))
|
| 41 |
+
dr.scatter(new_tensor.array, scatter_vals, mi.UInt32(indices2))
|
| 42 |
+
return new_tensor
|
| 43 |
+
|
| 44 |
+
def update_texture(self):
|
| 45 |
+
self.tensor2 = self.create_tensor(self.tensor)
|
| 46 |
+
self.texture = mi.Texture2f(self.tensor2, use_accel=False, migrate=False)
|
| 47 |
+
|
| 48 |
+
def get_value(self, points : mi.Point2f):
|
| 49 |
+
r = dr.norm(points - self.origin)
|
| 50 |
+
inside = r < self.inner_radius
|
| 51 |
+
points_square = disk_to_square(points, origin = self.origin, radius = self.inner_radius)
|
| 52 |
+
x, y = get_position_bbox(points_square, self.bbox)
|
| 53 |
+
if (self.interpolation == "cubic"):
|
| 54 |
+
res = self.texture.eval_cubic(mi.Point2f(x, y))[0]
|
| 55 |
+
elif (self.interpolation == "linear"):
|
| 56 |
+
res = self.texture.eval(mi.Point2f(x, y))[0]
|
| 57 |
+
else:
|
| 58 |
+
raise Exception(
|
| 59 |
+
f"There is no interpolation called \"{self.interpolation}\"")
|
| 60 |
+
return dr.select(inside, res, self.out_val)
|
| 61 |
+
#return res
|
| 62 |
+
def get_grad_laplacian(self, points: mi.Point2f, use_tensor_only = False):
|
| 63 |
+
dilate_x = self.bbox[1][0] - self.bbox[0][0]
|
| 64 |
+
dilate_y = self.bbox[1][1] - self.bbox[0][1]
|
| 65 |
+
|
| 66 |
+
points_square = disk_to_square(points, origin = self.origin, radius = self.inner_radius)
|
| 67 |
+
x, y = get_position_bbox(points_square, self.bbox)
|
| 68 |
+
eval_result = self.texture.eval_cubic_hessian(mi.Point2f(x, y))
|
| 69 |
+
grad_square = eval_result[1][0] / mi.Point2f(dilate_x, -dilate_y)
|
| 70 |
+
hessian_square = eval_result[2][0]
|
| 71 |
+
hessian_x = hessian_square[0, 0] / (dilate_x ** 2)
|
| 72 |
+
hessian_y = hessian_square[1, 1] / (dilate_y ** 2)
|
| 73 |
+
hessian_xy = hessian_square[0, 1] / (-dilate_x * dilate_y)
|
| 74 |
+
jak, jak2 = inverse_jakobian(points, origin = self.origin, radius = self.inner_radius)
|
| 75 |
+
|
| 76 |
+
grad_x = grad_square[0] * jak[0, 0] + grad_square[1] * jak[1, 0]
|
| 77 |
+
grad_y = grad_square[0] * jak[0, 1] + grad_square[1] * jak[1, 1]
|
| 78 |
+
|
| 79 |
+
laplacian_u = (hessian_x * dr.sqr(jak[0,0]) + grad_square[0] * jak2[0,0] +
|
| 80 |
+
hessian_y * dr.sqr(jak[1,0]) + grad_square[1] * jak2[1,0] +
|
| 81 |
+
2 * hessian_xy * jak[0, 0] * jak[1, 0])
|
| 82 |
+
laplacian_v = (hessian_x * dr.sqr(jak[0, 1]) + grad_square[0] * jak2[0, 1] +
|
| 83 |
+
hessian_y * dr.sqr(jak[1, 1]) + grad_square[1] * jak2[1, 1] +
|
| 84 |
+
2 * hessian_xy * jak[0, 1] * jak[1, 1])
|
| 85 |
+
|
| 86 |
+
grad = mi.Point2f(grad_x, grad_y)
|
| 87 |
+
laplacian = laplacian_u + laplacian_v
|
| 88 |
+
r = dr.norm(points - self.origin)
|
| 89 |
+
return dr.select(r<self.inner_radius, grad, 0), dr.select(r<self.inner_radius, laplacian, 0)
|
| 90 |
+
#return grad, laplacian
|
| 91 |
+
|
| 92 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 93 |
+
for key in opt_params:
|
| 94 |
+
vals = key.split(".")
|
| 95 |
+
name = vals[0]
|
| 96 |
+
type = vals[1]
|
| 97 |
+
param = vals[2]
|
| 98 |
+
if name == self.name and type == self.type:
|
| 99 |
+
if param == "tensor":
|
| 100 |
+
param_dict[key] = self.tensor
|
| 101 |
+
elif param == "outval":
|
| 102 |
+
param_dict[key] = self.outval
|
| 103 |
+
else:
|
| 104 |
+
raise Exception(
|
| 105 |
+
f"DiskTexture ({self.name}) does not have a parameter called \"{param}\"")
|
| 106 |
+
|
| 107 |
+
def update(self, optimizer):
|
| 108 |
+
name_outval = f"{self.name}.{self.type}.outval"
|
| 109 |
+
if name_outval in optimizer.keys():
|
| 110 |
+
self.out_val = optimizer[name_outval]
|
| 111 |
+
|
| 112 |
+
name_tensor = f"{self.name}.{self.type}.tensor"
|
| 113 |
+
if name_tensor in optimizer.keys():
|
| 114 |
+
self.tensor = optimizer[name_tensor]
|
| 115 |
+
|
| 116 |
+
self.update_texture()
|
| 117 |
+
|
| 118 |
+
def zero_grad(self):
|
| 119 |
+
if dr.grad_enabled(self.tensor):
|
| 120 |
+
dr.set_grad(self.tensor, 0.0)
|
| 121 |
+
if dr.grad_enabled(self.out_val):
|
| 122 |
+
dr.set_grad(self.out_val, 0.0)
|
| 123 |
+
|
| 124 |
+
def upsample(self, scale_factor=[2, 2]):
|
| 125 |
+
self.tensor = dr.upsample(self.tensor, scale_factor=scale_factor)
|
| 126 |
+
self.update_texture()
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def copy(self):
|
| 130 |
+
return DiskTextureCoefficient(name = self.name, tensor_np = self.tensor.numpy(),
|
| 131 |
+
origin = self.origin, radius = self.radius, constant_thickness = self.constant_thickness,
|
| 132 |
+
out_val = self.out_val, interpolation = self.interpolation)
|
data/PDE2D/Coefficient/elliptic_disk_map.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import mitsuba as mi
|
| 2 |
+
import drjit as dr
|
| 3 |
+
# Peter Shirley and Kenneth Chiu in 1997 derived an area preserving map between square to disc.
|
| 4 |
+
|
| 5 |
+
def square_to_disk(point : mi.Point2f, radius : mi.Float = 1, origin : mi.Point2f = mi.Point2f(0)):
|
| 6 |
+
x = (point[0] - origin[0]) / radius
|
| 7 |
+
y = (point[1] - origin[1]) / radius
|
| 8 |
+
u = x * dr.sqrt(1 - dr.sqr(y) / 2)
|
| 9 |
+
v = y * dr.sqrt(1 - dr.sqr(x) / 2)
|
| 10 |
+
return origin + radius * mi.Point2f(u,v)
|
| 11 |
+
|
| 12 |
+
def disk_to_square(point: mi.Point2f, radius: mi.Float = 1, origin: mi.Point2f = mi.Point2f(0)):
|
| 13 |
+
u = (point[0] - origin[0]) / radius
|
| 14 |
+
v = (point[1] - origin[1]) / radius
|
| 15 |
+
u2 = dr.sqr(u)
|
| 16 |
+
v2 = dr.sqr(v)
|
| 17 |
+
x = 0.5 * (dr.sqrt(2 + u2 - v2 + 2 * dr.sqrt(2) * u) -
|
| 18 |
+
dr.sqrt(2 + u2 - v2 - 2 * dr.sqrt(2) * u))
|
| 19 |
+
y = 0.5 * (dr.sqrt(2 - u2 + v2 + 2 * dr.sqrt(2) * v) -
|
| 20 |
+
dr.sqrt(2 - u2 + v2 - 2 * dr.sqrt(2) * v))
|
| 21 |
+
return origin + radius * mi.Point2f(x, y)
|
| 22 |
+
|
| 23 |
+
def jakobian(point: mi.Point2f, radius : mi.Float = 1, origin : mi.Point2f = mi.Point2f(0)):
|
| 24 |
+
x = (point[0] - origin[0]) / radius
|
| 25 |
+
y = (point[1] - origin[1]) / radius
|
| 26 |
+
x2 = dr.sqr(x)
|
| 27 |
+
y2 = dr.sqr(y)
|
| 28 |
+
a11 = dr.sqrt(1 - y2 / 2) # du/dx
|
| 29 |
+
a12 = -x * y / dr.sqrt(4 - 2 * y2) # du/dy
|
| 30 |
+
a21 = -x * y / dr.sqrt(4 - 2 * x2) # dv/dx
|
| 31 |
+
a22 = dr.sqrt(1 - x2 / 2) # dv/dy
|
| 32 |
+
return mi.Matrix2f(a11, a12, a21, a22)
|
| 33 |
+
|
| 34 |
+
def inverse_jakobian(point : mi.Point2f, radius : mi.Float = 1, origin : mi.Point2f = mi.Point2f(0)):
|
| 35 |
+
u = (point[0] - origin[0]) / radius
|
| 36 |
+
v = (point[1] - origin[1]) / radius
|
| 37 |
+
u2 = dr.sqr(u)
|
| 38 |
+
v2 = dr.sqr(v)
|
| 39 |
+
c11 = 1/(2 * dr.sqrt(2 + u2 - v2 + 2*dr.sqrt(2) * u))
|
| 40 |
+
c12 = 1/(2 * dr.sqrt(2 + u2 - v2 - 2*dr.sqrt(2) * u))
|
| 41 |
+
c21 = 1/(2 * dr.sqrt(2 - u2 + v2 + 2*dr.sqrt(2) * v))
|
| 42 |
+
c22 = 1/(2 * dr.sqrt(2 - u2 + v2 - 2*dr.sqrt(2) * v))
|
| 43 |
+
|
| 44 |
+
a11 = 1/2 * c11 * (2 * u + 2*dr.sqrt(2)) - 1/2 * c12 * (2 * u - 2*dr.sqrt(2)) # dx/du
|
| 45 |
+
a12 = -c11 * v + c12 * v # dx/dv
|
| 46 |
+
a21 = -c21 * u + c22 * u # dy/du
|
| 47 |
+
a22 = 1/2 * c21 * (2 * v + 2*dr.sqrt(2)) - 1/2 * c22 * (2 * v - 2*dr.sqrt(2)) # dy/dv
|
| 48 |
+
|
| 49 |
+
c11_u = -2 * dr.sqr(c11) * c11 * (2 * u + 2*dr.sqrt(2))
|
| 50 |
+
c12_u = -2 * dr.sqr(c12) * c12 * (2 * u - 2*dr.sqrt(2))
|
| 51 |
+
c21_u = 4 * dr.sqr(c21) * c21 * u
|
| 52 |
+
c22_u = 4 * dr.sqr(c22) * c22 * u
|
| 53 |
+
|
| 54 |
+
c11_v = 4 * dr.sqr(c11) * c11 * v
|
| 55 |
+
c12_v = 4 * dr.sqr(c12) * c12 * v
|
| 56 |
+
c21_v = -2 * dr.sqr(c21) * c21 * (2 * v + 2*dr.sqrt(2))
|
| 57 |
+
c22_v = -2 * dr.sqr(c22) * c22 * (2 * v - 2*dr.sqrt(2))
|
| 58 |
+
|
| 59 |
+
a11_u = 1/2 * c11_u * (2 * u + 2*dr.sqrt(2)) + c11 - 1/2 * c12_u * (2 * u - 2 * dr.sqrt(2)) - c12 # d2x/du2
|
| 60 |
+
a12_v = -c11 + c12 + v * (c12_v - c11_v)# d2x/dv2
|
| 61 |
+
a21_u = -c21 + c22 + u * (c22_u - c21_u) # d2y/du2
|
| 62 |
+
a22_v = 1/2 * c21_v * (2 * v + 2*dr.sqrt(2)) + c21 - 1/2 * c22_v * (2 * v - 2*dr.sqrt(2)) - c22 # d2y/dv2
|
| 63 |
+
|
| 64 |
+
return mi.Matrix2f(a11, a12, a21, a22), mi.Matrix2f(a11_u, a12_v, a21_u, a22_v)
|
data/PDE2D/Coefficient/function.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
from .coefficient import *
|
| 3 |
+
|
| 4 |
+
class FunctionCoefficient(Coefficient):
|
| 5 |
+
DRJIT_STRUCT = {
|
| 6 |
+
'parameters' : dict,
|
| 7 |
+
'function_generator' : callable,
|
| 8 |
+
}
|
| 9 |
+
def __init__(self, name: str, parameters: dict, function_generator: callable,
|
| 10 |
+
grad_generator: callable = None, laplacian_generator: callable = None):
|
| 11 |
+
self.is_zero = False
|
| 12 |
+
self.parameters = parameters
|
| 13 |
+
self.function_generator = function_generator
|
| 14 |
+
self.grad_generator = grad_generator
|
| 15 |
+
self.laplacian_generator = laplacian_generator
|
| 16 |
+
self.name = name
|
| 17 |
+
self.type = "CustomFunction"
|
| 18 |
+
for key in parameters.keys():
|
| 19 |
+
dr.make_opaque(parameters[key])
|
| 20 |
+
self.update_function()
|
| 21 |
+
|
| 22 |
+
def update_function(self):
|
| 23 |
+
self.function = lambda points : self.function_generator(points, self.parameters)
|
| 24 |
+
if ((self.grad_generator is not None) & (self.laplacian_generator is not None)):
|
| 25 |
+
self.grad = lambda points : self.grad_generator(points, self.parameters)
|
| 26 |
+
self.laplacian = lambda points : self.laplacian_generator(points, self.parameters)
|
| 27 |
+
else:
|
| 28 |
+
self.grad = None
|
| 29 |
+
self.laplacian = None
|
| 30 |
+
|
| 31 |
+
def get_value(self, points):
|
| 32 |
+
return self.function(points)
|
| 33 |
+
|
| 34 |
+
def get_grad_laplacian(self, points):
|
| 35 |
+
if ((self.grad is not None) & (self.laplacian is not None)):
|
| 36 |
+
return self.grad(points), self.laplacian(points)
|
| 37 |
+
else:
|
| 38 |
+
raise Exception(
|
| 39 |
+
f"Laplacian or gradient is not defined for the function coefficient\"{self.name}\"!")
|
| 40 |
+
|
| 41 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 42 |
+
for i in opt_params:
|
| 43 |
+
param_exists = False
|
| 44 |
+
for j in self.parameters.keys():
|
| 45 |
+
if i == j:
|
| 46 |
+
param_dict[f"{self.name}.{self.type}.{i}"] = self.parameters[i]
|
| 47 |
+
param_exists = True
|
| 48 |
+
if not param_exists:
|
| 49 |
+
raise Exception(
|
| 50 |
+
f"Function coefficient \"{self.name}\" of type \"{self.type}\" does not have parameter called \"{i}\".")
|
| 51 |
+
|
| 52 |
+
def update(self, optimizer):
|
| 53 |
+
param_exists = False
|
| 54 |
+
for key in optimizer.keys():
|
| 55 |
+
vals = key.split(".")
|
| 56 |
+
name = vals[0]
|
| 57 |
+
type = vals[1]
|
| 58 |
+
param = vals[2]
|
| 59 |
+
if (name == self.name) & (type == self.type):
|
| 60 |
+
for p in self.parameters.keys():
|
| 61 |
+
if p == param:
|
| 62 |
+
param_exists = True
|
| 63 |
+
self.parameters[p] = optimizer[key]
|
| 64 |
+
if param_exists:
|
| 65 |
+
self.update_function()
|
| 66 |
+
|
| 67 |
+
def zero_grad(self):
|
| 68 |
+
for key in self.parameters.keys():
|
| 69 |
+
if dr.grad_enabled(self.parameters[key]):
|
| 70 |
+
dr.set_grad(self.parameters[key], 0.0)
|
| 71 |
+
|
| 72 |
+
def copy(self):
|
| 73 |
+
new = FunctionCoefficient(self.name, self.parameters, self.function_generator,
|
| 74 |
+
self.grad_generator, self.laplacian_generator)
|
| 75 |
+
return new
|
data/PDE2D/Coefficient/gaussian.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .coefficient import *
|
| 2 |
+
from mitsuba import UInt
|
| 3 |
+
|
| 4 |
+
class GaussianMixtureCoefficient(Coefficient):
|
| 5 |
+
def __init__(self, name, mean, std, power=1.0, corr=1, bias=0, num_lobes: int = 1):
|
| 6 |
+
self.name = name
|
| 7 |
+
self.is_zero = False
|
| 8 |
+
self.type = "gaussian"
|
| 9 |
+
self.power = mi.Float(power) if (dr.width(
|
| 10 |
+
mi.Float(power)) == num_lobes) else dr.full(mi.Float, power, num_lobes)
|
| 11 |
+
std0 = mi.Float(std[0]) if (dr.width(mi.Float(std[0]))
|
| 12 |
+
== num_lobes) else dr.full(mi.Float, std[0], num_lobes)
|
| 13 |
+
std1 = mi.Float(std[1]) if (dr.width(mi.Float(std[1]))
|
| 14 |
+
== num_lobes) else dr.full(mi.Float, std[1], num_lobes)
|
| 15 |
+
self.std = mi.Point2f(std0, std1)
|
| 16 |
+
self.corr = mi.Float(corr) if (
|
| 17 |
+
dr.width(mi.Float(corr)) == num_lobes) else dr.full(mi.Float, corr, num_lobes)
|
| 18 |
+
self.bias = mi.Float(bias)
|
| 19 |
+
mean0 = mi.Float(mean[0]) if (dr.width(
|
| 20 |
+
mi.Float(mean[0])) == num_lobes) else dr.full(mi.Float, mean[0], num_lobes)
|
| 21 |
+
mean1 = mi.Float(mean[1]) if (dr.width(
|
| 22 |
+
mi.Float(mean[1])) == num_lobes) else dr.full(mi.Float, mean[1], num_lobes)
|
| 23 |
+
self.mean = mi.Point2f(mean0, mean1)
|
| 24 |
+
self.num_lobes = num_lobes
|
| 25 |
+
|
| 26 |
+
def get_lobe_params(self, lobe_num: UInt):
|
| 27 |
+
mean = dr.gather(mi.Point2f, self.mean, lobe_num)
|
| 28 |
+
std = dr.gather(mi.Point2f, self.std, lobe_num)
|
| 29 |
+
power = dr.gather(mi.Float, self.power, lobe_num)
|
| 30 |
+
corr = dr.gather(mi.Float, self.corr, lobe_num)
|
| 31 |
+
return mean, std, corr, power
|
| 32 |
+
|
| 33 |
+
def get_value(self, points):
|
| 34 |
+
value = mi.Float(0)
|
| 35 |
+
for i in range(self.num_lobes):
|
| 36 |
+
mean, std, corr, power = self.get_lobe_params(mi.Float(i))
|
| 37 |
+
m = dr.rcp(1 - dr.sqr(corr))
|
| 38 |
+
A = dr.rcp(2 * dr.pi * std[0] * std[1]) * dr.sqrt(m)
|
| 39 |
+
XY = (points - mean) / std
|
| 40 |
+
exponent = dr.sqr(XY[0]) + dr.sqr(XY[1]) - 2 * corr * XY[0] * XY[1]
|
| 41 |
+
exponent *= (-m / 2)
|
| 42 |
+
value += A * power * dr.exp(exponent)
|
| 43 |
+
return value + self.bias
|
| 44 |
+
|
| 45 |
+
def get_grad_laplacian(self, points):
|
| 46 |
+
grad = mi.Point2f(0)
|
| 47 |
+
laplacian = mi.Float(0)
|
| 48 |
+
for i in range(self.num_lobes):
|
| 49 |
+
mean, std, corr, power = self.get_lobe_params(mi.Float(i))
|
| 50 |
+
m = dr.rcp(1 - dr.sqr(corr))
|
| 51 |
+
A = dr.rcp(2 * dr.pi * std[0] * std[1]) * dr.sqrt(m)
|
| 52 |
+
XY = (points - mean) / std
|
| 53 |
+
exponent = dr.sqr(XY[0]) + dr.sqr(XY[1]) - 2 * corr * XY[0] * XY[1]
|
| 54 |
+
exponent *= (-m / 2)
|
| 55 |
+
E = dr.exp(exponent)
|
| 56 |
+
C_x = -m * (XY[0] - corr * XY[1]) / std[0]
|
| 57 |
+
C_y = -m * (XY[1] - corr * XY[0]) / std[1]
|
| 58 |
+
grad_ = A * E * power * mi.Point2f(C_x, C_y)
|
| 59 |
+
grad += grad_
|
| 60 |
+
k = dr.rcp(dr.sqr(std[0])) + dr.rcp(dr.sqr(std[1]))
|
| 61 |
+
laplacian += A * E * power * (dr.sqr(C_x) + dr.sqr(C_y) - m * k)
|
| 62 |
+
return grad, laplacian
|
| 63 |
+
|
| 64 |
+
def zero_grad(self):
|
| 65 |
+
for param in [self.power, self.std, self.corr, self.bias, self.mean]:
|
| 66 |
+
if dr.grad_enabled(param):
|
| 67 |
+
dr.set_grad(param, 0.0)
|
| 68 |
+
|
| 69 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 70 |
+
for i in opt_params:
|
| 71 |
+
if i == "mean":
|
| 72 |
+
param_dict[f"{self.name}.{self.type}.mean"] = self.mean
|
| 73 |
+
elif i == "std":
|
| 74 |
+
param_dict[f"{self.name}.{self.type}.std"] = self.std
|
| 75 |
+
elif i == "power":
|
| 76 |
+
param_dict[f"{self.name}.{self.type}.power"] = self.power
|
| 77 |
+
elif i == "correlation":
|
| 78 |
+
param_dict[f"{self.name}.{self.type}.correlation"] = self.corr
|
| 79 |
+
elif i == "bias":
|
| 80 |
+
param_dict[f"{self.name}.{self.type}.bias"] = self.bias
|
| 81 |
+
else:
|
| 82 |
+
raise Exception(
|
| 83 |
+
f"Gaussian Coefficient ({self.name}) does not have a parameter called \"{i}\"")
|
| 84 |
+
|
| 85 |
+
def update(self, optimizer):
|
| 86 |
+
for key in optimizer.keys():
|
| 87 |
+
vals = key.split(".")
|
| 88 |
+
name = vals[0]
|
| 89 |
+
type = vals[1]
|
| 90 |
+
param = vals[2]
|
| 91 |
+
if (name == self.name) & (type == self.type):
|
| 92 |
+
if param == "mean":
|
| 93 |
+
self.mean = optimizer[key]
|
| 94 |
+
elif param == "std":
|
| 95 |
+
self.std = optimizer[key]
|
| 96 |
+
elif param == "power":
|
| 97 |
+
self.power = optimizer[key]
|
| 98 |
+
elif param == "correlation":
|
| 99 |
+
self.corr = optimizer[key]
|
| 100 |
+
elif param == "bias":
|
| 101 |
+
self.bias = optimizer[key]
|
| 102 |
+
else:
|
| 103 |
+
raise Exception(
|
| 104 |
+
f"Gaussian Coefficient ({self.name}) does not have a parameter called \"{param}\"")
|
data/PDE2D/Coefficient/texture.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .coefficient import *
|
| 2 |
+
#from PDE2D import mi.TensorXf, mi.Float, mi.Point2f, mi.Texture2f, mi.UInt32, mi.TensorXb
|
| 3 |
+
from PDE2D.utils.helpers import get_position_bbox
|
| 4 |
+
from PDE2D.utils import upsample
|
| 5 |
+
|
| 6 |
+
class TextureCoefficient(Coefficient):
|
| 7 |
+
def __init__(self, name: str, bbox: list, tensor_np: np.array,
|
| 8 |
+
interpolation: str = "cubic", wrapping: str = "clamp",
|
| 9 |
+
grad_zero_points = None, out_val : mi.Float = None):
|
| 10 |
+
self.is_zero = False
|
| 11 |
+
self.interpolation = interpolation
|
| 12 |
+
self.tensor = mi.TensorXf(tensor_np.squeeze()[..., np.newaxis])
|
| 13 |
+
self.name = name
|
| 14 |
+
self.type = "texture"
|
| 15 |
+
self.wrapping = wrapping
|
| 16 |
+
self.bbox = bbox
|
| 17 |
+
dr.make_opaque(self.tensor)
|
| 18 |
+
self.grad_zero_points = grad_zero_points
|
| 19 |
+
self.out_val = out_val
|
| 20 |
+
self.grad_zero_mask = None
|
| 21 |
+
|
| 22 |
+
if self.grad_zero_points is not None:
|
| 23 |
+
mask = self.compute_grad_zero_mask()
|
| 24 |
+
self.grad_zero_mask = mi.TensorXb(mask, shape = (self.tensor.shape))
|
| 25 |
+
dr.eval(self.grad_zero_mask)
|
| 26 |
+
if self.out_val is None:
|
| 27 |
+
raise Exception("If you want to force gradient to be zero in some locations, "
|
| 28 |
+
"please specify a forced texture value (out_val).")
|
| 29 |
+
else:
|
| 30 |
+
dr.make_opaque(self.out_val)
|
| 31 |
+
|
| 32 |
+
self.texture = None
|
| 33 |
+
self.update_texture()
|
| 34 |
+
|
| 35 |
+
def compute_grad_zero_mask(self):
|
| 36 |
+
tensor = dr.arange(mi.Float, dr.width(self.tensor.array))
|
| 37 |
+
tensor = mi.TensorXf(tensor, shape = self.tensor.shape)
|
| 38 |
+
dr.enable_grad(tensor)
|
| 39 |
+
texture = self.create_texture(tensor)
|
| 40 |
+
dr.backward(self.get_grad_laplacian_(self.grad_zero_points, texture)[0])
|
| 41 |
+
mask = dr.abs(dr.grad(tensor).array) > 0
|
| 42 |
+
dr.disable_grad(tensor)
|
| 43 |
+
return mask
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def create_texture(self, tensor : mi.TensorXf):
|
| 47 |
+
# Creating the texture!
|
| 48 |
+
wrap_mode = None
|
| 49 |
+
if self.wrapping == "clamp":
|
| 50 |
+
wrap_mode = dr.WrapMode.Clamp
|
| 51 |
+
elif self.wrapping == "mirror":
|
| 52 |
+
wrap_mode = dr.WrapMode.Mirror
|
| 53 |
+
elif self.wrapping == "repeat":
|
| 54 |
+
wrap_mode = dr.WrapMode.Repeat
|
| 55 |
+
else:
|
| 56 |
+
raise Exception("Such wrapping is not defined.")
|
| 57 |
+
|
| 58 |
+
filter_type = dr.FilterMode.Nearest if self.interpolation=="nearest" else dr.FilterMode.Linear
|
| 59 |
+
return mi.Texture2f(tensor, wrap_mode=wrap_mode, use_accel=False, migrate=False, filter_mode=filter_type)
|
| 60 |
+
|
| 61 |
+
def update_texture(self):
|
| 62 |
+
tensor = mi.TensorXf(self.tensor)
|
| 63 |
+
if self.grad_zero_mask is not None:
|
| 64 |
+
tensor = dr.select(self.grad_zero_mask, mi.TensorXf(dr.detach(self.out_val)), tensor)
|
| 65 |
+
if self.texture is None:
|
| 66 |
+
self.texture = self.create_texture(tensor)
|
| 67 |
+
else:
|
| 68 |
+
self.texture.set_tensor(tensor)
|
| 69 |
+
|
| 70 |
+
def get_value(self, points: mi.Point2f):
|
| 71 |
+
x, y = get_position_bbox(points, self.bbox)
|
| 72 |
+
if (self.interpolation == "cubic"):
|
| 73 |
+
return self.texture.eval_cubic(mi.Point2f(x, y))[0]
|
| 74 |
+
elif (self.interpolation == "linear" or self.interpolation == "nearest"):
|
| 75 |
+
return self.texture.eval(mi.Point2f(x, y))[0]
|
| 76 |
+
else:
|
| 77 |
+
raise Exception(
|
| 78 |
+
f"There is no interpolation called \"{self.interpolation}\"")
|
| 79 |
+
|
| 80 |
+
def get_grad_laplacian(self, points):
|
| 81 |
+
return self.get_grad_laplacian_(points, self.texture)
|
| 82 |
+
|
| 83 |
+
def get_grad_laplacian_(self, points: mi.Point2f, texture : mi.Texture2f):
|
| 84 |
+
if not self.interpolation == "cubic":
|
| 85 |
+
raise Exception("Laplacian is only defined for cubic interpolation.")
|
| 86 |
+
dilate_x = self.bbox[1][0] - self.bbox[0][0]
|
| 87 |
+
dilate_y = self.bbox[1][1] - self.bbox[0][1]
|
| 88 |
+
x, y = get_position_bbox(points, self.bbox)
|
| 89 |
+
eval_result = texture.eval_cubic_hessian(mi.Point2f(x, y))
|
| 90 |
+
grad = eval_result[1][0] / mi.Point2f(dilate_x, -dilate_y)
|
| 91 |
+
hessian_image = eval_result[2][0]
|
| 92 |
+
laplacian = hessian_image[0, 0] / \
|
| 93 |
+
(dilate_x ** 2) + hessian_image[1, 1] / (dilate_y ** 2)
|
| 94 |
+
return mi.Point2f(grad), mi.Float(laplacian)
|
| 95 |
+
|
| 96 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 97 |
+
for key in opt_params:
|
| 98 |
+
vals = key.split(".")
|
| 99 |
+
name = vals[0]
|
| 100 |
+
type = vals[1]
|
| 101 |
+
param = vals[2]
|
| 102 |
+
if name == self.name and type == self.type:
|
| 103 |
+
if param == "tensor":
|
| 104 |
+
param_dict[key] = self.tensor
|
| 105 |
+
elif param == "outval":
|
| 106 |
+
param_dict[key] = self.out_val
|
| 107 |
+
else:
|
| 108 |
+
raise Exception(
|
| 109 |
+
f"TextureCoefficient ({self.name}) does not have a parameter called \"{param}\"")
|
| 110 |
+
|
| 111 |
+
def update(self, optimizer):
|
| 112 |
+
name_outval = f"{self.name}.{self.type}.outval"
|
| 113 |
+
if name_outval in optimizer.keys():
|
| 114 |
+
self.out_val = optimizer[name_outval]
|
| 115 |
+
|
| 116 |
+
name_tensor = f"{self.name}.{self.type}.tensor"
|
| 117 |
+
if name_tensor in optimizer.keys():
|
| 118 |
+
#if self.grad_zero_mask is not None:
|
| 119 |
+
self.tensor = optimizer[name_tensor]
|
| 120 |
+
self.update_texture()
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def zero_grad(self):
|
| 124 |
+
if dr.grad_enabled(self.tensor):
|
| 125 |
+
dr.set_grad(self.tensor, 0.0)
|
| 126 |
+
|
| 127 |
+
def copy(self):
|
| 128 |
+
new = TextureCoefficient(self.name, self.bbox, self.tensor.numpy().squeeze(),
|
| 129 |
+
self.interpolation, self.wrapping, self.grad_zero_points, self.out_val)
|
| 130 |
+
new.zero_grad()
|
| 131 |
+
return new
|
| 132 |
+
|
| 133 |
+
def upsample(self, scale_factor=[2, 2]):
|
| 134 |
+
self.tensor = dr.upsample(self.tensor, scale_factor=scale_factor)
|
| 135 |
+
self.update_texture()
|
| 136 |
+
|
| 137 |
+
def copy(self):
|
| 138 |
+
return TextureCoefficient(name = self.name, bbox = self.bbox, tensor_np=self.tensor.numpy().squeeze(),
|
| 139 |
+
interpolation = self.interpolation, wrapping = self.wrapping,
|
| 140 |
+
grad_zero_points=self.grad_zero_points, out_val = self.out_val)
|
| 141 |
+
|
| 142 |
+
def upsample2(self):
|
| 143 |
+
self.tensor = upsample(self.tensor, scale_factor=[2,2])
|
| 144 |
+
dr.eval(self.tensor)
|
| 145 |
+
if self.grad_zero_points is not None:
|
| 146 |
+
mask = self.compute_grad_zero_mask()
|
| 147 |
+
self.grad_zero_mask = mi.TensorXb(mask, shape = (self.tensor.shape))
|
| 148 |
+
self.update_texture()
|
| 149 |
+
|
data/PDE2D/GreenModels/green_2d_12.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d93ab9ad31b28cd5e2da82eada7c14e19bc9f5a126f0cf58f0387c194fd729cd
|
| 3 |
+
size 48073
|
data/PDE2D/GreenModels/green_2d_8.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:31e20b18e9838f307d8a1a5b3d01e232b32c50c04a1ae26c349c3f2e96e93652
|
| 3 |
+
size 32057
|
data/PDE2D/GreenModels/green_3d_12.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:36e0e9b18c145616c5403d652013320acfa3245fd326bfa7a214c925b03874de
|
| 3 |
+
size 48073
|
data/PDE2D/GreenModels/green_3d_8.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:31dde834a30d27c672690d41c365d5d23d024abed684bf4edd893457ad537793
|
| 3 |
+
size 32057
|
data/PDE2D/GreenModels/green_grad_2d_12.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a982772513fb02866d781b27c38c6e84206247935cfce80e880ab86e54baf456
|
| 3 |
+
size 48073
|
data/PDE2D/GreenModels/green_grad_2d_8.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f1ba97475407f902e490921cff5ef2484acccc87ee0a52e02073f7ad84dbbe9e
|
| 3 |
+
size 32057
|
data/PDE2D/GreenModels/green_grad_3d_12.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:124f1ed9fe1849ad04e0d2208378f50900d7073c8e4314709767223204658a05
|
| 3 |
+
size 48073
|
data/PDE2D/GreenModels/green_grad_3d_8.model
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:958dfbc57b9d7fbea592a47b89e405b5ab9f6256c087582cc50f30a776e12100
|
| 3 |
+
size 32057
|
data/PDE2D/Sampling/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .sampling_wos import *
|
| 2 |
+
#from .tabulated import TabulatedLinearPDF1D
|
| 3 |
+
from .green import GreensFunction
|
| 4 |
+
from .green_polynomial import GreensFunctionPolynomial
|
| 5 |
+
from .green_analytic import GreensFunctionAnalytic
|
data/PDE2D/Sampling/green.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import mitsuba as mi
|
| 2 |
+
from PDE2D import DIM
|
| 3 |
+
from PDE2D.Sampling.special import *
|
| 4 |
+
from mitsuba import Float
|
| 5 |
+
|
| 6 |
+
z_threshold = Float(0.05)
|
| 7 |
+
|
| 8 |
+
class GreensFunction:
|
| 9 |
+
def __init__(self, dim : DIM, grad : bool = False, newton_steps : int = 5) -> None:
|
| 10 |
+
"""
|
| 11 |
+
The parameter ``newton_it`` specifies how many Newton iteration steps
|
| 12 |
+
the implementation should perform in the ``.sample()`` method following
|
| 13 |
+
initialization from a starting guess.
|
| 14 |
+
"""
|
| 15 |
+
self.dim = dim
|
| 16 |
+
self.newton_steps = newton_steps
|
| 17 |
+
self.is_grad = grad
|
| 18 |
+
|
| 19 |
+
def initialize(self, z : Float) -> None:
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
def eval(self, r:Float, radius:Float, σ: Float) -> Float:
|
| 23 |
+
return Float(0)
|
| 24 |
+
|
| 25 |
+
def eval_pdf(self, r: Float, radius: Float, σ : Float) -> tuple[Float, Float, Float]:
|
| 26 |
+
return Float(0), Float(0), Float(0)
|
| 27 |
+
|
| 28 |
+
def eval_norm(self, radius : Float, σ : Float) -> Float:
|
| 29 |
+
return Float(0)
|
| 30 |
+
|
| 31 |
+
def sample(self, x: Float, radius: Float, σ: Float) -> tuple[Float, Float]:
|
| 32 |
+
return Float(0), Float(0)
|
| 33 |
+
|
| 34 |
+
def eval_poisson_kernel(self, r : Float, radius : Float, σ : Float) -> Float:
|
| 35 |
+
return Float(0)
|
| 36 |
+
|
| 37 |
+
def eval_pdf_only(self, r : Float, radius : Float, σ : Float) -> Float:
|
| 38 |
+
norm = self.eval_norm(radius, σ)
|
| 39 |
+
val = self.eval(r, radius, σ)
|
| 40 |
+
pdf = val * dr.rcp(norm)
|
| 41 |
+
return pdf
|
data/PDE2D/Sampling/green_analytic.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import drjit as dr
|
| 2 |
+
import mitsuba as mi
|
| 3 |
+
from PDE2D import DIM
|
| 4 |
+
from PDE2D.Sampling.special import *
|
| 5 |
+
from .green import GreensFunction
|
| 6 |
+
|
| 7 |
+
z_threshold = mi.Float(0.05)
|
| 8 |
+
|
| 9 |
+
class GreensFunctionAnalytic(GreensFunction):
|
| 10 |
+
def __init__(self, dim : DIM, grad : bool = False, newton_steps : int = 5) -> None:
|
| 11 |
+
"""
|
| 12 |
+
The parameter ``newton_it`` specifies how many Newton iteration steps
|
| 13 |
+
the implementation should perform in the ``.sample()`` method following
|
| 14 |
+
initialization from a starting guess.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
super().__init__(dim, grad, newton_steps)
|
| 18 |
+
|
| 19 |
+
@dr.syntax # type: ignore
|
| 20 |
+
def eval(self, r:mi.Float, radius:mi.Float, σ: mi.Float) -> mi.Float:
|
| 21 |
+
z = radius * dr.sqrt(σ)
|
| 22 |
+
y = r * dr.rcp(radius)
|
| 23 |
+
yz = y * z
|
| 24 |
+
rcpyz = dr.rcp(yz)
|
| 25 |
+
rcpz = dr.rcp(z)
|
| 26 |
+
val = mi.Float(0)
|
| 27 |
+
|
| 28 |
+
if dr.hint(self.dim == DIM.Two, mode = 'scalar'):
|
| 29 |
+
if dr.hint(self.is_grad, mode = 'scalar'):
|
| 30 |
+
#raise Exception("Not Implemented.")
|
| 31 |
+
if z < z_threshold:
|
| 32 |
+
val = 1 - dr.square(y)
|
| 33 |
+
else:
|
| 34 |
+
val = yz * dGσ(y, z)
|
| 35 |
+
else:
|
| 36 |
+
if z < z_threshold:
|
| 37 |
+
val = dr.select(r ==0, 0, -r * dr.log(y))
|
| 38 |
+
else:
|
| 39 |
+
val = r * Gσ(y, z)
|
| 40 |
+
else:
|
| 41 |
+
#raise Exception("Not implemented.")
|
| 42 |
+
if dr.hint(self.is_grad, mode = 'scalar'):
|
| 43 |
+
if z < z_threshold:
|
| 44 |
+
val = 1 - y * dr.square(y)
|
| 45 |
+
else:
|
| 46 |
+
val = yz * (dr.exp(-yz) * (1 + rcpyz) -
|
| 47 |
+
dr.exp(-z) * (1 + rcpz) * ( (dr.cosh(yz) - dr.sinh(yz) * rcpyz) * dr.rcp(dr.cosh(z) - dr.sinh(z) * rcpz) ))
|
| 48 |
+
val = dr.select(y <= 0, 1, val)
|
| 49 |
+
val = dr.select(y >= 1, 0, val)
|
| 50 |
+
|
| 51 |
+
else:
|
| 52 |
+
if z < z_threshold:
|
| 53 |
+
val = r * (1 - y)
|
| 54 |
+
else:
|
| 55 |
+
val = radius * y * yz * (dr.exp(-yz) * dr.rcp(yz) -
|
| 56 |
+
dr.exp(-z) * dr.rcp(yz) * dr.sinh(yz) * dr.rcp(dr.sinh(z)))
|
| 57 |
+
val = dr.select(y == 0, 0, val)
|
| 58 |
+
val = dr.select(y == 1, 0, val)
|
| 59 |
+
|
| 60 |
+
val = dr.select((y>=0) & (y<=1), val, 0)
|
| 61 |
+
return val
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
@dr.syntax # type: ignore
|
| 65 |
+
def eval_pdf(self, r: mi.Float, radius: mi.Float, σ : mi.Float) -> tuple[mi.Float, mi.Float, mi.Float]:
|
| 66 |
+
norm = self.eval_norm(radius, σ)
|
| 67 |
+
val = self.eval(r, radius, σ)
|
| 68 |
+
pdf = val * dr.rcp(norm)
|
| 69 |
+
cdf = mi.Float(0)
|
| 70 |
+
y = r * dr.rcp(radius)
|
| 71 |
+
z = radius * dr.sqrt(σ)
|
| 72 |
+
coshz = dr.cosh(z)
|
| 73 |
+
sinhz = dr.sinh(z)
|
| 74 |
+
yz = y * z
|
| 75 |
+
zyz = z - yz
|
| 76 |
+
y2 = dr.square(y)
|
| 77 |
+
|
| 78 |
+
if dr.hint(self.dim == DIM.Two, mode = 'scalar'):
|
| 79 |
+
if dr.hint(self.is_grad, mode = 'scalar'):
|
| 80 |
+
# raise Exception("Not implemented")
|
| 81 |
+
if z < z_threshold:
|
| 82 |
+
cdf = y * (1.5 - dr.square(y) * 0.5)
|
| 83 |
+
else:
|
| 84 |
+
cdf = mi.Float(dr.nan) # Other case requires evaluation of very expensive and complex functions.
|
| 85 |
+
else:
|
| 86 |
+
if z < z_threshold:
|
| 87 |
+
cdf = dr.square(y) * (1 - 2 * dr.log(y))
|
| 88 |
+
else:
|
| 89 |
+
cdf = Gσr_int(y,z) * dr.rcp(σ * norm)
|
| 90 |
+
|
| 91 |
+
else:
|
| 92 |
+
#raise Exception("Not implemented.")
|
| 93 |
+
if dr.hint(self.is_grad, mode = 'scalar'):
|
| 94 |
+
if z < z_threshold:
|
| 95 |
+
cdf = (4 * y - dr.square(y2)) / 3
|
| 96 |
+
else:
|
| 97 |
+
cdf = ((-2* coshz + (2- yz * z) * dr.cosh(zyz) + 2 * z * dr.sinh(z) + (y-2) * z * dr.sinh(zyz)) /
|
| 98 |
+
(2 - dr.square(z) - 2 * dr.cosh(z) + 2 * z * sinhz))
|
| 99 |
+
else:
|
| 100 |
+
if z < z_threshold:
|
| 101 |
+
cdf = dr.square(y) * (3 - 2 * y)
|
| 102 |
+
else:
|
| 103 |
+
cdf = (yz * dr.cosh(zyz) - dr.sinh(z) + dr.sinh(zyz)) * dr.rcp(z - dr.sinh(z))
|
| 104 |
+
|
| 105 |
+
if y <= 0:
|
| 106 |
+
cdf = mi.Float(0)
|
| 107 |
+
if y >= 1:
|
| 108 |
+
cdf = mi.Float(1)
|
| 109 |
+
return pdf, cdf, norm
|
| 110 |
+
|
| 111 |
+
@dr.syntax # type: ignore
|
| 112 |
+
def eval_norm(self, radius : mi.Float, σ : mi.Float) -> mi.Float:
|
| 113 |
+
norm = mi.Float(0)
|
| 114 |
+
z = radius * dr.sqrt(σ)
|
| 115 |
+
coshz = dr.cosh(z)
|
| 116 |
+
sinhz = dr.sinh(z)
|
| 117 |
+
|
| 118 |
+
if dr.hint(self.dim == DIM.Two, mode = 'scalar'):
|
| 119 |
+
if dr.hint(self.is_grad, mode = 'scalar'):
|
| 120 |
+
raise Exception("Not Implemented")
|
| 121 |
+
if z < z_threshold:
|
| 122 |
+
norm = 2 * radius / 3
|
| 123 |
+
else:
|
| 124 |
+
norm = mi.Float(dr.nan) # Other case requires evaluation of very expensive and complex functions.
|
| 125 |
+
else:
|
| 126 |
+
if z < z_threshold:
|
| 127 |
+
norm = dr.square(radius) / 4
|
| 128 |
+
else:
|
| 129 |
+
norm = dr.rcp(σ) * (1.0 - dr.rcp(i0(z)))
|
| 130 |
+
|
| 131 |
+
else:
|
| 132 |
+
#raise Exception("Not Implemented")
|
| 133 |
+
if dr.hint(self.is_grad, mode = 'scalar'):
|
| 134 |
+
if z < z_threshold:
|
| 135 |
+
norm = 3 * radius / 4
|
| 136 |
+
else:
|
| 137 |
+
norm = radius * (2 - dr.square(z) - 2 * coshz + 2 * z * sinhz) * dr.rcp(z * (z * coshz - sinhz))
|
| 138 |
+
else:
|
| 139 |
+
if z < z_threshold:
|
| 140 |
+
norm = dr.square(radius) / 6
|
| 141 |
+
else:
|
| 142 |
+
norm = dr.rcp(σ) * (1 - z * dr.rcp(dr.sinh(z)))
|
| 143 |
+
return norm
|
| 144 |
+
|
| 145 |
+
@dr.syntax # type: ignore
|
| 146 |
+
def sample(self, x: mi.Float, radius: mi.Float, σ: mi.Float) -> tuple[mi.Float, mi.Float]:
|
| 147 |
+
# The expression to initialize the Newton iteration is numerically
|
| 148 |
+
# unstable when 'z' is too small. Clamp to 1e-1 (for this part only)
|
| 149 |
+
z = dr.sqrt(σ)
|
| 150 |
+
z_init = dr.maximum(z, 1e-1)
|
| 151 |
+
b = None
|
| 152 |
+
|
| 153 |
+
if dr.hint(not self.is_grad, mode='scalar'):
|
| 154 |
+
if dr.hint(self.dim == DIM.Two, mode='scalar'):
|
| 155 |
+
# Based on 'Sample3Composed2' from the Mathematica notebook
|
| 156 |
+
sqrt_x = dr.sqrt(x)
|
| 157 |
+
b = 1 - dr.acosh(dr.fma(dr.cosh(z_init), 1 - sqrt_x, sqrt_x)) / z_init
|
| 158 |
+
elif self.dim == DIM.Three:
|
| 159 |
+
# Based on 'Sample2Composed1' from the Mathematica notebook
|
| 160 |
+
b = (1 - dr.acosh(dr.fma(dr.cosh(z_init), 1 - x, x)) / z_init) ** (2 / 3)
|
| 161 |
+
else:
|
| 162 |
+
raise RuntimeError("Unsupported number of dimensions!")
|
| 163 |
+
else:
|
| 164 |
+
# No good sampling strategy yet
|
| 165 |
+
b = (1 - dr.sqrt(1-x))
|
| 166 |
+
|
| 167 |
+
# Bracketing interval
|
| 168 |
+
a, c = mi.Float(0), mi.Float(1)
|
| 169 |
+
|
| 170 |
+
# Iteration counter
|
| 171 |
+
i = mi.UInt32(0)
|
| 172 |
+
norm = mi.Float(0)
|
| 173 |
+
while i < self.newton_steps:
|
| 174 |
+
# Perform a Newton step
|
| 175 |
+
deriv, cdf, norm = self.eval_pdf(b * radius, radius, σ)
|
| 176 |
+
deriv *= radius
|
| 177 |
+
b = b - (cdf - x) / deriv
|
| 178 |
+
|
| 179 |
+
# Newton-Bisection: potentially reject the Newton step
|
| 180 |
+
bad_step = ~((b >= a) & (b <= c))
|
| 181 |
+
b = dr.select(bad_step, (a + c) / 2, b)
|
| 182 |
+
|
| 183 |
+
# Update bracketing interval
|
| 184 |
+
is_neg = self.eval_pdf(b * radius, radius, σ)[1] - x < 0
|
| 185 |
+
a = dr.select(is_neg, b, a)
|
| 186 |
+
c = dr.select(is_neg, c, b)
|
| 187 |
+
|
| 188 |
+
i += 1
|
| 189 |
+
return b * radius, norm
|
| 190 |
+
|
| 191 |
+
@dr.syntax # type: ignore
|
| 192 |
+
def eval_poisson_kernel(self, r : mi.Float, radius : mi.Float, σ : mi.Float):
|
| 193 |
+
|
| 194 |
+
# There is no such relation for poisson kernel in gradient.
|
| 195 |
+
# I did not look to the 3D case.
|
| 196 |
+
assert (not self.is_grad) & (self.dim == DIM.Two)
|
| 197 |
+
|
| 198 |
+
z = radius * dr.sqrt(σ)
|
| 199 |
+
y = r/radius
|
| 200 |
+
|
| 201 |
+
result = mi.Float(0)
|
| 202 |
+
if z < z_threshold:
|
| 203 |
+
result = 1 - dr.square(y) * (1 - 2 * dr.log(y)) * self.eval_norm(radius, σ) * σ
|
| 204 |
+
else:
|
| 205 |
+
result = 1- Gσr_int(r/radius, z)
|
| 206 |
+
return result
|
| 207 |
+
|
data/PDE2D/Sampling/green_polynomial.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import drjit as dr
|
| 2 |
+
import numpy as np
|
| 3 |
+
import mitsuba as mi
|
| 4 |
+
from mitsuba import Float, UInt32, Point1f, TensorXf
|
| 5 |
+
from PDE2D import DIM, PATH
|
| 6 |
+
import os
|
| 7 |
+
from .green import GreensFunction
|
| 8 |
+
|
| 9 |
+
class GreensFunctionPolynomial(GreensFunction):
|
| 10 |
+
def __init__(self, dim : DIM, newton_steps: int = 4, grad : bool = False, ncoeffs : int = 8) -> None:
|
| 11 |
+
"""
|
| 12 |
+
Load a binary file containing series expansion coefficients describing
|
| 13 |
+
the Green's function in 2D or 3D.
|
| 14 |
+
|
| 15 |
+
The parameter ``newton_it`` specifies how many Newton iteration steps
|
| 16 |
+
the implementation should perform in the ``.sample()`` method following
|
| 17 |
+
initialization from a starting guess.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import array
|
| 21 |
+
import struct
|
| 22 |
+
|
| 23 |
+
super().__init__(dim, grad, newton_steps)
|
| 24 |
+
|
| 25 |
+
if self.is_grad:
|
| 26 |
+
filename = f"green_grad_3d_{ncoeffs}.model" if dim == DIM.Three else f"green_grad_2d_{ncoeffs}.model"
|
| 27 |
+
else:
|
| 28 |
+
filename = f"green_3d_{ncoeffs}.model" if dim == DIM.Three else f"green_2d_{ncoeffs}.model"
|
| 29 |
+
|
| 30 |
+
filename = os.path.join(PATH,"PDE2D", "GreenModels", filename)
|
| 31 |
+
|
| 32 |
+
with open(filename, "rb") as f:
|
| 33 |
+
# Double-check that this file was generated by the Mathematica notebook
|
| 34 |
+
if f.read(5) != b"GREEN":
|
| 35 |
+
raise RuntimeError(
|
| 36 |
+
f'GreensFunction("{filename}"): incompatible input file.'
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# Following the header, the file stores a few integers. The first
|
| 40 |
+
# one specifies whether the coefficients represent a Green's
|
| 41 |
+
# function or its gradient.
|
| 42 |
+
is_grad: int = struct.unpack("i", f.read(4))[0]
|
| 43 |
+
if is_grad != 0 and is_grad != 1:
|
| 44 |
+
raise RuntimeError(f'GreensFunction("{filename}"): invalid input.')
|
| 45 |
+
self.is_grad: bool = is_grad == 1
|
| 46 |
+
|
| 47 |
+
# The next field specifies the number of dimensions, which must be
|
| 48 |
+
# known by some functions below
|
| 49 |
+
self.ndim: int = struct.unpack("i", f.read(4))[0]
|
| 50 |
+
if self.ndim != 2 and self.ndim != 3:
|
| 51 |
+
raise RuntimeError(
|
| 52 |
+
f'GreensFunction("{filename}"): expected a 2D or 3D model file.'
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
# Number of coefficients per 'z' value
|
| 56 |
+
self.ncoeffs: int = struct.unpack("i", f.read(4))[0]
|
| 57 |
+
|
| 58 |
+
# Number of sampled 'z' values contained in the file
|
| 59 |
+
self.nsamples: int = struct.unpack("i", f.read(4))[0]
|
| 60 |
+
|
| 61 |
+
# Largest 'z' value represented in the file
|
| 62 |
+
self.zmax: float = struct.unpack("f", f.read(4))[0]
|
| 63 |
+
|
| 64 |
+
data = f.read()
|
| 65 |
+
if len(data) != self.ncoeffs * self.nsamples * 4:
|
| 66 |
+
raise RuntimeError(f'GreensFunction("{filename}"): invalid file size.')
|
| 67 |
+
|
| 68 |
+
coeff_flat = np.array(array.array("f", data)).squeeze()
|
| 69 |
+
data_shape = (self.nsamples, self.ncoeffs)
|
| 70 |
+
#coeff_tensor = TensorXf(coeff_flat, shape = data_shape)
|
| 71 |
+
coeff_tensor = TensorXf(coeff_flat, shape=data_shape)
|
| 72 |
+
|
| 73 |
+
# Create a 1D texture to interpolate the loaded data
|
| 74 |
+
self.coeff_tex = mi.Texture1f(coeff_tensor)
|
| 75 |
+
|
| 76 |
+
def initialize(self, z : Float):
|
| 77 |
+
self.coeffs = self.fetch_coeffs(z)
|
| 78 |
+
|
| 79 |
+
def fetch_coeffs(self, z: Float) -> list[Float]:
|
| 80 |
+
"""
|
| 81 |
+
Perform a linearly interpolated lookup into the texture to fetch
|
| 82 |
+
coefficients for a particular value of ``z``.
|
| 83 |
+
"""
|
| 84 |
+
# Scale ``z`` according to the texture discretization
|
| 85 |
+
# that places samples at position .5 within each texel
|
| 86 |
+
n = self.nsamples
|
| 87 |
+
z_scaled = dr.fma(z, dr.rcp(self.zmax) * (n - 1) / n, 0.5 / n)
|
| 88 |
+
return self.coeff_tex.eval(Point1f(z_scaled))
|
| 89 |
+
|
| 90 |
+
def eval(self, r: Float, radius: Float, σ : Float) -> Float:
|
| 91 |
+
pdf, _, norm = self.eval_pdf(r, radius, σ)
|
| 92 |
+
return pdf * norm
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def eval_pdf(self, r: Float, radius: Float, σ : Float) -> tuple[Float, Float, Float]:
|
| 96 |
+
"""
|
| 97 |
+
Evaluate the Green's function CDF for position ``y`` (between 0 and 1)
|
| 98 |
+
and parameter ``z``. The function returns a tuple containing
|
| 99 |
+
|
| 100 |
+
- the CDF (normalized), which is normalized, i.e., ``eval(1, z)[0] == 1``
|
| 101 |
+
- the y-derivative of the normalized CDF
|
| 102 |
+
- the normalization constant
|
| 103 |
+
|
| 104 |
+
It's fine to call this function even if you do not need all of the
|
| 105 |
+
results. Dr.Jit will optimize the rest away.
|
| 106 |
+
"""
|
| 107 |
+
#pdf, cdf, norm = self.eval_pdf_with_coeffs_y(r/radius, self.fetch_coeffs(radius * dr.sqrt(σ)))
|
| 108 |
+
pdf, cdf, norm = self.eval_pdf_with_coeffs_y(r/radius, self.coeffs)
|
| 109 |
+
pdf *= dr.rcp(radius)
|
| 110 |
+
norm *= radius if self.is_grad else dr.square(radius)
|
| 111 |
+
return pdf, cdf, norm
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def eval_pdf_with_coeffs_y(
|
| 115 |
+
self, y: Float, coeffs: list[Float]
|
| 116 |
+
) -> tuple[Float, Float, Float]:
|
| 117 |
+
"""
|
| 118 |
+
Implementation of the ``eval`` function. This function has
|
| 119 |
+
essentially the same signature but expects that polynomial
|
| 120 |
+
coefficients (obtained via ``fetch_coeffs()``) are provided
|
| 121 |
+
via the ``coeffs`` parameter.
|
| 122 |
+
"""
|
| 123 |
+
assert len(coeffs) == self.ncoeffs
|
| 124 |
+
|
| 125 |
+
L_accum, Ld_accum, R_accum, Rd_accum, norm = (
|
| 126 |
+
Float(0),
|
| 127 |
+
Float(0),
|
| 128 |
+
Float(0),
|
| 129 |
+
Float(0),
|
| 130 |
+
Float(0),
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
y2 = dr.square(y)
|
| 134 |
+
|
| 135 |
+
for i in reversed(range(0, self.ncoeffs, 2)):
|
| 136 |
+
exponent = i + 2 - int(self.is_grad)
|
| 137 |
+
R, L = coeffs[i], coeffs[i + 1]
|
| 138 |
+
R_accum = dr.fma(R_accum, y2, R)
|
| 139 |
+
L_accum = dr.fma(L_accum, y2, L)
|
| 140 |
+
Rd_accum = dr.fma(Rd_accum, y2, R * exponent)
|
| 141 |
+
Ld_accum = dr.fma(Ld_accum, y2, L * exponent)
|
| 142 |
+
norm += R
|
| 143 |
+
|
| 144 |
+
log_x = dr.log(dr.maximum(y, 1e-10))
|
| 145 |
+
inv_norm = dr.rcp(norm)
|
| 146 |
+
|
| 147 |
+
value = dr.fma(L_accum, log_x, R_accum) * inv_norm
|
| 148 |
+
deriv = dr.fma(Ld_accum, log_x, Rd_accum + L_accum) * inv_norm
|
| 149 |
+
|
| 150 |
+
if self.is_grad:
|
| 151 |
+
value *= y
|
| 152 |
+
else:
|
| 153 |
+
value *= y2
|
| 154 |
+
deriv *= y
|
| 155 |
+
|
| 156 |
+
return deriv, value, norm
|
| 157 |
+
|
| 158 |
+
def eval_norm(self, radius : Float, σ : Float) -> Float:
|
| 159 |
+
norm = Float(0)
|
| 160 |
+
#coeffs = self.fetch_coeffs(radius * dr.sqrt(σ))
|
| 161 |
+
for i in reversed(range(0, self.ncoeffs, 2)):
|
| 162 |
+
norm += self.coeffs[i]
|
| 163 |
+
norm *= radius if self.is_grad else dr.square(radius)
|
| 164 |
+
return norm
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@dr.syntax # type: ignore
|
| 168 |
+
def sample(self, x: Float, radius : Float, σ: Float) -> tuple[Float, Float]:
|
| 169 |
+
# The expression to initialize the Newton iteration is numerically
|
| 170 |
+
# unstable when 'z' is too small. Clamp to 1e-1 (for this part only)
|
| 171 |
+
z = radius * dr.sqrt(σ)
|
| 172 |
+
z_init = dr.maximum(z, 1e-1)
|
| 173 |
+
b = None
|
| 174 |
+
norm = Float(0)
|
| 175 |
+
if dr.hint(not self.is_grad, mode='scalar'):
|
| 176 |
+
if dr.hint(self.ndim == 2, mode='scalar'):
|
| 177 |
+
# Based on 'Sample3Composed2' from the Mathematica notebook
|
| 178 |
+
sqrt_x = dr.sqrt(x)
|
| 179 |
+
b = 1 - dr.acosh(dr.fma(dr.cosh(z_init), 1 - sqrt_x, sqrt_x)) / z_init
|
| 180 |
+
elif self.ndim == 3:
|
| 181 |
+
# Based on 'Sample2Composed1' from the Mathematica notebook
|
| 182 |
+
b = (1 - dr.acosh(dr.fma(dr.cosh(z_init), 1 - x, x)) / z_init) ** (2 / 3)
|
| 183 |
+
else:
|
| 184 |
+
raise RuntimeError("Unsupported number of dimensions!")
|
| 185 |
+
else:
|
| 186 |
+
# No good sampling strategy yet
|
| 187 |
+
b = Float(x)
|
| 188 |
+
|
| 189 |
+
# Fetch the coefficients once and then reuse them
|
| 190 |
+
coeffs = self.coeffs
|
| 191 |
+
|
| 192 |
+
# Bracketing interval
|
| 193 |
+
a, c = Float(0), Float(1)
|
| 194 |
+
|
| 195 |
+
# Iteration counter
|
| 196 |
+
i = UInt32(0)
|
| 197 |
+
|
| 198 |
+
while i < self.newton_steps:
|
| 199 |
+
# Perform a Newton step
|
| 200 |
+
deriv, cdf, norm = self.eval_pdf_with_coeffs_y(b, coeffs)
|
| 201 |
+
b = b - (cdf - x) / deriv
|
| 202 |
+
|
| 203 |
+
# Newton-Bisection: potentially reject the Newton step
|
| 204 |
+
bad_step = ~((b >= a) & (b <= c))
|
| 205 |
+
b = dr.select(bad_step, (a + c) / 2, b)
|
| 206 |
+
|
| 207 |
+
# Update bracketing interval
|
| 208 |
+
is_neg = self.eval_pdf_with_coeffs_y(b, coeffs)[1] - x < 0
|
| 209 |
+
a = dr.select(is_neg, b, a)
|
| 210 |
+
c = dr.select(is_neg, c, b)
|
| 211 |
+
|
| 212 |
+
i += 1
|
| 213 |
+
norm *= radius if self.is_grad else dr.square(radius)
|
| 214 |
+
return b * radius, norm
|
| 215 |
+
|
| 216 |
+
def eval_poisson_kernel(self, r: Float, radius: Float, σ : Float) -> Float:
|
| 217 |
+
_, cdf, norm = self.eval_pdf(r, radius, σ)
|
| 218 |
+
return 1 - cdf * norm * σ
|
| 219 |
+
|
data/PDE2D/Sampling/sampling_wos.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import mitsuba as mi
|
| 2 |
+
from mitsuba import Float, Bool
|
| 3 |
+
from .special import *
|
| 4 |
+
from ..utils import *
|
| 5 |
+
from ..utils.helpers import *
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def sample_cosk_direction(sample, direction, k : Float = Float(2)): #k>2
|
| 9 |
+
# sample symmetrically w.r.t. the direction with cos(theta / k)
|
| 10 |
+
right_sphere = sample >= 0.5
|
| 11 |
+
sample = dr.select(right_sphere, 2 * sample - 1, 2 * sample)
|
| 12 |
+
angle_shift = k * dr.asin(sample * dr.sin(dr.pi /k))
|
| 13 |
+
angle_shift = dr.select(right_sphere, angle_shift, -angle_shift)
|
| 14 |
+
angle_initial = dr.atan2(direction[1], direction[0])
|
| 15 |
+
angle = angle_initial + angle_shift
|
| 16 |
+
sampled_direction = mi.Point2f(dr.cos(angle), dr.sin(angle))
|
| 17 |
+
pdf = dr.rcp(2 * k * dr.sin(dr.pi /k)) * dr.cos(angle_shift / k)
|
| 18 |
+
return sampled_direction, pdf
|
| 19 |
+
|
| 20 |
+
def pdf_cosk_direction(sampled_direction, direction, k): #k>2
|
| 21 |
+
angle_diff = dr.abs(dr.acos(dr.dot(sampled_direction, direction)))
|
| 22 |
+
return dr.rcp(2 * k * dr.sin(dr.pi /k)) * dr.cos(angle_diff / k)
|
| 23 |
+
|
| 24 |
+
@dr.syntax
|
| 25 |
+
def sample_star_direction(sample, half_space_mask : Bool, boundary_normal : mi.Point2f) -> tuple[mi.Point2f, mi.Float]:
|
| 26 |
+
angle = mi.Float(0)
|
| 27 |
+
direction = mi.Point2f(0)
|
| 28 |
+
pdf = mi.Float(0)
|
| 29 |
+
if half_space_mask:
|
| 30 |
+
angle = mi.Float((sample - 0.5) * dr.pi)
|
| 31 |
+
direction = mi.Point2f(dr.sin(angle), dr.cos(angle))
|
| 32 |
+
direction = dr.normalize(to_world_direction(direction, boundary_normal))
|
| 33 |
+
pdf = Float(1/dr.pi)
|
| 34 |
+
else:
|
| 35 |
+
angle = mi.Float(2 * dr.pi * sample)
|
| 36 |
+
direction = mi.Point2f(dr.sin(angle), dr.cos(angle))
|
| 37 |
+
pdf = Float(1 / (2 * dr.pi))
|
| 38 |
+
return direction, pdf
|
| 39 |
+
|
| 40 |
+
def sample_uniform_direction(sample):
|
| 41 |
+
theta = 2 * dr.pi * sample
|
| 42 |
+
return mi.Point2f(dr.sin(theta), dr.cos(theta)), Float(1/(2 * dr.pi))
|
| 43 |
+
|
| 44 |
+
def sample_uniform_boundary(sample, origin, radius):
|
| 45 |
+
direction, pdf = sample_uniform_direction(sample)
|
| 46 |
+
sampled_points = origin + radius * direction
|
| 47 |
+
return sampled_points, pdf / radius
|
| 48 |
+
|
| 49 |
+
def sample_cosine_direction(sample : Float, direction : mi.Point2f) -> tuple[mi.Point2f, Float, Float]:
|
| 50 |
+
upper_sphere = sample >= 0.5
|
| 51 |
+
sample = dr.select(upper_sphere, 2 * sample - 1, 2 * sample)
|
| 52 |
+
angle_shift = dr.asin(2 * sample - 1)
|
| 53 |
+
abs_dot_prod = dr.sqrt(1 - dr.square(2 * sample -1))
|
| 54 |
+
angle_initial = dr.atan2(direction[1], direction[0])
|
| 55 |
+
angle = angle_initial + angle_shift
|
| 56 |
+
sampled_direction = mi.Point2f(dr.cos(angle), dr.sin(angle))
|
| 57 |
+
sign = dr.select(upper_sphere, Float(1), Float(-1))
|
| 58 |
+
sampled_direction *= sign
|
| 59 |
+
return sampled_direction, abs_dot_prod / 4, sign
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def sample_cosine_boundary(sample : Float, origin : mi.Point2f, radius : Float, direction : mi.Point2f) -> tuple[mi.Point2f, Float, Float]:
|
| 63 |
+
sampled_direction, pdf, sign = sample_cosine_direction(sample, direction)
|
| 64 |
+
point = origin + radius * sampled_direction
|
| 65 |
+
return point, pdf / radius, sign
|
| 66 |
+
|
| 67 |
+
def sample_cosine_boundary_antithetic(sample, origin, radius, direction, active):
|
| 68 |
+
angle_shift = dr.asin(2 * sample - 1)
|
| 69 |
+
direction1 = mi.Point2f(dr.sin(angle_shift), dr.cos(angle_shift))
|
| 70 |
+
direction2 = mi.Point2f(dr.sin(angle_shift), -dr.cos(angle_shift))
|
| 71 |
+
direction1 = to_world_direction(direction1, direction)
|
| 72 |
+
direction2 = to_world_direction(direction2, direction)
|
| 73 |
+
point1 = mi.Point2f(dr.select(active, origin + radius * direction1, origin))
|
| 74 |
+
point2 = mi.Point2f(dr.select(active, origin + radius * direction2, origin))
|
| 75 |
+
return point1, point2, dr.cos(angle_shift) / (2 * radius) , 2
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def pdf_cosine_boundary_(sampled_direction, R, direction):
|
| 79 |
+
return 1/4 * dr.abs(dr.dot(dr.normalize(sampled_direction), dr.normalize(direction))) / R
|
| 80 |
+
|
| 81 |
+
def pdf_cosine_boundary(points, origin, R, direction):
|
| 82 |
+
d = dr.normalize(points - origin)
|
| 83 |
+
return pdf_cosine_boundary_(d, R, direction)
|
| 84 |
+
|
| 85 |
+
def sample_uniform_volume(sample, origin, radius):
|
| 86 |
+
r = radius * dr.sqrt(sample[0])
|
| 87 |
+
theta = 2 * dr.pi * sample[1]
|
| 88 |
+
return mi.Point2f(origin + r * mi.Point2f(dr.cos(theta),dr.sin(theta))), dr.rcp(dr.pi * dr.sqr(radius))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def sample_sec_direction(sample : Float, direction : mi.Point2f, threshold : Float = Float(0.49 * dr.pi)):
|
| 93 |
+
negative = sample >= 0.5
|
| 94 |
+
sample = dr.select(negative, 2 * sample - 1, 2 * sample)
|
| 95 |
+
angle_shift = sample_sec_angle(sample, threshold)
|
| 96 |
+
angle_shift *= dr.select(negative, -1., 1)
|
| 97 |
+
|
| 98 |
+
angle_initial = dr.atan2(direction[1], direction[0])
|
| 99 |
+
angle = angle_initial + angle_shift
|
| 100 |
+
sampled_direction = mi.Point2f(dr.cos(angle), dr.sin(angle))
|
| 101 |
+
return sampled_direction
|
| 102 |
+
|
| 103 |
+
@dr.syntax
|
| 104 |
+
def pdf_sec_direction(dir : mi.Point2f, direction : mi.Point2f, threshold : Float = Float(0.49 * dr.pi)):
|
| 105 |
+
pdf = Float(0)
|
| 106 |
+
sec = dr.rcp(dr.dot(dir, direction))
|
| 107 |
+
csc_d = dr.rcp(dr.sin(threshold))
|
| 108 |
+
sec_d = dr.rcp(dr.cos(threshold))
|
| 109 |
+
normalization = 0.5 * dr.log((1 + csc_d)/(-1 + csc_d)) + (dr.pi/2 - threshold) * sec_d
|
| 110 |
+
|
| 111 |
+
if (sec > 0) & (sec < sec_d):
|
| 112 |
+
pdf = sec
|
| 113 |
+
elif (sec >= sec_d):
|
| 114 |
+
pdf = sec_d
|
| 115 |
+
return pdf / normalization * 0.5
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@dr.syntax
|
| 119 |
+
def sample_sec_angle(sample : Float, threshold : Float = Float(0.49 * dr.pi)):
|
| 120 |
+
csc_d = dr.rcp(dr.sin(threshold))
|
| 121 |
+
sec_d = dr.rcp(dr.cos(threshold))
|
| 122 |
+
|
| 123 |
+
th_val = 0.5 * dr.log((1 + csc_d)/(-1 + csc_d))
|
| 124 |
+
normalization = th_val + (dr.pi/2 - threshold) * sec_d
|
| 125 |
+
sample *= normalization
|
| 126 |
+
|
| 127 |
+
sampled_p = Float(0)
|
| 128 |
+
if sample < th_val:
|
| 129 |
+
exp = dr.exp(2 * sample)
|
| 130 |
+
sampled_p = dr.asin((exp - 1)/(exp + 1))
|
| 131 |
+
else:
|
| 132 |
+
sampled_p = threshold + (sample - th_val) / (normalization - th_val) * (dr.pi / 2 - threshold)
|
| 133 |
+
return sampled_p
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@dr.syntax
|
| 137 |
+
def pdf_sec_angle(angle : Float, threshold : Float = Float(0.49 * dr.pi)): # pdf with respect to secant.
|
| 138 |
+
pdf = Float(0)
|
| 139 |
+
sec = dr.rcp(dr.cos(angle))
|
| 140 |
+
csc_d = dr.rcp(dr.sin(threshold))
|
| 141 |
+
sec_d = dr.rcp(dr.cos(threshold))
|
| 142 |
+
normalization = 0.5 * dr.log((1 + csc_d)/(-1 + csc_d)) + (dr.pi/2 - threshold) * sec_d
|
| 143 |
+
if (angle >= 0) & (angle < threshold):
|
| 144 |
+
pdf = sec
|
| 145 |
+
elif (angle >= threshold) & (angle <= dr.pi/2):
|
| 146 |
+
pdf = sec_d
|
| 147 |
+
return pdf / normalization
|
| 148 |
+
|
| 149 |
+
@dr.syntax
|
| 150 |
+
def eval_dP_norm(radius : Float, σ : Float) -> Float:
|
| 151 |
+
# used in directional derivative
|
| 152 |
+
sqrtσ = dr.sqrt(σ)
|
| 153 |
+
z = radius * sqrtσ
|
| 154 |
+
result = Float(0)
|
| 155 |
+
if z < 0.001:
|
| 156 |
+
result = dr.rcp(dr.pi * dr.square(radius))
|
| 157 |
+
else:
|
| 158 |
+
result = sqrtσ * dr.rcp(2 * dr.pi * radius * i1(radius * sqrtσ))
|
| 159 |
+
return result
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def eval_Pσr_(r, R, sigma, in_mask = Bool(False)): # multiplied with 2 * pi * r version
|
| 163 |
+
z = R * dr.sqrt(sigma)
|
| 164 |
+
y = r / R
|
| 165 |
+
return dr.select(in_mask, Qσ(y, z), eval_Pσrs_(R, sigma))
|
| 166 |
+
|
| 167 |
+
def eval_Pσrs_(R, sigma):
|
| 168 |
+
return dr.rcp(i0(R * dr.sqrt(sigma)))
|
data/PDE2D/Sampling/special.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import drjit as dr
|
| 2 |
+
import mitsuba as mi
|
| 3 |
+
import numpy as np
|
| 4 |
+
from math import nan,inf
|
| 5 |
+
from mitsuba import Float
|
| 6 |
+
|
| 7 |
+
use_special_form = True
|
| 8 |
+
#C = 5
|
| 9 |
+
A_i0 = Float([
|
| 10 |
+
-4.41534164647933937950E-18, 3.33079451882223809783E-17,
|
| 11 |
+
-2.43127984654795469359E-16, 1.71539128555513303061E-15,
|
| 12 |
+
-1.16853328779934516808E-14, 7.67618549860493561688E-14,
|
| 13 |
+
-4.85644678311192946090E-13, 2.95505266312963983461E-12,
|
| 14 |
+
-1.72682629144155570723E-11, 9.67580903537323691224E-11,
|
| 15 |
+
-5.18979560163526290666E-10, 2.65982372468238665035E-9,
|
| 16 |
+
-1.30002500998624804212E-8, 6.04699502254191894932E-8,
|
| 17 |
+
-2.67079385394061173391E-7, 1.11738753912010371815E-6,
|
| 18 |
+
-4.41673835845875056359E-6, 1.64484480707288970893E-5,
|
| 19 |
+
-5.75419501008210370398E-5, 1.88502885095841655729E-4,
|
| 20 |
+
-5.76375574538582365885E-4, 1.63947561694133579842E-3,
|
| 21 |
+
-4.32430999505057594430E-3, 1.05464603945949983183E-2,
|
| 22 |
+
-2.37374148058994688156E-2, 4.93052842396707084878E-2,
|
| 23 |
+
-9.49010970480476444210E-2, 1.71620901522208775349E-1,
|
| 24 |
+
-3.04682672343198398683E-1, 6.76795274409476084995E-1])
|
| 25 |
+
|
| 26 |
+
B_i0 = Float([
|
| 27 |
+
-7.23318048787475395456E-18, -4.83050448594418207126E-18,
|
| 28 |
+
4.46562142029675999901E-17, 3.46122286769746109310E-17,
|
| 29 |
+
-2.82762398051658348494E-16, -3.42548561967721913462E-16,
|
| 30 |
+
1.77256013305652638360E-15, 3.81168066935262242075E-15,
|
| 31 |
+
-9.55484669882830764870E-15, -4.15056934728722208663E-14,
|
| 32 |
+
1.54008621752140982691E-14, 3.85277838274214270114E-13,
|
| 33 |
+
7.18012445138366623367E-13, -1.79417853150680611778E-12,
|
| 34 |
+
-1.32158118404477131188E-11, -3.14991652796324136454E-11,
|
| 35 |
+
1.18891471078464383424E-11, 4.94060238822496958910E-10,
|
| 36 |
+
3.39623202570838634515E-9, 2.26666899049817806459E-8,
|
| 37 |
+
2.04891858946906374183E-7, 2.89137052083475648297E-6,
|
| 38 |
+
6.88975834691682398426E-5, 3.36911647825569408990E-3,
|
| 39 |
+
8.04490411014108831608E-1])
|
| 40 |
+
|
| 41 |
+
A_k0 = Float([
|
| 42 |
+
1.37446543561352307156E-16, 4.25981614279661018399E-14,
|
| 43 |
+
1.03496952576338420167E-11, 1.90451637722020886025E-9,
|
| 44 |
+
2.53479107902614945675E-7, 2.28621210311945178607E-5,
|
| 45 |
+
1.26461541144692592338E-3, 3.59799365153615016266E-2,
|
| 46 |
+
3.44289899924628486886E-1, -5.35327393233902768720E-1])
|
| 47 |
+
|
| 48 |
+
B_k0 = Float([
|
| 49 |
+
5.30043377268626276149E-18, -1.64758043015242134646E-17,
|
| 50 |
+
5.21039150503902756861E-17, -1.67823109680541210385E-16,
|
| 51 |
+
5.51205597852431940784E-16, -1.84859337734377901440E-15,
|
| 52 |
+
6.34007647740507060557E-15, -2.22751332699166985548E-14,
|
| 53 |
+
8.03289077536357521100E-14, -2.98009692317273043925E-13,
|
| 54 |
+
1.14034058820847496303E-12, -4.51459788337394416547E-12,
|
| 55 |
+
1.85594911495471785253E-11, -7.95748924447710747776E-11,
|
| 56 |
+
3.57739728140030116597E-10, -1.69753450938905987466E-9,
|
| 57 |
+
8.57403401741422608519E-9, -4.66048989768794782956E-8,
|
| 58 |
+
2.76681363944501510342E-7, -1.83175552271911948767E-6,
|
| 59 |
+
1.39498137188764993662E-5, -1.28495495816278026384E-4,
|
| 60 |
+
1.56988388573005337491E-3, -3.14481013119645005427E-2,
|
| 61 |
+
2.44030308206595545468E0])
|
| 62 |
+
|
| 63 |
+
A_i1 = Float([
|
| 64 |
+
2.77791411276104639959E-18, -2.11142121435816608115E-17,
|
| 65 |
+
1.55363195773620046921E-16, -1.10559694773538630805E-15,
|
| 66 |
+
7.60068429473540693410E-15, -5.04218550472791168711E-14,
|
| 67 |
+
3.22379336594557470981E-13, -1.98397439776494371520E-12,
|
| 68 |
+
1.17361862988909016308E-11, -6.66348972350202774223E-11,
|
| 69 |
+
3.62559028155211703701E-10, -1.88724975172282928790E-9,
|
| 70 |
+
9.38153738649577178388E-9, -4.44505912879632808065E-8,
|
| 71 |
+
2.00329475355213526229E-7, -8.56872026469545474066E-7,
|
| 72 |
+
3.47025130813767847674E-6, -1.32731636560394358279E-5,
|
| 73 |
+
4.78156510755005422638E-5, -1.61760815825896745588E-4,
|
| 74 |
+
5.12285956168575772895E-4, -1.51357245063125314899E-3,
|
| 75 |
+
4.15642294431288815669E-3, -1.05640848946261981558E-2,
|
| 76 |
+
2.47264490306265168283E-2, -5.29459812080949914269E-2,
|
| 77 |
+
1.02643658689847095384E-1, -1.76416518357834055153E-1,
|
| 78 |
+
2.52587186443633654823E-1])
|
| 79 |
+
|
| 80 |
+
B_i1 = Float([
|
| 81 |
+
7.51729631084210481353E-18, 4.41434832307170791151E-18,
|
| 82 |
+
-4.65030536848935832153E-17, -3.20952592199342395980E-17,
|
| 83 |
+
2.96262899764595013876E-16, 3.30820231092092828324E-16
|
| 84 |
+
-1.88035477551078244854E-15, -3.81440307243700780478E-15,
|
| 85 |
+
1.04202769841288027642E-14, 4.27244001671195135429E-14,
|
| 86 |
+
-2.10154184277266431302E-14,-4.08355111109219731823E-13,
|
| 87 |
+
-7.19855177624590851209E-13,2.03562854414708950722E-12,
|
| 88 |
+
1.41258074366137813316E-11, 3.25260358301548823856E-11,
|
| 89 |
+
-1.89749581235054123450E-11, -5.58974346219658380687E-10,
|
| 90 |
+
-3.83538038596423702205E-9, -2.63146884688951950684E-8,
|
| 91 |
+
-2.51223623787020892529E-7,-3.88256480887769039346E-6,
|
| 92 |
+
-1.10588938762623716291E-4, -9.76109749136146840777E-3,
|
| 93 |
+
7.78576235018280120474E-1])
|
| 94 |
+
|
| 95 |
+
A_k1 = Float([
|
| 96 |
+
-7.02386347938628759343E-18, -2.42744985051936593393E-15,
|
| 97 |
+
-6.66690169419932900609E-13,-1.41148839263352776110E-10,
|
| 98 |
+
-2.21338763073472585583E-8,-2.43340614156596823496E-6,
|
| 99 |
+
-1.73028895751305206302E-4,-6.97572385963986435018E-3,
|
| 100 |
+
-1.22611180822657148235E-1,-3.53155960776544875667E-1,
|
| 101 |
+
1.52530022733894777053E0])
|
| 102 |
+
|
| 103 |
+
B_k1 = Float([
|
| 104 |
+
-5.75674448366501715755E-18,1.79405087314755922667E-17,
|
| 105 |
+
-5.68946255844285935196E-17,1.83809354436663880070E-16,
|
| 106 |
+
-6.05704724837331885336E-16,2.03870316562433424052E-15,
|
| 107 |
+
-7.01983709041831346144E-15,2.47715442448130437068E-14,
|
| 108 |
+
-8.97670518232499435011E-14,3.34841966607842919884E-13,
|
| 109 |
+
-1.28917396095102890680E-12,5.13963967348173025100E-12,
|
| 110 |
+
-2.12996783842756842877E-11,9.21831518760500529508E-11,
|
| 111 |
+
-4.19035475934189648750E-10,2.01504975519703286596E-9,
|
| 112 |
+
-1.03457624656780970260E-8,5.74108412545004946722E-8,
|
| 113 |
+
-3.50196060308781257119E-7,2.40648494783721712015E-6,
|
| 114 |
+
-1.93619797416608296024E-5,1.95215518471351631108E-4,
|
| 115 |
+
-2.85781685962277938680E-3,1.03923736576817238437E-1,
|
| 116 |
+
2.72062619048444266945E0])
|
| 117 |
+
|
| 118 |
+
""" Implementation of some special functions."""
|
| 119 |
+
|
| 120 |
+
""" Evaluate Chebyshev polynomial at x/2 argument."""
|
| 121 |
+
@dr.syntax
|
| 122 |
+
def chebyshev(x , coeffs):
|
| 123 |
+
b0 = Float(coeffs[0])
|
| 124 |
+
b1 = Float(0)
|
| 125 |
+
b2 = Float(0)
|
| 126 |
+
i = 0
|
| 127 |
+
while dr.hint(i < dr.width(coeffs), mode = 'scalar'):
|
| 128 |
+
b2 = b1
|
| 129 |
+
b1 = b0
|
| 130 |
+
b0 = x * b1 - (b2 - coeffs[i])
|
| 131 |
+
i += 1
|
| 132 |
+
return (b0 - b2) * 0.5;
|
| 133 |
+
|
| 134 |
+
@dr.syntax
|
| 135 |
+
def Gσ(y : Float, z : Float) -> Float: # Multiplied with 2*pi version
|
| 136 |
+
result = Float(0)
|
| 137 |
+
#if dr.hint(use_special_form, mode = 'scalar'):
|
| 138 |
+
c_i0_yz_below8 = chebyshev(y * z/2.0 - 2.0, A_i0)
|
| 139 |
+
c_i0_z_above8 = chebyshev(32.0/z - 2.0, B_i0)
|
| 140 |
+
i0_div = Float(0)
|
| 141 |
+
c_i0_yz_above8 = Float(0)
|
| 142 |
+
c_i0_z_below8 = Float(0)
|
| 143 |
+
if (y * z > 8):
|
| 144 |
+
c_i0_yz_above8 = chebyshev(32.0/(y * z) - 2.0, B_i0)
|
| 145 |
+
i0_div = c_i0_yz_above8/c_i0_z_above8 / dr.sqrt(y)
|
| 146 |
+
elif (z <= 8):
|
| 147 |
+
c_i0_z_below8 = chebyshev(z/2.0 - 2.0, A_i0)
|
| 148 |
+
i0_div = c_i0_yz_below8/c_i0_z_below8
|
| 149 |
+
else:
|
| 150 |
+
i0_div = c_i0_yz_below8/c_i0_z_above8 / dr.sqrt(z)
|
| 151 |
+
result = (k0(y * z) - k0(z) * i0_div * dr.exp((y-1) * z))
|
| 152 |
+
#else:
|
| 153 |
+
# result = k0(y * z) - k0(z) * i0(y * z) / i0(z)
|
| 154 |
+
|
| 155 |
+
valid_region = (y<1) & (y>0)
|
| 156 |
+
result = dr.select(valid_region, result, 0)
|
| 157 |
+
return result
|
| 158 |
+
|
| 159 |
+
@dr.syntax
|
| 160 |
+
def dGσ(y: Float, z: Float) -> Float: # Multiplied with 2*pi version
|
| 161 |
+
result = Float(0)
|
| 162 |
+
#if use_special_form:
|
| 163 |
+
c_i1_yz_below8 = chebyshev(y * z/2.0 - 2.0, A_i1)
|
| 164 |
+
c_i1_z_above8 = chebyshev(32.0/z - 2.0, B_i1)
|
| 165 |
+
i1_div = Float(0)
|
| 166 |
+
c_i1_yz_above8 = Float(0)
|
| 167 |
+
c_i1_z_below8 = Float(0)
|
| 168 |
+
if (y * z > 8):
|
| 169 |
+
c_i1_yz_above8 = chebyshev(32.0/(y * z) - 2.0, B_i1)
|
| 170 |
+
i1_div = c_i1_yz_above8/c_i1_z_above8 / dr.sqrt(y)
|
| 171 |
+
elif z <= 8:
|
| 172 |
+
c_i1_z_below8 = chebyshev(z/2.0 - 2.0, A_i1)
|
| 173 |
+
i1_div = c_i1_yz_below8/c_i1_z_below8 * y
|
| 174 |
+
else:
|
| 175 |
+
i1_div = c_i1_yz_below8/c_i1_z_above8 * y * z * dr.sqrt(z)
|
| 176 |
+
|
| 177 |
+
result = k1(y * z) - k1(z) * i1_div * dr.exp((y-1) * z)
|
| 178 |
+
#else:
|
| 179 |
+
# result = k1(y * z) - k1(z) * i1(y * z) / i1(z)
|
| 180 |
+
|
| 181 |
+
valid_region = (y<1) & (y>=0)
|
| 182 |
+
result = dr.select(valid_region, result, 0)
|
| 183 |
+
return result
|
| 184 |
+
|
| 185 |
+
@dr.syntax
|
| 186 |
+
def Gσr_int(y : Float, z : Float) -> Float: # This returns sigma |G|.
|
| 187 |
+
#if use_special_form:
|
| 188 |
+
c_i1_yz_below8 = chebyshev(y * z/2.0 - 2.0, A_i1)
|
| 189 |
+
c_i0_z_above8 = chebyshev(32.0/z - 2.0, B_i0)
|
| 190 |
+
c_i1_yz_above8 = Float(0)
|
| 191 |
+
c_i0_z_below8 = Float(0)
|
| 192 |
+
i_div = Float(0)
|
| 193 |
+
if y * z > 8:
|
| 194 |
+
c_i1_yz_above8 = chebyshev(32.0/(y * z) - 2.0, B_i1)
|
| 195 |
+
i_div = c_i1_yz_above8/c_i0_z_above8 / dr.sqrt(y)
|
| 196 |
+
elif z <= 8:
|
| 197 |
+
c_i0_z_below8 = chebyshev(z/2.0 - 2.0, A_i0)
|
| 198 |
+
i_div = c_i1_yz_below8/c_i0_z_below8 * z * y
|
| 199 |
+
else:
|
| 200 |
+
i_div = c_i1_yz_below8/c_i0_z_above8 * z * y * dr.sqrt(z)
|
| 201 |
+
result = 1 - y * z * (i_div * k0(z) * dr.exp((y-1) * z) + k1(y * z))
|
| 202 |
+
#else:
|
| 203 |
+
# result = 1 - y * z * (k0(z) * i1(y * z) / i0(z) + k1(y * z))
|
| 204 |
+
return result
|
| 205 |
+
|
| 206 |
+
def Qσ(y,z):
|
| 207 |
+
return 1 - Gσr_int(y,z) * dr.square(z)
|
| 208 |
+
|
| 209 |
+
@dr.syntax
|
| 210 |
+
def i0(x_ : Float) -> Float:
|
| 211 |
+
x = dr.abs(x_)
|
| 212 |
+
x = dr.select(x == 0, dr.epsilon(Float), x)
|
| 213 |
+
if x<=8:
|
| 214 |
+
result = chebyshev(x/2.0 - 2.0, A_i0)
|
| 215 |
+
else:
|
| 216 |
+
result = chebyshev(32.0/x - 2.0, B_i0) / dr.sqrt(x)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
if x_==0:
|
| 220 |
+
result = Float(1)
|
| 221 |
+
else:
|
| 222 |
+
result *= dr.exp(x)
|
| 223 |
+
return result
|
| 224 |
+
|
| 225 |
+
@dr.syntax
|
| 226 |
+
def k0(x_):
|
| 227 |
+
x = dr.abs(x_)
|
| 228 |
+
|
| 229 |
+
if x == Float(0):
|
| 230 |
+
x = Float(dr.epsilon(Float))
|
| 231 |
+
|
| 232 |
+
if x <= 2:
|
| 233 |
+
result = chebyshev((dr.sqr(x) - 2), A_k0) - dr.log(0.5 * x) * i0(x)
|
| 234 |
+
else:
|
| 235 |
+
result = dr.exp(-x) * chebyshev(8.0 / x - 2, B_k0) / dr.sqrt(x)
|
| 236 |
+
if x_ == 0:
|
| 237 |
+
result = Float(dr.inf)
|
| 238 |
+
if x_ < 0:
|
| 239 |
+
result = Float(dr.nan)
|
| 240 |
+
return result
|
| 241 |
+
|
| 242 |
+
@dr.syntax
|
| 243 |
+
def i1(x_):
|
| 244 |
+
x = dr.abs(x_)
|
| 245 |
+
if x == 0:
|
| 246 |
+
x += dr.epsilon(Float)
|
| 247 |
+
|
| 248 |
+
if x<=8:
|
| 249 |
+
result = chebyshev(x/2.0 - 2.0, A_i1) * x
|
| 250 |
+
else:
|
| 251 |
+
result = chebyshev(32.0 / x - 2.0, B_i1) / dr.sqrt(x)
|
| 252 |
+
|
| 253 |
+
if x_ == 0:
|
| 254 |
+
result = Float(0)
|
| 255 |
+
if x_ < 0:
|
| 256 |
+
result = -result
|
| 257 |
+
return result * dr.exp(x)
|
| 258 |
+
|
| 259 |
+
@dr.syntax
|
| 260 |
+
def k1(x_):
|
| 261 |
+
x = dr.abs(x_)
|
| 262 |
+
|
| 263 |
+
if x == 0:
|
| 264 |
+
x += dr.epsilon(Float)
|
| 265 |
+
|
| 266 |
+
if x <= 2:
|
| 267 |
+
result = dr.log(x * 0.5) * i1(x) + chebyshev(dr.sqr(x) - 2.0, A_k1) / x
|
| 268 |
+
else:
|
| 269 |
+
result = dr.exp(-x) * chebyshev(8.0 / x -2, B_k1) / dr.sqrt(x)
|
| 270 |
+
if x_ == 0:
|
| 271 |
+
result = Float(dr.inf)
|
| 272 |
+
if x_ < 0:
|
| 273 |
+
result = Float(dr.nan)
|
| 274 |
+
return result
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
## Remove the exponential terms
|
| 278 |
+
|
| 279 |
+
# divided by exp(x)
|
| 280 |
+
@dr.syntax
|
| 281 |
+
def i0_(x_):
|
| 282 |
+
x = dr.abs(x_)
|
| 283 |
+
x = dr.select(x == 0, dr.epsilon(Float), x)
|
| 284 |
+
if x<=8:
|
| 285 |
+
result = chebyshev(x/2.0 - 2.0, A_i0)
|
| 286 |
+
else:
|
| 287 |
+
result = chebyshev(32.0/x - 2.0, B_i0) / dr.sqrt(x)
|
| 288 |
+
|
| 289 |
+
if x_==0:
|
| 290 |
+
result = Float(1)
|
| 291 |
+
return result
|
| 292 |
+
|
| 293 |
+
# multiplied by exp(x)
|
| 294 |
+
@dr.syntax
|
| 295 |
+
def k0_(x_):
|
| 296 |
+
x = dr.abs(x_)
|
| 297 |
+
if x == 0:
|
| 298 |
+
x += dr.epsilon(Float)
|
| 299 |
+
if x <= 2:
|
| 300 |
+
result = dr.exp(x) (chebyshev((dr.sqr(x) - 2), A_k0) - dr.log(0.5 * x) * i0(x))
|
| 301 |
+
else:
|
| 302 |
+
result = chebyshev(8.0 / x - 2, B_k0) / dr.sqrt(x),
|
| 303 |
+
if x_ == 0:
|
| 304 |
+
result = Float(dr.inf)
|
| 305 |
+
if x_ < 0:
|
| 306 |
+
result = Float(dr.nan)
|
| 307 |
+
return result
|
| 308 |
+
|
| 309 |
+
# divided by exp(x)
|
| 310 |
+
@dr.syntax
|
| 311 |
+
def i1_(x_):
|
| 312 |
+
x = dr.abs(x_)
|
| 313 |
+
if x == 0:
|
| 314 |
+
x += dr.epsilon(Float)
|
| 315 |
+
|
| 316 |
+
if x<=8:
|
| 317 |
+
result = chebyshev(x/2.0 - 2.0, A_i1) * x
|
| 318 |
+
else:
|
| 319 |
+
result = chebyshev(32.0 / x - 2.0, B_i1) / dr.sqrt(x)
|
| 320 |
+
|
| 321 |
+
if x_ == 0:
|
| 322 |
+
result = Float(0)
|
| 323 |
+
if x_ < 0:
|
| 324 |
+
result = -result
|
| 325 |
+
return result
|
| 326 |
+
|
| 327 |
+
# multiplied by exp(x)
|
| 328 |
+
@dr.syntax
|
| 329 |
+
def k1_(x_):
|
| 330 |
+
x = dr.abs(x_)
|
| 331 |
+
|
| 332 |
+
if x == 0:
|
| 333 |
+
x += dr.epsilon(Float)
|
| 334 |
+
|
| 335 |
+
if x <= 2:
|
| 336 |
+
result = dr.exp(x) * (dr.log(x * 0.5) * i1(x) + chebyshev(dr.sqr(x) - 2.0, A_k1) / x)
|
| 337 |
+
else:
|
| 338 |
+
result = chebyshev(8.0 / x -2, B_k1) / dr.sqrt(x)
|
| 339 |
+
if x_ == 0:
|
| 340 |
+
result = Float(inf)
|
| 341 |
+
if x_ < 0:
|
| 342 |
+
result = Float(nan)
|
| 343 |
+
return result
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
|
data/PDE2D/Solver/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .data_holder import DataHolder, RegularizationType
|
| 2 |
+
from .constant.wos_constant import WosConstant
|
| 3 |
+
from .constant.wost_constant import WostConstant
|
| 4 |
+
from .constant.wos_constant_rejection import WosConstantRejection
|
| 5 |
+
from .variable.wos_variable import WosVariable
|
| 6 |
+
from .variable.wost_variable import WostVariable
|
| 7 |
+
from .variable.wos_variable_rejection import WosVariableRejection
|
data/PDE2D/Solver/constant/wos_constant.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import sys
|
| 3 |
+
import mitsuba as mi
|
| 4 |
+
from mitsuba import Bool, Float, Point2f, PCG32, UInt64, UInt32
|
| 5 |
+
from PDE2D import GreenSampling, DIM, ArrayXb, ArrayXf
|
| 6 |
+
from ..data_holder import DataHolder
|
| 7 |
+
from ...Coefficient import *
|
| 8 |
+
from ...Sampling import *
|
| 9 |
+
from PDE2D.BoundaryShape import *
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Particle:
|
| 13 |
+
DRJIT_STRUCT = {
|
| 14 |
+
'points' : Point2f,
|
| 15 |
+
'w': Float,
|
| 16 |
+
'sampler' : PCG32,
|
| 17 |
+
'path_index' : UInt32,
|
| 18 |
+
'path_length' : UInt32,
|
| 19 |
+
'thrown' : Bool
|
| 20 |
+
}
|
| 21 |
+
def __init__(self, points=None, w=None, sampler = None, path_index = None, path_length = None):
|
| 22 |
+
self.points = points
|
| 23 |
+
self.w = w
|
| 24 |
+
self.sampler = sampler
|
| 25 |
+
self.path_index = path_index
|
| 26 |
+
self.path_length = path_length
|
| 27 |
+
self.thrown = dr.zeros(Bool, dr.width(self.points))
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class WosConstant(object):
|
| 31 |
+
def __init__(self, input : DataHolder, seed : int = 37,
|
| 32 |
+
max_z : float = 4, green_sampling : GreenSampling = 0,
|
| 33 |
+
newton_steps : int = 5, opt_params : list[str] = []) -> None:
|
| 34 |
+
self.input = input
|
| 35 |
+
if(type(self.input.α) is not ConstantCoefficient):
|
| 36 |
+
raise Exception("Diffusion parameter needs to be constant coefficient!")
|
| 37 |
+
if(type(self.input.σ) is not ConstantCoefficient):
|
| 38 |
+
raise Exception("Screening parameter needs to be constant coefficient!")
|
| 39 |
+
self.σ = Float(self.input.σ.get_value(Point2f(0)) / self.input.α.get_value(Point2f(0)))
|
| 40 |
+
self.seed = UInt64(seed)
|
| 41 |
+
dr.make_opaque(self.seed)
|
| 42 |
+
self.input = input
|
| 43 |
+
self.max_z = Float(max_z)
|
| 44 |
+
dr.make_opaque(self.max_z)
|
| 45 |
+
self.opt_params = {}
|
| 46 |
+
self.get_opt_params(self.opt_params, opt_params)
|
| 47 |
+
|
| 48 |
+
if green_sampling == GreenSampling.Polynomial:
|
| 49 |
+
self.green = GreensFunctionPolynomial(dim = DIM.Two, newton_steps = newton_steps)
|
| 50 |
+
else:
|
| 51 |
+
self.green = GreensFunctionAnalytic(dim = DIM.Two, newton_steps = newton_steps)
|
| 52 |
+
|
| 53 |
+
def change_seed(self, seed : int):
|
| 54 |
+
self.seed = dr.opaque(UInt64, seed, shape = (1))
|
| 55 |
+
|
| 56 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 57 |
+
self.input.get_opt_params(param_dict, opt_params)
|
| 58 |
+
|
| 59 |
+
def update(self, opt):
|
| 60 |
+
self.input.update(opt)
|
| 61 |
+
self.σ = Float(self.input.σ.get_value(Point2f(0)) / self.input.α.get_value(Point2f(0)))
|
| 62 |
+
self.input.shape.update_shape(opt)
|
| 63 |
+
|
| 64 |
+
def zero_grad(self):
|
| 65 |
+
self.input.zero_grad()
|
| 66 |
+
|
| 67 |
+
@dr.syntax(print_code = False)
|
| 68 |
+
def solve(self, points_in = None, active_conf_in : ArrayXb = None, L_in : ArrayXf = None, initial_w : Float = Float(1),
|
| 69 |
+
mode : dr.ADMode = dr.ADMode.Primal, dL = ArrayXf(0),
|
| 70 |
+
derivative_dir : Point2f = None, conf_numbers : list[UInt32] = [UInt32(0)], all_inside = False,
|
| 71 |
+
max_step = dr.inf, normal_derivative_dist : float = None) -> list[Float, Particle]:
|
| 72 |
+
|
| 73 |
+
if conf_numbers is not None:
|
| 74 |
+
num_conf = len(conf_numbers)
|
| 75 |
+
else:
|
| 76 |
+
num_conf = 1
|
| 77 |
+
|
| 78 |
+
L_res = dr.zeros(ArrayXf, (num_conf, dr.width(points_in))) if (mode != dr.ADMode.Backward) else L_in
|
| 79 |
+
|
| 80 |
+
active_conf = dr.ones(ArrayXb, shape = L_res.shape) if active_conf_in is None else ArrayXb(active_conf_in)
|
| 81 |
+
assert L_res.shape == active_conf.shape
|
| 82 |
+
|
| 83 |
+
if (L_in is None) and (mode is dr.ADMode.Backward):
|
| 84 |
+
raise Exception("The primal solution needs to be specified in the backward gradient computation!")
|
| 85 |
+
|
| 86 |
+
if mode == dr.ADMode.Forward:
|
| 87 |
+
dL = ArrayXf(0)
|
| 88 |
+
|
| 89 |
+
active = Bool(True)
|
| 90 |
+
if dr.hint(self.input.shape.single_closed and not all_inside, mode = "scalar"):
|
| 91 |
+
active, L_res = self.input.shape.inside_closed_surface(points_in, L_res, conf_numbers)
|
| 92 |
+
|
| 93 |
+
particle = Particle(Point2f(points_in), Float(initial_w), PCG32(), dr.arange(UInt32, dr.width(points_in)), UInt32(0))
|
| 94 |
+
|
| 95 |
+
initstate, initseq = tea(UInt64(particle.path_index), UInt64(self.seed))
|
| 96 |
+
particle.sampler.seed(initstate=UInt64(initstate), initseq=UInt64(initseq))
|
| 97 |
+
|
| 98 |
+
with dr.suspend_grad():
|
| 99 |
+
if dr.hint(derivative_dir is not None, mode = "scalar"):
|
| 100 |
+
particle = self.take_derivative_step(derivative_dir, L_res, particle, mode, dL, active, active_conf)
|
| 101 |
+
while active:
|
| 102 |
+
particle = self.take_step(L_res, particle, mode, dL, active, active_conf,
|
| 103 |
+
normal_derivative_dist, conf_numbers)
|
| 104 |
+
active &= particle.path_length < max_step
|
| 105 |
+
return (dL, particle) if mode == dr.ADMode.Forward else (L_res, particle)
|
| 106 |
+
|
| 107 |
+
@dr.syntax(print_code = False)
|
| 108 |
+
def take_step(self, L : Float, p : Particle, mode : dr.ADMode, dL : Float, active : Bool, active_conf : ArrayXb,
|
| 109 |
+
normal_derivative_dist : float, conf_numbers : list[UInt32] = None):
|
| 110 |
+
primal = (mode == dr.ADMode.Primal)
|
| 111 |
+
|
| 112 |
+
bi = self.input.shape.boundary_interaction(p.points, star_generation = False, conf_numbers = conf_numbers)
|
| 113 |
+
z = bi.r * dr.sqrt(self.σ)
|
| 114 |
+
if z > self.max_z:
|
| 115 |
+
bi.r *= self.max_z / z
|
| 116 |
+
z = self.max_z
|
| 117 |
+
|
| 118 |
+
self.green.initialize(z)
|
| 119 |
+
dirichlet_ending = (active & bi.is_e & bi.is_d)
|
| 120 |
+
|
| 121 |
+
# Add the dirichlet boundary contribution in epsilon-shell!
|
| 122 |
+
added_near = dr.select(dirichlet_ending & active_conf, p.w * bi.dval, 0)
|
| 123 |
+
|
| 124 |
+
# Add the result
|
| 125 |
+
L += added_near if dr.hint(primal, mode = 'scalar') else -added_near
|
| 126 |
+
|
| 127 |
+
# Remove the channels in which the walk is finished.
|
| 128 |
+
active &= ~dirichlet_ending
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
p.thrown |= bi.is_far
|
| 132 |
+
active &= ~bi.is_far
|
| 133 |
+
|
| 134 |
+
# Volume Contribution
|
| 135 |
+
# Source Sampling (self.σ is detached! It is used for pdf calculations.)
|
| 136 |
+
|
| 137 |
+
normG = Float(0)
|
| 138 |
+
if dr.hint(not self.input.f.is_zero, mode = 'scalar'):
|
| 139 |
+
r, normG = self.green.sample(p.sampler.next_float32(), bi.r, self.σ)
|
| 140 |
+
dir_vol, _ = sample_uniform_direction(p.sampler.next_float32())
|
| 141 |
+
points_vol = p.points + r * dir_vol
|
| 142 |
+
|
| 143 |
+
with dr.resume_grad(when=not primal):
|
| 144 |
+
α_vol = self.input.α.get_value(points_vol)
|
| 145 |
+
f_vol = self.input.f.get_value(points_vol) / α_vol
|
| 146 |
+
f_cont = dr.select(active, p.w * f_vol * normG, 0)
|
| 147 |
+
#if dr.isnan(f_cont):
|
| 148 |
+
# f_cont = Float(0)
|
| 149 |
+
|
| 150 |
+
if dr.hint(mode == dr.ADMode.Backward, mode = 'scalar'):
|
| 151 |
+
dr.backward(dr.sum(f_cont * dL))
|
| 152 |
+
elif dr.hint(mode == dr.ADMode.Forward, mode = 'scalar'):
|
| 153 |
+
dL += dr.forward_to(dr.sum(f_cont))
|
| 154 |
+
|
| 155 |
+
L += f_cont if primal else -f_cont
|
| 156 |
+
else:
|
| 157 |
+
normG = self.green.eval_norm(bi.r, self.σ)
|
| 158 |
+
|
| 159 |
+
# Boundary Sampling
|
| 160 |
+
p.points, _ = sample_uniform_boundary(p.sampler.next_float32(), p.points, bi.r)
|
| 161 |
+
|
| 162 |
+
# Poisson Kernel computation
|
| 163 |
+
P = (1 - normG * self.σ)
|
| 164 |
+
p.w *= P
|
| 165 |
+
p.path_length += 1
|
| 166 |
+
|
| 167 |
+
# Boundary and Volume Contribution
|
| 168 |
+
return p
|
| 169 |
+
|
| 170 |
+
@dr.syntax
|
| 171 |
+
def take_derivative_step(self, derivative_dir : Point2f, L : Float, p : Particle, mode : dr.ADMode, dL : Float,
|
| 172 |
+
active : Bool, active_conf : ArrayXb) -> Particle:
|
| 173 |
+
|
| 174 |
+
primal = (mode == dr.ADMode.Primal)
|
| 175 |
+
# There is no way to sample Green's function analytically. Use polynomial.
|
| 176 |
+
greenGrad = GreensFunctionPolynomial(dim = DIM.Two, newton_steps=10, grad = True)
|
| 177 |
+
|
| 178 |
+
# Create boundary interaction.
|
| 179 |
+
bi = self.input.shape.boundary_interaction(p.points, star_generation = False)
|
| 180 |
+
# We just create spheres.
|
| 181 |
+
bi.r = bi.d
|
| 182 |
+
# Decrease radius for max_z.
|
| 183 |
+
z = bi.r * dr.sqrt(self.σ)
|
| 184 |
+
if z > self.max_z:
|
| 185 |
+
bi.r *= self.max_z / z
|
| 186 |
+
z = self.max_z
|
| 187 |
+
|
| 188 |
+
greenGrad.initialize(z)
|
| 189 |
+
# Remove the channels in which the walk is finished.
|
| 190 |
+
active &= ~(bi.is_d & bi.is_e)
|
| 191 |
+
|
| 192 |
+
# Get the contribution of the source term
|
| 193 |
+
f_cont = Float(0)
|
| 194 |
+
if dr.hint(not self.input.f.is_zero, mode = 'scalar'):
|
| 195 |
+
# Sample norm of the Gradient with the Greens function.
|
| 196 |
+
r, norm_dG = greenGrad.sample(p.sampler.next_float32(), bi.r, self.σ)
|
| 197 |
+
dir_vol, _, sign_vol = sample_cosine_direction(p.sampler.next_float32(), derivative_dir)
|
| 198 |
+
points_vol = p.points + r * dir_vol
|
| 199 |
+
α_vol = self.input.α.get_value(points_vol)
|
| 200 |
+
|
| 201 |
+
with dr.resume_grad(when=not primal):
|
| 202 |
+
f_vol = self.input.f.get_value(points_vol) / α_vol
|
| 203 |
+
f_cont = dr.select(active, f_vol * norm_dG * sign_vol * 2 / dr.pi , 0.0)
|
| 204 |
+
#if dr.isnan(f_cont):
|
| 205 |
+
# f_cont = Float(0)
|
| 206 |
+
if dr.hint(mode == dr.ADMode.Backward, mode = 'scalar'):
|
| 207 |
+
dr.backward(f_cont * dL)
|
| 208 |
+
elif dr.hint(mode == dr.ADMode.Forward, mode = 'scalar'):
|
| 209 |
+
dL += dr.forward_to(f_cont)
|
| 210 |
+
|
| 211 |
+
f_cont = dr.select(active_conf, f_cont, 0)
|
| 212 |
+
|
| 213 |
+
L += f_cont if primal else -f_cont
|
| 214 |
+
|
| 215 |
+
p.points, _, boundary_sign = sample_cosine_boundary(p.sampler.next_float32(), p.points, bi.r, derivative_dir)
|
| 216 |
+
|
| 217 |
+
p.w *= eval_dP_norm(bi.r, self.σ) * 4 * bi.r * boundary_sign
|
| 218 |
+
p.path_length += 1
|
| 219 |
+
|
| 220 |
+
return p
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def create_normal_derivative(self, res : int, spp : int, distance : float, conf_numbers : list[UInt32]):
|
| 224 |
+
shape = self.input.shape
|
| 225 |
+
assert isinstance(shape, BoundaryWithDirichlets)
|
| 226 |
+
assert len(shape.in_boundaries) == 1
|
| 227 |
+
in_shape = shape.in_boundaries[0]
|
| 228 |
+
|
| 229 |
+
points_, s_points, normal_dir = in_shape.create_boundary_points(distance = dr.epsilon(mi.Float) * 20, res = res, spp = spp, discrete_points = True)
|
| 230 |
+
bi = BoundaryInfo(points_)
|
| 231 |
+
ri = shape.ray_intersect(bi, dr.normalize(normal_dir))
|
| 232 |
+
|
| 233 |
+
distance = dr.minimum(distance, 0.3 * ri.t)
|
| 234 |
+
points = points_ + distance * dr.normalize(normal_dir)
|
| 235 |
+
normal_der, _ = self.solve(points, derivative_dir=normal_dir, conf_numbers=conf_numbers, all_inside = True)
|
| 236 |
+
_, result_mi = in_shape.create_boundary_result(normal_der, s_points, res)
|
| 237 |
+
dr.eval(result_mi)
|
| 238 |
+
normal_der = in_shape.set_normal_derivative(result_mi)
|
| 239 |
+
return result_mi, normal_der
|
| 240 |
+
|
data/PDE2D/Solver/constant/wos_constant_rejection.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import sys
|
| 3 |
+
import mitsuba as mi
|
| 4 |
+
from mitsuba import Bool, Float, Point2f, UInt32
|
| 5 |
+
from PDE2D import GreenSampling, ArrayXb
|
| 6 |
+
from ..data_holder import DataHolder
|
| 7 |
+
from ...Coefficient import *
|
| 8 |
+
from ...Sampling import *
|
| 9 |
+
from PDE2D.BoundaryShape import *
|
| 10 |
+
from .wos_constant import WosConstant
|
| 11 |
+
class Particle:
|
| 12 |
+
DRJIT_STRUCT = {
|
| 13 |
+
'points' : Point2f,
|
| 14 |
+
'w': Float,
|
| 15 |
+
'sampler' : PCG32,
|
| 16 |
+
'path_index' : UInt32,
|
| 17 |
+
'path_length' : UInt32,
|
| 18 |
+
'thrown' : Bool
|
| 19 |
+
}
|
| 20 |
+
def __init__(self, points=None, w=None, sampler = None, path_index = None, path_length = None):
|
| 21 |
+
self.points = points
|
| 22 |
+
self.w = w
|
| 23 |
+
self.sampler = sampler
|
| 24 |
+
self.path_index = path_index
|
| 25 |
+
self.path_length = path_length
|
| 26 |
+
self.thrown = dr.zeros(Bool, dr.width(self.points))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class WosConstantRejection(WosConstant):
|
| 30 |
+
def __init__(self, input : DataHolder, seed : int = 37,
|
| 31 |
+
max_z : float = 4, green_sampling : GreenSampling = 0,
|
| 32 |
+
newton_steps : int = 5, opt_params : list[str] = []) -> None:
|
| 33 |
+
super().__init__(input, seed, max_z, green_sampling, newton_steps, opt_params)
|
| 34 |
+
|
| 35 |
+
@dr.syntax(print_code = False)
|
| 36 |
+
def take_step(self, L : Float, p : Particle, mode : dr.ADMode, dL : Float, active : Bool, active_conf : ArrayXb,
|
| 37 |
+
normal_derivative_dist : float, conf_numbers : list[UInt32] = None):
|
| 38 |
+
primal = (mode == dr.ADMode.Primal)
|
| 39 |
+
|
| 40 |
+
bi = self.input.shape.boundary_interaction(p.points, star_generation = False, conf_numbers = conf_numbers)
|
| 41 |
+
z = bi.r * dr.sqrt(self.σ)
|
| 42 |
+
if z > self.max_z:
|
| 43 |
+
bi.r *= self.max_z / z
|
| 44 |
+
z = self.max_z
|
| 45 |
+
|
| 46 |
+
self.green.initialize(z)
|
| 47 |
+
dirichlet_ending = (active & bi.is_e & bi.is_d)
|
| 48 |
+
|
| 49 |
+
# Add the dirichlet boundary contribution in epsilon-shell!
|
| 50 |
+
added_near = dr.select(dirichlet_ending & active_conf, p.w * bi.dval, 0)
|
| 51 |
+
|
| 52 |
+
# Add the result
|
| 53 |
+
L += added_near if dr.hint(primal, mode = 'scalar') else -added_near
|
| 54 |
+
|
| 55 |
+
# Remove the channels in which the walk is finished.
|
| 56 |
+
active &= ~dirichlet_ending
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
p.thrown |= bi.is_far
|
| 60 |
+
active &= ~bi.is_far
|
| 61 |
+
|
| 62 |
+
# Volume Contribution
|
| 63 |
+
# Source Sampling (self.σ is detached! It is used for pdf calculations.)
|
| 64 |
+
|
| 65 |
+
normG = Float(0)
|
| 66 |
+
if dr.hint(not self.input.f.is_zero, mode = 'scalar'):
|
| 67 |
+
#r, normG = self.green.sample(p.sampler.next_float32(), bi.r, self.σ)
|
| 68 |
+
r, normG = self.sampleGreenRejection(p, bi.r, self.σ)
|
| 69 |
+
dir_vol, _ = sample_uniform_direction(p.sampler.next_float32())
|
| 70 |
+
points_vol = p.points + r * dir_vol
|
| 71 |
+
|
| 72 |
+
with dr.resume_grad(when=not primal):
|
| 73 |
+
α_vol = self.input.α.get_value(points_vol)
|
| 74 |
+
f_vol = self.input.f.get_value(points_vol) / α_vol
|
| 75 |
+
f_cont = dr.select(active, p.w * f_vol * normG, 0)
|
| 76 |
+
#if dr.isnan(f_cont):
|
| 77 |
+
# f_cont = Float(0)
|
| 78 |
+
|
| 79 |
+
if dr.hint(mode == dr.ADMode.Backward, mode = 'scalar'):
|
| 80 |
+
dr.backward(dr.sum(f_cont * dL))
|
| 81 |
+
elif dr.hint(mode == dr.ADMode.Forward, mode = 'scalar'):
|
| 82 |
+
dL += dr.forward_to(dr.sum(f_cont))
|
| 83 |
+
|
| 84 |
+
L += f_cont if primal else -f_cont
|
| 85 |
+
else:
|
| 86 |
+
normG = self.green.eval_norm(bi.r, self.σ)
|
| 87 |
+
|
| 88 |
+
# Boundary Sampling
|
| 89 |
+
p.points, _ = sample_uniform_boundary(p.sampler.next_float32(), p.points, bi.r)
|
| 90 |
+
|
| 91 |
+
# Poisson Kernel computation
|
| 92 |
+
P = (1 - normG * self.σ)
|
| 93 |
+
p.w *= P
|
| 94 |
+
p.path_length += 1
|
| 95 |
+
|
| 96 |
+
# Boundary and Volume Contribution
|
| 97 |
+
return p
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@dr.syntax
|
| 101 |
+
def sampleGreenRejection(self, p : Particle, R : Float, σ : Float):
|
| 102 |
+
# We apply rejection sampling based on WosVariable paper.
|
| 103 |
+
if R <= σ:
|
| 104 |
+
upper_bound = dr.maximum(2.2 * dr.maximum(dr.rcp(R), dr.rcp(σ)), 0.6 * dr.maximum(dr.sqrt(R), dr.sqrt(σ)))
|
| 105 |
+
else:
|
| 106 |
+
upper_bound = dr.maximum(2.2 * dr.minimum(dr.rcp(R), dr.rcp(σ)), 0.6 * dr.minimum(dr.sqrt(R), dr.sqrt(σ)))
|
| 107 |
+
|
| 108 |
+
sample1 = p.sampler.next_float32() * R
|
| 109 |
+
sample2 = p.sampler.next_float32()
|
| 110 |
+
pdf = self.green.eval_pdf_only(sample1, R, σ)
|
| 111 |
+
while(sample2 * upper_bound > pdf):
|
| 112 |
+
sample1 = p.sampler.next_float32() * R
|
| 113 |
+
sample2 = p.sampler.next_float32()
|
| 114 |
+
pdf = self.green.eval_pdf_only(sample1, R, σ)
|
| 115 |
+
return sample1, self.green.eval_norm(R, σ)
|
| 116 |
+
|
data/PDE2D/Solver/constant/wost_constant.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from ..data_holder import DataHolder
|
| 3 |
+
from ...Coefficient import *
|
| 4 |
+
from ...Sampling import *
|
| 5 |
+
from ...BoundaryShape.interaction import BoundaryInfo
|
| 6 |
+
from .wos_constant import *
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class WostConstant(WosConstant):
|
| 10 |
+
def __init__(self, input : DataHolder, seed : int = 37,
|
| 11 |
+
max_z : float = 4, green_sampling : GreenSampling = 0, newton_steps : int = 5, opt_params : list[str] = []) -> None:
|
| 12 |
+
super().__init__(input, seed, max_z, green_sampling, newton_steps, opt_params)
|
| 13 |
+
|
| 14 |
+
@dr.syntax(print_code = False)
|
| 15 |
+
def take_step(self, L : ArrayXf, p : Particle, mode : dr.ADMode, dL : ArrayXf, active : Bool,
|
| 16 |
+
active_conf : ArrayXb, normal_derivative_dist : float = None, conf_numbers : list[UInt32] = None) -> Particle:
|
| 17 |
+
|
| 18 |
+
if conf_numbers is not None:
|
| 19 |
+
num_conf = len(conf_numbers)
|
| 20 |
+
else:
|
| 21 |
+
num_conf = 1
|
| 22 |
+
|
| 23 |
+
primal = (mode == dr.ADMode.Primal)
|
| 24 |
+
|
| 25 |
+
# Apply boundary interaction.
|
| 26 |
+
with dr.resume_grad(when = (not primal) & (normal_derivative_dist is not None)):
|
| 27 |
+
bi = self.input.shape.boundary_interaction(p.points, star_generation = False, conf_numbers = conf_numbers)
|
| 28 |
+
|
| 29 |
+
# Decrease radius to sample from a reasonable Green's function.
|
| 30 |
+
z = bi.r * dr.sqrt(self.σ)
|
| 31 |
+
if z > self.max_z:
|
| 32 |
+
bi.r *= self.max_z / z
|
| 33 |
+
z = self.max_z
|
| 34 |
+
|
| 35 |
+
self.green.initialize(z)
|
| 36 |
+
# Generate stars.
|
| 37 |
+
bi = self.input.shape.star_generation(bi)
|
| 38 |
+
|
| 39 |
+
# End the paths if we are in the epsilon shell of a dirichlet boundary.
|
| 40 |
+
dirichlet_ending = (active & bi.is_e & bi.is_d)
|
| 41 |
+
|
| 42 |
+
# Final contribution
|
| 43 |
+
added_near = dr.select(dirichlet_ending & active_conf, p.w * bi.dval, 0.0)
|
| 44 |
+
#added_near = Float(0)
|
| 45 |
+
# Accumulate the throughput to the corresponding shape. (Only done if multiple shapes is defined.)
|
| 46 |
+
#dirichlet_grad = Float(0)
|
| 47 |
+
if dr.hint(primal, mode = 'scalar'):
|
| 48 |
+
L += added_near
|
| 49 |
+
else:
|
| 50 |
+
L -= added_near
|
| 51 |
+
# This part is for computing the derivative for discrete EIT experiments. Only
|
| 52 |
+
# single shape optimization is supported.
|
| 53 |
+
if dr.hint((normal_derivative_dist is not None), mode = 'scalar'):
|
| 54 |
+
assert isinstance(self.input.shape, BoundaryWithDirichlets)
|
| 55 |
+
assert len(self.input.shape.in_boundaries) == 1
|
| 56 |
+
|
| 57 |
+
jacobian = self.input.shape.get_jacobian_factor(bi, normal_derivative_dist)
|
| 58 |
+
with dr.resume_grad(when = not primal): # This is for optimizing the shape of the dirichlet boundaries.
|
| 59 |
+
normalder = dr.select(dirichlet_ending & active_conf,
|
| 60 |
+
p.w * self.input.shape.get_normal_derivative(dr.detach(bi.bpoint)),
|
| 61 |
+
0)
|
| 62 |
+
#dirichlet_grad = bi.d
|
| 63 |
+
distance_correction = self.input.shape.in_boundaries[0].get_distance_correction(p.points)
|
| 64 |
+
bi2 = self.input.shape.in_boundaries[0].boundary_interaction(p.points, star_generation = False, conf_numbers = conf_numbers)
|
| 65 |
+
dirichlet_grad = dr.select(dirichlet_ending, bi2.d * jacobian * normalder / distance_correction, 0)
|
| 66 |
+
#dr.backward(dirichlet_grad * dL)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# Remove the channels in which the walk is finished.
|
| 70 |
+
active &= ~dirichlet_ending
|
| 71 |
+
|
| 72 |
+
active &= ~bi.is_far
|
| 73 |
+
p.thrown |= bi.is_far
|
| 74 |
+
|
| 75 |
+
# Source Contribution
|
| 76 |
+
# Source Sampling (self.σ is detached! It is used for pdf calculations.)
|
| 77 |
+
if dr.hint(not self.input.f.is_zero, mode = 'scalar'):
|
| 78 |
+
r_vol, normG = self.green.sample(p.sampler.next_float32(), bi.r, self.σ)
|
| 79 |
+
dir_vol, _ = sample_star_direction(p.sampler.next_float32(), bi.on_boundary & bi.is_star, bi.bn)
|
| 80 |
+
points_vol = mi.Point2f(p.points + r_vol * dir_vol)
|
| 81 |
+
|
| 82 |
+
# If we are on a star, The sampled point might be outside of the boundary.
|
| 83 |
+
# We need to check this with a ray intersection.
|
| 84 |
+
ri_f = self.input.shape.ray_intersect(bi, dir_vol)
|
| 85 |
+
|
| 86 |
+
with dr.resume_grad(when=not primal):
|
| 87 |
+
α_vol = self.input.α.get_value(points_vol)
|
| 88 |
+
f_vol = self.input.f.get_value(points_vol) / α_vol
|
| 89 |
+
f_cont = dr.select(active & (r_vol <= ri_f.t), p.w * f_vol * normG, 0)
|
| 90 |
+
if dr.isnan(f_cont):
|
| 91 |
+
f_cont = Float(0)
|
| 92 |
+
f_cont = dr.select(active_conf, f_cont, 0)
|
| 93 |
+
L += f_cont if primal else -f_cont
|
| 94 |
+
|
| 95 |
+
# Now compute the Neumann Contribution. (NEE Contribution.)
|
| 96 |
+
# If we have a continous Neumann on the boundary, we need to sample it.
|
| 97 |
+
n_cont_cont = dr.zeros(ArrayXf, shape = L.shape)
|
| 98 |
+
|
| 99 |
+
if dr.hint(self.input.has_continuous_neumann, mode = 'scalar'):
|
| 100 |
+
# If we have a special sampling scheme then we need to sample for each configuration.
|
| 101 |
+
|
| 102 |
+
if dr.hint(self.input.NEE == NEE.Special, mode = 'scalar'):
|
| 103 |
+
for i in range(num_conf):
|
| 104 |
+
conf_number = None if conf_numbers is None else conf_numbers[i]
|
| 105 |
+
# Here n_val is a Float.
|
| 106 |
+
dist_n, n_val, pdf_n_r, _ = self.input.sampleNEE_special(bi, p.sampler.next_float32(), conf_number)
|
| 107 |
+
G_n_r = self.green.eval(dist_n, bi.r, self.σ)
|
| 108 |
+
if ((pdf_n_r > 0) & (dist_n < bi.r) & (dist_n > 0)):
|
| 109 |
+
n_cont_cont[i] = -p.w * n_val * G_n_r / pdf_n_r
|
| 110 |
+
if dr.isnan(n_cont_cont[i]):
|
| 111 |
+
n_cont_cont[i] = Float(0)
|
| 112 |
+
else: # If not then, we only call the sample function once. The neumann values will be different.
|
| 113 |
+
# Here n_val is an ArrayXf.
|
| 114 |
+
dist_n, n_val, pdf_n_r, _ = self.input.sampleNEE(bi, p.sampler.next_float32(), conf_numbers)
|
| 115 |
+
G_n_r = self.green.eval(dist_n, bi.r, self.σ)
|
| 116 |
+
|
| 117 |
+
n_cont_cont_ = Float(0)
|
| 118 |
+
if ((pdf_n_r > 0) & (dist_n < bi.r) & (dist_n > 0)):
|
| 119 |
+
n_cont_cont_ = -p.w * G_n_r / pdf_n_r
|
| 120 |
+
|
| 121 |
+
if dr.isnan(n_cont_cont_):
|
| 122 |
+
n_cont_cont_ = Float(0)
|
| 123 |
+
n_cont_cont = n_val * n_cont_cont_
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# Now, we get the all necessary delta distributions on the boundary (a.k.a. point current injections).
|
| 128 |
+
n_cont_delta = dr.zeros(ArrayXf, shape = L.shape)
|
| 129 |
+
if dr.hint(self.input.has_delta, mode = 'scalar'):
|
| 130 |
+
for i in range(num_conf):
|
| 131 |
+
conf_number = None if conf_numbers is None else conf_numbers[i]
|
| 132 |
+
dist_n, n_val, pdf_n_r, _ = self.input.get_point_neumann(bi, conf_number)
|
| 133 |
+
# We can have multiple relevant electrodes, add all the contribution.
|
| 134 |
+
for d, n, pdf_r in zip(dist_n, n_val, pdf_n_r):
|
| 135 |
+
G_n_r = self.green.eval(d, bi.r, self.σ)
|
| 136 |
+
if pdf_r > 0:
|
| 137 |
+
n_cont_delta[i] += -p.w * n * G_n_r / pdf_r
|
| 138 |
+
if dr.isnan(n_cont_delta[i]):
|
| 139 |
+
n_cont_delta[i] = Float(0)
|
| 140 |
+
# Compute the total neumann contribution, we need to multiply by two if we are on the boundary. (Check WoSt paper.)
|
| 141 |
+
|
| 142 |
+
n_cont = n_cont_cont + n_cont_delta
|
| 143 |
+
if bi.on_boundary:
|
| 144 |
+
n_cont *= 2
|
| 145 |
+
|
| 146 |
+
n_cont = dr.select(active_conf, n_cont, 0)
|
| 147 |
+
|
| 148 |
+
# One last step is to correct neumann value if the given Neumann is a current value.
|
| 149 |
+
if self.input.shape.measured_current:
|
| 150 |
+
with dr.resume_grad(when = not primal):
|
| 151 |
+
n_cont /= self.input.α.get_value(Point2f(0)) # Constant Conductance
|
| 152 |
+
|
| 153 |
+
L += n_cont if primal else -n_cont
|
| 154 |
+
|
| 155 |
+
# Now, we can accumulate the gradients as all necessary info is collected.
|
| 156 |
+
with dr.resume_grad(when = not primal):
|
| 157 |
+
if dr.hint(mode == dr.ADMode.Backward, mode = 'scalar'):
|
| 158 |
+
# dr.backward(dr.sum((f_cont + n_cont + dirichlet_grad) * dL))
|
| 159 |
+
dr.backward(dirichlet_grad * dL)
|
| 160 |
+
elif dr.hint(mode == dr.ADMode.Forward, mode = 'scalar'):
|
| 161 |
+
# dL += dr.forward_to(dr.sum(f_cont + n_cont + dirichlet_grad))
|
| 162 |
+
dL += dr.forward_to(dr.sum(dirichlet_grad))
|
| 163 |
+
|
| 164 |
+
# Recursive step
|
| 165 |
+
# Sample direction to get the next point.
|
| 166 |
+
dir_next, sphere_p, _ = bi.sample_recursive(p.sampler.next_float32())
|
| 167 |
+
# Check if we hit to the boundary before sphere.
|
| 168 |
+
ri = self.input.shape.ray_intersect(bi, dir_next)
|
| 169 |
+
on_boundary_next = bi.is_star & (ri.t < bi.r)
|
| 170 |
+
next_points = dr.select(bi.is_star & on_boundary_next, ri.intersected, sphere_p)
|
| 171 |
+
distance_rec = dr.select(on_boundary_next & bi.is_star, ri.t, bi.r)
|
| 172 |
+
|
| 173 |
+
first_mask = ~self.input.shape.inside_closed_surface_mask(next_points)
|
| 174 |
+
if first_mask:
|
| 175 |
+
p.bad_mask = Bool(True)
|
| 176 |
+
p.on_boundary1 = Bool(bi.on_boundary)
|
| 177 |
+
p.on_boundary2 = Bool(on_boundary_next)
|
| 178 |
+
p.loc1 = Point2f(p.points)
|
| 179 |
+
p.loc2 = Point2f(next_points)
|
| 180 |
+
p.intersected = Point2f(ri.intersected)
|
| 181 |
+
p.direction = Point2f(dir_next)
|
| 182 |
+
p.dist = Float(ri.t)
|
| 183 |
+
p.boundary_normal = Point2f(bi.bn)
|
| 184 |
+
|
| 185 |
+
# Poisson Kernel computation
|
| 186 |
+
p.points = Point2f(next_points)
|
| 187 |
+
p.w *= self.green.eval_poisson_kernel(distance_rec, bi.r, self.σ)
|
| 188 |
+
p.path_length += 1
|
| 189 |
+
|
| 190 |
+
return p
|
data/PDE2D/Solver/data_holder.py
ADDED
|
@@ -0,0 +1,643 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import drjit as dr
|
| 2 |
+
import mitsuba as mi
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PDE2D.Coefficient import *
|
| 5 |
+
from PDE2D.BoundaryShape import *
|
| 6 |
+
from PDE2D.utils import *
|
| 7 |
+
from PDE2D.Sampling import *
|
| 8 |
+
from mitsuba import Float, Point2f, TensorXf, Texture2f,Bool, UInt
|
| 9 |
+
from PDE2D import DIM
|
| 10 |
+
from enum import IntEnum
|
| 11 |
+
|
| 12 |
+
class RegularizationType(IntEnum):
|
| 13 |
+
none = 0,
|
| 14 |
+
L2 = 1,
|
| 15 |
+
tensorL2 = 2,
|
| 16 |
+
L1 = 3,
|
| 17 |
+
tensorL1 = 4,
|
| 18 |
+
TV = 5,
|
| 19 |
+
gradL1 = 6,
|
| 20 |
+
gradL2 = 7,
|
| 21 |
+
screeningL1 = 8,
|
| 22 |
+
screeningL2 = 9
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class DataHolder(object):
|
| 26 |
+
def __init__(self, shape: Shape = Shape(), bbox_center: list = [0,0],
|
| 27 |
+
bbox_length = 2.1, max_window_grid = 8,
|
| 28 |
+
max_mipmap_res = 1024, min_mipmap_res = 1,
|
| 29 |
+
max_z = 4, dist_texture_res = 512,
|
| 30 |
+
α : Coefficient = ConstantCoefficient("diffusion", 1),
|
| 31 |
+
σ : Coefficient = ConstantCoefficient("screening", 0),
|
| 32 |
+
f : Coefficient = ConstantCoefficient("source", 0),
|
| 33 |
+
α_split : Coefficient = None,
|
| 34 |
+
σ_split : Coefficient = None,
|
| 35 |
+
opt_param_shape: list = [], opt_param_α: list = [],
|
| 36 |
+
opt_param_σ: list = [], opt_param_f: list = [],
|
| 37 |
+
majorant_safety_low: float = 1.02,
|
| 38 |
+
majorant_safety_high : float = 1.02,
|
| 39 |
+
default_majorant : float = None,
|
| 40 |
+
verbose = False):
|
| 41 |
+
self.shape = shape
|
| 42 |
+
self.bbox_center = Point2f(bbox_center)
|
| 43 |
+
self.bbox_length = Float(bbox_length)
|
| 44 |
+
self.bbox = [[bbox_center[0] - bbox_length/2, bbox_center[1] - bbox_length/2],
|
| 45 |
+
[bbox_center[0] + bbox_length/2, bbox_center[1] + bbox_length/2]]
|
| 46 |
+
self.max_mipmap_res = max_mipmap_res
|
| 47 |
+
self.min_mipmap_res = min_mipmap_res
|
| 48 |
+
self.max_window_grid = UInt32(max_window_grid)
|
| 49 |
+
self.max_radius = bbox_length / min_mipmap_res * (max_window_grid - 1)
|
| 50 |
+
self.verbose = verbose
|
| 51 |
+
self.α = α
|
| 52 |
+
self.σ = σ
|
| 53 |
+
self.f = f
|
| 54 |
+
# These are defined for fd computations.
|
| 55 |
+
# When we deviate the coefficients, path splitting weights change
|
| 56 |
+
# We want fd forward computations to follow the same exact path.
|
| 57 |
+
self.α_split = α_split if (α_split is not None) else α
|
| 58 |
+
self.σ_split = σ_split if (σ_split is not None) else σ
|
| 59 |
+
self.params_shape = opt_param_shape
|
| 60 |
+
self.params_f = opt_param_f
|
| 61 |
+
self.params_σ = opt_param_σ
|
| 62 |
+
self.params_α = opt_param_α
|
| 63 |
+
self.majorant_safety_high = majorant_safety_high
|
| 64 |
+
self.majorant_safety_low = majorant_safety_low
|
| 65 |
+
self.default_majorant = default_majorant
|
| 66 |
+
self.has_continuous_neumann = self.shape.has_continuous_neumann
|
| 67 |
+
self.has_delta = self.shape.has_delta
|
| 68 |
+
self.NEE = self.shape.NEE
|
| 69 |
+
self.Rscale = [Float(0), self.shape.max_distance]
|
| 70 |
+
self.σscale = [Float(0.01), Float(10000)]
|
| 71 |
+
self.meanfree_res = [256, 256]
|
| 72 |
+
self.dist_tex_res = dist_texture_res
|
| 73 |
+
self.max_z = Float(max_z)
|
| 74 |
+
self.effective_σ = self.calculate_effective_screening(res = self.max_mipmap_res)
|
| 75 |
+
# We are multiplying the negative part with a safety factor as it might increase the througput too much.
|
| 76 |
+
self.majorant = dr.maximum(self.effective_σ * self.majorant_safety_high, -self.effective_σ * self.majorant_safety_low)
|
| 77 |
+
self.σ_bar =dr.max(self.majorant.array) if self.default_majorant is None else Float(self.default_majorant)
|
| 78 |
+
self.σ_bar = dr.maximum(1e-3, self.σ_bar)
|
| 79 |
+
#self.create_opt_parameters()
|
| 80 |
+
|
| 81 |
+
def σ_(self, σ, α, grad_α, laplacian_α): # Equation 21 (2nd paper)
|
| 82 |
+
return σ / α + 1/2 * (laplacian_α / α - dr.squared_norm(grad_α)/(2 * (α ** 2)))
|
| 83 |
+
|
| 84 |
+
#def create_opt_parameters(self):
|
| 85 |
+
# self.opt_params = {}
|
| 86 |
+
# self.shape.get_opt_params(self.opt_params, self.params_shape)
|
| 87 |
+
# self.α.get_opt_params(self.opt_params, self.params_α)
|
| 88 |
+
# self.σ.get_opt_params(self.opt_params, self.params_σ)
|
| 89 |
+
# self.f.get_opt_params(self.opt_params, self.params_f)
|
| 90 |
+
|
| 91 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 92 |
+
self.shape.get_opt_params_shape(param_dict, opt_params)
|
| 93 |
+
self.α.get_opt_params(param_dict, opt_params)
|
| 94 |
+
self.σ.get_opt_params(param_dict, opt_params)
|
| 95 |
+
self.f.get_opt_params(param_dict, opt_params)
|
| 96 |
+
|
| 97 |
+
def update(self, opt):
|
| 98 |
+
self.shape.update(opt)
|
| 99 |
+
self.f.update(opt)
|
| 100 |
+
self.σ.update(opt)
|
| 101 |
+
self.α.update(opt)
|
| 102 |
+
self.α_split = self.α
|
| 103 |
+
self.σ_split = self.σ
|
| 104 |
+
#self.create_accelaration()
|
| 105 |
+
|
| 106 |
+
def create_accelaration(self):
|
| 107 |
+
self.effective_σ = self.calculate_effective_screening(res = self.max_mipmap_res)
|
| 108 |
+
self.majorant = dr.maximum(self.effective_σ * self.majorant_safety_high, -self.effective_σ * self.majorant_safety_low)
|
| 109 |
+
self.σ_bar =dr.max(self.majorant.array) if self.default_majorant is None else self.default_majorant
|
| 110 |
+
self.σ_bar = dr.maximum(1e-3, self.σ_bar)
|
| 111 |
+
self.majorant = (dr.maximum(1e-3, self.majorant))
|
| 112 |
+
self.majorant_tex = TextureCoefficient("effective_screening", self.bbox, self.majorant.numpy(), interpolation = "linear")
|
| 113 |
+
self.σ_mipmap = self.create_mipmap(self.majorant, min_res = self.min_mipmap_res, type = "max")
|
| 114 |
+
|
| 115 |
+
self.meanfree_tex = self.get_mean_free_image()
|
| 116 |
+
self.r_best_tex, self.σ_best_tex, self.σ_begin_tex = self.get_Rσ_domain(res = self.dist_tex_res, n_bisection=5, n_grid_search=10)
|
| 117 |
+
|
| 118 |
+
def get_mean_free_image(self, spp = 2**8, resolution = [256, 256]):
|
| 119 |
+
R = self.Rscale[0] + (self.Rscale[1] - self.Rscale[0]) * dr.arange(Float, resolution[0]) / (resolution[0] - 1)
|
| 120 |
+
σ = self.σscale[0] * 2 ** (dr.arange(Float, resolution[1]) / (resolution[1] - 1) * dr.log2(self.σscale[1] / self.σscale[0]))
|
| 121 |
+
RR, σσ = dr.meshgrid(R, σ, indexing = 'ij')
|
| 122 |
+
RR = dr.repeat(RR, spp)
|
| 123 |
+
σσ = dr.repeat(σσ, spp)
|
| 124 |
+
|
| 125 |
+
z = Float(RR * dr.sqrt(σσ))
|
| 126 |
+
sample = dr.arange(Float, spp) / spp + 1/(2 * spp)
|
| 127 |
+
sample = dr.tile(sample, (resolution[0]) * resolution[1])
|
| 128 |
+
green = GreensFunctionAnalytic(dim = DIM.Two, newton_steps = 8, grad = False)
|
| 129 |
+
r, normG = green.sample(sample, RR, σσ)
|
| 130 |
+
prob_boundary = 1 - σσ * normG
|
| 131 |
+
result = r * (1-prob_boundary) + RR * prob_boundary
|
| 132 |
+
result = dr.select(RR == 0, 0, result)
|
| 133 |
+
result = TensorXf(dr.block_sum(result, spp) / spp)
|
| 134 |
+
result = dr.reshape(TensorXf, result, shape = [resolution[0], resolution[1], 1])
|
| 135 |
+
result_tex = Texture2f(result)
|
| 136 |
+
return result_tex
|
| 137 |
+
|
| 138 |
+
def get_mean_free_path(self, R, σ):
|
| 139 |
+
Rgrid = 1 / self.meanfree_res[0]
|
| 140 |
+
σgrid = 1 / self.meanfree_res[1]
|
| 141 |
+
ind_R = Rgrid / 2 + (R - self.Rscale[0]) / (self.Rscale[1] - self.Rscale[0]) * (1.0-Rgrid)
|
| 142 |
+
ind_σ = σgrid/2 + dr.log2(σ / self.σscale[0]) / dr.log2(self.σscale[1] / self.σscale[0]) * (1.0 - σgrid)
|
| 143 |
+
return self.meanfree_tex.eval(Point2f(ind_σ, ind_R))[0]
|
| 144 |
+
|
| 145 |
+
def calculate_effective_screening(self, res = 1024):
|
| 146 |
+
with dr.suspend_grad():
|
| 147 |
+
resolution = [res, res]
|
| 148 |
+
points = create_image_points(self.bbox, resolution, 1, centered = True)
|
| 149 |
+
active = Bool(True)
|
| 150 |
+
if (self.shape.single_closed):
|
| 151 |
+
active = self.shape.inside_closed_surface_mask(points)
|
| 152 |
+
# Calculate the textures
|
| 153 |
+
α_vals = self.α_split.get_value(points)
|
| 154 |
+
grad_α, laplacian_α = self.α_split.get_grad_laplacian(points)
|
| 155 |
+
σ_vals = self.σ_split.get_value(points)
|
| 156 |
+
# Equation 21 (2nd paper)
|
| 157 |
+
σ_new = self.σ_(σ_vals, α_vals, grad_α, laplacian_α)
|
| 158 |
+
# Eliminate the calculations outside the boundary (if the given shape
|
| 159 |
+
# is single closed boundary)
|
| 160 |
+
σ_new = dr.select(active, σ_new, 0)
|
| 161 |
+
numpy_σ, tensor_σ = create_image_from_result(σ_new, resolution)
|
| 162 |
+
self.eff_screening_tex = TextureCoefficient("effective_screening", self.bbox, numpy_σ[0], interpolation = "linear")
|
| 163 |
+
return tensor_σ[0]
|
| 164 |
+
|
| 165 |
+
def create_mipmap(self, tensor, min_res, type = "max"):
|
| 166 |
+
# Now create the mipmap hierarchy
|
| 167 |
+
res = tensor.shape[0]
|
| 168 |
+
num_iter = int(dr.floor(dr.log2(res // min_res)))
|
| 169 |
+
n = res * res
|
| 170 |
+
array = dr.zeros(Float, n * (num_iter + 1))
|
| 171 |
+
current_res = res
|
| 172 |
+
current_array = Float(tensor.array)
|
| 173 |
+
dr.eval(current_array)
|
| 174 |
+
dr.scatter(array, current_array, dr.arange(UInt, n))
|
| 175 |
+
|
| 176 |
+
for k in range(num_iter):
|
| 177 |
+
current_res //= 2
|
| 178 |
+
i = dr.arange(UInt, current_res) * 2
|
| 179 |
+
j = dr.arange(UInt, current_res) * 2
|
| 180 |
+
ii, jj = dr.meshgrid(i, j, indexing = "ij")
|
| 181 |
+
|
| 182 |
+
index00 = ii * current_res * 2 + jj
|
| 183 |
+
index01 = ii * current_res * 2 + jj + 1
|
| 184 |
+
index10 = (ii + 1) * current_res * 2 + jj
|
| 185 |
+
index11 = (ii + 1) * current_res * 2 + jj + 1
|
| 186 |
+
|
| 187 |
+
dr.eval(index00, index01, index10, index11)
|
| 188 |
+
val00 = dr.gather(Float, current_array, index00)
|
| 189 |
+
val01 = dr.gather(Float, current_array, index01)
|
| 190 |
+
val10 = dr.gather(Float, current_array, index10)
|
| 191 |
+
val11 = dr.gather(Float, current_array, index11)
|
| 192 |
+
if type == "max":
|
| 193 |
+
max0 = dr.maximum(val00, val01)
|
| 194 |
+
max1 = dr.maximum(val10, val11)
|
| 195 |
+
current_array = dr.maximum(max0, max1)
|
| 196 |
+
elif type == "min":
|
| 197 |
+
min0 = dr.minimum(val00, val01)
|
| 198 |
+
min1 = dr.minimum(val10, val11)
|
| 199 |
+
current_array = dr.minimum(min0, min1)
|
| 200 |
+
elif type == "mean":
|
| 201 |
+
current_array = (val00 + val01 + val10 + val11) / 4
|
| 202 |
+
else:
|
| 203 |
+
raise Exception("There is no such mipmap creation type.")
|
| 204 |
+
current_tensor = TensorXf(current_array)
|
| 205 |
+
current_tensor = dr.reshape(TensorXf, value = current_tensor, shape = [current_res, current_res])
|
| 206 |
+
u_factor = res // current_res
|
| 207 |
+
current_upsampled = upsample(current_tensor, scale_factor = [u_factor, u_factor])
|
| 208 |
+
#current_upsampled = dr.upsample(current_tensor, scale_factor=[res//current_res, res//current_res])
|
| 209 |
+
dr.scatter(array, current_upsampled.array, dr.arange(UInt, n) + (k+1) * n)
|
| 210 |
+
tensor = TensorXf(array)
|
| 211 |
+
tensor = dr.reshape(TensorXf, value = tensor, shape = [num_iter + 1, res, res])
|
| 212 |
+
#return TensorXf(array, shape = [num_iter + 1, res, res])
|
| 213 |
+
return tensor
|
| 214 |
+
@dr.syntax
|
| 215 |
+
def get_sphere_screening(self, points, radius):
|
| 216 |
+
x = (points[0] - self.bbox[0][0]) / self.bbox_length
|
| 217 |
+
y = 1.0 - (points[1] - self.bbox[0][1]) / self.bbox_length
|
| 218 |
+
k_max, res_all,_ = self.σ_mipmap.shape
|
| 219 |
+
#mask = mi.TensorXf(mi.Float(0) ,shape = [res_all, res_all])
|
| 220 |
+
|
| 221 |
+
k_max -= 1
|
| 222 |
+
# which mipmap level to select
|
| 223 |
+
k = UInt32(dr.ceil(dr.log2(2 * radius * res_all / ((self.max_window_grid - 1) * self.bbox_length))))
|
| 224 |
+
|
| 225 |
+
k = dr.select(k > k_max, k_max, k)
|
| 226 |
+
if k < 0:
|
| 227 |
+
k = UInt32(0)
|
| 228 |
+
#dr.select(k < 0, 0, k)
|
| 229 |
+
# resolution of the selected grid
|
| 230 |
+
res_decrease = UInt32(dr.round(Float(2)**Float(k)))
|
| 231 |
+
|
| 232 |
+
#res_decrease = mi.UInt32(4)
|
| 233 |
+
res = res_all // res_decrease
|
| 234 |
+
|
| 235 |
+
n1_point = UInt32(dr.floor(y * res))
|
| 236 |
+
n2_point = UInt32(dr.floor(x * res))
|
| 237 |
+
|
| 238 |
+
# get the center grid val of sphere
|
| 239 |
+
if self.max_window_grid % 2 == 0:
|
| 240 |
+
n1 = UInt32(dr.round(y * res))
|
| 241 |
+
n2 = UInt32(dr.round(x * res))
|
| 242 |
+
else:
|
| 243 |
+
n1 = n1_point
|
| 244 |
+
n2 = n2_point
|
| 245 |
+
|
| 246 |
+
# get the index of the window
|
| 247 |
+
n1_start = n1 - self.max_window_grid//2
|
| 248 |
+
n2_start = n2 - self.max_window_grid//2
|
| 249 |
+
#v = 0
|
| 250 |
+
v = UInt32(0)
|
| 251 |
+
# We start the majorant with the correspoinding grid where the point is inside
|
| 252 |
+
index_point = k * res_all * res_all + n1_point * res_decrease * res_all + n2_point * res_decrease
|
| 253 |
+
majorant = dr.gather(Float, self.σ_mipmap.array, index_point)
|
| 254 |
+
|
| 255 |
+
#i = dr.arange(mi.UInt, res_decrease[0])
|
| 256 |
+
#j = dr.arange(mi.UInt, res_decrease[0])
|
| 257 |
+
#ii, jj = dr.meshgrid(i, j, indexing = "ij")
|
| 258 |
+
#mask_indices = (ii + n1_point * res_decrease) * res_all + jj + n2_point * res_decrease
|
| 259 |
+
#dr.scatter(mask.array, mi.Float(1), mask_indices)
|
| 260 |
+
grid_length = self.bbox_length / res
|
| 261 |
+
|
| 262 |
+
#loop = mi.Loop("Iterate over grids and get the max majorant if it touches the sphere!", state= lambda : (v, majorant))
|
| 263 |
+
while (v < self.max_window_grid**2):
|
| 264 |
+
n1_iter = v // self.max_window_grid + n1_start
|
| 265 |
+
n2_iter = v % self.max_window_grid + n2_start
|
| 266 |
+
|
| 267 |
+
n1_iter = dr.select(n1_iter<0, 0, n1_iter)
|
| 268 |
+
n1_iter = dr.select(n1_iter>=res, res-1, n1_iter)
|
| 269 |
+
n2_iter = dr.select(n2_iter<0, 0, n2_iter)
|
| 270 |
+
n2_iter = dr.select(n2_iter>=res, res-1, n2_iter)
|
| 271 |
+
|
| 272 |
+
square_corner_x = self.bbox[0][0] + n2_iter * grid_length
|
| 273 |
+
square_corner_y = self.bbox[0][1] + (res - n1_iter - 1) * grid_length
|
| 274 |
+
corner = Point2f(square_corner_x, square_corner_y)
|
| 275 |
+
dist = self.get_distance_to_square(points, corner, grid_length)
|
| 276 |
+
|
| 277 |
+
#if dist[0] < radius:
|
| 278 |
+
# i = dr.arange(mi.UInt, res_decrease[0])
|
| 279 |
+
# j = dr.arange(mi.UInt, res_decrease[0])
|
| 280 |
+
# ii, jj = dr.meshgrid(i, j, indexing = "ij")
|
| 281 |
+
# mask_indices = (ii + n1_iter * res_decrease) * res_all + jj + n2_iter * res_decrease
|
| 282 |
+
# dr.scatter(mask.array, mi.Float(1), mask_indices)
|
| 283 |
+
index_point = k * res_all * res_all + n1_iter * res_decrease * res_all + n2_iter * res_decrease
|
| 284 |
+
majorant_iter = dr.gather(Float, self.σ_mipmap.array, index_point)
|
| 285 |
+
majorant = dr.select(dist < radius, dr.maximum(majorant_iter, majorant), majorant)
|
| 286 |
+
v += 1
|
| 287 |
+
#mask_tex = TextureCoefficient("mask", self.bbox, mask.numpy(), interpolation = "nearest")
|
| 288 |
+
return majorant
|
| 289 |
+
|
| 290 |
+
def compute_regularization(self, λ : float, type : RegularizationType,
|
| 291 |
+
resolution = [256, 256], spp = 1, coeff_str = "diffusion"):
|
| 292 |
+
out_val = 0
|
| 293 |
+
coeff = self.get_coefficient(coeff_str)
|
| 294 |
+
if coeff.out_val is not None:
|
| 295 |
+
out_val = coeff.out_val
|
| 296 |
+
with dr.suspend_grad():
|
| 297 |
+
points = self.shape.create_volume_points(resolution, spp)
|
| 298 |
+
dL = dr.ones(Float, dr.width(points)) * dr.rcp(dr.width(points))
|
| 299 |
+
if type == RegularizationType.none:
|
| 300 |
+
reg = Float(0)
|
| 301 |
+
|
| 302 |
+
elif type == RegularizationType.L2:
|
| 303 |
+
vals = coeff.get_value(points)
|
| 304 |
+
reg = dr.square(vals - out_val)
|
| 305 |
+
|
| 306 |
+
elif type == RegularizationType.tensorL2:
|
| 307 |
+
resolution = coeff.tensor.shape[0:2]
|
| 308 |
+
reg = Float(0)
|
| 309 |
+
dL = Float(1)
|
| 310 |
+
for i in range(resolution[0]):
|
| 311 |
+
for j in range(resolution[1]):
|
| 312 |
+
index = i * resolution[1] + j
|
| 313 |
+
val = dr.gather(Float, self.α.tensor.array, index)
|
| 314 |
+
reg += dr.square(val - out_val)
|
| 315 |
+
elif (type == RegularizationType.L1):
|
| 316 |
+
vals = coeff.get_value(points)
|
| 317 |
+
reg = dr.abs(vals - out_val)
|
| 318 |
+
|
| 319 |
+
elif (type == RegularizationType.tensorL1):
|
| 320 |
+
resolution = coeff.tensor.shape[0:2]
|
| 321 |
+
reg = Float(0)
|
| 322 |
+
dL = Float(1)
|
| 323 |
+
for i in range(resolution[0]):
|
| 324 |
+
for j in range(resolution[1]):
|
| 325 |
+
index = i * resolution[1] + j
|
| 326 |
+
val = dr.gather(Float, self.α.tensor.array, index)
|
| 327 |
+
reg += dr.abs(val - out_val)
|
| 328 |
+
reg /= ((resolution[0]) * resolution[1])
|
| 329 |
+
|
| 330 |
+
elif (type == RegularizationType.TV):
|
| 331 |
+
resolution = coeff.tensor.shape[0:2]
|
| 332 |
+
reg = Float(0)
|
| 333 |
+
dL = Float(1)
|
| 334 |
+
for i in range(resolution[0]-1):
|
| 335 |
+
for j in range(resolution[1]-1):
|
| 336 |
+
index = i * resolution[1] + j
|
| 337 |
+
val = dr.gather(Float, self.α.tensor.array, index)
|
| 338 |
+
val1 = dr.gather(Float, self.α.tensor.array, index+1)
|
| 339 |
+
val2 = dr.gather(Float, self.α.tensor.array, index+resolution[1])
|
| 340 |
+
reg += dr.abs(val1 - val)
|
| 341 |
+
reg += dr.abs(val2 - val)
|
| 342 |
+
reg /= ((resolution[0]-1) * resolution[1]-1)
|
| 343 |
+
|
| 344 |
+
elif (type == RegularizationType.gradL1):
|
| 345 |
+
grad = coeff.get_grad_laplacian(points)[0]
|
| 346 |
+
reg = dr.abs(grad[0]) + dr.abs(grad[1])
|
| 347 |
+
|
| 348 |
+
elif(type == RegularizationType.gradL2):
|
| 349 |
+
grad = coeff.get_grad_laplacian(points)[0]
|
| 350 |
+
reg = dr.squared_norm(grad)
|
| 351 |
+
|
| 352 |
+
elif (type == RegularizationType.screeningL2) or (type == RegularizationType.screeningL1):
|
| 353 |
+
σ = self.σ.get_value(points)
|
| 354 |
+
α = self.α.get_value(points)
|
| 355 |
+
grad_α, laplacian_α = self.α.get_grad_laplacian(points)
|
| 356 |
+
σ_ = self.σ_(σ, α, grad_α, laplacian_α)
|
| 357 |
+
reg = dr.square(σ_) if type == RegularizationType.screening_squared else dr.abs(σ_)
|
| 358 |
+
|
| 359 |
+
else:
|
| 360 |
+
raise Exception("There is no such regularization type.")
|
| 361 |
+
return dL * reg * λ
|
| 362 |
+
|
| 363 |
+
@dr.syntax
|
| 364 |
+
def get_Rσ(self, points, radius, n_bisection = 10, n_grid_search = 10, screening_offset = Float(0)):
|
| 365 |
+
σ_begin = self.get_sphere_screening(points, radius + 2 * screening_offset)
|
| 366 |
+
σ = self.get_sphere_screening(points, radius + screening_offset)
|
| 367 |
+
z = radius * dr.sqrt(σ)
|
| 368 |
+
|
| 369 |
+
# We will shrink these radii for g
|
| 370 |
+
r = Float(radius)
|
| 371 |
+
# Here we shrink the radii of the spheres where z is high by bisection.
|
| 372 |
+
# At each iter we shrink to the middle value of max and min z, and compute
|
| 373 |
+
# the corresponding z value by also querying the correct majorant value.
|
| 374 |
+
# If we found something close enough to z_high, we end the iteration.
|
| 375 |
+
if z > self.max_z:
|
| 376 |
+
r_high = Float(radius)
|
| 377 |
+
r_low = self.max_z / dr.sqrt(σ)
|
| 378 |
+
i = UInt32(0)
|
| 379 |
+
while i < n_bisection:
|
| 380 |
+
r_sep = (r_high + r_low) / 2
|
| 381 |
+
σ_sep = self.get_sphere_screening(points, r_sep + screening_offset)
|
| 382 |
+
z_sep = r_sep * dr.sqrt(σ_sep)
|
| 383 |
+
if z_sep < self.max_z:
|
| 384 |
+
r_low = Float(r_sep)
|
| 385 |
+
else:
|
| 386 |
+
r_high = Float(r_sep)
|
| 387 |
+
i += 1
|
| 388 |
+
r = Float(r_low)
|
| 389 |
+
σ = self.get_sphere_screening(points, r + screening_offset)
|
| 390 |
+
z = r * dr.sqrt(σ)
|
| 391 |
+
|
| 392 |
+
# Now all z vals should be in the correct range that we can sample from.
|
| 393 |
+
# We will compute the best radius value in terms of the mean free path
|
| 394 |
+
# by grid search.
|
| 395 |
+
i = UInt32(0)
|
| 396 |
+
meanfree_best = Float(0)
|
| 397 |
+
r_best = Float(0)
|
| 398 |
+
while i < n_grid_search:
|
| 399 |
+
r_iter = r * Float(i + 1) / n_grid_search
|
| 400 |
+
σ_iter = self.get_sphere_screening(points, r_iter + screening_offset)
|
| 401 |
+
meanfree_iter = self.get_mean_free_path(r_iter, σ_iter)
|
| 402 |
+
if meanfree_iter > meanfree_best:
|
| 403 |
+
meanfree_best = meanfree_iter
|
| 404 |
+
r_best = r_iter
|
| 405 |
+
σ = σ_iter
|
| 406 |
+
i += 1
|
| 407 |
+
|
| 408 |
+
return r_best, σ, σ_begin
|
| 409 |
+
|
| 410 |
+
def get_coefficient(self, name : str = "diffusion"):
|
| 411 |
+
if name == "diffusion":
|
| 412 |
+
return self.α
|
| 413 |
+
elif name == "screening":
|
| 414 |
+
return self.σ
|
| 415 |
+
elif name == "source":
|
| 416 |
+
return self.f
|
| 417 |
+
else:
|
| 418 |
+
raise Exception("There is no such coefficient.")
|
| 419 |
+
|
| 420 |
+
def get_Rσ_domain(self, res, n_bisection = 10, n_grid_search = 10):
|
| 421 |
+
points = create_image_points(self.bbox, resolution = [res, res], spp = 1, centered = True)
|
| 422 |
+
bi = self.shape.boundary_interaction(points, star_generation=False)
|
| 423 |
+
# We will always add these small offset value while computing the majorant to
|
| 424 |
+
# account for the grid size.
|
| 425 |
+
s_offset = self.bbox_length / res / dr.sqrt(2) * 1.01
|
| 426 |
+
self.radius_threshold = s_offset * 5
|
| 427 |
+
|
| 428 |
+
r_best, σ_best, σ_begin = self.get_Rσ(points, bi.r, n_bisection = n_bisection, n_grid_search=n_grid_search,
|
| 429 |
+
screening_offset=s_offset)
|
| 430 |
+
# We need to be careful while using the corresponding radii as it does not represent
|
| 431 |
+
# exactly the correct radius values.
|
| 432 |
+
r_image, _ = create_image_from_result(r_best, resolution = [res, res])
|
| 433 |
+
σ_image, _ = create_image_from_result(σ_best, resolution = [res, res])
|
| 434 |
+
σ_begin_image, _ = create_image_from_result(σ_begin, resolution = [res, res])
|
| 435 |
+
r_best_tex = TextureCoefficient("Best-radius", self.bbox, r_image[0], interpolation = "nearest")
|
| 436 |
+
σ_best_tex = TextureCoefficient("Best-majorant", self.bbox, σ_image[0], interpolation = "nearest")
|
| 437 |
+
σ_begin_tex = TextureCoefficient("Beginning-majorant", self.bbox, σ_begin_image[0], interpolation = "nearest")
|
| 438 |
+
return r_best_tex, σ_best_tex, σ_begin_tex
|
| 439 |
+
|
| 440 |
+
@dr.syntax
|
| 441 |
+
def get_Rσz(self, points, radius):
|
| 442 |
+
r = self.r_best_tex.get_value(points)
|
| 443 |
+
σ = self.σ_best_tex.get_value(points)
|
| 444 |
+
σ_begin = self.σ_begin_tex.get_value(points)
|
| 445 |
+
|
| 446 |
+
# If we chose a greater best radius due to discretization of the domain or
|
| 447 |
+
# if the distance is too small, then select the original distance for taking a step!
|
| 448 |
+
if (radius < r) | (radius < 20 * self.shape.epsilon) | (radius < self.radius_threshold):
|
| 449 |
+
r = radius
|
| 450 |
+
σ = σ_begin
|
| 451 |
+
|
| 452 |
+
σ = dr.maximum(1e-3, σ)
|
| 453 |
+
z = r * dr.sqrt(σ)
|
| 454 |
+
# For rare cases, now the z value might be larger than the max z. Especially if the majorant
|
| 455 |
+
# is super high near the boundary.
|
| 456 |
+
if z >= self.max_z:
|
| 457 |
+
r *= (self.max_z / z)
|
| 458 |
+
z = self.max_z
|
| 459 |
+
# return the selected parameters for sampling the next step.
|
| 460 |
+
return r, σ, z
|
| 461 |
+
|
| 462 |
+
@dr.syntax
|
| 463 |
+
def get_distance_to_square(self, point, corner, length):
|
| 464 |
+
i = UInt32(0)
|
| 465 |
+
min1 = Float(dr.inf)
|
| 466 |
+
min2 = Float(dr.inf)
|
| 467 |
+
p1 = Point2f(dr.nan)
|
| 468 |
+
p2 = Point2f(dr.nan)
|
| 469 |
+
while i < 4:
|
| 470 |
+
n1 = Float(i // 2)
|
| 471 |
+
n2 = Float(i % 2)
|
| 472 |
+
corner_ = corner + length * (Point2f(0,1) * n1 +
|
| 473 |
+
Point2f(1,0) * n2)
|
| 474 |
+
dist = dr.norm(corner_ - point)
|
| 475 |
+
mask1 = dist < min1
|
| 476 |
+
mask2 = dist < min2
|
| 477 |
+
min2 = dr.select(mask1, min1, min2)
|
| 478 |
+
min1 = dr.select(mask1, dist, min1)
|
| 479 |
+
min2 = dr.select(~mask1 & mask2, dist, min2)
|
| 480 |
+
p2 = Point2f(dr.select(mask1, p1, p2))
|
| 481 |
+
p1 = Point2f(dr.select(mask1, corner_, p1))
|
| 482 |
+
p2 = Point2f(dr.select(~mask1 & mask2, corner_, p2))
|
| 483 |
+
i += 1
|
| 484 |
+
vec1 = dr.normalize(p2 - p1)
|
| 485 |
+
vec2 = point - p1
|
| 486 |
+
d = dr.dot(vec1,vec2)
|
| 487 |
+
d = dr.select(d<0, 0, d)
|
| 488 |
+
d = dr.select(d>length, length, d)
|
| 489 |
+
closest_point = p1 + d * vec1
|
| 490 |
+
return dr.norm(point - closest_point)
|
| 491 |
+
|
| 492 |
+
def zero_grad(self):
|
| 493 |
+
self.α.zero_grad()
|
| 494 |
+
self.σ.zero_grad()
|
| 495 |
+
self.f.zero_grad()
|
| 496 |
+
self.shape.zero_grad()
|
| 497 |
+
|
| 498 |
+
def visualize(self, ax1, ax2, ax3, ax4, resolution = [512, 512], spp = 4):
|
| 499 |
+
self.f.visualize(ax1, self.bbox, resolution, spp)
|
| 500 |
+
self.σ.visualize(ax2, self.bbox, resolution, spp)
|
| 501 |
+
self.α.visualize(ax3, self.bbox, resolution, spp)
|
| 502 |
+
image, tensor = self.get_effective_screening(resolution, spp)
|
| 503 |
+
plot_image(image[0], ax4)
|
| 504 |
+
ax1.set_title("Source (f)")
|
| 505 |
+
ax2.set_title("Screening (σ)")
|
| 506 |
+
ax3.set_title("Diffusion (α)")
|
| 507 |
+
ax4.set_title("Effective Screening (σ)")
|
| 508 |
+
|
| 509 |
+
def get_effective_screening(self, resolution = [512, 512], spp = 4):
|
| 510 |
+
points = create_image_points(self.bbox, resolution, spp)
|
| 511 |
+
σ = self.σ.get_value(points)
|
| 512 |
+
α = self.α.get_value(points)
|
| 513 |
+
grad_α, laplacian_α = self.α.get_grad_laplacian(points)
|
| 514 |
+
effective_σ = σ / α + 1/2 * (laplacian_α / α - dr.squared_norm(grad_α)/(2 * (α ** 2)))
|
| 515 |
+
return create_image_from_result(effective_σ, resolution)
|
| 516 |
+
|
| 517 |
+
def get_point_neumann(self, bi : BoundaryInfo, conf_number : UInt32) -> tuple[list[Float], list[Float], list[Float], list[Point2f]]:
|
| 518 |
+
return self.shape.get_point_neumann(bi, conf_number)
|
| 519 |
+
|
| 520 |
+
def sampleNEE_special(self, bi:BoundaryInfo, sample : Float, conf_number : UInt32):
|
| 521 |
+
# If we have a special sampling routine for getting NEE. (sampling only electrodes.)
|
| 522 |
+
return self.shape.sampleNEE(bi, sample, conf_number)
|
| 523 |
+
|
| 524 |
+
@dr.syntax
|
| 525 |
+
def sampleNEE(self, bi : BoundaryInfo, sample : Float, conf_numbers : list[UInt32]) -> tuple[Float, Float, Float, Point2f]:
|
| 526 |
+
d, pdf_n_r, sampled_p = (Float(0), Float(1), Point2f(0))
|
| 527 |
+
n_val = dr.zeros(ArrayXf, shape = (len(conf_numbers), dr.width(bi.origin)))
|
| 528 |
+
if dr.hint(self.NEE == NEE.Normal, mode = 'scalar'): # Sample uniformly to the star part of the sphere.
|
| 529 |
+
# Sampled direction for getting the Neumann contribution.
|
| 530 |
+
dir_n, pdf_n = bi.sample_neumann(sample, bi.on_boundary)
|
| 531 |
+
# Check the selected sample hits to the boundary shape with neumann value.
|
| 532 |
+
#d, sampled_p, normals_n = self.shape.ray_intersect(bi.origin, dir_n, bi.on_boundary)
|
| 533 |
+
ri = self.shape.ray_intersect(bi, dir_n, conf_numbers =conf_numbers)
|
| 534 |
+
d = ri.t
|
| 535 |
+
sampled_p = ri.intersected
|
| 536 |
+
# If we hit to the boundary, add the contribution.
|
| 537 |
+
if bi.is_star & (ri.t < bi.r) & ~ri.is_dirichlet:
|
| 538 |
+
for i in range(len(conf_numbers)):
|
| 539 |
+
n_val[i] = Float(ri.neumann[i])
|
| 540 |
+
pdf_n_r = pdf_n * dr.abs(dr.dot(dir_n, ri.normal)) * 2 * dr.pi # pdf multiplied with 2 * pi * bi.r
|
| 541 |
+
|
| 542 |
+
elif dr.hint(self.NEE == NEE.BruteForce, mode = 'scalar'):
|
| 543 |
+
dir_n, pdf_n = bi.sample_brute_force(sample)
|
| 544 |
+
ri = self.shape.ray_intersect(bi, dir_n, conf_numbers =conf_numbers)
|
| 545 |
+
d = ri.t
|
| 546 |
+
sampled_p = ri.intersected
|
| 547 |
+
|
| 548 |
+
if bi.is_star & (ri.t < bi.r) & ~ri.is_dirichlet:
|
| 549 |
+
for i in range(len(conf_numbers)):
|
| 550 |
+
n_val[i] = Float(ri.neumann[i])
|
| 551 |
+
pdf_n_r = pdf_n * dr.abs(dr.dot(dir_n, ri.normal)) * 2 * dr.pi # pdf multiplied with 2 * pi * bi.r
|
| 552 |
+
return d, n_val, pdf_n_r, sampled_p
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def compute_high_conductance_points(self, max_num_points = 3, cond_threshold = 2, grad_threshold = 1, merge_distance = 0.2):
|
| 556 |
+
bbox = self.shape.bbox
|
| 557 |
+
bbox_center = Point2f(bbox[0][0] + bbox[1][0],
|
| 558 |
+
bbox[0][1] + bbox[1][1])
|
| 559 |
+
bbox_length = max(bbox[1][0] - bbox[0][0], bbox[1][1] - bbox[0][1])
|
| 560 |
+
|
| 561 |
+
if isinstance(self.shape, BoundaryWithDirichlets):
|
| 562 |
+
points = self.shape.out_boundary.create_volume_points(resolution = [1024, 1024])
|
| 563 |
+
else:
|
| 564 |
+
points = self.shape.create_volume_points(resolution = [1024, 1024])
|
| 565 |
+
|
| 566 |
+
val = self.α.get_value(points)
|
| 567 |
+
grad, laplacian = self.α.get_grad_laplacian(points)
|
| 568 |
+
mask = (dr.norm(grad) < grad_threshold) & (val > cond_threshold) & (laplacian < 0)
|
| 569 |
+
indices = dr.compress(mask)
|
| 570 |
+
points = dr.gather(Point2f, points, indices)
|
| 571 |
+
if np.size(points.numpy()) == 0:
|
| 572 |
+
return bbox_center.numpy().T
|
| 573 |
+
|
| 574 |
+
#means = create_circle_points(origin=bbox_center, radius = bbox_length,
|
| 575 |
+
# resolution = 20, spp = 1, discrete_points= True)
|
| 576 |
+
means = self.shape.create_volume_points(resolution = [16,16])
|
| 577 |
+
|
| 578 |
+
means, groups = k_means(points, means, num_iter = 3)
|
| 579 |
+
mask = ~dr.isnan(means[0] + means[1])
|
| 580 |
+
indices = dr.compress(mask)
|
| 581 |
+
means = dr.gather(Point2f, means, indices)
|
| 582 |
+
|
| 583 |
+
"""
|
| 584 |
+
# Merge close points
|
| 585 |
+
nmeans = dr.width(means)
|
| 586 |
+
ind = dr.arange(UInt32, nmeans)
|
| 587 |
+
for i in range(nmeans):
|
| 588 |
+
if ind[i] == i:
|
| 589 |
+
for j in range(i + 1, nmeans):
|
| 590 |
+
means_i = dr.gather(Point2f, means, i)
|
| 591 |
+
means_j = dr.gather(Point2f, means, j)
|
| 592 |
+
if dr.norm(means_i - means_j)[0] < merge_distance * bbox_length:
|
| 593 |
+
dr.scatter(means, Point2f(dr.nan), j)
|
| 594 |
+
ind[j] = i
|
| 595 |
+
"""
|
| 596 |
+
# Recompute the means once more.
|
| 597 |
+
#mask = ~dr.isnan(means[0] + means[1])
|
| 598 |
+
#indices = dr.compress(mask)
|
| 599 |
+
#means = dr.gather(Point2f, means, indices)
|
| 600 |
+
means, groups = k_means(points, means, num_iter = 1)
|
| 601 |
+
|
| 602 |
+
# Get the highest conduction region.∂
|
| 603 |
+
val = self.α.get_value(points)
|
| 604 |
+
cond_sum = dr.zeros(Float, dr.width(means))
|
| 605 |
+
counter_sum = dr.zeros(Float, dr.width(means))
|
| 606 |
+
dr.scatter_add(cond_sum, val, groups)
|
| 607 |
+
dr.scatter_add(counter_sum, Float(1), groups)
|
| 608 |
+
mean_cond = (cond_sum / counter_sum)
|
| 609 |
+
|
| 610 |
+
# Now we sort with numpy to get the biggest mean conductance regions.
|
| 611 |
+
mean_cond_np = mean_cond.numpy()
|
| 612 |
+
|
| 613 |
+
#sort_index = mean_cond_np.argsort()[::-1][:num_points]
|
| 614 |
+
sort_index = mean_cond_np.argsort()[::-1]
|
| 615 |
+
|
| 616 |
+
# means
|
| 617 |
+
means = means.numpy()[:, sort_index].T
|
| 618 |
+
|
| 619 |
+
# Now we eliminate the points that are very close to the region
|
| 620 |
+
# we are interested in.
|
| 621 |
+
n = means.shape[0]
|
| 622 |
+
i = 0
|
| 623 |
+
while(i < n):
|
| 624 |
+
deleted_indices = []
|
| 625 |
+
for k in range(i+1, n):
|
| 626 |
+
dist = np.linalg.norm(means[i] - means[k])
|
| 627 |
+
if dist < merge_distance * bbox_length:
|
| 628 |
+
deleted_indices.append(k)
|
| 629 |
+
means = np.delete(means, deleted_indices, axis = 0)
|
| 630 |
+
n = means.shape[0]
|
| 631 |
+
i += 1
|
| 632 |
+
num_points = min(means.shape[0], max_num_points)
|
| 633 |
+
means = means[:num_points]
|
| 634 |
+
# Apply one last k-means
|
| 635 |
+
#means = k_means(points, Point2f(means.T), num_iter = 2)[0].numpy()
|
| 636 |
+
#return means.T
|
| 637 |
+
if means.shape[0] == 0:
|
| 638 |
+
means = np.zeros([1,2])
|
| 639 |
+
return means
|
| 640 |
+
|
| 641 |
+
def upsample2(self, coefficient = "diffusion"):
|
| 642 |
+
coeff = self.get_coefficient(coefficient)
|
| 643 |
+
coeff.upsample2()
|
data/PDE2D/Solver/variable/wos_variable.py
ADDED
|
@@ -0,0 +1,736 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import mitsuba as mi
|
| 2 |
+
from ..data_holder import DataHolder
|
| 3 |
+
from ...Coefficient import *
|
| 4 |
+
from ...Sampling import *
|
| 5 |
+
from ...BoundaryShape.interaction import BoundaryInfo
|
| 6 |
+
from PDE2D.BoundaryShape import *
|
| 7 |
+
from mitsuba import Bool, Float, Point2f, UInt, PCG32, UInt64, UInt32, UInt
|
| 8 |
+
from PDE2D import (Array4u64, ArrayXf, ArrayXb, GreenSampling, Split, DIM)
|
| 9 |
+
|
| 10 |
+
class Particle:
|
| 11 |
+
DRJIT_STRUCT = {
|
| 12 |
+
'points' : Point2f,
|
| 13 |
+
'w': Float,
|
| 14 |
+
'w_split' : Float,
|
| 15 |
+
'sampler' : PCG32,
|
| 16 |
+
'path_index' : UInt32,
|
| 17 |
+
'path_length' : UInt32,
|
| 18 |
+
'traverse_h' : Array4u64,
|
| 19 |
+
'thrown' : Bool
|
| 20 |
+
}
|
| 21 |
+
def __init__(self, points=None, w=None, w_split = None,
|
| 22 |
+
sampler = None, path_index = None, path_length = None,
|
| 23 |
+
traverse_h = None):
|
| 24 |
+
self.points = points
|
| 25 |
+
self.w = w
|
| 26 |
+
self.w_split = w_split
|
| 27 |
+
self.sampler = sampler
|
| 28 |
+
self.path_index = path_index
|
| 29 |
+
self.path_length = path_length
|
| 30 |
+
self.traverse_h = traverse_h
|
| 31 |
+
self.thrown = Bool(False)
|
| 32 |
+
|
| 33 |
+
class WosVariable(object):
|
| 34 |
+
def __init__(self, input : DataHolder, seed : int = 37, weight_window = [0.5, 2], max_z : float = 4,
|
| 35 |
+
green_sampling : GreenSampling = 0, newton_steps : int = 5, use_accelaration : bool = True,
|
| 36 |
+
opt_params : list[str] = []):
|
| 37 |
+
self.input = input
|
| 38 |
+
self.seed = UInt64(seed)
|
| 39 |
+
dr.make_opaque(self.seed)
|
| 40 |
+
self.input = input
|
| 41 |
+
self.w_window = weight_window
|
| 42 |
+
self.max_z = Float(max_z)
|
| 43 |
+
self.use_accel = use_accelaration
|
| 44 |
+
self.input.max_z = self.max_z
|
| 45 |
+
|
| 46 |
+
if self.use_accel:
|
| 47 |
+
self.input.create_accelaration()
|
| 48 |
+
|
| 49 |
+
self.opt_params = {}
|
| 50 |
+
self.get_opt_params(self.opt_params, opt_params)
|
| 51 |
+
|
| 52 |
+
if green_sampling == GreenSampling.Polynomial:
|
| 53 |
+
self.green = GreensFunctionPolynomial(dim = DIM.Two, newton_steps = newton_steps)
|
| 54 |
+
else:
|
| 55 |
+
self.green = GreensFunctionAnalytic(dim = DIM.Two, newton_steps = newton_steps)
|
| 56 |
+
|
| 57 |
+
def change_seed(self, seed : int):
|
| 58 |
+
self.seed = dr.opaque(UInt64, seed, shape = (1))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 62 |
+
self.input.get_opt_params(param_dict, opt_params)
|
| 63 |
+
|
| 64 |
+
def update(self, opt):
|
| 65 |
+
self.input.update(opt)
|
| 66 |
+
|
| 67 |
+
def zero_grad(self):
|
| 68 |
+
self.input.zero_grad()
|
| 69 |
+
|
| 70 |
+
def get_opt_params(self, param_dict: dict, opt_params: list):
|
| 71 |
+
self.input.get_opt_params(param_dict, opt_params)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def σ_(self, σ, α, grad_α, laplacian_α): # Equation 21 (2nd paper)
|
| 75 |
+
return σ / α + 1/2 * (laplacian_α / α - dr.squared_norm(grad_α)/(2 * (α ** 2)))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@dr.syntax(print_code = False)
|
| 79 |
+
def solve(self, points_in = None, active_conf_in : ArrayXb = None, split : Split = Split.Normal, derivative_dir : Point2f = None, initial_w = Float(1),
|
| 80 |
+
conf_numbers : list[UInt32] = [UInt32(0)], max_length : UInt32 = None, tput_kill : Float = Float(0.8), all_inside = False,
|
| 81 |
+
fd_forward = False, max_depth_split = 100, verbose : bool = True):
|
| 82 |
+
size = dr.width(points_in)
|
| 83 |
+
|
| 84 |
+
# The channel size of the rendering.
|
| 85 |
+
if conf_numbers is not None:
|
| 86 |
+
num_conf = len(conf_numbers)
|
| 87 |
+
else:
|
| 88 |
+
num_conf = 1
|
| 89 |
+
|
| 90 |
+
#L_res = dr.zeros(Float, size)
|
| 91 |
+
L_res = dr.zeros(ArrayXf, (num_conf, size))
|
| 92 |
+
|
| 93 |
+
active_conf_begin = dr.ones(ArrayXb, shape = L_res.shape) if active_conf_in is None else active_conf_in
|
| 94 |
+
assert L_res.shape == active_conf_begin.shape
|
| 95 |
+
|
| 96 |
+
active_conf = ArrayXb(active_conf_begin)
|
| 97 |
+
|
| 98 |
+
active = Bool(True)
|
| 99 |
+
if dr.hint(self.input.shape.single_closed and (not all_inside), mode = 'scalar'):
|
| 100 |
+
active, L_res = self.input.shape.inside_closed_surface(points_in, L_res, conf_numbers)
|
| 101 |
+
|
| 102 |
+
seq = dr.arange(UInt64, size)
|
| 103 |
+
initstate, initseq = tea(UInt64(seq), UInt64(self.seed))
|
| 104 |
+
pcg = PCG32()
|
| 105 |
+
pcg.seed(initstate, initseq)
|
| 106 |
+
|
| 107 |
+
particle = Particle(points = Point2f(points_in), w = Float(initial_w), w_split = Float(1.0),
|
| 108 |
+
sampler = PCG32(pcg), path_index = dr.arange(UInt32, size),
|
| 109 |
+
path_length = UInt32(0), traverse_h = Array4u64(1,0,0,0))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
with dr.suspend_grad():
|
| 113 |
+
# If we apply no path splitting.
|
| 114 |
+
if dr.hint(split == Split.Naive, mode = 'scalar'):
|
| 115 |
+
# Primal phase.
|
| 116 |
+
# We take a derivative step in the beginning if the direction is specified.
|
| 117 |
+
if dr.hint(derivative_dir is not None, mode = 'scalar'):
|
| 118 |
+
particle = self.take_derivative_step(derivative_dir, L_res, particle, dr.ADMode.Primal, ArrayXf(0), active, active_conf = active_conf)
|
| 119 |
+
|
| 120 |
+
# Take other steps.
|
| 121 |
+
while active:
|
| 122 |
+
particle = self.take_step(L_res, particle, dr.ADMode.Primal, split, ArrayXf(0), active, active_conf,
|
| 123 |
+
conf_numbers, max_length, tput_kill, fd_forward)
|
| 124 |
+
# Russian roulette
|
| 125 |
+
if (particle.w_split < self.w_window[0]) & active:
|
| 126 |
+
if particle.sampler.next_float32() >= particle.w:
|
| 127 |
+
active = Bool(False)
|
| 128 |
+
else:
|
| 129 |
+
particle.w = Float(1)
|
| 130 |
+
return L_res, particle
|
| 131 |
+
|
| 132 |
+
# Otherwise do the path splitting scheme.
|
| 133 |
+
iter_num = 0
|
| 134 |
+
while (size > 0) and (iter_num < (max_depth_split + 1)):
|
| 135 |
+
queue_index = UInt32(0)
|
| 136 |
+
|
| 137 |
+
is_split = iter_num < max_depth_split
|
| 138 |
+
if dr.hint(is_split, mode = 'scalar'):
|
| 139 |
+
# Preallocate memory for the queue. The necessary amount of memory is
|
| 140 |
+
# task-dependent (how many splits there are)
|
| 141 |
+
queue_size = dr.maximum(50, int(2 * size))
|
| 142 |
+
queue_size_opaque = dr.opaque(UInt32, queue_size)
|
| 143 |
+
queue = dr.empty(dtype=Particle, shape=queue_size)
|
| 144 |
+
|
| 145 |
+
# Get the primal result of each iteration in the gradient computation for prb.
|
| 146 |
+
L_iter = dr.zeros(ArrayXf, shape = (num_conf, size))
|
| 147 |
+
|
| 148 |
+
# We again first take the derivative direction if it is specified.
|
| 149 |
+
if dr.hint((derivative_dir is not None) & (iter_num == 0), mode = 'scalar'):
|
| 150 |
+
particle = self.take_derivative_step(derivative_dir, L_iter, particle, dr.ADMode.Primal, Float(0), active, active_conf)
|
| 151 |
+
|
| 152 |
+
while active:
|
| 153 |
+
# This is the main part of the algorithm (WoS).
|
| 154 |
+
particle = self.take_step(L_iter, particle, dr.ADMode.Primal, split, Float(0), active, active_conf,
|
| 155 |
+
conf_numbers, max_length, tput_kill, fd_forward = fd_forward)
|
| 156 |
+
|
| 157 |
+
# Russian roulette
|
| 158 |
+
if (particle.w_split < self.w_window[0]) & active:
|
| 159 |
+
if particle.sampler.next_float32() >= particle.w_split:
|
| 160 |
+
active = Bool(False)
|
| 161 |
+
else:
|
| 162 |
+
particle.w /= particle.w_split
|
| 163 |
+
particle.w_split = Float(1)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
# Splitting begins. #################################################
|
| 167 |
+
if (particle.w_split >= self.w_window[1]) & active:
|
| 168 |
+
particle, new_particle = split_particle(particle)
|
| 169 |
+
|
| 170 |
+
if dr.hint(is_split, mode = 'scalar'):
|
| 171 |
+
slot = dr.scatter_inc(queue_index, index=0)
|
| 172 |
+
|
| 173 |
+
# Be careful not to write beyond the end of the queue
|
| 174 |
+
valid = (slot < queue_size_opaque)
|
| 175 |
+
|
| 176 |
+
# Write 'new_state' into the reserved slot
|
| 177 |
+
dr.scatter(target=queue, value=new_particle, index=slot, active=valid)
|
| 178 |
+
|
| 179 |
+
dr.scatter_add(L_res, L_iter, particle.path_index)
|
| 180 |
+
next_size = queue_index[0]
|
| 181 |
+
if verbose:
|
| 182 |
+
print('%u : %u -> %u' % (iter_num, size, next_size))
|
| 183 |
+
iter_num += 1
|
| 184 |
+
|
| 185 |
+
if dr.hint(is_split, mode = "scalar"):
|
| 186 |
+
if next_size > queue_size:
|
| 187 |
+
print('Warning: Preallocated queue was too small: tried to store '
|
| 188 |
+
f'{next_size} elements in a queue of size {queue_size}')
|
| 189 |
+
size = queue_size
|
| 190 |
+
|
| 191 |
+
if dr.hint(iter_num == max_depth_split, mode = "scalar"):
|
| 192 |
+
print(f'Warning : The split tree depth exceeds the specified value {max_depth_split}. '
|
| 193 |
+
f'The rest of the particles ({size}, {size / dr.width(points_in) * 100 :.1f} %) will be'
|
| 194 |
+
'simulated without splitting.')
|
| 195 |
+
|
| 196 |
+
size = next_size
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# Generate the varibles for the next step.
|
| 200 |
+
if size > 0:
|
| 201 |
+
# Get the values from the queue for the next iter.
|
| 202 |
+
particle = dr.reshape(type(particle), value=queue, shape=next_size, shrink=True)
|
| 203 |
+
# Initially, all particles are active in the next iter.
|
| 204 |
+
active = dr.full(Bool, True, size)
|
| 205 |
+
|
| 206 |
+
active_conf = dr.gather(ArrayXb, active_conf_begin, particle.path_index)
|
| 207 |
+
return L_res, particle
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
@dr.syntax(print_code = False)
|
| 211 |
+
def solve_grad(self, points_in : Point2f = None, active_conf_in : ArrayXb = None, split : Split = Split.Normal,
|
| 212 |
+
mode : dr.ADMode = dr.ADMode.Backward, dL : ArrayXf = ArrayXf(0),
|
| 213 |
+
derivative_dir : Point2f = None, conf_numbers : list[UInt32] = [UInt32(0)],
|
| 214 |
+
max_length : UInt32 = None, tput_kill : Float = Float(0.8), all_inside = False, fd_forward = False,
|
| 215 |
+
max_depth_split = 100, verbose = False):
|
| 216 |
+
|
| 217 |
+
size = dr.width(points_in)
|
| 218 |
+
if conf_numbers is not None:
|
| 219 |
+
num_conf = len(conf_numbers)
|
| 220 |
+
else:
|
| 221 |
+
num_conf = 1
|
| 222 |
+
#L_res = dr.zeros(Float, size)
|
| 223 |
+
L_res = dr.zeros(ArrayXf, (num_conf, size))
|
| 224 |
+
|
| 225 |
+
# Loss grad value splatted to the paths.
|
| 226 |
+
dL_begin = ArrayXf(dL)
|
| 227 |
+
|
| 228 |
+
if mode == dr.ADMode.Forward:
|
| 229 |
+
dL = ArrayXf(0)
|
| 230 |
+
|
| 231 |
+
active = Bool(True)
|
| 232 |
+
active_conf_begin = dr.ones(ArrayXb, shape = L_res.shape) if active_conf_in is None else active_conf_in
|
| 233 |
+
active_conf = ArrayXb(active_conf_begin)
|
| 234 |
+
assert L_res.shape == active_conf.shape
|
| 235 |
+
|
| 236 |
+
if dr.hint(self.input.shape.single_closed and (not all_inside), mode = 'scalar'):
|
| 237 |
+
active, L_res = self.input.shape.inside_closed_surface(points_in, L_res, conf_numbers)
|
| 238 |
+
|
| 239 |
+
seq = dr.arange(UInt64, size)
|
| 240 |
+
initstate, initseq = tea(UInt64(seq), UInt64(self.seed))
|
| 241 |
+
pcg = PCG32()
|
| 242 |
+
pcg.seed(initstate, initseq)
|
| 243 |
+
|
| 244 |
+
particle = Particle(points = Point2f(points_in), w = Float(1.0), w_split = Float(1.0),
|
| 245 |
+
sampler = PCG32(pcg), path_index = dr.arange(UInt32, size),
|
| 246 |
+
path_length = UInt32(0), traverse_h = Array4u64(1,0,0,0))
|
| 247 |
+
|
| 248 |
+
particle_prb = Particle(points = Point2f(points_in), w = Float(1.0), w_split = Float(1.0),
|
| 249 |
+
sampler = PCG32(pcg), path_index = dr.arange(UInt32, size),
|
| 250 |
+
path_length = UInt32(0), traverse_h = Array4u64(1,0,0,0))
|
| 251 |
+
active_prb = Bool(active)
|
| 252 |
+
|
| 253 |
+
with dr.suspend_grad():
|
| 254 |
+
# If we apply no path splitting.
|
| 255 |
+
if dr.hint(split == Split.Naive, mode = 'scalar'):
|
| 256 |
+
# Primal phase.
|
| 257 |
+
# We take a derivative step in the beginning if the direction is specified.
|
| 258 |
+
if dr.hint(derivative_dir is not None , mode = 'scalar'):
|
| 259 |
+
particle = self.take_derivative_step(derivative_dir, L_res, particle, dr.ADMode.Primal, Float(0), active, active_conf)
|
| 260 |
+
|
| 261 |
+
# Take other steps.
|
| 262 |
+
while active:
|
| 263 |
+
particle = self.take_step(L_res, particle, dr.ADMode.Primal, split, Float(0), active, active_conf,
|
| 264 |
+
conf_numbers, max_length, tput_kill, fd_forward)
|
| 265 |
+
# Russian roulette
|
| 266 |
+
if active & (particle.w_split < self.w_window[0]):
|
| 267 |
+
if particle.sampler.next_float32() >= particle.w:
|
| 268 |
+
active = Bool(False)
|
| 269 |
+
else:
|
| 270 |
+
particle.w = Float(1)
|
| 271 |
+
|
| 272 |
+
# Replay phase.
|
| 273 |
+
L_replay = ArrayXf(L_res)
|
| 274 |
+
# We do the same exact thing with different compuation mode.
|
| 275 |
+
if dr.hint(derivative_dir is not None, mode = 'scalar'):
|
| 276 |
+
particle_prb = self.take_derivative_step(derivative_dir, L_replay, particle_prb, mode, dL, active_prb, active_conf)
|
| 277 |
+
# Take other steps.
|
| 278 |
+
while active_prb:
|
| 279 |
+
particle_prb = self.take_step(L_replay, particle_prb, mode, split, dL, active_prb, active_conf,
|
| 280 |
+
conf_numbers, max_length, tput_kill, fd_forward)
|
| 281 |
+
# Russian roulette
|
| 282 |
+
if active_prb & (particle_prb.w_split < self.w_window[0]):
|
| 283 |
+
if particle_prb.sampler.next_float32() >= particle_prb.w:
|
| 284 |
+
active_prb = Bool(False)
|
| 285 |
+
else:
|
| 286 |
+
particle_prb.w = Float(1)
|
| 287 |
+
return L_res, particle
|
| 288 |
+
|
| 289 |
+
# Otherwise do the path splitting scheme.
|
| 290 |
+
iter_num = 0
|
| 291 |
+
traverse_index = dr.zeros(Array4u64, size) # We start with the traverse index of the last splitted particle.
|
| 292 |
+
traverse_index_prb = dr.zeros(Array4u64, size)
|
| 293 |
+
traverse_index[0] = UInt64(1)
|
| 294 |
+
traverse_index_prb[0] = UInt64(1)
|
| 295 |
+
|
| 296 |
+
while (size > 0) & (iter_num < (max_depth_split + 1)):
|
| 297 |
+
queue_index = UInt32(0)
|
| 298 |
+
is_split = iter_num < max_depth_split
|
| 299 |
+
|
| 300 |
+
if dr.hint(is_split, mode = 'scalar'):
|
| 301 |
+
# Preallocate memory for the queue. The necessary amount of memory is
|
| 302 |
+
# task-dependent (how many splits there are)
|
| 303 |
+
queue_size = dr.maximum(50, int(2 * size))
|
| 304 |
+
queue_size_opaque = dr.opaque(UInt32, queue_size)
|
| 305 |
+
queue = dr.empty(dtype=Particle, shape=queue_size)
|
| 306 |
+
|
| 307 |
+
# Get the primal result of each iteration in the gradient computation for prb.
|
| 308 |
+
L_iter = dr.zeros(ArrayXf, shape = (num_conf, size))
|
| 309 |
+
# We again first take the derivative step if it is specified.
|
| 310 |
+
if dr.hint((derivative_dir is not None) & (iter_num == 0), mode = 'scalar'):
|
| 311 |
+
first_traverse = is_one(traverse_index)
|
| 312 |
+
particle = self.take_derivative_step(derivative_dir, L_iter, particle, dr.ADMode.Primal, ArrayXf(0),
|
| 313 |
+
active, active_conf, illumination_mask= first_traverse)
|
| 314 |
+
|
| 315 |
+
while active:
|
| 316 |
+
# This is the main part of the algorithm (WoS).
|
| 317 |
+
first_traverse = is_one(traverse_index)
|
| 318 |
+
particle = self.take_step(L_iter, particle, dr.ADMode.Primal, split, ArrayXf(0), active, active_conf,
|
| 319 |
+
conf_numbers, max_length, tput_kill, fd_forward = fd_forward,
|
| 320 |
+
illumination_mask= first_traverse)
|
| 321 |
+
# Russian roulette
|
| 322 |
+
if active & (particle.w_split < self.w_window[0]):
|
| 323 |
+
if particle.sampler.next_float32() >= particle.w_split:
|
| 324 |
+
active = Bool(False)
|
| 325 |
+
else:
|
| 326 |
+
particle.w /= particle.w_split
|
| 327 |
+
particle.w_split = Float(1)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
# Splitting begins. #################################################
|
| 331 |
+
if ((particle.w_split >= self.w_window[1]) & active):
|
| 332 |
+
particle, new_particle = split_particle(particle)
|
| 333 |
+
|
| 334 |
+
if dr.hint(is_split, mode = 'scalar'):
|
| 335 |
+
slot = dr.scatter_inc(queue_index, index=0, active = first_traverse)
|
| 336 |
+
|
| 337 |
+
# Be careful not to write beyond the end of the queue
|
| 338 |
+
valid = first_traverse & (slot < queue_size_opaque)
|
| 339 |
+
|
| 340 |
+
# Write 'new_state' into the reserved slot
|
| 341 |
+
dr.scatter(target=queue, value=new_particle, index=slot, active=valid)
|
| 342 |
+
|
| 343 |
+
if ~first_traverse:
|
| 344 |
+
msb2, traverse_index = MSB2(traverse_index)
|
| 345 |
+
if msb2 == 1:
|
| 346 |
+
particle = new_particle
|
| 347 |
+
|
| 348 |
+
if dr.hint(mode != dr.ADMode.Primal, mode = 'scalar'):
|
| 349 |
+
# Start the replay phase.
|
| 350 |
+
L_replay = ArrayXf(L_iter)
|
| 351 |
+
# We again first take the derivative step if the direction is specified.
|
| 352 |
+
if dr.hint((derivative_dir is not None) & (iter_num == 0), mode = 'scalar'):
|
| 353 |
+
first_traverse_prb = is_one(traverse_index_prb)
|
| 354 |
+
particle_prb = self.take_derivative_step(derivative_dir, L_replay, particle_prb, mode, dL,
|
| 355 |
+
active_prb, active_conf, illumination_mask=first_traverse_prb)
|
| 356 |
+
|
| 357 |
+
while active_prb:
|
| 358 |
+
# This is the main part of the algorithm (WoS).
|
| 359 |
+
first_traverse_prb = is_one(traverse_index_prb)
|
| 360 |
+
particle_prb = self.take_step(L_replay, particle_prb, mode, split, dL, active_prb, active_conf,
|
| 361 |
+
conf_numbers, max_length, tput_kill, fd_forward = fd_forward,
|
| 362 |
+
illumination_mask=first_traverse_prb)
|
| 363 |
+
|
| 364 |
+
# Russian roulette
|
| 365 |
+
if ((particle_prb.w_split < self.w_window[0]) & active_prb):
|
| 366 |
+
if particle_prb.sampler.next_float32() >= particle_prb.w_split:
|
| 367 |
+
active_prb = Bool(False)
|
| 368 |
+
else:
|
| 369 |
+
particle_prb.w /= particle_prb.w_split
|
| 370 |
+
particle_prb.w_split = Float(1)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
if ((particle_prb.w_split >= self.w_window[1]) & active_prb):
|
| 375 |
+
# Split the particle in the same way.
|
| 376 |
+
particle_prb, new_particle_prb = split_particle(particle_prb)
|
| 377 |
+
|
| 378 |
+
if ~first_traverse_prb:
|
| 379 |
+
msb2_prb, traverse_index_prb = MSB2(traverse_index_prb)
|
| 380 |
+
if msb2_prb == 1:
|
| 381 |
+
particle_prb = new_particle_prb
|
| 382 |
+
|
| 383 |
+
dr.scatter_add(L_res, L_iter, particle.path_index)
|
| 384 |
+
next_size = queue_index[0]
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
if verbose:
|
| 388 |
+
print('%u : %u -> %u' % (iter_num, size, next_size))
|
| 389 |
+
iter_num += 1
|
| 390 |
+
|
| 391 |
+
if dr.hint(is_split, mode = "scalar"):
|
| 392 |
+
if next_size > queue_size:
|
| 393 |
+
print('Warning: Preallocated queue was too small: tried to store '
|
| 394 |
+
f'{next_size} elements in a queue of size {queue_size}')
|
| 395 |
+
size = queue_size
|
| 396 |
+
|
| 397 |
+
if dr.hint(iter_num == max_depth_split, mode = "scalar"):
|
| 398 |
+
print(f'Warning : The split tree depth exceeds the specified value f{max_depth_split}. '
|
| 399 |
+
f'The rest of the particles ({size}, {size / dr.width(points_in) * 100 :.1f} %) will be'
|
| 400 |
+
'simulated without splitting.')
|
| 401 |
+
|
| 402 |
+
size = next_size
|
| 403 |
+
# Generate the varibles for the next step.
|
| 404 |
+
if size > 0:
|
| 405 |
+
# Get the values from the queue.
|
| 406 |
+
particle_f = dr.reshape(type(particle), value=queue, shape=size, shrink=True)
|
| 407 |
+
|
| 408 |
+
# Initially, all particles are active in the next iter.
|
| 409 |
+
active = dr.full(Bool, True, size)
|
| 410 |
+
|
| 411 |
+
# Set the traverse index to be the last traverse history.
|
| 412 |
+
traverse_index = Array4u64(particle_f.traverse_h)
|
| 413 |
+
|
| 414 |
+
# Get the initial points for the next run.
|
| 415 |
+
next_points = dr.gather(Point2f, points_in, particle_f.path_index)
|
| 416 |
+
|
| 417 |
+
# Get the active configurations.
|
| 418 |
+
active_conf = dr.gather(ArrayXb, active_conf_begin, particle_f.path_index)
|
| 419 |
+
|
| 420 |
+
# Get the loss grad value splatted to the paths.
|
| 421 |
+
if mode == dr.ADMode.Backward:
|
| 422 |
+
dL = dr.gather(ArrayXf, dL_begin, particle_f.path_index)
|
| 423 |
+
|
| 424 |
+
initseq, initstate = tea(UInt64(particle_f.path_index), UInt64(self.seed))
|
| 425 |
+
pcg_iter = PCG32()
|
| 426 |
+
pcg_iter.seed(initseq, initstate)
|
| 427 |
+
|
| 428 |
+
particle = Particle(points=Point2f(next_points),
|
| 429 |
+
w = Float(1),
|
| 430 |
+
w_split = Float(1),
|
| 431 |
+
sampler = PCG32(pcg_iter),
|
| 432 |
+
path_index = UInt32(particle_f.path_index),
|
| 433 |
+
path_length = UInt32(0),
|
| 434 |
+
traverse_h= Array4u64(1,0,0,0))
|
| 435 |
+
|
| 436 |
+
# Generate the same for the replay stage.
|
| 437 |
+
active_prb = Bool(active)
|
| 438 |
+
traverse_index_prb = Array4u64(traverse_index)
|
| 439 |
+
|
| 440 |
+
particle_prb = Particle(points=Point2f(next_points),
|
| 441 |
+
w = Float(1.),
|
| 442 |
+
w_split = Float(1.),
|
| 443 |
+
sampler = PCG32(pcg_iter),
|
| 444 |
+
path_index = UInt32(particle_f.path_index),
|
| 445 |
+
path_length = UInt32(0),
|
| 446 |
+
traverse_h= Array4u64(1,0,0,0))
|
| 447 |
+
return L_res, particle
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
@dr.syntax(print_code = False)
|
| 451 |
+
def take_step(self, L : ArrayXf, p : Particle, mode : dr.ADMode, split : Split, dL : ArrayXf, active : Bool, active_conf : ArrayXb = ArrayXb(True),
|
| 452 |
+
conf_numbers : list[UInt32] = None, max_length : UInt32 = None, tput_kill : Float = Float(0.8),
|
| 453 |
+
fd_forward : bool = False, illumination_mask : Bool = Bool(True)):
|
| 454 |
+
|
| 455 |
+
if conf_numbers is not None:
|
| 456 |
+
num_conf = len(conf_numbers)
|
| 457 |
+
else:
|
| 458 |
+
num_conf = 1
|
| 459 |
+
|
| 460 |
+
primal = (mode == dr.ADMode.Primal)
|
| 461 |
+
bi = self.input.shape.boundary_interaction(p.points, star_generation = False, conf_numbers = conf_numbers)
|
| 462 |
+
|
| 463 |
+
if bi.is_far:
|
| 464 |
+
p.thrown = Bool(True)
|
| 465 |
+
active &= Bool(False)
|
| 466 |
+
|
| 467 |
+
# Decrease radius if it is big.
|
| 468 |
+
σ_bar = self.input.σ_bar
|
| 469 |
+
z = Float(0)
|
| 470 |
+
if self.use_accel:
|
| 471 |
+
bi.r, σ_bar, z = self.input.get_Rσz(p.points, bi.r)
|
| 472 |
+
else:
|
| 473 |
+
z = bi.r * dr.sqrt(σ_bar)
|
| 474 |
+
if z > self.max_z:
|
| 475 |
+
bi.r *= self.max_z / z
|
| 476 |
+
z = self.max_z
|
| 477 |
+
|
| 478 |
+
self.green.initialize(z)
|
| 479 |
+
dirichlet_ending = (active & bi.is_e & bi.is_d)
|
| 480 |
+
|
| 481 |
+
# Add the dirichlet boundary contribution in epsilon-shell!
|
| 482 |
+
added_near = dr.select(dirichlet_ending & active_conf, p.w * bi.dval, 0)
|
| 483 |
+
|
| 484 |
+
L += added_near if primal else -added_near
|
| 485 |
+
|
| 486 |
+
with dr.resume_grad(when=not primal):
|
| 487 |
+
α = self.input.α.get_value(p.points)
|
| 488 |
+
|
| 489 |
+
# Remove the channels in which the walk is finished.
|
| 490 |
+
active &= ~dirichlet_ending
|
| 491 |
+
|
| 492 |
+
f_cont = Float(0)
|
| 493 |
+
# Add the source contribution.
|
| 494 |
+
if dr.hint(not self.input.f.is_zero, mode = 'scalar'):
|
| 495 |
+
sample_source = Point2f(p.sampler.next_float32(), p.sampler.next_float32())
|
| 496 |
+
#if illumination_mask:
|
| 497 |
+
r_vol, normG = self.green.sample(sample_source[0], bi.r, σ_bar)
|
| 498 |
+
dir_vol, _ = sample_uniform_direction(sample_source[1])
|
| 499 |
+
points_vol = p.points + r_vol * dir_vol
|
| 500 |
+
with dr.resume_grad(when=not primal):
|
| 501 |
+
α_vol = self.input.α.get_value(points_vol)
|
| 502 |
+
f_vol = self.input.f.get_value(points_vol)
|
| 503 |
+
f_cont = p.w * f_vol * normG / dr.sqrt(α * α_vol)
|
| 504 |
+
if dr.isnan(f_cont) | ~illumination_mask:
|
| 505 |
+
f_cont = Float(0)
|
| 506 |
+
|
| 507 |
+
f_cont = dr.select(active_conf, f_cont, 0)
|
| 508 |
+
L += f_cont if primal else -f_cont
|
| 509 |
+
|
| 510 |
+
# Now select between boundary or volume sampling (2nd paper, eqn 28)
|
| 511 |
+
normG = self.green.eval_norm(bi.r, σ_bar)
|
| 512 |
+
prob_vol = σ_bar * normG
|
| 513 |
+
sample_rec = Point2f(p.sampler.next_float32(), p.sampler.next_float32())
|
| 514 |
+
sample_vol = active & (sample_rec[0] < prob_vol)
|
| 515 |
+
sample_rec[0] = dr.select(sample_vol, sample_rec[0] / prob_vol, (sample_rec[0] - prob_vol) / (1-prob_vol))
|
| 516 |
+
|
| 517 |
+
r_next = Float(bi.r)
|
| 518 |
+
if sample_vol:
|
| 519 |
+
r_next = self.green.sample(sample_rec[0], bi.r, σ_bar)[0]
|
| 520 |
+
|
| 521 |
+
dir_next, _ = sample_uniform_direction(sample_rec[1])
|
| 522 |
+
points_next = p.points + r_next * dir_next
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
with dr.resume_grad(when=not primal):
|
| 526 |
+
α_next = self.input.α.get_value(points_next)
|
| 527 |
+
grad_α_next, laplacian_α_next = self.input.α.get_grad_laplacian(points_next)
|
| 528 |
+
σ_next = self.input.σ.get_value(points_next)
|
| 529 |
+
σ_new = self.σ_(σ_next, α_next, grad_α_next, laplacian_α_next)
|
| 530 |
+
w_ = dr.select(active, dr.sqrt(α_next / α), 1.0)
|
| 531 |
+
w_s = dr.select(sample_vol, (1.0 - σ_new / σ_bar), 1.0)
|
| 532 |
+
w_update = w_ * w_s
|
| 533 |
+
# Boundary and Volume Contribution
|
| 534 |
+
prb_cont = dr.select(dr.isfinite(w_update), L * w_update / dr.detach(w_update), 0.0)
|
| 535 |
+
|
| 536 |
+
if dr.hint(mode == dr.ADMode.Backward, mode = 'scalar'):
|
| 537 |
+
dr.backward(dr.sum((prb_cont + f_cont) * dL))
|
| 538 |
+
elif dr.hint(mode == dr.ADMode.Forward, mode = 'scalar'):
|
| 539 |
+
dL += dr.forward_to(dr.sum(prb_cont + f_cont))
|
| 540 |
+
|
| 541 |
+
p.w *= w_update
|
| 542 |
+
# If we are not doing fd computation, then just use the original coefficient.
|
| 543 |
+
if dr.hint((not fd_forward), mode = 'scalar'):
|
| 544 |
+
if dr.hint(split == Split.Agressive, mode = 'scalar'):
|
| 545 |
+
p.w_split *= w_update
|
| 546 |
+
elif dr.hint(split == Split.Normal, mode = 'scalar'):
|
| 547 |
+
p.w_split *= w_s
|
| 548 |
+
else:
|
| 549 |
+
α = self.input.α_split.get_value(p.points) # We did not get this before if f is zero!
|
| 550 |
+
α_next = self.input.α_split.get_value(points_next)
|
| 551 |
+
grad_α_next, laplacian_α_next = self.input.α_split.get_grad_laplacian(points_next)
|
| 552 |
+
σ_next = self.input.σ_split.get_value(points_next)
|
| 553 |
+
σ_new = self.σ_(σ_next, α_next, grad_α_next, laplacian_α_next)
|
| 554 |
+
w_ = dr.select(active, dr.sqrt(α_next / α), 1.0)
|
| 555 |
+
w_s = dr.select(sample_vol, (1.0 - σ_new / σ_bar), 1.0)
|
| 556 |
+
if dr.hint(split == Split.Agressive, mode = 'scalar'):
|
| 557 |
+
p.w_split *= (w_ * w_s)
|
| 558 |
+
elif dr.hint(split == Split.Normal, mode = 'scalar'):
|
| 559 |
+
p.w_split *= w_s
|
| 560 |
+
|
| 561 |
+
if dr.hint(max_length is not None, mode = 'scalar'):
|
| 562 |
+
if p.path_length > max_length:
|
| 563 |
+
p.w *= tput_kill
|
| 564 |
+
p.w_split *= tput_kill
|
| 565 |
+
|
| 566 |
+
active &= dr.isfinite(w_update)
|
| 567 |
+
p.points = points_next
|
| 568 |
+
p.path_length += 1
|
| 569 |
+
return p
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
@dr.syntax
|
| 573 |
+
def take_derivative_step(self, derivative_dir : Point2f, L : ArrayXf, p : Particle, mode : dr.ADMode, dL : ArrayXf,
|
| 574 |
+
active : Bool, active_conf : ArrayXb = ArrayXb(True), illumination_mask : Bool = Bool(True)) -> Particle:
|
| 575 |
+
"Computes the directional derivative of the computation!"
|
| 576 |
+
# There is no way to sample Green's function analytically. Use polynomial.
|
| 577 |
+
primal = (mode == dr.ADMode.Primal)
|
| 578 |
+
greenGrad = GreensFunctionPolynomial(dim = DIM.Two, newton_steps=10, grad = True)
|
| 579 |
+
bi = self.input.shape.boundary_interaction(p.points, star_generation = False)
|
| 580 |
+
bi.r = bi.d
|
| 581 |
+
# Decrease radius if it is big.
|
| 582 |
+
σ_bar = self.input.σ_bar
|
| 583 |
+
z = Float(0)
|
| 584 |
+
if self.use_accel:
|
| 585 |
+
bi.r, σ_bar, z = self.input.get_Rσz(p.points, bi.r)
|
| 586 |
+
else:
|
| 587 |
+
z = bi.r * dr.sqrt(σ_bar)
|
| 588 |
+
if z > self.max_z:
|
| 589 |
+
bi.r *= self.max_z / z
|
| 590 |
+
z = self.max_z
|
| 591 |
+
|
| 592 |
+
greenGrad.initialize(z)
|
| 593 |
+
active &= ~(bi.is_d & bi.is_e)
|
| 594 |
+
|
| 595 |
+
# This value is used pretty often.
|
| 596 |
+
with dr.resume_grad(when = not primal):
|
| 597 |
+
α = self.input.α.get_value(p.points)
|
| 598 |
+
|
| 599 |
+
# Get the contribution of the source term
|
| 600 |
+
f_cont = Float(0)
|
| 601 |
+
if dr.hint(not self.input.f.is_zero, mode = 'scalar'):
|
| 602 |
+
sample_source = Point2f(p.sampler.next_float32(), p.sampler.next_float32())
|
| 603 |
+
#if illumination_mask:
|
| 604 |
+
# Sample norm of the Gradient with the Greens function.
|
| 605 |
+
r_f, normdG_f = greenGrad.sample(sample_source[0], bi.r, σ_bar)
|
| 606 |
+
dir_f, _, sign_f = sample_cosine_direction(sample_source[1], derivative_dir)
|
| 607 |
+
points_f = p.points + r_f * dir_f
|
| 608 |
+
with dr.resume_grad(when=not primal):
|
| 609 |
+
f_f = self.input.f.get_value(points_f)
|
| 610 |
+
α_f = self.input.α.get_value(points_f)
|
| 611 |
+
f_cont = f_f * normdG_f * dr.rcp(dr.sqrt(α_f * α)) * sign_f * 2 / dr.pi
|
| 612 |
+
if dr.isnan(f_cont) | ~illumination_mask:
|
| 613 |
+
f_cont = Float(0)
|
| 614 |
+
f_cont = dr.select(active_conf, f_cont, 0)
|
| 615 |
+
L += f_cont if primal else -f_cont
|
| 616 |
+
|
| 617 |
+
# If diffusion is not constant, we need to split the path into 3, otherwise 2.
|
| 618 |
+
is_alpha_c = isinstance(self.input.α, ConstantCoefficient)
|
| 619 |
+
prob_paths = Float(0.5) if is_alpha_c else Float(1/3)
|
| 620 |
+
w_update = 1 / prob_paths
|
| 621 |
+
selected_path = UInt(0)
|
| 622 |
+
sign_next = Float(1)
|
| 623 |
+
points_next = Point2f(0)
|
| 624 |
+
_ = Float(0)
|
| 625 |
+
sample_rec = Point2f(p.sampler.next_float32(), p.sampler.next_float32())
|
| 626 |
+
if sample_rec[0] < prob_paths:
|
| 627 |
+
sample_rec[0] /= prob_paths
|
| 628 |
+
r_next, normdG = greenGrad.sample(sample_rec[0], bi.r, σ_bar)
|
| 629 |
+
dir, _, sign_next = sample_cosine_direction(sample_rec[1], derivative_dir)
|
| 630 |
+
points_next = p.points + r_next * dir
|
| 631 |
+
w_update *= normdG * sign_next * 2 / dr.pi
|
| 632 |
+
selected_path = UInt32(0)
|
| 633 |
+
elif sample_rec[0] < 2 * prob_paths:
|
| 634 |
+
sample_rec[0] = (sample_rec[0] - prob_paths) / prob_paths
|
| 635 |
+
points_next, _, sign_next = sample_cosine_boundary(sample_rec[1], p.points, bi.r, derivative_dir)
|
| 636 |
+
w_update *= 4 * sign_next * bi.r * eval_dP_norm(bi.r, σ_bar)
|
| 637 |
+
selected_path = UInt32(1)
|
| 638 |
+
else:
|
| 639 |
+
points_next = p.points
|
| 640 |
+
selected_path = UInt32(2)
|
| 641 |
+
|
| 642 |
+
# Compute the throughput updates that needs to be diffrentiated.
|
| 643 |
+
with dr.resume_grad(when=not primal):
|
| 644 |
+
# The first path (Volume sampling)
|
| 645 |
+
σ_next = self.input.σ.get_value(points_next)
|
| 646 |
+
α_next = self.input.α.get_value(points_next)
|
| 647 |
+
|
| 648 |
+
if dr.hint(is_alpha_c, mode = 'scalar'):
|
| 649 |
+
if selected_path == 0:
|
| 650 |
+
w_update *= (σ_bar - σ_next / α_next)
|
| 651 |
+
else:
|
| 652 |
+
if dr.hint(self.input.f.is_zero, mode = 'scalar'):
|
| 653 |
+
α = self.input.α.get_value(p.points) # We did not get this before if f is zero!
|
| 654 |
+
grad_α, _ = self.input.α.get_grad_laplacian(p.points)
|
| 655 |
+
grad_α_next, laplacian_α_next = self.input.α.get_grad_laplacian(points_next)
|
| 656 |
+
σ_new = self.σ_(σ_next, α_next, grad_α_next, laplacian_α_next)
|
| 657 |
+
|
| 658 |
+
w_update *= dr.select(selected_path == 0, dr.sqrt(α_next / α) * (σ_bar - σ_new), 1)
|
| 659 |
+
w_update *= dr.select(selected_path == 1, dr.sqrt(α_next / α), 1)
|
| 660 |
+
w_update *= dr.select(selected_path == 2, -dr.rcp(2 * α) * dr.dot(grad_α, derivative_dir), 1)
|
| 661 |
+
|
| 662 |
+
# Apply path replay gradient contribution.
|
| 663 |
+
prb_cont = dr.select(active, L * w_update / dr.detach(w_update), 0)
|
| 664 |
+
if dr.hint(mode == dr.ADMode.Backward, mode = 'scalar'):
|
| 665 |
+
dr.backward(dr.sum((prb_cont + f_cont) * dL))
|
| 666 |
+
elif dr.hint(mode == dr.ADMode.Forward, mode = 'scalar'):
|
| 667 |
+
dL += dr.forward_to(dr.sum(prb_cont + f_cont))
|
| 668 |
+
|
| 669 |
+
# Update throughput and next points.
|
| 670 |
+
p.points = points_next
|
| 671 |
+
p.w *= w_update
|
| 672 |
+
return p
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
def is_one(index : Array4u64) -> Bool:
|
| 676 |
+
return (index[0] == UInt64(1)) & (index[1] == UInt64(0)) & (index[2] == UInt64(0)) & (index[3] == UInt64(0))
|
| 677 |
+
|
| 678 |
+
@dr.syntax
|
| 679 |
+
def shift_left(index : Array4u64):
|
| 680 |
+
index_new = Array4u64(index)
|
| 681 |
+
for i in range(3, 0, -1):
|
| 682 |
+
index_new[i] = index[i] << 1
|
| 683 |
+
if dr.lzcnt(index[i-1]) == 0:
|
| 684 |
+
index_new[i] += 1
|
| 685 |
+
index_new[0] = index[0] << 1
|
| 686 |
+
return index_new
|
| 687 |
+
|
| 688 |
+
@dr.syntax
|
| 689 |
+
def MSB2(index : Array4u64):
|
| 690 |
+
"Find the 2nd MSB and throw it out"
|
| 691 |
+
index_residual = UInt32(0)
|
| 692 |
+
index_full = UInt32(0)
|
| 693 |
+
for i in range(3, -1, -1):
|
| 694 |
+
if index_residual == 0:
|
| 695 |
+
index_residual += (64 - UInt32(dr.lzcnt(index[i])))
|
| 696 |
+
index_full = UInt32(i)
|
| 697 |
+
|
| 698 |
+
if (index_residual == 0) & (index_full > 0):
|
| 699 |
+
index_full -= 1
|
| 700 |
+
index_residual = UInt32(64)
|
| 701 |
+
|
| 702 |
+
msb2 = UInt64(0)
|
| 703 |
+
thrown = Array4u64(index)
|
| 704 |
+
for i in range(4):
|
| 705 |
+
if index_full == i:
|
| 706 |
+
if index_residual > 1:
|
| 707 |
+
shift_num = (index_residual - 2)
|
| 708 |
+
msb2 = (index[i] >> shift_num) & 1
|
| 709 |
+
msb2e = UInt64(1) << shift_num
|
| 710 |
+
thrown[i] = index[i] % msb2e + msb2e
|
| 711 |
+
elif index_residual == 1:
|
| 712 |
+
if i > 0:
|
| 713 |
+
msb2 = (index[i-1] >> 63) & 1
|
| 714 |
+
thrown[i] = UInt64(0)
|
| 715 |
+
msb2e = UInt64(1)<<63
|
| 716 |
+
thrown[i-1] = index[i-1] % msb2e + msb2e
|
| 717 |
+
return msb2, thrown
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
def split_particle(particle : Particle):
|
| 721 |
+
new_particle_state = particle.sampler.next_uint64()
|
| 722 |
+
shifted = shift_left(particle.traverse_h)
|
| 723 |
+
new_particle = Particle(points = particle.points,
|
| 724 |
+
w=particle.w/2,
|
| 725 |
+
w_split = particle.w_split/2,
|
| 726 |
+
sampler = PCG32(particle.sampler),
|
| 727 |
+
path_index = particle.path_index,
|
| 728 |
+
path_length = particle.path_length,
|
| 729 |
+
traverse_h = Array4u64(shifted))
|
| 730 |
+
new_particle.traverse_h[0] += UInt64(1)
|
| 731 |
+
|
| 732 |
+
new_particle.sampler.state = new_particle_state
|
| 733 |
+
particle.w /= 2
|
| 734 |
+
particle.w_split /= 2
|
| 735 |
+
particle.traverse_h = Array4u64(shifted)
|
| 736 |
+
return particle, new_particle
|
data/PDE2D/Solver/variable/wos_variable_rejection.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from ..data_holder import DataHolder
|
| 3 |
+
from ...Coefficient import *
|
| 4 |
+
from ...Sampling import *
|
| 5 |
+
from ...BoundaryShape.interaction import BoundaryInfo
|
| 6 |
+
from PDE2D.BoundaryShape import *
|
| 7 |
+
from .wos_variable import *
|
| 8 |
+
|
| 9 |
+
class WosVariableRejection(WosVariable):
|
| 10 |
+
def __init__(self, input : DataHolder, seed : int = 37, weight_window = [0.5, 2], max_z : float = 4,
|
| 11 |
+
green_sampling : GreenSampling = 0, newton_steps : int = 5, use_accelaration : bool = True,
|
| 12 |
+
opt_params : list[str] = []):
|
| 13 |
+
super().__init__(input, seed, weight_window, max_z,
|
| 14 |
+
green_sampling, newton_steps, use_accelaration, opt_params)
|
| 15 |
+
|
| 16 |
+
@dr.syntax(print_code = False)
|
| 17 |
+
def take_step(self, L : ArrayXf, p : Particle, mode : dr.ADMode, split : Split, dL : ArrayXf, active : Bool, active_conf : ArrayXb = ArrayXb(True),
|
| 18 |
+
conf_numbers : list[UInt32] = None, max_length : UInt32 = None, tput_kill : Float = Float(0.8),
|
| 19 |
+
fd_forward : bool = False, illumination_mask : Bool = Bool(True)):
|
| 20 |
+
if conf_numbers is not None:
|
| 21 |
+
num_conf = len(conf_numbers)
|
| 22 |
+
else:
|
| 23 |
+
num_conf = 1
|
| 24 |
+
|
| 25 |
+
primal = (mode == dr.ADMode.Primal)
|
| 26 |
+
bi = self.input.shape.boundary_interaction(p.points, star_generation = False, conf_numbers = conf_numbers)
|
| 27 |
+
|
| 28 |
+
if bi.is_far:
|
| 29 |
+
p.thrown = Bool(True)
|
| 30 |
+
active &= Bool(False)
|
| 31 |
+
|
| 32 |
+
# Decrease radius if it is big.
|
| 33 |
+
σ_bar = self.input.σ_bar
|
| 34 |
+
z = Float(0)
|
| 35 |
+
if self.use_accel:
|
| 36 |
+
bi.r, σ_bar, z = self.input.get_Rσz(p.points, bi.r)
|
| 37 |
+
else:
|
| 38 |
+
z = bi.r * dr.sqrt(σ_bar)
|
| 39 |
+
if z > self.max_z:
|
| 40 |
+
bi.r *= self.max_z / z
|
| 41 |
+
z = self.max_z
|
| 42 |
+
|
| 43 |
+
self.green.initialize(z)
|
| 44 |
+
dirichlet_ending = (active & bi.is_e & bi.is_d)
|
| 45 |
+
|
| 46 |
+
# Add the dirichlet boundary contribution in epsilon-shell!
|
| 47 |
+
added_near = dr.select(dirichlet_ending & active_conf, p.w * bi.dval, 0)
|
| 48 |
+
|
| 49 |
+
L += added_near if primal else -added_near
|
| 50 |
+
|
| 51 |
+
with dr.resume_grad(when=not primal):
|
| 52 |
+
α = self.input.α.get_value(p.points)
|
| 53 |
+
|
| 54 |
+
# Remove the channels in which the walk is finished.
|
| 55 |
+
active &= ~dirichlet_ending
|
| 56 |
+
|
| 57 |
+
f_cont = Float(0)
|
| 58 |
+
# Add the source contribution.
|
| 59 |
+
if dr.hint(not self.input.f.is_zero, mode = 'scalar'):
|
| 60 |
+
sample_source = Point2f(p.sampler.next_float32(), p.sampler.next_float32())
|
| 61 |
+
#if illumination_mask:
|
| 62 |
+
#r_vol, normG = self.green.sample(sample_source[0], bi.r, σ_bar)
|
| 63 |
+
r_vol, normG = self.sampleGreenRejection(p, bi.r, σ_bar)
|
| 64 |
+
dir_vol, _ = sample_uniform_direction(sample_source[1])
|
| 65 |
+
points_vol = p.points + r_vol * dir_vol
|
| 66 |
+
with dr.resume_grad(when=not primal):
|
| 67 |
+
α_vol = self.input.α.get_value(points_vol)
|
| 68 |
+
f_vol = self.input.f.get_value(points_vol)
|
| 69 |
+
f_cont = p.w * f_vol * normG / dr.sqrt(α * α_vol)
|
| 70 |
+
if dr.isnan(f_cont) | ~illumination_mask:
|
| 71 |
+
f_cont = Float(0)
|
| 72 |
+
|
| 73 |
+
f_cont = dr.select(active_conf, f_cont, 0)
|
| 74 |
+
L += f_cont if primal else -f_cont
|
| 75 |
+
|
| 76 |
+
# Now select between boundary or volume sampling (2nd paper, eqn 28)
|
| 77 |
+
normG = self.green.eval_norm(bi.r, σ_bar)
|
| 78 |
+
prob_vol = σ_bar * normG
|
| 79 |
+
sample_rec = Point2f(p.sampler.next_float32(), p.sampler.next_float32())
|
| 80 |
+
sample_vol = active & (sample_rec[0] < prob_vol)
|
| 81 |
+
sample_rec[0] = dr.select(sample_vol, sample_rec[0] / prob_vol, (sample_rec[0] - prob_vol) / (1-prob_vol))
|
| 82 |
+
|
| 83 |
+
r_next = Float(bi.r)
|
| 84 |
+
if sample_vol:
|
| 85 |
+
#r_next = self.green.sample(sample_rec[0], bi.r, σ_bar)[0]
|
| 86 |
+
r_next = self.sampleGreenRejection(p, bi.r, σ_bar)[0]
|
| 87 |
+
|
| 88 |
+
dir_next, _ = sample_uniform_direction(sample_rec[1])
|
| 89 |
+
points_next = p.points + r_next * dir_next
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
with dr.resume_grad(when=not primal):
|
| 93 |
+
α_next = self.input.α.get_value(points_next)
|
| 94 |
+
grad_α_next, laplacian_α_next = self.input.α.get_grad_laplacian(points_next)
|
| 95 |
+
σ_next = self.input.σ.get_value(points_next)
|
| 96 |
+
σ_new = self.σ_(σ_next, α_next, grad_α_next, laplacian_α_next)
|
| 97 |
+
w_ = dr.select(active, dr.sqrt(α_next / α), 1.0)
|
| 98 |
+
w_s = dr.select(sample_vol, (1.0 - σ_new / σ_bar), 1.0)
|
| 99 |
+
w_update = w_ * w_s
|
| 100 |
+
# Boundary and Volume Contribution
|
| 101 |
+
prb_cont = dr.select(dr.isfinite(w_update), L * w_update / dr.detach(w_update), 0.0)
|
| 102 |
+
|
| 103 |
+
if dr.hint(mode == dr.ADMode.Backward, mode = 'scalar'):
|
| 104 |
+
dr.backward(dr.sum((prb_cont + f_cont) * dL))
|
| 105 |
+
elif dr.hint(mode == dr.ADMode.Forward, mode = 'scalar'):
|
| 106 |
+
dL += dr.forward_to(dr.sum(prb_cont + f_cont))
|
| 107 |
+
|
| 108 |
+
p.w *= w_update
|
| 109 |
+
# If we are not doing fd computation, then just use the original coefficient.
|
| 110 |
+
if dr.hint((not fd_forward), mode = 'scalar'):
|
| 111 |
+
if dr.hint(split == Split.Agressive, mode = 'scalar'):
|
| 112 |
+
p.w_split *= w_update
|
| 113 |
+
elif dr.hint(split == Split.Normal, mode = 'scalar'):
|
| 114 |
+
p.w_split *= w_s
|
| 115 |
+
else:
|
| 116 |
+
α = self.input.α_split.get_value(p.points) # We did not get this before if f is zero!
|
| 117 |
+
α_next = self.input.α_split.get_value(points_next)
|
| 118 |
+
grad_α_next, laplacian_α_next = self.input.α_split.get_grad_laplacian(points_next)
|
| 119 |
+
σ_next = self.input.σ_split.get_value(points_next)
|
| 120 |
+
σ_new = self.σ_(σ_next, α_next, grad_α_next, laplacian_α_next)
|
| 121 |
+
w_ = dr.select(active, dr.sqrt(α_next / α), 1.0)
|
| 122 |
+
w_s = dr.select(sample_vol, (1.0 - σ_new / σ_bar), 1.0)
|
| 123 |
+
if dr.hint(split == Split.Agressive, mode = 'scalar'):
|
| 124 |
+
p.w_split *= (w_ * w_s)
|
| 125 |
+
elif dr.hint(split == Split.Normal, mode = 'scalar'):
|
| 126 |
+
p.w_split *= w_s
|
| 127 |
+
|
| 128 |
+
if dr.hint(max_length is not None, mode = 'scalar'):
|
| 129 |
+
if p.path_length > max_length:
|
| 130 |
+
p.w *= tput_kill
|
| 131 |
+
p.w_split *= tput_kill
|
| 132 |
+
|
| 133 |
+
active &= dr.isfinite(w_update)
|
| 134 |
+
p.points = points_next
|
| 135 |
+
p.path_length += 1
|
| 136 |
+
return p
|
| 137 |
+
|
| 138 |
+
@dr.syntax
|
| 139 |
+
def sampleGreenRejection(self, p : Particle, R : Float, σ : Float):
|
| 140 |
+
# We apply rejection sampling based on WosVariable paper.
|
| 141 |
+
if R <= σ:
|
| 142 |
+
upper_bound = dr.maximum(2.2 * dr.maximum(dr.rcp(R), dr.rcp(σ)), 0.6 * dr.maximum(dr.sqrt(R), dr.sqrt(σ)))
|
| 143 |
+
else:
|
| 144 |
+
upper_bound = dr.maximum(2.2 * dr.minimum(dr.rcp(R), dr.rcp(σ)), 0.6 * dr.minimum(dr.sqrt(R), dr.sqrt(σ)))
|
| 145 |
+
|
| 146 |
+
sample1 = p.sampler.next_float32() * R
|
| 147 |
+
sample2 = p.sampler.next_float32()
|
| 148 |
+
pdf = self.green.eval_pdf_only(sample1, R, σ)
|
| 149 |
+
while(sample2 * upper_bound > pdf):
|
| 150 |
+
sample1 = p.sampler.next_float32() * R
|
| 151 |
+
sample2 = p.sampler.next_float32()
|
| 152 |
+
pdf = self.green.eval_pdf_only(sample1, R, σ)
|
| 153 |
+
return sample1, self.green.eval_norm(R, σ)
|
data/PDE2D/Solver/variable/wost_variable.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import sys
|
| 3 |
+
from ..data_holder import DataHolder
|
| 4 |
+
from ...Coefficient import *
|
| 5 |
+
from ...Sampling import *
|
| 6 |
+
from .wos_variable import *
|
| 7 |
+
|
| 8 |
+
class WostVariable(WosVariable):
|
| 9 |
+
def __init__(self, input : DataHolder, seed : int = 37, weight_window = [0.5, 2],
|
| 10 |
+
max_z : float = 4, green_sampling : GreenSampling = 0,
|
| 11 |
+
newton_steps : int = 5, use_accelaration : Bool = True, opt_params : list[str] = []):
|
| 12 |
+
super().__init__(input, seed, weight_window, max_z,
|
| 13 |
+
green_sampling, newton_steps, use_accelaration, opt_params)
|
| 14 |
+
|
| 15 |
+
@dr.syntax
|
| 16 |
+
def take_step(self, L : ArrayXf, p : Particle, mode : dr.ADMode, split : Split, dL : ArrayXf, active : Bool, active_conf : ArrayXb = ArrayXb(True),
|
| 17 |
+
conf_numbers : list[UInt32] = None, max_length : UInt32 = None, tput_kill : Float = Float(0.8), fd_forward : bool = False,
|
| 18 |
+
illumination_mask: Bool = Bool(True)) -> Particle:
|
| 19 |
+
primal = (mode == dr.ADMode.Primal)
|
| 20 |
+
|
| 21 |
+
if conf_numbers is not None:
|
| 22 |
+
num_conf = len(conf_numbers)
|
| 23 |
+
else:
|
| 24 |
+
num_conf = 1
|
| 25 |
+
|
| 26 |
+
# Apply boundary interaction.
|
| 27 |
+
bi = self.input.shape.boundary_interaction(p.points, star_generation = False, conf_numbers = conf_numbers)
|
| 28 |
+
|
| 29 |
+
if bi.is_far:
|
| 30 |
+
p.thrown = Bool(True)
|
| 31 |
+
active &= Bool(False)
|
| 32 |
+
|
| 33 |
+
# Decrease radius to sample from a reasonable Green's function.
|
| 34 |
+
σ_bar = self.input.σ_bar
|
| 35 |
+
z = Float(0)
|
| 36 |
+
if self.use_accel:
|
| 37 |
+
bi.r, σ_bar, z = self.input.get_Rσz(p.points, bi.r)
|
| 38 |
+
else:
|
| 39 |
+
z = bi.r * dr.sqrt(σ_bar)
|
| 40 |
+
if z > self.max_z:
|
| 41 |
+
bi.r *= self.max_z / z
|
| 42 |
+
z = self.max_z
|
| 43 |
+
|
| 44 |
+
self.green.initialize(z)
|
| 45 |
+
# Generate stars.
|
| 46 |
+
bi = self.input.shape.star_generation(bi)
|
| 47 |
+
|
| 48 |
+
# End the paths if we are in the epsilon shell of a dirichlet boundary.
|
| 49 |
+
dirichlet_ending = (active & bi.is_e & bi.is_d)
|
| 50 |
+
|
| 51 |
+
# Add the dirichlet boundary contribution in epsilon-shell!
|
| 52 |
+
added_near = dr.select(dirichlet_ending & active_conf, p.w * bi.dval, 0)
|
| 53 |
+
|
| 54 |
+
L += added_near if primal else -added_near
|
| 55 |
+
|
| 56 |
+
# Remove the channels in which the walk is finished.
|
| 57 |
+
active &= ~dirichlet_ending
|
| 58 |
+
|
| 59 |
+
#This is used throughout the integrator. So we compute it in the beginning.
|
| 60 |
+
with dr.resume_grad(when = not primal):
|
| 61 |
+
α = self.input.α.get_value(p.points)
|
| 62 |
+
|
| 63 |
+
# Source term contribution.
|
| 64 |
+
f_cont = Float(0)
|
| 65 |
+
if dr.hint(not self.input.f.is_zero, mode = 'scalar'):
|
| 66 |
+
sample_source = Point2f(p.sampler.next_float32(), p.sampler.next_float32())
|
| 67 |
+
#if illumination_mask:
|
| 68 |
+
r_f, normG = self.green.sample(sample_source[0], bi.r, σ_bar)
|
| 69 |
+
dir_f, _ = sample_star_direction(sample_source[1], bi.is_star & bi.on_boundary, bi.bn)
|
| 70 |
+
points_f = mi.Point2f(p.points + r_f * dir_f)
|
| 71 |
+
# If we are on a star, The sampled point might be outside of the boundary.
|
| 72 |
+
# We need to check this with a ray intersection.
|
| 73 |
+
ri_f = self.input.shape.ray_intersect(bi, dir_f)
|
| 74 |
+
with dr.resume_grad(when=not primal):
|
| 75 |
+
α_f = self.input.α.get_value(points_f)
|
| 76 |
+
f_f = self.input.f.get_value(points_f)
|
| 77 |
+
f_cont = p.w * f_f * normG / dr.sqrt(α * α_f)
|
| 78 |
+
#if dr.isnan(f_cont) | (r_f > ri_f.t) | ~illumination_mask:
|
| 79 |
+
# f_cont = Float(0)
|
| 80 |
+
f_cont = dr.select(active_conf, f_cont, 0)
|
| 81 |
+
|
| 82 |
+
L += f_cont if primal else -f_cont
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
# Neumann boundary contribution.
|
| 86 |
+
# If we have a continous Neumann on the boundary, we need to sample it.
|
| 87 |
+
n_cont_cont = dr.zeros(ArrayXf, shape = L.shape)
|
| 88 |
+
|
| 89 |
+
if dr.hint(self.input.has_continuous_neumann, mode = 'scalar'):
|
| 90 |
+
# If we have a special sampling scheme based on boundary values, then we need to get all of the values.
|
| 91 |
+
if dr.hint(self.input.NEE == NEE.Special, mode = 'scalar'):
|
| 92 |
+
for i in range(num_conf):
|
| 93 |
+
conf_number = None if conf_numbers is None else conf_numbers[i]
|
| 94 |
+
#==if illumination_mask:
|
| 95 |
+
sample_neumann = p.sampler.next_float32()
|
| 96 |
+
dist_n, n_val, pdf_n_r, p_n = self.input.sampleNEE_special(bi, sample_neumann, conf_number)
|
| 97 |
+
G_n_r = self.green.eval(dist_n, bi.r, σ_bar)
|
| 98 |
+
|
| 99 |
+
if ((pdf_n_r > 0) & (dist_n < bi.r) & (dist_n > 0)):
|
| 100 |
+
n_cont_cont[i] = -p.w * n_val * G_n_r / pdf_n_r
|
| 101 |
+
|
| 102 |
+
with dr.resume_grad(when = not primal):
|
| 103 |
+
α_n = self.input.α.get_value(p_n)
|
| 104 |
+
n_cont_cont[i] *= dr.sqrt(dr.rcp( α * α_n)) if dr.hint(self.input.shape.measured_current, mode = 'scalar') else dr.sqrt(α_n / α)
|
| 105 |
+
|
| 106 |
+
if dr.isnan(n_cont_cont[i]) | ~illumination_mask:
|
| 107 |
+
n_cont_cont[i] = Float(0)
|
| 108 |
+
else:
|
| 109 |
+
# Here n_val is an ArrayXf.
|
| 110 |
+
dist_n, n_val, pdf_n_r, p_n = self.input.sampleNEE(bi, p.sampler.next_float32(), conf_numbers)
|
| 111 |
+
G_n_r = self.green.eval(dist_n, bi.r, σ_bar)
|
| 112 |
+
|
| 113 |
+
n_cont_cont_ = Float(0)
|
| 114 |
+
if ((pdf_n_r > 0) & (dist_n < bi.r) & (dist_n > 0)):
|
| 115 |
+
n_cont_cont_ = -p.w * G_n_r / pdf_n_r
|
| 116 |
+
|
| 117 |
+
with dr.resume_grad(when = not primal):
|
| 118 |
+
α_n = self.input.α.get_value(p_n)
|
| 119 |
+
n_cont_cont_ *= dr.sqrt(dr.rcp( α * α_n)) if dr.hint(self.input.shape.measured_current, mode = 'scalar') else dr.sqrt(α_n / α)
|
| 120 |
+
|
| 121 |
+
if dr.isnan(n_cont_cont_) | ~illumination_mask:
|
| 122 |
+
n_cont_cont_ = Float(0)
|
| 123 |
+
n_cont_cont = n_val * n_cont_cont_
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# Now, we get the all necessary delta distributions on the boundary (a.k.a. point current injections).
|
| 127 |
+
n_cont_delta =dr.zeros(ArrayXf, shape = L.shape)
|
| 128 |
+
|
| 129 |
+
if dr.hint(self.input.has_delta, mode = 'scalar'):
|
| 130 |
+
for i in range(num_conf):
|
| 131 |
+
conf_number = None if conf_numbers is None else conf_numbers[i]
|
| 132 |
+
#if dr.hint(illumination_mask, mode="evaluated"):
|
| 133 |
+
dist_n, n_val, pdf_n_r, sampled_n = self.input.get_point_neumann(bi, conf_number)
|
| 134 |
+
# We can have multiple relevant electrodes, add all the contribution.
|
| 135 |
+
for d, n, pdf_r, p_n in zip(dist_n, n_val, pdf_n_r, sampled_n):
|
| 136 |
+
n_cont_delta_iter = Float(0)
|
| 137 |
+
G_n_r = self.green.eval(d, bi.r, σ_bar)
|
| 138 |
+
with dr.resume_grad(when = not primal):
|
| 139 |
+
α_n = self.input.α.get_value(p_n)
|
| 140 |
+
if (pdf_r > 0) & (d <= bi.r):
|
| 141 |
+
n_cont_delta_iter = -p.w * n * G_n_r / pdf_r
|
| 142 |
+
# Here, we need to apply a correction term if the given neumann boundary is a current value.
|
| 143 |
+
n_cont_delta_iter *= dr.sqrt(dr.rcp(α * α_n)) if dr.hint(self.input.shape.measured_current, mode = 'scalar') else dr.sqrt(α_n / α)
|
| 144 |
+
n_cont_delta[i] += n_cont_delta_iter
|
| 145 |
+
|
| 146 |
+
if dr.isnan(n_cont_delta[i]) | ~illumination_mask:
|
| 147 |
+
n_cont_delta[i] = Float(0)
|
| 148 |
+
|
| 149 |
+
# Compute the total neumann contribution.
|
| 150 |
+
with dr.resume_grad(when = not primal):
|
| 151 |
+
n_cont = n_cont_cont + n_cont_delta
|
| 152 |
+
# There is a factor of 2 for smooth neumann boundaries if we are exactly on the boundary. (Check WoSt paper.)
|
| 153 |
+
if bi.on_boundary:
|
| 154 |
+
n_cont *= 2
|
| 155 |
+
n_cont = dr.select(active_conf, n_cont, 0)
|
| 156 |
+
|
| 157 |
+
L += n_cont if primal else -n_cont
|
| 158 |
+
|
| 159 |
+
# Sampling the recursive term.
|
| 160 |
+
# Now select between boundary or volume sampling (2nd paper, eqn 28)
|
| 161 |
+
sample_rec = Point2f(p.sampler.next_float32(), p.sampler.next_float32())
|
| 162 |
+
normG = self.green.eval_norm(bi.r, σ_bar)
|
| 163 |
+
prob_vol = σ_bar * normG
|
| 164 |
+
sample_vol = active & (sample_rec[0] < prob_vol)
|
| 165 |
+
sample_rec[0] = dr.select(sample_vol, sample_rec[0] / prob_vol, (sample_rec[0] - prob_vol) / (1-prob_vol))
|
| 166 |
+
# Sample direction
|
| 167 |
+
dir_next, _, _ = bi.sample_recursive(sample_rec[1])
|
| 168 |
+
# We will stamp the next sampled point in case it is sampled outside of the star.
|
| 169 |
+
ri_next = self.input.shape.ray_intersect(bi, dir_next)
|
| 170 |
+
# Radius sampling with the Green's function.
|
| 171 |
+
r_next = Float(bi.r)
|
| 172 |
+
if sample_vol:
|
| 173 |
+
r_next = self.green.sample(sample_rec[0], bi.r, σ_bar)[0]
|
| 174 |
+
|
| 175 |
+
# Stamping. Also we need to update the sample vol term for correct throughput update.
|
| 176 |
+
on_boundary_next = (ri_next.t < r_next)
|
| 177 |
+
sample_vol &= ~on_boundary_next
|
| 178 |
+
if on_boundary_next:
|
| 179 |
+
r_next = ri_next.t
|
| 180 |
+
|
| 181 |
+
# Next iteration points.
|
| 182 |
+
points_next = mi.Point2f(ri_next.origin + r_next * dir_next)
|
| 183 |
+
|
| 184 |
+
with dr.resume_grad(when=not primal):
|
| 185 |
+
α_next = self.input.α.get_value(points_next)
|
| 186 |
+
grad_α_next, laplacian_α_next = self.input.α.get_grad_laplacian(points_next)
|
| 187 |
+
σ_next = self.input.σ.get_value(points_next)
|
| 188 |
+
σ_new = self.σ_(σ_next, α_next, grad_α_next, laplacian_α_next)
|
| 189 |
+
w_ = dr.sqrt(α_next / α)
|
| 190 |
+
w_s = dr.select(sample_vol, (1.0 - σ_new / σ_bar), 1.0)
|
| 191 |
+
w_update = w_ * w_s
|
| 192 |
+
# Path replay gradient contribution.
|
| 193 |
+
prb_cont = dr.select(dr.isfinite(w_update), L * w_update / dr.detach(w_update), 0.0)
|
| 194 |
+
|
| 195 |
+
# Here, all the gradients from different contributions computed in single backward pass.
|
| 196 |
+
grad_cont = prb_cont + f_cont + n_cont
|
| 197 |
+
if dr.hint(mode == dr.ADMode.Backward, mode = 'scalar'):
|
| 198 |
+
dr.backward(dr.sum(grad_cont * dL))
|
| 199 |
+
elif dr.hint(mode == dr.ADMode.Forward, mode = 'scalar'):
|
| 200 |
+
dL += dr.forward_to(dr.sum(grad_cont))
|
| 201 |
+
|
| 202 |
+
active &= dr.isfinite(w_update)
|
| 203 |
+
|
| 204 |
+
# If we are not doing fd computation, then just use the original coefficient.
|
| 205 |
+
if dr.hint((not fd_forward), mode = 'scalar'):
|
| 206 |
+
if dr.hint(split == Split.Agressive, mode = 'scalar'):
|
| 207 |
+
p.w_split *= w_update
|
| 208 |
+
elif dr.hint(split == Split.Normal, mode = 'scalar'):
|
| 209 |
+
p.w_split *= w_s
|
| 210 |
+
else: # Otherwise use the non-deviated coefficients for throughput update.
|
| 211 |
+
α = self.input.α_split.get_value(p.points) # We did not get this before if f is zero!
|
| 212 |
+
α_next = self.input.α_split.get_value(points_next)
|
| 213 |
+
grad_α_next, laplacian_α_next = self.input.α_split.get_grad_laplacian(points_next)
|
| 214 |
+
σ_next = self.input.σ_split.get_value(points_next)
|
| 215 |
+
σ_new = self.σ_(σ_next, α_next, grad_α_next, laplacian_α_next)
|
| 216 |
+
w_ = dr.select(active, dr.sqrt(α_next / α), 1.0)
|
| 217 |
+
w_s = dr.select(sample_vol, (1.0 - σ_new / σ_bar), 1.0)
|
| 218 |
+
if dr.hint(split == Split.Agressive, mode = 'scalar'):
|
| 219 |
+
p.w_split *= (w_ * w_s)
|
| 220 |
+
elif dr.hint(split == Split.Normal, mode = 'scalar'):
|
| 221 |
+
p.w_split *= w_s
|
| 222 |
+
|
| 223 |
+
if dr.hint(max_length is not None, mode = 'scalar'):
|
| 224 |
+
if p.path_length > max_length:
|
| 225 |
+
p.w *= tput_kill
|
| 226 |
+
p.w_split *= tput_kill
|
| 227 |
+
|
| 228 |
+
# Update the points for the next iteration.
|
| 229 |
+
p.w *= w_update
|
| 230 |
+
p.points = points_next
|
| 231 |
+
p.path_length += 1
|
| 232 |
+
return p
|
data/PDE2D/__init__.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import drjit as dr
|
| 3 |
+
import mitsuba as mi
|
| 4 |
+
from enum import IntEnum
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
PATH = os.path.dirname((os.path.dirname(__file__)))
|
| 9 |
+
|
| 10 |
+
#from drjit.cuda.ad import (ArrayXu, ArrayXu64, ArrayXf, ArrayXf64, ArrayXb, Array4u64)
|
| 11 |
+
|
| 12 |
+
#double_precision = True
|
| 13 |
+
#source = dr.cuda.ad
|
| 14 |
+
|
| 15 |
+
#vars = ["ArrayXu", "ArrayXu64", "ArrayXf", "ArrayXf64", "ArrayXb", "Array4u64"]
|
| 16 |
+
|
| 17 |
+
#if double_precision:
|
| 18 |
+
# vars_precision = ["ArrayXu", "ArrayXu64", "ArrayXf64", "ArrayXf64", "ArrayXb", "Array4u64"]
|
| 19 |
+
#else:
|
| 20 |
+
# vars_precision = ["ArrayXu64", "ArrayXu64", "ArrayXf", "ArrayXf64", "ArrayXb", "Array4u64"]
|
| 21 |
+
|
| 22 |
+
#for name, name_precision in zip(vars, vars_precision):
|
| 23 |
+
# globals()[name] = getattr(source, name_precision)
|
| 24 |
+
ArrayXf = None
|
| 25 |
+
ArrayXu = None
|
| 26 |
+
if "double" in mi.variant():
|
| 27 |
+
ArrayXf = dr.cuda.ad.ArrayXf64 if "cuda" in mi.variant() else dr.llvm.ad.ArrayXf64
|
| 28 |
+
ArrayXu = dr.cuda.ad.ArrayXu64 if "cuda" in mi.variant() else dr.llvm.ad.ArrayXu64
|
| 29 |
+
else:
|
| 30 |
+
ArrayXf = dr.cuda.ad.ArrayXf if "cuda" in mi.variant() else dr.llvm.ad.ArrayXf
|
| 31 |
+
ArrayXu = dr.cuda.ad.ArrayXu if "cuda" in mi.variant() else dr.llvm.ad.ArrayXu
|
| 32 |
+
|
| 33 |
+
ArrayXu64 = dr.cuda.ad.ArrayXu64 if "cuda" in mi.variant() else dr.llvm.ad.ArrayXu64
|
| 34 |
+
ArrayXf64 = dr.cuda.ad.ArrayXf64 if "cuda" in mi.variant() else dr.llvm.ad.ArrayXf64
|
| 35 |
+
Array4u64 = dr.cuda.ad.Array4u64 if "cuda" in mi.variant() else dr.llvm.ad.Array4u64
|
| 36 |
+
ArrayXb = dr.cuda.ad.ArrayXb if "cuda" in mi.variant() else dr.llvm.ad.ArrayXb
|
| 37 |
+
|
| 38 |
+
class DIM(IntEnum):
|
| 39 |
+
Two = 0,
|
| 40 |
+
Three = 1
|
| 41 |
+
|
| 42 |
+
class GreenSampling(IntEnum):
|
| 43 |
+
Polynomial = 0,
|
| 44 |
+
Analytic = 1
|
| 45 |
+
|
| 46 |
+
class Split(IntEnum):
|
| 47 |
+
Naive = 0,
|
| 48 |
+
Normal = 1,
|
| 49 |
+
Agressive = 2
|
data/PDE2D/utils/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .helpers import *
|
| 2 |
+
from .sketch import *
|
| 3 |
+
from .imageUtils import *
|
| 4 |
+
from .optimization import *
|
| 5 |
+
from .sketch import *
|
| 6 |
+
from .common import *
|
| 7 |
+
from .optimizer import Optimizer, SGD, Adam
|
data/PDE2D/utils/animation.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from PDE2D import PATH
|
| 3 |
+
from PDE2D.utils.imageUtils import create_image_points, create_image_from_result
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
import matplotlib.gridspec as gridspec
|
| 6 |
+
import matplotlib.animation as animation
|
| 7 |
+
import os
|
| 8 |
+
'''
|
| 9 |
+
def create_animation(record, path, iternum, bbox, wos, max_range = None, wos_obj = None, resolution = [512, 512],
|
| 10 |
+
opt_param = "diffusion.texture.tensor", fileset = None, out_val = None,
|
| 11 |
+
optimize_electrode = True, primal_range = ):
|
| 12 |
+
|
| 13 |
+
name = "reconstruction" if max_range is None else "reconstruction-scaled"
|
| 14 |
+
if (wos_obj is None) and (fileset is None):
|
| 15 |
+
fig , ((ax1, ax2), (ax3, ax4)) = plt.subplots(1,2, figsize = (10, 10))
|
| 16 |
+
else:
|
| 17 |
+
fig = plt.figure(figsize=(8, 6))
|
| 18 |
+
g = gridspec.GridSpec(16, 20, figure = fig, wspace = 0.5, hspace=0.1)
|
| 19 |
+
ax0 = fig.add_subplot(g[0:9,0:9])
|
| 20 |
+
ax1 = fig.add_subplot(g[0:9,10:19])
|
| 21 |
+
ax2 = fig.add_subplot(g[10:,:19])
|
| 22 |
+
|
| 23 |
+
coeff_name = opt_param.split(".")[0]
|
| 24 |
+
|
| 25 |
+
coeff = wos.input.get_coefficient(coeff_name)
|
| 26 |
+
|
| 27 |
+
if fileset is not None:
|
| 28 |
+
image_file = os.path.join(PATH ,f"eit-data/target_photos/fantom_{fileset}.jpg")
|
| 29 |
+
image = plt.imread(image_file)
|
| 30 |
+
ax0.imshow(image)
|
| 31 |
+
ax0.set_axis_off()
|
| 32 |
+
ax0.set_title("Objective")
|
| 33 |
+
|
| 34 |
+
elif wos_obj is not None:
|
| 35 |
+
coeff_obj = wos_obj.input.get_coefficient(coeff_name)
|
| 36 |
+
|
| 37 |
+
points = create_image_points(bbox, resolution, spp=1, centered = True)
|
| 38 |
+
vals = coeff_obj.get_value(points)
|
| 39 |
+
if out_val is not None:
|
| 40 |
+
mask = wos_obj.input.shape.inside_closed_surface_mask(points)
|
| 41 |
+
vals = dr.select(mask, vals, out_val)
|
| 42 |
+
obj_image, _ = create_image_from_result(vals, resolution)
|
| 43 |
+
if max_range is None:
|
| 44 |
+
plot_image(obj_image[0], ax0)
|
| 45 |
+
else:
|
| 46 |
+
plot_image(obj_image[0], ax0, input_range = max_range)
|
| 47 |
+
ax0.set_title("Objective")
|
| 48 |
+
wos_obj.input.shape.sketch(ax0, bbox, resolution, sketch_center = True)
|
| 49 |
+
|
| 50 |
+
if max_range is None:
|
| 51 |
+
maxval = -np.inf
|
| 52 |
+
minval = np.inf
|
| 53 |
+
for i in range(iternum):
|
| 54 |
+
tensor = TensorXf(record[f"{opt_param}-{i}"]).numpy()
|
| 55 |
+
maxval = max(maxval, np.max(tensor))
|
| 56 |
+
minval = min(minval, np.min(tensor))
|
| 57 |
+
max_range = [minval, maxval]
|
| 58 |
+
coeff.tensor = TensorXf(record[f"{opt_param}-0"])
|
| 59 |
+
coeff.update_texture()
|
| 60 |
+
|
| 61 |
+
dirichlet_str = "dirichletpoints-0"
|
| 62 |
+
dirichlet_points = None
|
| 63 |
+
if dirichlet_str in record:
|
| 64 |
+
dirichlet_points_ = record[f"dirichletpoints-0"]
|
| 65 |
+
if dirichlet_points_.shape[0] > 0:
|
| 66 |
+
dirichlet_points = Point2f(dirichlet_points_.T)
|
| 67 |
+
dirichlet_points = point2sketch(dirichlet_points, bbox, resolution).numpy()
|
| 68 |
+
|
| 69 |
+
im, s, line = start_animation(ax1, ax2, record, bbox, wos, dirichlet_points, coeff, resolution, max_range, out_val = out_val)
|
| 70 |
+
update = lambda iteration : update_animation(wos, iteration, record, coeff, resolution, im, s, line, bbox, opt_param, out_val = out_val)
|
| 71 |
+
|
| 72 |
+
ani = animation.FuncAnimation(fig=fig, func=update, frames=iternum+1, interval=30)
|
| 73 |
+
writervideo = animation.FFMpegWriter(fps=25)
|
| 74 |
+
ani.save(filename=f"{path}/{name}.gif", writer="pillow")
|
| 75 |
+
ani.save(f"{path}/{name}.mp4", writer=writervideo)
|
| 76 |
+
|
| 77 |
+
def start_animation(ax1, ax2, record, bbox, wos, in_boundary_points, coeff, resolution, max_range, out_val : float = None):
|
| 78 |
+
points = create_image_points(bbox, resolution, spp = 4, centered = False)
|
| 79 |
+
vals = coeff.get_value(points)
|
| 80 |
+
if out_val is not None:
|
| 81 |
+
mask = wos.input.shape.inside_closed_surface_mask(points)
|
| 82 |
+
vals = dr.select(mask, vals, out_val)
|
| 83 |
+
image, _ = create_image_from_result(vals, resolution)
|
| 84 |
+
im = plot_image(image[0], ax1, input_range = max_range)
|
| 85 |
+
wos.input.shape.sketch(ax1, bbox, resolution, sketch_center = True, sketch_in_boundaries = False)
|
| 86 |
+
s = None
|
| 87 |
+
if in_boundary_points is not None:
|
| 88 |
+
s = ax1.scatter(in_boundary_points[0], in_boundary_points[1], s = 5, color = "red")
|
| 89 |
+
|
| 90 |
+
ax1.set_title("Reconstruction")
|
| 91 |
+
|
| 92 |
+
loss = record["loss"].sum(axis = 1).squeeze()
|
| 93 |
+
loss_reg = record["loss-reg"]
|
| 94 |
+
iters = np.arange(0, len(loss))
|
| 95 |
+
ax2.plot(iters, loss + loss_reg, color = "grey", ls = "-.")
|
| 96 |
+
line = ax2.plot(iters[0], loss[0], color = "red")[0]
|
| 97 |
+
ax2.yaxis.tick_right()
|
| 98 |
+
ax2.set_yscale("log")
|
| 99 |
+
ax2.set_yscale("log")
|
| 100 |
+
ax2.grid()
|
| 101 |
+
ax2.set_ylabel("Loss")
|
| 102 |
+
return im, s, line
|
| 103 |
+
|
| 104 |
+
def update_animation(wos, iteration, record, coeff, resolution, im, s, line, bbox, opt_param, out_val : float = None):
|
| 105 |
+
coeff.tensor = TensorXf(record[f"{opt_param}-{iteration}"])
|
| 106 |
+
coeff.update_texture()
|
| 107 |
+
points = create_image_points(bbox, resolution, spp = 4, centered = False)
|
| 108 |
+
vals = coeff.get_value(points)
|
| 109 |
+
if out_val is not None:
|
| 110 |
+
mask = wos.input.shape.inside_closed_surface_mask(points)
|
| 111 |
+
vals = dr.select(mask, vals, out_val)
|
| 112 |
+
image, _ = create_image_from_result(vals, resolution)
|
| 113 |
+
im.set_data(image[0])
|
| 114 |
+
if s is not None:
|
| 115 |
+
dirichlet_points = record[f"dirichletpoints-{iteration}"]
|
| 116 |
+
if dirichlet_points.shape[0] > 0:
|
| 117 |
+
dirichlet_points = Point2f(dirichlet_points.T)
|
| 118 |
+
dirichlet_points = point2sketch(dirichlet_points, bbox, resolution).numpy()
|
| 119 |
+
s.set_offsets(dirichlet_points.T)
|
| 120 |
+
|
| 121 |
+
loss = record["loss"].sum(axis = 1)[:iteration].squeeze()
|
| 122 |
+
loss_reg = record["loss-reg"][:iteration]
|
| 123 |
+
iters = np.arange(0, iteration)
|
| 124 |
+
line.set_xdata(iters)
|
| 125 |
+
line.set_ydata(loss + loss_reg)
|
| 126 |
+
|
| 127 |
+
'''
|
data/PDE2D/utils/common.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from os.path import join
|
| 3 |
+
import subprocess
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
__SCRIPT_DIR = os.path.realpath(os.path.dirname(__file__))
|
| 7 |
+
sys.path.insert(0, join(__SCRIPT_DIR, '../../mitsuba3/build/python/'))
|
| 8 |
+
FIGURE_DIR = os.path.realpath(join(__SCRIPT_DIR, '..', 'outputs', 'figures'))
|
| 9 |
+
SCENE_DIR = os.path.realpath(join(__SCRIPT_DIR, '..', 'scenes'))
|
| 10 |
+
PAPER_FIG_OUTPUT_DIR = os.path.realpath(join(__SCRIPT_DIR, '..', '..', 'phd-thesis', 'chapters'))
|
| 11 |
+
del __SCRIPT_DIR
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from string import ascii_lowercase
|
| 15 |
+
|
| 16 |
+
import drjit as dr
|
| 17 |
+
|
| 18 |
+
import matplotlib
|
| 19 |
+
|
| 20 |
+
# Override any style changes by VSCode
|
| 21 |
+
if hasattr(matplotlib, "style"):
|
| 22 |
+
matplotlib.style.use('default')
|
| 23 |
+
|
| 24 |
+
# Use double the true size for figures, as this leads to nicer, thinner plot lines
|
| 25 |
+
COLUMN_WIDTH = 3.37704722222
|
| 26 |
+
TEXT_WIDTH = 7.08743055556
|
| 27 |
+
DEFAULT_FONTSIZE = 8 # Font size used by captions in ACM format
|
| 28 |
+
DEFAULT_FONTSIZE_SMALL = 6.5
|
| 29 |
+
|
| 30 |
+
MPL_STYLE = {
|
| 31 |
+
"text.usetex": True,
|
| 32 |
+
"text.color": 'black',
|
| 33 |
+
"font.size": DEFAULT_FONTSIZE,
|
| 34 |
+
"axes.titlesize": DEFAULT_FONTSIZE,
|
| 35 |
+
"axes.labelsize": DEFAULT_FONTSIZE_SMALL,
|
| 36 |
+
"xtick.labelsize": DEFAULT_FONTSIZE_SMALL,
|
| 37 |
+
"ytick.labelsize": DEFAULT_FONTSIZE_SMALL,
|
| 38 |
+
"legend.fontsize": DEFAULT_FONTSIZE_SMALL,
|
| 39 |
+
"figure.titlesize": DEFAULT_FONTSIZE,
|
| 40 |
+
"text.latex.preamble": r"""\usepackage{libertine}
|
| 41 |
+
\usepackage[libertine]{newtxmath}
|
| 42 |
+
\usepackage{amsmath}
|
| 43 |
+
\usepackage{amsfonts}
|
| 44 |
+
\usepackage{bm}
|
| 45 |
+
\usepackage{bbm}""",
|
| 46 |
+
"pdf.fonttype": 42,
|
| 47 |
+
"ps.fonttype": 42,
|
| 48 |
+
'axes.edgecolor':'black',
|
| 49 |
+
'axes.linewidth': 0.4,
|
| 50 |
+
'xtick.major.size': 0.5,
|
| 51 |
+
'xtick.major.width': 0.5,
|
| 52 |
+
'xtick.minor.size': 0.25,
|
| 53 |
+
'xtick.minor.width': 0.5,
|
| 54 |
+
|
| 55 |
+
'ytick.major.size': 0.5,
|
| 56 |
+
'ytick.major.width': 0.5,
|
| 57 |
+
'ytick.minor.size': 0.25,
|
| 58 |
+
'ytick.minor.width': 0.5,
|
| 59 |
+
|
| 60 |
+
'lines.linewidth': 0.75,
|
| 61 |
+
'patch.linewidth': 0.5,
|
| 62 |
+
|
| 63 |
+
'grid.linewidth': 0.5,
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
# MPL_STYLE['savefig.facecolor'] = "0.8"
|
| 67 |
+
|
| 68 |
+
matplotlib.rcParams.update(MPL_STYLE)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
import matplotlib.pyplot as plt
|
| 72 |
+
import matplotlib.patheffects as path_effects
|
| 73 |
+
|
| 74 |
+
#import seaborn as sns
|
| 75 |
+
#sns.set()
|
| 76 |
+
matplotlib.rcParams.update(MPL_STYLE)
|
| 77 |
+
|
| 78 |
+
"""
|
| 79 |
+
def read_img(fn, exposure=0, tonemap=True, background_color=None,
|
| 80 |
+
handle_inexistant_file=False):
|
| 81 |
+
if handle_inexistant_file and not os.path.isfile(fn):
|
| 82 |
+
return np.ones((256, 256, 3)) * 0.3
|
| 83 |
+
bmp = mi.Bitmap(fn)
|
| 84 |
+
if tonemap:
|
| 85 |
+
if background_color is not None:
|
| 86 |
+
img = np.array(bmp.convert(mi.Bitmap.PixelFormat.RGBA, mi.Struct.Type.Float32, False))
|
| 87 |
+
background_color = np.array(background_color).ravel()[None, None, :]
|
| 88 |
+
# img = img[:, :, :3] * img[..., -1][..., None] + (1.0 - img[..., -1][..., None]) * background_color
|
| 89 |
+
img = img[:, :, :3] + (1.0 - img[..., -1][..., None]) * background_color
|
| 90 |
+
else:
|
| 91 |
+
img = np.array(bmp.convert(mi.Bitmap.PixelFormat.RGB, mi.Struct.Type.Float32, False))
|
| 92 |
+
img = img * 2 ** exposure
|
| 93 |
+
|
| 94 |
+
return np.clip(np.array(mi.Bitmap(img).convert(mi.Bitmap.PixelFormat.RGB, mi.Struct.Type.Float32, True)), 0, 1)
|
| 95 |
+
else:
|
| 96 |
+
return np.array(bmp)
|
| 97 |
+
|
| 98 |
+
def tonemap(img):
|
| 99 |
+
return np.clip(np.array(mi.Bitmap(img).convert(mi.Bitmap.PixelFormat.RGB, mi.Struct.Type.Float32, True)), 0, 1)
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def save_fig(fig_name, fig_sub_dir, dpi=300, pad_inches=0.005, bbox_inches='tight', compress=True):
|
| 103 |
+
output_dir = os.path.join(PAPER_FIG_OUTPUT_DIR, fig_sub_dir, fig_name)
|
| 104 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 105 |
+
fn = join(output_dir, fig_name + '.pdf')
|
| 106 |
+
orig_fn = fn
|
| 107 |
+
if compress:
|
| 108 |
+
fn = fn.replace('.pdf', '_uc.pdf')
|
| 109 |
+
plt.savefig(fn, format='pdf', dpi=dpi, bbox_inches=bbox_inches, pad_inches=pad_inches)
|
| 110 |
+
# plt.savefig(fn, format='pdf', dpi=dpi)
|
| 111 |
+
|
| 112 |
+
if compress:
|
| 113 |
+
gs = f"gs -o {orig_fn} -dQUIET -f -dNOPAUSE -dBATCH "
|
| 114 |
+
gs += "-sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -dCompatibilityLevel=1.6 "
|
| 115 |
+
gs += f"-dDownsampleColorImages=false -DownsampleGrayImages=false {fn}"
|
| 116 |
+
subprocess.call(gs, shell=True)
|
| 117 |
+
return orig_fn
|
| 118 |
+
|
| 119 |
+
def disable_ticks(ax):
|
| 120 |
+
ax.axes.get_xaxis().set_ticklabels([])
|
| 121 |
+
ax.axes.get_yaxis().set_ticklabels([])
|
| 122 |
+
ax.axes.get_xaxis().set_ticks([])
|
| 123 |
+
ax.axes.get_yaxis().set_ticks([])
|
| 124 |
+
|
| 125 |
+
def disable_border(ax):
|
| 126 |
+
ax.spines['top'].set_visible(False)
|
| 127 |
+
ax.spines['right'].set_visible(False)
|
| 128 |
+
ax.spines['bottom'].set_visible(False)
|
| 129 |
+
ax.spines['left'].set_visible(False)
|
| 130 |
+
|
| 131 |
+
def apply_color_map(data, cmap='coolwarm', vmin=None, vmax=None):
|
| 132 |
+
from matplotlib import cm
|
| 133 |
+
|
| 134 |
+
data = np.array(data)
|
| 135 |
+
if vmin is None:
|
| 136 |
+
vmin = np.min(data)
|
| 137 |
+
if vmax is None:
|
| 138 |
+
vmax = np.max(data)
|
| 139 |
+
return getattr(cm, cmap)(plt.Normalize(vmin, vmax)(data))[..., :3]
|
| 140 |
+
|
| 141 |
+
def time_to_string(duration):
|
| 142 |
+
duration = round(duration)
|
| 143 |
+
m, s = divmod(duration, 60)
|
| 144 |
+
h, m = divmod(m, 60)
|
| 145 |
+
d, h = divmod(h, 24)
|
| 146 |
+
result = ''
|
| 147 |
+
if d > 0:
|
| 148 |
+
result += f'{d}d '
|
| 149 |
+
if h > 0:
|
| 150 |
+
result += f'{h}h '
|
| 151 |
+
if m > 0:
|
| 152 |
+
result += f'{m}m '
|
| 153 |
+
result += f'{s}s'
|
| 154 |
+
return result
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def set_aspect(ax, aspect):
|
| 158 |
+
x_left, x_right = ax.get_xlim()
|
| 159 |
+
y_low, y_high = ax.get_ylim()
|
| 160 |
+
ax.set_aspect(abs((x_right - x_left) / (y_low - y_high)) * aspect)
|
| 161 |
+
|
| 162 |
+
def merge_pdfs(fn1, fn2, out_fn):
|
| 163 |
+
"""Merges two PDF files"""
|
| 164 |
+
from PyPDF2 import PdfReader, PdfWriter
|
| 165 |
+
reader_base = PdfReader(fn1)
|
| 166 |
+
page_base = reader_base.pages[0]
|
| 167 |
+
reader = PdfReader(fn2)
|
| 168 |
+
page_box = reader.pages[0]
|
| 169 |
+
page_base.merge_page(page_box)
|
| 170 |
+
writer = PdfWriter()
|
| 171 |
+
writer.add_page(page_base)
|
| 172 |
+
with open(out_fn, 'wb') as fp:
|
| 173 |
+
writer.write(fp)
|
data/PDE2D/utils/helpers.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import drjit as dr
|
| 3 |
+
import mitsuba as mi
|
| 4 |
+
from math import sqrt
|
| 5 |
+
from mitsuba import Point2f, Float, UInt32
|
| 6 |
+
from collections.abc import Sequence
|
| 7 |
+
|
| 8 |
+
#def deviate_points(points, max = 0.1, repeat= 5, seed = 37):
|
| 9 |
+
# sampler = mi.load_dict({'type': 'stratified'})
|
| 10 |
+
# sampler.seed(seed, dr.width(points) * repeat)
|
| 11 |
+
# return dr.repeat(points, repeat) + max * (sampler.next_2d() - 1/2)
|
| 12 |
+
|
| 13 |
+
def get_position_bbox(points : Float, bbox):
|
| 14 |
+
"Get the new positions of the points normalized for the bbox."
|
| 15 |
+
x = (points[0] - bbox[0][0]) / (bbox[1][0] - bbox[0][0])
|
| 16 |
+
y = 1.0 - (points[1] - bbox[0][1]) / (bbox[1][1] - bbox[0][1])
|
| 17 |
+
return x, y
|
| 18 |
+
|
| 19 |
+
def to_world_direction(direction : Point2f, normal : Point2f):
|
| 20 |
+
return direction[1] * normal + direction[0] * Point2f(normal[1], -normal[0])
|
| 21 |
+
|
| 22 |
+
def to_normal_direction(direction : Point2f, normal: Point2f):
|
| 23 |
+
normal_comp = dr.dot(direction, normal)
|
| 24 |
+
other_comp = dr.dot(Point2f(normal[1], normal[0]), direction)
|
| 25 |
+
return Point2f(other_comp, normal_comp)
|
| 26 |
+
|
| 27 |
+
@dr.syntax
|
| 28 |
+
def correct_angle(angle : Float):
|
| 29 |
+
if angle<0:
|
| 30 |
+
angle += 2 * dr.pi
|
| 31 |
+
elif angle >= 2 * dr.pi:
|
| 32 |
+
angle -= 2 * dr.pi
|
| 33 |
+
return angle
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
def upsample(tensor = TensorXf, upsample = [2,2]):
|
| 37 |
+
n1, n2 = tensor.shape
|
| 38 |
+
array = tensor.array
|
| 39 |
+
array_new = dr.zeros(Float, n1 * n2 * upsample[0] * upsample[1])
|
| 40 |
+
rows = dr.arange(UInt, n1 * upsample[0])
|
| 41 |
+
cols = dr.arange(UInt, n2 * upsample[1])
|
| 42 |
+
indices = dr.meshgrid(rows, cols)
|
| 43 |
+
indices_low = Array2i(indices[0] // upsample[0], indices[1] // upsample[1])
|
| 44 |
+
ind = indices[0] * n2 * upsample[1] + indices[1]
|
| 45 |
+
ind_low = indices_low[0] * n2 + indices_low[1]
|
| 46 |
+
low_vals = dr.gather(Float, array, ind_low)
|
| 47 |
+
dr.scatter(array_new, low_vals, ind)
|
| 48 |
+
tensor_new = TensorXf(array_new)
|
| 49 |
+
tensor_new = dr.reshape(TensorXf, tensor_new, shape = [n1 * upsample[0], n2 * upsample[1]])
|
| 50 |
+
return tensor_new
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
def tea(v0: UInt32, v1: UInt32, rounds=4):
|
| 54 |
+
sum = UInt32(0)
|
| 55 |
+
for i in range(rounds):
|
| 56 |
+
sum += 0x9e3779b9
|
| 57 |
+
v0 += ((v1 << 4) + 0xa341316c) ^ (v1 + sum) ^ ((v1>>5) + 0xc8013ea4)
|
| 58 |
+
v1 += ((v0 << 4) + 0xad90777d) ^ (v0 + sum) ^ ((v0>>5) + 0x7e95761e)
|
| 59 |
+
return v0, v1
|
| 60 |
+
|
| 61 |
+
@dr.syntax
|
| 62 |
+
def k_means(points : Point2f, initial_means : Point2f, num_iter = 2):
|
| 63 |
+
# Set initial vals.
|
| 64 |
+
means = Point2f(initial_means)
|
| 65 |
+
npoints = dr.width(points)
|
| 66 |
+
nmeans = dr.width(means)
|
| 67 |
+
groups = dr.zeros(UInt32, npoints)
|
| 68 |
+
dist = dr.full(Float, dr.inf, npoints)
|
| 69 |
+
# Start K-means.
|
| 70 |
+
for i in range(num_iter):
|
| 71 |
+
# Assign to the groups.
|
| 72 |
+
for j in range(nmeans):
|
| 73 |
+
mean = dr.gather(Point2f, means, j)
|
| 74 |
+
dist_iter = dr.squared_norm(points - mean)
|
| 75 |
+
if dist_iter < dist:
|
| 76 |
+
groups = UInt32(j)
|
| 77 |
+
dist = dist_iter
|
| 78 |
+
# Recompute the means.
|
| 79 |
+
next_means = dr.zeros(Point2f, nmeans)
|
| 80 |
+
counter_sum = dr.zeros(Float, nmeans)
|
| 81 |
+
dr.scatter_add(next_means, points, groups)
|
| 82 |
+
dr.scatter_add(counter_sum, Float(1), groups)
|
| 83 |
+
means = next_means / counter_sum
|
| 84 |
+
return means, groups
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def upsample(t, shape=None, scale_factor=None, align_corners=False):
|
| 88 |
+
'''
|
| 89 |
+
upsample(source, shape=None, scale_factor=None, align_corners=False)
|
| 90 |
+
Up-sample the input tensor or texture according to the provided shape.
|
| 91 |
+
|
| 92 |
+
Alternatively to specifying the target shape, a scale factor can be
|
| 93 |
+
provided.
|
| 94 |
+
|
| 95 |
+
The behavior of this function depends on the type of ``source``:
|
| 96 |
+
|
| 97 |
+
1. When ``source`` is a Dr.Jit tensor, nearest neighbor up-sampling will use
|
| 98 |
+
hence the target ``shape`` values must be multiples of the source shape
|
| 99 |
+
values. When `scale_factor` is used, its values must be integers.
|
| 100 |
+
|
| 101 |
+
2. When ``source`` is a Dr.Jit texture type, the up-sampling will be
|
| 102 |
+
performed according to the filter mode set on the input texture. Target
|
| 103 |
+
``shape`` values are not required to be multiples of the source shape
|
| 104 |
+
values. When `scale_factor` is used, its values must be integers.
|
| 105 |
+
|
| 106 |
+
Args:
|
| 107 |
+
source (object): A Dr.Jit tensor or texture type.
|
| 108 |
+
|
| 109 |
+
shape (list): The target shape (optional)
|
| 110 |
+
|
| 111 |
+
scale_factor (list): The scale factor to apply to the current shape
|
| 112 |
+
(optional)
|
| 113 |
+
|
| 114 |
+
align_corners (bool): Defines whether or not the corner pixels of the
|
| 115 |
+
input and output should be aligned. This allows the values at the
|
| 116 |
+
corners to be preserved. This flag is only relevant when ``source`` is
|
| 117 |
+
a Dr.Jit texture type performing linear interpolation. The default is
|
| 118 |
+
`False`.
|
| 119 |
+
|
| 120 |
+
Returns:
|
| 121 |
+
object: the up-sampled tensor or texture object. The type of the output
|
| 122 |
+
will be the same as the type of the source.
|
| 123 |
+
'''
|
| 124 |
+
if not getattr(t, 'IsTexture', False) and not dr.is_tensor_v(t):
|
| 125 |
+
raise TypeError("upsample(): unsupported input type, expected Dr.Jit "
|
| 126 |
+
"tensor or texture type!")
|
| 127 |
+
|
| 128 |
+
if shape is not None and scale_factor is not None:
|
| 129 |
+
raise TypeError("upsample(): shape and scale_factor arguments cannot "
|
| 130 |
+
"be defined at the same time!")
|
| 131 |
+
|
| 132 |
+
if shape is not None:
|
| 133 |
+
if not isinstance(shape, Sequence):
|
| 134 |
+
raise TypeError("upsample(): unsupported shape type, expected a list!")
|
| 135 |
+
|
| 136 |
+
if len(shape) > len(t.shape):
|
| 137 |
+
raise TypeError("upsample(): invalid shape size!")
|
| 138 |
+
|
| 139 |
+
shape = list(shape) + list(t.shape[len(shape):])
|
| 140 |
+
|
| 141 |
+
scale_factor = []
|
| 142 |
+
for i, s in enumerate(shape):
|
| 143 |
+
if type(s) is not int:
|
| 144 |
+
raise TypeError("upsample(): target shape must contain integer values!")
|
| 145 |
+
|
| 146 |
+
if s < t.shape[i]:
|
| 147 |
+
raise TypeError("upsample(): target shape values must be larger "
|
| 148 |
+
"or equal to input shape! (%i vs %i)" % (s, t.shape[i]))
|
| 149 |
+
|
| 150 |
+
if dr.is_tensor_v(t):
|
| 151 |
+
factor = s / float(t.shape[i])
|
| 152 |
+
if factor != int(factor):
|
| 153 |
+
raise TypeError("upsample(): target shape must be multiples of "
|
| 154 |
+
"the input shape! (%i vs %i)" % (s, t.shape[i]))
|
| 155 |
+
else:
|
| 156 |
+
if not isinstance(scale_factor, Sequence):
|
| 157 |
+
raise TypeError("upsample(): unsupported scale_factor type, expected a list!")
|
| 158 |
+
|
| 159 |
+
if len(scale_factor) > len(t.shape):
|
| 160 |
+
raise TypeError("upsample(): invalid scale_factor size!")
|
| 161 |
+
|
| 162 |
+
scale_factor = list(scale_factor)
|
| 163 |
+
for i in range(len(t.shape) - len(scale_factor)):
|
| 164 |
+
scale_factor.append(1)
|
| 165 |
+
|
| 166 |
+
shape = []
|
| 167 |
+
for i, factor in enumerate(scale_factor):
|
| 168 |
+
if type(factor) is not int:
|
| 169 |
+
raise TypeError("upsample(): scale_factor must contain integer values!")
|
| 170 |
+
|
| 171 |
+
if factor < 1:
|
| 172 |
+
raise TypeError("upsample(): scale_factor values must be greater "
|
| 173 |
+
"than 0!")
|
| 174 |
+
|
| 175 |
+
shape.append(factor * t.shape[i])
|
| 176 |
+
|
| 177 |
+
if getattr(t, 'IsTexture', False):
|
| 178 |
+
value_type = type(t.value())
|
| 179 |
+
dim = len(t.shape) - 1
|
| 180 |
+
|
| 181 |
+
if t.shape[dim] != shape[dim]:
|
| 182 |
+
raise TypeError("upsample(): channel counts doesn't match input texture!")
|
| 183 |
+
|
| 184 |
+
# Create the query coordinates
|
| 185 |
+
coords = list(dr.meshgrid(*[
|
| 186 |
+
dr.linspace(value_type, 0.0, 1.0, shape[i], endpoint=align_corners)
|
| 187 |
+
for i in range(dim)
|
| 188 |
+
],
|
| 189 |
+
indexing='ij'
|
| 190 |
+
))
|
| 191 |
+
|
| 192 |
+
# Offset coordinates by half a voxel to hit the center of the new voxels
|
| 193 |
+
if align_corners:
|
| 194 |
+
for i in range(dim):
|
| 195 |
+
coords[i] *= (1 - 1 / t.shape[i])
|
| 196 |
+
coords[i] += 0.5 / t.shape[i]
|
| 197 |
+
else:
|
| 198 |
+
for i in range(dim):
|
| 199 |
+
coords[i] += 0.5 / shape[i]
|
| 200 |
+
|
| 201 |
+
# Reverse coordinates order according to dr.Texture convention
|
| 202 |
+
coords.reverse()
|
| 203 |
+
|
| 204 |
+
# Evaluate the texture at all voxel coordinates with interpolation
|
| 205 |
+
values = t.eval(coords)
|
| 206 |
+
|
| 207 |
+
# Concatenate output values to a flatten buffer
|
| 208 |
+
channels = len(values)
|
| 209 |
+
width = dr.width(values[0])
|
| 210 |
+
index = dr.arange(dr.uint32_array_t(value_type), width)
|
| 211 |
+
data = dr.zeros(value_type, width * channels)
|
| 212 |
+
for c in range(channels):
|
| 213 |
+
dr.scatter(data, values[c], channels * index + c)
|
| 214 |
+
|
| 215 |
+
# Create the up-sampled texture
|
| 216 |
+
texture = type(t)(shape[:-1], channels,
|
| 217 |
+
use_accel=t.use_accel(),
|
| 218 |
+
filter_mode=t.filter_mode(),
|
| 219 |
+
wrap_mode=t.wrap_mode())
|
| 220 |
+
texture.set_value(data)
|
| 221 |
+
|
| 222 |
+
return texture
|
| 223 |
+
else:
|
| 224 |
+
dim = len(shape)
|
| 225 |
+
size = dr.prod(shape[:dim])
|
| 226 |
+
base = dr.arange(dr.uint32_array_t(type(t.array)), size)
|
| 227 |
+
|
| 228 |
+
index = 0
|
| 229 |
+
stride = 1
|
| 230 |
+
for i in reversed(range(dim)):
|
| 231 |
+
ratio = shape[i] // t.shape[i]
|
| 232 |
+
index += (base // ratio % t.shape[i]) * stride
|
| 233 |
+
base //= shape[i]
|
| 234 |
+
stride *= t.shape[i]
|
| 235 |
+
|
| 236 |
+
return type(t)(dr.gather(type(t.array), t.array, index), tuple(shape))
|
| 237 |
+
|
data/PDE2D/utils/imageUtils.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import drjit as dr
|
| 3 |
+
import mitsuba as mi
|
| 4 |
+
from mitsuba import PCG32, Float, Point2f, TensorXf
|
| 5 |
+
from PDE2D import ArrayXu, ArrayXf
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
def create_image_points(bbox : list, resolution : list[int], spp : int, seed : int = 64, centered = False) -> Point2f:
|
| 9 |
+
# Generate the first points
|
| 10 |
+
|
| 11 |
+
x, y = dr.meshgrid(dr.arange(Float, resolution[1]),
|
| 12 |
+
dr.arange(Float, resolution[0]), indexing='xy')
|
| 13 |
+
x = dr.repeat(x, spp)
|
| 14 |
+
y = dr.repeat(y, spp)
|
| 15 |
+
if not centered:
|
| 16 |
+
npoints = resolution[0] * resolution[1] * spp
|
| 17 |
+
np.random.seed(seed)
|
| 18 |
+
init_state = np.random.randint(sys.maxsize, size = npoints)
|
| 19 |
+
init_seq = np.random.randint(sys.maxsize, size = npoints)
|
| 20 |
+
sampler = PCG32(npoints, initstate = init_state, initseq = init_seq)
|
| 21 |
+
film_points = Point2f(x,y) + Point2f(sampler.next_float32(), sampler.next_float32())
|
| 22 |
+
else:
|
| 23 |
+
film_points = Point2f(x,y) + Point2f(0.5, 0.5)
|
| 24 |
+
# The bounding box is defined as (bottom-left,up-right)
|
| 25 |
+
points = (Point2f(bbox[0][0], bbox[1][1]) +
|
| 26 |
+
film_points / Point2f(resolution[1], resolution[0]) *
|
| 27 |
+
(Point2f(bbox[1][0], bbox[0][1]) - Point2f(bbox[0][0], bbox[1][1])))
|
| 28 |
+
return points
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def create_image_from_result(result, resolution = [256, 256], compute_std = False):
|
| 32 |
+
if isinstance(result, Float):
|
| 33 |
+
num_conf = 1
|
| 34 |
+
else:
|
| 35 |
+
if result.ndim == 1:
|
| 36 |
+
num_conf = 1
|
| 37 |
+
else:
|
| 38 |
+
num_conf = result.shape[0]
|
| 39 |
+
# Splat to film
|
| 40 |
+
spp = int(dr.width(result) / (resolution[0] * resolution[1]))
|
| 41 |
+
#active_lanes = dr.select(result != 0, 1, 0)
|
| 42 |
+
#active_sum = dr.block_sum(active_lanes, spp)
|
| 43 |
+
result_sum = dr.block_sum(result, spp) / spp
|
| 44 |
+
#image_res = TensorXf(dr.select(active_sum > 0, result_sum / active_sum, 0))
|
| 45 |
+
image_res = TensorXf(result_sum)
|
| 46 |
+
|
| 47 |
+
shape = [num_conf, resolution[0], resolution[1]]
|
| 48 |
+
tensor = dr.reshape(TensorXf, value = image_res, shape = shape)
|
| 49 |
+
|
| 50 |
+
if not compute_std:
|
| 51 |
+
return tensor.numpy(), tensor
|
| 52 |
+
|
| 53 |
+
else:
|
| 54 |
+
variance = TensorXf(dr.block_sum(dr.square(result), spp) / spp)
|
| 55 |
+
variance = dr.reshape(TensorXf, value = variance, shape = shape) - dr.square(tensor)
|
| 56 |
+
variance /= spp
|
| 57 |
+
return tensor.numpy(), tensor, np.abs(variance.numpy()), variance
|
| 58 |
+
|
| 59 |
+
def create_circle_points(origin : list = [0,0], radius : float = 1.0, resolution = 1024,
|
| 60 |
+
spp = 256, seed : int = 14, centered = False, discrete_points = False, shift : float = 0):
|
| 61 |
+
if not discrete_points:
|
| 62 |
+
npoints = spp * resolution
|
| 63 |
+
np.random.seed(seed)
|
| 64 |
+
init_state = np.random.randint(sys.maxsize, size = npoints)
|
| 65 |
+
init_seq = np.random.randint(sys.maxsize, size = npoints)
|
| 66 |
+
sampler = PCG32(npoints, initstate = init_state, initseq = init_seq)
|
| 67 |
+
film_points = dr.arange(Float, resolution)
|
| 68 |
+
film_points = dr.repeat(film_points, spp) + sampler.next_float32()
|
| 69 |
+
film_points -= 1/2 if centered else 0
|
| 70 |
+
angles = film_points / resolution * 2 * dr.pi + shift
|
| 71 |
+
points = Point2f(origin) + radius * Point2f(dr.sin(angles), dr.cos(angles))
|
| 72 |
+
else:
|
| 73 |
+
film_points = dr.arange(Float, resolution)
|
| 74 |
+
film_points = dr.repeat(film_points, spp)
|
| 75 |
+
film_points += 1/2 if centered else 0
|
| 76 |
+
angles = film_points / resolution * 2 * dr.pi + shift
|
| 77 |
+
points = Point2f(origin) + radius * Point2f(dr.sin(angles), dr.cos(angles))
|
| 78 |
+
return points
|
| 79 |
+
|
| 80 |
+
def create_circle_from_result(result, resolution = 1024):
|
| 81 |
+
# Splat to film
|
| 82 |
+
spp = int(dr.width(result) / resolution)
|
| 83 |
+
res_image = TensorXf(dr.block_sum(result, spp)) / spp
|
| 84 |
+
return res_image.numpy(), res_image
|
| 85 |
+
|
| 86 |
+
def create_electrode_result(L, spe, electrode_nums : ArrayXu, apply_normalization = True, compute_std = False):
|
| 87 |
+
#unnormalized = dr.block_sum(L, spe) / spe
|
| 88 |
+
unnormalized = dr.block_sum(L, spe) / spe
|
| 89 |
+
num_active_electrodes = dr.width(electrode_nums)
|
| 90 |
+
|
| 91 |
+
if apply_normalization:
|
| 92 |
+
bias = dr.block_sum(unnormalized, dr.width(unnormalized)) / num_active_electrodes
|
| 93 |
+
result = unnormalized - dr.select(unnormalized != 0, bias, 0)
|
| 94 |
+
else:
|
| 95 |
+
result = unnormalized
|
| 96 |
+
|
| 97 |
+
if not compute_std:
|
| 98 |
+
return result
|
| 99 |
+
|
| 100 |
+
variance = dr.block_sum(dr.square(L), spe) / spe - dr.square(unnormalized)
|
| 101 |
+
variance /= spe
|
| 102 |
+
|
| 103 |
+
return result, dr.sqrt(variance)
|
| 104 |
+
|
| 105 |
+
'''
|
| 106 |
+
def block_sum(L : Float, spp : int) -> Float: #spe needs to be power of 2
|
| 107 |
+
iternum = int(dr.log2(spp))
|
| 108 |
+
sum = ArrayXf(L)
|
| 109 |
+
for i in range(iternum):
|
| 110 |
+
sum = dr.block_sum(sum, 2)
|
| 111 |
+
return sum
|
| 112 |
+
|
| 113 |
+
def block_sum_(L : Float, spp : int) -> Float: # Kahan-compensated blocksum.
|
| 114 |
+
num_bins = dr.width(L)//spp
|
| 115 |
+
index = dr.arange(UInt32, num_bins)
|
| 116 |
+
index = dr.repeat(index, spp)
|
| 117 |
+
target1 = dr.zeros(Float, num_bins)
|
| 118 |
+
target2 = dr.zeros(Float, num_bins)
|
| 119 |
+
dr.scatter_add_kahan(target1, target2, L, index)
|
| 120 |
+
return target1 + target2
|
| 121 |
+
|
| 122 |
+
'''
|
| 123 |
+
|
data/PDE2D/utils/optimization.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import drjit as dr
|
| 2 |
+
import mitsuba as mi
|
| 3 |
+
from PDE2D import ArrayXf
|
| 4 |
+
from mitsuba import TensorXf
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
def MSE(img , img_ref = 0):
|
| 8 |
+
val = img
|
| 9 |
+
val_ref = img_ref
|
| 10 |
+
if isinstance(val, TensorXf):
|
| 11 |
+
val = val.array
|
| 12 |
+
if isinstance(val_ref, TensorXf):
|
| 13 |
+
val_ref = val_ref.array
|
| 14 |
+
return dr.block_sum(dr.square(val - val_ref), dr.width(val)) / dr.width(val)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def MSE_image(img , img_ref = 0):
|
| 18 |
+
return dr.sum(dr.square(img - img_ref).array) / (img.shape[1] * img.shape[2])
|
| 19 |
+
|
| 20 |
+
def MSE_numpy(val :np.array , val_ref : np.array = 0):
|
| 21 |
+
return np.sum(np.square(val - val_ref), axis = tuple(range(1, val.ndim))) / (np.size(val) / val.shape[0])
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def compute_loss_grad(result, result_ref=0):
|
| 25 |
+
return (2 * (result - result_ref)) / dr.width(result)
|
| 26 |
+
|
| 27 |
+
def compute_dL(L, loss_grad, spe, electrode_nums = None, apply_normalization = False):
|
| 28 |
+
if not apply_normalization:
|
| 29 |
+
# The commented lines show that there is no difference between
|
| 30 |
+
# applying normalization to the primal computation.
|
| 31 |
+
#normalization = dr.sum(L) / dr.width(L)
|
| 32 |
+
#L = L - normalization
|
| 33 |
+
#dr.enable_grad(L)
|
| 34 |
+
#result = dr.block_sum(L, spe) / spe
|
| 35 |
+
#dr.set_grad(result, adjoint_result)
|
| 36 |
+
#dr.backward(result)
|
| 37 |
+
dL = dr.repeat(loss_grad, spe) / spe
|
| 38 |
+
else:
|
| 39 |
+
num_active_electrodes = dr.width(electrode_nums)
|
| 40 |
+
unnormalized = dr.block_sum(L, spe) / spe
|
| 41 |
+
#unnormalized = self.block_sum(L, spe) / spe
|
| 42 |
+
dr.enable_grad(unnormalized)
|
| 43 |
+
bias = dr.block_sum(unnormalized, dr.width(unnormalized)) / num_active_electrodes
|
| 44 |
+
result = unnormalized - dr.select(unnormalized != 0, bias, 0)
|
| 45 |
+
#result = unnormalized - dr.sum(unnormalized) / dr.width(unnormalized)
|
| 46 |
+
dr.enable_grad(result)
|
| 47 |
+
dr.set_grad(result, loss_grad)
|
| 48 |
+
dr.enqueue(dr.ADMode.Backward, result)
|
| 49 |
+
dr.traverse(dr.ADMode.Backward)
|
| 50 |
+
grad = dr.grad(unnormalized)
|
| 51 |
+
dL = dr.repeat(grad, spe) / spe
|
| 52 |
+
return dL
|
| 53 |
+
|
| 54 |
+
def compute_loss_grad_image(result, result_ref = 0):
|
| 55 |
+
return (2 * (result - result_ref)) / (result.shape[1] * result.shape[2])
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def compute_dL_image(loss_grad, spp):
|
| 59 |
+
size = loss_grad.shape[1] * loss_grad.shape[2] * spp
|
| 60 |
+
dL = dr.zeros(ArrayXf, shape = (loss_grad.shape[0], size))
|
| 61 |
+
for i in range(loss_grad.shape[0]):
|
| 62 |
+
dL[i] = dr.repeat(loss_grad[i].array, spp) / spp
|
| 63 |
+
return dL
|