├── pygmi
├── nn
│ ├── nerf.py
│ ├── __init__.py
│ ├── deepsdf.py
│ ├── encoder.py
│ └── siren.py
├── data
│ ├── __init__.py
│ ├── dataset
│ │ ├── __init__.py
│ │ ├── core.py
│ │ └── sdf.py
│ ├── sources
│ │ ├── __init__.py
│ │ ├── pyg.py
│ │ ├── core.py
│ │ └── misc.py
│ └── preprocess
│ │ ├── __init__.py
│ │ ├── core.py
│ │ └── sdf.py
├── __version__.py
├── __init__.py
├── types
│ ├── __init__.py
│ ├── core.py
│ └── sdf.py
├── utils
│ ├── math
│ │ ├── __init__.py
│ │ └── diffops.py
│ ├── extract
│ │ ├── __init__.py
│ │ └── core.py
│ ├── visual
│ │ ├── __init__.py
│ │ └── core.py
│ ├── __init__.py
│ ├── files.py
│ └── misc.py
└── tasks
│ ├── __init__.py
│ ├── core.py
│ ├── distance_regression.py
│ └── distance_eikonal_ivp.py
├── setup.cfg
├── setup.py
├── examples
├── surface_reconstruction.py
└── encode_faust_sdf.py
├── .gitignore
├── README.md
└── LICENSE
/pygmi/nn/nerf.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/pygmi/data/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/pygmi/__version__.py:
--------------------------------------------------------------------------------
1 | __version__ = '0.1.0'
--------------------------------------------------------------------------------
/pygmi/__init__.py:
--------------------------------------------------------------------------------
1 | from pygmi.__version__ import __version__
--------------------------------------------------------------------------------
/pygmi/types/__init__.py:
--------------------------------------------------------------------------------
1 | from pygmi.types.sdf import SDF
2 | from pygmi.types.core import ImplicitFunction
--------------------------------------------------------------------------------
/pygmi/utils/math/__init__.py:
--------------------------------------------------------------------------------
1 | from pygmi.utils.math.diffops import gradient, jacobian, hessian, divergence
--------------------------------------------------------------------------------
/pygmi/utils/extract/__init__.py:
--------------------------------------------------------------------------------
1 | from pygmi.utils.extract.core import extract_level_set, grid_evaluation, marching_cubes
--------------------------------------------------------------------------------
/pygmi/utils/visual/__init__.py:
--------------------------------------------------------------------------------
1 | from pygmi.utils.visual.core import validate_figure, plot_trisurf, isosurf_animation, plot_isosurfaces, make_3d_subplots
--------------------------------------------------------------------------------
/pygmi/data/dataset/__init__.py:
--------------------------------------------------------------------------------
1 | from pygmi.data.dataset.core import MultiSourceData
2 | from pygmi.data.dataset.sdf import SDFUnsupervisedData, SDFSupervisedData
--------------------------------------------------------------------------------
/pygmi/data/sources/__init__.py:
--------------------------------------------------------------------------------
1 | from pygmi.data.sources.pyg import PyGDataSource
2 | from pygmi.data.sources.misc import PLYDataSource, PNGDataSource, TXTArrayDataSource
--------------------------------------------------------------------------------
/pygmi/nn/__init__.py:
--------------------------------------------------------------------------------
1 | from pygmi.nn.deepsdf import SmoothDeepSDFNet, DeepReLUSDFNet
2 | from pygmi.nn.encoder import PointNet2Encoder, Autodecoder
3 | from pygmi.nn.siren import SirenMLP, SirenSDF
--------------------------------------------------------------------------------
/pygmi/data/preprocess/__init__.py:
--------------------------------------------------------------------------------
1 | from pygmi.data.preprocess.sdf import get_distance_values, upsample_with_normals, center_point_cloud
2 | from pygmi.data.preprocess.core import gather_fnames, process_source
--------------------------------------------------------------------------------
/pygmi/tasks/__init__.py:
--------------------------------------------------------------------------------
1 | from pygmi.tasks.core import TaskBaseModule
2 | from pygmi.tasks.distance_regression import SupervisedDistanceRegression
3 | from pygmi.tasks.distance_eikonal_ivp import EikonalIVPOptimization
--------------------------------------------------------------------------------
/pygmi/utils/__init__.py:
--------------------------------------------------------------------------------
1 | from pygmi.utils.files import validate_fnames
2 | from pygmi.utils.misc import make_grid, cat_points_latent, sphere_sdf, label_to_interval
3 | from pygmi.utils.math import *
4 | from pygmi.utils.extract import *
5 | from pygmi.utils.visual import *
--------------------------------------------------------------------------------
/pygmi/tasks/core.py:
--------------------------------------------------------------------------------
1 | import pytorch_lightning as pl
2 | from pygmi.types import ImplicitFunction
3 |
4 |
5 |
6 | class TaskBaseModule(pl.LightningModule):
7 |
8 | def __init__(self, geom_repr: ImplicitFunction):
9 | """Instantiates a `TaskBaseModule`, an abstract `LightningModule`
10 | optimizing an `ImplicitFunction`
11 |
12 | Parameters
13 | ----------
14 | geom_repr : ImplicitFunction
15 | The implicit geometry of the scene(s) to optimize
16 | """
17 | super(TaskBaseModule, self).__init__()
18 | self.geometry = geom_repr
19 |
20 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | name = pygmi
3 | version = attr: pygmi.__version__.__version__
4 | description = PyGMI - A library for neural implicit geometry
5 | url = https://github.com/daniele-baieri/PyGMI
6 | long_description = file: README.md
7 | author = Daniele Baieri
8 | author_email = daniele.baieri@gmail.com
9 | license = GNU General Public License v3.0
10 |
11 | [options]
12 | packages = find:
13 | install_requires =
14 | numpy
15 | torch
16 | torchvision
17 | pytorch-lightning
18 | cgal
19 | wandb
20 | scikit-image
21 | plotly
22 | trimesh
23 | typing-extensions; python_version < "3.8"
24 | zip_safe = False
25 |
26 | [options.packages.find]
27 | exclude =
28 | bin*
29 | tmp*
--------------------------------------------------------------------------------
/pygmi/data/sources/pyg.py:
--------------------------------------------------------------------------------
1 | import torch_geometric.datasets as pygdst
2 | from typing import Dict, List
3 | from pygmi.data.sources.core import DataSource
4 |
5 |
6 |
7 | class PyGDataSource(DataSource):
8 |
9 | def __init__(self, source: str, idx_select: List[int] = None, **pyg_kwargs: Dict):
10 | """Initializes a data source from a PyTorch Geometric dataset.
11 | kwargs are passed to the PyG initializer.
12 |
13 | Parameters
14 | ----------
15 | source : str
16 | Name of the PyG dataset to use.
17 | idx_select : List[int]
18 | indices of data objects to select, by default None
19 | """
20 | self.source = getattr(pygdst, source)(**pyg_kwargs)
21 | super(PyGDataSource, self).__init__(indices=idx_select)
22 |
--------------------------------------------------------------------------------
/pygmi/utils/files.py:
--------------------------------------------------------------------------------
1 | import os
2 | from typing import List
3 |
4 |
5 |
6 | def mkdir_ifnotexists(path: str) -> None:
7 | """Creates directory at given path, if it does not exist.
8 |
9 | Parameters
10 | ----------
11 | path : str
12 | Path to directory to create
13 | """
14 | if not os.path.isdir(path):
15 | os.mkdir(path)
16 |
17 | def validate_fnames(paths: List[str]) -> bool:
18 | """
19 | Verifies that a list of paths exists as files in memory.
20 |
21 | Parameters
22 | ----------
23 | paths : str
24 | A list of file paths
25 |
26 | Returns
27 | -------
28 | bool
29 | True if every path leads to a file, False ow
30 | """
31 | for f in paths:
32 | if not os.path.isfile(f):
33 | return False
34 | return True
--------------------------------------------------------------------------------
/pygmi/data/sources/core.py:
--------------------------------------------------------------------------------
1 | from typing import List, Any
2 |
3 |
4 | class DataSource:
5 |
6 | def __init__(self, indices: List[int] = None):
7 | """Initialize abstract data source.
8 | If no indices are selected, use all the available data.
9 |
10 | Parameters
11 | ----------
12 | indices : List[int], optional
13 | indices of data objects to select, by default None
14 | """
15 | self.indices = range(len(self.source)) if indices is None else indices
16 |
17 | def __getitem__(self, idx: int) -> Any:
18 | return self.process(self.source[self.indices[idx]])
19 |
20 | def __len__(self) -> int:
21 | return len(self.indices)
22 |
23 | def process(self, obj: Any) -> Any:
24 | """Make raw object ready for preprocessing.
25 | For this abstract base class, simply return the object.
26 |
27 | Parameters
28 | ----------
29 | obj : Any
30 | Raw object belonging to data source `self`.
31 |
32 | Returns
33 | -------
34 | Any
35 | Returns `obj`
36 | """
37 | return obj
38 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import os
2 | import warnings
3 | import subprocess
4 | from setuptools import setup
5 |
6 |
7 | NO_ADD_DEPS_KEY = 'PYGMI_NO_ADD_DEPS'
8 | DEPS = 'torch-scatter torch-sparse torch-geometric -f https://data.pyg.org/whl/torch-{}+{}.html"'
9 |
10 |
11 | if __name__ == "__main__":
12 |
13 | setup()
14 |
15 | no_additional = os.environ[NO_ADD_DEPS_KEY] if NO_ADD_DEPS_KEY in os.environ.keys() else None
16 |
17 |
18 | if not no_additional or no_additional is None:
19 | try:
20 | import torch
21 | try:
22 | import torch_geometric
23 | warnings.warn('PyG already found, skipping.')
24 | except ImportError:
25 | vrs = torch.__version__
26 | cuda = 'cu' + torch.version.cuda.replace('.', '') if torch.cuda.is_available() else 'cpu'
27 | deps = DEPS.format(vrs, cuda)
28 | subprocess.call(['pip', 'install'] + deps.split(' '))
29 | except:
30 | warnings.warn('PyTorch not available. PyTorch Geometric will not be installed.')
31 |
32 | else:
33 | warnings.warn('Additional dependencies install is disabled. Exiting.')
34 |
35 | # PyGMI
36 |
--------------------------------------------------------------------------------
/pygmi/data/preprocess/core.py:
--------------------------------------------------------------------------------
1 | from typing import Callable, Dict, List
2 | from tqdm import tqdm
3 | from pygmi.data.sources.core import DataSource
4 |
5 |
6 | def gather_fnames(out_dir: str, source_name: str, n: int) -> List[str]:
7 | """Creates a list of filenames for storing processed data points.
8 |
9 | Parameters
10 | ----------
11 | out_dir : str
12 | Root dir of preprocessing output
13 | source_name : str
14 | Name of data source being preprocessed
15 | n : int
16 | Size of data source being preprocessed
17 |
18 | Returns
19 | -------
20 | List[str]
21 | List of filepaths to write preprocessed data
22 | """
23 | return [out_dir + '/{}_{}.pth'.format(source_name, i) for i in range(n)]
24 |
25 | def process_source(data: DataSource, fnames: List[str], fn: Callable, fn_kwargs: Dict) -> None:
26 | """Runs a preprocessing function for each element in a data source.
27 |
28 | Parameters
29 | ----------
30 | data : DataSource
31 | Collection of data points (inputs to fn)
32 | fnames : List[str]
33 | List of output locations on resident memory
34 | fn : Callable
35 | Preprocessing function
36 | fn_kwargs : Dict
37 | Additional arguments to preprocessing function
38 | """
39 | for i in tqdm(range(len(fnames)), desc='Preprocessing data with {}'.format(fn.__name__)):
40 | fn(data[i], fnames[i], **fn_kwargs)
--------------------------------------------------------------------------------
/pygmi/types/core.py:
--------------------------------------------------------------------------------
1 | import torch.nn as nn
2 | from typing import Any, Callable
3 | from torch import Tensor
4 | from pygmi.utils import cat_points_latent
5 |
6 |
7 | class ImplicitFunction(nn.Module):
8 |
9 | def __init__(self, approximator: Callable):
10 | """Base class for objects representing implicit functions
11 |
12 | Parameters
13 | ----------
14 | approximator : Callable
15 | Callable objects computing the function (e.g. a neural net)
16 | """
17 | super(ImplicitFunction, self).__init__()
18 | self.F = approximator
19 |
20 | def forward(self, coords: Tensor, condition: Tensor = None, *args, **kwargs) -> Any:
21 | """Computes the represented function on a set of points. args and kwargs are
22 | forwarded to `self.F`, while a condition vector can be paired to each given point.
23 |
24 | Parameters
25 | ----------
26 | coords : Tensor
27 | A Tensor of point coordinates, shape `B_1 x ... x B_n x S x D`
28 | condition : Tensor, optional
29 | A condition vector to be paired to each sample of points,
30 | shape `B_1 x ... x B_n x N`, by default None
31 |
32 | Returns
33 | -------
34 | Any
35 | Function computed over point set `coords`
36 | """
37 | x = coords if condition is None else cat_points_latent(coords, condition)
38 | return self.F(x, *args, **kwargs)
--------------------------------------------------------------------------------
/examples/surface_reconstruction.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import pytorch_lightning as pl
3 | from pytorch_lightning.loggers import WandbLogger
4 | from pygmi.data.dataset import SDFUnsupervisedData
5 | from pygmi.tasks import EikonalIVPOptimization
6 | from pygmi.types import SDF
7 | from pygmi.nn import SirenSDF
8 | from pygmi.utils.extract import grid_evaluation
9 | from pygmi.utils.visual import isosurf_animation
10 |
11 |
12 | """Learns a SDF from a single .txt point cloud, using a Siren
13 | network and unsupervised training. The result is plotted after
14 | optimization.
15 | """
16 |
17 | if __name__ == "__main__":
18 |
19 | logging = False
20 | gpu = 1 if torch.cuda.is_available() else 0
21 |
22 | has_normal_data = True
23 | data = SDFUnsupervisedData(
24 | train_source_conf=[
25 | dict(
26 | type='TXTArrayDataSource',
27 | source_conf=dict(
28 | source='/path/to/dir/containing/txt/file',
29 | idx_select=None
30 | )
31 | )
32 | ],
33 | preprocessing_conf=dict(
34 | do_preprocessing=True,
35 | out_dir='/path/to/data/output/',
36 | script='center_point_cloud',
37 | conf=dict(mnfld_sigma=True)
38 | ),
39 | batch_size=dict(train=1, val=1, test=1),
40 | use_normals=has_normal_data,
41 | surf_sample=30000,
42 | global_space_sample=3750
43 | )
44 |
45 | net = SirenSDF()
46 | sdf = SDF(net)
47 | task = EikonalIVPOptimization(sdf, lr_sdf=1e-4, lr_sched_step=None, lr_sched_gamma=None)
48 |
49 | epochs = 5000
50 | if logging is True:
51 | logger = WandbLogger(project='PyGMI Task Logs')
52 | else:
53 | logger = False
54 | trainer = pl.Trainer(logger=logger, max_epochs=epochs, accelerator='gpu' if gpu == 1 else 'cpu', devices=gpu)
55 | trainer.fit(task, data)
56 |
57 | net = net.to('cuda' if gpu == 1 else 'cpu')
58 | volume = grid_evaluation(sdf, 3, 100, 1.2, 'cuda' if gpu == 1 else 'cpu')
59 | fig = isosurf_animation(volume, axes=[-1.2, 1.2] * 3, steps=10, min_level=-0.5, max_level=0.7)
60 | fig.show()
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 | *.pyc
30 |
31 | # PyInstaller
32 | # Usually these files are written by a python script from a template
33 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
34 | *.manifest
35 | *.spec
36 |
37 | # Installer logs
38 | pip-log.txt
39 | pip-delete-this-directory.txt
40 |
41 | # Unit test / coverage reports
42 | htmlcov/
43 | .tox/
44 | .nox/
45 | .coverage
46 | .coverage.*
47 | .cache
48 | nosetests.xml
49 | coverage.xml
50 | *.cover
51 | *.py,cover
52 | .hypothesis/
53 | .pytest_cache/
54 |
55 | # Translations
56 | *.mo
57 | *.pot
58 |
59 | # Django stuff:
60 | *.log
61 | local_settings.py
62 | db.sqlite3
63 | db.sqlite3-journal
64 |
65 | # Flask stuff:
66 | instance/
67 | .webassets-cache
68 |
69 | # Scrapy stuff:
70 | .scrapy
71 |
72 | # Sphinx documentation
73 | docs/_build/
74 |
75 | # PyBuilder
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | .python-version
87 |
88 | # pipenv
89 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
90 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
91 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
92 | # install all needed dependencies.
93 | #Pipfile.lock
94 |
95 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
96 | __pypackages__/
97 |
98 | # Celery stuff
99 | celerybeat-schedule
100 | celerybeat.pid
101 |
102 | # SageMath parsed files
103 | *.sage.py
104 |
105 | # Environments
106 | .env
107 | .venv
108 | env/
109 | venv/
110 | ENV/
111 | env.bak/
112 | venv.bak/
113 |
114 | # Spyder project settings
115 | .spyderproject
116 | .spyproject
117 |
118 | # Rope project settings
119 | .ropeproject
120 |
121 | # mkdocs documentation
122 | /site
123 |
124 | # mypy
125 | .mypy_cache/
126 | .dmypy.json
127 | dmypy.json
128 |
129 | # Pyre type checker
130 | .pyre/
131 |
132 |
133 | tmp/
134 | bin/
135 | data/
--------------------------------------------------------------------------------
/examples/encode_faust_sdf.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import pytorch_lightning as pl
3 | from pytorch_lightning.loggers import WandbLogger
4 | from pygmi.data.dataset import SDFSupervisedData
5 | from pygmi.tasks import SupervisedDistanceRegression
6 | from pygmi.types import SDF
7 | from pygmi.nn import DeepReLUSDFNet
8 | from pygmi.utils.extract import grid_evaluation
9 | from pygmi.utils.visual import isosurf_animation
10 |
11 |
12 | """Learns a parametric SDF for the FAUST train + test dataset.
13 | Preprocesses the data from its PyG counterpart, then runs
14 | sign agnostic distance regression. Finally, the result for one
15 | of the training shapes is plotted.
16 | """
17 |
18 | if __name__ == "__main__":
19 |
20 | logging = False
21 | num_shapes = 100
22 | latent_dim = 256
23 | gpu = 1 if torch.cuda.is_available() else 0
24 |
25 | data = SDFSupervisedData(
26 | train_source_conf=[
27 | dict(
28 | type='PyGDataSource',
29 | source_conf=dict(
30 | source='FAUST',
31 | idx_select=None,
32 | root='/path/to/FAUST/dir',
33 | train=True
34 | )
35 | ),
36 | dict(
37 | type='PyGDataSource',
38 | source_conf=dict(
39 | source='FAUST',
40 | idx_select=None,
41 | root='/path/to/FAUST/dir',
42 | train=False
43 | )
44 | )
45 | ],
46 | preprocessing_conf=dict(
47 | do_preprocessing=True,
48 | out_dir='/path/to/data/output/',
49 | script='get_distance_values',
50 | conf=dict(sample=500000)
51 | ),
52 | batch_size=dict(train=10, val=1, test=1),
53 | use_normals=False
54 | )
55 |
56 | net = DeepReLUSDFNet(input_dim = 3 + latent_dim)
57 | sdf = SDF(net)
58 | task = SupervisedDistanceRegression(sdf, num_shapes=num_shapes, condition_size=latent_dim)
59 |
60 | epochs = 2000
61 | if logging is True:
62 | logger = WandbLogger(project='PyGMI Task Logs')
63 | else:
64 | logger = False
65 | trainer = pl.Trainer(logger=logger, max_epochs=epochs, accelerator='gpu' if gpu==1 else 'cpu', devices=gpu)
66 | trainer.fit(task, data)
67 |
68 | device = 'cuda' if gpu == 1 else 'cpu'
69 | shape_to_plot = 16
70 | latent = task.autodecoder(shape_to_plot).to(device)
71 | net = net.to(device)
72 | volume = grid_evaluation(sdf, 3, 100, 1.2, device, condition=latent)
73 | fig = isosurf_animation(volume, axes=[-1.2, 1.2] * 3, steps=10, min_level=-0.5, max_level=0.7)
74 | fig.show()
--------------------------------------------------------------------------------
/pygmi/types/sdf.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import pygmi.utils.math.diffops as diffops
3 | import pygmi.utils.extract as extract
4 | from typing import Callable, Literal, Tuple
5 | from torch import Tensor
6 | from pygmi.types.core import ImplicitFunction
7 |
8 |
9 | class SDF(ImplicitFunction):
10 |
11 | def __init__(self, approximator: Callable, dim: int = 3):
12 | """A utility class for objects representing signed distance fields.
13 |
14 | Parameters
15 | ----------
16 | approximator : Callable
17 | Function computing the SDF of given points
18 | dim : int, optional
19 | Dimensionality of domain, by default 3
20 | """
21 | super(SDF, self).__init__(approximator)
22 | self.dim = dim
23 |
24 | def normal(self, coords: Tensor, condition: Tensor = None) -> Tensor:
25 | """Computes SDF normals in query points `coords`, using the
26 | normalized gradient of the SDF
27 |
28 | Parameters
29 | ----------
30 | coords : Tensor
31 | A Tensor of point coordinates, shape `B_1 x ... x B_n x S x D`
32 | condition : Tensor, optional
33 | A condition vector to be paired to each sample of points,
34 | shape `B_1 x ... x B_n x N`, by default None
35 |
36 | Returns
37 | -------
38 | Tensor
39 | Shape `B_1 x ... x B_n x S x D`, normals of each point in `coords`
40 | """
41 | x = coords.requires_grad_()
42 | d = self(x, condition=condition)
43 | n = diffops.gradient(x, d, dim=self.dim)
44 | return n / n.norm(dim=-1, keepdim=True)
45 |
46 | def to_mesh(
47 | self,
48 | condition: Tensor = None,
49 | res: int = 100,
50 | max_coord: float = 1.0,
51 | device: Literal['cpu', 'cuda'] = 'cpu'
52 | ) -> Tuple[np.ndarray, np.ndarray]:
53 | """Converts `self` to a mesh using Marching Cubes.
54 |
55 | Parameters
56 | ----------
57 | condition : Tensor, optional
58 | Condition vector (for parametric SDFs), by default None
59 | res : int, optional
60 | Grid resolution, by default 100
61 | max_coord : float, optional
62 | Grid maximum absolute coordinate, by default 1.0
63 | device : Literal['cpu', 'cuda'], optional
64 | Device to run grid evaluation of SDF, by default 'cpu'
65 |
66 | Returns
67 | -------
68 | Tuple[np.ndarray, np.ndarray]
69 | Vertices and faces of output mesh
70 | """
71 | return extract.extract_level_set(self.forward, self.dim, res, bound=max_coord, device=device, condition=condition)
72 |
73 |
--------------------------------------------------------------------------------
/pygmi/utils/misc.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import functools
3 | import time
4 | import numpy as np
5 | from torch import Tensor
6 | from typing import Callable
7 |
8 |
9 |
10 |
11 | def timer(func: Callable) -> Callable:
12 | """Decorator for timing functions.
13 |
14 | Parameters
15 | ----------
16 | func : Callable
17 | Any function
18 |
19 | Returns
20 | -------
21 | Callable
22 | Timing wrapper for `func`
23 | """
24 | @functools.wraps(func)
25 | def wrapper_timer(*args, **kwargs):
26 | start_time = time.perf_counter()
27 | value = func(*args, **kwargs)
28 | end_time = time.perf_counter()
29 | run_time = end_time - start_time
30 | print(f"Timed {func.__name__!r}: {run_time:.4f}s")
31 | return value
32 | return wrapper_timer
33 |
34 | def sphere_sdf(x: Tensor, p: float = 2.0, r: float = 1.0) -> Tensor:
35 | """Signed distance function for a d-dimensional sphere.
36 | The sphere is assumed to be centered in the R^d origin.
37 |
38 | Parameters
39 | ----------
40 | x : Tensor
41 | Points: shape `B_1 x ... x B_n x d`
42 | p : float, optional
43 | Specify which L_p norm to compute, by default 2.0
44 | r : float, optional
45 | Radius of the sphere, by default 1.0
46 |
47 | Returns
48 | -------
49 | Tensor
50 | SDF values from the sphere for each point in `x`.
51 | """
52 | return x.norm(dim=-1, p=p, keepdim=True) - r
53 |
54 | def make_grid(resolution: int, bound: float, dim: int = 3) -> Tensor:
55 | """Instantiate a regular voxel grid with given bounds and resolution.
56 |
57 | Parameters
58 | ----------
59 | resolution : int
60 | Number of voxels in each dimension
61 | bound : float
62 | Maximum coordinate of voxel points
63 | dim : int, optional
64 | Number of dimensions, by default 3
65 |
66 | Returns
67 | -------
68 | Tensor
69 | Shape `N x dim`, each point representing a voxel corner in the
70 | specified grid
71 | """
72 | line = np.linspace(-bound, bound, resolution)
73 | grid = np.meshgrid(*([line] * dim))
74 | return torch.tensor(
75 | np.vstack([l.ravel() for l in grid]).T, dtype=torch.float
76 | )
77 |
78 | def cat_points_latent(points: Tensor, latent: Tensor) -> Tensor:
79 | """Utility function to concatenate latent vectors of continuous
80 | data to finite samples of continuous data.
81 |
82 | Parameters
83 | ----------
84 | points : Tensor
85 | A coordinate Tensor, shape `B x S x D`
86 | latent : Tensor
87 | A Tensor of latent vectors, shape `B x N`
88 |
89 | Returns
90 | -------
91 | Tensor
92 | Each point concatenated to the respective latent vector, shape `B x S x (D + N)`
93 | """
94 | B, S = points.shape[0], points.shape[1]
95 | if len(latent.shape) == 1:
96 | latent = latent.unsqueeze(0)
97 | z_exp = torch.stack([latent[i, :].expand(S, -1) for i in range(B)])
98 | x = torch.cat([points, z_exp], dim=-1).view(-1, points.shape[2] + latent.shape[1])
99 | return x
100 |
101 | def label_to_interval(i: int, lo: float, hi: float, steps: int) -> float:
102 | """Maps `i` to the proper float value in the linear space with `steps` steps
103 | between `lo` and `hi`.
104 |
105 | Parameters
106 | ----------
107 | i : int
108 | An integer value
109 | lo : float
110 | The minimum value of the linear space
111 | hi : float
112 | The maximum value of the linear space
113 | steps : int
114 | Number of steps between `lo` and `hi`
115 |
116 | Returns
117 | -------
118 | float
119 | The `i`-th step in the linspace
120 | """
121 | return lo + (((hi - lo) / (steps - 1)) * i)
--------------------------------------------------------------------------------
/pygmi/data/sources/misc.py:
--------------------------------------------------------------------------------
1 | import os
2 | from typing import List
3 | from torch_geometric.data import Data as PyGData
4 | from torch_geometric.io import read_txt_array, read_ply
5 | from torchvision.datasets import ImageFolder
6 | from pygmi.data.sources.core import DataSource
7 |
8 |
9 | class PLYDataSource(DataSource):
10 |
11 | def __init__(self, source: str, idx_select: List[int] = None):
12 | """Initializes a data source from .ply files in a folder.
13 |
14 | Parameters
15 | ----------
16 | source : str
17 | path to directory containing the files
18 | idx_select : List[int], optional
19 | indices of data objects to select, by default None
20 | """
21 | self.source = [source + '/' + fp for fp in os.listdir(source)]
22 | super(PLYDataSource, self).__init__(indices=idx_select)
23 |
24 | def process(self, obj: str) -> PyGData:
25 | """Override of `process` method. Calls `torch_geometric.io.read_ply`
26 | to load a filepath pointing to a .ply file into a `torch_geometric.data.Data`
27 | object.
28 |
29 | Parameters
30 | ----------
31 | obj : str
32 | Path to a .ply file on disk.
33 |
34 | Returns
35 | -------
36 | PyGData
37 | A `torch_geometric.data.Data` object, representing a mesh or a point cloud.
38 | Usual attributes are `pos`, `face`, and `normal`.
39 | """
40 | return read_ply(obj)
41 |
42 |
43 | class TXTArrayDataSource(DataSource):
44 |
45 | def __init__(self, source: str, idx_select: List[int] = None):
46 | """Initializes a data source from .txt files in a folder,
47 | containing array data. Usually convenient for point clouds,
48 | following the format:
49 | x y z u v w
50 | where each row contains point coordinates and normals.
51 |
52 | Parameters
53 | ----------
54 | source : str
55 | path to directory containing the files
56 | idx_select : List[int], optional
57 | indices of data objects to select, by default None
58 | """
59 | self.source = [source + '/' + fp for fp in os.listdir(source)]
60 | super(TXTArrayDataSource, self).__init__(indices=idx_select)
61 |
62 | def process(self, obj: str) -> PyGData:
63 | """Overrides the `process` method, by reading a .txt array and
64 | returning it as a `torch_geometric.data.Data` object containing
65 | point coordinates and (optionally) normals of a point cloud.
66 |
67 | Parameters
68 | ----------
69 | obj : str
70 | Path to a .txt file containing a point cloud saved as array,
71 | with format:
72 | x y z [u v w]
73 | Where (x, y, z) are the point coordinates and (u, v, w) are the
74 | (optional) surface normals of the corresponding points.
75 |
76 | Returns
77 | -------
78 | PyGData
79 | A `torch_geometric.data.Data` with attributes `pos` and `normal`.
80 | """
81 | t = read_txt_array(obj)
82 | pos = t[:, :3]
83 | if t.shape[1] > 3:
84 | normal = t[:, 3:]
85 | return PyGData(pos=pos, normal=normal)
86 |
87 |
88 | class PNGDataSource(DataSource):
89 |
90 | def __init__(self, source: str, idx_select: List[int] = None):
91 | """Initializes a data source from .png files in a folder.
92 |
93 | Parameters
94 | ----------
95 | source : str
96 | path to directory containing the files
97 | idx_select : List[int], optional
98 | indices of data objects to select, by default None
99 | """
100 | self.source = ImageFolder(source)
101 | super(PNGDataSource, self).__init__(indices=idx_select)
102 |
103 |
--------------------------------------------------------------------------------
/pygmi/nn/deepsdf.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import numpy as np
4 | from typing import List
5 | from torch import Tensor
6 |
7 |
8 |
9 | class _MLP(nn.Module):
10 |
11 | def __init__(
12 | self,
13 | num_layers: int,
14 | input_dim: int,
15 | output_dim: int,
16 | hidden_dim: int,
17 | skip_in: List[int],
18 | geometric_init: bool,
19 | activation: nn.Module
20 | ):
21 | super(_MLP, self).__init__()
22 | self.actvn = activation
23 | hidden_sizes = [input_dim] + ([hidden_dim] * (num_layers - 1)) + [output_dim]
24 | self.num_layers = len(hidden_sizes)
25 | self.skip_conn = set(skip_in)
26 |
27 | self.linears = nn.ModuleList()
28 | for layer in range(1, self.num_layers):
29 | out_size = hidden_sizes[layer]
30 | if layer + 1 in self.skip_conn:
31 | out_size -= input_dim
32 | lin = nn.Linear(hidden_sizes[layer - 1], out_size)
33 | if geometric_init:
34 | if layer == self.num_layers - 1:
35 | torch.nn.init.normal_(lin.weight, mean=np.sqrt(np.pi) / np.sqrt(out_size), std=0.00001)
36 | torch.nn.init.constant_(lin.bias, -1.0)
37 | else:
38 | torch.nn.init.constant_(lin.bias, 0.0)
39 | torch.nn.init.normal_(lin.weight, 0.0, np.sqrt(2) / np.sqrt(out_size))
40 | self.linears.append(lin)
41 |
42 | def forward(self, x: Tensor) -> Tensor:
43 | h = x
44 | for idx, layer in enumerate(self.linears[:-1]):
45 | if idx + 1 in self.skip_conn:
46 | h = torch.cat([h, x], dim=-1)
47 | h = self.actvn(layer(h))
48 | output = self.linears[-1](h)
49 | return output
50 |
51 |
52 | class SmoothDeepSDFNet(_MLP):
53 |
54 | def __init__(
55 | self,
56 | input_dim: int = 3,
57 | hidden_dim: int = 512,
58 | num_layers: int = 8,
59 | skip_conn: List[int] = [4],
60 | geom_init: bool = True
61 | ):
62 | """Softplus-activated MLP, as proposed in https://arxiv.org/abs/2002.10099.
63 | Default parameters and spherical weight initialization are as in original paper.
64 |
65 | Parameters
66 | ----------
67 | input_dim : int, optional
68 | _description_, by default 3
69 | hidden_dim : int, optional
70 | _description_, by default 512
71 | num_layers : int, optional
72 | _description_, by default 8
73 | skip_conn : List[int], optional
74 | _description_, by default [4]
75 | """
76 | super(SmoothDeepSDFNet, self).__init__(
77 | num_layers, input_dim, 1, hidden_dim, skip_conn, geom_init, nn.Softplus(beta=100)
78 | )
79 |
80 |
81 | class DeepReLUSDFNet(_MLP):
82 |
83 | def __init__(
84 | self,
85 | input_dim: int = 3,
86 | hidden_dim: int = 512,
87 | num_layers: int = 8,
88 | skip_conn: List[int] = [4],
89 | geom_init: bool = True
90 | ):
91 | """ReLU-activated MLP, as proposed in https://arxiv.org/abs/1901.05103.
92 | Default parameters are as in original paper. Also features spherical
93 | weight initialization proposed in https://arxiv.org/abs/1911.10414.
94 |
95 | Parameters
96 | ----------
97 | input_dim : int, optional
98 | _description_, by default 3
99 | hidden_dim : int, optional
100 | _description_, by default 512
101 | num_layers : int, optional
102 | _description_, by default 8
103 | skip_conn : List[int], optional
104 | _description_, by default [4]
105 | """
106 | super(DeepReLUSDFNet, self).__init__(
107 | num_layers, input_dim, 1, hidden_dim, skip_conn, geom_init, nn.ReLU()
108 | )
--------------------------------------------------------------------------------
/pygmi/utils/extract/core.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import numpy as np
3 | import pygmi.utils as utils
4 | from skimage import measure
5 | from typing import Tuple, Callable, Literal
6 |
7 |
8 | def extract_level_set(
9 | f: Callable,
10 | dim: int,
11 | res: int,
12 | bound: float = 1.0,
13 | device: Literal['cpu', 'cuda'] = 'cpu',
14 | level: float = 0.0,
15 | *f_args, **f_kwargs
16 | ) -> Tuple[np.ndarray, np.ndarray]:
17 | """Approximates a given level set of an implicit function with a mesh.
18 | The function is evaluated on a regular voxel grid and the output mesh
19 | is extracted using the Marching Cubes algorithm.
20 |
21 | Parameters
22 | ----------
23 | f : Callable
24 | Callable representing the implicit function. Its first argument
25 | has to be a tensor of spatial coordinates of shape (B, S, dim)
26 | dim : int
27 | Dimensionality of query points for `f`
28 | res : int
29 | Grid resolution for mesh extraction
30 | bound : float, optional
31 | Maximum coordinate of voxel grid, by default 1.0
32 | device : Literal['cpu', 'cuda'], optional
33 | Device on which to run the computation, by default 'cpu'
34 | level : float, optional
35 | Which level set to extract, by default 0.0
36 |
37 | Returns
38 | -------
39 | Tuple[np.ndarray, np.ndarray]
40 | Vertices and faces of extracted mesh. If there is no zero crossing,
41 | it returns a single triangle collapsing on the origin.
42 | """
43 | volume = grid_evaluation(f, dim, res, bound, device, *f_args, **f_kwargs)
44 | verts, faces = marching_cubes(volume, (2 * bound) / (res - 1), level)
45 | if len(faces) > 1:
46 | verts -= bound
47 | return verts, faces
48 |
49 | def grid_evaluation(
50 | f: Callable,
51 | dim: int,
52 | res: int,
53 | bound: float,
54 | device: str,
55 | split: int = 100000,
56 | *f_args, **f_kwargs,
57 | ) -> np.ndarray:
58 | """Evaluates an implicit function on a regular voxel grid. Input space
59 | coordinates be given as a tensor with shape `(B, S, dim)` where
60 | `B` is the batch size and `S` is the sample size (number of points).
61 | args and kwargs are forwarded to f when it is invoked.
62 |
63 | Parameters
64 | ----------
65 | f : Callable
66 | SDF function. If parametric (i.e. `latent is not None`), it expects
67 | two Tensors of shapes `B x S x dim` and `B x n`. Otherwise, it expecst
68 | one Tensor of shape `B x S x dim`
69 | dim : int
70 | Dimensionality of query points for `f`
71 | res : int
72 | Grid resolution for mesh extraction
73 | bound : float
74 | Maximum coordinate of voxel grid, by default 1.0
75 | device : str
76 | Device on which to run the computation, by default 'cpu'
77 | split : int, optional
78 | _description_, by default 20000
79 |
80 | Returns
81 | -------
82 | np.ndarray
83 | Shape `res x res x res`, containing SDF values
84 | """
85 |
86 | volume = []
87 | with torch.no_grad():
88 | G = utils.make_grid(res, bound, dim)
89 | split = torch.split(G, split, dim=0)
90 | for j in range(len(split)):
91 | pnts = split[j].to(device)
92 | volume.append(f(pnts.unsqueeze(0), *f_args, **f_kwargs).detach().cpu().numpy())
93 | return np.concatenate(volume, axis=1).reshape(res, res, res).transpose([1, 0, 2])
94 |
95 | def marching_cubes(volume: np.ndarray, voxel_size: float, level: float = 0.0) -> Tuple[np.ndarray, np.ndarray]:
96 | """Invokes Marching Cubes on a voxel grid containing a scalar function.
97 | Gracefully handles the case of functions with no level crossing.
98 |
99 | Parameters
100 | ----------
101 | volume : np.ndarray
102 | Shape `N x N x N`
103 | voxel_size : float
104 | Size of a voxel in all dimensions
105 | level : float, optional
106 | Function level set to extract, by default 0.0
107 |
108 | Returns
109 | -------
110 | Tuple[np.ndarray, np.ndarray]
111 | Vertices and faces of extracted mesh. If there is no zero crossing,
112 | it returns a single triangle collapsing on the origin.
113 | """
114 | try:
115 | verts, faces, _, _ = measure.marching_cubes(volume, level=level, spacing=[voxel_size] * 3) # [(2 * bound) / (res - 1)] * 3
116 | except:
117 | verts = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
118 | faces = np.array([[0, 1, 2]])
119 | return verts, faces
120 |
--------------------------------------------------------------------------------
/pygmi/tasks/distance_regression.py:
--------------------------------------------------------------------------------
1 | import wandb
2 | import torch
3 | from torch import Tensor
4 | from typing import List
5 | from pygmi.tasks import TaskBaseModule
6 | from pygmi.types import SDF
7 | from pygmi.utils.extract import extract_level_set
8 | from pygmi.utils.visual import plot_trisurf
9 | from pygmi.nn.encoder import Autodecoder
10 |
11 |
12 |
13 | class SupervisedDistanceRegression(TaskBaseModule):
14 |
15 | def __init__(
16 | self,
17 | sdf_functional: SDF,
18 | num_shapes: int = 1,
19 | condition_size: int = 256,
20 | sign_agnostic: bool = True,
21 | lr_sdf: float = 5e-4,
22 | lr_autodec: float = 1e-3,
23 | lr_sched_step: int = 500,
24 | lr_sched_gamma: float = 0.5,
25 | latent_loss_w: float = 1e-3,
26 | plot_resolution: int = 100,
27 | plot_max_coord: float = 1.0,
28 | ):
29 | """Instantiates a `SupervisedDistanceRegression` task. This tasks reconstructs
30 | SDFs from labeled point clouds by regression from a signal over points in space.
31 |
32 | Parameters
33 | ----------
34 | sdf_functional : SDF
35 | Tensor functional representing a signed distance function
36 | num_shapes : int, optional
37 | Support for multi-shape optimization, by default 1
38 | condition_size : int, optional
39 | Dimension of latent vectors for multi-shape optimization, by default 256
40 | sign_agnostic : bool, optional
41 | Whether the training data is signed (False) or unsigned (True), by default True
42 | lr_sdf : float, optional
43 | Learning rate for SDF optimization, by default 5e-4
44 | lr_autodec : float, optional
45 | Learning rate for latent vectors optimization, by default 1e-3
46 | lr_sched_step : int, optional
47 | Step LR scheduler - size of steps, by default 500
48 | lr_sched_gamma : float, optional
49 | Step LR scheduler - decay factor, by default 0.5
50 | latent_loss_w : float, optional
51 | Weight of zero-mean constraint for latent vectors, by default 1e-3
52 | plot_resolution : int, optional
53 | Grid resolution of mesh extraction for plots, by default 100
54 | plot_max_coord : float, optional
55 | Maximum absolute coordinate of plot figures, by default 1.0
56 | """
57 | super(SupervisedDistanceRegression, self).__init__(sdf_functional)
58 | self.dim = self.geometry.dim
59 | self.sal = sign_agnostic
60 | self.lr_sdf = lr_sdf
61 | self.scheduler_step = lr_sched_step
62 | self.gamma = lr_sched_gamma
63 | self.latent_loss_w = latent_loss_w
64 | self.resolution = plot_resolution
65 | self.max_coord = plot_max_coord
66 | if num_shapes > 1:
67 | self.autodecoder = Autodecoder(num_shapes, condition_size)
68 | self.is_conditioned = True
69 | self.lr_autodec = lr_autodec
70 |
71 | def configure_optimizers(self) -> List:
72 | opt_params = [{'params': self.geometry.parameters(), 'lr': self.lr_sdf}]
73 | if self.is_conditioned:
74 | opt_params.append({'params': self.autodecoder.parameters(), 'lr': self.lr_autodec})
75 | optimizer = torch.optim.Adam(opt_params)
76 | scheduler = torch.optim.lr_scheduler.StepLR(optimizer, self.scheduler_step, self.gamma)
77 | return [optimizer], [scheduler]
78 |
79 | def training_step(self, batch, batch_idx) -> Tensor:
80 | indices, _, _, dist_sample = batch
81 | x_space, y_space = dist_sample[..., :self.dim], dist_sample[..., self.dim:]
82 |
83 | condition = None
84 | latent_loss = 0.0
85 | if self.is_conditioned:
86 | condition = self.autodecoder(indices)
87 | if self.latent_loss_w > 0:
88 | latent_loss = self.latent_loss_w * condition.norm(dim=-1).mean()
89 |
90 | sdf = self.geometry(x_space, condition)
91 |
92 | if self.sal:
93 | sdf_loss = (sdf.view_as(y_space).abs() - y_space).abs().mean()
94 | else:
95 | sdf_loss = (sdf.view_as(y_space) - y_space).abs().mean()
96 |
97 | loss = sdf_loss + latent_loss
98 | self.log("loss", loss)
99 | self.log("sdf_loss", sdf_loss)
100 | self.log("latent_loss", latent_loss)
101 | return loss
102 |
103 | def validation_step(self, batch, batch_idx) -> None:
104 | condition = None
105 | if self.is_conditioned:
106 | condition = self.autodecoder(torch.randint(0, self.autodecoder.N, ()))
107 | V, T = extract_level_set(self.geometry, self.dim, self.resolution, self.max_coord, self.device, condition=condition)
108 | fig = plot_trisurf(V, T)
109 | self.log("Reconstruction", wandb.Image(fig))
--------------------------------------------------------------------------------
/pygmi/utils/math/diffops.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from torch import Tensor
3 | from torch.autograd import grad
4 |
5 |
6 | def gradient(inputs: Tensor, outputs: Tensor, dim: int = 3) -> Tensor:
7 | """Computes the gradient of `outputs` wrt `inputs`. `inputs` must require grad
8 | and there must be a path from `outputs` to `inputs` in the computational graph.
9 |
10 | Parameters
11 | ----------
12 | inputs : Tensor
13 | List of input vectors. Shape `B_1 x ... x B_n x dim`
14 | outputs : Tensor
15 | List of output scalar values. Shape `B_1 x ... x B_n x 1`
16 | dim : int, optional
17 | Dimensionality of input vectors, by default 3
18 |
19 | Returns
20 | -------
21 | Tensor
22 | Point-wise gradient
23 | """
24 | d_points = torch.ones_like(outputs, requires_grad=False, device=outputs.device)
25 | points_grad = grad(
26 | outputs=outputs,
27 | inputs=inputs,
28 | grad_outputs=d_points,
29 | create_graph=True,
30 | retain_graph=True,
31 | only_inputs=True)
32 | return points_grad[0][..., :dim]
33 |
34 | def divergence(inputs: Tensor, outputs: Tensor, dim: int = 3) -> Tensor:
35 | """Computes the divergence of `outputs` wrt `inputs`. `inputs` must require grad
36 | and there must be a path from `outputs` to `inputs` in the computational graph.
37 |
38 | Parameters
39 | ----------
40 | inputs : Tensor
41 | List of input vectors. Shape `B_1 x ... x B_n x dim`
42 | outputs : Tensor
43 | List of output vectors. Shape `B_1 x ... x B_n x dim`
44 | dim : int, optional
45 | Dimensionality of input and output vectors, by default 3
46 |
47 | Returns
48 | -------
49 | Tensor
50 | Point-wise divergence
51 | """
52 |
53 | gradients = torch.zeros_like(outputs, dtype=torch.float, device=outputs.device)
54 | d_points = torch.ones((*outputs.shape[:-1], 1), requires_grad=False, device=outputs.device)
55 | for d in range(dim):
56 | gradients[..., d] = grad(
57 | outputs=outputs[..., d:d+1],
58 | inputs=inputs,
59 | grad_outputs=d_points,
60 | retain_graph=True,
61 | create_graph=True,
62 | only_inputs=True)[0][..., d]
63 | return gradients.sum(dim=-1, keepdim=True)
64 |
65 | def jacobian(inputs: Tensor, outputs: Tensor) -> Tensor:
66 | """Computes the Jacobian of `outputs` wrt `inputs`. `inputs` must require grad
67 | and there must be a path from `outputs` to `inputs` in the computational graph.
68 |
69 | Parameters
70 | ----------
71 | inputs : Tensor
72 | List of input vectors. Shape `B_1 x ... x B_n x dim`
73 | outputs : Tensor
74 | List of output vectors. Shape `B_1 x ... x B_n x dim`
75 |
76 | Returns
77 | -------
78 | Tensor
79 | Point-wise Jacobian
80 | """
81 | in_d = inputs.shape[-1]
82 | out_d = outputs.shape[-1]
83 | J = torch.zeros((*outputs.shape[:-1], in_d, out_d), dtype=torch.float, device=outputs.device)
84 | d_points = torch.ones((*outputs.shape[:-1], 1), requires_grad=False, device=outputs.device)
85 | for d in range(out_d):
86 | J[..., :, d] = grad(
87 | outputs=outputs[..., d:d+1],
88 | inputs=inputs,
89 | grad_outputs=d_points,
90 | retain_graph=True,
91 | create_graph=True,
92 | only_inputs=True)[0]
93 | return J
94 |
95 | def hessian(inputs: Tensor, outputs: Tensor, dim: int = 3, diff: bool = True) -> Tensor:
96 | """Computes the Hessian of `outputs` wrt `inputs` as the Jacobian of the gradient.
97 | `inputs` must require grad and there must be a path from `outputs` to `inputs`
98 | in the computational graph.
99 |
100 | Parameters
101 | ----------
102 | inputs : Tensor
103 | List of input vectors. Shape `B_1 x ... x B_n x dim`
104 | outputs : Tensor
105 | List of output scalar values. Shape `B_1 x ... x B_n x 1`
106 | dim : int, optional
107 | Dimensionality of input points, by default 3
108 | diff: bool, optional
109 | Whether the return value should be differentiable, by default True
110 |
111 | Returns
112 | -------
113 | Tensor
114 | Point-wise Hessian
115 | """
116 | H = torch.zeros((*outputs.shape[:-1], dim, dim), dtype=torch.float, device=outputs.device)
117 | G = gradient(inputs, outputs, dim=dim).view_as(inputs) # .squeeze()
118 | d_points = torch.ones_like(outputs, requires_grad=False)
119 | for i in range(dim): # Gradient of gradient in each dimension
120 | H[..., i, :] = torch.autograd.grad(
121 | outputs=G[..., i:i+1],
122 | inputs=inputs,
123 | create_graph=diff,
124 | retain_graph=True,
125 | grad_outputs=d_points,
126 | only_inputs=True
127 | )[0]
128 | return H
129 |
--------------------------------------------------------------------------------
/pygmi/nn/encoder.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch_geometric.nn as gnn
4 | from torch import Tensor
5 | from typing import List, Tuple
6 |
7 |
8 |
9 | class Autodecoder(nn.Module):
10 |
11 | def __init__(self, num_data_pts: int, latent_dim: int, sigma: float = 0.0):
12 | """Creates an Autodecoder, as proposed in https://arxiv.org/abs/1901.05103.
13 |
14 | Parameters
15 | ----------
16 | num_data_pts : int
17 | Number of data points to represent (= # latent vectors)
18 | latent_dim : int
19 | Dimensionality of optimized latent vectors
20 | sigma : float
21 | stddev of initial distribution
22 | """
23 | super(Autodecoder, self).__init__()
24 | self.num_vectors = num_data_pts
25 | self.latent_dim = latent_dim
26 | self.init_sigma = sigma
27 | self.vectors = nn.parameter.Parameter(
28 | torch.randn((num_data_pts, latent_dim)) * sigma)
29 |
30 | def forward(self, idx: Tensor) -> Tensor:
31 | return self.vectors[idx, :]
32 |
33 |
34 | ### PointNet++ ###
35 |
36 | class PointNet2Layer(nn.Module):
37 |
38 | def __init__(self, point_filter: nn.Module, radius: float, density: float, set_filter: nn.Module = None):
39 | """A PointNet++ layer, performing radius aggregation over a
40 | percentage of input points.
41 |
42 | Parameters
43 | ----------
44 | point_filter : nn.Module
45 | Point-wise MLP processing point features and coordinates
46 | radius : float
47 | Maximum distance of neighbors of each pivot point
48 | density : float
49 | Fraction of pivot points over given input point samples
50 | set_filter : nn.Module, optional
51 | Point-wise MLP processing point features and coordinates after aggregation, by default None
52 | """
53 | super(PointNet2Layer, self).__init__()
54 |
55 | self.rad = radius
56 | self.density = density
57 | self.conv = gnn.PointNetConv(point_filter, set_filter, False)
58 | self.do_set_filter = set_filter is not None
59 |
60 | def forward(self, pos: Tensor, batch: Tensor, x: Tensor = None) -> Tuple[Tensor]:
61 | """Performs PointNet++ convolution over input.
62 |
63 | Parameters
64 | ----------
65 | pos : Tensor
66 | Point coordinates, shape `N x D`
67 | batch : Tensor
68 | Batch tensor, shape `N x 1`, batch size = `max(batch)`
69 | x : Tensor, optional
70 | Point features, shape `N x F`
71 |
72 | Returns
73 | -------
74 | Tuple[Tensor]
75 | Pivot points coordinates, processed features, and batch tensor
76 | """
77 | centr_idx = gnn.fps(pos, batch, ratio=self.density)
78 | centroids, centr_batch = pos[centr_idx], batch[centr_idx]
79 | row, col = gnn.radius(pos, centroids, self.rad, batch, centr_batch, max_num_neighbors=64)
80 | centr_x = None if x is None else x[centr_idx]
81 | out = self.conv((x, centr_x), (pos, centroids), torch.stack([col, row]))
82 | return centroids, out, centr_batch
83 |
84 |
85 | class PointNet2Encoder(nn.Module):
86 |
87 | def __init__(
88 | self,
89 | density: List[float],
90 | radius: List[float],
91 | pf_size: List[List[int]],
92 | sf_size: List[List[int]] = None
93 | ):
94 | """Creates a PointNet++ encoder, mapping point clouds to n-dimensional vectors.
95 |
96 | Parameters
97 | ----------
98 | density : List[float]
99 | Fraction of pivot points over input sample for each layer
100 | radius : List[float]
101 | Maximum distance of neighbors of each pivot point for each layer
102 | pf_size : List[List[int]]
103 | Layer dimensions of MLP point filters for each layers
104 | sf_size : List[List[int]], optional
105 | Layer dimensions of MLP set filters for each layers, by default None
106 | """
107 | super(PointNet2Encoder, self).__init__()
108 |
109 | num_layers = len(density)
110 | self.layers = nn.ModuleList()
111 | do_set_filtering = sf_size is not None
112 | for l in range(num_layers):
113 | pf = gnn.MLP(pf_size[l])
114 | sf = gnn.MLP(sf_size[l]) if do_set_filtering else None
115 | layer = PointNet2Layer(pf, radius[l], density[l], sf)
116 | self.layers.append(layer)
117 |
118 | def forward(self, pos: Tensor, batch: Tensor, x: Tensor = None) -> Tensor:
119 | """Encodes a batch of point clouds.
120 |
121 | Parameters
122 | ----------
123 | pos : Tensor
124 | Point coordinates, shape `N x D`
125 | batch : Tensor
126 | Batch tensor, shape `N x 1`, batch size = `max(batch)`
127 | x : Tensor, optional
128 | Point features, shape `N x F`
129 |
130 | Returns
131 | -------
132 | Tensor
133 | Latent vectors for each input point cloud, shape `N x L`
134 | """
135 | p, b, x = pos, batch, x
136 | for layer in self.layers:
137 | p, x, b = layer(p, b, x)
138 | z = gnn.global_max_pool(x, b)
139 | return z
--------------------------------------------------------------------------------
/pygmi/nn/siren.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import numpy as np
4 | from torch import Tensor
5 |
6 |
7 | ### Adapted from official Siren implementation https://github.com/vsitzmann/siren ###
8 |
9 | def first_layer_sine_init(m: nn.Module) -> None:
10 | """Special first layer initialization for Sine-activate MLPs.
11 |
12 | Parameters
13 | ----------
14 | m : nn.Module
15 | Linear layer to initialize
16 | """
17 | with torch.no_grad():
18 | if hasattr(m, 'weight'):
19 | num_input = m.weight.size(-1)
20 | nn.init.uniform_(m.weight, -1 / num_input, 1 / num_input)
21 |
22 |
23 | def sine_init(m: nn.Module, w0: float = None) -> None:
24 | """Special initialization for layers of Sine-activated MLPs.
25 |
26 | Parameters
27 | ----------
28 | m : nn.Module
29 | Linear layer to initialize
30 | w0 : float, optional
31 | Phase factor which can be leveraged in initialization, by default None
32 | """
33 | with torch.no_grad():
34 | if hasattr(m, 'weight'):
35 | num_input = m.weight.size(-1)
36 | if w0 is None:
37 | nn.init.uniform_(m.weight, -np.sqrt(6 / num_input), np.sqrt(6 / num_input))
38 | else:
39 | nn.init.uniform_(m.weight, -np.sqrt(6 / (num_input * (w0 ** 2))), np.sqrt(6 / (num_input * (w0 ** 2))))
40 |
41 |
42 | class Sine(nn.Module):
43 |
44 | def __init__(self, w0: float):
45 | """Initializes a Sine activation function with phase factor `w0`
46 |
47 | Parameters
48 | ----------
49 | w0 : float
50 | Phase factor
51 | """
52 | super(Sine, self).__init__()
53 | self.w = w0
54 |
55 | def forward(self, input: Tensor) -> Tensor:
56 | """Runs Sine activation function over `input`
57 |
58 | Parameters
59 | ----------
60 | input : Tensor
61 | A (partially processed) batch of data points
62 |
63 | Returns
64 | -------
65 | Tensor
66 | Point-wise sine of the scalar product of `self.w` (phase factor) and `input`
67 | """
68 | return torch.sin(self.w * input)
69 |
70 |
71 | class SirenMLP(nn.Module):
72 |
73 | def __init__(
74 | self,
75 | in_dim: int,
76 | out_dim: int,
77 | hidden_dim: int,
78 | hidden_layers: int,
79 | w0: float,
80 | init_w0: float,
81 | use_first_layer_init: bool,
82 | w0_in_layer_init: bool
83 | ):
84 | """Creates as fully-configurable Siren MLP as presented in https://arxiv.org/abs/2006.09661.
85 |
86 |
87 | Parameters
88 | ----------
89 | in_dim : int
90 | Number of input features
91 | out_dim : int
92 | Number of output features
93 | hidden_dim : int
94 | Hidden dimension, same for all layers
95 | hidden_layers : int
96 | Number of hidden layers
97 | w0 : float
98 | Sine phase amplification factor (layers 2+)
99 | init_w0 : float
100 | Sine phase amplification factor (layer 1)
101 | use_first_layer_init : bool
102 | Use a special initialization for first layer weights
103 | w0_in_layer_init : bool
104 | Leverage w0 in layer initialization, as proposed in Siren supmat
105 | """
106 | super(SirenMLP, self).__init__()
107 |
108 | self.init_w0, self.w0 = init_w0, w0
109 | self.init_actvn, self.actvn = Sine(self.init_w0), Sine(self.w0)
110 |
111 | self.net = nn.ModuleList()
112 | self.net.append(nn.Linear(in_dim, hidden_dim))
113 |
114 | if use_first_layer_init:
115 | first_layer_sine_init(self.net[-1])
116 | else:
117 | w = self.init_w0 if w0_in_layer_init else None
118 | sine_init(self.net[-1], w)
119 |
120 | w = self.w0 if w0_in_layer_init else None
121 | for i in range(hidden_layers):
122 | self.net.append(nn.Linear(hidden_dim, hidden_dim))
123 | sine_init(self.net[-1], w)
124 | self.net.append(nn.Linear(hidden_dim, out_dim))
125 | sine_init(self.net[-1], w)
126 |
127 | def forward(self, x_in: Tensor) -> Tensor:
128 | """Runs the model over a sample of points.
129 |
130 | Parameters
131 | ----------
132 | x_in : Tensor
133 | Sample of points, shape `B_1 x ... x B_n x I`
134 |
135 | Returns
136 | -------
137 | Tensor
138 | Output for each point, shape `B_1 x ... x B_n x O`
139 | """
140 | h = self.init_actvn(self.net[0](x_in))
141 | for layer in self.net[1:-1]:
142 | h = self.actvn(layer(h))
143 | h = self.net[-1](h)
144 | return h
145 |
146 |
147 | class SirenSDF(SirenMLP):
148 |
149 | def __init__(
150 | self,
151 | in_dim: int = 3,
152 | hidden_dim: int = 256,
153 | hidden_layers: int = 5,
154 | use_first_layer_init: bool = False,
155 | w0_in_layer_init: bool = True
156 | ):
157 | """Preconfigured Siren MLP for SDF tasks. w0 is fixed to 30 as motivated
158 | in original paper. Parameter defaults are as in original implementation.
159 |
160 | Parameters
161 | ----------
162 | in_dim : int, optional
163 | Number of input features, by default 3
164 | hidden_dim : int, optional
165 | Hidden dimension, same for all layers, by default 256
166 | hidden_layers : int, optional
167 | Number of hidden layers, by default 5
168 | use_first_layer_init : bool, optional
169 | Use a special initialization for first layer weights, by default False
170 | w0_in_layer_init : bool, optional
171 | Leverage w0 in layer initialization, by default True
172 | """
173 | super(SirenSDF, self).__init__(
174 | in_dim, 1, hidden_dim, hidden_layers, 30.0, 30.0, use_first_layer_init, w0_in_layer_init
175 | )
--------------------------------------------------------------------------------
/pygmi/tasks/distance_eikonal_ivp.py:
--------------------------------------------------------------------------------
1 | import wandb
2 | import torch
3 | import torch.nn.functional as F
4 | import pygmi.utils.math.diffops as diffops
5 | from torch import Tensor
6 | from typing import List
7 | from pygmi.tasks import TaskBaseModule
8 | from pygmi.types import SDF
9 | from pygmi.utils.extract import extract_level_set
10 | from pygmi.utils.visual import plot_trisurf
11 | from pygmi.nn.encoder import Autodecoder
12 |
13 |
14 |
15 | class EikonalIVPOptimization(TaskBaseModule):
16 |
17 | def __init__(
18 | self,
19 | sdf_functional: SDF,
20 | num_shapes: int = 1,
21 | condition_size: int = 256,
22 | lr_sdf: float = 5e-4,
23 | lr_autodec: float = 1e-3,
24 | lr_sched_step: int = 2000,
25 | lr_sched_gamma: float = 0.5,
26 | surf_loss_w: float = 3e3,
27 | eikonal_loss_w: float = 5e1,
28 | norm_loss_w: float = 1e2,
29 | zero_penalty_w: float = 1e2,
30 | zero_penalty_a: float = -1e2,
31 | latent_loss_w: float = 1e-3,
32 | plot_resolution: int = 100,
33 | plot_max_coord: float = 1.0
34 | ):
35 | """Instantiates an `EikonalIVPOptimization` task. This task reconstructs geometry
36 | from a point cloud by requiring the SDF to vanish on zero-level set points and to
37 | have unitary norm of gradient (the SDF needs to support 2nd order derivatives).
38 | Optionally, normal constraint (gradient at surface points equals normals) and
39 | zero-value penalty (no small function values far away from surface) can be optimized for.
40 |
41 | Parameters
42 | ----------
43 | sdf_functional : SDF
44 | Tensor functional representing a signed distance function
45 | num_shapes : int, optional
46 | Support for multi-shape optimization, by default 1
47 | condition_size : int, optional
48 | Dimension of latent vectors for multi-shape optimization, by default 256
49 | lr_sdf : float, optional
50 | Learning rate for SDF optimization, by default 5e-4
51 | lr_autodec : float, optional
52 | Learning rate for latent vectors optimization, by default 1e-3
53 | lr_sched_step : int, optional
54 | Step LR scheduler - size of steps, by default 2000
55 | lr_sched_gamma : float, optional
56 | Step LR scheduler - decay factor, by default 0.5
57 | surf_loss_w : float, optional
58 | Weight of zero level set loss, by default 1.0
59 | eikonal_loss_w : float, optional
60 | Weight of eikonal loss, by default 1e-2
61 | norm_loss_w : float, optional
62 | Weight of normal loss, by default 1.0
63 | zero_penalty_w : float, optional
64 | Weight of zero value penalty, by default 1e-1
65 | zero_penalty_a : float, optional
66 | Alpha of zero value penalty, by default 1e2
67 | latent_loss_w : float, optional
68 | Weight of zero-mean constraint for latent vectors, by default 1e-3
69 | plot_resolution : int, optional
70 | Grid resolution of mesh extraction for plots, by default 100
71 | plot_max_coord : float, optional
72 | Maximum absolute coordinate of plot figures, by default 1.0
73 | """
74 | super(EikonalIVPOptimization, self).__init__(sdf_functional)
75 | self.dim = self.geometry.dim
76 | self.lr_sdf = lr_sdf
77 | self.scheduler_step = lr_sched_step
78 | self.gamma = lr_sched_gamma
79 | self.surf_loss_w = surf_loss_w
80 | self.eikonal_loss_w = eikonal_loss_w
81 | self.norm_loss_w = norm_loss_w
82 | self.zero_penalty_w = zero_penalty_w
83 | self.zero_penalty_a = zero_penalty_a
84 | self.latent_loss_w = latent_loss_w
85 | self.resolution = plot_resolution
86 | self.max_coord = plot_max_coord
87 | self.is_conditioned = False
88 | if num_shapes > 1:
89 | self.autodecoder = Autodecoder(num_shapes, condition_size)
90 | self.is_conditioned = True
91 | self.lr_autodec = lr_autodec
92 |
93 | def configure_optimizers(self) -> List:
94 | opt_params = [{'params': self.geometry.parameters(), 'lr': self.lr_sdf}]
95 | if self.is_conditioned:
96 | opt_params.append({'params': self.autodecoder.parameters(), 'lr': self.lr_autodec})
97 | optimizer = torch.optim.Adam(opt_params)
98 | if self.scheduler_step is None or self.gamma is None:
99 | return optimizer
100 | scheduler = torch.optim.lr_scheduler.StepLR(optimizer, self.scheduler_step, self.gamma)
101 | return [optimizer], [scheduler]
102 |
103 | def training_step(self, batch, batch_idx) -> Tensor:
104 | indices, surf_sample, norm_sample, space_sample = batch
105 |
106 | condition = None
107 | latent_loss = 0.0
108 | if self.is_conditioned:
109 | condition = self.autodecoder(indices)
110 | if self.latent_loss_w > 0:
111 | latent_loss = self.latent_loss_w * condition.norm(dim=-1).mean()
112 |
113 | x_surf = surf_sample.requires_grad_()
114 | x_space = space_sample.requires_grad_()
115 |
116 | surf_dist = self.geometry(x_surf, condition).view(*(x_surf.shape[:-1]), 1)
117 | space_dist = self.geometry(x_space, condition)
118 |
119 | surf_loss = 0.0
120 | if self.surf_loss_w > 0:
121 | surf_loss = self.surf_loss_w * surf_dist.abs().mean()
122 |
123 | eikonal_loss = 0.0
124 | if self.eikonal_loss_w > 0:
125 | grad = diffops.gradient(x_space, space_dist, self.dim)
126 | eikonal_loss = self.eikonal_loss_w * ((grad.norm(dim=-1) - 1).abs()).mean()
127 |
128 | norm_loss = 0.0
129 | if self.norm_loss_w > 0:
130 | grad = diffops.gradient(x_surf, surf_dist, self.dim)
131 | norm_loss = self.norm_loss_w * (1 - F.cosine_similarity(grad, norm_sample, dim=-1)).mean()
132 |
133 | zero_penalty = 0.0
134 | if self.zero_penalty_w > 0:
135 | zero_penalty = self.zero_penalty_w * torch.exp(self.zero_penalty_a * torch.abs(space_dist)).mean()
136 |
137 | loss = surf_loss + eikonal_loss + norm_loss + zero_penalty + latent_loss
138 | self.log("loss", loss)
139 | self.log("surf_loss", surf_loss)
140 | self.log("eikonal_loss", eikonal_loss)
141 | self.log("norm_loss", norm_loss)
142 | self.log("zero_penalty", zero_penalty)
143 | self.log("latent_loss", latent_loss)
144 | return loss
145 |
146 | def validation_step(self, batch, batch_idx) -> None:
147 | condition = None
148 | if self.is_conditioned:
149 | condition = self.autodecoder(torch.randint(0, self.autodecoder.N, ()))
150 | V, T = extract_level_set(self.geometry, self.dim, self.resolution, self.max_coord, self.device, condition=condition)
151 | fig = plot_trisurf(V, T)
152 | self.log("Reconstruction", wandb.Image(fig))
--------------------------------------------------------------------------------
/pygmi/utils/visual/core.py:
--------------------------------------------------------------------------------
1 | import functools
2 | import plotly.graph_objects as go
3 | import pygmi.utils.extract
4 | from torch import Tensor
5 | from numpy import ndarray
6 | from plotly.subplots import make_subplots
7 | from typing import Callable, Dict, Tuple, Union
8 | from pygmi.utils import label_to_interval
9 |
10 |
11 | def validate_figure(func: Callable):
12 | """Decorator allowing to call plotting functions without
13 | passing a Figure - it is automatically created, passed to
14 | the plotting function and returned by the decorator.
15 |
16 | Parameters
17 | ----------
18 | func : Callable
19 | A plotting function from ngt.utils.visual
20 | """
21 | @functools.wraps(func)
22 | def wrapper(*args, **kwargs):
23 | newargs = args
24 | if 'fig' not in kwargs.keys():
25 | ffig = None
26 | newargs = []
27 | for arg in args:
28 | if type(arg) == go.Figure():
29 | ffig = arg
30 | else:
31 | newargs.append(arg)
32 | kwargs['fig'] = go.Figure() if ffig is None else ffig
33 | func(*newargs, **kwargs)
34 | return kwargs['fig']
35 | return wrapper
36 |
37 | def make_3d_subplots(rows: int = 1, cols: int = 1) -> go.Figure:
38 | """Creates a plotly Figure with 3D subplots.
39 |
40 | Parameters
41 | ----------
42 | rows : int, optional
43 | Number of rows in subplot grid, by default 1
44 | cols : int, optional
45 | Number of columns in subplot grid, by default 1
46 |
47 | Returns
48 | -------
49 | go.Figure
50 | Plotly Figure containing the subplots
51 | """
52 | return make_subplots(
53 | rows, cols, specs=[[{'type': 'surface'}] * cols] * rows
54 | )
55 |
56 | @validate_figure
57 | def plot_trisurf(
58 | vert: Union[Tensor, ndarray],
59 | triv: Union[Tensor, ndarray],
60 | fig: go.Figure = None
61 | ) -> go.Figure:
62 | """Plots a 3D mesh.
63 |
64 | Parameters
65 | ----------
66 | vert : Union[Tensor, ndarray]
67 | Vertices of the mesh
68 | triv : Union[Tensor, ndarray]
69 | Triangles of the mesh
70 | fig : go.Figure, optional
71 | Figure to append plot to, by default None
72 |
73 | Returns
74 | -------
75 | go.Figure
76 | Either `fig` or a new `go.Figure` containing the plot
77 | """
78 | fig.add_trace(
79 | go.Mesh3d(
80 | x=vert[:, 0], y=vert[:, 1], z=vert[:, 2],
81 | i=triv[:, 0], j=triv[:, 1], k=triv[:, 2]
82 | )
83 | )
84 |
85 | @validate_figure
86 | def plot_isosurfaces(
87 | grid_coords: Union[Tensor, ndarray],
88 | F: Union[Tensor, ndarray],
89 | min_level: float = -0.5,
90 | max_level: float = 0.5,
91 | num_surfs: int = 3,
92 | fig: go.Figure = None
93 | ) -> go.Figure:
94 | """Plots multiple isosurfaces extracted from an implicit function.
95 |
96 | Parameters
97 | ----------
98 | grid_coords : Union[Tensor, ndarray]
99 | Point coordinates of the grid
100 | F : Union[Tensor, ndarray]
101 | Implicit function evaluated on `grid_coords`
102 | min_level : float, optional
103 | Minimum function level, by default -0.5
104 | max_level : float, optional
105 | Maximum function level, by default 0.5
106 | num_surfs : int, optional
107 | Number of isosurfaces to extract, with linearly spaced levels
108 | between `min_level` and `max_level`, by default 3
109 | fig : go.Figure, optional
110 | Figure to append plot to, by default None
111 |
112 | Returns
113 | -------
114 | go.Figure
115 | Either `fig` or a new `go.Figure` containing the plot
116 | """
117 | fig.add_trace(go.Volume(
118 | x=grid_coords[:, 0],
119 | y=grid_coords[:, 1],
120 | z=grid_coords[:, 2],
121 | value=F,
122 | isomin=min_level,
123 | max_level=max_level,
124 | surface_count=num_surfs,
125 | opacity=0.1
126 | ))
127 |
128 | @validate_figure
129 | def isosurf_animation(
130 | F_volume: Union[Tensor, ndarray],
131 | min_level: float = -0.5,
132 | max_level: float = 0.5,
133 | axes: Tuple[float] = (-1.0, 1.0),
134 | steps: int = 3,
135 | fig: go.Figure = None
136 | ) -> go.Figure:
137 | """Plots an animated figure allowing to singularly inspect level surfaces
138 | of any given implicit function.
139 |
140 | Parameters
141 | ----------
142 | F_volume : Union[Tensor, ndarray]
143 | `N x N x N` tensor containing function values
144 | min_level : float, optional
145 | Minimum surface level, by default -0.5
146 | max_level : float, optional
147 | Maximum surface level, by default 0.5
148 | steps : int, optional
149 | Number of linear steps between `min_level` and `max_level`, by default 3
150 | fig : go.Figure, optional
151 | Figure to append plot to, by default None
152 |
153 | Returns
154 | -------
155 | go.Figure
156 | Either `fig` or a new `go.Figure` containing the plot
157 | """
158 | frames = []
159 | space_size = axes[1] - axes[0]
160 | voxel_size = (space_size) / (F_volume.shape[0] - 1)
161 | for s in range(steps):
162 | t = label_to_interval(s, min_level, max_level, steps)
163 | V, T = pygmi.utils.extract.marching_cubes(F_volume, voxel_size, t)
164 | V -= (space_size) / 2
165 | if s == 0:
166 | fig.add_trace(go.Mesh3d(x=V[:, 0], y=V[:, 1], z=V[:, 2], i=T[:, 0], j=T[:, 1], k=T[:, 2]))
167 | frames.append(go.Frame(
168 | data=go.Mesh3d(x=V[:, 0], y=V[:, 1], z=V[:, 2], i=T[:, 0], j=T[:, 1], k=T[:, 2]),
169 | name='{:1.3f}-lvl set'.format(label_to_interval(s, min_level, max_level, steps)), traces=[0]))
170 | fig.update(frames=frames)
171 |
172 | def frame_args(duration: float) -> Dict:
173 | return {
174 | "frame": {"duration": duration},
175 | "mode": "immediate",
176 | "fromcurrent": True,
177 | "transition": {"duration": duration, "easing": "linear"},
178 | }
179 | sliders = [
180 | dict(
181 | pad={"b": 10, "t": 60},
182 | len=0.9,
183 | x=0.1,
184 | y=0,
185 | steps=[
186 | dict(
187 | method='animate',
188 | label='{:1.3f}-lvl set'.format(label_to_interval(k, min_level, max_level, steps)),
189 | args=[[f.name], frame_args(0)]
190 | ) for k, f in enumerate(fig.frames)
191 | ],
192 | )
193 | ]
194 | fig.update_layout(
195 | title='Level sets animation',
196 | width=600,
197 | height=600,
198 | scene=dict(
199 | zaxis=dict(range=[axes[0], axes[1]], autorange=False),
200 | yaxis=dict(range=[axes[0], axes[1]], autorange=False),
201 | xaxis=dict(range=[axes[0], axes[1]], autorange=False)
202 | ),
203 | updatemenus = [
204 | {
205 | "buttons": [
206 | {
207 | "args": [None, frame_args(50)],
208 | "label": "▶", # play symbol
209 | "method": "animate",
210 | },
211 | {
212 | "args": [[None], frame_args(0)],
213 | "label": "◼", # pause symbol
214 | "method": "animate",
215 | },
216 | ],
217 | "direction": "left",
218 | "pad": {"r": 10, "t": 70},
219 | "type": "buttons",
220 | "x": 0.1,
221 | "y": 0,
222 | }
223 | ],
224 | sliders=sliders
225 | )
226 |
--------------------------------------------------------------------------------
/pygmi/data/dataset/core.py:
--------------------------------------------------------------------------------
1 | import re
2 | import random
3 | import pytorch_lightning as pl
4 | import pygmi.data.sources
5 | import pygmi.data.preprocess
6 | from torch.utils.data import DataLoader
7 | from typing import Optional, List, Dict, Tuple, Any
8 | from pygmi.data.preprocess import gather_fnames, process_source
9 | from pygmi.utils.files import validate_fnames, mkdir_ifnotexists
10 |
11 |
12 |
13 |
14 | class _ListWithIndices(list):
15 |
16 | def __init__(self):
17 | """Initializes a subclass of list which returns objects and their indices.
18 | """
19 | super(_ListWithIndices, self).__init__()
20 |
21 | def __getitem__(self, idx: int) -> Tuple[Any, int]:
22 | """Overrides the List __getitem__ to return the index along with the object.
23 |
24 | Parameters
25 | ----------
26 | idx : int
27 | Index of objects to retrieve
28 |
29 | Returns
30 | -------
31 | Tuple[Any, int]
32 | Retrieved object and index
33 | """
34 | return super(_ListWithIndices, self).__getitem__(idx), idx
35 |
36 |
37 |
38 | class MultiSourceData(pl.LightningDataModule):
39 |
40 | def __init__(
41 | self,
42 | train_source_conf: List[Dict] = [],
43 | test_source_conf: List[Dict] = [],
44 | preprocessing_conf: Dict = {},
45 | batch_size: Dict[str, int] = {'train': 1, 'val': 1, 'test': 1},
46 | val_split: float = 0.0
47 | ):
48 | """Generic multi-source data module. Should be subclassed to define
49 | custom behaviour for collecting preprocessed data into batches.
50 |
51 | Parameters
52 | ----------
53 | train_source_conf : List[Dict], optional
54 | List of configurations for multiple data sources. Each should specify a type
55 | (i.e. a subclass of ngt.data.sources.core.DataSource), and a configuration in
56 | dict format depending on the source type (see ngt.data.sources), by default []
57 | test_source_conf : List[Dict], optional
58 | List of configurations for multiple data sources, by default []
59 | preprocessing_conf : Dict, optional
60 | Configuration for preprocessing procedure for the selected data sources, by default {}
61 | batch_size : Dict[str, int], optional
62 | Batch size for train, test, val. Expects keys: {"train", "val", "test"},
63 | by default {'train': 1, 'val': 1, 'test': 1}
64 | val_split : float, optional
65 | Fraction of training data serving for validation, by default 0.0
66 | """
67 | super(MultiSourceData, self).__init__()
68 | self.train = train_source_conf
69 | self.test = test_source_conf
70 | self.preproc_conf = preprocessing_conf
71 | if 'script' in self.preproc_conf.keys():
72 | self.preproc_fn = getattr(pygmi.data.preprocess, self.preproc_conf['script'])
73 | else:
74 | self.preproc_fn = None
75 | self.train_paths = _ListWithIndices()
76 | self.val_paths = _ListWithIndices()
77 | self.test_paths = _ListWithIndices()
78 | self.val_split = val_split
79 | self.batch_size = batch_size
80 |
81 | def setup(self, stage: Optional[str] = None) -> None:
82 |
83 | if stage == 'fit' or stage is None:
84 | for conf in self.train:
85 | source = getattr(pygmi.data.sources, conf['type'])(**conf['source_conf'])
86 | sname = '_'.join(re.split('/|\\\\', conf['source_conf']['source']))
87 | fnames = sorted(gather_fnames(self.preproc_conf['out_dir'], sname, len(source)))
88 | mkdir_ifnotexists(self.preproc_conf['out_dir'])
89 | if self.preproc_conf['do_preprocessing']:
90 | process_source(source, fnames, self.preproc_fn, self.preproc_conf['conf'])
91 | else:
92 | if not validate_fnames(fnames) or len(fnames) == 0:
93 | raise RuntimeError('Processed files missing with preprocessing disabled.')
94 | self.train_paths += fnames
95 |
96 | n_val = int(len(self.train_paths) * self.val_split)
97 | val_idxs = random.sample(range(len(self.train_paths)), n_val)
98 | self.val_paths += [self.train_paths[i] for i in val_idxs]
99 | for i in val_idxs:
100 | self.train_paths.pop(i)
101 |
102 | if stage == 'test' or stage is None:
103 | for conf in self.test:
104 | source = getattr(pygmi.data.sources, conf['type'])(**conf['source_conf'])
105 | sname = '_'.join(re.split('/|\\', conf['source_conf']['source'].replace('/', '_')))
106 | fnames = sorted(gather_fnames(self.preproc_conf['out_dir'], sname, len(source)))
107 | if self.preproc_conf['do_preprocessing']:
108 | process_source(source, self.preproc_fn, fnames, self.preproc_conf['conf'])
109 | else:
110 | if not validate_fnames(fnames):
111 | raise RuntimeError('Processed files missing with preprocessing disabled.')
112 | self.train_paths += fnames
113 |
114 | def collate(self, data: List[Any], idxs: List[int]) -> Any:
115 | """Users should override this method to define how to put
116 | several data points in batch form.
117 |
118 | Parameters
119 | ----------
120 | data : List[Any]
121 | List of data points and their indices in the dataset
122 | idxs : List[int]
123 | Indices of `data` in the dataset
124 |
125 | Returns
126 | -------
127 | Any
128 | Data points in batch form, ready for usage in train/val/test loops
129 | (will be returned when iterating on the DataLoader)
130 |
131 | Raises
132 | ------
133 | NotImplementedError
134 | Has to be implemented in subclasses
135 | """
136 | raise NotImplementedError()
137 |
138 | def load_data_point(self, path: str) -> Any:
139 | """Users should override this method to define how data points
140 | are loaded from disk into Python objects.
141 |
142 | Parameters
143 | ----------
144 | path : str
145 | A path to a data point stored on disk.
146 |
147 | Returns
148 | -------
149 | Any
150 | The Python object storing the loaded data point
151 |
152 | Raises
153 | ------
154 | NotImplementedError
155 | Has to be implemented in subclasses
156 | """
157 | raise NotImplementedError()
158 |
159 | def load_and_collate(self, paths: List[Tuple[str, int]]) -> Any:
160 | """Collate function for DataLoaders, useful for datasets stored on
161 | disk and accessed on demand. Loads each given path and returns the
162 | batch of data points.
163 |
164 | Parameters
165 | ----------
166 | paths : List[Tuple[str, int]]
167 | A list of filepaths and the indices in the dataset of their corresponding
168 | data points
169 |
170 | Returns
171 | -------
172 | Any
173 | Data points in batch form, ready for usage in train/val/test loops
174 | (will be returned when iterating on the DataLoader)
175 |
176 | """
177 | loaded = [self.load_data_point(p[0]) for p in paths]
178 | collated = self.collate(loaded, [p[1] for p in paths])
179 | return collated
180 |
181 | def train_dataloader(self) -> DataLoader:
182 | return DataLoader(self.train_paths, self.batch_size['train'], shuffle=True, collate_fn=self.load_and_collate)
183 |
184 | def val_dataloader(self) -> DataLoader:
185 | return DataLoader(self.val_paths, self.batch_size['val'], collate_fn=self.load_and_collate)
186 |
187 | def test_dataloader(self) -> DataLoader:
188 | return DataLoader(self.test_paths, self.batch_size['test'], collate_fn=self.load_and_collate)
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PyGMI
2 |
3 | Following the recent trends in geometric deep learning, we release PyTorch Geometric Implicit (PyGMI): a toolbox to facilitate operating with neural implicit geometric representations.
4 |
5 | # Installation
6 |
7 | **We recommend to install in a Python environment with a working PyTorch (>= 1.8.0) installation**. If PyTorch is not found, the installer will automatically pick a minimal CPU installation. To install PyGMI, download this repository, cd to top level folder, and run:
8 | ```
9 | pip install --extra-index-url=https://test.pypi.org/simple/ .
10 | ```
11 | This will install PyGMI, along with several other dependencies, to the current shell's Python directory. We advise to do this in a virtual environment.
12 |
13 | ## Additional dependencies
14 |
15 | Our setup script will run additional silent `pip install`s for PyTorch Geometric and its dependencies, if it is not found in the installation environment. If you do not wish to run these code lines, set the environment variable `PYGMI_NO_ADD_DEPS` to `1`. Then, to install PyTorch Geometric, we refer to [the library's documentation](https://pytorch-geometric.readthedocs.io/en/latest/notes/installation.html), but we advise to run the simple install procedure with conda:
16 | ```
17 | conda install pyg -c pyg
18 | ```
19 | which will auto-detect your torch and cuda versions.
20 |
21 |
22 |
23 | # Usage
24 |
25 | Besides a vast utility library spanning from volume rendering to batched differential operations, PyGMI features the following modules:
26 |
27 | * `pygmi.nn`: a torch-based collection of popularly used neural network models in the field
28 | * `pygmi.types`: an object-oriented interface to represent implicit functions
29 | * `pygmi.data`: a data utility interface which allows to load data from heterogenous sources and run preprocessing algorithms
30 | * `pygmi.tasks`: a collection of out-of-the-box PyTorch Lightning Modules allowing to quickly solve popular implicit geometry tasks
31 |
32 | We document each submodule individually.
33 |
34 | ## Neural Networks
35 |
36 | Just a collection of `torch.nn.Module`s. It features popular neural architectures used in neural implicit geometry. Most objects in this module can be initialized without constructor parameters: they will take as defaults the values shown in the original paper/implementation. SDF nets have fixed output dimension 1 and default input dimension 3. A comprehensive list:
37 |
38 | * `DeepReLUSDFNet`: An 8-layer MLP with 512 hidden units, ReLU activation, spherical weight initialization and skip connection at layer 4.
39 | * `SmoothDeepSDFNet`: An 8-layer MLP with 512 hidden units, SoftPlus activation, spherical weight initialization and skip connection at layer 4.
40 | * `SirenMLP`: Siren (sine-activated MLP) networks base class. __This is general purpose and has no defaults__. The `w_0` constant is set to 30 as motivated in original paper.
41 | * `SirenSDF`: A 5-layer MLP with 256 hidden units, Sine activation with phase `w_0=30`, and sine weight initialization.
42 | * `NeRFMLP` (and others): **To be released!**
43 |
44 | As an additional features, we include implementations of simple shape encoding architectures.
45 |
46 | * `Autodecoder`: a collection of trainable latent vectors, one for each data point.
47 | * `PointNet2Encoder`: a convenient implementation of PointNet++. Uses farthest point sampling for choosing pivots and radius clustering for convolution.
48 |
49 |
50 | ## Data Pipeline
51 |
52 | The data interface is completely optional to basic PyGMI usage, but it is applied in our pre-implemented Tasks. We mainly developed it for the common need of integrating data from multiple homogenous data sources (e.g. multiple 3D shape datasets). At the moment, our data pipeline only supports in-memory datasets (i.e. data which is preprocessed, stored on disk and loaded on-demand).
53 |
54 | While we suggest to follow the usage showed in `examples/`, a simple `pygmi.data` use case can be described as follows:
55 |
56 | 1. Select any number of data sources, each with its type (must be a class name in `pyg.data.sources`), configuration and index selection (to cherry-pick dataset elements)
57 | 2. Define a preprocessing function or select one from `pygmi.data.preprocess`; this function should take raw data as input and save processed data to disk *
58 | 3. Subclass `pygmi.data.dataset.MultiSourceData` to override:
59 | 1. The `collate` method, defining how a list of data points is aggregated to form a batch *
60 | 2. The `load_data_point` method, defining how a preprocessed data point is loaded from disk to main memory *
61 | 5. Instantiate your subclass by passing the data sources (see below) and the preprocessing information (see below) as `dict`s
62 |
63 |
64 | \* This behaviour may change in the future.
65 |
66 |
67 | Data source configuration example:
68 | ```
69 | ### Create a dataset using both FAUST splits (train and test) as training dataset. ###
70 |
71 | train_source_conf=[
72 | dict(
73 | type='PyGDataSource',
74 | source_conf=dict(
75 | source='FAUST',
76 | idx_select=None,
77 | root='/path/to/FAUST/dir', # kwargs for PyG FAUST constructor
78 | train=True # kwargs for PyG FAUST constructor
79 | )
80 | ),
81 | dict(
82 | type='PyGDataSource',
83 | source_conf=dict(
84 | source='FAUST',
85 | idx_select=None,
86 | root='/path/to/FAUST/dir', # kwargs for PyG FAUST constructor
87 | train=False # kwargs for PyG FAUST constructor
88 | )
89 | )
90 | ]
91 | ```
92 |
93 | Preprocessing configuration example:
94 | ```
95 | ### Require computation of 500.000 ground truth distance values for each shape ###
96 |
97 | preprocessing_conf=dict(
98 | do_preprocessing=True,
99 | out_dir='path/to/data/output/',
100 | script='get_distance_values',
101 | conf=dict(sample=500000)
102 | )
103 | ```
104 | You should always supply at least `out_dir` and `do_preprocessing`; if preprocessing is not required, PyGMI will look for saved preprocessed files in `out_dir`. An error will be raised if preprocessing is disabled and there are no files to load.
105 |
106 |
107 | ## Tasks
108 |
109 | You may regard the `tasks` submodule as a collection of algorithms to solve popular implicit geometry tasks (e.g. surface reconstruction, view synthesis).
110 | As for `nn`, we tried to define as many default parameter values as possible, following the values found in original publications/code releases.
111 |
112 | In general, all tasks take as input a `pygmi.types.ImplicitFunction` object and run some optimization task on it. Once the process is completed, you may access
113 | `task.geometry` to recover the optimized implicit function along with its interface methods.
114 |
115 | Since tasks inherit from PyTorch Lightning Modules, you may execute them by creating a Trainer and a LightningDataModule (`pygmi.data.dataset` objects comply with this standard)
116 | and calling `trainer.fit(task, data)`. Take a look at `examples/` for a more concrete demonstration!
117 |
118 |
119 | ## Implicit Functions
120 |
121 | `pygmi.types` defines abstract object-oriented interfaces to work with `ImplicitFunction` subclasses. The real computation occurs in the `approximator` object which is required at creation. This could be a neural network or an analytic function, such as `pygmi.utils.sphere_sdf`.
122 |
123 |
124 |
125 | ## Utilities
126 |
127 | Our `utils` submodule is structured as follows:
128 |
129 | * `utils`
130 | * `files`: filesystem operations (useful for, e.g., preprocessing functions)
131 | * `misc`: various generic functions with no precise application
132 | * `extract`: extraction of explicit geometry from implicit representations
133 | * `core`: functions that can be applied to most implicit representations (generic level set operations)
134 | * `math`: predefined math operations
135 | * `diffops`: batched differential operations such as gradient, Jacobian, Hessian, etc. All are computed using `autograd`, optionally allowing higher-order differentiation
136 | * `visual`: visualization utilities
137 | * `core`: generic figure handling functions, common 3D plots use-cases (isosurfaces)
138 |
139 | All functions can be accessed directly from `pygmi.utils`, without further nesting.
140 |
--------------------------------------------------------------------------------
/pygmi/data/preprocess/sdf.py:
--------------------------------------------------------------------------------
1 | import trimesh
2 | import torch
3 | import numpy as np
4 | from typing import Tuple
5 | from torch import Tensor
6 | from torch_geometric.data import Data as PyGData
7 | from scipy.spatial import cKDTree
8 | from CGAL.CGAL_Kernel import Triangle_3, Point_3
9 | from CGAL.CGAL_AABB_tree import AABB_tree_Triangle_3_soup
10 |
11 |
12 |
13 | def _upsample_and_normalize(
14 | S: PyGData, sample: int
15 | ) -> Tuple[trimesh.Trimesh, Tensor, Tensor, Tensor, np.ndarray, float]:
16 | """Upsamples, centers and normalizes mesh to unitary area.
17 |
18 | Parameters
19 | ----------
20 | S : PyGData
21 | A mesh stored as a `torch_geometric.data.Data` object
22 | sample : int
23 | Number of points to sample from mesh surface
24 |
25 | Returns
26 | -------
27 | Tuple[trimesh.Trimesh, Tensor, Tensor, Tensor, np.ndarray, float]
28 | Trimesh representation of given mesh, mesh vertices, upsampled
29 | point cloud, normals for each point in point cloud, mesh center point,
30 | mesh area.
31 | """
32 |
33 | # Create trimesh #
34 | F = S.face
35 | V = S.pos
36 | mesh = trimesh.Trimesh(vertices=V, faces=F.T)
37 |
38 | # Sample points and normals #
39 | pnts, face_index = trimesh.sample.sample_surface(mesh, sample)
40 | center = np.mean(pnts, axis=0)
41 | pnts = pnts - np.expand_dims(center, axis=0)
42 | normals = torch.from_numpy(mesh.face_normals[face_index])[:, [0, 2, 1]].float()
43 |
44 | # Normalize registered surface points and upsample #
45 | V = V[:, [0, 2, 1]] - torch.from_numpy(center[[0, 2, 1]]).unsqueeze(0).float()
46 | area = np.sqrt(mesh.area)
47 | pnts /= area
48 | V /= area
49 |
50 | return mesh, V, torch.from_numpy(pnts)[:, [0, 2, 1]].float(), normals, center, area
51 |
52 | def _compute_sigmas(pnts: Tensor) -> np.ndarray:
53 | """Computes point-wise standard deviations for informed spatial sampling
54 | around a shape, given a Tensor of surface points. Applies the 50-th nearest
55 | neighbor heuristic.
56 |
57 | Parameters
58 | ----------
59 | pnts : Tensor
60 | A surface sample of the shape of interest
61 |
62 | Returns
63 | -------
64 | np.ndarray
65 | For each point in `pnts`, the distance from the 50-th nearest neighbor
66 | """
67 |
68 | query = pnts.numpy()
69 | sigmas = []
70 | ptree = cKDTree(query)
71 | for p in np.array_split(query,100,axis=0):
72 | d = ptree.query(p, 51) # sigma = dist from 50-th NN (heuristic)
73 | sigmas.append(d[0][:,-1])
74 |
75 | return np.concatenate(sigmas)
76 |
77 |
78 | def get_distance_values(S: PyGData, out_path: str, sample: int, global_sigma: float = 0.2) -> None:
79 | """Preprocess a mesh for SDF tasks: get ground truth distance values
80 | without sign. Useful for learning SDFs using (e.g.) sign agnostic regression.
81 | `out_path` will contain a dict with keys {'surface', 'dists', 'vertices', 'faces', 'normals'},
82 | respectively mapping to: a point cloud obtained by upsamping the mesh (`N x 3` Tensor),
83 | a cloud of random points labeled with distances from the surface (`M x 4` Tensor), vertices
84 | and faces of the original mesh, surface normals for points in 'surface' (`N x 3` Tensor).
85 |
86 | Parameters
87 | ----------
88 | S : PyGData
89 | A torch_geometric.data.Data object, representing a mesh
90 | sample : int
91 | Surface sample size and half distance sample size
92 | out_path : str
93 | Memory location to save preprocessed data
94 | global_sigma : float, optional
95 | Standard deviation for sampling points around shape, by default 0.2
96 | """
97 |
98 | mesh, V, pnts, normals, center, area = _upsample_and_normalize(S, sample)
99 |
100 | # Instantiate CGAL AABB tree #
101 | triangles = []
102 | for tri in mesh.triangles:
103 | T = (tri - center) / area
104 | a = Point_3(T[0][0], T[0][1], T[0][2]) # (tri[0][0] - center[0]), (tri[0][1] - center[1]), (tri[0][2] - center[2]))
105 | b = Point_3(T[1][0], T[1][1], T[1][2]) # (tri[1][0] - center[0]), (tri[1][1] - center[1]), (tri[1][2] - center[2]))
106 | c = Point_3(T[2][0], T[2][1], T[2][2]) # (tri[2][0] - center[0]), (tri[2][1] - center[1]), (tri[2][2] - center[2]))
107 | triangles.append(Triangle_3(a, b, c))
108 | tree = AABB_tree_Triangle_3_soup(triangles)
109 |
110 | # Sample points with 50-th NN heuristic #
111 | sigmas = _compute_sigmas(pnts)
112 | sigmas_big = global_sigma * np.ones_like(sigmas)
113 |
114 | sample = np.concatenate([
115 | pnts + np.expand_dims(sigmas,-1) * np.random.normal(0.0, 1.0, size=pnts.shape),
116 | pnts + np.expand_dims(sigmas_big,-1) * np.random.normal(0.0, 1.0, size=pnts.shape)], axis=0)
117 |
118 | # Compute distances #
119 | dists = []
120 | for np_query in sample:
121 | cgal_query = Point_3(np_query[0].astype(np.double), np_query[1].astype(np.double), np_query[2].astype(np.double))
122 |
123 | cp = tree.closest_point(cgal_query)
124 | cp = np.array([cp.x(), cp.y(), cp.z()])
125 | dist = np.sqrt(((cp - np_query)**2).sum(axis=0))
126 |
127 | dists.append(dist)
128 | dists = np.array(dists).reshape(-1, 1)
129 |
130 | sample_dists = torch.from_numpy(np.concatenate([sample, dists], axis=-1))[:, [0, 2, 1, 3]].float()
131 |
132 | # Save everything to pth #
133 | torch.save(
134 | {
135 | 'surface': pnts,
136 | 'dists': sample_dists,
137 | 'vertices': V,
138 | 'faces': S.face,
139 | 'normals': normals
140 | },
141 | out_path
142 | )
143 |
144 | def upsample_with_normals(
145 | S: PyGData,
146 | out_path: str,
147 | sample: int,
148 | mnfld_sigma: bool = False
149 | ) -> None:
150 | """Preprocess a mesh for SDF tasks: upsample mesh vertices and normals, optionally
151 | compute spatial sampling sigmas. `out_path` will contain a dict with keys {'surface',
152 | 'vertices', 'faces', 'normals', 'mnfld_sigma'}, respectively mapping to: a point cloud
153 | obtained by upsamping the mesh (`N x 3` Tensor), vertices and faces of the original mesh,
154 | surface normals for points in 'surface' (`N x 3` Tensor), and (optionally) point-wise
155 | standard deviations for informed spatial sampling around the shape, for points in
156 | 'surface' (`N x 1` Tensor).
157 |
158 | Parameters
159 | ----------
160 | S : PyGData
161 | A torch_geometric.data.Data object, representing a mesh
162 | sample : int
163 | Surface (and normals) sample size
164 | out_path : str
165 | Memory location to save preprocessed data
166 | mnfld_sigma: bool, optional
167 | Specifies whether to compute space sampling std for each point, by default False
168 | """
169 |
170 | _, V, pnts, normals, _, _ = _upsample_and_normalize(S, sample)
171 |
172 | sigmas = None
173 | if mnfld_sigma:
174 | sigmas = torch.from_numpy(_compute_sigmas(pnts)).float().unsqueeze(-1)
175 |
176 | # Save everything to pth #
177 | torch.save(
178 | {
179 | 'surface': pnts,
180 | 'vertices': V,
181 | 'faces': S.face,
182 | 'normals': normals,
183 | 'mnfld_sigma': sigmas
184 | },
185 | out_path
186 | )
187 |
188 | def center_point_cloud(S: PyGData, out_path: str, mnfld_sigma: bool = False) -> None:
189 | """Save a point cloud to disk, after centering in the origin. `out_path` will
190 | contain a dict with keys {'surface', 'normals'}, respectively mapping to: the point cloud
191 | (`N x 3` Tensor), (optionally) surface normals for points in 'surface' (`N x 3` Tensor),
192 | and (optionally) point-wise standard deviations for informed spatial sampling around the
193 | shape, for points in 'surface' (`N x 1` Tensor).
194 |
195 | Parameters
196 | ----------
197 | S : PyGData
198 | A torch_geometric.data.Data object, representing a point cloud (all
199 | attributes are ignored except for S.pos). If it contains normals, they
200 | are expected to be stored in `S.normal`.
201 | mnfld_sigma: bool, optional
202 | Specifies whether to compute space sampling std for each point, by default False
203 | """
204 |
205 | # Center in origin
206 | V = S.pos - S.pos.mean(dim=0, keepdim=True)
207 |
208 | # Compute sigmas
209 | sigmas = None
210 | if mnfld_sigma:
211 | sigmas = torch.from_numpy(_compute_sigmas(V)).float().unsqueeze(-1)
212 |
213 | # Save everything to pth #
214 | torch.save(
215 | {
216 | 'surface': V,
217 | 'normals': getattr(S, 'normal', None),
218 | 'mnfld_sigma': sigmas
219 | },
220 | out_path
221 | )
--------------------------------------------------------------------------------
/pygmi/data/dataset/sdf.py:
--------------------------------------------------------------------------------
1 | import random
2 | import torch
3 | from torch import Tensor
4 | from typing import List, Dict, Tuple, Union
5 | from pygmi.data.dataset import MultiSourceData
6 |
7 |
8 |
9 | class SDFUnsupervisedData(MultiSourceData):
10 |
11 | def __init__(
12 | self,
13 | train_source_conf: List[Dict] = [],
14 | test_source_conf: List[Dict] = [],
15 | preprocessing_conf: Dict = {},
16 | val_split: float = 0.0,
17 | batch_size: Dict[str, int] = {'train': 1, 'val': 1, 'test': 1},
18 | surf_sample: int = 16384,
19 | global_space_sample: int = 2048,
20 | global_sigma: float = 1.8,
21 | local_sigma: float = None,
22 | use_normals: bool = True
23 | ):
24 | """3D data for unsupervised (i.e. without ground truth distances)
25 | SDF tasks. Uses supersampled meshes with normals, and by default
26 | uses point-wise standard deviations for spatial sampling.
27 |
28 | Parameters
29 | ----------
30 | train_source_conf : List[Dict], optional
31 | List of configurations for multiple data sources. Each should specify a type
32 | (i.e. a subclass of ngt.data.sources.core.DataSource), and a configuration in
33 | dict format depending on the source type (see ngt.data.sources), by default []
34 | test_source_conf : List[Dict], optional
35 | List of configurations for multiple data sources, by default []
36 | preprocessing_conf : Dict, optional
37 | Configuration for preprocessing procedure for the selected data sources, by default {}
38 | val_split : float, optional
39 | Fraction of training data serving for validation, by default 0.0
40 | batch_size : _type_, optional
41 | Batch size for train, test, val. Expects keys: {"train", "val", "test"},
42 | by default {'train': 1, 'val': 1, 'test': 1}
43 | surf_sample : int, optional
44 | Size of point sample representing a shape's surface, by default 16384
45 | global_space_sample : int, optional
46 | Size of global point samples in spatial sampling. Usually set equal to
47 | `surf_sample // 8`. The final size of spatial samples is `surf_sample + global_space_sample`,
48 | by default 2048
49 | global_sigma : float, optional
50 | Maximum coordinate of space for global spatial point sampling, by default 1.8
51 | local_sigma : float, optional
52 | std. dev. for local spatial point sampling; if None, preprocessed shapes
53 | are expected to have key "mnfld_sigma", by default None
54 | use_normals : bool, optional
55 | Whether to sample normals together with surface points, by default True
56 | """
57 | super(SDFUnsupervisedData, self).__init__(
58 | train_source_conf, test_source_conf, preprocessing_conf, batch_size, val_split)
59 | self.surf_sample = surf_sample
60 | self.space_sample = global_space_sample
61 | self.global_sigma = global_sigma
62 | self.use_normals = use_normals
63 | if local_sigma is None:
64 | self.fixed_local_sigma = False
65 | else:
66 | self.fixed_local_sigma = True
67 | self.local_sigma = local_sigma
68 |
69 | def sample_shape_space(self, point_cloud: Tensor, local_sigma: Union[Tensor, float]) -> Tensor:
70 | """Samples points from embedding space, concatenating a small uniformly sampled
71 | (global) sample with a large Gaussian local sample, computed either with point-wise
72 | standard deviations (if `type(local_sigma) == Tensor`) or fixed standard deviation
73 | (if `type(local_sigma) == float`)
74 |
75 | Parameters
76 | ----------
77 | point_cloud : Tensor
78 | Surface samples of shapes for which to perform spatial sampling. Shape: `B x S x 3`
79 | local_sigma : Union[Tensor, float]
80 | Standard deviation for local sampling. Either fixed (if type is float) or point-wise
81 | (if type is Tensor)
82 |
83 | Returns
84 | -------
85 | Tensor
86 | A random sample of points around each given point cloud
87 | """
88 | sample_local = point_cloud + (torch.randn_like(point_cloud) * local_sigma)
89 | sample_global = (
90 | 2 * self.global_sigma * torch.rand(
91 | point_cloud.shape[0], self.space_sample, point_cloud.shape[2]
92 | )) - self.global_sigma
93 | return torch.cat([sample_local, sample_global], dim=1)
94 |
95 | def sample_surface(self, shape: Dict[str, Tensor]) -> Tuple[Tensor, Tensor, Tensor]:
96 | """Samples a surface, optionally with normals and point-wise
97 | local sampling standard deviations.
98 |
99 | Parameters
100 | ----------
101 | shape : Dict[str, Tensor]
102 | Preprocessed shape data. Expects keys {'surface', 'normals'}
103 | and optionally 'mnfld_sigma'
104 |
105 | Returns
106 | -------
107 | Tuple[Tensor, Tensor, Tensor]
108 | Surface sample, normals sample, sigmas sample. Normals and sigmas can be
109 | None if they are not required by configuration
110 | """
111 | surf = shape['surface']
112 | indices = random.sample(range(surf.shape[0]), self.surf_sample)
113 | surf_sample = surf[indices, :]
114 | norm_sample = shape['normals'][indices, :] if self.use_normals else None
115 | sigmas_sample = shape['mnfld_sigma'][indices, :] if not self.fixed_local_sigma else None
116 | return surf_sample, norm_sample, sigmas_sample
117 |
118 | def collate(self, data: List[Dict], idxs: List[int]) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
119 | """Implementation of collate method. Loads a list of dictionaries with keys
120 | {'surface', 'normals', 'mnfld_sigma'} to a tuple of 4 Tensors (some of which may be
121 | None, depending on configuration).
122 |
123 | Parameters
124 | ----------
125 | data : List[Dict]
126 | A list of dictionaries with keys {'surface', 'normals', 'mnfld_sigma'} and Tensor values
127 | idxs : List[int]
128 | Indices of `data` in the dataset
129 |
130 | Returns
131 | -------
132 | Tuple[Tensor, Tensor, Tensor, Tensor]
133 | `B x 1` LongTensor of indices of each shape in the batch,
134 | `B x S x 3` FloatTensor of surface samples for each shape in the batch,
135 | `B x S x 3` FloatTensor of normals for each sampled surface point (may be None),
136 | `B x T x 3` FloatTensor of space point samples for each shape in the batch
137 | """
138 | shape_ids = torch.tensor(idxs, dtype=torch.long)
139 | samples = [self.sample_surface(x) for x in data]
140 | surf_sample = torch.stack([x[0] for x in samples])
141 | norm_sample = torch.stack([x[1] for x in samples]) if self.use_normals else None
142 | sigma = self.local_sigma if self.fixed_local_sigma else torch.stack([x[2] for x in samples])
143 | space_sample = self.sample_shape_space(surf_sample, sigma)
144 | return shape_ids, surf_sample, norm_sample, space_sample
145 |
146 | def load_data_point(self, path: str) -> Dict[str, Tensor]:
147 | """Implementation of load_data_point method. Loads a dictionary from `path` using
148 | `torch.load`.
149 |
150 | Parameters
151 | ----------
152 | path : str
153 | Path to data point stored on disk
154 |
155 | Returns
156 | -------
157 | Dict[str, Tensor]
158 | Loaded data point, must have keys {'surface', 'normals'} and optionally 'mnfld_sigma'
159 | """
160 | return torch.load(path)
161 |
162 |
163 |
164 | class SDFSupervisedData(MultiSourceData):
165 |
166 | def __init__(
167 | self,
168 | train_source_conf: List[Dict] = [],
169 | test_source_conf: List[Dict] = [],
170 | preprocessing_conf: Dict = {},
171 | val_split: float = 0.0,
172 | batch_size: Dict[str, int] = {'train': 1, 'val': 1, 'test': 1},
173 | surf_sample: int = 16384,
174 | space_sample: int = 16384,
175 | use_normals: bool = True
176 | ):
177 | """3D data for supervised (i.e. with ground truth distances) SDF tasks.
178 |
179 | Parameters
180 | ----------
181 | train_source_conf : List[Dict], optional
182 | List of configurations for multiple data sources. Each should specify a type
183 | (i.e. a subclass of ngt.data.sources.core.DataSource), and a configuration in
184 | dict format depending on the source type (see ngt.data.sources), by default []
185 | test_source_conf : List[Dict], optional
186 | List of configurations for multiple data sources, by default []
187 | preprocessing_conf : Dict, optional
188 | Configuration for preprocessing procedure for the selected data sources, by default {}
189 | val_split : float, optional
190 | Fraction of training data serving for validation, by default 0.0
191 | batch_size : Dict[str, int], optional
192 | Batch size for train, test, val. Expects keys: {"train", "val", "test"},
193 | by default {'train': 1, 'val': 1, 'test': 1}
194 | surf_sample : int, optional
195 | Size of point sample representing a shape's surface, by default 16384
196 | space_sample : int, optional
197 | Size of point samples for a shape's embedding space, with distances, by default 16384
198 | use_normals : bool, optional
199 | Whether to sample normals together with surface points, by default True
200 | """
201 | super(SDFSupervisedData, self).__init__(
202 | train_source_conf, test_source_conf, preprocessing_conf, batch_size, val_split)
203 | self.surf_sample = surf_sample
204 | self.space_sample = space_sample
205 | self.use_normals = use_normals
206 |
207 | def sample_distances(self, shape: Dict[str, Tensor]) -> Tensor:
208 | """Samples indices from a Tensor containing coordinates and
209 | distance values, expected to be the value of `shape['dists']`
210 |
211 | Parameters
212 | ----------
213 | shape : Dict[str, Tensor]
214 | A dict with key 'dists' mapping to a `N x 4` Tensor
215 |
216 | Returns
217 | -------
218 | Tensor
219 | A sample of points and distances, with shape `self.space_sample x 4`
220 | """
221 | dist = shape['dists']
222 | indices = random.sample(range(dist.shape[0]), self.space_sample)
223 | return dist[indices, :]
224 |
225 | def sample_surface(self, shape: Dict[str, Tensor]) -> Tuple[Tensor, Tensor]:
226 | """Samples indices from a Tensor containing surface points of a shape,
227 | expected to be the value of `shape['surface']`. If required by configuration,
228 | normals are sampled as well (from `shape['normals']`)
229 |
230 | Parameters
231 | ----------
232 | shape : Dict[str, Tensor]
233 | A dict with keys 'surface' mapping to a `N x 3` Tensor and 'normals' mapping
234 | to a `N x 3` Tensor (optional)
235 |
236 | Returns
237 | -------
238 | Tuple[Tensor, Tensor]
239 | Surface sample, normals sample. Normals can be
240 | None if they are not required by configuration
241 | """
242 | surf = shape['surface']
243 | indices = random.sample(range(surf.shape[0]), self.surf_sample)
244 | surf_sample = surf[indices, :]
245 | norm_sample = shape['normals'][indices, :] if self.use_normals else None
246 | return surf_sample, norm_sample
247 |
248 | def collate(self, data: List[Dict], idxs: List[int]) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
249 | """Implementation of collate method. Loads a list of dictionaries with keys
250 | {'surface', 'normals', 'dists'} to a tuple of 4 Tensors (some of which may be
251 | None, depending on configuration).
252 |
253 | Parameters
254 | ----------
255 | data : List[Dict]
256 | A list of dictionaries with keys {'surface', 'normals', 'dists'} and Tensor values
257 | idxs : List[int]
258 | Indices of `data` in the dataset
259 |
260 | Returns
261 | -------
262 | Tuple[Tensor, Tensor, Tensor, Tensor]
263 | `B x 1` LongTensor of indices of each shape in the batch,
264 | `B x S x 3` FloatTensor of surface samples for each shape in the batch,
265 | `B x S x 3` FloatTensor of normals for each sampled surface point (may be None),
266 | `B x T x 3` FloatTensor of space point samples for each shape in the batch
267 | """
268 | shape_ids = torch.tensor(idxs, dtype=torch.long)
269 | samples = [self.sample_surface(x) for x in data]
270 | surf_sample = torch.stack([x[0] for x in samples])
271 | norm_sample = torch.stack([x[1] for x in samples]) if self.use_normals else None
272 | dist_sample = torch.stack([self.sample_distances(x) for x in data])
273 | return shape_ids, surf_sample, norm_sample, dist_sample
274 |
275 | def load_data_point(self, path: str) -> Dict[str, Tensor]:
276 | """Implementation of load_data_point method. Loads a dictionary from `path` using
277 | `torch.load`.
278 |
279 | Parameters
280 | ----------
281 | path : str
282 | Path to data point stored on disk
283 |
284 | Returns
285 | -------
286 | Dict[str, Tensor]
287 | Loaded data point, must have keys {'surface', 'normals', 'dists'}
288 | """
289 | return torch.load(path)
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------