dcoupler 0.2.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 (49) hide show
  1. dcoupler-0.2.0/LICENSE +191 -0
  2. dcoupler-0.2.0/PKG-INFO +101 -0
  3. dcoupler-0.2.0/README.md +61 -0
  4. dcoupler-0.2.0/dcoupler/__init__.py +52 -0
  5. dcoupler-0.2.0/dcoupler/components/__init__.py +13 -0
  6. dcoupler-0.2.0/dcoupler/components/fuse.py +193 -0
  7. dcoupler-0.2.0/dcoupler/components/routing.py +219 -0
  8. dcoupler-0.2.0/dcoupler/core/__init__.py +26 -0
  9. dcoupler-0.2.0/dcoupler/core/bmi.py +76 -0
  10. dcoupler-0.2.0/dcoupler/core/component.py +158 -0
  11. dcoupler-0.2.0/dcoupler/core/connection.py +118 -0
  12. dcoupler-0.2.0/dcoupler/core/conservation.py +55 -0
  13. dcoupler-0.2.0/dcoupler/core/graph.py +394 -0
  14. dcoupler-0.2.0/dcoupler/core/temporal.py +31 -0
  15. dcoupler-0.2.0/dcoupler/diagnostics/__init__.py +3 -0
  16. dcoupler-0.2.0/dcoupler/diagnostics/gradients.py +125 -0
  17. dcoupler-0.2.0/dcoupler/losses/__init__.py +29 -0
  18. dcoupler-0.2.0/dcoupler/losses/hydrological.py +159 -0
  19. dcoupler-0.2.0/dcoupler/observers/__init__.py +4 -0
  20. dcoupler-0.2.0/dcoupler/observers/base.py +29 -0
  21. dcoupler-0.2.0/dcoupler/observers/streamflow.py +34 -0
  22. dcoupler-0.2.0/dcoupler/optimization/__init__.py +11 -0
  23. dcoupler-0.2.0/dcoupler/optimization/multi_observation.py +102 -0
  24. dcoupler-0.2.0/dcoupler/optimization/parameters.py +139 -0
  25. dcoupler-0.2.0/dcoupler/optimization/trainer.py +196 -0
  26. dcoupler-0.2.0/dcoupler/py.typed +0 -0
  27. dcoupler-0.2.0/dcoupler/utils/__init__.py +3 -0
  28. dcoupler-0.2.0/dcoupler/utils/temporal.py +45 -0
  29. dcoupler-0.2.0/dcoupler/wrappers/__init__.py +17 -0
  30. dcoupler-0.2.0/dcoupler/wrappers/enzyme.py +188 -0
  31. dcoupler-0.2.0/dcoupler/wrappers/jax.py +420 -0
  32. dcoupler-0.2.0/dcoupler/wrappers/process.py +248 -0
  33. dcoupler-0.2.0/dcoupler.egg-info/PKG-INFO +101 -0
  34. dcoupler-0.2.0/dcoupler.egg-info/SOURCES.txt +47 -0
  35. dcoupler-0.2.0/dcoupler.egg-info/dependency_links.txt +1 -0
  36. dcoupler-0.2.0/dcoupler.egg-info/requires.txt +17 -0
  37. dcoupler-0.2.0/dcoupler.egg-info/top_level.txt +1 -0
  38. dcoupler-0.2.0/pyproject.toml +66 -0
  39. dcoupler-0.2.0/setup.cfg +4 -0
  40. dcoupler-0.2.0/tests/test_bmi_protocol.py +168 -0
  41. dcoupler-0.2.0/tests/test_conservation_integration.py +208 -0
  42. dcoupler-0.2.0/tests/test_deps_smoke.py +20 -0
  43. dcoupler-0.2.0/tests/test_equivalence.py +127 -0
  44. dcoupler-0.2.0/tests/test_graph.py +201 -0
  45. dcoupler-0.2.0/tests/test_jax_component.py +174 -0
  46. dcoupler-0.2.0/tests/test_phase3.py +91 -0
  47. dcoupler-0.2.0/tests/test_phase4.py +129 -0
  48. dcoupler-0.2.0/tests/test_phase5.py +318 -0
  49. dcoupler-0.2.0/tests/test_process_component.py +145 -0
