deep-nonlinear-causality 1.0.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.
- deep_nonlinear_causality-1.0.0/LICENSE +21 -0
- deep_nonlinear_causality-1.0.0/PKG-INFO +72 -0
- deep_nonlinear_causality-1.0.0/README.md +36 -0
- deep_nonlinear_causality-1.0.0/deep_nonlinear_causality.egg-info/PKG-INFO +72 -0
- deep_nonlinear_causality-1.0.0/deep_nonlinear_causality.egg-info/SOURCES.txt +14 -0
- deep_nonlinear_causality-1.0.0/deep_nonlinear_causality.egg-info/dependency_links.txt +1 -0
- deep_nonlinear_causality-1.0.0/deep_nonlinear_causality.egg-info/requires.txt +10 -0
- deep_nonlinear_causality-1.0.0/deep_nonlinear_causality.egg-info/top_level.txt +1 -0
- deep_nonlinear_causality-1.0.0/deepcausality/__init__.py +25 -0
- deep_nonlinear_causality-1.0.0/deepcausality/causality.py +83 -0
- deep_nonlinear_causality-1.0.0/deepcausality/models.py +91 -0
- deep_nonlinear_causality-1.0.0/deepcausality/utils.py +79 -0
- deep_nonlinear_causality-1.0.0/pyproject.toml +7 -0
- deep_nonlinear_causality-1.0.0/setup.cfg +4 -0
- deep_nonlinear_causality-1.0.0/setup.py +33 -0
- deep_nonlinear_causality-1.0.0/tests/test_deepcausality.py +25 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dr. Abdullah Mohammad Ghazi Al khatib
|
|
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,72 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: deep-nonlinear-causality
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Multivariate Nonlinear Granger Causality Detection with Deep Learning and Machine Learning
|
|
5
|
+
Home-page: https://github.com/ABDULLAH-AL-KHATIB
|
|
6
|
+
Author: Dr. Abdullah Mohammad Ghazi Al khatib
|
|
7
|
+
Author-email: genius.275@hotmail.com
|
|
8
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: numpy>=1.20.0
|
|
17
|
+
Requires-Dist: scipy>=1.7.0
|
|
18
|
+
Requires-Dist: pandas>=1.3.0
|
|
19
|
+
Requires-Dist: scikit-learn>=1.0.0
|
|
20
|
+
Provides-Extra: all
|
|
21
|
+
Requires-Dist: tensorflow>=2.6.0; extra == "all"
|
|
22
|
+
Requires-Dist: xgboost>=1.5.0; extra == "all"
|
|
23
|
+
Requires-Dist: lightgbm>=3.3.0; extra == "all"
|
|
24
|
+
Requires-Dist: pytest>=7.0.0; extra == "all"
|
|
25
|
+
Dynamic: author
|
|
26
|
+
Dynamic: author-email
|
|
27
|
+
Dynamic: classifier
|
|
28
|
+
Dynamic: description
|
|
29
|
+
Dynamic: description-content-type
|
|
30
|
+
Dynamic: home-page
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
Dynamic: provides-extra
|
|
33
|
+
Dynamic: requires-dist
|
|
34
|
+
Dynamic: requires-python
|
|
35
|
+
Dynamic: summary
|
|
36
|
+
|
|
37
|
+
# Deep Nonlinear Causality (deepcausality)
|
|
38
|
+
|
|
39
|
+
**Author**: Dr. Abdullah Mohammad Ghazi Al khatib
|
|
40
|
+
**Affiliation**: Al Sham Private University
|
|
41
|
+
**Email**: genius.275@hotmail.com
|
|
42
|
+
**GitHub**: https://github.com/ABDULLAH-AL-KHATIB
|
|
43
|
+
**Release Date**: 17-08-2026
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Overview
|
|
48
|
+
A Python framework for discovering multivariate, non-linear Granger causality and conditional causality in complex dynamical systems using Deep Learning (LSTM, GRU, CNN, MLP) and Machine Learning (RF, XGBoost, LightGBM, Kernel Ridge).
|
|
49
|
+
|
|
50
|
+
## Installation
|
|
51
|
+
```bash
|
|
52
|
+
pip install deep-nonlinear-causality[all]
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Quick Start
|
|
56
|
+
```python
|
|
57
|
+
import numpy as np
|
|
58
|
+
from deepcausality import CausalityTest
|
|
59
|
+
|
|
60
|
+
n = 500
|
|
61
|
+
X = np.random.randn(n, 2)
|
|
62
|
+
Y = np.zeros(n)
|
|
63
|
+
for t in range(2, n):
|
|
64
|
+
Y[t] = 0.4 * Y[t-1] + 0.3 * (X[t-1, 0]**2) + np.random.normal(0, 0.05)
|
|
65
|
+
|
|
66
|
+
engine = CausalityTest(random_state=42)
|
|
67
|
+
res = engine.run_test(Y, X, lag=2, model_type='mlp', n_permutations=50)
|
|
68
|
+
print(f'Is Causal: {res["is_causal"]}, p-value: {res["p_value"]:.4f}')
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## License
|
|
72
|
+
MIT License. Copyright (c) 2026 Dr. Abdullah Mohammad Ghazi Al khatib.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Deep Nonlinear Causality (deepcausality)
|
|
2
|
+
|
|
3
|
+
**Author**: Dr. Abdullah Mohammad Ghazi Al khatib
|
|
4
|
+
**Affiliation**: Al Sham Private University
|
|
5
|
+
**Email**: genius.275@hotmail.com
|
|
6
|
+
**GitHub**: https://github.com/ABDULLAH-AL-KHATIB
|
|
7
|
+
**Release Date**: 17-08-2026
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Overview
|
|
12
|
+
A Python framework for discovering multivariate, non-linear Granger causality and conditional causality in complex dynamical systems using Deep Learning (LSTM, GRU, CNN, MLP) and Machine Learning (RF, XGBoost, LightGBM, Kernel Ridge).
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
```bash
|
|
16
|
+
pip install deep-nonlinear-causality[all]
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Quick Start
|
|
20
|
+
```python
|
|
21
|
+
import numpy as np
|
|
22
|
+
from deepcausality import CausalityTest
|
|
23
|
+
|
|
24
|
+
n = 500
|
|
25
|
+
X = np.random.randn(n, 2)
|
|
26
|
+
Y = np.zeros(n)
|
|
27
|
+
for t in range(2, n):
|
|
28
|
+
Y[t] = 0.4 * Y[t-1] + 0.3 * (X[t-1, 0]**2) + np.random.normal(0, 0.05)
|
|
29
|
+
|
|
30
|
+
engine = CausalityTest(random_state=42)
|
|
31
|
+
res = engine.run_test(Y, X, lag=2, model_type='mlp', n_permutations=50)
|
|
32
|
+
print(f'Is Causal: {res["is_causal"]}, p-value: {res["p_value"]:.4f}')
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## License
|
|
36
|
+
MIT License. Copyright (c) 2026 Dr. Abdullah Mohammad Ghazi Al khatib.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: deep-nonlinear-causality
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Multivariate Nonlinear Granger Causality Detection with Deep Learning and Machine Learning
|
|
5
|
+
Home-page: https://github.com/ABDULLAH-AL-KHATIB
|
|
6
|
+
Author: Dr. Abdullah Mohammad Ghazi Al khatib
|
|
7
|
+
Author-email: genius.275@hotmail.com
|
|
8
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
9
|
+
Classifier: Intended Audience :: Science/Research
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.8
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: numpy>=1.20.0
|
|
17
|
+
Requires-Dist: scipy>=1.7.0
|
|
18
|
+
Requires-Dist: pandas>=1.3.0
|
|
19
|
+
Requires-Dist: scikit-learn>=1.0.0
|
|
20
|
+
Provides-Extra: all
|
|
21
|
+
Requires-Dist: tensorflow>=2.6.0; extra == "all"
|
|
22
|
+
Requires-Dist: xgboost>=1.5.0; extra == "all"
|
|
23
|
+
Requires-Dist: lightgbm>=3.3.0; extra == "all"
|
|
24
|
+
Requires-Dist: pytest>=7.0.0; extra == "all"
|
|
25
|
+
Dynamic: author
|
|
26
|
+
Dynamic: author-email
|
|
27
|
+
Dynamic: classifier
|
|
28
|
+
Dynamic: description
|
|
29
|
+
Dynamic: description-content-type
|
|
30
|
+
Dynamic: home-page
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
Dynamic: provides-extra
|
|
33
|
+
Dynamic: requires-dist
|
|
34
|
+
Dynamic: requires-python
|
|
35
|
+
Dynamic: summary
|
|
36
|
+
|
|
37
|
+
# Deep Nonlinear Causality (deepcausality)
|
|
38
|
+
|
|
39
|
+
**Author**: Dr. Abdullah Mohammad Ghazi Al khatib
|
|
40
|
+
**Affiliation**: Al Sham Private University
|
|
41
|
+
**Email**: genius.275@hotmail.com
|
|
42
|
+
**GitHub**: https://github.com/ABDULLAH-AL-KHATIB
|
|
43
|
+
**Release Date**: 17-08-2026
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Overview
|
|
48
|
+
A Python framework for discovering multivariate, non-linear Granger causality and conditional causality in complex dynamical systems using Deep Learning (LSTM, GRU, CNN, MLP) and Machine Learning (RF, XGBoost, LightGBM, Kernel Ridge).
|
|
49
|
+
|
|
50
|
+
## Installation
|
|
51
|
+
```bash
|
|
52
|
+
pip install deep-nonlinear-causality[all]
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Quick Start
|
|
56
|
+
```python
|
|
57
|
+
import numpy as np
|
|
58
|
+
from deepcausality import CausalityTest
|
|
59
|
+
|
|
60
|
+
n = 500
|
|
61
|
+
X = np.random.randn(n, 2)
|
|
62
|
+
Y = np.zeros(n)
|
|
63
|
+
for t in range(2, n):
|
|
64
|
+
Y[t] = 0.4 * Y[t-1] + 0.3 * (X[t-1, 0]**2) + np.random.normal(0, 0.05)
|
|
65
|
+
|
|
66
|
+
engine = CausalityTest(random_state=42)
|
|
67
|
+
res = engine.run_test(Y, X, lag=2, model_type='mlp', n_permutations=50)
|
|
68
|
+
print(f'Is Causal: {res["is_causal"]}, p-value: {res["p_value"]:.4f}')
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## License
|
|
72
|
+
MIT License. Copyright (c) 2026 Dr. Abdullah Mohammad Ghazi Al khatib.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
setup.py
|
|
5
|
+
deep_nonlinear_causality.egg-info/PKG-INFO
|
|
6
|
+
deep_nonlinear_causality.egg-info/SOURCES.txt
|
|
7
|
+
deep_nonlinear_causality.egg-info/dependency_links.txt
|
|
8
|
+
deep_nonlinear_causality.egg-info/requires.txt
|
|
9
|
+
deep_nonlinear_causality.egg-info/top_level.txt
|
|
10
|
+
deepcausality/__init__.py
|
|
11
|
+
deepcausality/causality.py
|
|
12
|
+
deepcausality/models.py
|
|
13
|
+
deepcausality/utils.py
|
|
14
|
+
tests/test_deepcausality.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
deepcausality
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Deep Nonlinear Causality Framework
|
|
3
|
+
Author: Dr. Abdullah Mohammad Ghazi Al khatib
|
|
4
|
+
Affiliation: Al Sham Private University
|
|
5
|
+
Email: genius.275@hotmail.com
|
|
6
|
+
GitHub: https://github.com/ABDULLAH-AL-KHATIB
|
|
7
|
+
Date: 17-08-2026
|
|
8
|
+
"""
|
|
9
|
+
from .causality import CausalityTest, ConditionalCausalityTest
|
|
10
|
+
from .utils import prepare_data, prepare_sequential_data, block_permutation
|
|
11
|
+
|
|
12
|
+
__version__ = "1.0.0"
|
|
13
|
+
__author__ = "Dr. Abdullah Mohammad Ghazi Al khatib"
|
|
14
|
+
__email__ = "genius.275@hotmail.com"
|
|
15
|
+
__affiliation__ = "Al Sham Private University"
|
|
16
|
+
__github__ = "https://github.com/ABDULLAH-AL-KHATIB"
|
|
17
|
+
__date__ = "17-08-2026"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"CausalityTest",
|
|
21
|
+
"ConditionalCausalityTest",
|
|
22
|
+
"prepare_data",
|
|
23
|
+
"prepare_sequential_data",
|
|
24
|
+
"block_permutation",
|
|
25
|
+
]
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from sklearn.metrics import mean_squared_error
|
|
3
|
+
from .utils import prepare_data, prepare_sequential_data, block_permutation, to_2d_array
|
|
4
|
+
from .models import create_model, fit_model, predict_model, clean_backend
|
|
5
|
+
|
|
6
|
+
class CausalityTest:
|
|
7
|
+
"""Multivariate Nonlinear Granger Causality Engine by Dr. Abdullah Mohammad Ghazi Al khatib."""
|
|
8
|
+
def __init__(self, random_state=42):
|
|
9
|
+
self.random_state = random_state
|
|
10
|
+
self.rng = np.random.default_rng(random_state)
|
|
11
|
+
|
|
12
|
+
def run_test(self, y, x, z=None, lag=2, model_type="mlp", test_size=0.2, n_permutations=50, block_size=None, **kwargs):
|
|
13
|
+
clean_backend()
|
|
14
|
+
y_arr = to_2d_array(y, "y")
|
|
15
|
+
x_arr = to_2d_array(x, "x")
|
|
16
|
+
z_arr = to_2d_array(z, "z") if z is not None else None
|
|
17
|
+
is_seq = model_type.lower() in ["lstm", "gru", "cnn"]
|
|
18
|
+
|
|
19
|
+
if is_seq:
|
|
20
|
+
X_f, X_r, y_t = prepare_sequential_data(y_arr, x_arr, lag=lag, z=z_arr)
|
|
21
|
+
sh_f, sh_r = (X_f.shape[1], X_f.shape[2]), (X_r.shape[1], X_r.shape[2])
|
|
22
|
+
else:
|
|
23
|
+
X_f, X_r, y_t = prepare_data(y_arr, x_arr, lag=lag, z=z_arr)
|
|
24
|
+
sh_f, sh_r = X_f.shape[1], X_r.shape[1]
|
|
25
|
+
|
|
26
|
+
n_samples = len(y_t)
|
|
27
|
+
split = int(n_samples * (1.0 - test_size))
|
|
28
|
+
if split < 5 or (n_samples - split) < 5:
|
|
29
|
+
raise ValueError(f"Dataset too small ({n_samples}) for test split {test_size}")
|
|
30
|
+
|
|
31
|
+
X_f_tr, X_f_te = X_f[:split], X_f[split:]
|
|
32
|
+
X_r_tr, X_r_te = X_r[:split], X_r[split:]
|
|
33
|
+
y_tr, y_te = y_t[:split], y_t[split:]
|
|
34
|
+
|
|
35
|
+
# Cached Restricted Model
|
|
36
|
+
m_r = create_model(model_type, sh_r, random_state=self.random_state, **kwargs)
|
|
37
|
+
fit_model(m_r, X_r_tr, y_tr, model_type, **kwargs)
|
|
38
|
+
pred_r = predict_model(m_r, X_r_te, model_type)
|
|
39
|
+
mse_r = mean_squared_error(y_te, pred_r)
|
|
40
|
+
|
|
41
|
+
# Baseline Full Model
|
|
42
|
+
m_f = create_model(model_type, sh_f, random_state=self.random_state, **kwargs)
|
|
43
|
+
fit_model(m_f, X_f_tr, y_tr, model_type, **kwargs)
|
|
44
|
+
pred_f = predict_model(m_f, X_f_te, model_type)
|
|
45
|
+
mse_f = mean_squared_error(y_te, pred_f)
|
|
46
|
+
obs_stat = (mse_r - mse_f) / (mse_r + 1e-12)
|
|
47
|
+
|
|
48
|
+
# Permutation Distribution
|
|
49
|
+
p_stats = []
|
|
50
|
+
for i in range(n_permutations):
|
|
51
|
+
x_p = block_permutation(x_arr, block_size=block_size, rng=self.rng)
|
|
52
|
+
if is_seq:
|
|
53
|
+
X_fp, _, _ = prepare_sequential_data(y_arr, x_p, lag=lag, z=z_arr)
|
|
54
|
+
else:
|
|
55
|
+
X_fp, _, _ = prepare_data(y_arr, x_p, lag=lag, z=z_arr)
|
|
56
|
+
m_p = create_model(model_type, sh_f, random_state=self.random_state + i + 1, **kwargs)
|
|
57
|
+
fit_model(m_p, X_fp[:split], y_tr, model_type, **kwargs)
|
|
58
|
+
pred_p = predict_model(m_p, X_fp[split:], model_type)
|
|
59
|
+
stat_p = (mse_r - mean_squared_error(y_te, pred_p)) / (mse_r + 1e-12)
|
|
60
|
+
p_stats.append(stat_p)
|
|
61
|
+
|
|
62
|
+
p_stats = np.array(p_stats)
|
|
63
|
+
p_val = (np.sum(p_stats >= obs_stat) + 1.0) / (n_permutations + 1.0)
|
|
64
|
+
clean_backend()
|
|
65
|
+
|
|
66
|
+
return {
|
|
67
|
+
"p_value": float(p_val),
|
|
68
|
+
"is_causal": bool(p_val < 0.05),
|
|
69
|
+
"observed_statistic": float(obs_stat),
|
|
70
|
+
"mse_full": float(mse_f),
|
|
71
|
+
"mse_restricted": float(mse_r),
|
|
72
|
+
"model_type": model_type,
|
|
73
|
+
"lag": lag,
|
|
74
|
+
"n_permutations": n_permutations,
|
|
75
|
+
"author": "Dr. Abdullah Mohammad Ghazi Al khatib",
|
|
76
|
+
"affiliation": "Al Sham Private University",
|
|
77
|
+
"github": "https://github.com/ABDULLAH-AL-KHATIB"
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
class ConditionalCausalityTest(CausalityTest):
|
|
81
|
+
def run_test(self, y, x, z, lag=2, model_type="mlp", **kwargs):
|
|
82
|
+
if z is None: raise ValueError("Conditioning variable Z is required")
|
|
83
|
+
return super().run_test(y=y, x=x, z=z, lag=lag, model_type=model_type, **kwargs)
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import gc
|
|
2
|
+
import numpy as np
|
|
3
|
+
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
|
4
|
+
from sklearn.kernel_ridge import KernelRidge
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
from xgboost import XGBRegressor
|
|
8
|
+
XGB_AVAILABLE = True
|
|
9
|
+
except ImportError:
|
|
10
|
+
XGB_AVAILABLE = False
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
from lightgbm import LGBMRegressor
|
|
14
|
+
LGBM_AVAILABLE = True
|
|
15
|
+
except ImportError:
|
|
16
|
+
LGBM_AVAILABLE = False
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
import tensorflow as tf
|
|
20
|
+
from tensorflow.keras.models import Sequential
|
|
21
|
+
from tensorflow.keras.layers import Dense, LSTM, GRU, Conv1D, GlobalMaxPooling1D, Dropout
|
|
22
|
+
from tensorflow.keras.optimizers import Adam
|
|
23
|
+
TF_AVAILABLE = True
|
|
24
|
+
except ImportError:
|
|
25
|
+
TF_AVAILABLE = False
|
|
26
|
+
|
|
27
|
+
def create_model(model_type, input_shape, **kwargs):
|
|
28
|
+
model_type = model_type.lower()
|
|
29
|
+
seed = kwargs.get("random_state", 42)
|
|
30
|
+
if model_type == "random_forest":
|
|
31
|
+
return RandomForestRegressor(n_estimators=kwargs.get("n_estimators", 100), max_depth=kwargs.get("max_depth", None), n_jobs=-1, random_state=seed)
|
|
32
|
+
elif model_type == "gradient_boosting":
|
|
33
|
+
return GradientBoostingRegressor(n_estimators=kwargs.get("n_estimators", 100), learning_rate=kwargs.get("learning_rate", 0.05), max_depth=kwargs.get("max_depth", 3), random_state=seed)
|
|
34
|
+
elif model_type == "kernel_ridge":
|
|
35
|
+
return KernelRidge(kernel=kwargs.get("kernel", "rbf"), alpha=kwargs.get("alpha", 1.0))
|
|
36
|
+
elif model_type == "xgboost":
|
|
37
|
+
if not XGB_AVAILABLE: raise ImportError("Run: pip install xgboost")
|
|
38
|
+
return XGBRegressor(n_estimators=kwargs.get("n_estimators", 100), learning_rate=kwargs.get("learning_rate", 0.05), verbosity=0, random_state=seed, n_jobs=-1)
|
|
39
|
+
elif model_type == "lightgbm":
|
|
40
|
+
if not LGBM_AVAILABLE: raise ImportError("Run: pip install lightgbm")
|
|
41
|
+
return LGBMRegressor(n_estimators=kwargs.get("n_estimators", 100), learning_rate=kwargs.get("learning_rate", 0.05), random_state=seed, n_jobs=-1, verbose=-1)
|
|
42
|
+
elif model_type in ["mlp", "lstm", "gru", "cnn"]:
|
|
43
|
+
if not TF_AVAILABLE: raise ImportError("Run: pip install tensorflow")
|
|
44
|
+
lr = kwargs.get("learning_rate", 0.002)
|
|
45
|
+
h = kwargs.get("hidden_units", 64)
|
|
46
|
+
dr = kwargs.get("dropout_rate", 0.1)
|
|
47
|
+
m = Sequential()
|
|
48
|
+
if model_type == "mlp":
|
|
49
|
+
dim = input_shape if isinstance(input_shape, int) else input_shape[0]
|
|
50
|
+
m.add(Dense(h, activation="relu", input_shape=(dim,)))
|
|
51
|
+
if dr > 0: m.add(Dropout(dr))
|
|
52
|
+
m.add(Dense(h // 2, activation="relu"))
|
|
53
|
+
m.add(Dense(1))
|
|
54
|
+
elif model_type == "lstm":
|
|
55
|
+
m.add(LSTM(h, activation="tanh", input_shape=input_shape))
|
|
56
|
+
if dr > 0: m.add(Dropout(dr))
|
|
57
|
+
m.add(Dense(1))
|
|
58
|
+
elif model_type == "gru":
|
|
59
|
+
m.add(GRU(h, activation="tanh", input_shape=input_shape))
|
|
60
|
+
if dr > 0: m.add(Dropout(dr))
|
|
61
|
+
m.add(Dense(1))
|
|
62
|
+
elif model_type == "cnn":
|
|
63
|
+
m.add(Conv1D(filters=h, kernel_size=kwargs.get("kernel_size", 2), activation="relu", input_shape=input_shape, padding="same"))
|
|
64
|
+
m.add(GlobalMaxPooling1D())
|
|
65
|
+
m.add(Dense(h // 2, activation="relu"))
|
|
66
|
+
m.add(Dense(1))
|
|
67
|
+
m.compile(optimizer=Adam(learning_rate=lr), loss="mse")
|
|
68
|
+
return m
|
|
69
|
+
else:
|
|
70
|
+
raise ValueError(f"Unknown model type: {model_type}")
|
|
71
|
+
|
|
72
|
+
def fit_model(model, X_train, y_train, model_type, **kwargs):
|
|
73
|
+
model_type = model_type.lower()
|
|
74
|
+
if model_type in ["random_forest", "gradient_boosting", "kernel_ridge", "xgboost", "lightgbm"]:
|
|
75
|
+
model.fit(X_train, y_train)
|
|
76
|
+
else:
|
|
77
|
+
epochs = kwargs.get("epochs", 30)
|
|
78
|
+
batch_size = kwargs.get("batch_size", 32)
|
|
79
|
+
model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=0)
|
|
80
|
+
|
|
81
|
+
def predict_model(model, X_val, model_type):
|
|
82
|
+
model_type = model_type.lower()
|
|
83
|
+
if model_type in ["random_forest", "gradient_boosting", "kernel_ridge", "xgboost", "lightgbm"]:
|
|
84
|
+
return model.predict(X_val).flatten()
|
|
85
|
+
else:
|
|
86
|
+
return model.predict(X_val, verbose=0).flatten()
|
|
87
|
+
|
|
88
|
+
def clean_backend():
|
|
89
|
+
if TF_AVAILABLE:
|
|
90
|
+
tf.keras.backend.clear_session()
|
|
91
|
+
gc.collect()
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
|
|
4
|
+
def to_2d_array(arr, name="variable"):
|
|
5
|
+
if arr is None:
|
|
6
|
+
return None
|
|
7
|
+
if isinstance(arr, (pd.Series, pd.DataFrame)):
|
|
8
|
+
arr = arr.to_numpy()
|
|
9
|
+
arr = np.asarray(arr, dtype=np.float32)
|
|
10
|
+
if arr.ndim == 1:
|
|
11
|
+
arr = arr.reshape(-1, 1)
|
|
12
|
+
elif arr.ndim > 2:
|
|
13
|
+
raise ValueError(f"{name} must be 1D or 2D. Shape received: {arr.shape}")
|
|
14
|
+
return arr
|
|
15
|
+
|
|
16
|
+
def block_permutation(arr, block_size=None, rng=None):
|
|
17
|
+
if rng is None:
|
|
18
|
+
rng = np.random.default_rng()
|
|
19
|
+
n = arr.shape[0]
|
|
20
|
+
if block_size is None or block_size <= 1:
|
|
21
|
+
return rng.permutation(arr)
|
|
22
|
+
n_blocks = int(np.ceil(n / block_size))
|
|
23
|
+
start_indices = rng.integers(0, n, size=n_blocks)
|
|
24
|
+
resampled = []
|
|
25
|
+
for s in start_indices:
|
|
26
|
+
resampled.extend([(s + i) % n for i in range(block_size)])
|
|
27
|
+
return arr[resampled[:n]]
|
|
28
|
+
|
|
29
|
+
def prepare_data(y, x, lag=1, z=None):
|
|
30
|
+
y_2d = to_2d_array(y, "y")
|
|
31
|
+
x_2d = to_2d_array(x, "x")
|
|
32
|
+
z_2d = to_2d_array(z, "z") if z is not None else None
|
|
33
|
+
n = len(y_2d)
|
|
34
|
+
if len(x_2d) != n:
|
|
35
|
+
raise ValueError("X and Y length mismatch")
|
|
36
|
+
if z_2d is not None and len(z_2d) != n:
|
|
37
|
+
raise ValueError("Z and Y length mismatch")
|
|
38
|
+
if n <= lag:
|
|
39
|
+
raise ValueError(f"Sample size {n} must be greater than lag {lag}")
|
|
40
|
+
|
|
41
|
+
X_full, X_restr, y_target = [], [], []
|
|
42
|
+
for t in range(lag, n):
|
|
43
|
+
y_past = y_2d[t - lag:t].flatten()
|
|
44
|
+
x_past = x_2d[t - lag:t].flatten()
|
|
45
|
+
if z_2d is not None:
|
|
46
|
+
z_past = z_2d[t - lag:t].flatten()
|
|
47
|
+
X_full.append(np.concatenate([y_past, x_past, z_past]))
|
|
48
|
+
X_restr.append(np.concatenate([y_past, z_past]))
|
|
49
|
+
else:
|
|
50
|
+
X_full.append(np.concatenate([y_past, x_past]))
|
|
51
|
+
X_restr.append(y_past)
|
|
52
|
+
y_target.append(y_2d[t, 0])
|
|
53
|
+
|
|
54
|
+
return np.array(X_full, dtype=np.float32), np.array(X_restr, dtype=np.float32), np.array(y_target, dtype=np.float32)
|
|
55
|
+
|
|
56
|
+
def prepare_sequential_data(y, x, lag=1, z=None):
|
|
57
|
+
y_2d = to_2d_array(y, "y")
|
|
58
|
+
x_2d = to_2d_array(x, "x")
|
|
59
|
+
z_2d = to_2d_array(z, "z") if z is not None else None
|
|
60
|
+
n = len(y_2d)
|
|
61
|
+
if len(x_2d) != n or (z_2d is not None and len(z_2d) != n):
|
|
62
|
+
raise ValueError("Time series dimension mismatch")
|
|
63
|
+
if n <= lag:
|
|
64
|
+
raise ValueError(f"Sample size {n} must be greater than lag {lag}")
|
|
65
|
+
|
|
66
|
+
X_full, X_restr, y_target = [], [], []
|
|
67
|
+
for t in range(lag, n):
|
|
68
|
+
y_p = y_2d[t - lag:t]
|
|
69
|
+
x_p = x_2d[t - lag:t]
|
|
70
|
+
if z_2d is not None:
|
|
71
|
+
z_p = z_2d[t - lag:t]
|
|
72
|
+
X_full.append(np.hstack([y_p, x_p, z_p]))
|
|
73
|
+
X_restr.append(np.hstack([y_p, z_p]))
|
|
74
|
+
else:
|
|
75
|
+
X_full.append(np.hstack([y_p, x_p]))
|
|
76
|
+
X_restr.append(y_p)
|
|
77
|
+
y_target.append(y_2d[t, 0])
|
|
78
|
+
|
|
79
|
+
return np.array(X_full, dtype=np.float32), np.array(X_restr, dtype=np.float32), np.array(y_target, dtype=np.float32)
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
from setuptools import setup, find_packages
|
|
2
|
+
|
|
3
|
+
with open("README.md", "r", encoding="utf-8") as fh:
|
|
4
|
+
long_description = fh.read()
|
|
5
|
+
|
|
6
|
+
setup(
|
|
7
|
+
name="deep-nonlinear-causality",
|
|
8
|
+
version="1.0.0",
|
|
9
|
+
author="Dr. Abdullah Mohammad Ghazi Al khatib",
|
|
10
|
+
author_email="genius.275@hotmail.com",
|
|
11
|
+
description="Multivariate Nonlinear Granger Causality Detection with Deep Learning and Machine Learning",
|
|
12
|
+
long_description=long_description,
|
|
13
|
+
long_description_content_type="text/markdown",
|
|
14
|
+
url="https://github.com/ABDULLAH-AL-KHATIB",
|
|
15
|
+
packages=find_packages(),
|
|
16
|
+
classifiers=[
|
|
17
|
+
"Development Status :: 5 - Production/Stable",
|
|
18
|
+
"Intended Audience :: Science/Research",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
],
|
|
23
|
+
python_requires=">=3.8",
|
|
24
|
+
install_requires=[
|
|
25
|
+
"numpy>=1.20.0",
|
|
26
|
+
"scipy>=1.7.0",
|
|
27
|
+
"pandas>=1.3.0",
|
|
28
|
+
"scikit-learn>=1.0.0",
|
|
29
|
+
],
|
|
30
|
+
extras_require={
|
|
31
|
+
"all": ["tensorflow>=2.6.0", "xgboost>=1.5.0", "lightgbm>=3.3.0", "pytest>=7.0.0"]
|
|
32
|
+
}
|
|
33
|
+
)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
import numpy as np
|
|
3
|
+
from deepcausality import CausalityTest
|
|
4
|
+
from deepcausality.utils import prepare_data
|
|
5
|
+
|
|
6
|
+
def test_dimensions():
|
|
7
|
+
y = np.random.randn(100)
|
|
8
|
+
x = np.random.randn(100, 2)
|
|
9
|
+
z = np.random.randn(100, 1)
|
|
10
|
+
X_f, X_r, y_t = prepare_data(y, x, lag=2, z=z)
|
|
11
|
+
assert X_f.shape == (98, 8)
|
|
12
|
+
assert X_r.shape == (98, 4)
|
|
13
|
+
assert y_t.shape == (98,)
|
|
14
|
+
|
|
15
|
+
def test_pipeline():
|
|
16
|
+
np.random.seed(42)
|
|
17
|
+
n = 150
|
|
18
|
+
x = np.random.randn(n)
|
|
19
|
+
y = np.zeros(n)
|
|
20
|
+
for t in range(2, n):
|
|
21
|
+
y[t] = 0.4 * y[t-1] + 0.3 * (x[t-1]**2) + np.random.normal(0, 0.05)
|
|
22
|
+
engine = CausalityTest(random_state=42)
|
|
23
|
+
res = engine.run_test(y, x, lag=2, model_type="random_forest", n_permutations=3)
|
|
24
|
+
assert "p_value" in res
|
|
25
|
+
assert 0.0 <= res["p_value"] <= 1.0
|