nops 0.2.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. {nops-0.2.0 → nops-0.4.0}/PKG-INFO +3 -3
  2. {nops-0.2.0 → nops-0.4.0}/README.md +1 -1
  3. nops-0.4.0/nops/data/__init__.py +133 -0
  4. nops-0.4.0/nops/data/datasets/__init__.py +17 -0
  5. nops-0.4.0/nops/data/datasets/base.py +222 -0
  6. nops-0.4.0/nops/data/datasets/burgers.py +97 -0
  7. nops-0.4.0/nops/data/datasets/darcy.py +85 -0
  8. nops-0.4.0/nops/data/datasets/heat.py +85 -0
  9. nops-0.4.0/nops/data/datasets/navier_stokes.py +85 -0
  10. nops-0.4.0/nops/data/datasets/poisson.py +75 -0
  11. nops-0.4.0/nops/data/datasets/wave.py +91 -0
  12. nops-0.4.0/nops/data/generators/__init__.py +17 -0
  13. nops-0.4.0/nops/data/generators/base.py +138 -0
  14. nops-0.4.0/nops/data/generators/burgers.py +267 -0
  15. nops-0.4.0/nops/data/generators/darcy.py +368 -0
  16. nops-0.4.0/nops/data/generators/heat.py +341 -0
  17. nops-0.4.0/nops/data/generators/navier_stokes.py +349 -0
  18. nops-0.4.0/nops/data/generators/poisson.py +146 -0
  19. nops-0.4.0/nops/data/generators/wave.py +408 -0
  20. nops-0.4.0/nops/data/utils/__init__.py +3 -0
  21. nops-0.4.0/nops/data/utils/gaussian_rf.py +203 -0
  22. {nops-0.2.0 → nops-0.4.0}/nops/deeponet/models/deeponet.py +4 -5
  23. {nops-0.2.0 → nops-0.4.0}/nops/fno/layers/spectral_convolution.py +34 -40
  24. {nops-0.2.0 → nops-0.4.0}/nops/gno/layers/integral_transform.py +3 -15
  25. nops-0.4.0/nops/gno/layers/neighbor_search.py +179 -0
  26. {nops-0.2.0 → nops-0.4.0}/nops/gno/models/original.py +46 -80
  27. {nops-0.2.0 → nops-0.4.0}/nops/losses/derivatives.py +23 -44
  28. {nops-0.2.0 → nops-0.4.0}/pyproject.toml +1 -1
  29. nops-0.4.0/tests/test_constant_derivatives.py +30 -0
  30. nops-0.4.0/tests/test_data.py +720 -0
  31. nops-0.4.0/tests/test_dataset_snapshot_roundtrip.py +31 -0
  32. nops-0.4.0/tests/test_deeponet_cartesian_regression.py +20 -0
  33. {nops-0.2.0 → nops-0.4.0}/tests/test_gno.py +10 -0
  34. nops-0.4.0/tests/test_gno_kernel_registration.py +34 -0
  35. nops-0.4.0/tests/test_gno_position_regression.py +20 -0
  36. nops-0.4.0/tests/test_knn_batch_regression.py +35 -0
  37. nops-0.4.0/tests/test_spectral_frequency_regression.py +39 -0
  38. {nops-0.2.0 → nops-0.4.0}/uv.lock +1 -1
  39. nops-0.2.0/nops/gno/layers/neighbor_search.py +0 -227
  40. {nops-0.2.0 → nops-0.4.0}/.github/workflows/ci.yml +0 -0
  41. {nops-0.2.0 → nops-0.4.0}/.github/workflows/pypi.yml +0 -0
  42. {nops-0.2.0 → nops-0.4.0}/.gitignore +0 -0
  43. {nops-0.2.0 → nops-0.4.0}/.python-version +0 -0
  44. {nops-0.2.0 → nops-0.4.0}/LICENSE +0 -0
  45. {nops-0.2.0 → nops-0.4.0}/example_deeponet.py +0 -0
  46. {nops-0.2.0 → nops-0.4.0}/example_gno.py +0 -0
  47. {nops-0.2.0 → nops-0.4.0}/nops/__init__.py +0 -0
  48. {nops-0.2.0 → nops-0.4.0}/nops/deeponet/__init__.py +0 -0
  49. {nops-0.2.0 → nops-0.4.0}/nops/deeponet/layers/__init__.py +0 -0
  50. {nops-0.2.0 → nops-0.4.0}/nops/deeponet/layers/mlp.py +0 -0
  51. {nops-0.2.0 → nops-0.4.0}/nops/deeponet/models/__init__.py +0 -0
  52. {nops-0.2.0 → nops-0.4.0}/nops/fno/layers/__init__.py +0 -0
  53. {nops-0.2.0 → nops-0.4.0}/nops/fno/layers/ffn.py +0 -0
  54. {nops-0.2.0 → nops-0.4.0}/nops/fno/layers/fno_block.py +0 -0
  55. {nops-0.2.0 → nops-0.4.0}/nops/fno/layers/mlp.py +0 -0
  56. {nops-0.2.0 → nops-0.4.0}/nops/fno/models/original.py +0 -0
  57. {nops-0.2.0 → nops-0.4.0}/nops/gno/__init__.py +0 -0
  58. {nops-0.2.0 → nops-0.4.0}/nops/gno/layers/__init__.py +0 -0
  59. {nops-0.2.0 → nops-0.4.0}/nops/gno/layers/gno_block.py +0 -0
  60. {nops-0.2.0 → nops-0.4.0}/nops/gno/layers/mlp.py +0 -0
  61. {nops-0.2.0 → nops-0.4.0}/nops/gno/models/__init__.py +0 -0
  62. {nops-0.2.0 → nops-0.4.0}/nops/gno/models/mGNO.py +0 -0
  63. {nops-0.2.0 → nops-0.4.0}/nops/gno/utils/__init__.py +0 -0
  64. {nops-0.2.0 → nops-0.4.0}/nops/gno/utils/geometry.py +0 -0
  65. {nops-0.2.0 → nops-0.4.0}/nops/losses/__init__.py +0 -0
  66. {nops-0.2.0 → nops-0.4.0}/nops/losses/base.py +0 -0
  67. {nops-0.2.0 → nops-0.4.0}/nops/losses/boundary.py +0 -0
  68. {nops-0.2.0 → nops-0.4.0}/nops/losses/data.py +0 -0
  69. {nops-0.2.0 → nops-0.4.0}/nops/losses/energy.py +0 -0
  70. {nops-0.2.0 → nops-0.4.0}/nops/losses/initial.py +0 -0
  71. {nops-0.2.0 → nops-0.4.0}/nops/losses/pde/__init__.py +0 -0
  72. {nops-0.2.0 → nops-0.4.0}/nops/losses/pde/burgers.py +0 -0
  73. {nops-0.2.0 → nops-0.4.0}/nops/losses/pde/darcy.py +0 -0
  74. {nops-0.2.0 → nops-0.4.0}/nops/losses/pde/generic.py +0 -0
  75. {nops-0.2.0 → nops-0.4.0}/nops/losses/pde/heat.py +0 -0
  76. {nops-0.2.0 → nops-0.4.0}/nops/losses/pde/navier_stokes.py +0 -0
  77. {nops-0.2.0 → nops-0.4.0}/nops/losses/pde/poisson.py +0 -0
  78. {nops-0.2.0 → nops-0.4.0}/nops/losses/pde/wave.py +0 -0
  79. {nops-0.2.0 → nops-0.4.0}/nops.png +0 -0
  80. {nops-0.2.0 → nops-0.4.0}/tests/test_deeponet.py +0 -0
  81. {nops-0.2.0 → nops-0.4.0}/tests/test_fno.py +0 -0
  82. {nops-0.2.0 → nops-0.4.0}/tests/test_losses.py +0 -0
  83. {nops-0.2.0 → nops-0.4.0}/tests/test_spectral_convolution.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: nops
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: nops: Neural Operators made simple — with physics-informed losses for FNO, DeepONet, and GNO
5
5
  Project-URL: Homepage, https://github.com/abelsr/nops