dcoupler-0.2.0/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2024 Darri Eythorsson
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: dcoupler
3
+ Version: 0.2.0
4
+ Summary: Differentiable Earth System Coupler
5
+ Author-email: Darri Eythorsson <darri.eythorsson@ucalgary.ca>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Repository, https://github.com/DarriEy/dcoupler
8
+ Project-URL: Homepage, https://github.com/DarriEy/dcoupler
9
+ Project-URL: Issues, https://github.com/DarriEy/dcoupler/issues
10
+ Keywords: hydrology,differentiable,coupling,earth-system,pytorch
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Scientific/Engineering :: Hydrology
21
+ Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: torch>=2.0
27
+ Requires-Dist: numpy
28
+ Requires-Dist: scipy
29
+ Requires-Dist: xarray
30
+ Provides-Extra: jax
31
+ Requires-Dist: jax>=0.4; extra == "jax"
32
+ Requires-Dist: jaxlib; extra == "jax"
33
+ Provides-Extra: models
34
+ Provides-Extra: dev
35
+ Requires-Dist: pytest; extra == "dev"
36
+ Requires-Dist: pytest-cov; extra == "dev"
37
+ Provides-Extra: all
38
+ Requires-Dist: dcoupler[dev,jax]; extra == "all"
39
+ Dynamic: license-file
40
+
41
+ # dCoupler
42
+
43
+ Differentiable Earth System Coupler — a PyTorch-based framework for building
44
+ differentiable coupling graphs between hydrological and earth system model
45
+ components.
46
+
47
+ ## Quickstart
48
+
49
+ ```bash
50
+ pip install dcoupler
51
+ ```
52
+
53
+ ```python
54
+ import torch
55
+ import dcoupler as dc
56
+
57
+ # Define two components
58
+ class Bucket(dc.DifferentiableComponent):
59
+ ...
60
+
61
+ class Router(dc.DifferentiableComponent):
62
+ ...
63
+
64
+ # Build coupling graph
65
+ graph = dc.CouplingGraph()
66
+ graph.add_component(bucket)
67
+ graph.add_component(router)
68
+ graph.connect("bucket", "runoff", "router", "lateral_inflow")
69
+
70
+ # Run forward
71
+ outputs = graph.forward(external_inputs, n_timesteps=365, dt=86400)
72
+
73
+ # Optimize via backprop
74
+ loss = loss_fn(outputs, observations)
75
+ loss.backward()
76
+ optimizer.step()
77
+ ```
78
+
79
+ ## Component Types
80
+
81
+ | Type | Gradient | Use Case |
82
+ |------|----------|----------|
83
+ | `DifferentiableComponent` | PyTorch autograd | Pure PyTorch models |
84
+ | `JAXComponent` | JAX vjp via bridge | JAX models (XAJ, SAC-SMA, Snow-17) |
85
+ | `ProcessComponent` | None / finite diff | External executables (SUMMA, MESH) |
86
+ | `EnzymeComponent` | Enzyme AD | C++ models with Enzyme |
87
+
88
+ All component types implement the `BMIMixin` protocol for standardized
89
+ lifecycle management (initialize/update/finalize).
90
+
91
+ ## Optional Dependencies
92
+
93
+ ```bash
94
+ pip install dcoupler[jax] # JAX bridge support
95
+ pip install dcoupler[models] # cfuse + droute components
96
+ pip install dcoupler[all] # Everything
97
+ ```
98
+
99
+ ## License
100
+
101
+ Apache 2.0 — see [LICENSE](LICENSE) for details.
@@ -0,0 +1,61 @@
1
+ # dCoupler
2
+
3
+ Differentiable Earth System Coupler — a PyTorch-based framework for building
4
+ differentiable coupling graphs between hydrological and earth system model
5
+ components.
6
+
7
+ ## Quickstart
8
+
9
+ ```bash
10
+ pip install dcoupler
11
+ ```
12
+
13
+ ```python
14
+ import torch
15
+ import dcoupler as dc
16
+
17
+ # Define two components
18
+ class Bucket(dc.DifferentiableComponent):
19
+ ...
20
+
21
+ class Router(dc.DifferentiableComponent):
22
+ ...
23
+
24
+ # Build coupling graph
25
+ graph = dc.CouplingGraph()
26
+ graph.add_component(bucket)
27
+ graph.add_component(router)
28
+ graph.connect("bucket", "runoff", "router", "lateral_inflow")
29
+
30
+ # Run forward
31
+ outputs = graph.forward(external_inputs, n_timesteps=365, dt=86400)
32
+
33
+ # Optimize via backprop
34
+ loss = loss_fn(outputs, observations)
35
+ loss.backward()
36
+ optimizer.step()
37
+ ```
38
+
39
+ ## Component Types
40
+
41
+ | Type | Gradient | Use Case |
42
+ |------|----------|----------|
43
+ | `DifferentiableComponent` | PyTorch autograd | Pure PyTorch models |
44
+ | `JAXComponent` | JAX vjp via bridge | JAX models (XAJ, SAC-SMA, Snow-17) |
45
+ | `ProcessComponent` | None / finite diff | External executables (SUMMA, MESH) |
46
+ | `EnzymeComponent` | Enzyme AD | C++ models with Enzyme |
47
+
48
+ All component types implement the `BMIMixin` protocol for standardized
49
+ lifecycle management (initialize/update/finalize).
50
+
51
+ ## Optional Dependencies
52
+
53
+ ```bash
54
+ pip install dcoupler[jax] # JAX bridge support
55
+ pip install dcoupler[models] # cfuse + droute components
56
+ pip install dcoupler[all] # Everything
57
+ ```
58
+
59
+ ## License
60
+
61
+ Apache 2.0 — see [LICENSE](LICENSE) for details.
@@ -0,0 +1,52 @@
1
+ from dcoupler.core import (
2
+ CouplingGraph,
3
+ DifferentiableComponent,
4
+ FluxDirection,
5
+ FluxSpec,
6
+ GradientMethod,
7
+ ParameterSpec,
8
+ FluxConnection,
9
+ SpatialRemapper,
10
+ TemporalOrchestrator,
11
+ ConservationChecker,
12
+ BMIMixin,
13
+ )
14
+ from dcoupler.optimization import (
15
+ ParameterManager,
16
+ MultiObservationLoss,
17
+ LossTerm,
18
+ Trainer,
19
+ TrainingResult,
20
+ )
21
+ from dcoupler import observers as _observers
22
+ from dcoupler import diagnostics as _diagnostics
23
+ from dcoupler import utils as _utils
24
+ from dcoupler.observers import * # noqa: F401,F403
25
+ from dcoupler.diagnostics import * # noqa: F401,F403
26
+ from dcoupler import losses as _losses
27
+ from dcoupler import components as _components
28
+ from dcoupler import wrappers as _wrappers
29
+ from dcoupler.losses import * # noqa: F401,F403
30
+ from dcoupler.components import * # noqa: F401,F403
31
+ from dcoupler.wrappers import * # noqa: F401,F403
32
+
33
+ __version__ = "0.2.0"
34
+
35
+ __all__ = [
36
+ "CouplingGraph",
37
+ "DifferentiableComponent",
38
+ "FluxDirection",
39
+ "FluxSpec",
40
+ "GradientMethod",
41
+ "ParameterSpec",
42
+ "FluxConnection",
43
+ "SpatialRemapper",
44
+ "TemporalOrchestrator",
45
+ "ConservationChecker",
46
+ "BMIMixin",
47
+ "ParameterManager",
48
+ "MultiObservationLoss",
49
+ "LossTerm",
50
+ "Trainer",
51
+ "TrainingResult",
52
+ ] + _losses.__all__ + _components.__all__ + _wrappers.__all__ + _observers.__all__ + _diagnostics.__all__ + _utils.__all__
@@ -0,0 +1,13 @@
1
+ __all__ = []
2
+
3
+ try:
4
+ from .fuse import FUSEComponent
5
+ __all__.append("FUSEComponent")
6
+ except Exception:
7
+ FUSEComponent = None # type: ignore
8
+
9
+ try:
10
+ from .routing import MuskingumCungeRouting
11
+ __all__.append("MuskingumCungeRouting")
12
+ except Exception:
13
+ MuskingumCungeRouting = None # type: ignore
@@ -0,0 +1,193 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Dict, List, Optional
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+ from dcoupler.core.component import (
8
+ DifferentiableComponent,
9
+ FluxDirection,
10
+ FluxSpec,
11
+ GradientMethod,
12
+ ParameterSpec,
13
+ )
14
+
15
+ try:
16
+ import cfuse
17
+ import cfuse_core
18
+ from cfuse.torch import DifferentiableFUSEBatch
19
+ except ImportError:
20
+ cfuse = None
21
+ cfuse_core = None
22
+ DifferentiableFUSEBatch = None
23
+
24
+
25
+ class FUSEComponent(DifferentiableComponent, nn.Module):
26
+ """FUSE component wrapper using DifferentiableFUSEBatch."""
27
+
28
+ def __init__(
29
+ self,
30
+ name: str,
31
+ fuse_config,
32
+ n_hrus: int,
33
+ dt: float = 86400.0,
34
+ spatial_params: bool = True,
35
+ n_states: Optional[int] = None,
36
+ ) -> None:
37
+ super().__init__()
38
+ if DifferentiableFUSEBatch is None or cfuse is None:
39
+ raise RuntimeError("cfuse and DifferentiableFUSEBatch are required for FUSEComponent")
40
+ if fuse_config is None:
41
+ raise ValueError("fuse_config is required")
42
+
43
+ self._name = name
44
+ self.fuse_config = fuse_config
45
+ self.config_dict = fuse_config.to_dict() if hasattr(fuse_config, "to_dict") else fuse_config
46
+ self.n_hrus = n_hrus
47
+ self.dt_seconds = float(dt)
48
+ self.dt_days = self.dt_seconds / 86400.0
49
+ self.spatial_params = spatial_params
50
+
51
+ if n_states is None:
52
+ if cfuse_core is None:
53
+ raise RuntimeError("cfuse_core required to infer state size")
54
+ self.n_states = int(cfuse_core.get_num_active_states(self.config_dict))
55
+ else:
56
+ self.n_states = int(n_states)
57
+
58
+ self.param_names = list(cfuse.PARAM_NAMES)
59
+ self.n_params = len(self.param_names)
60
+ lowers = torch.tensor([cfuse.PARAM_BOUNDS[n][0] for n in self.param_names], dtype=torch.float32)
61
+ uppers = torch.tensor([cfuse.PARAM_BOUNDS[n][1] for n in self.param_names], dtype=torch.float32)
62
+ self.register_buffer("param_lower", lowers)
63
+ self.register_buffer("param_upper", uppers)
64
+
65
+ self._raw_params = nn.ParameterList()
66
+ for _ in range(self.n_params):
67
+ if self.spatial_params:
68
+ init = torch.zeros(self.n_hrus) + torch.randn(self.n_hrus) * 0.2
69
+ else:
70
+ init = torch.zeros(())
71
+ self._raw_params.append(nn.Parameter(init))
72
+
73
+ @property
74
+ def name(self) -> str:
75
+ return self._name
76
+
77
+ @property
78
+ def input_fluxes(self) -> List[FluxSpec]:
79
+ return [
80
+ FluxSpec(
81
+ name="forcing",
82
+ units="mixed",
83
+ direction=FluxDirection.INPUT,
84
+ spatial_type="hru",
85
+ temporal_resolution=self.dt_seconds,
86
+ dims=("time", "hru", "var"),
87
+ optional=False,
88
+ )
89
+ ]
90
+
91
+ @property
92
+ def output_fluxes(self) -> List[FluxSpec]:
93
+ return [
94
+ FluxSpec(
95
+ name="runoff",
96
+ units="mm/day",
97
+ direction=FluxDirection.OUTPUT,
98
+ spatial_type="hru",
99
+ temporal_resolution=self.dt_seconds,
100
+ dims=("time", "hru"),
101
+ conserved_quantity="water_mass",
102
+ )
103
+ ]
104
+
105
+ @property
106
+ def parameters(self) -> List[ParameterSpec]:
107
+ specs: List[ParameterSpec] = []
108
+ for i, name in enumerate(self.param_names):
109
+ specs.append(
110
+ ParameterSpec(
111
+ name=name,
112
+ lower_bound=float(self.param_lower[i].item()),
113
+ upper_bound=float(self.param_upper[i].item()),
114
+ spatial=self.spatial_params,
115
+ n_spatial=self.n_hrus if self.spatial_params else None,
116
+ log_transform=False,
117
+ )
118
+ )
119
+ return specs
120
+
121
+ @property
122
+ def gradient_method(self) -> GradientMethod:
123
+ return GradientMethod.ENZYME
124
+
125
+ @property
126
+ def state_size(self) -> int:
127
+ return self.n_states
128
+
129
+ @property
130
+ def requires_batch(self) -> bool:
131
+ return True
132
+
133
+ def get_initial_state(self) -> torch.Tensor:
134
+ state = torch.zeros(self.n_hrus, self.n_states)
135
+ if self.n_states > 0:
136
+ state[:, 0] = 50.0
137
+ if self.n_states > 1:
138
+ state[:, 1] = 20.0
139
+ if self.n_states > 2:
140
+ state[:, 2] = 200.0
141
+ return state
142
+
143
+ def _raw_param_matrix(self) -> torch.Tensor:
144
+ if self.spatial_params:
145
+ return torch.stack(list(self._raw_params), dim=1)
146
+ return torch.stack(list(self._raw_params), dim=0)
147
+
148
+ def get_physical_parameters(self) -> Dict[str, torch.Tensor]:
149
+ raw = self._raw_param_matrix()
150
+ if self.spatial_params:
151
+ phys = self.param_lower + (self.param_upper - self.param_lower) * torch.sigmoid(raw)
152
+ else:
153
+ phys = self.param_lower + (self.param_upper - self.param_lower) * torch.sigmoid(raw)
154
+ return {name: phys[:, i] if self.spatial_params else phys[i] for i, name in enumerate(self.param_names)}
155
+
156
+ def _physical_param_tensor(self) -> torch.Tensor:
157
+ raw = self._raw_param_matrix()
158
+ if self.spatial_params:
159
+ return self.param_lower + (self.param_upper - self.param_lower) * torch.sigmoid(raw)
160
+ return self.param_lower + (self.param_upper - self.param_lower) * torch.sigmoid(raw)
161
+
162
+ def step(
163
+ self,
164
+ inputs: Dict[str, torch.Tensor],
165
+ state: torch.Tensor,
166
+ dt: float,
167
+ ):
168
+ raise RuntimeError("FUSEComponent requires batch execution")
169
+
170
+ def run(
171
+ self,
172
+ inputs: Dict[str, torch.Tensor],
173
+ state: torch.Tensor,
174
+ dt: float,
175
+ n_timesteps: int,
176
+ ):
177
+ forcing = inputs.get("forcing")
178
+ if forcing is None:
179
+ raise ValueError("Missing required input 'forcing'")
180
+ phys_params = self._physical_param_tensor()
181
+ if state is None:
182
+ state = self.get_initial_state().to(forcing.device)
183
+ runoff = DifferentiableFUSEBatch.apply(
184
+ phys_params,
185
+ state,
186
+ forcing,
187
+ self.config_dict,
188
+ self.dt_days,
189
+ )
190
+ return {"runoff": runoff}, state
191
+
192
+ def get_torch_parameters(self) -> List[torch.nn.Parameter]:
193
+ return list(self._raw_params)