File size: 3,155 Bytes
fdb3169 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | """
Geometric Constraints - Differentiable constraint functions for optimization.
Following GeoSDF paper Section 5.
"""
import torch
from typing import Callable
class GeometricConstraints:
"""Collection of differentiable geometric constraint functions."""
@staticmethod
def point_on_curve(sdf: Callable, point: torch.Tensor) -> torch.Tensor:
"""Constraint: point lies on curve (SDF = 0)."""
return sdf(point.unsqueeze(0))**2
@staticmethod
def distance_constraint(p1: torch.Tensor, p2: torch.Tensor,
target_dist: float) -> torch.Tensor:
"""Constraint: distance between two points equals target."""
actual_dist = torch.norm(p1 - p2)
return (actual_dist - target_dist)**2
@staticmethod
def eccentricity_ellipse(a: torch.Tensor, b: torch.Tensor,
target_e: float) -> torch.Tensor:
"""Constraint: ellipse eccentricity."""
c_squared = a**2 - b**2
c = torch.sqrt(torch.clamp(c_squared, min=1e-8))
e = c / a
return (e - target_e)**2
@staticmethod
def eccentricity_hyperbola(a: torch.Tensor, b: torch.Tensor,
target_e: float) -> torch.Tensor:
"""Constraint: hyperbola eccentricity e = c/a where c² = a² + b²."""
c_squared = a**2 + b**2
c = torch.sqrt(c_squared)
e = c / (a + 1e-8)
return (e - target_e)**2
@staticmethod
def asymptote_slope(a: torch.Tensor, b: torch.Tensor,
target_slope: float) -> torch.Tensor:
"""Constraint: hyperbola asymptote slope b/a."""
actual_slope = b / (a + 1e-8)
return (actual_slope - target_slope)**2
@staticmethod
def focus_constraint(a: torch.Tensor, b: torch.Tensor,
focus_coord: float, is_hyperbola: bool = False) -> torch.Tensor:
"""Constraint: focus at specific coordinate."""
if is_hyperbola:
c_squared = a**2 + b**2
else:
c_squared = a**2 - b**2
c = torch.sqrt(torch.clamp(c_squared, min=1e-8))
return (c - abs(focus_coord))**2
@staticmethod
def focus_constraint_hyperbola(a: torch.Tensor, b: torch.Tensor,
target_c: float) -> torch.Tensor:
"""Constraint: hyperbola focus distance c where c² = a² + b²."""
c_squared = a**2 + b**2
c = torch.sqrt(c_squared)
return (c - target_c)**2
@staticmethod
def positive_constraint(param: torch.Tensor, min_val: float = 0.1) -> torch.Tensor:
"""Soft constraint to keep parameter positive."""
return torch.relu(min_val - param)**2
@staticmethod
def crowd_penalty(positions: list, min_dist: float = 0.5) -> torch.Tensor:
"""Penalty for elements being too close together."""
penalty = torch.tensor(0.0)
for i, p1 in enumerate(positions):
for p2 in positions[i+1:]:
dist = torch.norm(p1 - p2)
penalty = penalty + torch.relu(min_dist - dist)**2
return penalty
|