Image_SDF / src /sdf_geo /constraints.py
WendingGao's picture
Upload 22 files
fdb3169 verified
"""
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