dots-causal 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 CHAI-UK
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: dots-causal
3
+ Version: 0.1.0
4
+ Summary: DOTS (Diffusion Ordered Temporal Structure): causal structure learning from time series.
5
+ Author: Pedro Sanchez, Damian Machlanski, Steven McDonagh, Sotirios A. Tsaftaris
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/chai-uk/dots
8
+ Project-URL: Paper, https://openreview.net/forum?id=hWuTzqggSd
9
+ Project-URL: Benchmark, https://chai-uk.github.io/tscd-benchmark/
10
+ Keywords: causal discovery,time series,diffusion models,structure learning
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: torch>=2.0
19
+ Requires-Dist: numpy
20
+ Requires-Dist: pandas
21
+ Requires-Dist: scikit-learn
22
+ Requires-Dist: networkx
23
+ Requires-Dist: tqdm
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest; extra == "test"
26
+ Dynamic: license-file
27
+
28
+ # Diffusion Ordered Temporal Structure (DOTS)
29
+
30
+ This repository accompanies the paper "Causal Ordering for Structure Learning from Time Series" published in Transactions on Machine Learning Research ([link to the paper](https://openreview.net/forum?id=hWuTzqggSd)).
31
+
32
+ **See also:** [Time Series Causal Discovery Benchmark](https://chai-uk.github.io/tscd-benchmark/) (used to run experiments).
33
+
34
+ > **Reproducing the paper?** Use the [`tmlr-2025`](https://github.com/chai-uk/dots/tree/tmlr-2025) release.
35
+ > It contains the exact code and conda environment used for the paper's results.
36
+ > The `main` branch holds the actively maintained `dots-causal` Python package, which may change over time.
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install dots-causal
42
+ ```
43
+
44
+ or, from a clone of this repository:
45
+
46
+ ```bash
47
+ pip install -e .
48
+ ```
49
+
50
+ ### Requirement: R with `mgcv`
51
+
52
+ The final pruning step of DOTS (CAM pruning) runs in R. You need:
53
+
54
+ 1. R installed, with `Rscript` on your `PATH` ([CRAN](https://cran.r-project.org/)).
55
+ 2. The `mgcv` R package:
56
+
57
+ ```bash
58
+ Rscript -e 'install.packages("mgcv", repos = "https://cloud.r-project.org")'
59
+ ```
60
+
61
+ If R or `mgcv` is missing, `DOTS.fit` raises `dots_causal.RNotFoundError` with instructions.
62
+
63
+ Alternatively, conda can install Python, R and `mgcv` together. From the repository root:
64
+
65
+ ```bash
66
+ conda env create -f environment.yml
67
+ conda activate dots
68
+ ```
69
+
70
+ A GPU is used automatically when PyTorch detects CUDA; otherwise DOTS runs on CPU.
71
+
72
+ ## Quick start
73
+
74
+ DOTS takes *lagged* data: one column per variable per lag
75
+ (e.g. `X1_lag0, X2_lag0, X1_lag1, X2_lag1`, ...), with variables ordered within each lag.
76
+
77
+ ```python
78
+ import pandas as pd
79
+ from dots_causal import DOTS
80
+
81
+ data_lagged = pd.read_csv("data/samples_lagged.csv") # columns: X1_lag0, X2_lag0, X3_lag0, X1_lag1, ...
82
+ nb_vars = 3
83
+ nb_nodes = data_lagged.shape[1]
84
+ nb_lags = nb_nodes // nb_vars
85
+
86
+ model = DOTS(nb_nodes)
87
+ adj = model.fit(data_lagged.to_numpy(), nb_timesteps=nb_lags, nb_variables=nb_vars)
88
+
89
+ adj_df = pd.DataFrame(adj, columns=data_lagged.columns, index=data_lagged.columns)
90
+ ```
91
+
92
+ `adj[i, j] == 1` means an estimated edge from node `i` to node `j`.
93
+
94
+ ### Evaluating against a known graph
95
+
96
+ ```python
97
+ from dots_causal import perform_eval, read_json
98
+
99
+ graphs_true = read_json("data/graphs_true.json")
100
+ print(perform_eval(graphs_true, adj_df, ["X1", "X2", "X3"]))
101
+ ```
102
+
103
+ ## Demo
104
+
105
+ From the repository root, run `sh setup-run.sh` to create the conda environment and run the demo in one step, or after installing:
106
+
107
+ ```bash
108
+ python demo.py
109
+ ```
110
+
111
+ There is also an interactive [notebook demo](https://github.com/chai-uk/dots/blob/main/demo.ipynb).
112
+
113
+ ## Replicating Experiments
114
+
115
+ You can use the [TSCD Benchmark](https://chai-uk.github.io/tscd-benchmark/) to fully replicate our results in an end-to-end manner.
116
+
117
+ ## Cite Us
118
+
119
+ ```
120
+ @article{sanchez2025causal,
121
+ title={Causal Ordering for Structure Learning from Time Series},
122
+ author={Pedro Sanchez and Damian Machlanski and Steven McDonagh and Sotirios A. Tsaftaris},
123
+ journal={Transactions on Machine Learning Research},
124
+ issn={2835-8856},
125
+ year={2025},
126
+ url={https://openreview.net/forum?id=hWuTzqggSd}}
127
+ ```
@@ -0,0 +1,100 @@
1
+ # Diffusion Ordered Temporal Structure (DOTS)
2
+
3
+ This repository accompanies the paper "Causal Ordering for Structure Learning from Time Series" published in Transactions on Machine Learning Research ([link to the paper](https://openreview.net/forum?id=hWuTzqggSd)).
4
+
5
+ **See also:** [Time Series Causal Discovery Benchmark](https://chai-uk.github.io/tscd-benchmark/) (used to run experiments).
6
+
7
+ > **Reproducing the paper?** Use the [`tmlr-2025`](https://github.com/chai-uk/dots/tree/tmlr-2025) release.
8
+ > It contains the exact code and conda environment used for the paper's results.
9
+ > The `main` branch holds the actively maintained `dots-causal` Python package, which may change over time.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pip install dots-causal
15
+ ```
16
+
17
+ or, from a clone of this repository:
18
+
19
+ ```bash
20
+ pip install -e .
21
+ ```
22
+
23
+ ### Requirement: R with `mgcv`
24
+
25
+ The final pruning step of DOTS (CAM pruning) runs in R. You need:
26
+
27
+ 1. R installed, with `Rscript` on your `PATH` ([CRAN](https://cran.r-project.org/)).
28
+ 2. The `mgcv` R package:
29
+
30
+ ```bash
31
+ Rscript -e 'install.packages("mgcv", repos = "https://cloud.r-project.org")'
32
+ ```
33
+
34
+ If R or `mgcv` is missing, `DOTS.fit` raises `dots_causal.RNotFoundError` with instructions.
35
+
36
+ Alternatively, conda can install Python, R and `mgcv` together. From the repository root:
37
+
38
+ ```bash
39
+ conda env create -f environment.yml
40
+ conda activate dots
41
+ ```
42
+
43
+ A GPU is used automatically when PyTorch detects CUDA; otherwise DOTS runs on CPU.
44
+
45
+ ## Quick start
46
+
47
+ DOTS takes *lagged* data: one column per variable per lag
48
+ (e.g. `X1_lag0, X2_lag0, X1_lag1, X2_lag1`, ...), with variables ordered within each lag.
49
+
50
+ ```python
51
+ import pandas as pd
52
+ from dots_causal import DOTS
53
+
54
+ data_lagged = pd.read_csv("data/samples_lagged.csv") # columns: X1_lag0, X2_lag0, X3_lag0, X1_lag1, ...
55
+ nb_vars = 3
56
+ nb_nodes = data_lagged.shape[1]
57
+ nb_lags = nb_nodes // nb_vars
58
+
59
+ model = DOTS(nb_nodes)
60
+ adj = model.fit(data_lagged.to_numpy(), nb_timesteps=nb_lags, nb_variables=nb_vars)
61
+
62
+ adj_df = pd.DataFrame(adj, columns=data_lagged.columns, index=data_lagged.columns)
63
+ ```
64
+
65
+ `adj[i, j] == 1` means an estimated edge from node `i` to node `j`.
66
+
67
+ ### Evaluating against a known graph
68
+
69
+ ```python
70
+ from dots_causal import perform_eval, read_json
71
+
72
+ graphs_true = read_json("data/graphs_true.json")
73
+ print(perform_eval(graphs_true, adj_df, ["X1", "X2", "X3"]))
74
+ ```
75
+
76
+ ## Demo
77
+
78
+ From the repository root, run `sh setup-run.sh` to create the conda environment and run the demo in one step, or after installing:
79
+
80
+ ```bash
81
+ python demo.py
82
+ ```
83
+
84
+ There is also an interactive [notebook demo](https://github.com/chai-uk/dots/blob/main/demo.ipynb).
85
+
86
+ ## Replicating Experiments
87
+
88
+ You can use the [TSCD Benchmark](https://chai-uk.github.io/tscd-benchmark/) to fully replicate our results in an end-to-end manner.
89
+
90
+ ## Cite Us
91
+
92
+ ```
93
+ @article{sanchez2025causal,
94
+ title={Causal Ordering for Structure Learning from Time Series},
95
+ author={Pedro Sanchez and Damian Machlanski and Steven McDonagh and Sotirios A. Tsaftaris},
96
+ journal={Transactions on Machine Learning Research},
97
+ issn={2835-8856},
98
+ year={2025},
99
+ url={https://openreview.net/forum?id=hWuTzqggSd}}
100
+ ```
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "dots-causal"
7
+ dynamic = ["version"]
8
+ description = "DOTS (Diffusion Ordered Temporal Structure): causal structure learning from time series."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ authors = [
14
+ { name = "Pedro Sanchez" },
15
+ { name = "Damian Machlanski" },
16
+ { name = "Steven McDonagh" },
17
+ { name = "Sotirios A. Tsaftaris" },
18
+ ]
19
+ keywords = ["causal discovery", "time series", "diffusion models", "structure learning"]
20
+ classifiers = [
21
+ "Programming Language :: Python :: 3",
22
+ "Operating System :: OS Independent",
23
+ "Intended Audience :: Science/Research",
24
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
25
+ ]
26
+ dependencies = [
27
+ "torch>=2.0",
28
+ "numpy",
29
+ "pandas",
30
+ "scikit-learn",
31
+ "networkx",
32
+ "tqdm",
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ test = ["pytest"]
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/chai-uk/dots"
40
+ Paper = "https://openreview.net/forum?id=hWuTzqggSd"
41
+ Benchmark = "https://chai-uk.github.io/tscd-benchmark/"
42
+
43
+ [tool.setuptools.dynamic]
44
+ version = { attr = "dots_causal.__version__" }
45
+
46
+ [tool.setuptools.packages.find]
47
+ where = ["src"]
48
+
49
+ [tool.setuptools.package-data]
50
+ dots_causal = ["r_scripts/*.R"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,21 @@
1
+ """DOTS: Diffusion Ordered Temporal Structure.
2
+
3
+ Causal structure learning from time series, as described in
4
+ "Causal Ordering for Structure Learning from Time Series" (TMLR 2025).
5
+ """
6
+ from .dots import DOTS, DiffBase
7
+ from .eval_utils import perform_eval, read_json
8
+ from .pruning import RNotFoundError
9
+ from .utils import apply_temporal_constraint
10
+
11
+ __version__ = "0.1.0"
12
+
13
+ __all__ = [
14
+ "DOTS",
15
+ "DiffBase",
16
+ "perform_eval",
17
+ "read_json",
18
+ "apply_temporal_constraint",
19
+ "RNotFoundError",
20
+ "__version__",
21
+ ]
@@ -0,0 +1,12 @@
1
+ """Compatibility shims.
2
+
3
+ `functorch` was merged into PyTorch as `torch.func` (PyTorch >= 2.0).
4
+ Prefer `torch.func` and fall back to the standalone `functorch` package
5
+ for older PyTorch installs.
6
+ """
7
+ try:
8
+ from torch.func import vmap, jacrev, jacfwd
9
+ except ImportError: # pragma: no cover - PyTorch < 2.0
10
+ from functorch import vmap, jacrev, jacfwd
11
+
12
+ __all__ = ["vmap", "jacrev", "jacfwd"]
@@ -0,0 +1,283 @@
1
+ import torch
2
+ import numpy as np
3
+
4
+ from ._compat import vmap, jacrev, jacfwd
5
+ from collections import Counter
6
+ from copy import deepcopy
7
+ from tqdm import tqdm
8
+ from itertools import permutations
9
+ from sklearn.mixture import GaussianMixture
10
+
11
+ from .gaussian_diffusion import GaussianDiffusion, UniformSampler, get_named_beta_schedule, \
12
+ LossType, ModelMeanType, ModelVarType
13
+ from .nn import DiffMLP
14
+ from .pruning import cam_pruning
15
+ from .utils import full_DAG, get_soft_transitive_closure_from_orderings, apply_temporal_constraint
16
+
17
+ class DiffBase():
18
+ def __init__(self, n_nodes, masking = True, residue= True,
19
+ epochs: int = int(3e3), batch_size : int = 1024, learning_rate : float = 0.001, nn_depth_mul=3, steps=1e2, esw=300):
20
+ self.n_nodes = n_nodes
21
+ assert self.n_nodes > 1, "Not enough nodes, make sure the dataset contain at least 2 variables (columns)."
22
+ self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
23
+
24
+ ## Diffusion parameters
25
+ self.n_steps = int(steps)
26
+ betas = get_named_beta_schedule(schedule_name = "linear",
27
+ num_diffusion_timesteps = self.n_steps, scale = 1,
28
+ beta_start = 0.0001, beta_end = 0.02)
29
+ self.gaussian_diffusion = GaussianDiffusion(betas = betas,
30
+ loss_type = LossType.MSE,
31
+ model_mean_type= ModelMeanType.EPSILON,#START_X,EPSILON
32
+ model_var_type= ModelVarType.FIXED_LARGE,
33
+ rescale_timesteps = True,
34
+ )
35
+ self.schedule_sampler = UniformSampler(self.gaussian_diffusion)
36
+
37
+ ## Diffusion training
38
+ self.epochs = epochs
39
+ self.batch_size = int(batch_size)
40
+ self.model = DiffMLP(n_nodes, depth_mul= nn_depth_mul).to(self.device)
41
+ n_trainable_params = sum(p.numel() for p in self.model.parameters() if p.requires_grad)
42
+ print(f'MLP number of parameters {n_trainable_params}')
43
+ self.model.float()
44
+ self.opt = torch.optim.Adam(self.model.parameters(), float(learning_rate))
45
+ self.val_diffusion_loss = []
46
+ self.best_loss = float("inf")
47
+ self.early_stopping_wait = esw
48
+
49
+ ## Topological Ordering
50
+ self.n_votes = 3
51
+ self.masking = masking
52
+ self.residue = residue
53
+ self.sorting = (not masking) and (not residue)
54
+ ## Pruning
55
+ self.cutoff = 0.001
56
+
57
+ def fit(self, X, constraint=False, inst_const=True, nb_timesteps=-1, nb_variables=-1, nb_orderings=10):
58
+ X = self.normalize_data(X)
59
+ self.train_score(X)
60
+ order = self.topological_ordering(X)
61
+ adj = self.pruning(order, X.detach().cpu().numpy())
62
+ if constraint:
63
+ adj = apply_temporal_constraint(adj, nb_timesteps, nb_variables, inst_const)
64
+ return adj
65
+
66
+ def normalize_data(self, X):
67
+ X = (X - X.mean(0, keepdims = True)) / X.std(0, keepdims = True)
68
+ X = torch.FloatTensor(X).to(self.device)
69
+ return X
70
+
71
+ def pruning(self, order, X):
72
+ return cam_pruning(full_DAG(order), X, self.cutoff)
73
+
74
+ def pruning_adj(self, adj, X):
75
+ return cam_pruning(adj, X, self.cutoff)
76
+
77
+ def train_score(self, X, fixed = None):
78
+ if fixed is not None:
79
+ self.epochs = fixed
80
+ best_model_state_epoch = 300
81
+ self.model.train()
82
+ n_samples = X.shape[0]
83
+ self.batch_size = min(n_samples, self.batch_size)
84
+ val_ratio = 0.2
85
+ val_size = int(n_samples * val_ratio)
86
+ train_size = n_samples - val_size
87
+ X = X.to(self.device)
88
+ X_train, X_val = X[:train_size],X[train_size:]
89
+ data_loader_val = torch.utils.data.DataLoader(X_val, min(val_size, self.batch_size))
90
+ data_loader = torch.utils.data.DataLoader(X_train, min(train_size, self.batch_size), drop_last= True)
91
+ pbar = tqdm(range(self.epochs), desc = "Training Epoch")
92
+ for epoch in pbar:
93
+ loss_per_step = []
94
+ for steps, x_start in enumerate(data_loader):
95
+ # apply noising and masking
96
+ x_start = x_start.float().to(self.device)
97
+ t, weights = self.schedule_sampler.sample(x_start.shape[0], self.device)
98
+ noise = torch.randn_like(x_start).to(self.device)
99
+ x_t = self.gaussian_diffusion.q_sample(x_start, t, noise=noise)
100
+ # get loss function
101
+ model_output = self.model(x_t, self.gaussian_diffusion._scale_timesteps(t))
102
+ diffusion_losses = (noise - model_output) ** 2
103
+ diffusion_loss = (diffusion_losses.mean(dim=list(range(1, len(diffusion_losses.shape)))) * weights).mean()
104
+ loss_per_step.append(diffusion_loss.item())
105
+ self.opt.zero_grad()
106
+ diffusion_loss.backward()
107
+ self.opt.step()
108
+ if fixed is None:
109
+ if epoch % 10 == 0 and epoch > best_model_state_epoch:
110
+ with torch.no_grad():
111
+ loss_per_step_val = []
112
+ for steps, x_start in enumerate(data_loader_val):
113
+ t, weights = self.schedule_sampler.sample(x_start.shape[0], self.device)
114
+ noise = torch.randn_like(x_start).to(self.device)
115
+ x_t = self.gaussian_diffusion.q_sample(x_start, t, noise=noise)
116
+ model_output = self.model(x_t, self.gaussian_diffusion._scale_timesteps(t))
117
+ diffusion_losses = (noise - model_output) ** 2
118
+ diffusion_loss = (diffusion_losses.mean(dim=list(range(1, len(diffusion_losses.shape)))) * weights).mean()
119
+ loss_per_step_val.append(diffusion_loss.item())
120
+ epoch_val_loss = np.mean(loss_per_step_val)
121
+
122
+ if self.best_loss > epoch_val_loss:
123
+ self.best_loss = epoch_val_loss
124
+ best_model_state = deepcopy(self.model.state_dict())
125
+ best_model_state_epoch = epoch
126
+ pbar.set_postfix({'Epoch Loss': epoch_val_loss})
127
+
128
+ if epoch - best_model_state_epoch > self.early_stopping_wait: # Early stopping
129
+ break
130
+ if fixed is None:
131
+ print(f"Early stoping at epoch {epoch}")
132
+ print(f"Best model at epoch {best_model_state_epoch} with loss {self.best_loss}")
133
+ self.model.load_state_dict(best_model_state)
134
+
135
+ def compute_hessian_get_leaves(self, X, steps_list, eval_batch_size, order, active_nodes):
136
+ leaves_per_step = list()
137
+ for step in steps_list:
138
+ model_fn_functorch = self.get_model_function_with_residue(step, active_nodes, order)
139
+ data_loader = torch.utils.data.DataLoader(X, eval_batch_size, drop_last=True, shuffle=False)
140
+ hessian_diag_var = self.compute_hessian_diagonal(data_loader, active_nodes, model_fn_functorch)
141
+ leaves = self.get_leaves(hessian_diag_var)
142
+ leaves_per_step.append(leaves)
143
+ # get intersection of leaves in leaves_per_step which is a list of lists
144
+ all_leaves = [item for sublist in leaves_per_step for item in sublist]
145
+ leaves_count = Counter(all_leaves)
146
+ sorted_leaves = sorted(leaves_count, key=leaves_count.get, reverse=True)
147
+ unique_leaves = sorted_leaves[:2] if len(sorted_leaves) > 2 else sorted_leaves
148
+ print(f'Unique leaves: {unique_leaves}')
149
+ # get numbers that appear more than once
150
+ # leaves_appearing_more_than_once = [item for item, count in Counter(all_leaves).items() if count > 1]
151
+ inner_order = [active_nodes[n] for n in unique_leaves]
152
+ return unique_leaves, inner_order
153
+
154
+ def topological_ordering(self, X, step = None, eval_batch_size = None):
155
+
156
+ if eval_batch_size is None:
157
+ eval_batch_size = self.batch_size
158
+ eval_batch_size = min(eval_batch_size, X.shape[0])
159
+
160
+ X = X[:self.batch_size]
161
+
162
+ self.model.eval()
163
+ order = []
164
+ active_nodes = list(range(self.n_nodes))
165
+
166
+ steps_list = [step] if step is not None else range(0, self.n_steps+1, self.n_steps//self.n_votes)
167
+ if self.sorting:
168
+ steps_list = [self.n_steps//2]
169
+ pbar = tqdm(range(self.n_nodes-1), desc = "Nodes ordered ")
170
+ leaf = None
171
+ for jac_step in pbar:
172
+ leaves = []
173
+ for i, steps in enumerate(steps_list):
174
+ data_loader = torch.utils.data.DataLoader(X, eval_batch_size, drop_last = True)
175
+ model_fn_functorch = self.get_model_function_with_residue(steps, active_nodes, order)
176
+ hessian_diag_var = self.compute_hessian_diagonal(data_loader, active_nodes, model_fn_functorch)
177
+ leaf_ = self.get_leaf(hessian_diag_var)
178
+ if self.sorting:
179
+ order = leaf_.tolist()
180
+ order.reverse()
181
+ return order
182
+ leaves.append(leaf_)
183
+
184
+ leaf = Counter(leaves).most_common(1)[0][0]
185
+ leaf_global = active_nodes[leaf]
186
+ order.append(leaf_global)
187
+ active_nodes.pop(leaf)
188
+
189
+
190
+ order.append(active_nodes[0])
191
+ order.reverse()
192
+
193
+ return order
194
+
195
+ def get_model_function_with_residue(self, step, active_nodes, order):
196
+ t_functorch = (torch.ones(1)*step).long().to(self.device) # test if other ts or random ts are better, self.n_steps
197
+ get_score_active = lambda x: self.model(x, self.gaussian_diffusion._scale_timesteps(t_functorch))[:,active_nodes]
198
+ get_score_previous_leaves = lambda x: self.model(x, self.gaussian_diffusion._scale_timesteps(t_functorch))[:,order]
199
+ def model_fn_functorch(X):
200
+ score_active = get_score_active(X).squeeze()
201
+ if self.residue and len(order) > 0:
202
+ score_previous_leaves = get_score_previous_leaves(X).squeeze()
203
+ hessian_ = jacfwd(get_score_previous_leaves)(X).squeeze()
204
+ if len(order) == 1:
205
+ hessian_, score_previous_leaves = hessian_.unsqueeze(0), score_previous_leaves.unsqueeze(0)
206
+ score_active += torch.einsum("i,ij -> j", score_previous_leaves/ hessian_[:, order].diag(),hessian_[:, active_nodes])
207
+ return score_active
208
+ return model_fn_functorch
209
+
210
+ def get_masked(self, x, active_nodes):
211
+ dropout_mask = torch.zeros_like(x).to(self.device)
212
+ dropout_mask[:, active_nodes] = 1
213
+ return (x * dropout_mask).float()
214
+
215
+ def compute_hessian_diagonal(self, data_loader, active_nodes, model_fn_functorch):
216
+ hessian = []
217
+ for x_batch in data_loader:
218
+ x_batch_dropped = self.get_masked(x_batch, active_nodes) if self.masking else x_batch
219
+ hessian_ = vmap(jacrev(model_fn_functorch),randomness='same')(x_batch_dropped.unsqueeze(1)).squeeze()
220
+ hessian.append(hessian_[...,active_nodes].detach().cpu().numpy())
221
+ hessian = np.concatenate(hessian, 0)
222
+ hessian_var = hessian.var(0)
223
+ hessian_var_diag = hessian_var.diagonal()
224
+ return hessian_var_diag
225
+
226
+ def get_leaf(self, hess_var):
227
+ var_sorted_nodes = np.argsort(hess_var)
228
+ if self.sorting:
229
+ return var_sorted_nodes
230
+ leaf_current = var_sorted_nodes[0]
231
+ return leaf_current
232
+
233
+ def get_leaves(self, hess_var):
234
+ # Assuming 'data' is your numpy array of non-negative floats
235
+ data = hess_var.reshape(-1, 1) # Reshape data for sklearn (if necessary)
236
+ # Range of components to try
237
+ n_components_range = range(2, max(data.shape[0]//2,3))
238
+
239
+ lowest_bic = np.inf
240
+ best_gmm = None
241
+
242
+ # Fit GMMs with different numbers of components and select the best one
243
+ for n_components in n_components_range:
244
+ gmm = GaussianMixture(n_components=n_components, random_state=0)
245
+ gmm.fit(data)
246
+ bic = gmm.bic(data)
247
+ if bic < lowest_bic:
248
+ lowest_bic = bic
249
+ best_gmm = gmm
250
+
251
+ # Extract the means of the components
252
+ component_means = best_gmm.means_.flatten()
253
+
254
+ # Identify the component with the lowest mean
255
+ min_mean_component = np.argmin(component_means)
256
+
257
+ # Predict component assignments for each data point
258
+ component_assignments = best_gmm.predict(data)
259
+
260
+ # Select data points assigned to the component with the lowest mean
261
+ selected_indices = np.where(component_assignments == min_mean_component)[0]
262
+ # select the 2 smallest data components with selected_indices
263
+ selected_indices = np.argsort(data[selected_indices].flatten())[:2]
264
+ return selected_indices
265
+
266
+ class DOTS(DiffBase):
267
+ def __init__(self, n_nodes, masking = True, residue= True,
268
+ epochs: int = int(3e3), batch_size : int = 1024, learning_rate : float = 0.001, nn_depth_mul=3, steps=1e2, esw=300):
269
+ super().__init__(n_nodes, masking, residue, epochs, batch_size, learning_rate, nn_depth_mul, steps, esw)
270
+
271
+ def fit(self, X, constraint=True, inst_const=True, nb_timesteps=-1, nb_variables=-1, nb_orderings=10):
272
+ X = self.normalize_data(X)
273
+ self.train_score(X)
274
+ steps_list = list(range(0, self.n_steps+1, self.n_steps//nb_orderings))
275
+ orders = list()
276
+ for step in steps_list:
277
+ order = self.topological_ordering(X, step=step)
278
+ orders.append(order)
279
+ adj_matrix = get_soft_transitive_closure_from_orderings(orders)
280
+ adj = self.pruning_adj(adj_matrix.astype(int), X.detach().cpu().numpy())
281
+ if constraint:
282
+ adj = apply_temporal_constraint(adj, nb_timesteps, nb_variables, inst_const)
283
+ return adj