6
6
  Project-URL: Repository, https://github.com/abelsr/nops
@@ -143,7 +143,7 @@ print(f"Output Field Shape: {output.shape}")
143
143
  - [x] **DeepONet:** Implementation of Deep Operator Networks.
144
144
  - [x] **GNO (Graph Neural Operator):** Support for irregular meshes.
145
145
  - [x] **Physics-Informed Losses:** Built-in loss functions for PDE constraints.
146
- - [ ] **Data Loaders:** Standard datasets (Burgers, Navier-Stokes, Darcy Flow).
146
+ - [x] **Data Loaders:** Standard datasets (Burgers, Navier-Stokes, Darcy Flow).
147
147
 
148
148
  ## 🤝 Contributing
149
149
 
@@ -107,7 +107,7 @@ print(f"Output Field Shape: {output.shape}")
107
107
  - [x] **DeepONet:** Implementation of Deep Operator Networks.
108
108
  - [x] **GNO (Graph Neural Operator):** Support for irregular meshes.
109
109
  - [x] **Physics-Informed Losses:** Built-in loss functions for PDE constraints.
110
- - [ ] **Data Loaders:** Standard datasets (Burgers, Navier-Stokes, Darcy Flow).
110
+ - [x] **Data Loaders:** Standard datasets (Burgers, Navier-Stokes, Darcy Flow).
111
111
 
112
112
  ## 🤝 Contributing
113
113
 
@@ -0,0 +1,133 @@
1
+ """
2
+ nops.data — PDE Data Generators and Datasets
3
+ =============================================
4
+
5
+ Pseudo-spectral data generators and :class:`~torch.utils.data.Dataset`
6
+ wrappers for six canonical PDE benchmarks used in neural operator research.
7
+
8
+ Generators
9
+ ----------
10
+ Each generator uses a spectrally-accurate solver and returns a
11
+ ``dict[str, Tensor]``.
12
+
13
+ .. list-table::
14
+ :header-rows: 1
15
+
16
+ * - Class
17
+ - Equation
18
+ - Solver
19
+ * - :class:`~nops.data.generators.BurgersGenerator`
20
+ - 1D viscous Burgers
21
+ - ETDRK4 (integrating factor)
22
+ * - :class:`~nops.data.generators.NavierStokesGenerator`
23
+ - 2D incompressible NS (vorticity)
24
+ - CN-Heun (IMEX-RK2)
25
+ * - :class:`~nops.data.generators.DarcyGenerator`
26
+ - 2D steady Darcy flow
27
+ - Spectral Picard iteration or file loader
28
+ * - :class:`~nops.data.generators.HeatGenerator`
29
+ - 1D/2D heat equation
30
+ - Exact integrating factor
31
+ * - :class:`~nops.data.generators.WaveGenerator`
32
+ - 1D/2D (damped) wave equation
33
+ - Exact matrix exponential
34
+ * - :class:`~nops.data.generators.PoissonGenerator`
35
+ - 2D Poisson equation
36
+ - Direct spectral solve
37
+
38
+ Datasets
39
+ --------
40
+ Each dataset wraps a generator (or pre-built data) and exposes a standard
41
+ PyTorch ``Dataset`` returning ``(input, target)`` pairs.
42
+
43
+ .. list-table::
44
+ :header-rows: 1
45
+
46
+ * - Class
47
+ - input
48
+ - target
49
+ * - :class:`~nops.data.datasets.BurgersDataset`
50
+ - ``u(x, 0)``
51
+ - ``u(x, T)``
52
+ * - :class:`~nops.data.datasets.NavierStokesDataset`
53
+ - ``ω(x, 0)``
54
+ - ``ω(x, T)``
55
+ * - :class:`~nops.data.datasets.DarcyDataset`
56
+ - ``a(x)`` (permeability)
57
+ - ``u(x)`` (pressure)
58
+ * - :class:`~nops.data.datasets.HeatDataset`
59
+ - ``u(x, 0)``
60
+ - ``u(x, T)``
61
+ * - :class:`~nops.data.datasets.WaveDataset`
62
+ - ``(u(x,0), ∂u/∂t(x,0))``
63
+ - ``u(x, T)``
64
+ * - :class:`~nops.data.datasets.PoissonDataset`
65
+ - ``f(x)`` (source)
66
+ - ``u(x)`` (potential)
67
+
68
+ Utility
69
+ -------
70
+ :class:`~nops.data.utils.GaussianRF`
71
+ Spectral Gaussian Random Field sampler (1D/2D) used by all generators
72
+ for initial conditions and forcing.
73
+
74
+ Quick start
75
+ -----------
76
+ >>> from nops.data import BurgersGenerator, BurgersDataset
77
+ >>> gen = BurgersGenerator(N=1024, nu=0.1, T=1.0, record_steps=1)
78
+ >>> ds = BurgersDataset(generator=gen, n_samples=200)
79
+ >>> loader = ds.get_dataloader(batch_size=32)
80
+ >>> x, y = next(iter(loader)) # x: (32, 1024), y: (32, 1024)
81
+
82
+ >>> from nops.data import NavierStokesGenerator, NavierStokesDataset
83
+ >>> gen = NavierStokesGenerator(N=64, nu=1e-3, T=1.0, record_steps=10)
84
+ >>> ds = NavierStokesDataset(generator=gen, n_samples=100)
85
+ >>> ds.save("ns_data.pt") # persist to disk
86
+ >>> ds2 = NavierStokesDataset.load("ns_data.pt") # reload
87
+ """
88
+
89
+ # Generators
90
+ from nops.data.generators import (
91
+ BaseGenerator,
92
+ BurgersGenerator,
93
+ DarcyGenerator,
94
+ HeatGenerator,
95
+ NavierStokesGenerator,
96
+ PoissonGenerator,
97
+ WaveGenerator,
98
+ )
99
+
100
+ # Datasets
101
+ from nops.data.datasets import (
102
+ BasePDEDataset,
103
+ BurgersDataset,
104
+ DarcyDataset,
105
+ HeatDataset,
106
+ NavierStokesDataset,
107
+ PoissonDataset,
108
+ WaveDataset,
109
+ )
110
+
111
+ # Utilities
112
+ from nops.data.utils import GaussianRF
113
+
114
+ __all__ = [
115
+ # Generators
116
+ "BaseGenerator",
117
+ "BurgersGenerator",
118
+ "DarcyGenerator",
119
+ "HeatGenerator",
120
+ "NavierStokesGenerator",
121
+ "PoissonGenerator",
122
+ "WaveGenerator",
123
+ # Datasets
124
+ "BasePDEDataset",
125
+ "BurgersDataset",
126
+ "DarcyDataset",
127
+ "HeatDataset",
128
+ "NavierStokesDataset",
129
+ "PoissonDataset",
130
+ "WaveDataset",
131
+ # Utilities
132
+ "GaussianRF",
133
+ ]
@@ -0,0 +1,17 @@
1
+ from nops.data.datasets.base import BasePDEDataset
2
+ from nops.data.datasets.burgers import BurgersDataset
3
+ from nops.data.datasets.darcy import DarcyDataset
4
+ from nops.data.datasets.heat import HeatDataset
5
+ from nops.data.datasets.navier_stokes import NavierStokesDataset
6
+ from nops.data.datasets.poisson import PoissonDataset
7
+ from nops.data.datasets.wave import WaveDataset
8
+
9
+ __all__ = [
10
+ "BasePDEDataset",
11
+ "BurgersDataset",
12
+ "DarcyDataset",
13
+ "HeatDataset",
14
+ "NavierStokesDataset",
15
+ "PoissonDataset",
16
+ "WaveDataset",
17
+ ]
@@ -0,0 +1,222 @@
1
+ """
2
+ Abstract base class for PDE datasets.
3
+
4
+ All datasets expose a standard :class:`torch.utils.data.Dataset` interface
5
+ returning ``(input, target)`` pairs, plus two extra capabilities:
6
+
7
+ 1. **Two storage modes**
8
+
9
+ - ``mode="memory"`` — tensors are held in RAM after generation or loading.
10
+ - ``mode="disk"`` — a single ``.pt`` file on disk; samples are loaded
11
+ lazily in :meth:`__getitem__` (useful when the full dataset does not fit
12
+ in RAM).
13
+
14
+ 2. **Save / load round-trip**
15
+
16
+ :meth:`save` serialises the full raw ``data`` dict plus metadata to a
17
+ ``.pt`` file. :meth:`load` restores an identical dataset from that file.
18
+
19
+ Subclasses only need to implement :meth:`_make_pair`, which maps the raw
20
+ ``dict[str, Tensor]`` entry at a given index to an ``(input, target)`` pair.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from abc import ABC, abstractmethod
26
+ from pathlib import Path
27
+ from typing import Literal
28
+
29
+ import torch
30
+ from torch import Tensor
31
+ from torch.utils.data import DataLoader, Dataset
32
+
33
+
34
+ class BasePDEDataset(Dataset, ABC):
35
+ """Base class for PDE datasets with memory and disk storage modes.
36
+
37
+ Parameters
38
+ ----------
39
+ data : dict[str, Tensor] or None
40
+ Pre-built raw data dict (e.g. as returned by a generator).
41
+ Required when ``mode="memory"`` and no path/generator is given.
42
+ mode : {"memory", "disk"}
43
+ Storage mode. In ``"disk"`` mode, ``data`` is ignored and the
44
+ dataset is loaded lazily from ``path``.
45
+ path : str or Path or None
46
+ Path to a ``.pt`` file. Required when ``mode="disk"``.
47
+
48
+ Notes
49
+ -----
50
+ Subclasses must implement :meth:`_make_pair`.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ data: dict[str, Tensor] | None = None,
56
+ mode: Literal["memory", "disk"] = "memory",
57
+ path: str | Path | None = None,
58
+ ) -> None:
59
+ super().__init__()
60
+ self.mode = mode
61
+
62
+ if mode == "memory":
63
+ if data is None:
64
+ raise ValueError("'data' must be provided when mode='memory'")
65
+ self._data = data
66
+ self._n = self._infer_length(data)
67
+
68
+ elif mode == "disk":
69
+ if path is None:
70
+ raise ValueError("'path' must be provided when mode='disk'")
71
+ self._path = Path(path)
72
+ if not self._path.exists():
73
+ raise FileNotFoundError(f"Dataset file not found: {self._path}")
74
+ # Load just to know the length; keep the full file on disk
75
+ meta = torch.load(self._path, map_location="cpu", weights_only=True)
76
+ if hasattr(self, "snapshot_idx") and self.snapshot_idx is None:
77
+ self.snapshot_idx = meta.get("snapshot_idx") if meta.get("snapshot_idx") is not None else -1
78
+ self._n = self._infer_length(meta["data"])
79
+ self._disk_data: dict[str, Tensor] | None = None # lazy
80
+
81
+ else:
82
+ raise ValueError(f"mode must be 'memory' or 'disk', got {mode!r}")
83
+
84
+ # ------------------------------------------------------------------
85
+ # Abstract interface
86
+ # ------------------------------------------------------------------
87
+
88
+ @abstractmethod
89
+ def _make_pair(self, data: dict[str, Tensor], idx: int) -> tuple[Tensor, Tensor]:
90
+ """Extract ``(input, target)`` tensors for sample ``idx``.
91
+
92
+ Parameters
93
+ ----------
94
+ data : dict[str, Tensor]
95
+ The full raw data dict (all samples).
96
+ idx : int
97
+ Sample index.
98
+
99
+ Returns
100
+ -------
101
+ input : Tensor
102
+ target : Tensor
103
+ """
104
+ ...
105
+
106
+ # ------------------------------------------------------------------
107
+ # Dataset protocol
108
+ # ------------------------------------------------------------------
109
+
110
+ def __len__(self) -> int:
111
+ return self._n
112
+
113
+ def __getitem__(self, idx: int) -> tuple[Tensor, Tensor]:
114
+ data = self._get_data()
115
+ return self._make_pair(data, idx)
116
+
117
+ # ------------------------------------------------------------------
118
+ # Save / load
119
+ # ------------------------------------------------------------------
120
+
121
+ def save(self, path: str | Path) -> None:
122
+ """Serialise the dataset to a ``.pt`` file.
123
+
124
+ Parameters
125
+ ----------
126
+ path : str or Path
127
+ Destination file. The ``.pt`` extension is recommended.
128
+ """
129
+ path = Path(path)
130
+ path.parent.mkdir(parents=True, exist_ok=True)
131
+ data = self._get_data()
132
+ torch.save(
133
+ {
134
+ "data": data,
135
+ "class": self.__class__.__name__,
136
+ "snapshot_idx": getattr(self, "snapshot_idx", None),
137
+ },
138
+ path,
139
+ )
140
+
141
+ @classmethod
142
+ def load(cls, path: str | Path) -> "BasePDEDataset":
143
+ """Load a dataset saved with :meth:`save`.
144
+
145
+ Parameters
146
+ ----------
147
+ path : str or Path
148
+ Path to the ``.pt`` file produced by :meth:`save`.
149
+
150
+ Returns
151
+ -------
152
+ BasePDEDataset
153
+ A new instance in ``"memory"`` mode with the loaded data.
154
+ """
155
+ path = Path(path)
156
+ if not path.exists():
157
+ raise FileNotFoundError(f"Dataset file not found: {path}")
158
+ raw = torch.load(path, map_location="cpu", weights_only=True)
159
+ return cls(data=raw["data"], mode="memory")
160
+
161
+ # ------------------------------------------------------------------
162
+ # DataLoader helper
163
+ # ------------------------------------------------------------------
164
+
165
+ def get_dataloader(
166
+ self,
167
+ batch_size: int = 32,
168
+ shuffle: bool = True,
169
+ num_workers: int = 0,
170
+ **kwargs,
171
+ ) -> DataLoader:
172
+ """Wrap this dataset in a :class:`~torch.utils.data.DataLoader`.
173
+
174
+ Parameters
175
+ ----------
176
+ batch_size : int
177
+ Samples per batch. Default ``32``.
178
+ shuffle : bool
179
+ Whether to shuffle at every epoch. Default ``True``.
180
+ num_workers : int
181
+ Subprocesses for data loading. Default ``0`` (main process).
182
+ **kwargs
183
+ Forwarded to :class:`~torch.utils.data.DataLoader`.
184
+
185
+ Returns
186
+ -------
187
+ DataLoader
188
+ """
189
+ return DataLoader(
190
+ self,
191
+ batch_size=batch_size,
192
+ shuffle=shuffle,
193
+ num_workers=num_workers,
194
+ **kwargs,
195
+ )
196
+
197
+ # ------------------------------------------------------------------
198
+ # Internal helpers
199
+ # ------------------------------------------------------------------
200
+
201
+ def _get_data(self) -> dict[str, Tensor]:
202
+ if self.mode == "memory":
203
+ return self._data
204
+ # Disk mode: load on first access and cache
205
+ if self._disk_data is None:
206
+ raw = torch.load(self._path, map_location="cpu", weights_only=True)
207
+ self._disk_data = raw["data"]
208
+ return self._disk_data
209
+
210
+ @staticmethod
211
+ def _infer_length(data: dict[str, Tensor]) -> int:
212
+ """Return the batch dimension (first dim of any tensor in ``data``)."""
213
+ for v in data.values():
214
+ if isinstance(v, Tensor) and v.dim() >= 1:
215
+ return v.shape[0]
216
+ raise ValueError("Cannot infer dataset length: no tensors found in data dict")
217
+
218
+ def __repr__(self) -> str:
219
+ return (
220
+ f"{self.__class__.__name__}("
221
+ f"n={self._n}, mode={self.mode!r})"
222
+ )
@@ -0,0 +1,97 @@
1
+ """
2
+ PyTorch Dataset for 1D Burgers equation data.
3
+
4
+ Input / target convention
5
+ --------------------------
6
+ input : u(x, 0) — initial condition, shape ``(N,)``
7
+ target : u(x, T) — solution at final snapshot, shape ``(N,)``
8
+
9
+ For multi-step training, the full trajectory is available via
10
+ ``dataset._get_data()["solution"]`` (shape ``(n, N, T_steps)``).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from pathlib import Path
16
+ from typing import Literal
17
+
18
+ import torch
19
+ from torch import Tensor
20
+
21
+ from nops.data.datasets.base import BasePDEDataset
22
+ from nops.data.generators.burgers import BurgersGenerator
23
+
24
+
25
+ class BurgersDataset(BasePDEDataset):
26
+ """Dataset of 1D Burgers equation trajectories.
27
+
28
+ Can be constructed from:
29
+
30
+ - A pre-generated data dict (``data=...``).
31
+ - A :class:`~nops.data.generators.burgers.BurgersGenerator` that is
32
+ called immediately on construction (``generator=...``).
33
+ - A ``.pt`` file produced by :meth:`save` (``path=...``,
34
+ ``mode="disk"``).
35
+
36
+ Parameters
37
+ ----------
38
+ data : dict[str, Tensor] or None
39
+ Pre-built data dict with keys ``"ic"`` and ``"solution"``.
40
+ generator : BurgersGenerator or None
41
+ If provided (and ``data`` is ``None``), :meth:`generate` is called
42
+ with ``n_samples`` immediately.
43
+ n_samples : int
44
+ Number of samples to generate when ``generator`` is given.
45
+ Default ``1000``.
46
+ mode : {"memory", "disk"}
47
+ Storage mode. Default ``"memory"``.
48
+ path : str or Path or None
49
+ File path for disk mode or for loading a saved dataset.
50
+ snapshot_idx : int or None
51
+ Which snapshot to use as target. Defaults to the **last** snapshot
52
+ (``-1``).
53
+
54
+ Examples
55
+ --------
56
+ >>> gen = BurgersGenerator(N=1024, nu=0.1, T=1.0, record_steps=1)
57
+ >>> ds = BurgersDataset(generator=gen, n_samples=200)
58
+ >>> x, y = ds[0]
59
+ >>> x.shape, y.shape # (1024,), (1024,)
60
+
61
+ >>> loader = ds.get_dataloader(batch_size=32)
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ data: dict[str, Tensor] | None = None,
67
+ generator: BurgersGenerator | None = None,
68
+ n_samples: int = 1000,
69
+ mode: Literal["memory", "disk"] = "memory",
70
+ path: str | Path | None = None,
71
+ snapshot_idx: int | None = None,
72
+ ) -> None:
73
+ self.snapshot_idx = snapshot_idx
74
+
75
+ if mode == "disk" and data is None and generator is None:
76
+ super().__init__(mode="disk", path=path)
77
+ return
78
+
79
+ if data is None:
80
+ if generator is None:
81
+ generator = BurgersGenerator()
82
+ data = generator.generate(n_samples)
83
+
84
+ if self.snapshot_idx is None:
85
+ self.snapshot_idx = -1
86
+ super().__init__(data=data, mode=mode)
87
+
88
+ def _make_pair(self, data: dict[str, Tensor], idx: int) -> tuple[Tensor, Tensor]:
89
+ inp = data["ic"][idx] # (N,)
90
+ tgt = data["solution"][idx, :, self.snapshot_idx] # (N,)
91
+ return inp, tgt
92
+
93
+ @classmethod
94
+ def load(cls, path: str | Path) -> "BurgersDataset":
95
+ path = Path(path)
96
+ raw = torch.load(path, map_location="cpu", weights_only=True)
97
+ return cls(data=raw["data"], mode="memory", snapshot_idx=raw.get("snapshot_idx", -1))
@@ -0,0 +1,85 @@
1
+ """
2
+ PyTorch Dataset for 2D Darcy flow data.
3
+
4
+ Input / target convention
5
+ --------------------------
6
+ input : a(x) — permeability coefficient, shape ``(N, N)``
7
+ target : u(x) — pressure solution, shape ``(N, N)``
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pathlib import Path
13
+ from typing import Literal
14
+
15
+ import torch
16
+ from torch import Tensor
17
+
18
+ from nops.data.datasets.base import BasePDEDataset
19
+ from nops.data.generators.darcy import DarcyGenerator
20
+
21
+
22
+ class DarcyDataset(BasePDEDataset):
23
+ """Dataset of 2D Darcy flow permeability-solution pairs.
24
+
25
+ Parameters
26
+ ----------
27
+ data : dict[str, Tensor] or None
28
+ Pre-built data dict with keys ``"coeff"`` and ``"solution"``.
29
+ generator : DarcyGenerator or None
30
+ If provided (and ``data`` is ``None``), :meth:`generate` is called
31
+ immediately with ``n_samples``.
32
+ n_samples : int
33
+ Number of samples to generate. Default ``1000``.
34
+ mode : {"memory", "disk"}
35
+ Storage mode. Default ``"memory"``.
36
+ path : str or Path or None
37
+ File path for disk mode or saved dataset.
38
+ When ``generator`` uses ``solver="file"``, pass ``gen_path`` instead.
39
+ gen_path : str or Path or None
40
+ Path forwarded to :meth:`DarcyGenerator.generate` when
41
+ ``generator.solver == "file"``.
42
+
43
+ Examples
44
+ --------
45
+ >>> gen = DarcyGenerator(N=128, solver="spectral")
46
+ >>> ds = DarcyDataset(generator=gen, n_samples=100)
47
+ >>> x, y = ds[0]
48
+ >>> x.shape, y.shape # (128, 128), (128, 128)
49
+
50
+ >>> # Load FNO benchmark .mat file
51
+ >>> gen = DarcyGenerator(N=421, solver="file")
52
+ >>> ds = DarcyDataset(generator=gen, n_samples=1024,
53
+ ... gen_path="piececonst_r421_N1024_smooth1.mat")
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ data: dict[str, Tensor] | None = None,
59
+ generator: DarcyGenerator | None = None,
60
+ n_samples: int = 1000,
61
+ mode: Literal["memory", "disk"] = "memory",
62
+ path: str | Path | None = None,
63
+ gen_path: str | Path | None = None,
64
+ ) -> None:
65
+ if mode == "disk" and data is None and generator is None:
66
+ super().__init__(mode="disk", path=path)
67
+ return
68
+
69
+ if data is None:
70
+ if generator is None:
71
+ generator = DarcyGenerator()
72
+ data = generator.generate(n_samples, path=gen_path)
73
+
74
+ super().__init__(data=data, mode=mode)
75
+
76
+ def _make_pair(self, data: dict[str, Tensor], idx: int) -> tuple[Tensor, Tensor]:
77
+ inp = data["coeff"][idx] # (N, N)
78
+ tgt = data["solution"][idx] # (N, N)
79
+ return inp, tgt
80
+
81
+ @classmethod
82
+ def load(cls, path: str | Path) -> "DarcyDataset":
83
+ path = Path(path)
84
+ raw = torch.load(path, map_location="cpu", weights_only=True)
85
+ return cls(data=raw["data"], mode="memory")
@@ -0,0 +1,85 @@
1
+ """
2
+ PyTorch Dataset for 1D/2D heat equation data.
3
+
4
+ Input / target convention
5
+ --------------------------
6
+ input : u(x, 0) — initial temperature, shape ``(N,)`` or ``(N, N)``
7
+ target : u(x, T) — temperature at final snapshot, same shape
8
+
9
+ The per-sample diffusivity ``α`` and the full trajectory are available via
10
+ ``dataset._get_data()``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from pathlib import Path
16
+ from typing import Literal
17
+
18
+ import torch
19
+ from torch import Tensor
20
+
21
+ from nops.data.datasets.base import BasePDEDataset
22
+ from nops.data.generators.heat import HeatGenerator
23
+
24
+
25
+ class HeatDataset(BasePDEDataset):
26
+ """Dataset of 1D/2D heat equation trajectories.
27
+
28
+ Parameters
29
+ ----------
30
+ data : dict[str, Tensor] or None
31
+ Pre-built data dict with keys ``"ic"``, ``"solution"``, ``"alpha"``.
32
+ generator : HeatGenerator or None
33
+ If provided (and ``data`` is ``None``), :meth:`generate` is called
34
+ immediately with ``n_samples``.
35
+ n_samples : int
36
+ Number of samples to generate. Default ``1000``.
37
+ mode : {"memory", "disk"}
38
+ Storage mode. Default ``"memory"``.
39
+ path : str or Path or None
40
+ File path for disk mode or saved dataset.
41
+ snapshot_idx : int
42
+ Which snapshot index to use as target. Default ``-1`` (last).
43
+
44
+ Examples
45
+ --------
46
+ >>> gen = HeatGenerator(N=64, dim=2, alpha=0.01, T=1.0, record_steps=1)
47
+ >>> ds = HeatDataset(generator=gen, n_samples=100)
48
+ >>> x, y = ds[0]
49
+ >>> x.shape, y.shape # (64, 64), (64, 64)
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ data: dict[str, Tensor] | None = None,
55
+ generator: HeatGenerator | None = None,
56
+ n_samples: int = 1000,
57
+ mode: Literal["memory", "disk"] = "memory",
58
+ path: str | Path | None = None,
59
+ snapshot_idx: int | None = None,
60
+ ) -> None:
61
+ self.snapshot_idx = snapshot_idx
62
+
63
+ if mode == "disk" and data is None and generator is None:
64
+ super().__init__(mode="disk", path=path)
65
+ return
66
+
67
+ if data is None:
68
+ if generator is None:
69
+ generator = HeatGenerator()
70
+ data = generator.generate(n_samples)
71
+
72
+ if self.snapshot_idx is None:
73
+ self.snapshot_idx = -1
74
+ super().__init__(data=data, mode=mode)
75
+
76
+ def _make_pair(self, data: dict[str, Tensor], idx: int) -> tuple[Tensor, Tensor]:
77
+ inp = data["ic"][idx] # (*spatial)
78
+ tgt = data["solution"][idx, ..., self.snapshot_idx] # (*spatial)
79
+ return inp, tgt
80
+
81
+ @classmethod
82
+ def load(cls, path: str | Path) -> "HeatDataset":
83
+ path = Path(path)
84
+ raw = torch.load(path, map_location="cpu", weights_only=True)
85
+ return cls(data=raw["data"], mode="memory", snapshot_idx=raw.get("snapshot_idx", -1))