├── docs ├── .nojekyll ├── html │ ├── .nojekyll │ ├── _sources │ │ ├── generators.rst.txt │ │ ├── settings.rst.txt │ │ ├── metrics.rst.txt │ │ ├── data.rst.txt │ │ ├── models.rst.txt │ │ ├── utils.rst.txt │ │ ├── independence.rst.txt │ │ ├── causality.rst.txt │ │ └── tutorial.rst.txt │ ├── objects.inv │ ├── _static │ │ ├── up.png │ │ ├── down.png │ │ ├── file.png │ │ ├── plus.png │ │ ├── banner.png │ │ ├── comment.png │ │ ├── favicon.png │ │ ├── minus.png │ │ ├── ajax-loader.gif │ │ ├── down-pressed.png │ │ ├── up-pressed.png │ │ ├── comment-bright.png │ │ ├── comment-close.png │ │ ├── fonts │ │ │ ├── FontAwesome.otf │ │ │ ├── Inconsolata.ttf │ │ │ ├── Lato-Bold.ttf │ │ │ ├── lato-bold.woff │ │ │ ├── lato-bold.woff2 │ │ │ ├── Lato-Regular.ttf │ │ │ ├── lato-normal.woff │ │ │ ├── lato-normal.woff2 │ │ │ ├── Inconsolata-Bold.ttf │ │ │ ├── Lato │ │ │ │ ├── lato-bold.eot │ │ │ │ ├── lato-bold.ttf │ │ │ │ ├── lato-bold.woff │ │ │ │ ├── lato-bold.woff2 │ │ │ │ ├── lato-italic.eot │ │ │ │ ├── lato-italic.ttf │ │ │ │ ├── lato-italic.woff │ │ │ │ ├── lato-italic.woff2 │ │ │ │ ├── lato-regular.eot │ │ │ │ ├── lato-regular.ttf │ │ │ │ ├── lato-regular.woff │ │ │ │ ├── lato-bolditalic.eot │ │ │ │ ├── lato-bolditalic.ttf │ │ │ │ ├── lato-bolditalic.woff │ │ │ │ ├── lato-regular.woff2 │ │ │ │ └── lato-bolditalic.woff2 │ │ │ ├── RobotoSlab-Bold.ttf │ │ │ ├── Roboto-Slab-Bold.woff │ │ │ ├── Roboto-Slab-Bold.woff2 │ │ │ ├── Roboto-Slab-Light.woff │ │ │ ├── Roboto-Slab-Thin.woff │ │ │ ├── Roboto-Slab-Thin.woff2 │ │ │ ├── RobotoSlab-Regular.ttf │ │ │ ├── lato-bold-italic.woff │ │ │ ├── lato-bold-italic.woff2 │ │ │ ├── Inconsolata-Regular.ttf │ │ │ ├── Roboto-Slab-Light.woff2 │ │ │ ├── Roboto-Slab-Regular.woff │ │ │ ├── Roboto-Slab-Regular.woff2 │ │ │ ├── fontawesome-webfont.eot │ │ │ ├── fontawesome-webfont.ttf │ │ │ ├── fontawesome-webfont.woff │ │ │ ├── fontawesome-webfont.woff2 │ │ │ ├── lato-normal-italic.woff │ │ │ ├── lato-normal-italic.woff2 │ │ │ └── RobotoSlab │ │ │ │ ├── roboto-slab-v7-bold.eot │ │ │ │ ├── roboto-slab-v7-bold.ttf │ │ │ │ ├── roboto-slab-v7-bold.woff │ │ │ │ ├── roboto-slab-v7-bold.woff2 │ │ │ │ ├── roboto-slab-v7-regular.eot │ │ │ │ ├── roboto-slab-v7-regular.ttf │ │ │ │ ├── roboto-slab-v7-regular.woff │ │ │ │ └── roboto-slab-v7-regular.woff2 │ │ ├── css │ │ │ ├── fonts │ │ │ │ ├── lato-bold.woff │ │ │ │ ├── lato-bold.woff2 │ │ │ │ ├── lato-normal.woff │ │ │ │ ├── lato-normal.woff2 │ │ │ │ ├── Roboto-Slab-Bold.woff │ │ │ │ ├── lato-bold-italic.woff │ │ │ │ ├── Roboto-Slab-Bold.woff2 │ │ │ │ ├── fontawesome-webfont.eot │ │ │ │ ├── fontawesome-webfont.ttf │ │ │ │ ├── lato-bold-italic.woff2 │ │ │ │ ├── lato-normal-italic.woff │ │ │ │ ├── Roboto-Slab-Regular.woff │ │ │ │ ├── Roboto-Slab-Regular.woff2 │ │ │ │ ├── fontawesome-webfont.woff │ │ │ │ ├── fontawesome-webfont.woff2 │ │ │ │ └── lato-normal-italic.woff2 │ │ │ └── badge_only.css │ │ ├── documentation_options.js │ │ ├── custom.css │ │ ├── js │ │ │ ├── badge_only.js │ │ │ ├── html5shiv.min.js │ │ │ ├── html5shiv-printshiv.min.js │ │ │ └── theme.js │ │ └── pygments.css │ ├── _images │ │ └── banner.png │ └── .doctrees │ │ ├── data.doctree │ │ ├── index.doctree │ │ ├── models.doctree │ │ ├── utils.doctree │ │ ├── metrics.doctree │ │ ├── settings.doctree │ │ ├── tutorial.doctree │ │ ├── causality.doctree │ │ ├── developer.doctree │ │ ├── environment.pickle │ │ ├── generators.doctree │ │ ├── tutorial_1.doctree │ │ ├── tutorial_2.doctree │ │ └── independence.doctree ├── index.html ├── banner.png ├── favicon.png ├── .doctrees │ ├── index.doctree │ └── installation-link.doctree ├── settings.rst ├── metrics.rst ├── data.rst ├── _static │ └── custom.css ├── Makefile ├── .old.index ├── make.bat ├── models.rst ├── utils.rst ├── independence.rst ├── causality.rst └── tutorial.rst ├── r_requirements.txt ├── rel_travis.enc ├── pytest.ini ├── tests ├── datasets │ ├── Example_target_adj.csv │ ├── Example_pairwise_targets.csv │ ├── Example_graph_confounders_target.csv │ ├── Example_graph_confounders_skeleton.csv │ ├── Lucas_graph.csv │ ├── Example_graph_target.csv │ ├── Example_graph_skeleton.csv │ └── graph_poly_target.csv └── scripts │ ├── test_datasetloader.py │ ├── test_metrics.py │ ├── test_independence_stats.py │ ├── test_independence_graph.py │ ├── test_io.py │ ├── graph_generators.py │ ├── test_causality_graph.py │ ├── test_generators.py │ ├── test_pipeline_CGNN.py │ ├── test_Jarfo.py │ ├── test_causality_pairwise.py │ └── test_varLINGAM.py ├── docker-requirements.txt ├── requirements.txt ├── .codecov.yml ├── CONTRIBUTING.md ├── install-deps ├── Dockerfile-env-1.1 ├── Dockerfile-env └── install-dependencies.sh ├── cdt ├── data │ ├── resources │ │ ├── cyto_full_target.csv │ │ ├── Tuebingen_targets.csv │ │ ├── goldstandard_insilico100_multifactorial_1.csv │ │ ├── goldstandard_insilico100_multifactorial_5.csv │ │ ├── goldstandard_insilico100_multifactorial_3.csv │ │ ├── goldstandard_insilico100_multifactorial_4.csv │ │ └── goldstandard_insilico100_multifactorial_2.csv │ └── __init__.py ├── causality │ ├── pairwise │ │ ├── Jarfo_model │ │ │ ├── util.py │ │ │ ├── __init__.py │ │ │ ├── train.py │ │ │ ├── README.md │ │ │ ├── SETTINGS.json │ │ │ └── hsic.py │ │ ├── __init__.py │ │ ├── Bivariate_fit.py │ │ └── RECI.py │ ├── __init__.py │ └── graph │ │ ├── R_templates │ │ ├── lingam.R │ │ ├── CCDr.R │ │ ├── cam.R │ │ ├── bnlearn.R │ │ ├── ges.R │ │ ├── gies.R │ │ └── pc.R │ │ ├── __init__.py │ │ └── model.py ├── timeseries │ ├── pairwise │ │ └── __init__.py │ ├── graph │ │ ├── __init__.py │ │ └── VARLiNGAM.py │ └── __init__.py ├── independence │ ├── __init__.py │ ├── stats │ │ ├── __init__.py │ │ └── model.py │ └── graph │ │ ├── __init__.py │ │ └── Lasso.py ├── utils │ ├── R_templates │ │ ├── test_import.R │ │ ├── cpdag.R │ │ ├── sid.R │ │ └── sid_cpdag.R │ └── __init__.py └── __init__.py ├── Dockerfile ├── nv-Dockerfile ├── CHANGELOG.md ├── .circleci └── bumpversion.sh ├── .github └── ISSUE_TEMPLATE │ └── bug_report.md ├── .gitignore ├── LICENSE.md ├── setup.py └── installation_instructions.md /docs/.nojekyll: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/html/.nojekyll: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /docs/html/_sources/generators.rst.txt: -------------------------------------------------------------------------------- 1 | cdt.generators 2 | ============== 3 | 4 | ToDo 5 | -------------------------------------------------------------------------------- /r_requirements.txt: -------------------------------------------------------------------------------- 1 | pcalg 2 | kpcalg 3 | bnlearn 4 | sparsebn 5 | SID 6 | CAM 7 | D2C 8 | RCIT 9 | -------------------------------------------------------------------------------- /rel_travis.enc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/rel_travis.enc -------------------------------------------------------------------------------- /docs/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/banner.png -------------------------------------------------------------------------------- /docs/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/favicon.png -------------------------------------------------------------------------------- /docs/html/objects.inv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/objects.inv -------------------------------------------------------------------------------- /docs/html/_static/up.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/up.png -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | filterwarnings = 3 | ignore::DeprecationWarning 4 | ignore::PendingDeprecationWarning 5 | -------------------------------------------------------------------------------- /docs/html/_static/down.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/down.png -------------------------------------------------------------------------------- /docs/html/_static/file.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/file.png -------------------------------------------------------------------------------- /docs/html/_static/plus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/plus.png -------------------------------------------------------------------------------- /tests/datasets/Example_target_adj.csv: -------------------------------------------------------------------------------- 1 | V0,V1,V2,V3,V4 2 | 1,0,0,0,0 3 | 0,0,0,1,0 4 | 1,1,1,1,1 5 | 0,1,0,1,0 6 | 0,0,0,0,1 7 | -------------------------------------------------------------------------------- /docs/.doctrees/index.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/.doctrees/index.doctree -------------------------------------------------------------------------------- /docs/html/_images/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_images/banner.png -------------------------------------------------------------------------------- /docs/html/_static/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/banner.png -------------------------------------------------------------------------------- /docs/html/_static/comment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/comment.png -------------------------------------------------------------------------------- /docs/html/_static/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/favicon.png -------------------------------------------------------------------------------- /docs/html/_static/minus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/minus.png -------------------------------------------------------------------------------- /tests/datasets/Example_pairwise_targets.csv: -------------------------------------------------------------------------------- 1 | SampleID,Target 2 | pair1,1.0 3 | pair2,1.0 4 | pair3,-1.0 5 | pair4,-1.0 6 | pair5,1.0 7 | -------------------------------------------------------------------------------- /docs/html/.doctrees/data.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/data.doctree -------------------------------------------------------------------------------- /docs/html/.doctrees/index.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/index.doctree -------------------------------------------------------------------------------- /docs/html/.doctrees/models.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/models.doctree -------------------------------------------------------------------------------- /docs/html/.doctrees/utils.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/utils.doctree -------------------------------------------------------------------------------- /docs/html/_static/ajax-loader.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/ajax-loader.gif -------------------------------------------------------------------------------- /docs/html/_static/down-pressed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/down-pressed.png -------------------------------------------------------------------------------- /docs/html/_static/up-pressed.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/up-pressed.png -------------------------------------------------------------------------------- /docs/html/.doctrees/metrics.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/metrics.doctree -------------------------------------------------------------------------------- /docs/html/.doctrees/settings.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/settings.doctree -------------------------------------------------------------------------------- /docs/html/.doctrees/tutorial.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/tutorial.doctree -------------------------------------------------------------------------------- /docs/html/_static/comment-bright.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/comment-bright.png -------------------------------------------------------------------------------- /docs/html/_static/comment-close.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/comment-close.png -------------------------------------------------------------------------------- /docs/html/.doctrees/causality.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/causality.doctree -------------------------------------------------------------------------------- /docs/html/.doctrees/developer.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/developer.doctree -------------------------------------------------------------------------------- /docs/html/.doctrees/environment.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/environment.pickle -------------------------------------------------------------------------------- /docs/html/.doctrees/generators.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/generators.doctree -------------------------------------------------------------------------------- /docs/html/.doctrees/tutorial_1.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/tutorial_1.doctree -------------------------------------------------------------------------------- /docs/html/.doctrees/tutorial_2.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/tutorial_2.doctree -------------------------------------------------------------------------------- /docs/html/_static/fonts/FontAwesome.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/FontAwesome.otf -------------------------------------------------------------------------------- /docs/html/_static/fonts/Inconsolata.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Inconsolata.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato-Bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato-Bold.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/lato-bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/lato-bold.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/lato-bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/lato-bold.woff2 -------------------------------------------------------------------------------- /docker-requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | scipy 3 | scikit-learn 4 | joblib 5 | pandas 6 | networkx 7 | tqdm 8 | GPUtil 9 | statsmodels 10 | requests 11 | -------------------------------------------------------------------------------- /docs/.doctrees/installation-link.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/.doctrees/installation-link.doctree -------------------------------------------------------------------------------- /docs/html/.doctrees/independence.doctree: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/.doctrees/independence.doctree -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato-Regular.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/lato-normal.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/lato-normal.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/lato-normal.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/lato-normal.woff2 -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/lato-bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/lato-bold.woff -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/lato-bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/lato-bold.woff2 -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/lato-normal.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/lato-normal.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/Inconsolata-Bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Inconsolata-Bold.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-bold.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-bold.eot -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-bold.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-bold.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-bold.woff2 -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-italic.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-italic.eot -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-italic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-italic.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/RobotoSlab-Bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/RobotoSlab-Bold.ttf -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | scipy 3 | scikit-learn 4 | joblib 5 | pandas 6 | networkx 7 | tqdm 8 | GPUtil 9 | statsmodels 10 | requests 11 | torch 12 | -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/lato-normal.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/lato-normal.woff2 -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-italic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-italic.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-italic.woff2 -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-regular.eot -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-regular.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-regular.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/Roboto-Slab-Bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Roboto-Slab-Bold.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/Roboto-Slab-Bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Roboto-Slab-Bold.woff2 -------------------------------------------------------------------------------- /docs/html/_static/fonts/Roboto-Slab-Light.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Roboto-Slab-Light.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/Roboto-Slab-Thin.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Roboto-Slab-Thin.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/Roboto-Slab-Thin.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Roboto-Slab-Thin.woff2 -------------------------------------------------------------------------------- /docs/html/_static/fonts/RobotoSlab-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/RobotoSlab-Regular.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/lato-bold-italic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/lato-bold-italic.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/lato-bold-italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/lato-bold-italic.woff2 -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/Roboto-Slab-Bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/Roboto-Slab-Bold.woff -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/lato-bold-italic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/lato-bold-italic.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/Inconsolata-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Inconsolata-Regular.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-bolditalic.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-bolditalic.eot -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-bolditalic.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-bolditalic.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-bolditalic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-bolditalic.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-regular.woff2 -------------------------------------------------------------------------------- /docs/html/_static/fonts/Roboto-Slab-Light.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Roboto-Slab-Light.woff2 -------------------------------------------------------------------------------- /docs/html/_static/fonts/Roboto-Slab-Regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Roboto-Slab-Regular.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/Roboto-Slab-Regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Roboto-Slab-Regular.woff2 -------------------------------------------------------------------------------- /docs/html/_static/fonts/fontawesome-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/fontawesome-webfont.eot -------------------------------------------------------------------------------- /docs/html/_static/fonts/fontawesome-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/fontawesome-webfont.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/fontawesome-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/fontawesome-webfont.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/fontawesome-webfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/fontawesome-webfont.woff2 -------------------------------------------------------------------------------- /docs/html/_static/fonts/lato-normal-italic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/lato-normal-italic.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/lato-normal-italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/lato-normal-italic.woff2 -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/Roboto-Slab-Bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/Roboto-Slab-Bold.woff2 -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/fontawesome-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/fontawesome-webfont.eot -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/fontawesome-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/fontawesome-webfont.ttf -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/lato-bold-italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/lato-bold-italic.woff2 -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/lato-normal-italic.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/lato-normal-italic.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/Lato/lato-bolditalic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/Lato/lato-bolditalic.woff2 -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/Roboto-Slab-Regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/Roboto-Slab-Regular.woff -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/Roboto-Slab-Regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/Roboto-Slab-Regular.woff2 -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/fontawesome-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/fontawesome-webfont.woff -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/fontawesome-webfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/fontawesome-webfont.woff2 -------------------------------------------------------------------------------- /docs/html/_static/css/fonts/lato-normal-italic.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/css/fonts/lato-normal-italic.woff2 -------------------------------------------------------------------------------- /docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.eot -------------------------------------------------------------------------------- /docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-bold.woff2 -------------------------------------------------------------------------------- /docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.eot -------------------------------------------------------------------------------- /docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.ttf -------------------------------------------------------------------------------- /docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff -------------------------------------------------------------------------------- /docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FenTechSolutions/CausalDiscoveryToolbox/HEAD/docs/html/_static/fonts/RobotoSlab/roboto-slab-v7-regular.woff2 -------------------------------------------------------------------------------- /docs/settings.rst: -------------------------------------------------------------------------------- 1 | Toolbox Settings 2 | ================ 3 | 4 | .. automodule:: cdt.utils.Settings 5 | 6 | .. autoclass:: ConfigSettings 7 | :members: 8 | 9 | .. autofunction:: autoset_settings 10 | -------------------------------------------------------------------------------- /docs/metrics.rst: -------------------------------------------------------------------------------- 1 | cdt.metrics 2 | =================================== 3 | .. automodule:: cdt.metrics 4 | 5 | .. autofunction:: precision_recall 6 | 7 | .. autofunction:: SHD 8 | 9 | .. autofunction:: SID 10 | -------------------------------------------------------------------------------- /docs/html/_sources/settings.rst.txt: -------------------------------------------------------------------------------- 1 | Toolbox Settings 2 | ================ 3 | 4 | .. automodule:: cdt.utils.Settings 5 | 6 | .. autoclass:: ConfigSettings 7 | :members: 8 | 9 | .. autofunction:: autoset_settings 10 | -------------------------------------------------------------------------------- /docs/html/_sources/metrics.rst.txt: -------------------------------------------------------------------------------- 1 | cdt.metrics 2 | =================================== 3 | .. automodule:: cdt.metrics 4 | 5 | .. autofunction:: precision_recall 6 | 7 | .. autofunction:: SHD 8 | 9 | .. autofunction:: SID 10 | -------------------------------------------------------------------------------- /.codecov.yml: -------------------------------------------------------------------------------- 1 | comment: 2 | layout: "reach, diff, flags, files" 3 | behavior: default 4 | require_changes: true # if true: only post the comment if coverage changes 5 | branches: master # branch names that can post comment 6 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Before contributing, please read and follow all guidelines described on the documentation website: [https://FenTechSolutions.github.io/CausalDiscoveryToolbox/html/developer.html](https://FenTechSolutions.github.io/CausalDiscoveryToolbox/html/developer.html) 4 | 5 | Thank you! 6 | -------------------------------------------------------------------------------- /install-deps/Dockerfile-env-1.1: -------------------------------------------------------------------------------- 1 | FROM divkal/cdt-env-base:1.0 2 | MAINTAINER Diviyan Kalainathan 3 | LABEL version="1.1" 4 | LABEL description="Docker image environment for the Causal Discovery Toolbox" 5 | 6 | RUN Rscript -e 'install.packages(c("sparsebn"),repos="http://cran.us.r-project.org")' 7 | CMD /bin/bash 8 | -------------------------------------------------------------------------------- /tests/datasets/Example_graph_confounders_target.csv: -------------------------------------------------------------------------------- 1 | Cause,Effect 2 | V0,V2 3 | V0,V4 4 | V2,V5 5 | V0,V7 6 | V1,V7 7 | V0,V9 8 | V1,V10 9 | V0,V11 10 | V5,V12 11 | V2,V13 12 | V2,V14 13 | V0,V15 14 | V11,V15 15 | V10,V16 16 | V14,V16 17 | V1,V17 18 | V7,V18 19 | V11,V19 20 | V9,V20 21 | V5,V20 22 | V15,V21 23 | -------------------------------------------------------------------------------- /install-deps/Dockerfile-env: -------------------------------------------------------------------------------- 1 | ARG nv 2 | FROM ubuntu 3 | MAINTAINER Diviyan Kalainathan 4 | LABEL version="0.2.5" 5 | LABEL description="Docker image for the Causal Discovery Toolbox" 6 | 7 | COPY . /tmp 8 | COPY "install-deps/install-dependencies.sh" /tmp 9 | RUN cd /tmp && bash "install-dependencies.sh" 10 | CMD /bin/sh 11 | -------------------------------------------------------------------------------- /tests/datasets/Example_graph_confounders_skeleton.csv: -------------------------------------------------------------------------------- 1 | Cause,Effect 2 | V11,V9 3 | V12,V14 4 | V17,V19 5 | V0,V2 6 | V0,V4 7 | V2,V5 8 | V0,V7 9 | V1,V7 10 | V0,V9 11 | V1,V10 12 | V0,V11 13 | V5,V12 14 | V2,V13 15 | V2,V14 16 | V0,V15 17 | V11,V15 18 | V10,V16 19 | V14,V16 20 | V1,V17 21 | V7,V18 22 | V11,V19 23 | V9,V20 24 | V5,V20 25 | V15,V21 26 | -------------------------------------------------------------------------------- /tests/datasets/Lucas_graph.csv: -------------------------------------------------------------------------------- 1 | Cause,Effect,Score 2 | Allergy,Coughing,1 3 | Anxiety,Smoking,1 4 | Attention_Disorder,Car_Accident,1 5 | Coughing,Fatigue,1 6 | Fatigue,Car_Accident,1 7 | Genetics,Attention_Disorder,1 8 | Genetics,Lung_Cancer,1 9 | Lung_Cancer,Coughing,1 10 | Lung_Cancer,Fatigue,1 11 | Peer_Pressure,Smoking,1 12 | Smoking,Lung_Cancer,1 13 | Smoking,Yellow_Fingers,1 14 | -------------------------------------------------------------------------------- /cdt/data/resources/cyto_full_target.csv: -------------------------------------------------------------------------------- 1 | "Cause","Effect" 2 | "PIP2","PKC" 3 | "plcg","PIP2" 4 | "PIP3","plcg" 5 | "PIP2","PIP3" 6 | "plcg","PKC" 7 | "PKC","pjnk" 8 | "PKC","P38" 9 | "PKA","P38" 10 | "PKC","praf" 11 | "PKA","praf" 12 | "praf","pmek" 13 | "pmek","p44/42" 14 | "PKC","pmek" 15 | "PKA","pakts473" 16 | "PIP3","pakts473" 17 | "PKA","pmek" 18 | "PKA","p44/42" 19 | "PKA","pjnk" 20 | -------------------------------------------------------------------------------- /tests/datasets/Example_graph_target.csv: -------------------------------------------------------------------------------- 1 | Node1,Node2 2 | V0,V2 3 | V0,V3 4 | V0,V4 5 | V2,V5 6 | V3,V6 7 | V0,V7 8 | V1,V7 9 | V0,V8 10 | V0,V9 11 | V3,V9 12 | V1,V10 13 | V0,V11 14 | V3,V11 15 | V5,V12 16 | V6,V12 17 | V2,V13 18 | V2,V14 19 | V6,V14 20 | V0,V15 21 | V11,V15 22 | V10,V16 23 | V14,V16 24 | V8,V17 25 | V1,V17 26 | V7,V18 27 | V8,V19 28 | V11,V19 29 | V9,V20 30 | V5,V20 31 | V15,V21 32 | -------------------------------------------------------------------------------- /docs/data.rst: -------------------------------------------------------------------------------- 1 | cdt.data 2 | ============== 3 | 4 | .. automodule:: cdt.data 5 | .. currentmodule:: cdt.data 6 | 7 | CausalPairGenerator 8 | --------------------- 9 | .. autoclass:: CausalPairGenerator 10 | :members: 11 | 12 | 13 | AcyclicGraphGenerator 14 | ----------------------- 15 | .. autoclass:: AcyclicGraphGenerator 16 | :members: 17 | 18 | load_dataset 19 | --------------------- 20 | .. autofunction:: load_dataset 21 | -------------------------------------------------------------------------------- /tests/datasets/Example_graph_skeleton.csv: -------------------------------------------------------------------------------- 1 | Node1,Node2 2 | V0,V2 3 | V0,V3 4 | V0,V4 5 | V2,V5 6 | V3,V6 7 | V0,V7 8 | V1,V7 9 | V0,V8 10 | V0,V9 11 | V3,V9 12 | V1,V10 13 | V0,V11 14 | V3,V11 15 | V5,V12 16 | V6,V12 17 | V2,V13 18 | V2,V14 19 | V6,V14 20 | V0,V15 21 | V11,V15 22 | V10,V16 23 | V14,V16 24 | V8,V17 25 | V1,V17 26 | V7,V18 27 | V8,V19 28 | V11,V19 29 | V9,V20 30 | V5,V20 31 | V15,V21 32 | -------------------------------------------------------------------------------- /docs/html/_sources/data.rst.txt: -------------------------------------------------------------------------------- 1 | cdt.data 2 | ============== 3 | 4 | .. automodule:: cdt.data 5 | .. currentmodule:: cdt.data 6 | 7 | CausalPairGenerator 8 | --------------------- 9 | .. autoclass:: CausalPairGenerator 10 | :members: 11 | 12 | 13 | AcyclicGraphGenerator 14 | ----------------------- 15 | .. autoclass:: AcyclicGraphGenerator 16 | :members: 17 | 18 | load_dataset 19 | --------------------- 20 | .. autofunction:: load_dataset 21 | -------------------------------------------------------------------------------- /docs/html/_static/documentation_options.js: -------------------------------------------------------------------------------- 1 | var DOCUMENTATION_OPTIONS = { 2 | URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), 3 | VERSION: '0.6.0', 4 | LANGUAGE: 'en', 5 | COLLAPSE_INDEX: false, 6 | BUILDER: 'html', 7 | FILE_SUFFIX: '.html', 8 | LINK_SUFFIX: '.html', 9 | HAS_SOURCE: true, 10 | SOURCELINK_SUFFIX: '.txt', 11 | NAVIGATION_WITH_KEYS: false, 12 | SHOW_SEARCH_SUMMARY: true, 13 | ENABLE_SEARCH_SHORTCUTS: true, 14 | }; -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM fentechai/cdt-base:latest 2 | MAINTAINER Diviyan Kalainathan 3 | LABEL description="Docker image for the Causal Discovery Toolbox" 4 | 5 | RUN mkdir -p /CDT 6 | COPY . /CDT 7 | RUN cd /CDT && \ 8 | python3 -m pip install -r docker-requirements.txt && \ 9 | python3 -m pip install torch --extra-index-url https://download.pytorch.org/whl/cpu && \ 10 | python3 -m pip install pytest pytest-cov && \ 11 | python3 -m pip install codecov && \ 12 | python3 setup.py install 13 | CMD /bin/sh 14 | -------------------------------------------------------------------------------- /nv-Dockerfile: -------------------------------------------------------------------------------- 1 | FROM fentechai/nv-cdt-base:latest 2 | MAINTAINER Diviyan Kalainathan 3 | LABEL description="Nvidia Docker image for the Causal Discovery Toolbox" 4 | 5 | RUN mkdir -p /CDT 6 | COPY . /CDT 7 | RUN cd /CDT && \ 8 | python3 -m pip install -r docker-requirements.txt && \ 9 | python3 -m pip install torch --extra-index-url https://download.pytorch.org/whl/cpu && \ 10 | python3 -m pip install pytest pytest-cov && \ 11 | python3 -m pip install codecov && \ 12 | python3 setup.py install 13 | CMD /bin/sh 14 | -------------------------------------------------------------------------------- /docs/_static/custom.css: -------------------------------------------------------------------------------- 1 | .wy-side-nav-search, .wy-nav-top { 2 | background: #ffffff; 3 | color: auto; 4 | } 5 | 6 | .wy-menu-vertical { 7 | background: #415867; 8 | 9 | } 10 | .wy-side-scroll { 11 | background: #415867; 12 | } 13 | 14 | .wy-nav-side { 15 | background: #415867; 16 | } 17 | .version { 18 | color: #1cb39a; 19 | } 20 | .wy-side-nav-search>div.version { 21 | margin-top:-.4045em; 22 | margin-bottom:.809em; 23 | font-weight:normal; 24 | color: #1cb39a; 25 | } 26 | .rst-content dl:not(.docutils) dt { 27 | color: #189b85; 28 | } 29 | -------------------------------------------------------------------------------- /docs/html/_static/custom.css: -------------------------------------------------------------------------------- 1 | .wy-side-nav-search, .wy-nav-top { 2 | background: #ffffff; 3 | color: auto; 4 | } 5 | 6 | .wy-menu-vertical { 7 | background: #415867; 8 | 9 | } 10 | .wy-side-scroll { 11 | background: #415867; 12 | } 13 | 14 | .wy-nav-side { 15 | background: #415867; 16 | } 17 | .version { 18 | color: #1cb39a; 19 | } 20 | .wy-side-nav-search>div.version { 21 | margin-top:-.4045em; 22 | margin-bottom:.809em; 23 | font-weight:normal; 24 | color: #1cb39a; 25 | } 26 | .rst-content dl:not(.docutils) dt { 27 | color: #189b85; 28 | } 29 | -------------------------------------------------------------------------------- /tests/scripts/test_datasetloader.py: -------------------------------------------------------------------------------- 1 | """Testing dataset import""" 2 | 3 | from cdt.data import load_dataset 4 | 5 | 6 | def test_tuebingen(): 7 | data, labels = load_dataset('tuebingen') 8 | # print(data.head(), labels.head()) 9 | 10 | 11 | def test_sachs(): 12 | data, graph = load_dataset('sachs') 13 | 14 | 15 | def test_dream(): 16 | data, graph = load_dataset('dream4-2') 17 | 18 | 19 | def test_unknown_dataset(): 20 | try: 21 | data, graph = load_dataset('asdasd') 22 | except ValueError: 23 | pass 24 | 25 | 26 | if __name__ == '__main__': 27 | test_tuebingen() 28 | -------------------------------------------------------------------------------- /cdt/causality/pairwise/Jarfo_model/util.py: -------------------------------------------------------------------------------- 1 | """ 2 | Random permutation of a symmetrized database 3 | 4 | """ 5 | 6 | # Author: Jose A. R. Fonollosa 7 | # 8 | # License: Apache, Version 2.0 9 | 10 | import numpy as np 11 | 12 | def random_permutation(x, y, seed=14777777): 13 | np.random.seed(seed) 14 | global_random_permutation = np.array(range(len(x)//2)) 15 | np.random.shuffle(global_random_permutation) 16 | index = np.array(range(len(x))) 17 | index[0::2] = 2*global_random_permutation 18 | index[1::2] = 2*global_random_permutation + 1 19 | x.index = index 20 | y.index = index 21 | return x.sort_index(), y.sort_index() 22 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | SPHINXPROJ = CausalDiscoveryToolbox 8 | SOURCEDIR = . 9 | BUILDDIR = . 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/.old.index: -------------------------------------------------------------------------------- 1 | .. Causal Discovery Toolbox documentation master file, created by 2 | sphinx-quickstart on Sun Apr 22 18:41:44 2018. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. cdt.causality 5 | cdt.independence 6 | cdt.generators 7 | utils 8 | 9 | 10 | Causal Discovery Toolbox: Index 11 | ==================================================== 12 | .. include:: readme-link.md 13 | 14 | .. toctree:: 15 | :maxdepth: 2 16 | 17 | Home 18 | Installation Instructions 19 | utils 20 | metrics 21 | settings 22 | 23 | Indices and tables 24 | ================== 25 | 26 | * :ref:`genindex` 27 | * :ref:`modindex` 28 | * :ref:`search` 29 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes will be documented in this file. 4 | 5 | ## 0.2.5 6 | - Added documentation website (not yet completed) 7 | - Eased up the API of some classes and added robustness to the codebase 8 | 9 | ## 0.2.4 10 | - Updates and bugfixes on CGNN and pytorch models 11 | 12 | ## 0.2.3 13 | - Added many algorithms in R (Pcalg, bnlearn, SID...) 14 | 15 | ## 0.2.2 16 | - Added the R wrapper for packages at `cdt.utils.R` 17 | 18 | ## 0.2 19 | ### Rework of the Toobox 20 | - Dropped the `Graph` class to use the `networkx` classes 21 | - Removed the traceback of the warning messages 22 | - Cleaning out dependencies 23 | - Dropping support of tensorflow to keep PyTorch 24 | - Added causal generators 25 | 26 | ### Added tests 27 | - Tests for each class 28 | - Travis for automatic testing 29 | 30 | 31 | ## 0.1 32 | 33 | - Initial Development 34 | 35 | -------------------------------------------------------------------------------- /docs/html/_static/js/badge_only.js: -------------------------------------------------------------------------------- 1 | !function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=4)}({4:function(e,t,r){}}); -------------------------------------------------------------------------------- /.circleci/bumpversion.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | VERSION=$(cat setup.py| grep version | cut -c 20- | rev | cut -c 3- | rev) 4 | COMMIT_MESSAGE="$(git log --format=%B -n 1)" 5 | 6 | git config --global user.email "diviyan@circleci.com" 7 | git config --global user.name "CircleCI Bumpversion" 8 | git config --global push.default simple 9 | pip install bumpversion 10 | if [[ $COMMIT_MESSAGE == *"[NV]"* ]] || [[ $COMMIT_MESSAGE == *"[DOC]"* ]]; 11 | then echo "No version update"; 12 | elif [[ $COMMIT_MESSAGE == *"[REL]"* ]]; 13 | then bumpversion --current-version $VERSION minor setup.py README.md docs/index.rst docs/conf.py cdt/__init__.py; 14 | elif [[ $COMMIT_MESSAGE == *"[MREL]"* ]]; 15 | then bumpversion --current-version $VERSION major setup.py README.md docs/index.rst docs/conf.py cdt/__init__.py; 16 | else bumpversion --current-version $VERSION patch setup.py README.md docs/index.rst docs/conf.py cdt/__init__.py; 17 | fi 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "[BUG] Function or algorithm name + Bug summary" 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | Encountering a bug while using this package may occur. In order to fix the said bug and improve all users’ experience, it is highly recommended to submit a bug report on the GitHub issue tracker: https://github.com/FenTechSolutions/CausalDiscoveryToolbox/issues 11 | 12 | **Describe the bug** 13 | A clear and concise description of what the bug is. 14 | 15 | **Please mention** 16 | - Your cdt package version or docker image tag. 17 | - Your python version. 18 | - Your PyTorch package version. 19 | - Your hardware configuration, if there are GPUs available. 20 | - The full traceback of the raised error if one is raised. 21 | - A small code snippet to reproduce the bug if the description is not explicit. 22 | -------------------------------------------------------------------------------- /install-deps/install-dependencies.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | apt-get update 4 | DEBIAN_FRONTEND=noninteractive apt-get install -y tzdata 5 | apt-get -q install r-base -y --allow-unauthenticated 6 | apt-get -q install libssl-dev -y 7 | apt-get -q install libgmp3-dev -y --allow-unauthenticated 8 | apt-get -q install git -y 9 | apt-get -q install build-essential -y --allow-unauthenticated 10 | apt-get -q install libv8-3.14-dev -y --allow-unauthenticated 11 | apt-get -q install libcurl4-openssl-dev -y --allow-unauthenticated 12 | Rscript -e 'install.packages(c("V8","sfsmisc","clue","randomForest","lattice","devtools","MASS"),repos="http://cran.us.r-project.org")' 13 | Rscript -e 'source("http://bioconductor.org/biocLite.R"); biocLite(c("CAM", "SID", "bnlearn", "pcalg", "kpcalg", "D2C"))' 14 | Rscript -e 'library(devtools); install_github("cran/momentchi2"); install_github("Diviyan-Kalainathan/RCIT")' 15 | Rscript -e 'install.packages(c("sparsebn"),repos="http://cran.us.r-project.org")' 16 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | set SPHINXPROJ=CausalDiscoveryToolbox 13 | 14 | if "%1" == "" goto help 15 | 16 | %SPHINXBUILD% >NUL 2>NUL 17 | if errorlevel 9009 ( 18 | echo. 19 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 20 | echo.installed, then set the SPHINXBUILD environment variable to point 21 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 22 | echo.may add the Sphinx directory to PATH. 23 | echo. 24 | echo.If you don't have Sphinx installed, grab it from 25 | echo.http://sphinx-doc.org/ 26 | exit /b 1 27 | ) 28 | 29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 30 | goto end 31 | 32 | :help 33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% 34 | 35 | :end 36 | popd 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | *.xml 6 | .ipynb_checkpoints 7 | .pytest_cache 8 | *~ 9 | \#* 10 | *\# 11 | .idea 12 | doctrees/ 13 | .buildinfo 14 | builddir 15 | # C extensions 16 | *.so 17 | rel_travis* 18 | # Distribution / packaging 19 | .Python 20 | env/ 21 | build/ 22 | develop-eggs/ 23 | dist/ 24 | downloads/ 25 | eggs/ 26 | .eggs/ 27 | lib/ 28 | lib64/ 29 | parts/ 30 | sdist/ 31 | var/ 32 | wheels/ 33 | *.egg-info/ 34 | .installed.cfg 35 | *.egg 36 | _build/ 37 | scratch 38 | 39 | # PyInstaller 40 | # Usually these files are written by a python script from a template 41 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 42 | *.manifest 43 | *.spec 44 | 45 | # Installer logs 46 | pip-log.txt 47 | pip-delete-this-directory.txt 48 | 49 | # Unit test / coverage reports 50 | htmlcov/ 51 | .tox/ 52 | .coverage 53 | .coverage.* 54 | .cache 55 | nosetests.xml 56 | coverage.xml 57 | *,cover 58 | .hypothesis/ 59 | test_data.csv 60 | test_target.csv 61 | -------------------------------------------------------------------------------- /tests/scripts/test_metrics.py: -------------------------------------------------------------------------------- 1 | """Test the metrics.""" 2 | import numpy as np 3 | import networkx as nx 4 | from cdt.metrics import precision_recall, SHD, SID, SHD_CPDAG, SID_CPDAG 5 | from copy import deepcopy 6 | 7 | 8 | def init(): 9 | mat1 = np.zeros((3, 3)) 10 | mat1[1, 0] = 1 11 | mat1[2, 1] = 1 12 | mat1[2, 0] = 1 13 | mat2 = deepcopy(mat1) 14 | mat2[2, 1] = 0 15 | mat2[1, 2] = .5 16 | return nx.DiGraph(mat1), nx.DiGraph(mat2) 17 | 18 | 19 | def test_precision_recall(): 20 | assert precision_recall(*init()) 21 | 22 | 23 | def test_SHD(): 24 | assert SHD(*init()) == 2 25 | assert SHD(*init(), double_for_anticausal=False) == 1 26 | 27 | 28 | def test_SID(): 29 | assert SID(*init()) == 4.0 30 | 31 | def test_SIDC(): 32 | assert type(SID_CPDAG(*init())) == tuple 33 | 34 | 35 | def test_SHDC(): 36 | assert type(SHD_CPDAG(*init())) == np.float64 37 | 38 | if __name__ == '__main__': 39 | a, b = init() 40 | print(SID_CPDAG(a, b)) 41 | print(type(SHD_CPDAG(a, b)) == np.float64) 42 | -------------------------------------------------------------------------------- /docs/models.rst: -------------------------------------------------------------------------------- 1 | PyTorch Models 2 | ============== 3 | 4 | In order to have more flexibility in the use of neural network models, 5 | these are directly assessible as `torch.nn.Module`, using the extensions `.model`, for example: 6 | 7 | .. code-block:: python 8 | 9 | >>> from cdt.causality.graph.model.CGNN 10 | 11 | to import the CGNN Pytorch model. The available models are the following: 12 | 13 | - CGNN 14 | 15 | - SAM 16 | 17 | - NCC 18 | 19 | - GNN 20 | 21 | - FSGNN 22 | 23 | .. currentmodule:: cdt.causality.graph.model 24 | 25 | CGNN 26 | ---- 27 | 28 | .. autoclass:: CGNN_model 29 | :members: 30 | 31 | SAM 32 | --- 33 | 34 | .. autoclass:: SAM_generators 35 | :members: 36 | 37 | .. autoclass:: SAM_discriminator 38 | :members: 39 | 40 | .. currentmodule:: cdt.causality.pairwise.model 41 | 42 | NCC 43 | --- 44 | 45 | .. autoclass:: NCC_model 46 | :members: 47 | 48 | GNN 49 | --- 50 | 51 | .. autoclass:: GNN_model 52 | :members: 53 | 54 | .. currentmodule:: cdt.independence.graph.model 55 | 56 | FSGNN 57 | ----- 58 | 59 | .. autoclass:: FSGNN_model 60 | :members: 61 | -------------------------------------------------------------------------------- /docs/html/_sources/models.rst.txt: -------------------------------------------------------------------------------- 1 | PyTorch Models 2 | ============== 3 | 4 | In order to have more flexibility in the use of neural network models, 5 | these are directly assessible as `torch.nn.Module`, using the extensions `.model`, for example: 6 | 7 | .. code-block:: python 8 | 9 | >>> from cdt.causality.graph.model.CGNN 10 | 11 | to import the CGNN Pytorch model. The available models are the following: 12 | 13 | - CGNN 14 | 15 | - SAM 16 | 17 | - NCC 18 | 19 | - GNN 20 | 21 | - FSGNN 22 | 23 | .. currentmodule:: cdt.causality.graph.model 24 | 25 | CGNN 26 | ---- 27 | 28 | .. autoclass:: CGNN_model 29 | :members: 30 | 31 | SAM 32 | --- 33 | 34 | .. autoclass:: SAM_generators 35 | :members: 36 | 37 | .. autoclass:: SAM_discriminator 38 | :members: 39 | 40 | .. currentmodule:: cdt.causality.pairwise.model 41 | 42 | NCC 43 | --- 44 | 45 | .. autoclass:: NCC_model 46 | :members: 47 | 48 | GNN 49 | --- 50 | 51 | .. autoclass:: GNN_model 52 | :members: 53 | 54 | .. currentmodule:: cdt.independence.graph.model 55 | 56 | FSGNN 57 | ----- 58 | 59 | .. autoclass:: FSGNN_model 60 | :members: 61 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Diviyan Kalainathan 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. 22 | -------------------------------------------------------------------------------- /cdt/timeseries/pairwise/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | .. MIT License 3 | .. 4 | .. Copyright (c) 2018 Diviyan Kalainathan 5 | .. 6 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 7 | .. of this software and associated documentation files (the "Software"), to deal 8 | .. in the Software without restriction, including without limitation the rights 9 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | .. copies of the Software, and to permit persons to whom the Software is 11 | .. furnished to do so, subject to the following conditions: 12 | .. 13 | .. The above copyright notice and this permission notice shall be included in all 14 | .. copies or substantial portions of the Software. 15 | .. 16 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | .. SOFTWARE. 23 | """ 24 | -------------------------------------------------------------------------------- /cdt/causality/pairwise/Jarfo_model/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | .. MIT License 4 | .. 5 | .. Copyright (c) 2018 Diviyan Kalainathan 6 | .. 7 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 8 | .. of this software and associated documentation files (the "Software"), to deal 9 | .. in the Software without restriction, including without limitation the rights 10 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | .. copies of the Software, and to permit persons to whom the Software is 12 | .. furnished to do so, subject to the following conditions: 13 | .. 14 | .. The above copyright notice and this permission notice shall be included in all 15 | .. copies or substantial portions of the Software. 16 | .. 17 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | .. SOFTWARE. 24 | """ 25 | -------------------------------------------------------------------------------- /cdt/timeseries/graph/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | .. MIT License 3 | .. 4 | .. Copyright (c) 2018 Diviyan Kalainathan 5 | .. 6 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 7 | .. of this software and associated documentation files (the "Software"), to deal 8 | .. in the Software without restriction, including without limitation the rights 9 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | .. copies of the Software, and to permit persons to whom the Software is 11 | .. furnished to do so, subject to the following conditions: 12 | .. 13 | .. The above copyright notice and this permission notice shall be included in all 14 | .. copies or substantial portions of the Software. 15 | .. 16 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | .. SOFTWARE. 23 | """ 24 | from .VARLiNGAM import VarLiNGAM 25 | -------------------------------------------------------------------------------- /cdt/causality/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | .. MIT License 3 | .. 4 | .. Copyright (c) 2018 Diviyan Kalainathan 5 | .. 6 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 7 | .. of this software and associated documentation files (the "Software"), to deal 8 | .. in the Software without restriction, including without limitation the rights 9 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | .. copies of the Software, and to permit persons to whom the Software is 11 | .. furnished to do so, subject to the following conditions: 12 | .. 13 | .. The above copyright notice and this permission notice shall be included in all 14 | .. copies or substantial portions of the Software. 15 | .. 16 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | .. SOFTWARE. 23 | """ 24 | from .pairwise import __init__ 25 | from .graph import __init__ 26 | -------------------------------------------------------------------------------- /cdt/timeseries/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | .. MIT License 3 | .. 4 | .. Copyright (c) 2018 Diviyan Kalainathan 5 | .. 6 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 7 | .. of this software and associated documentation files (the "Software"), to deal 8 | .. in the Software without restriction, including without limitation the rights 9 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | .. copies of the Software, and to permit persons to whom the Software is 11 | .. furnished to do so, subject to the following conditions: 12 | .. 13 | .. The above copyright notice and this permission notice shall be included in all 14 | .. copies or substantial portions of the Software. 15 | .. 16 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | .. SOFTWARE. 23 | """ 24 | from .graph import __init__ 25 | from .pairwise import __init__ 26 | -------------------------------------------------------------------------------- /cdt/independence/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | .. MIT License 3 | .. 4 | .. Copyright (c) 2018 Diviyan Kalainathan 5 | .. 6 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 7 | .. of this software and associated documentation files (the "Software"), to deal 8 | .. in the Software without restriction, including without limitation the rights 9 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | .. copies of the Software, and to permit persons to whom the Software is 11 | .. furnished to do so, subject to the following conditions: 12 | .. 13 | .. The above copyright notice and this permission notice shall be included in all 14 | .. copies or substantial portions of the Software. 15 | .. 16 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | .. SOFTWARE. 23 | """ 24 | from .stats import __init__ as stats 25 | from .graph import __init__ as skeleton 26 | -------------------------------------------------------------------------------- /tests/scripts/test_independence_stats.py: -------------------------------------------------------------------------------- 1 | """Test stat methods.""" 2 | 3 | 4 | import os 5 | import pandas as pd 6 | import numpy as np 7 | import networkx as nx 8 | from cdt.independence.stats import (AdjMI, NormMI, PearsonCorrelation, 9 | SpearmanCorrelation, KendallTau, 10 | NormalizedHSIC, MIRegression) 11 | 12 | from cdt.utils.graph import dagify_min_edge 13 | 14 | 15 | def init(): 16 | return pd.read_csv('{}/../datasets/Example_graph_numdata.csv'.format(os.path.dirname(os.path.realpath(__file__)))).iloc[:50, :5] 17 | 18 | 19 | def test_statistical_methods(): 20 | data = init() 21 | for method in [AdjMI, NormMI, PearsonCorrelation, SpearmanCorrelation, 22 | KendallTau, NormalizedHSIC, MIRegression]: 23 | model = method() 24 | assert type(model.predict_undirected_graph(data)) == nx.Graph 25 | assert model.predict(data.iloc[:, 0], data.iloc[:, 1]) != model.predict(data.iloc[:, 0], data.iloc[:, 0]) 26 | 27 | 28 | def test_dagify(): 29 | graph = nx.DiGraph(np.random.uniform(size=(5,5))) 30 | for node in graph.nodes(): 31 | graph.remove_edge(node, node) 32 | g2 = dagify_min_edge(graph) 33 | assert nx.is_directed_acyclic_graph(g2) 34 | 35 | 36 | if __name__ == '__main__': 37 | test_dagify() 38 | -------------------------------------------------------------------------------- /cdt/utils/R_templates/test_import.R: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (c) 2018 Diviyan Kalainathan 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. 22 | 23 | # Code to test the import of the 'bnlearn' package. 24 | # ToDo: Try to install if not available. 25 | result = library("{package}") 26 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright (C) 2016 Diviyan Kalainathan 3 | # Licence: Apache 2.0 4 | 5 | try: 6 | from setuptools import setup, find_packages 7 | except ImportError: 8 | from distutils.core import setup, find_packages 9 | 10 | 11 | with open('README.md', encoding="utf-8") as f: 12 | long_description = f.read() 13 | 14 | 15 | def setup_package(): 16 | setup(name='cdt', 17 | version='0.6.0', 18 | description='A Toolbox for causal graph inference', 19 | long_description="Documentation available at https://fentechsolutions.github.io/CausalDiscoveryToolbox/html/index.html", 20 | long_description_content_type="text/markdown", 21 | packages=find_packages(exclude=['examples', 'tests', 'tests.*']), 22 | url='https://github.com/FenTechSolutions/CausalDiscoveryToolbox', 23 | package_data={'': ['**/*.R', '**/*.csv']}, 24 | install_requires=['numpy', 'scipy', 'scikit-learn', 25 | 'joblib', 'pandas', 'statsmodels', 26 | 'networkx', 'skrebate', 'tqdm', 'GPUtil', 'requests'], 27 | include_package_data=True, 28 | author='Diviyan Kalainathan', 29 | author_email='diviyan.kalainathan@lri.fr', 30 | license='Apache 2.0') 31 | 32 | 33 | if __name__ == '__main__': 34 | setup_package() 35 | -------------------------------------------------------------------------------- /tests/scripts/test_independence_graph.py: -------------------------------------------------------------------------------- 1 | """Test markov blanket recovering methods.""" 2 | 3 | import os 4 | import pandas as pd 5 | import networkx as nx 6 | from cdt import SETTINGS 7 | from cdt.independence.graph import (Glasso, ARD, DecisionTreeRegression, 8 | LinearSVRL2, HSICLasso, 9 | ) 10 | from cdt.utils.graph import remove_indirect_links 11 | 12 | SETTINGS.NJOBS = 1 13 | 14 | 15 | def init(): 16 | return pd.read_csv('{}/../datasets/Example_graph_numdata.csv'.format(os.path.dirname(os.path.realpath(__file__)))).iloc[:50, :5] 17 | 18 | 19 | def test_statistical_methods(): 20 | data = init() 21 | for method in [Glasso, ARD, DecisionTreeRegression, 22 | LinearSVRL2, HSICLasso, 23 | ]: 24 | model = method() 25 | # print(method) 26 | assert isinstance(model.predict(data), nx.Graph) 27 | return 0 28 | 29 | 30 | def test_indirect_link_removal(): 31 | data = init() 32 | umg = Glasso().predict(data) 33 | for method in ["nd", "clr", "aracne"]: 34 | assert isinstance(remove_indirect_links(umg, alg=method), nx.Graph) 35 | return 0 36 | 37 | 38 | if __name__ == '__main__': 39 | print("Statistical Methods") 40 | test_statistical_methods() 41 | print("test_indirect_link_removal") 42 | test_indirect_link_removal() 43 | -------------------------------------------------------------------------------- /cdt/independence/stats/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | .. MIT License 3 | .. 4 | .. Copyright (c) 2018 Diviyan Kalainathan 5 | .. 6 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 7 | .. of this software and associated documentation files (the "Software"), to deal 8 | .. in the Software without restriction, including without limitation the rights 9 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | .. copies of the Software, and to permit persons to whom the Software is 11 | .. furnished to do so, subject to the following conditions: 12 | .. 13 | .. The above copyright notice and this permission notice shall be included in all 14 | .. copies or substantial portions of the Software. 15 | .. 16 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | .. SOFTWARE. 23 | """ 24 | from .all_types import AdjMI, NormMI 25 | from .numerical import (PearsonCorrelation, SpearmanCorrelation, KendallTau, NormalizedHSIC, MIRegression) 26 | -------------------------------------------------------------------------------- /cdt/independence/graph/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | .. MIT License 3 | .. 4 | .. Copyright (c) 2018 Diviyan Kalainathan 5 | .. 6 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 7 | .. of this software and associated documentation files (the "Software"), to deal 8 | .. in the Software without restriction, including without limitation the rights 9 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | .. copies of the Software, and to permit persons to whom the Software is 11 | .. furnished to do so, subject to the following conditions: 12 | .. 13 | .. The above copyright notice and this permission notice shall be included in all 14 | .. copies or substantial portions of the Software. 15 | .. 16 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | .. SOFTWARE. 23 | """ 24 | from .Lasso import (Glasso, HSICLasso) 25 | from .FSGNN import FSGNN 26 | from .FSRegression import (LinearSVRL2, #RRelief, RFECVLinearSVR, 27 | DecisionTreeRegression, ARD) 28 | -------------------------------------------------------------------------------- /cdt/causality/graph/R_templates/lingam.R: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (c) 2018 Diviyan Kalainathan 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. 22 | 23 | library(pcalg) 24 | 25 | dataset <- read.csv(file='{FOLDER}{FILE}', header=FALSE, sep=","); 26 | estDAG <- lingam(dataset, verbose = {VERBOSE}) 27 | write.csv(as.matrix(estDAG$Bpruned),row.names = FALSE, file = '{FOLDER}{OUTPUT}'); 28 | -------------------------------------------------------------------------------- /docs/utils.rst: -------------------------------------------------------------------------------- 1 | 2 | cdt.utils 3 | ========= 4 | .. automodule:: cdt.utils 5 | 6 | cdt.utils.R 7 | ----------------------- 8 | .. automodule:: cdt.utils.R 9 | .. autoclass:: DefaultRPackages 10 | :members: 11 | 12 | .. autofunction:: launch_R_script 13 | 14 | 15 | cdt.utils.io 16 | ------------ 17 | .. automodule:: cdt.utils.io 18 | 19 | .. autofunction:: read_causal_pairs 20 | .. autofunction:: read_adjacency_matrix 21 | .. autofunction:: read_list_edges 22 | 23 | cdt.utils.graph 24 | --------------- 25 | .. automodule:: cdt.utils.graph 26 | .. autofunction:: network_deconvolution 27 | .. autofunction:: aracne 28 | .. autofunction:: clr 29 | .. autofunction:: remove_indirect_links 30 | .. autofunction:: dagify_min_edge 31 | 32 | cdt.utils.loss 33 | -------------- 34 | .. automodule:: cdt.utils.loss 35 | 36 | .. autoclass:: MMDloss 37 | 38 | .. autoclass:: MomentMatchingLoss 39 | 40 | .. autoclass:: TTestCriterion 41 | :members: 42 | 43 | .. autofunction:: notears_constr 44 | 45 | cdt.utils.parallel 46 | ------------------ 47 | .. automodule:: cdt.utils.parallel 48 | 49 | .. autofunction:: parallel_run 50 | 51 | .. autofunction:: parallel_run_generator 52 | 53 | cdt.utils.torch 54 | --------------- 55 | .. automodule:: cdt.utils.torch 56 | 57 | .. autoclass:: ChannelBatchNorm1d 58 | :members: 59 | 60 | .. autoclass:: Linear3D 61 | :members: 62 | 63 | .. autofunction:: gumbel_softmax 64 | 65 | .. autoclass:: MatrixSampler 66 | :members: 67 | -------------------------------------------------------------------------------- /docs/html/_sources/utils.rst.txt: -------------------------------------------------------------------------------- 1 | 2 | cdt.utils 3 | ========= 4 | .. automodule:: cdt.utils 5 | 6 | cdt.utils.R 7 | ----------------------- 8 | .. automodule:: cdt.utils.R 9 | .. autoclass:: DefaultRPackages 10 | :members: 11 | 12 | .. autofunction:: launch_R_script 13 | 14 | 15 | cdt.utils.io 16 | ------------ 17 | .. automodule:: cdt.utils.io 18 | 19 | .. autofunction:: read_causal_pairs 20 | .. autofunction:: read_adjacency_matrix 21 | .. autofunction:: read_list_edges 22 | 23 | cdt.utils.graph 24 | --------------- 25 | .. automodule:: cdt.utils.graph 26 | .. autofunction:: network_deconvolution 27 | .. autofunction:: aracne 28 | .. autofunction:: clr 29 | .. autofunction:: remove_indirect_links 30 | .. autofunction:: dagify_min_edge 31 | 32 | cdt.utils.loss 33 | -------------- 34 | .. automodule:: cdt.utils.loss 35 | 36 | .. autoclass:: MMDloss 37 | 38 | .. autoclass:: MomentMatchingLoss 39 | 40 | .. autoclass:: TTestCriterion 41 | :members: 42 | 43 | .. autofunction:: notears_constr 44 | 45 | cdt.utils.parallel 46 | ------------------ 47 | .. automodule:: cdt.utils.parallel 48 | 49 | .. autofunction:: parallel_run 50 | 51 | .. autofunction:: parallel_run_generator 52 | 53 | cdt.utils.torch 54 | --------------- 55 | .. automodule:: cdt.utils.torch 56 | 57 | .. autoclass:: ChannelBatchNorm1d 58 | :members: 59 | 60 | .. autoclass:: Linear3D 61 | :members: 62 | 63 | .. autofunction:: gumbel_softmax 64 | 65 | .. autoclass:: MatrixSampler 66 | :members: 67 | -------------------------------------------------------------------------------- /cdt/utils/R_templates/cpdag.R: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (c) 2018 Diviyan Kalainathan 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. 22 | 23 | library(pcalg) 24 | library(methods) 25 | 26 | dag <- read.csv(file="{dag}" , header=FALSE, sep=",") 27 | dag <- as(dag, "matrix") 28 | 29 | cpdag <- as(dag2cpdag(as(dag, "graphNEL")), "matrix") 30 | 31 | write.table(cpdag, file='{result}', row.names=FALSE, col.names=FALSE) 32 | -------------------------------------------------------------------------------- /cdt/utils/R_templates/sid.R: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (c) 2018 Diviyan Kalainathan 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. 22 | 23 | library(SID) 24 | library(methods) 25 | 26 | target <- read.csv(file="{target}" , header=FALSE, sep=",") 27 | prediction <- read.csv(file="{prediction}" , header=FALSE, sep=",") 28 | 29 | SID_dist <- structIntervDist(target, prediction)$sid 30 | write.table(SID_dist, '{result}', row.names=FALSE, col.names=FALSE) 31 | -------------------------------------------------------------------------------- /cdt/causality/pairwise/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | .. MIT License 3 | .. 4 | .. Copyright (c) 2018 Diviyan Kalainathan 5 | .. 6 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 7 | .. of this software and associated documentation files (the "Software"), to deal 8 | .. in the Software without restriction, including without limitation the rights 9 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | .. copies of the Software, and to permit persons to whom the Software is 11 | .. furnished to do so, subject to the following conditions: 12 | .. 13 | .. The above copyright notice and this permission notice shall be included in all 14 | .. copies or substantial portions of the Software. 15 | .. 16 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | .. SOFTWARE. 23 | """ 24 | from .ANM import ANM 25 | from .CDS import CDS 26 | from .Jarfo import Jarfo 27 | from .IGCI import IGCI 28 | from .GNN import GNN 29 | from .Bivariate_fit import BivariateFit 30 | from .RECI import RECI 31 | from ...utils.Settings import SETTINGS 32 | from .RCC import RCC 33 | from .NCC import NCC 34 | -------------------------------------------------------------------------------- /cdt/causality/graph/R_templates/CCDr.R: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (c) 2018 Diviyan Kalainathan 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. 22 | 23 | 24 | library(sparsebn) 25 | library(MASS) 26 | 27 | dataset <- read.csv(file='{FOLDER}{FILE}', header=FALSE, sep=","); 28 | dat <- sparsebnData(as.matrix(dataset), type = "c"); 29 | estDAG <- estimate.dag(data = dat); 30 | 31 | lambda = select.parameter(estDAG,dat); 32 | write.matrix(get.adjacency.matrix(estDAG[[lambda]]), 33 | file = '{FOLDER}{OUTPUT}', sep=","); 34 | -------------------------------------------------------------------------------- /cdt/causality/graph/__init__.py: -------------------------------------------------------------------------------- 1 | """Find causal relationships and output a directed graph. 2 | 3 | .. MIT License 4 | .. 5 | .. Copyright (c) 2018 Diviyan Kalainathan 6 | .. 7 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 8 | .. of this software and associated documentation files (the "Software"), to deal 9 | .. in the Software without restriction, including without limitation the rights 10 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | .. copies of the Software, and to permit persons to whom the Software is 12 | .. furnished to do so, subject to the following conditions: 13 | .. 14 | .. The above copyright notice and this permission notice shall be included in all 15 | .. copies or substantial portions of the Software. 16 | .. 17 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | .. SOFTWARE. 24 | """ 25 | from .PC import PC 26 | from .CGNN import CGNN 27 | from .SAMv1 import SAMv1 28 | from .SAM import SAM 29 | from .GES import GES 30 | from .GIES import GIES 31 | from .CAM import CAM 32 | from .LiNGAM import LiNGAM 33 | from .bnlearn import MMPC, GS, IAMB, Fast_IAMB, Inter_IAMB 34 | from .CCDr import CCDr 35 | -------------------------------------------------------------------------------- /tests/scripts/test_io.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import pandas as pd 4 | from cdt.utils.io import (read_list_edges, 5 | read_adjacency_matrix, 6 | read_causal_pairs) 7 | import networkx as nx 8 | import os 9 | 10 | 11 | def test_read_causal_pairs(): 12 | w = read_causal_pairs('{}/../datasets/Example_pairwise_pairs.csv'.format(os.path.dirname(os.path.realpath(__file__)))) 13 | assert type(w) == pd.DataFrame 14 | data = pd.read_csv('{}/../datasets/Example_pairwise_pairs.csv'.format(os.path.dirname(os.path.realpath(__file__)))) 15 | w = read_causal_pairs(data) 16 | assert type(w) == pd.DataFrame 17 | 18 | 19 | def test_read_adj_mat(): 20 | w = read_adjacency_matrix('{}/../datasets/Example_target_adj.csv'.format(os.path.dirname(os.path.realpath(__file__)))) 21 | assert type(w) == nx.DiGraph 22 | data = pd.read_csv('{}/../datasets/Example_target_adj.csv'.format(os.path.dirname(os.path.realpath(__file__)))) 23 | w = read_adjacency_matrix(data, directed=False) 24 | assert type(w) == nx.Graph 25 | 26 | 27 | def test_read_list_edges(): 28 | w = read_list_edges('{}/../datasets/Example_graph_target.csv'.format(os.path.dirname(os.path.realpath(__file__)))) 29 | assert type(w) == nx.DiGraph 30 | data = pd.read_csv('{}/../datasets/Example_graph_target.csv'.format(os.path.dirname(os.path.realpath(__file__)))) 31 | w = read_list_edges(data, directed=False) 32 | assert type(w) == nx.Graph 33 | 34 | 35 | if __name__ == '__main__': 36 | test_read_causal_pairs() 37 | test_read_adj_mat() 38 | test_read_list_edges() 39 | -------------------------------------------------------------------------------- /cdt/__init__.py: -------------------------------------------------------------------------------- 1 | """The Causal Discovery Toolbox contains various methods for graph structure recovery and causal inference. 2 | 3 | It is CUDA-compatible for the most computationally expensive algorithms. 4 | 5 | .. MIT License 6 | .. 7 | .. Copyright (c) 2018 Diviyan Kalainathan 8 | .. 9 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 10 | .. of this software and associated documentation files (the "Software"), to deal 11 | .. in the Software without restriction, including without limitation the rights 12 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | .. copies of the Software, and to permit persons to whom the Software is 14 | .. furnished to do so, subject to the following conditions: 15 | .. 16 | .. The above copyright notice and this permission notice shall be included in all 17 | .. copies or substantial portions of the Software. 18 | .. 19 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | .. SOFTWARE. 26 | """ 27 | 28 | import cdt.causality 29 | import cdt.independence 30 | import cdt.data 31 | import cdt.metrics 32 | from cdt.utils import loss 33 | from cdt.utils.Settings import SETTINGS 34 | from cdt.utils.R import RPackages 35 | __version__ = '0.6.0' 36 | -------------------------------------------------------------------------------- /cdt/causality/graph/R_templates/cam.R: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (c) 2018 Diviyan Kalainathan 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. 22 | 23 | 24 | library(CAM) 25 | 26 | dataset <- read.csv(file='{FOLDER}{FILE}', header=FALSE, sep=","); 27 | estDAG <- CAM(dataset, scoreName = "{SCORE}", numCores = {NJOBS}, output = {VERBOSE}, 28 | variableSel = {VARSEL}, variableSelMethod = {SELMETHOD}, pruning = {PRUNING}, 29 | pruneMethod = {PRUNMETHOD}, pruneMethodPars = list(cutOffPVal = {CUTOFF})) 30 | write.csv(as.matrix(estDAG$Adj),row.names = FALSE, file = '{FOLDER}{OUTPUT}'); 31 | -------------------------------------------------------------------------------- /cdt/data/resources/Tuebingen_targets.csv: -------------------------------------------------------------------------------- 1 | SampleID,Target 2 | pair1,1.0 3 | pair2,1.0 4 | pair3,1.0 5 | pair4,1.0 6 | pair5,1.0 7 | pair6,1.0 8 | pair7,1.0 9 | pair8,1.0 10 | pair9,1.0 11 | pair10,1.0 12 | pair11,1.0 13 | pair12,1.0 14 | pair13,1.0 15 | pair14,1.0 16 | pair15,1.0 17 | pair16,1.0 18 | pair17,1.0 19 | pair18,1.0 20 | pair19,1.0 21 | pair20,1.0 22 | pair21,1.0 23 | pair22,1.0 24 | pair23,1.0 25 | pair24,1.0 26 | pair25,1.0 27 | pair26,1.0 28 | pair27,1.0 29 | pair28,1.0 30 | pair29,1.0 31 | pair30,1.0 32 | pair31,1.0 33 | pair32,1.0 34 | pair33,1.0 35 | pair34,1.0 36 | pair35,1.0 37 | pair36,1.0 38 | pair37,1.0 39 | pair38,1.0 40 | pair39,1.0 41 | pair40,1.0 42 | pair41,1.0 43 | pair42,1.0 44 | pair43,1.0 45 | pair44,1.0 46 | pair45,1.0 47 | pair46,1.0 48 | pair47,1.0 49 | pair48,1.0 50 | pair49,1.0 51 | pair50,1.0 52 | pair51,1.0 53 | pair52,1.0 54 | pair53,1.0 55 | pair54,1.0 56 | pair55,1.0 57 | pair56,1.0 58 | pair57,1.0 59 | pair58,1.0 60 | pair59,1.0 61 | pair60,1.0 62 | pair61,1.0 63 | pair62,1.0 64 | pair63,1.0 65 | pair64,1.0 66 | pair65,1.0 67 | pair66,1.0 68 | pair67,1.0 69 | pair68,1.0 70 | pair69,1.0 71 | pair70,1.0 72 | pair71,1.0 73 | pair72,1.0 74 | pair73,1.0 75 | pair74,1.0 76 | pair75,1.0 77 | pair76,1.0 78 | pair77,1.0 79 | pair78,1.0 80 | pair79,1.0 81 | pair80,1.0 82 | pair81,1.0 83 | pair82,1.0 84 | pair83,1.0 85 | pair84,1.0 86 | pair85,1.0 87 | pair86,1.0 88 | pair87,1.0 89 | pair88,1.0 90 | pair89,1.0 91 | pair90,1.0 92 | pair91,1.0 93 | pair92,1.0 94 | pair93,1.0 95 | pair94,1.0 96 | pair95,1.0 97 | pair96,1.0 98 | pair97,1.0 99 | pair98,1.0 100 | pair99,1.0 101 | -------------------------------------------------------------------------------- /cdt/utils/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | .. MIT License 3 | .. 4 | .. Copyright (c) 2018 Diviyan Kalainathan 5 | .. 6 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 7 | .. of this software and associated documentation files (the "Software"), to deal 8 | .. in the Software without restriction, including without limitation the rights 9 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | .. copies of the Software, and to permit persons to whom the Software is 11 | .. furnished to do so, subject to the following conditions: 12 | .. 13 | .. The above copyright notice and this permission notice shall be included in all 14 | .. copies or substantial portions of the Software. 15 | .. 16 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | .. SOFTWARE. 23 | """ 24 | from .io import (read_causal_pairs, 25 | read_adjacency_matrix, 26 | read_list_edges) 27 | 28 | from .graph import (remove_indirect_links, 29 | dagify_min_edge, 30 | clr, 31 | aracne, 32 | network_deconvolution) 33 | 34 | from .loss import (TTestCriterion, 35 | notears_constr, 36 | MMDloss, MomentMatchingLoss) 37 | -------------------------------------------------------------------------------- /cdt/utils/R_templates/sid_cpdag.R: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (c) 2018 Diviyan Kalainathan 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. 22 | 23 | library(SID) 24 | library(methods) 25 | 26 | target <- read.csv(file="{target}" , header=FALSE, sep=",") 27 | prediction <- read.csv(file="{prediction}" , header=FALSE, sep=",") 28 | 29 | result <- structIntervDist(target, prediction) 30 | SID_lower_bound <- result$sidLowerBound 31 | SID_upper_bound <- result$sidUpperBound 32 | 33 | write.table(SID_lower_bound, '{result_lower}', row.names=FALSE, col.names=FALSE) 34 | write.table(SID_upper_bound, '{result_upper}', row.names=FALSE, col.names=FALSE) 35 | -------------------------------------------------------------------------------- /tests/datasets/graph_poly_target.csv: -------------------------------------------------------------------------------- 1 | 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 2 | 0.0,0.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 3 | 0.0,0.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0 4 | 0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0 5 | 0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0 6 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 7 | 0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0 8 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0 9 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,0.0 10 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 11 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,1.0,0.0 12 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 13 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0,1.0,0.0,0.0,0.0 14 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 15 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0 16 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0 17 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0,0.0,0.0,0.0 18 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 19 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 20 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 21 | 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0 22 | -------------------------------------------------------------------------------- /cdt/causality/graph/R_templates/bnlearn.R: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (c) 2018 Diviyan Kalainathan 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. 22 | 23 | library(methods) 24 | library(bnlearn) 25 | dataset <- read.csv(file='{FOLDER}{FILE}', sep=","); 26 | whitelist = NULL 27 | blacklist = NULL 28 | 29 | if({E_BLACKL}){ 30 | blacklist <- read.csv(file='{FOLDER}{BLACKLIST}', sep=",") # NULL 31 | } 32 | if({E_WHITEL}){ 33 | whitelist <- read.csv(file='{FOLDER}{WHITELIST}', sep=",") # NULL 34 | } 35 | result <- {ALGORITHM}(dataset, whitelist=whitelist, blacklist=blacklist, alpha={ALPHA}, B={BETA}, test={SCORE}, debug={VERBOSE}); 36 | write.csv(result$arc, row.names=FALSE, file = '{FOLDER}{OUTPUT}'); 37 | -------------------------------------------------------------------------------- /cdt/causality/pairwise/Jarfo_model/train.py: -------------------------------------------------------------------------------- 1 | """ 2 | Cause-effect model training 3 | 4 | """ 5 | 6 | # Author: Jose A. R. Fonollosa 7 | # 8 | # License: Apache, Version 2.0 9 | 10 | import sys 11 | import numpy as np 12 | from .estimator import CauseEffectSystemCombination 13 | # import features as f 14 | import pandas as pd 15 | # from scipy.optimize import fmin 16 | # import _pickle as pickle 17 | from .util import random_permutation 18 | 19 | 20 | MODEL = CauseEffectSystemCombination 21 | MODEL_PARAMS = {'weights': [0.383, 0.370, 0.247], 'njobs': 1} 22 | 23 | 24 | def train(df, tar): 25 | set1 = 'train' if len(sys.argv) < 2 else sys.argv[1] 26 | # set2 = [] if len(sys.argv) < 3 else sys.argv[2:] 27 | train_filter = None 28 | # if len(df) % 2: 29 | # df.drop(df.tail(1).index, inplace=True) 30 | # tar.drop(tar.tail(1).index, inplace=True) 31 | model = MODEL(**MODEL_PARAMS) 32 | print("Reading in training data " + set1) 33 | train = df 34 | print("Extracting features") 35 | train = model.extract(train) 36 | # if save: 37 | # print("Saving train features") 38 | # write_data(set1, train) 39 | # target = data_io.read_target(set1) 40 | 41 | 42 | # Data selection 43 | train, target = random_permutation(train, tar) 44 | train_filter = None 45 | if train_filter is not None: 46 | train = train[train_filter] 47 | target = target[train_filter] 48 | 49 | print("Training model with optimal weights") 50 | # print(train) 51 | # print(tar.values) 52 | X = pd.concat([train]) 53 | y = np.concatenate((tar.values)) 54 | model.fit(X, y) 55 | # if save: 56 | # model_path = "model.pkl" 57 | # print("Saving model", model_path) 58 | # save_model(model, model_path) 59 | return model 60 | -------------------------------------------------------------------------------- /cdt/causality/graph/R_templates/ges.R: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (c) 2018 Diviyan Kalainathan 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. 22 | 23 | library(methods) 24 | library(pcalg) 25 | 26 | dataset <- read.csv(file='{FOLDER}{FILE}', header=FALSE, sep=","); 27 | 28 | if({SKELETON}){ 29 | fixedGaps <- read.csv(file='{FOLDER}{GAPS}', sep=",", header=FALSE) # NULL 30 | fixedGaps = (data.matrix(fixedGaps)) 31 | rownames(fixedGaps) <- colnames(fixedGaps) 32 | }else{ 33 | fixedGaps = NULL 34 | } 35 | score <- new("{SCORE}", data = dataset) 36 | result <- pcalg::ges(score, fixedGaps=fixedGaps) 37 | gesmat <- as(result$essgraph, "matrix") 38 | gesmat[gesmat] <- 1 39 | #gesmat[!gesmat] <- 0 40 | write.csv(gesmat, row.names=FALSE, file = '{FOLDER}{OUTPUT}'); 41 | -------------------------------------------------------------------------------- /cdt/causality/graph/R_templates/gies.R: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # 3 | # Copyright (c) 2018 Diviyan Kalainathan 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. 22 | 23 | library(methods) 24 | library(pcalg) 25 | 26 | dataset <- read.csv(file='{FOLDER}{FILE}', header=FALSE, sep=","); 27 | 28 | if({SKELETON}){ 29 | fixedGaps <- read.csv(file='{FOLDER}{GAPS}', sep=",", header=FALSE) # NULL 30 | fixedGaps = (data.matrix(fixedGaps)) 31 | rownames(fixedGaps) <- colnames(fixedGaps) 32 | }else{ 33 | fixedGaps = NULL 34 | } 35 | score <- new("{SCORE}", data = dataset) 36 | result <- pcalg::gies(score, fixedGaps=fixedGaps) 37 | gesmat <- as(result$essgraph, "matrix") 38 | gesmat[gesmat] <- 1 39 | #gesmat[!gesmat] <- 0 40 | write.csv(gesmat, row.names=FALSE, file = '{FOLDER}{OUTPUT}'); 41 | -------------------------------------------------------------------------------- /cdt/causality/pairwise/Jarfo_model/README.md: -------------------------------------------------------------------------------- 1 | Copyright José A. R. Fonollosa 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | 15 | code version: 2.02 16 | code date: 09-OCT-2013 17 | installation instructions: python 2.7 code. No installation required 18 | required python modules: numpy, pandas, sklearn, scipy 19 | Tested on a Linux machine (Fedora 17) with python 2.7.3 and the following versions of the python libraries 20 | numpy==1.6.2 21 | pandas==0.10.0 22 | scikit-learn==0.13.1 23 | scipy==0.10.1 24 | 25 | TRAINING (Aprox. 45 minutes) 26 | - Download train, SUP1 and SUP2 data from Kaggle (cause-effect competition) 27 | - Edit SETTINGS.json to indicate your data folders 28 | - Train the models: python train.py train train1 train2 29 | 30 | FAST TEST (first 9 entries of the validation data) 31 | - python predict.py CEfinal_valid_pairs_head.csv CEfinal_valid_publicinfo_head.csv CEfinal_valid_predictions_head.csv 32 | Time to process: 10 seconds 33 | Results: (CEfinal_valid_predictions_head.csv rounded to 4 decimals places) 34 | SampleID,Target 35 | valid1, 0.70 36 | valid2, 0.00 37 | valid3, 0.00 38 | valid4, 0.00 39 | valid5, 0.00 40 | valid6,-0.55 41 | valid7,-0.14 42 | valid8, 0.00 43 | valid9,-0.01 44 | 45 | See the data page of the Kaggle cause-effect competition for information about the data 46 | -------------------------------------------------------------------------------- /tests/scripts/graph_generators.py: -------------------------------------------------------------------------------- 1 | """Testing generators.""" 2 | 3 | import networkx as nx 4 | from cdt.generators import AcyclicGraphGenerator, CyclicGraphGenerator 5 | from cdt.generators.causal_mechanisms import normal_noise, uniform_noise, gmm_cause, gaussian_cause 6 | mechanisms = ['linear', 'polynomial', 'sigmoid_add', 7 | 'sigmoid_mix', 'gp_add', 'gp_mix', 'NN'] 8 | import matplotlib.pyplot as plt 9 | import numpy as np 10 | import torch as th 11 | import pandas as pd 12 | 13 | 14 | if __name__ == "__main__": 15 | 16 | 17 | for nb_points in [200,500,1000]: 18 | 19 | for nb_nodes in [20,50,100]: 20 | 21 | for mecanism in mechanisms: 22 | print(nb_points) 23 | print(nb_nodes) 24 | print(mecanism) 25 | 26 | if(mecanism == "linear"): 27 | cause = gaussian_cause 28 | else: 29 | cause = gmm_cause 30 | 31 | agg, data = AcyclicGraphGenerator(mecanism, points=nb_points, nodes=nb_nodes, parents_max=5, initial_variable_generator=cause).generate() 32 | 33 | Adj = nx.to_numpy_matrix(agg) 34 | 35 | 36 | 37 | cpt = 0 38 | for i in range(Adj.shape[0]): 39 | 40 | for j in range(Adj.shape[1]): 41 | 42 | if(Adj[i,j]==1): 43 | cpt+=1 44 | cause = data["V" + str(i)].values 45 | effect = data["V" + str(j)].values 46 | 47 | # if(20 7 | # 8 | # License: Apache, Version 2.0 9 | 10 | import numpy as np 11 | 12 | 13 | # def rbf_dot2(p1, p2, deg): 14 | # if p1.ndim == 1: 15 | # p1 = p1[:, np.newaxis] 16 | # p2 = p2[:, np.newaxis] 17 | # 18 | # size1 = p1.shape 19 | # size2 = p2.shape 20 | # 21 | # G = np.sum(p1 * p1, axis=1)[:, np.newaxis] 22 | # H = np.sum(p2 * p2, axis=1)[:, np.newaxis] 23 | # 24 | # Q = np.tile(G, (1, size2[0])) 25 | # R = np.tile(H.T, (size1[0], 1)) 26 | # 27 | # H = Q + R - 2.0 * np.dot(p1, p2.T) 28 | # 29 | # H = np.exp(-H / 2.0 / (deg ** 2)) 30 | # 31 | # return H 32 | 33 | 34 | def rbf_dot(X, deg): 35 | # Set kernel size to median distance between points, if no kernel specified 36 | if X.ndim == 1: 37 | X = X[:, np.newaxis] 38 | m = X.shape[0] 39 | G = np.sum(X * X, axis=1)[:, np.newaxis] 40 | Q = np.tile(G, (1, m)) 41 | H = Q + Q.T - 2.0 * np.dot(X, X.T) 42 | if deg == -1: 43 | dists = (H - np.tril(H)).flatten() 44 | deg = np.sqrt(0.5 * np.median(dists[dists > 0])) 45 | H = np.exp(-H / 2.0 / (deg ** 2)) 46 | 47 | return H 48 | 49 | 50 | def FastHsicTestGamma(X, Y, sig=[-1, -1], maxpnt=200): 51 | """This function implements the HSIC independence test using a Gamma approximation 52 | to the test threshold 53 | Inputs: 54 | X contains dx columns, m rows. Each row is an i.i.d sample 55 | Y contains dy columns, m rows. Each row is an i.i.d sample 56 | sig[0] is kernel size for x (set to median distance if -1) 57 | sig[1] is kernel size for y (set to median distance if -1) 58 | Outputs: 59 | testStat: test statistic 60 | 61 | Use at most maxpnt points to save time.""" 62 | 63 | m = X.shape[0] 64 | if m > maxpnt: 65 | indx = np.floor(np.r_[0:m:float(m - 1) / (maxpnt - 1)]).astype(int); 66 | # indx = np.r_[0:maxpnt] 67 | Xm = X[indx].astype(float) 68 | Ym = Y[indx].astype(float) 69 | m = Xm.shape[0] 70 | else: 71 | Xm = X.astype(float) 72 | Ym = Y.astype(float) 73 | 74 | H = np.eye(m) - 1.0 / m * np.ones((m, m)) 75 | 76 | K = rbf_dot(Xm, sig[0]); 77 | L = rbf_dot(Ym, sig[1]); 78 | 79 | Kc = np.dot(H, np.dot(K, H)); 80 | Lc = np.dot(H, np.dot(L, H)); 81 | 82 | testStat = (1.0 / m) * (Kc.T * Lc).sum(); 83 | if ~np.isfinite(testStat): 84 | testStat = 0 85 | 86 | return testStat 87 | -------------------------------------------------------------------------------- /cdt/data/__init__.py: -------------------------------------------------------------------------------- 1 | """ This module focusses on data: data generation but also provides the user 2 | with standard and well known datasets, useful for validation and benchmarking. 3 | 4 | The generators provide the user the ability to choose which causal mechanism to 5 | be used in the data generation process, as well as the type of noise 6 | contribution (additive and/or multiplicative). Currently, the implemented 7 | mechanisms are (:math:`+\\times` denotes either addition or multiplication, and 8 | :math:`\\mathbf{X}` denotes the vector of causes, and :math:`E` represents the 9 | noise variable accounting for all unobserved variables): 10 | 11 | - Linear: :math:`y = \\mathbf{X}W +\\times E` 12 | - Polynomial: :math:`y = \\left( W_0 + \\mathbf{X}W_1 + ...+ \\mathbf{X}^d W_d \\right) +\\times E` 13 | - Gaussian Process: :math:`y = GP(\\mathbf{X}) +\\times E` 14 | - Sigmoid: :math:`y = \\sum_i^d W_i * sigmoid(\\mathbf{X_i}) +\\times E` 15 | - Randomly init. Neural network: :math:`y = \\sigma((\\mathbf{X},E) W_{in})W_{out}` 16 | 17 | Causal pairs can be generated using the ``cdt.data.CausalPairGenerator`` class, 18 | and acyclic graphs can be generated using the ``cdt.data.AcyclicGraphGenerator`` class. 19 | 20 | 21 | .. MIT License 22 | .. 23 | .. Copyright (c) 2018 Diviyan Kalainathan 24 | .. 25 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 26 | .. of this software and associated documentation files (the "Software"), to deal 27 | .. in the Software without restriction, including without limitation the rights 28 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 29 | .. copies of the Software, and to permit persons to whom the Software is 30 | .. furnished to do so, subject to the following conditions: 31 | .. 32 | .. The above copyright notice and this permission notice shall be included in all 33 | .. copies or substantial portions of the Software. 34 | .. 35 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 36 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 37 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 38 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 39 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 40 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 41 | .. SOFTWARE. 42 | """ 43 | 44 | from .acyclic_graph_generator import AcyclicGraphGenerator 45 | from .causal_pair_generator import CausalPairGenerator 46 | from .loader import load_dataset 47 | -------------------------------------------------------------------------------- /tests/scripts/test_generators.py: -------------------------------------------------------------------------------- 1 | """Testing generators.""" 2 | 3 | import networkx as nx 4 | from cdt.data import AcyclicGraphGenerator, CausalPairGenerator 5 | from cdt.data.causal_mechanisms import gmm_cause, gaussian_cause 6 | import pandas as pd 7 | import os 8 | 9 | 10 | mechanisms = ['linear', 'polynomial', 'sigmoid_add', 11 | 'sigmoid_mix', 'gp_add', 'gp_mix', 'nn'] 12 | 13 | 14 | def test_acyclic_generators(): 15 | for mechanism in mechanisms: 16 | g = AcyclicGraphGenerator(mechanism, npoints=200, nodes=10, parents_max=3) 17 | data, agg = g.generate() 18 | g.to_csv('test') 19 | # cleanup 20 | os.remove('test_data.csv') 21 | os.remove('test_target.csv') 22 | assert type(agg) == nx.DiGraph 23 | assert nx.is_directed_acyclic_graph(agg) 24 | 25 | 26 | def test_error(): 27 | g = AcyclicGraphGenerator('linear', npoints=200, nodes=10, parents_max=3) 28 | try: 29 | g.to_csv('test') 30 | except ValueError: 31 | pass 32 | 33 | 34 | def test_causal_pairs(): 35 | for mechanism in mechanisms: 36 | data, labels = CausalPairGenerator(mechanism).generate(10, npoints=200) 37 | assert type(data) == pd.DataFrame 38 | 39 | 40 | def test_acyclic_generators_bigg(): 41 | for mechanism in mechanisms: 42 | data, agg = AcyclicGraphGenerator(mechanism, npoints=500, nodes=100, parents_max=6).generate() 43 | assert type(agg) == nx.DiGraph 44 | assert nx.is_directed_acyclic_graph(agg) 45 | 46 | # def test_cyclic_generators(): 47 | # for mechanism in mechanisms: 48 | # cgg, data = CyclicGraphGenerator(mechanism, points=200, nodes=10, parents_max=3).generate(nb_steps=5, averaging=2) 49 | # assert type(cgg) == nx.DiGraph 50 | # assert not nx.is_directed_acyclic_graph(cgg) 51 | 52 | 53 | def test_causes(): 54 | for cause in [gmm_cause, gaussian_cause]: 55 | data, agg = AcyclicGraphGenerator("linear", npoints=200, nodes=10, parents_max=3, initial_variable_generator=cause).generate() 56 | assert type(agg) == nx.DiGraph 57 | assert nx.is_directed_acyclic_graph(agg) 58 | 59 | 60 | def test_noises(): 61 | for noise in ['gaussian', 'uniform']: 62 | data, agg = AcyclicGraphGenerator("linear", npoints=200, nodes=10, parents_max=3, noise=noise).generate() 63 | assert type(agg) == nx.DiGraph 64 | assert nx.is_directed_acyclic_graph(agg) 65 | 66 | 67 | if __name__ == "__main__": 68 | test_acyclic_generators() 69 | test_causal_pairs() 70 | test_causes() 71 | test_noises() 72 | -------------------------------------------------------------------------------- /cdt/data/resources/goldstandard_insilico100_multifactorial_5.csv: -------------------------------------------------------------------------------- 1 | Source,Target 2 | G7,G17 3 | G7,G18 4 | G7,G22 5 | G7,G27 6 | G7,G58 7 | G7,G66 8 | G7,G93 9 | G8,G5 10 | G8,G20 11 | G8,G32 12 | G8,G50 13 | G8,G51 14 | G8,G79 15 | G8,G80 16 | G8,G82 17 | G8,G92 18 | G8,G99 19 | G10,G15 20 | G10,G16 21 | G10,G21 22 | G10,G54 23 | G10,G55 24 | G10,G69 25 | G10,G78 26 | G10,G84 27 | G10,G87 28 | G10,G89 29 | G10,G91 30 | G10,G92 31 | G10,G93 32 | G12,G95 33 | G20,G6 34 | G20,G23 35 | G20,G30 36 | G20,G39 37 | G20,G44 38 | G20,G49 39 | G20,G60 40 | G20,G64 41 | G20,G66 42 | G20,G78 43 | G20,G100 44 | G26,G7 45 | G26,G28 46 | G26,G31 47 | G26,G37 48 | G26,G46 49 | G26,G49 50 | G26,G51 51 | G26,G56 52 | G26,G59 53 | G26,G63 54 | G26,G76 55 | G26,G92 56 | G30,G3 57 | G30,G13 58 | G30,G14 59 | G30,G27 60 | G30,G45 61 | G30,G58 62 | G30,G68 63 | G30,G74 64 | G30,G92 65 | G30,G96 66 | G32,G79 67 | G33,G86 68 | G33,G97 69 | G35,G32 70 | G36,G22 71 | G36,G25 72 | G36,G83 73 | G38,G71 74 | G39,G62 75 | G39,G70 76 | G39,G73 77 | G39,G79 78 | G39,G92 79 | G42,G93 80 | G42,G97 81 | G43,G35 82 | G51,G2 83 | G51,G4 84 | G51,G5 85 | G51,G32 86 | G51,G38 87 | G51,G41 88 | G51,G65 89 | G51,G69 90 | G51,G70 91 | G51,G71 92 | G51,G79 93 | G51,G80 94 | G51,G82 95 | G51,G83 96 | G51,G92 97 | G51,G99 98 | G52,G13 99 | G52,G62 100 | G52,G86 101 | G53,G12 102 | G53,G23 103 | G53,G26 104 | G53,G29 105 | G53,G36 106 | G53,G80 107 | G53,G84 108 | G53,G87 109 | G53,G93 110 | G59,G23 111 | G59,G25 112 | G59,G90 113 | G59,G92 114 | G59,G97 115 | G59,G99 116 | G68,G25 117 | G68,G50 118 | G68,G65 119 | G68,G67 120 | G68,G70 121 | G68,G79 122 | G68,G80 123 | G68,G88 124 | G68,G91 125 | G68,G99 126 | G69,G10 127 | G69,G38 128 | G69,G53 129 | G69,G54 130 | G69,G85 131 | G69,G87 132 | G69,G91 133 | G69,G97 134 | G71,G2 135 | G71,G19 136 | G71,G32 137 | G71,G59 138 | G71,G72 139 | G71,G79 140 | G71,G90 141 | G71,G99 142 | G72,G16 143 | G72,G24 144 | G72,G60 145 | G72,G65 146 | G72,G94 147 | G74,G1 148 | G74,G4 149 | G74,G8 150 | G74,G19 151 | G74,G22 152 | G74,G41 153 | G74,G47 154 | G74,G54 155 | G74,G61 156 | G74,G65 157 | G74,G68 158 | G74,G72 159 | G74,G78 160 | G75,G13 161 | G75,G43 162 | G77,G17 163 | G81,G34 164 | G81,G40 165 | G81,G77 166 | G82,G9 167 | G82,G11 168 | G82,G41 169 | G82,G46 170 | G82,G48 171 | G82,G57 172 | G82,G69 173 | G82,G70 174 | G82,G77 175 | G82,G79 176 | G82,G88 177 | G85,G54 178 | G85,G79 179 | G86,G83 180 | G88,G32 181 | G88,G54 182 | G88,G59 183 | G92,G18 184 | G92,G23 185 | G92,G37 186 | G92,G47 187 | G92,G59 188 | G92,G61 189 | G92,G95 190 | G94,G3 191 | G94,G27 192 | G94,G96 193 | G98,G36 194 | G98,G66 195 | -------------------------------------------------------------------------------- /docs/html/_static/js/html5shiv.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @preserve HTML5 Shiv 3.7.3 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed 3 | */ 4 | !function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=t.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=t.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),t.elements=c+" "+a,j(b)}function f(a){var b=s[a[q]];return b||(b={},r++,a[q]=r,s[r]=b),b}function g(a,c,d){if(c||(c=b),l)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():p.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||o.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),l)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return t.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(t,b.frag)}function j(a){a||(a=b);var d=f(a);return!t.shivCSS||k||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),l||i(a,d),a}var k,l,m="3.7.3-pre",n=a.html5||{},o=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,p=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,q="_html5shiv",r=0,s={};!function(){try{var a=b.createElement("a");a.innerHTML="",k="hidden"in a,l=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){k=!0,l=!0}}();var t={elements:n.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:m,shivCSS:n.shivCSS!==!1,supportsUnknownElements:l,shivMethods:n.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=t,j(b),"object"==typeof module&&module.exports&&(module.exports=t)}("undefined"!=typeof window?window:this,document); -------------------------------------------------------------------------------- /cdt/data/resources/goldstandard_insilico100_multifactorial_3.csv: -------------------------------------------------------------------------------- 1 | Source,Target 2 | G3,G41 3 | G3,G52 4 | G4,G35 5 | G4,G46 6 | G4,G72 7 | G4,G80 8 | G9,G35 9 | G9,G43 10 | G9,G46 11 | G9,G53 12 | G9,G78 13 | G9,G92 14 | G9,G99 15 | G11,G16 16 | G11,G90 17 | G14,G13 18 | G14,G88 19 | G18,G33 20 | G19,G2 21 | G19,G24 22 | G19,G27 23 | G19,G52 24 | G19,G54 25 | G19,G57 26 | G19,G61 27 | G19,G67 28 | G19,G72 29 | G19,G73 30 | G19,G77 31 | G19,G96 32 | G21,G16 33 | G25,G14 34 | G25,G56 35 | G25,G59 36 | G25,G88 37 | G25,G90 38 | G28,G20 39 | G28,G35 40 | G28,G41 41 | G28,G63 42 | G28,G85 43 | G28,G87 44 | G28,G88 45 | G30,G17 46 | G30,G58 47 | G30,G65 48 | G30,G83 49 | G31,G15 50 | G31,G59 51 | G31,G62 52 | G31,G87 53 | G32,G5 54 | G32,G45 55 | G32,G95 56 | G32,G96 57 | G34,G1 58 | G34,G2 59 | G34,G7 60 | G34,G8 61 | G34,G10 62 | G34,G12 63 | G34,G29 64 | G34,G37 65 | G34,G55 66 | G34,G64 67 | G34,G65 68 | G34,G67 69 | G34,G77 70 | G34,G90 71 | G34,G100 72 | G35,G17 73 | G38,G16 74 | G38,G26 75 | G38,G42 76 | G38,G44 77 | G38,G51 78 | G38,G52 79 | G38,G54 80 | G38,G56 81 | G38,G72 82 | G38,G76 83 | G39,G40 84 | G39,G62 85 | G39,G81 86 | G40,G16 87 | G40,G23 88 | G40,G70 89 | G41,G2 90 | G41,G14 91 | G41,G67 92 | G41,G77 93 | G41,G82 94 | G41,G88 95 | G45,G5 96 | G45,G16 97 | G45,G32 98 | G45,G74 99 | G45,G88 100 | G45,G91 101 | G45,G95 102 | G47,G6 103 | G47,G14 104 | G47,G16 105 | G47,G26 106 | G47,G38 107 | G47,G44 108 | G47,G52 109 | G47,G76 110 | G47,G87 111 | G47,G100 112 | G48,G43 113 | G48,G50 114 | G50,G1 115 | G50,G20 116 | G50,G63 117 | G51,G9 118 | G51,G52 119 | G51,G75 120 | G51,G89 121 | G52,G11 122 | G52,G28 123 | G52,G42 124 | G52,G44 125 | G52,G51 126 | G52,G54 127 | G52,G56 128 | G53,G7 129 | G53,G10 130 | G53,G29 131 | G53,G37 132 | G53,G38 133 | G53,G55 134 | G53,G64 135 | G53,G65 136 | G53,G74 137 | G53,G86 138 | G53,G90 139 | G53,G91 140 | G53,G96 141 | G53,G100 142 | G56,G18 143 | G56,G27 144 | G56,G41 145 | G56,G59 146 | G56,G88 147 | G56,G97 148 | G58,G61 149 | G60,G62 150 | G60,G69 151 | G60,G81 152 | G62,G41 153 | G65,G55 154 | G65,G94 155 | G65,G95 156 | G70,G66 157 | G71,G41 158 | G73,G40 159 | G73,G68 160 | G73,G88 161 | G77,G14 162 | G77,G22 163 | G80,G83 164 | G82,G25 165 | G82,G36 166 | G82,G49 167 | G82,G61 168 | G82,G72 169 | G82,G73 170 | G91,G74 171 | G92,G86 172 | G94,G19 173 | G94,G34 174 | G94,G40 175 | G94,G62 176 | G94,G75 177 | G96,G16 178 | G96,G45 179 | G96,G60 180 | G96,G69 181 | G96,G90 182 | G97,G14 183 | G97,G25 184 | G97,G38 185 | G97,G47 186 | G97,G50 187 | G97,G62 188 | G98,G22 189 | G98,G74 190 | G98,G78 191 | G98,G91 192 | G100,G33 193 | G100,G47 194 | G100,G79 195 | G100,G84 196 | G100,G93 197 | -------------------------------------------------------------------------------- /tests/scripts/test_pipeline_CGNN.py: -------------------------------------------------------------------------------- 1 | """Test script for FSGNN, GNN and CGNN.""" 2 | 3 | # Import libraries 4 | from cdt import SETTINGS 5 | from cdt.independence.graph import FSGNN 6 | from cdt.causality.graph import CGNN 7 | # A warning on R libraries might occur. It is for the use of the r libraries that could be imported into the framework 8 | import pandas as pd 9 | import os 10 | import networkx as nx 11 | 12 | SETTINGS.NJOBS = 1 13 | 14 | 15 | def test_pipeline_CGNN(): 16 | data = pd.read_csv('{}/../datasets/NUM_LUCAS.csv'.format(os.path.dirname(os.path.realpath(__file__)))).iloc[:50, :3] 17 | 18 | # Finding the structure of the graph 19 | Fsgnn = FSGNN(train_epochs=5, test_epochs=5, l1=0.006) 20 | 21 | ugraph = Fsgnn.predict(data, threshold=1e-2) 22 | # List results 23 | # print(nx.adj_matrix(ugraph).todense().shape) 24 | # Orient the edges of the graph 25 | 26 | Cgnn = CGNN(nruns=1, train_epochs=2, test_epochs=2) 27 | assert type(Cgnn.predict(data, graph=ugraph)) == nx.DiGraph 28 | return 0 29 | 30 | 31 | def test_multiprocessing_CGNN(): 32 | data = pd.read_csv('{}/../datasets/NUM_LUCAS.csv'.format(os.path.dirname(os.path.realpath(__file__)))).iloc[:50, :3] 33 | 34 | # Finding the structure of the graph 35 | Fsgnn = FSGNN(train_epochs=5, test_epochs=5, l1=0.006, njobs=2) 36 | 37 | ugraph = Fsgnn.predict(data, threshold=1e-2) 38 | # List results 39 | # print(nx.adj_matrix(ugraph).todense().shape) 40 | # Orient the edges of the graph 41 | Cgnn = CGNN(nruns=6, njobs=2, train_epochs=2, test_epochs=2) 42 | assert type(Cgnn.predict(data, graph=ugraph)) == nx.DiGraph 43 | return 0 44 | 45 | 46 | def test_multiprocessing_ete_CGNN(): 47 | data = pd.read_csv('{}/../datasets/NUM_LUCAS.csv'.format(os.path.dirname(os.path.realpath(__file__)))).iloc[:50, :3] 48 | 49 | # Finding the structure of the graph 50 | 51 | # List results 52 | # print(nx.adj_matrix(ugraph).todense().shape) 53 | # Orient the edges of the graph 54 | SETTINGS.GPU = 0 55 | Cgnn = CGNN(nruns=6, njobs=2, train_epochs=2, test_epochs=2) 56 | assert type(Cgnn.predict(data)) == nx.DiGraph 57 | return 0 58 | 59 | 60 | def test_scratch_CGNN(): 61 | data = pd.read_csv('{}/../datasets/NUM_LUCAS.csv'.format(os.path.dirname(os.path.realpath(__file__)))).iloc[:50, :3] 62 | 63 | # Finding the structure of the graph 64 | # List results 65 | # print(nx.adj_matrix(ugraph).todense().shape) 66 | # Orient the edges of the graph 67 | 68 | Cgnn = CGNN(nruns=1, train_epochs=2, test_epochs=2) 69 | assert type(Cgnn.predict(data)) == nx.DiGraph 70 | 71 | return 0 72 | 73 | 74 | if __name__ == '__main__': 75 | # test_pipeline_CGNN() 76 | # test_scratch_CGNN() 77 | # test_multiprocessing_ete_CGNN() 78 | test_multiprocessing_CGNN() 79 | -------------------------------------------------------------------------------- /tests/scripts/test_Jarfo.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | import pandas as pd 4 | import networkx as nx 5 | from cdt.causality.pairwise.Jarfo import Jarfo 6 | from cdt.independence.graph import Glasso 7 | from cdt.utils.io import read_causal_pairs 8 | from cdt import SETTINGS 9 | from cdt.data import load_dataset 10 | 11 | 12 | SETTINGS.NJOBS = 1 13 | 14 | 15 | train_data = read_causal_pairs("{}/../datasets/Example_pairwise_pairs.csv".format(os.path.dirname(os.path.realpath(__file__)))).iloc[:, :50] 16 | 17 | train_target = pd.read_csv("{}/../datasets/Example_pairwise_targets.csv".format(os.path.dirname(os.path.realpath(__file__)))).iloc[:, :50].set_index("SampleID") 18 | 19 | data_pairwise = read_causal_pairs("{}/../datasets/Example_pairwise_pairs.csv".format(os.path.dirname(os.path.realpath(__file__)))).iloc[:5, :50] 20 | 21 | data_graph = pd.read_csv('{}/../datasets/Example_graph_numdata.csv'.format(os.path.dirname(os.path.realpath(__file__)))).iloc[:100, :5] 22 | 23 | train_data = pd.concat([train_data]*5, ignore_index=True) 24 | train_target = pd.concat([train_target]*5, ignore_index=True) 25 | train_target.iloc[10:,:]=0 26 | # print(train_target) 27 | graph_skeleton = Glasso().predict(data_graph) 28 | 29 | 30 | def test_pairwise(): 31 | for method in [Jarfo]: # Jarfo 32 | # print(method) 33 | m = method() 34 | if hasattr(m, "fit"): 35 | # print(train_data) 36 | m.fit(train_data, train_target) 37 | r = m.predict(data_pairwise) 38 | assert r is not None 39 | print(r) 40 | return 0 41 | 42 | 43 | def test_graph(): 44 | for method in [Jarfo]: # Jarfo 45 | print(method) 46 | m = method() 47 | if hasattr(m, "fit"): 48 | m.fit(train_data, train_target) 49 | assert type(m.predict(data_graph, graph_skeleton)) == nx.DiGraph 50 | return 0 51 | 52 | 53 | def test_tuebingen(): 54 | data, labels = load_dataset('tuebingen') 55 | data = data[:30] 56 | labels = labels[:30] 57 | # print(labels) 58 | m = Jarfo() 59 | m.fit(data, labels[['Target']]) 60 | r = m.predict(data) 61 | print(r) 62 | return 0 63 | 64 | 65 | def test_categorical(): 66 | data, labels = load_dataset('tuebingen') 67 | data = data[:10] 68 | for idx in data.index: 69 | data.at[idx, "A"] = np.digitize(data.loc[idx, "A"], 70 | np.histogram(data.loc[idx, "A"])[1]) 71 | data.at[idx, "B"] = np.digitize(data.loc[idx, "B"], 72 | np.histogram(data.loc[idx, "B"])[1]) 73 | labels = labels[:10] 74 | m = Jarfo() 75 | m.fit(data, labels[['Target']]) 76 | r = m.predict(data) 77 | print(r) 78 | return 0 79 | 80 | 81 | 82 | if __name__ == "__main__": 83 | # test_pairwise() 84 | # test_graph() 85 | test_tuebingen() 86 | test_categorical() 87 | -------------------------------------------------------------------------------- /cdt/data/resources/goldstandard_insilico100_multifactorial_4.csv: -------------------------------------------------------------------------------- 1 | Source,Target 2 | G3,G2 3 | G3,G24 4 | G3,G41 5 | G3,G42 6 | G3,G44 7 | G3,G56 8 | G3,G90 9 | G3,G93 10 | G6,G21 11 | G8,G6 12 | G8,G12 13 | G8,G17 14 | G8,G21 15 | G8,G24 16 | G8,G30 17 | G8,G40 18 | G8,G51 19 | G8,G59 20 | G8,G66 21 | G8,G76 22 | G8,G82 23 | G8,G91 24 | G8,G92 25 | G10,G42 26 | G10,G90 27 | G10,G97 28 | G12,G57 29 | G12,G61 30 | G13,G60 31 | G13,G99 32 | G14,G7 33 | G14,G55 34 | G14,G57 35 | G14,G61 36 | G15,G42 37 | G15,G50 38 | G15,G56 39 | G15,G90 40 | G17,G1 41 | G17,G7 42 | G17,G8 43 | G17,G29 44 | G17,G30 45 | G17,G35 46 | G17,G37 47 | G17,G40 48 | G17,G55 49 | G17,G61 50 | G17,G62 51 | G17,G63 52 | G17,G74 53 | G17,G75 54 | G17,G87 55 | G17,G98 56 | G22,G1 57 | G22,G3 58 | G22,G27 59 | G22,G35 60 | G22,G38 61 | G22,G44 62 | G22,G54 63 | G22,G62 64 | G22,G67 65 | G22,G73 66 | G22,G77 67 | G22,G79 68 | G22,G89 69 | G24,G1 70 | G24,G7 71 | G24,G19 72 | G24,G33 73 | G24,G34 74 | G24,G55 75 | G24,G61 76 | G24,G66 77 | G24,G68 78 | G24,G83 79 | G25,G54 80 | G28,G1 81 | G28,G7 82 | G28,G18 83 | G31,G9 84 | G31,G55 85 | G31,G62 86 | G31,G66 87 | G33,G64 88 | G34,G17 89 | G34,G18 90 | G34,G33 91 | G34,G60 92 | G34,G66 93 | G34,G71 94 | G34,G83 95 | G34,G88 96 | G36,G15 97 | G36,G27 98 | G36,G40 99 | G36,G43 100 | G36,G48 101 | G36,G80 102 | G37,G42 103 | G37,G44 104 | G37,G50 105 | G37,G56 106 | G37,G62 107 | G37,G75 108 | G37,G87 109 | G37,G90 110 | G38,G3 111 | G38,G8 112 | G38,G16 113 | G38,G22 114 | G38,G25 115 | G38,G39 116 | G38,G44 117 | G38,G50 118 | G38,G54 119 | G38,G62 120 | G38,G69 121 | G38,G83 122 | G38,G86 123 | G39,G26 124 | G39,G84 125 | G40,G13 126 | G40,G37 127 | G40,G62 128 | G40,G66 129 | G40,G74 130 | G40,G81 131 | G45,G4 132 | G45,G42 133 | G45,G56 134 | G47,G9 135 | G47,G19 136 | G47,G68 137 | G47,G83 138 | G47,G99 139 | G52,G3 140 | G52,G36 141 | G52,G78 142 | G52,G95 143 | G53,G25 144 | G53,G38 145 | G54,G26 146 | G55,G80 147 | G56,G42 148 | G56,G58 149 | G56,G97 150 | G58,G5 151 | G58,G23 152 | G58,G36 153 | G58,G48 154 | G58,G62 155 | G58,G72 156 | G58,G73 157 | G58,G79 158 | G58,G84 159 | G58,G85 160 | G58,G96 161 | G58,G99 162 | G63,G20 163 | G63,G32 164 | G63,G44 165 | G63,G49 166 | G63,G52 167 | G63,G62 168 | G63,G67 169 | G63,G89 170 | G63,G98 171 | G64,G22 172 | G64,G28 173 | G64,G91 174 | G65,G62 175 | G65,G99 176 | G66,G71 177 | G70,G55 178 | G70,G57 179 | G70,G84 180 | G70,G89 181 | G72,G5 182 | G72,G23 183 | G72,G44 184 | G72,G46 185 | G72,G58 186 | G72,G73 187 | G72,G84 188 | G72,G96 189 | G75,G29 190 | G75,G37 191 | G75,G40 192 | G75,G50 193 | G75,G60 194 | G75,G87 195 | G75,G90 196 | G78,G3 197 | G78,G36 198 | G78,G77 199 | G78,G95 200 | G81,G2 201 | G81,G18 202 | G81,G92 203 | G94,G60 204 | G94,G62 205 | G94,G81 206 | G99,G9 207 | G99,G25 208 | G99,G38 209 | G100,G10 210 | G100,G11 211 | G100,G46 212 | G100,G66 213 | -------------------------------------------------------------------------------- /cdt/independence/stats/model.py: -------------------------------------------------------------------------------- 1 | """Base class for dependence models. 2 | 3 | Author: Diviyan Kalainathan 4 | 5 | .. MIT License 6 | .. 7 | .. Copyright (c) 2018 Diviyan Kalainathan 8 | .. 9 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 10 | .. of this software and associated documentation files (the "Software"), to deal 11 | .. in the Software without restriction, including without limitation the rights 12 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | .. copies of the Software, and to permit persons to whom the Software is 14 | .. furnished to do so, subject to the following conditions: 15 | .. 16 | .. The above copyright notice and this permission notice shall be included in all 17 | .. copies or substantial portions of the Software. 18 | .. 19 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | .. SOFTWARE. 26 | """ 27 | from networkx import Graph 28 | 29 | 30 | class IndependenceModel(object): 31 | """Base class for independence and utilities to recover the 32 | undirected graph out of data. 33 | 34 | Args: 35 | predictor (function): function to estimate dependence (0 : independence), taking as input 2 array-like variables. 36 | 37 | """ 38 | 39 | def __init__(self, predictor=None): 40 | """Init the model.""" 41 | super(IndependenceModel, self).__init__() 42 | if predictor is not None: 43 | self.predict = predictor 44 | 45 | def predict(self, a, b): 46 | """Compute a dependence test statistic between variables. 47 | 48 | Args: 49 | a (numpy.ndarray): First variable 50 | b (numpy.ndarray): Second variable 51 | 52 | Returns: 53 | float: dependence test statistic (close to 0 -> independent) 54 | """ 55 | raise NotImplementedError 56 | 57 | def predict_undirected_graph(self, data): 58 | """Build a skeleton using a pairwise independence criterion. 59 | 60 | Args: 61 | data (pandas.DataFrame): Raw data table 62 | 63 | Returns: 64 | networkx.Graph: Undirected graph representing the skeleton. 65 | """ 66 | graph = Graph() 67 | for idx_i, i in enumerate(data.columns): 68 | for idx_j, j in enumerate(data.columns[idx_i+1:]): 69 | score = self.predict(data[i].values, data[j].values) 70 | if abs(score) > 0.001: 71 | graph.add_edge(i, j, weight=score) 72 | 73 | return graph 74 | -------------------------------------------------------------------------------- /docs/html/_static/css/badge_only.css: -------------------------------------------------------------------------------- 1 | .fa:before{-webkit-font-smoothing:antialiased}.clearfix{*zoom:1}.clearfix:after,.clearfix:before{display:table;content:""}.clearfix:after{clear:both}@font-face{font-family:FontAwesome;font-style:normal;font-weight:400;src:url(fonts/fontawesome-webfont.eot?674f50d287a8c48dc19ba404d20fe713?#iefix) format("embedded-opentype"),url(fonts/fontawesome-webfont.woff2?af7ae505a9eed503f8b8e6982036873e) format("woff2"),url(fonts/fontawesome-webfont.woff?fee66e712a8a08eef5805a46892932ad) format("woff"),url(fonts/fontawesome-webfont.ttf?b06871f281fee6b241d60582ae9369b9) format("truetype"),url(fonts/fontawesome-webfont.svg?912ec66d7572ff821749319396470bde#FontAwesome) format("svg")}.fa:before{font-family:FontAwesome;font-style:normal;font-weight:400;line-height:1}.fa:before,a .fa{text-decoration:inherit}.fa:before,a .fa,li .fa{display:inline-block}li .fa-large:before{width:1.875em}ul.fas{list-style-type:none;margin-left:2em;text-indent:-.8em}ul.fas li .fa{width:.8em}ul.fas li .fa-large:before{vertical-align:baseline}.fa-book:before,.icon-book:before{content:"\f02d"}.fa-caret-down:before,.icon-caret-down:before{content:"\f0d7"}.fa-caret-up:before,.icon-caret-up:before{content:"\f0d8"}.fa-caret-left:before,.icon-caret-left:before{content:"\f0d9"}.fa-caret-right:before,.icon-caret-right:before{content:"\f0da"}.rst-versions{position:fixed;bottom:0;left:0;width:300px;color:#fcfcfc;background:#1f1d1d;font-family:Lato,proxima-nova,Helvetica Neue,Arial,sans-serif;z-index:400}.rst-versions a{color:#2980b9;text-decoration:none}.rst-versions .rst-badge-small{display:none}.rst-versions .rst-current-version{padding:12px;background-color:#272525;display:block;text-align:right;font-size:90%;cursor:pointer;color:#27ae60}.rst-versions .rst-current-version:after{clear:both;content:"";display:block}.rst-versions .rst-current-version .fa{color:#fcfcfc}.rst-versions .rst-current-version .fa-book,.rst-versions .rst-current-version .icon-book{float:left}.rst-versions .rst-current-version.rst-out-of-date{background-color:#e74c3c;color:#fff}.rst-versions .rst-current-version.rst-active-old-version{background-color:#f1c40f;color:#000}.rst-versions.shift-up{height:auto;max-height:100%;overflow-y:scroll}.rst-versions.shift-up .rst-other-versions{display:block}.rst-versions .rst-other-versions{font-size:90%;padding:12px;color:grey;display:none}.rst-versions .rst-other-versions hr{display:block;height:1px;border:0;margin:20px 0;padding:0;border-top:1px solid #413d3d}.rst-versions .rst-other-versions dd{display:inline-block;margin:0}.rst-versions .rst-other-versions dd a{display:inline-block;padding:6px;color:#fcfcfc}.rst-versions.rst-badge{width:auto;bottom:20px;right:20px;left:auto;border:none;max-width:300px;max-height:90%}.rst-versions.rst-badge .fa-book,.rst-versions.rst-badge .icon-book{float:none;line-height:30px}.rst-versions.rst-badge.shift-up .rst-current-version{text-align:right}.rst-versions.rst-badge.shift-up .rst-current-version .fa-book,.rst-versions.rst-badge.shift-up .rst-current-version .icon-book{float:left}.rst-versions.rst-badge>.rst-current-version{width:auto;height:30px;line-height:30px;padding:0 6px;display:block;text-align:center}@media screen and (max-width:768px){.rst-versions{width:85%;display:none}.rst-versions.shift{display:block}} -------------------------------------------------------------------------------- /tests/scripts/test_causality_pairwise.py: -------------------------------------------------------------------------------- 1 | """Test pairwise causal Discovery models.""" 2 | 3 | import os 4 | import pandas as pd 5 | import networkx as nx 6 | from cdt.causality.pairwise import (ANM, IGCI, BivariateFit, CDS, 7 | NCC, RCC, RECI, GNN) 8 | from cdt.independence.graph import Glasso 9 | from cdt.utils.io import read_causal_pairs 10 | from cdt import SETTINGS 11 | from cdt.data import load_dataset 12 | 13 | SETTINGS.NJOBS = 1 14 | 15 | 16 | train_data = read_causal_pairs("{}/../datasets/Example_pairwise_pairs.csv".format(os.path.dirname(os.path.realpath(__file__)))).iloc[:, :50] 17 | 18 | train_target = pd.read_csv("{}/../datasets/Example_pairwise_targets.csv".format(os.path.dirname(os.path.realpath(__file__)))).iloc[:, :50].set_index("SampleID") 19 | 20 | data_pairwise = read_causal_pairs("{}/../datasets/Example_pairwise_pairs.csv".format(os.path.dirname(os.path.realpath(__file__)))).iloc[0, :50] 21 | 22 | data_graph = pd.read_csv('{}/../datasets/Example_graph_numdata.csv'.format(os.path.dirname(os.path.realpath(__file__)))).iloc[:50, :5] 23 | 24 | graph_skeleton = Glasso().predict(data_graph) 25 | tueb, labels = load_dataset('tuebingen') 26 | tueb, labels = tueb[:10], labels[:10] 27 | 28 | 29 | def test_pairwise(): 30 | for method in [ANM, IGCI, BivariateFit, CDS, RCC, NCC, RECI]: # Jarfo 31 | print(method) 32 | m = method() 33 | if hasattr(m, "fit"): 34 | m.fit(train_data, train_target) 35 | r = m.predict(data_pairwise) 36 | assert r is not None 37 | print(r) 38 | return 0 39 | 40 | 41 | def test_pairwise(): 42 | for method in [ANM, IGCI, BivariateFit, CDS, RCC, NCC, RECI]: # Jarfo 43 | print(method) 44 | m = method() 45 | if hasattr(m, "fit"): 46 | m.fit(train_data, train_target) 47 | r = m.predict_dataset(tueb) 48 | assert r is not None 49 | print(r) 50 | return 0 51 | 52 | 53 | def test_pairwise_GNN(): 54 | method = GNN 55 | print(method) 56 | m = method(train_epochs=10, test_epochs=10, nruns=1) 57 | r = m.predict(data_pairwise) 58 | assert r is not None 59 | print(r) 60 | return 0 61 | 62 | 63 | def test_graph_GNN(): 64 | method = GNN 65 | print(method) 66 | m = method(train_epochs=10, test_epochs=10, nruns=2) 67 | assert type(m.predict(data_graph, graph_skeleton)) == nx.DiGraph 68 | return 0 69 | 70 | 71 | def test_graph(): 72 | for method in [ANM, IGCI, BivariateFit, CDS, RCC, RECI, NCC]: # Jarfo 73 | print(method) 74 | m = method() 75 | if hasattr(m, "fit"): 76 | m.fit(train_data, train_target) 77 | assert type(m.predict(data_graph, graph_skeleton)) == nx.DiGraph 78 | return 0 79 | 80 | 81 | def test_pairwise_t(): 82 | for method in [NCC]: # Jarfo 83 | print(method) 84 | m = method() 85 | if hasattr(m, "fit"): 86 | m.fit(tueb, labels) 87 | r = m.predict(data_pairwise) 88 | assert r is not None 89 | print(r) 90 | return 0 91 | 92 | if __name__ == "__main__": 93 | test_pairwise() 94 | test_graph() 95 | test_pairwise_GNN() 96 | test_graph_GNN() 97 | test_pairwise_t() 98 | -------------------------------------------------------------------------------- /docs/causality.rst: -------------------------------------------------------------------------------- 1 | .. role:: hidden 2 | :class: hidden-section 3 | 4 | cdt.causality 5 | ============= 6 | 7 | cdt.causality.pairwise 8 | ---------------------- 9 | .. automodule:: cdt.causality.pairwise 10 | .. currentmodule:: cdt.causality.pairwise.model 11 | .. autoclass:: PairwiseModel 12 | :members: 13 | 14 | .. currentmodule:: cdt.causality.pairwise 15 | 16 | :hidden:`ANM` 17 | ~~~~~~~~~~~~~~ 18 | 19 | .. autoclass:: ANM 20 | :members: 21 | 22 | :hidden:`Bivariate Fit` 23 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 24 | 25 | .. autoclass:: BivariateFit 26 | :members: 27 | 28 | :hidden:`CDS` 29 | ~~~~~~~~~~~~~~ 30 | 31 | .. autoclass:: CDS 32 | :members: 33 | 34 | :hidden:`GNN` 35 | ~~~~~~~~~~~~~~ 36 | 37 | .. autoclass:: GNN 38 | :members: 39 | 40 | :hidden:`IGCI` 41 | ~~~~~~~~~~~~~~ 42 | 43 | .. autoclass:: IGCI 44 | :members: 45 | 46 | :hidden:`Jarfo` 47 | ~~~~~~~~~~~~~~~ 48 | 49 | .. autoclass:: Jarfo 50 | :members: 51 | 52 | :hidden:`NCC` 53 | ~~~~~~~~~~~~~~ 54 | 55 | .. autoclass:: NCC 56 | :members: 57 | 58 | :hidden:`RCC` 59 | ~~~~~~~~~~~~~~ 60 | 61 | .. autoclass:: RCC 62 | :members: 63 | 64 | :hidden:`RECI` 65 | ~~~~~~~~~~~~~~ 66 | 67 | .. autoclass:: RECI 68 | :members: 69 | 70 | 71 | cdt.causality.graph 72 | ------------------- 73 | 74 | .. automodule:: cdt.causality.graph 75 | .. currentmodule:: cdt.causality.graph.model 76 | .. autoclass:: GraphModel 77 | :members: 78 | 79 | :hidden:`bnlearn-based models` 80 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 81 | .. currentmodule:: cdt.causality.graph.bnlearn 82 | .. autoclass:: BNlearnAlgorithm 83 | :members: 84 | 85 | :hidden:`GS` 86 | ^^^^^^^^^^^^ 87 | 88 | .. autoclass:: GS 89 | :members: 90 | 91 | :hidden:`IAMB` 92 | ^^^^^^^^^^^^^^^ 93 | 94 | .. autoclass:: IAMB 95 | :members: 96 | 97 | :hidden:`Fast_IAMB` 98 | ^^^^^^^^^^^^^^^^^^^^^ 99 | 100 | .. autoclass:: Fast_IAMB 101 | :members: 102 | 103 | :hidden:`Inter_IAMB` 104 | ^^^^^^^^^^^^^^^^^^^^^ 105 | 106 | .. autoclass:: Inter_IAMB 107 | :members: 108 | 109 | :hidden:`MMPC` 110 | ^^^^^^^^^^^^^^^ 111 | 112 | .. autoclass:: MMPC 113 | :members: 114 | 115 | .. currentmodule:: cdt.causality.graph 116 | 117 | :hidden:`CAM` 118 | ~~~~~~~~~~~~~~ 119 | 120 | .. autoclass:: CAM 121 | :members: create_graph_from_data 122 | 123 | :hidden:`CCDr` 124 | ~~~~~~~~~~~~~~ 125 | 126 | .. autoclass:: CCDr 127 | :members: create_graph_from_data 128 | 129 | :hidden:`CGNN` 130 | ~~~~~~~~~~~~~~~~ 131 | 132 | .. autoclass:: CGNN 133 | :members: 134 | 135 | :hidden:`GES` 136 | ~~~~~~~~~~~~~ 137 | 138 | .. autoclass:: GES 139 | :members: 140 | 141 | :hidden:`GIES` 142 | ~~~~~~~~~~~~~~~~ 143 | 144 | .. autoclass:: GIES 145 | :members: 146 | 147 | 148 | :hidden:`LiNGAM` 149 | ~~~~~~~~~~~~~~~~ 150 | 151 | .. autoclass:: LiNGAM 152 | :members: create_graph_from_data 153 | 154 | :hidden:`PC` 155 | ~~~~~~~~~~~~~~ 156 | 157 | .. autoclass:: PC 158 | :members: 159 | 160 | :hidden:`SAM` 161 | ~~~~~~~~~~~~~~~ 162 | 163 | .. autoclass:: SAM 164 | :members: predict 165 | 166 | :hidden:`SAMv1` 167 | ~~~~~~~~~~~~~~~ 168 | 169 | .. autoclass:: SAMv1 170 | :members: predict 171 | -------------------------------------------------------------------------------- /docs/html/_sources/causality.rst.txt: -------------------------------------------------------------------------------- 1 | .. role:: hidden 2 | :class: hidden-section 3 | 4 | cdt.causality 5 | ============= 6 | 7 | cdt.causality.pairwise 8 | ---------------------- 9 | .. automodule:: cdt.causality.pairwise 10 | .. currentmodule:: cdt.causality.pairwise.model 11 | .. autoclass:: PairwiseModel 12 | :members: 13 | 14 | .. currentmodule:: cdt.causality.pairwise 15 | 16 | :hidden:`ANM` 17 | ~~~~~~~~~~~~~~ 18 | 19 | .. autoclass:: ANM 20 | :members: 21 | 22 | :hidden:`Bivariate Fit` 23 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 24 | 25 | .. autoclass:: BivariateFit 26 | :members: 27 | 28 | :hidden:`CDS` 29 | ~~~~~~~~~~~~~~ 30 | 31 | .. autoclass:: CDS 32 | :members: 33 | 34 | :hidden:`GNN` 35 | ~~~~~~~~~~~~~~ 36 | 37 | .. autoclass:: GNN 38 | :members: 39 | 40 | :hidden:`IGCI` 41 | ~~~~~~~~~~~~~~ 42 | 43 | .. autoclass:: IGCI 44 | :members: 45 | 46 | :hidden:`Jarfo` 47 | ~~~~~~~~~~~~~~~ 48 | 49 | .. autoclass:: Jarfo 50 | :members: 51 | 52 | :hidden:`NCC` 53 | ~~~~~~~~~~~~~~ 54 | 55 | .. autoclass:: NCC 56 | :members: 57 | 58 | :hidden:`RCC` 59 | ~~~~~~~~~~~~~~ 60 | 61 | .. autoclass:: RCC 62 | :members: 63 | 64 | :hidden:`RECI` 65 | ~~~~~~~~~~~~~~ 66 | 67 | .. autoclass:: RECI 68 | :members: 69 | 70 | 71 | cdt.causality.graph 72 | ------------------- 73 | 74 | .. automodule:: cdt.causality.graph 75 | .. currentmodule:: cdt.causality.graph.model 76 | .. autoclass:: GraphModel 77 | :members: 78 | 79 | :hidden:`bnlearn-based models` 80 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 81 | .. currentmodule:: cdt.causality.graph.bnlearn 82 | .. autoclass:: BNlearnAlgorithm 83 | :members: 84 | 85 | :hidden:`GS` 86 | ^^^^^^^^^^^^ 87 | 88 | .. autoclass:: GS 89 | :members: 90 | 91 | :hidden:`IAMB` 92 | ^^^^^^^^^^^^^^^ 93 | 94 | .. autoclass:: IAMB 95 | :members: 96 | 97 | :hidden:`Fast_IAMB` 98 | ^^^^^^^^^^^^^^^^^^^^^ 99 | 100 | .. autoclass:: Fast_IAMB 101 | :members: 102 | 103 | :hidden:`Inter_IAMB` 104 | ^^^^^^^^^^^^^^^^^^^^^ 105 | 106 | .. autoclass:: Inter_IAMB 107 | :members: 108 | 109 | :hidden:`MMPC` 110 | ^^^^^^^^^^^^^^^ 111 | 112 | .. autoclass:: MMPC 113 | :members: 114 | 115 | .. currentmodule:: cdt.causality.graph 116 | 117 | :hidden:`CAM` 118 | ~~~~~~~~~~~~~~ 119 | 120 | .. autoclass:: CAM 121 | :members: create_graph_from_data 122 | 123 | :hidden:`CCDr` 124 | ~~~~~~~~~~~~~~ 125 | 126 | .. autoclass:: CCDr 127 | :members: create_graph_from_data 128 | 129 | :hidden:`CGNN` 130 | ~~~~~~~~~~~~~~~~ 131 | 132 | .. autoclass:: CGNN 133 | :members: 134 | 135 | :hidden:`GES` 136 | ~~~~~~~~~~~~~ 137 | 138 | .. autoclass:: GES 139 | :members: 140 | 141 | :hidden:`GIES` 142 | ~~~~~~~~~~~~~~~~ 143 | 144 | .. autoclass:: GIES 145 | :members: 146 | 147 | 148 | :hidden:`LiNGAM` 149 | ~~~~~~~~~~~~~~~~ 150 | 151 | .. autoclass:: LiNGAM 152 | :members: create_graph_from_data 153 | 154 | :hidden:`PC` 155 | ~~~~~~~~~~~~~~ 156 | 157 | .. autoclass:: PC 158 | :members: 159 | 160 | :hidden:`SAM` 161 | ~~~~~~~~~~~~~~~ 162 | 163 | .. autoclass:: SAM 164 | :members: predict 165 | 166 | :hidden:`SAMv1` 167 | ~~~~~~~~~~~~~~~ 168 | 169 | .. autoclass:: SAMv1 170 | :members: predict 171 | -------------------------------------------------------------------------------- /cdt/data/resources/goldstandard_insilico100_multifactorial_2.csv: -------------------------------------------------------------------------------- 1 | Source,Target 2 | G1,G13 3 | G1,G96 4 | G5,G39 5 | G6,G2 6 | G6,G3 7 | G6,G4 8 | G6,G5 9 | G6,G14 10 | G6,G15 11 | G6,G17 12 | G6,G20 13 | G6,G21 14 | G6,G25 15 | G6,G27 16 | G6,G39 17 | G6,G44 18 | G6,G46 19 | G6,G49 20 | G6,G53 21 | G6,G54 22 | G6,G56 23 | G6,G58 24 | G6,G61 25 | G6,G62 26 | G6,G64 27 | G6,G66 28 | G6,G68 29 | G6,G72 30 | G6,G73 31 | G6,G75 32 | G6,G78 33 | G6,G82 34 | G6,G86 35 | G6,G87 36 | G6,G89 37 | G6,G90 38 | G6,G91 39 | G6,G92 40 | G6,G93 41 | G6,G97 42 | G6,G98 43 | G10,G7 44 | G10,G9 45 | G10,G12 46 | G10,G17 47 | G10,G23 48 | G10,G29 49 | G10,G33 50 | G10,G36 51 | G10,G38 52 | G10,G43 53 | G10,G45 54 | G10,G47 55 | G10,G54 56 | G10,G55 57 | G10,G69 58 | G10,G77 59 | G10,G80 60 | G10,G81 61 | G10,G82 62 | G10,G83 63 | G10,G92 64 | G10,G95 65 | G11,G28 66 | G11,G31 67 | G13,G8 68 | G13,G9 69 | G13,G23 70 | G13,G55 71 | G13,G83 72 | G13,G96 73 | G13,G100 74 | G14,G98 75 | G16,G9 76 | G16,G23 77 | G21,G12 78 | G21,G26 79 | G21,G74 80 | G23,G9 81 | G23,G10 82 | G23,G13 83 | G23,G96 84 | G26,G71 85 | G26,G74 86 | G30,G42 87 | G30,G51 88 | G33,G7 89 | G33,G80 90 | G34,G49 91 | G34,G89 92 | G37,G10 93 | G38,G22 94 | G38,G81 95 | G39,G5 96 | G40,G3 97 | G40,G4 98 | G40,G8 99 | G40,G9 100 | G40,G11 101 | G40,G17 102 | G40,G22 103 | G40,G23 104 | G40,G25 105 | G40,G27 106 | G40,G28 107 | G40,G29 108 | G40,G31 109 | G40,G41 110 | G40,G49 111 | G40,G50 112 | G40,G52 113 | G40,G53 114 | G40,G54 115 | G40,G55 116 | G40,G59 117 | G40,G60 118 | G40,G61 119 | G40,G63 120 | G40,G64 121 | G40,G66 122 | G40,G69 123 | G40,G73 124 | G40,G76 125 | G40,G78 126 | G40,G79 127 | G40,G85 128 | G40,G87 129 | G40,G88 130 | G40,G89 131 | G40,G90 132 | G40,G91 133 | G49,G89 134 | G51,G26 135 | G51,G74 136 | G52,G2 137 | G52,G8 138 | G52,G9 139 | G52,G19 140 | G52,G23 141 | G52,G25 142 | G52,G35 143 | G52,G40 144 | G52,G42 145 | G52,G48 146 | G52,G60 147 | G52,G61 148 | G52,G64 149 | G52,G67 150 | G52,G73 151 | G52,G75 152 | G52,G85 153 | G52,G87 154 | G52,G88 155 | G55,G9 156 | G55,G13 157 | G55,G23 158 | G55,G96 159 | G57,G18 160 | G63,G11 161 | G63,G17 162 | G63,G25 163 | G63,G27 164 | G63,G28 165 | G63,G31 166 | G63,G54 167 | G63,G61 168 | G63,G64 169 | G63,G69 170 | G63,G73 171 | G63,G78 172 | G63,G79 173 | G65,G45 174 | G69,G41 175 | G70,G26 176 | G70,G32 177 | G70,G44 178 | G70,G74 179 | G70,G83 180 | G70,G97 181 | G76,G8 182 | G76,G88 183 | G80,G7 184 | G80,G33 185 | G83,G26 186 | G83,G32 187 | G83,G44 188 | G83,G74 189 | G83,G97 190 | G84,G23 191 | G84,G42 192 | G84,G55 193 | G86,G2 194 | G86,G3 195 | G86,G4 196 | G86,G5 197 | G86,G6 198 | G86,G14 199 | G86,G15 200 | G86,G17 201 | G86,G20 202 | G86,G21 203 | G86,G25 204 | G86,G27 205 | G86,G39 206 | G86,G44 207 | G86,G46 208 | G86,G49 209 | G86,G53 210 | G86,G54 211 | G86,G56 212 | G86,G58 213 | G86,G61 214 | G86,G62 215 | G86,G64 216 | G86,G66 217 | G86,G68 218 | G86,G72 219 | G86,G73 220 | G86,G75 221 | G86,G78 222 | G86,G82 223 | G86,G87 224 | G86,G89 225 | G86,G90 226 | G86,G91 227 | G86,G92 228 | G86,G93 229 | G86,G97 230 | G86,G98 231 | G91,G20 232 | G91,G59 233 | G94,G1 234 | G94,G13 235 | G94,G50 236 | G94,G96 237 | G99,G24 238 | G99,G26 239 | G99,G71 240 | G99,G74 241 | G100,G18 242 | G100,G36 243 | G100,G43 244 | G100,G56 245 | G100,G66 246 | G100,G67 247 | G100,G77 248 | G100,G92 249 | G100,G93 250 | G100,G95 251 | -------------------------------------------------------------------------------- /installation_instructions.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | The packages requires a python version >=3.5, as well as some libraries listed in [requirements file](requirements.txt). For some additional functionalities, more libraries are needed for these extra functions and options to become available. Here is a quick installation guide for the package, starting off with the minimal install up to the full installation. 4 | 5 | **Note**: A (mini/ana)conda framework would help installing all those packages and therefore could be recommended for non-expert users. 6 | 7 | ## Miniconda installation [optional] 8 | As miniconda is lighter and has most of the interesting functionalities of anaconda, we would recommend using Miniconda. 9 | 1. Go to https://conda.io/miniconda.html and download the latest version of the software in 64bits. The python version here (2.7 or 3.6) does not make any importance at this stage. 10 | 2. Go to your downloaded folder and execute the installation script. For linux users, in a terminal: 11 | ``` 12 | $ bash Miniconda-X.sh 13 | ``` 14 | 3. Start off by creating your first environment named _'py35'_: open a (new, or refresh the .bashrc) terminal and type: 15 | ``` 16 | $ conda create --name py35 python=3.5 17 | ``` 18 | 4. Activate your new environment by using the command: 19 | ``` 20 | $ source activate py35 21 | ``` 22 | **Note**: Keep your environment activated in order to install all your libraries in your environment. 23 | 24 | ## Python 3.5 or higher 25 | If you installed a Miniconda framework at the last step, you already installed python3.5 in an environment, and therefore you can skip this step. 26 | 27 | To check if python 3.5 is installed on your device, execute the command: 28 | ``` 29 | $ python --version 30 | ``` 31 | If not, you can install it with the command (Debian distribution): 32 | ``` 33 | $ sudo apt-get install python3 python3-pip python3-wheel 34 | ``` 35 | ## Install PyTorch 36 | As some of the key algorithms in the _cdt_ package use the PyTorch package, it is required to install it. 37 | Check out their website to install the PyTorch version suited to your hardware configuration: http://pytorch.org 38 | 39 | ## Install the CausalDiscoveryToolboxPackage 40 | ```sh 41 | $ git clone https://github.com/FenTechSolutions/CausalDiscoveryToolbox.git # Download the package 42 | $ cd CausalDiscoveryToolbox 43 | $ pip install -r requirements.txt # Install the requirements 44 | $ python setup.py install develop --user 45 | ``` 46 | **The package is then up and running ! You can run most of the algorithms in the CausalDiscoveryToolbox, you might get warnings: some additional features are not available** 47 | 48 | From now on, you can import the library using : 49 | ```python 50 | import cdt 51 | ``` 52 | Check out the package structure and more info on the package itself [here](https://github.com/FenTechSolutions/CausalDiscoveryToolbox/blob/master/documentation.md). 53 | 54 | ## Additional : R and R libraries 55 | In order to have access to additional algorithms from various R packages such as bnlearn, kpcalg, pcalg, ... while using the _cdt_ framework, it is required to install R. 56 | 57 | Using bioconductor (https://www.bioconductor.org/) might be an easier alternative to install all packages. 58 | Check out the [r-requirements file](https://github.com/FenTechSolutions/CausalDiscoveryToolbox/blob/master/r_requirements.txt) to see all the packages used by the toolbox. 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /cdt/causality/graph/model.py: -------------------------------------------------------------------------------- 1 | """Graph causal models base class. 2 | 3 | Author: Diviyan Kalainathan 4 | Date : 7/06/2017 5 | 6 | .. MIT License 7 | .. 8 | .. Copyright (c) 2018 Diviyan Kalainathan 9 | .. 10 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 11 | .. of this software and associated documentation files (the "Software"), to deal 12 | .. in the Software without restriction, including without limitation the rights 13 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | .. copies of the Software, and to permit persons to whom the Software is 15 | .. furnished to do so, subject to the following conditions: 16 | .. 17 | .. The above copyright notice and this permission notice shall be included in all 18 | .. copies or substantial portions of the Software. 19 | .. 20 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | .. SOFTWARE. 27 | """ 28 | import networkx as nx 29 | 30 | 31 | class GraphModel(object): 32 | """Base class for all graph causal inference models. 33 | 34 | Usage for undirected/directed graphs and raw data. All causal discovery 35 | models out of observational data base themselves on this class. Its main 36 | feature is the predict function that executes a function according to the 37 | given arguments. 38 | """ 39 | 40 | def __init__(self): 41 | """Init.""" 42 | super(GraphModel, self).__init__() 43 | 44 | def predict(self, df_data, graph=None, **kwargs): 45 | """Orient a graph using the method defined by the arguments. 46 | 47 | Depending on the type of `graph`, this function process to execute 48 | different functions: 49 | 50 | 1. If ``graph`` is a ``networkx.DiGraph``, then ``self.orient_directed_graph`` is executed. 51 | 2. If ``graph`` is a ``networkx.Graph``, then ``self.orient_undirected_graph`` is executed. 52 | 3. If ``graph`` is a ``None``, then ``self.create_graph_from_data`` is executed. 53 | 54 | Args: 55 | df_data (pandas.DataFrame): DataFrame containing the observational data. 56 | graph (networkx.DiGraph or networkx.Graph or None): Prior knowledge on the causal graph. 57 | 58 | .. warning:: 59 | Requirement : Name of the nodes in the graph must correspond to the 60 | name of the variables in df_data 61 | """ 62 | if graph is None: 63 | return self.create_graph_from_data(df_data, **kwargs) 64 | elif isinstance(graph, nx.DiGraph): 65 | return self.orient_directed_graph(df_data, graph, **kwargs) 66 | elif isinstance(graph, nx.Graph): 67 | return self.orient_undirected_graph(df_data, graph, **kwargs) 68 | else: 69 | print('Unknown Graph type') 70 | raise ValueError 71 | 72 | def orient_undirected_graph(self, data, umg, **kwargs): 73 | """Orient an undirected graph. 74 | 75 | .. note:: 76 | Not implemented: will be implemented by the model classes. 77 | """ 78 | raise NotImplementedError 79 | 80 | def orient_directed_graph(self, data, dag, **kwargs): 81 | """Re/Orient an undirected graph. 82 | 83 | .. note:: 84 | Not implemented: will be implemented by the model classes. 85 | """ 86 | raise NotImplementedError 87 | 88 | def create_graph_from_data(self, data, **kwargs): 89 | """Infer a directed graph out of data. 90 | 91 | .. note:: 92 | Not implemented: will be implemented by the model classes. 93 | """ 94 | raise NotImplementedError 95 | 96 | from .SAM import SAM_generators, SAM_discriminator 97 | from .CGNN import CGNN_model 98 | -------------------------------------------------------------------------------- /cdt/causality/graph/R_templates/pc.R: -------------------------------------------------------------------------------- 1 | # R script to prepare and run the PC algorithms 2 | 3 | # MIT License 4 | # 5 | # Copyright (c) 2018 Diviyan Kalainathan 6 | # 7 | # Permission is hereby granted, free of charge, to any person obtaining a copy 8 | # of this software and associated documentation files (the "Software"), to deal 9 | # in the Software without restriction, including without limitation the rights 10 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | # copies of the Software, and to permit persons to whom the Software is 12 | # furnished to do so, subject to the following conditions: 13 | # 14 | # The above copyright notice and this permission notice shall be included in all 15 | # copies or substantial portions of the Software. 16 | # 17 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | # SOFTWARE. 24 | 25 | library('pcalg') 26 | library('kpcalg') 27 | library('methods') 28 | library('RCIT') 29 | 30 | runPC <- function(X, suffStat, parentsOf, alpha, variableSelMat, setOptions, 31 | directed, verbose,fixedEdges,fixedGaps, 32 | result, ...){ 33 | 34 | dots <- list(...) 35 | if(length(dots) > 0){ 36 | warning("options provided via '...' not taken") 37 | } 38 | 39 | # additional options for PC 40 | optionsList <- list("indepTest"={CITEST}, "fixedEdges"=fixedEdges, 41 | "NAdelete"=TRUE, "m.max"=Inf, "u2pd" = "relaxed", 42 | "skel.method"= "stable.fast", "conservative"=FALSE, 43 | "maj.rule"=TRUE, "solve.confl"=FALSE, numCores={NJOBS}) 44 | 45 | 46 | if(is.null(suffStat)){ 47 | suffStat <- list({METHOD_INDEP}) # data=X, ic.method=method_indep) 48 | } 49 | 50 | pc.fit <- pcalg::pc(suffStat, indepTest = optionsList$indepTest, p=ncol(X), 51 | alpha = alpha, 52 | fixedGaps= fixedGaps, 53 | fixedEdges = fixedEdges , 54 | NAdelete= optionsList$NAdelete, m.max= optionsList$m.max, 55 | u2pd=optionsList$u2pd, skel.method= optionsList$skel.method, 56 | conservative= optionsList$conservative, 57 | maj.rule= optionsList$maj.rule, 58 | solve.confl = optionsList$solve.confl, 59 | verbose= verbose) 60 | 61 | pcmat <- as(pc.fit@graph, "matrix") 62 | 63 | result <- vector("list", length = length(parentsOf)) 64 | 65 | for (k in 1:length(parentsOf)){ 66 | result[[k]] <- which(as.logical(pcmat[, parentsOf[k]])) 67 | attr(result[[k]],"parentsOf") <- parentsOf[k] 68 | } 69 | 70 | if(length(parentsOf) < ncol(X)){ 71 | pcmat <- pcmat[,parentsOf] 72 | } 73 | 74 | list(resList = result, resMat = pcmat) 75 | } 76 | 77 | dataset <- read.csv(file='{FOLDER}{FILE}', header=FALSE, sep=","); 78 | 79 | variableSelMat = {SELMAT} # NULL 80 | directed = {DIRECTED} # TRUE 81 | verbose = {VERBOSE} # FALSE 82 | setOptions = {SETOPTIONS} # NULL 83 | parentsOf = 1:ncol(dataset) 84 | alpha <- {ALPHA} # 0.01 85 | fixedGaps = NULL 86 | fixedEdges = NULL 87 | 88 | if ({E_GAPS}){ 89 | fixedGaps <- read.csv(file='{FOLDER}{GAPS}', sep=",", header=FALSE) # NULL 90 | fixedGaps = (data.matrix(fixedGaps)) 91 | rownames(fixedGaps) <- colnames(fixedGaps) 92 | } 93 | if ({E_EDGES}){ 94 | fixedEdges <- read.csv(file='{FOLDER}{EDGES}', sep=",", header=FALSE) # NULL 95 | fixedEdges = (data.matrix(fixedEdges)) 96 | rownames(fixedEdges) <- colnames(fixedEdges) 97 | } 98 | result <- runPC(dataset, suffStat = NULL, parentsOf, alpha, 99 | variableSelMat, setOptions, 100 | directed, verbose, fixedEdges, fixedGaps, CI_test) 101 | 102 | write.csv(result$resMat,row.names = FALSE, file = '{FOLDER}{OUTPUT}'); 103 | -------------------------------------------------------------------------------- /docs/html/_static/js/html5shiv-printshiv.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @preserve HTML5 Shiv 3.7.3-pre | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed 3 | */ 4 | !function(a,b){function c(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x",d.insertBefore(c.lastChild,d.firstChild)}function d(){var a=y.elements;return"string"==typeof a?a.split(" "):a}function e(a,b){var c=y.elements;"string"!=typeof c&&(c=c.join(" ")),"string"!=typeof a&&(a=a.join(" ")),y.elements=c+" "+a,j(b)}function f(a){var b=x[a[v]];return b||(b={},w++,a[v]=w,x[w]=b),b}function g(a,c,d){if(c||(c=b),q)return c.createElement(a);d||(d=f(c));var e;return e=d.cache[a]?d.cache[a].cloneNode():u.test(a)?(d.cache[a]=d.createElem(a)).cloneNode():d.createElem(a),!e.canHaveChildren||t.test(a)||e.tagUrn?e:d.frag.appendChild(e)}function h(a,c){if(a||(a=b),q)return a.createDocumentFragment();c=c||f(a);for(var e=c.frag.cloneNode(),g=0,h=d(),i=h.length;i>g;g++)e.createElement(h[g]);return e}function i(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return y.shivMethods?g(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+d().join().replace(/[\w\-:]+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(y,b.frag)}function j(a){a||(a=b);var d=f(a);return!y.shivCSS||p||d.hasCSS||(d.hasCSS=!!c(a,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),q||i(a,d),a}function k(a){for(var b,c=a.getElementsByTagName("*"),e=c.length,f=RegExp("^(?:"+d().join("|")+")$","i"),g=[];e--;)b=c[e],f.test(b.nodeName)&&g.push(b.applyElement(l(b)));return g}function l(a){for(var b,c=a.attributes,d=c.length,e=a.ownerDocument.createElement(A+":"+a.nodeName);d--;)b=c[d],b.specified&&e.setAttribute(b.nodeName,b.nodeValue);return e.style.cssText=a.style.cssText,e}function m(a){for(var b,c=a.split("{"),e=c.length,f=RegExp("(^|[\\s,>+~])("+d().join("|")+")(?=[[\\s,>+~#.:]|$)","gi"),g="$1"+A+"\\:$2";e--;)b=c[e]=c[e].split("}"),b[b.length-1]=b[b.length-1].replace(f,g),c[e]=b.join("}");return c.join("{")}function n(a){for(var b=a.length;b--;)a[b].removeNode()}function o(a){function b(){clearTimeout(g._removeSheetTimer),d&&d.removeNode(!0),d=null}var d,e,g=f(a),h=a.namespaces,i=a.parentWindow;return!B||a.printShived?a:("undefined"==typeof h[A]&&h.add(A),i.attachEvent("onbeforeprint",function(){b();for(var f,g,h,i=a.styleSheets,j=[],l=i.length,n=Array(l);l--;)n[l]=i[l];for(;h=n.pop();)if(!h.disabled&&z.test(h.media)){try{f=h.imports,g=f.length}catch(o){g=0}for(l=0;g>l;l++)n.push(f[l]);try{j.push(h.cssText)}catch(o){}}j=m(j.reverse().join("")),e=k(a),d=c(a,j)}),i.attachEvent("onafterprint",function(){n(e),clearTimeout(g._removeSheetTimer),g._removeSheetTimer=setTimeout(b,500)}),a.printShived=!0,a)}var p,q,r="3.7.3",s=a.html5||{},t=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,u=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,v="_html5shiv",w=0,x={};!function(){try{var a=b.createElement("a");a.innerHTML="",p="hidden"in a,q=1==a.childNodes.length||function(){b.createElement("a");var a=b.createDocumentFragment();return"undefined"==typeof a.cloneNode||"undefined"==typeof a.createDocumentFragment||"undefined"==typeof a.createElement}()}catch(c){p=!0,q=!0}}();var y={elements:s.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:r,shivCSS:s.shivCSS!==!1,supportsUnknownElements:q,shivMethods:s.shivMethods!==!1,type:"default",shivDocument:j,createElement:g,createDocumentFragment:h,addElements:e};a.html5=y,j(b);var z=/^$|\b(?:all|print)\b/,A="html5shiv",B=!q&&function(){var c=b.documentElement;return!("undefined"==typeof b.namespaces||"undefined"==typeof b.parentWindow||"undefined"==typeof c.applyElement||"undefined"==typeof c.removeNode||"undefined"==typeof a.attachEvent)}();y.type+=" print",y.shivPrint=o,o(b),"object"==typeof module&&module.exports&&(module.exports=y)}("undefined"!=typeof window?window:this,document); -------------------------------------------------------------------------------- /cdt/causality/pairwise/Bivariate_fit.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bivariate fit model 3 | Author : Olivier Goudet 4 | Date : 7/06/17 5 | 6 | .. MIT License 7 | .. 8 | .. Copyright (c) 2018 Diviyan Kalainathan 9 | .. 10 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 11 | .. of this software and associated documentation files (the "Software"), to deal 12 | .. in the Software without restriction, including without limitation the rights 13 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | .. copies of the Software, and to permit persons to whom the Software is 15 | .. furnished to do so, subject to the following conditions: 16 | .. 17 | .. The above copyright notice and this permission notice shall be included in all 18 | .. copies or substantial portions of the Software. 19 | .. 20 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | .. SOFTWARE. 27 | """ 28 | from sklearn.gaussian_process import GaussianProcessRegressor 29 | from sklearn.preprocessing import scale 30 | from sklearn.metrics import mean_squared_error 31 | import numpy as np 32 | from .model import PairwiseModel 33 | from sklearn.preprocessing import PolynomialFeatures 34 | poly=PolynomialFeatures(degree=3) 35 | from sklearn.linear_model import LinearRegression 36 | 37 | 38 | class BivariateFit(PairwiseModel): 39 | """Bivariate Fit model. 40 | 41 | **Description:** The bivariate fit model is based onon a best-fit criterion 42 | relying on a Gaussian Process regressor. Used as weak baseline. 43 | 44 | **Data Type**: Continuous 45 | 46 | **Assumptions**: This is often a model used to show that correlation 47 | :math:`\\neq` causation. It holds very weak performance, as it states that 48 | the best predictive model is the causal model. 49 | 50 | Example: 51 | >>> from cdt.causality.pairwise import BivariateFit 52 | >>> import networkx as nx 53 | >>> import matplotlib.pyplot as plt 54 | >>> from cdt.data import load_dataset 55 | >>> data, labels = load_dataset('tuebingen') 56 | >>> obj = BivariateFit() 57 | >>> 58 | >>> # This example uses the predict() method 59 | >>> output = obj.predict(data) 60 | >>> 61 | >>> # This example uses the orient_graph() method. The dataset used 62 | >>> # can be loaded using the cdt.data module 63 | >>> data, graph = load_dataset("sachs") 64 | >>> output = obj.orient_graph(data, nx.Graph(graph)) 65 | >>> 66 | >>> #To view the directed graph run the following command 67 | >>> nx.draw_networkx(output, font_size=8) 68 | >>> plt.show() 69 | """ 70 | def __init__(self, ffactor=2, maxdev=3, minc=12): 71 | super(BivariateFit, self).__init__() 72 | 73 | def predict_proba(self, dataset, **kwargs): 74 | """ Infer causal relationships between 2 variables using regression. 75 | 76 | Args: 77 | dataset (tuple): Couple of np.ndarray variables to classify 78 | 79 | Returns: 80 | float: Causation score (Value : 1 if a->b and -1 if b->a) 81 | """ 82 | a, b = dataset 83 | return self.b_fit_score(b, a) - self.b_fit_score(a, b) 84 | 85 | def b_fit_score(self, x, y): 86 | """ Computes the cds statistic from variable 1 to variable 2 87 | 88 | Args: 89 | a (numpy.ndarray): Variable 1 90 | b (numpy.ndarray): Variable 2 91 | 92 | Returns: 93 | float: BF fit score 94 | """ 95 | x = np.reshape(scale(x), (-1, 1)) 96 | y = np.reshape(scale(y), (-1, 1)) 97 | gp = GaussianProcessRegressor().fit(x, y) 98 | y_predict = gp.predict(x) 99 | error = mean_squared_error(y_predict, y) 100 | 101 | return error 102 | -------------------------------------------------------------------------------- /cdt/independence/graph/Lasso.py: -------------------------------------------------------------------------------- 1 | """Build undirected graph out of raw data. 2 | 3 | Author: Diviyan Kalainathan 4 | Date: 1/06/17 5 | 6 | .. MIT License 7 | .. 8 | .. Copyright (c) 2018 Diviyan Kalainathan 9 | .. 10 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 11 | .. of this software and associated documentation files (the "Software"), to deal 12 | .. in the Software without restriction, including without limitation the rights 13 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | .. copies of the Software, and to permit persons to whom the Software is 15 | .. furnished to do so, subject to the following conditions: 16 | .. 17 | .. The above copyright notice and this permission notice shall be included in all 18 | .. copies or substantial portions of the Software. 19 | .. 20 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | .. SOFTWARE. 27 | 28 | """ 29 | import networkx as nx 30 | from sklearn.covariance import GraphicalLasso 31 | from .model import GraphSkeletonModel, FeatureSelectionModel 32 | from .HSICLasso import hsiclasso 33 | import numpy as np 34 | 35 | 36 | class Glasso(GraphSkeletonModel): 37 | """Graphical Lasso to find an adjacency matrix 38 | 39 | .. note:: 40 | Ref : Friedman, J., Hastie, T., & Tibshirani, R. (2008). Sparse inverse 41 | covariance estimation with the graphical lasso. Biostatistics, 9(3), 42 | 432-441. 43 | 44 | Example: 45 | >>> from cdt.independence.graph import Glasso 46 | >>> df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD')) 47 | >>> obj = Glasso() 48 | >>> output = obj.predict(df) 49 | """ 50 | 51 | def __init__(self): 52 | super(Glasso, self).__init__() 53 | 54 | def predict(self, data, alpha=0.01, max_iter=2000, **kwargs): 55 | """ Predict the graph skeleton. 56 | 57 | Args: 58 | data (pandas.DataFrame): observational data 59 | alpha (float): regularization parameter 60 | max_iter (int): maximum number of iterations 61 | 62 | Returns: 63 | networkx.Graph: Graph skeleton 64 | """ 65 | edge_model = GraphicalLasso(alpha=alpha, max_iter=max_iter) 66 | edge_model.fit(data.values) 67 | 68 | return nx.relabel_nodes(nx.DiGraph(edge_model.get_precision()), 69 | {idx: i for idx, i in enumerate(data.columns)}) 70 | 71 | 72 | class HSICLasso(FeatureSelectionModel): 73 | """Graphical Lasso with a kernel-based independence test. 74 | 75 | Example: 76 | >>> from cdt.independence.graph import HSICLasso 77 | >>> from sklearn.datasets import load_boston 78 | >>> boston = load_boston() 79 | >>> df_features = pd.DataFrame(boston['data']) 80 | >>> df_target = pd.DataFrame(boston['target']) 81 | >>> obj = HSICLasso() 82 | >>> output = obj.predict_features(df_features, df_target) 83 | >>> ugraph = obj.predict(df_features) # Predict skeleton 84 | 85 | """ 86 | def __init__(self): 87 | super(HSICLasso, self).__init__() 88 | 89 | def predict_features(self, df_features, df_target, idx=0, **kwargs): 90 | """For one variable, predict its neighbouring nodes. 91 | 92 | Args: 93 | df_features (pandas.DataFrame): 94 | df_target (pandas.Series): 95 | idx (int): (optional) for printing purposes 96 | kwargs (dict): additional options for algorithms 97 | 98 | Returns: 99 | list: scores of each feature relatively to the target 100 | 101 | """ 102 | 103 | y = np.transpose(df_target.values) 104 | X = np.transpose(df_features.values) 105 | 106 | path, beta, A, lam = hsiclasso(X, y) 107 | 108 | return beta 109 | -------------------------------------------------------------------------------- /docs/tutorial.rst: -------------------------------------------------------------------------------- 1 | .. role:: hidden 2 | :class: hidden-section 3 | 4 | =========== 5 | Get started 6 | =========== 7 | 8 | This section focuses on explaining the general functionalities of the package, 9 | and how its components interact with each other. Then two tutorials are 10 | provided: 11 | 12 | - :ref:`The first one going through the main features of the package ` 13 | 14 | - :ref:`The second for GPU users, highlighting advanced features. ` 15 | 16 | For an installation guide, please check :ref:`here ` 17 | 18 | 19 | .. toctree:: 20 | :hidden: 21 | 22 | tutorial_1 23 | tutorial_2 24 | 25 | 26 | Package Description 27 | =================== 28 | 29 | General package architecture 30 | ---------------------------- 31 | The Causal Discovery Toolbox is a package for causal discovery in the 32 | observational setting. Therefore support for data with interventions is not 33 | available at the moment, but is considered for later versions. 34 | 35 | The package is structured in 5 modules: 36 | 37 | 1. Causality: ``cdt.causality`` implements algorithms for causal discovery, either 38 | in the pairwise setting or the graph setting. 39 | 40 | 2. Independence: ``cdt.independence`` includes methods to recover the dependence 41 | graph of the data. 42 | 43 | 3. Data: ``cdt.data`` provides the user with tools to generate data, and load 44 | benchmark data. 45 | 46 | 4. Utils: ``cdt.utils`` provides tools to the users for model 47 | construction, graph utilities and settings. 48 | 49 | 5. Metrics: ``cdt.metrics`` includes scoring metrics for graphs, taking as input 50 | ``networkx.DiGraph`` 51 | 52 | All methods for computation adopt a 'scikit-learn' like interface, where ``.predict()`` 53 | manages to launch the algorithm on the given data to the toolbox, ``.fit()`` allows 54 | to train learning algorithms Most of the algorithms are classes, and their 55 | parameters can be customized in the ``.__init__()`` function of the class. 56 | 57 | .. note:: 58 | The ``.predict()`` function is often implemented in the base class 59 | (``cdt.causality.graph.GraphModel`` for causal graph algorithms). 60 | ``.predict()`` is often a wrapper calling sub-functions depending on the 61 | arguments fed to the functions. The sub-functions, such as 62 | ``.orient_directed_graph()`` for ``cdt.causality.graph`` models (which is 63 | called when a directed graph is fed as a second argument ), are 64 | implemented and documented in the various algorithms. 65 | 66 | 67 | Hardware and algorithm settings 68 | ------------------------------- 69 | The toolbox has a SETTINGS class that defines the hardware settings. Those 70 | settings are unique and their default parameters are defined in 71 | ``cdt/utils/Settings``. 72 | 73 | These parameters are accessible and overridable via accessing the class: 74 | 75 | .. code-block:: python 76 | 77 | >>> import cdt 78 | >>> cdt.SETTINGS 79 | 80 | 81 | Moreover, the hardware parameters are detected and defined automatically 82 | (including number of GPUs, CPUs, available optional packages) at the ``import`` 83 | of the package using the ``cdt.utils.Settings.autoset_settings`` method, ran at 84 | startup. 85 | 86 | These settings are overriddable in two ways: 87 | 88 | 1. By changing ``cdt.SETTINGS`` attributes, thus changing the SETTINGS for the 89 | whole python session. 90 | 91 | 2. By changing the parameters of the functions/classes used. When their default 92 | value in the class definition is ``None``, the ``cdt.SETTINGS`` value is taken, by 93 | using the ``cdt.SETTINGS.get_default`` function. This allows for quick and 94 | temporary parameter change. 95 | 96 | The graph class 97 | --------------- 98 | The whole package revolves around using the graph classes of the ``networkx`` 99 | package. 100 | Most of the methods have the option of predicting a directed graph 101 | (`networkx.DiGraph`) or an undirected graph (`networkx.Graph`). 102 | 103 | The ``networkx`` library might not be intuitive to use at first, but it comes 104 | with many useful tools for graphs. Here is a list of handy function, to 105 | understand the output of the toolbox's outputs: 106 | 107 | .. code-block:: python 108 | 109 | >>> import networkx as nx 110 | >>> g = nx.DiGraph() # initialize a directed graph 111 | >>> l = list(g.nodes()) # list of nodes in the graph 112 | >>> a = nx.adj_matrix(g).todense() # Output the adjacency matrix of the graph 113 | >>> e = list(g.edges()) # list of edges in the graph 114 | 115 | Please refer to `networkx` 's documentation for more detailed information: 116 | https://networkx.github.io/documentation/stable/ 117 | 118 | -------------------------------------------------------------------------------- /tests/scripts/test_varLINGAM.py: -------------------------------------------------------------------------------- 1 | """VARLiNGAM algorithm. 2 | 3 | Author: Georgios Koutroulis 4 | 5 | .. MIT License 6 | .. 7 | .. Copyright (c) 2019 Georgios Koutroulis 8 | .. 9 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 10 | .. of this software and associated documentation files (the "Software"), to deal 11 | .. in the Software without restriction, including without limitation the rights 12 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | .. copies of the Software, and to permit persons to whom the Software is 14 | .. furnished to do so, subject to the following conditions: 15 | .. 16 | .. The above copyright notice and this permission notice shall be included in all 17 | .. copies or substantial portions of the Software. 18 | .. 19 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | .. SOFTWARE. 26 | """ 27 | 28 | import numpy as np 29 | from statsmodels.tsa.vector_ar.var_model import VAR 30 | from cdt.timeseries.graph import VarLiNGAM 31 | import networkx as nx 32 | import pandas as pd 33 | 34 | 35 | def setRCmatrix(m, p): 36 | """Random generate matrix ids to set zeros. 37 | Parameters 38 | ---------- 39 | m : integer 40 | Number of rows/columns of square matrix 41 | p : float (0. < p < 1.0) 42 | percent of entries in matrix that set to zero. 43 | Returns 44 | ------- 45 | rowsZeros, columnsZeros : Tuple 46 | Rows and columns id of matrix 47 | that will be set to zero 48 | """ 49 | idZeros = np.random.choice(np.arange(m*m), int(p*m*m), replace=False) 50 | rowsZeros = [] 51 | columnsZeros = [] 52 | for i in idZeros: 53 | if i > m-1: 54 | rowsZeros.append(i//m) 55 | columnsZeros.append(i%m) 56 | else: 57 | rowsZeros.append(i) 58 | columnsZeros.append(1) 59 | return (rowsZeros, columnsZeros) 60 | 61 | 62 | def test_VARLiNGAM(m=5, n=300): 63 | # Test VARLiNGAM on simulated data reproduced from the paper 64 | # - A. Hyvärinen, K. Zhang, S. Shimizu, P.O. Hoyer (JMLR-2010). Estimation of 65 | # a Structural Vector Autoregression Model Using Non-Gaussianity; 66 | 67 | # Randomly construct lower triangular instantaneuous causality matrix Bo 68 | Bo = np.random.uniform(0.05, 0.5, size=(m,m)) 69 | # Bo = np.resize(Bo,(m, m)) 70 | Bo = np.tril(Bo) 71 | Bo[np.arange(m), np.arange(m)] = 0 72 | 73 | signs = np.random.choice([-1, 1],size=m*m) 74 | signs = np.resize(signs, (m, m)) 75 | Bo = Bo*signs 76 | 77 | # Randomly construct lower triangular lagged causality matrix B1 (60% set to zero) 78 | B1 = np.random.uniform(0.05, 0.5, size=(m,m)) 79 | signs = np.random.choice([-1, 1],size=m*m) 80 | signs = np.resize(signs, (m, m)) 81 | B1 = B1*signs 82 | 83 | # Set 60% of the entries to zero 84 | rowsZeros, columnsZeros = setRCmatrix(m, 0.6) 85 | B1[rowsZeros, columnsZeros] = .0 86 | 87 | rowsZeros, columnsZeros = setRCmatrix(m, 0.6) 88 | Bo[rowsZeros, columnsZeros] = .0 89 | 90 | #Generate non-Gaussian disturbances 91 | q = np.random.uniform(m) * 0.5 + 1.5 92 | 93 | e = np.random.randn(n, m) 94 | e = np.sign(e) * (np.abs(e)**q) 95 | 96 | #Generate time series with predefined length 97 | xt = np.zeros((n, m)) 98 | I = np.identity(m) 99 | M1 = np.dot(np.linalg.inv(I - Bo), B1) 100 | Bo_t = [] 101 | rowsZeros, colsZeros = np.where(Bo != 0.) 102 | 103 | # Generate time series according to autoregressive and causal Matrices 104 | for i in range(n): 105 | xt[i, :] = np.dot(xt[i-1, :], M1) + np.dot(np.linalg.inv(I - Bo), e[i, :]) 106 | 107 | #Test VARLiNGAM 108 | model = VarLiNGAM() 109 | Bo_, Bhat_ = model._run_varLiNGAM(xt) 110 | 111 | 112 | def test_pipeline(): 113 | data = pd.DataFrame(np.random.randn(500, 10)) 114 | model = VarLiNGAM() 115 | out1, out2 = model.predict(data) 116 | assert type(out1) == nx.DiGraph 117 | assert type(out1) == nx.DiGraph 118 | 119 | 120 | if __name__ == '__main__': 121 | test_VARLiNGAM(10, 500) 122 | test_pipeline() 123 | -------------------------------------------------------------------------------- /docs/html/_sources/tutorial.rst.txt: -------------------------------------------------------------------------------- 1 | .. role:: hidden 2 | :class: hidden-section 3 | 4 | =========== 5 | Get started 6 | =========== 7 | 8 | This section focuses on explaining the general functionalities of the package, 9 | and how its components interact with each other. Then two tutorials are 10 | provided: 11 | 12 | - :ref:`The first one going through the main features of the package ` 13 | 14 | - :ref:`The second for GPU users, highlighting advanced features. ` 15 | 16 | For an installation guide, please check :ref:`here ` 17 | 18 | 19 | .. toctree:: 20 | :hidden: 21 | 22 | tutorial_1 23 | tutorial_2 24 | 25 | 26 | Package Description 27 | =================== 28 | 29 | General package architecture 30 | ---------------------------- 31 | The Causal Discovery Toolbox is a package for causal discovery in the 32 | observational setting. Therefore support for data with interventions is not 33 | available at the moment, but is considered for later versions. 34 | 35 | The package is structured in 5 modules: 36 | 37 | 1. Causality: ``cdt.causality`` implements algorithms for causal discovery, either 38 | in the pairwise setting or the graph setting. 39 | 40 | 2. Independence: ``cdt.independence`` includes methods to recover the dependence 41 | graph of the data. 42 | 43 | 3. Data: ``cdt.data`` provides the user with tools to generate data, and load 44 | benchmark data. 45 | 46 | 4. Utils: ``cdt.utils`` provides tools to the users for model 47 | construction, graph utilities and settings. 48 | 49 | 5. Metrics: ``cdt.metrics`` includes scoring metrics for graphs, taking as input 50 | ``networkx.DiGraph`` 51 | 52 | All methods for computation adopt a 'scikit-learn' like interface, where ``.predict()`` 53 | manages to launch the algorithm on the given data to the toolbox, ``.fit()`` allows 54 | to train learning algorithms Most of the algorithms are classes, and their 55 | parameters can be customized in the ``.__init__()`` function of the class. 56 | 57 | .. note:: 58 | The ``.predict()`` function is often implemented in the base class 59 | (``cdt.causality.graph.GraphModel`` for causal graph algorithms). 60 | ``.predict()`` is often a wrapper calling sub-functions depending on the 61 | arguments fed to the functions. The sub-functions, such as 62 | ``.orient_directed_graph()`` for ``cdt.causality.graph`` models (which is 63 | called when a directed graph is fed as a second argument ), are 64 | implemented and documented in the various algorithms. 65 | 66 | 67 | Hardware and algorithm settings 68 | ------------------------------- 69 | The toolbox has a SETTINGS class that defines the hardware settings. Those 70 | settings are unique and their default parameters are defined in 71 | ``cdt/utils/Settings``. 72 | 73 | These parameters are accessible and overridable via accessing the class: 74 | 75 | .. code-block:: python 76 | 77 | >>> import cdt 78 | >>> cdt.SETTINGS 79 | 80 | 81 | Moreover, the hardware parameters are detected and defined automatically 82 | (including number of GPUs, CPUs, available optional packages) at the ``import`` 83 | of the package using the ``cdt.utils.Settings.autoset_settings`` method, ran at 84 | startup. 85 | 86 | These settings are overriddable in two ways: 87 | 88 | 1. By changing ``cdt.SETTINGS`` attributes, thus changing the SETTINGS for the 89 | whole python session. 90 | 91 | 2. By changing the parameters of the functions/classes used. When their default 92 | value in the class definition is ``None``, the ``cdt.SETTINGS`` value is taken, by 93 | using the ``cdt.SETTINGS.get_default`` function. This allows for quick and 94 | temporary parameter change. 95 | 96 | The graph class 97 | --------------- 98 | The whole package revolves around using the graph classes of the ``networkx`` 99 | package. 100 | Most of the methods have the option of predicting a directed graph 101 | (`networkx.DiGraph`) or an undirected graph (`networkx.Graph`). 102 | 103 | The ``networkx`` library might not be intuitive to use at first, but it comes 104 | with many useful tools for graphs. Here is a list of handy function, to 105 | understand the output of the toolbox's outputs: 106 | 107 | .. code-block:: python 108 | 109 | >>> import networkx as nx 110 | >>> g = nx.DiGraph() # initialize a directed graph 111 | >>> l = list(g.nodes()) # list of nodes in the graph 112 | >>> a = nx.adj_matrix(g).todense() # Output the adjacency matrix of the graph 113 | >>> e = list(g.edges()) # list of edges in the graph 114 | 115 | Please refer to `networkx` 's documentation for more detailed information: 116 | https://networkx.github.io/documentation/stable/ 117 | 118 | -------------------------------------------------------------------------------- /cdt/causality/pairwise/RECI.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bivariate fit model 3 | Author : Olivier Goudet 4 | Date : 7/06/17 5 | 6 | .. MIT License 7 | .. 8 | .. Copyright (c) 2018 Diviyan Kalainathan 9 | .. 10 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 11 | .. of this software and associated documentation files (the "Software"), to deal 12 | .. in the Software without restriction, including without limitation the rights 13 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 14 | .. copies of the Software, and to permit persons to whom the Software is 15 | .. furnished to do so, subject to the following conditions: 16 | .. 17 | .. The above copyright notice and this permission notice shall be included in all 18 | .. copies or substantial portions of the Software. 19 | .. 20 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 21 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 22 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 23 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 24 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 25 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 26 | .. SOFTWARE. 27 | """ 28 | from sklearn.gaussian_process import GaussianProcessRegressor 29 | from sklearn.preprocessing import minmax_scale 30 | from sklearn.metrics import mean_squared_error 31 | import numpy as np 32 | from .model import PairwiseModel 33 | from sklearn.preprocessing import PolynomialFeatures 34 | from sklearn.linear_model import LinearRegression 35 | 36 | 37 | class RECI(PairwiseModel): 38 | """RECI model. 39 | 40 | **Description:** Regression Error based Causal Inference (RECI) 41 | relies on a best-fit mse with monome regressor and [0,1] rescaling to 42 | infer causal direction. 43 | 44 | **Data Type:** Continuous (depends on the regressor used) 45 | 46 | **Assumptions:** No independence tests are used, but the assumptions on 47 | the model depend on the regessor used for RECI. 48 | 49 | Args: 50 | degree (int): Degree of the polynomial regression. 51 | 52 | .. note:: 53 | Bloebaum, P., Janzing, D., Washio, T., Shimizu, S., & Schoelkopf, B. 54 | (2018, March). Cause-Effect Inference by Comparing Regression Errors. 55 | In International Conference on Artificial Intelligence and Statistics (pp. 900-909). 56 | 57 | Example: 58 | >>> from cdt.causality.pairwise import RECI 59 | >>> import networkx as nx 60 | >>> import matplotlib.pyplot as plt 61 | >>> from cdt.data import load_dataset 62 | >>> data, labels = load_dataset('tuebingen') 63 | >>> obj = RECI() 64 | >>> 65 | >>> # This example uses the predict() method 66 | >>> output = obj.predict(data) 67 | >>> 68 | >>> # This example uses the orient_graph() method. The dataset used 69 | >>> # can be loaded using the cdt.data module 70 | >>> data, graph = load_dataset("sachs") 71 | >>> output = obj.orient_graph(data, nx.Graph(graph)) 72 | >>> 73 | >>> #To view the directed graph run the following command 74 | >>> nx.draw_networkx(output, font_size=8) 75 | >>> plt.show() 76 | """ 77 | def __init__(self, degree=3): 78 | super(RECI, self).__init__() 79 | self.degree = degree 80 | 81 | def predict_proba(self, dataset, **kwargs): 82 | """ Infer causal relationships between 2 variables using the RECI statistic 83 | 84 | Args: 85 | dataset (tuple): Couple of np.ndarray variables to classify 86 | 87 | Returns: 88 | float: Causation coefficient (Value : 1 if a->b and -1 if b->a) 89 | """ 90 | a, b = dataset 91 | return self.b_fit_score(b, a) - self.b_fit_score(a, b) 92 | 93 | def b_fit_score(self, x, y): 94 | """ Compute the RECI fit score 95 | 96 | Args: 97 | x (numpy.ndarray): Variable 1 98 | y (numpy.ndarray): Variable 2 99 | 100 | Returns: 101 | float: RECI fit score 102 | 103 | """ 104 | x = np.reshape(minmax_scale(x), (-1, 1)) 105 | y = np.reshape(minmax_scale(y), (-1, 1)) 106 | poly = PolynomialFeatures(degree=self.degree) 107 | poly_x = poly.fit_transform(x) 108 | 109 | poly_x[:,1] = 0 110 | poly_x[:,2] = 0 111 | 112 | regressor = LinearRegression() 113 | regressor.fit(poly_x, y) 114 | 115 | y_predict = regressor.predict(poly_x) 116 | error = mean_squared_error(y_predict, y) 117 | 118 | return error 119 | -------------------------------------------------------------------------------- /cdt/timeseries/graph/VARLiNGAM.py: -------------------------------------------------------------------------------- 1 | """VARLiNGAM algorithm. 2 | 3 | Author: Georgios Koutroulis 4 | 5 | .. MIT License 6 | .. 7 | .. Copyright (c) 2019 Georgios Koutroulis 8 | .. 9 | .. Permission is hereby granted, free of charge, to any person obtaining a copy 10 | .. of this software and associated documentation files (the "Software"), to deal 11 | .. in the Software without restriction, including without limitation the rights 12 | .. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | .. copies of the Software, and to permit persons to whom the Software is 14 | .. furnished to do so, subject to the following conditions: 15 | .. 16 | .. The above copyright notice and this permission notice shall be included in all 17 | .. copies or substantial portions of the Software. 18 | .. 19 | .. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | .. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | .. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | .. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | .. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | .. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | .. SOFTWARE. 26 | """ 27 | import numpy as np 28 | import pandas as pd 29 | import networkx as nx 30 | from statsmodels.tsa.vector_ar.var_model import VAR 31 | from ...causality.graph import LiNGAM 32 | from ...causality.graph.model import GraphModel 33 | from ...utils.Settings import SETTINGS 34 | 35 | 36 | class VarLiNGAM(GraphModel): 37 | """ Estimate a VAR-LiNGAM 38 | Random generate matrix ids to set zeros. 39 | 40 | Args: 41 | lag (float): order to estimate the vector autoregressive model 42 | verbose (bool): Verbosity of the class. Defaults to SETTINGS.verbose 43 | 44 | .. note:: 45 | Ref: - A. Hyvarinen, S. Shimizu, P.O. Hoyer ((ICML-2008). Causal modelling 46 | combining instantaneous and lagged effects: an identifiable model based 47 | on non-Gaussianity; 48 | - A. Hyvarinen, K. Zhang, S. Shimizu, P.O. Hoyer (JMLR-2010). Estimation of 49 | a Structural Vector Autoregression Model Using Non-Gaussianity; 50 | """ 51 | 52 | def __init__(self, lag=1, verbose=None): 53 | self.lag = lag 54 | self.verbose = SETTINGS.get_default(verbose=verbose) 55 | 56 | def orient_undirected_graph(self, data, graph): 57 | """Run varLiNGAM on an undirected graph.""" 58 | # Building setup w/ arguments. 59 | raise ValueError("VarLiNGAM cannot (yet) be ran with a skeleton/directed graph.") 60 | 61 | def orient_directed_graph(self, data, graph): 62 | """Run varLiNGAM on a directed_graph.""" 63 | raise ValueError("VarLiNGAM cannot (yet) be ran with a skeleton/directed graph.") 64 | 65 | def create_graph_from_data(self, data): 66 | """ Run the VarLiNGAM algorithm on data. 67 | 68 | Args: 69 | data (pandas.DataFrame): time series data 70 | 71 | Returns: 72 | tuple :(networkx.Digraph, networkx.Digraph) Predictions given by 73 | the varLiNGAM algorithm: Instantaneous and Lagged causal Graphs 74 | """ 75 | inst, lagged = self._run_varLiNGAM(data.values, verbose=self.verbose) 76 | return (nx.relabel_nodes(nx.DiGraph(inst), 77 | {idx: i for idx, i in enumerate(data.columns)}), 78 | nx.relabel_nodes(nx.DiGraph(lagged), 79 | {idx: i for idx, i in enumerate(data.columns)}), 80 | ) 81 | 82 | def _run_varLiNGAM(self, xt, verbose=False): 83 | """ Run the VarLiNGAM algorithm on data. 84 | 85 | Args: 86 | xt : time series matrix with size n*m (length*num_variables) 87 | 88 | Returns: 89 | Tuple: (Bo, Bhat) Instantaneous and lagged causal coefficients 90 | 91 | """ 92 | Ident = np.identity(xt.shape[1]) 93 | 94 | # Step 1: VAR estimation 95 | model = VAR(xt) 96 | results = model.fit(self.lag) 97 | Mt_ = results.params[1:, :] 98 | 99 | # Step 2: LiNGAM on Residuals 100 | resid_VAR = results.resid 101 | model = LiNGAM(verbose=verbose) 102 | data = pd.DataFrame(resid_VAR) 103 | Bo_ = model._run_LiNGAM(data) 104 | 105 | # Step 3: Get instantaneous matrix Bo from LiNGAM 106 | # Bo_ = pd.read_csv("results.csv").values 107 | 108 | # Step 4: Calculation of lagged Bhat 109 | Bhat_ = np.dot((Ident - Bo_), Mt_) 110 | return (Bo_, Bhat_) 111 | -------------------------------------------------------------------------------- /docs/html/_static/js/theme.js: -------------------------------------------------------------------------------- 1 | !function(n){var e={};function t(i){if(e[i])return e[i].exports;var o=e[i]={i:i,l:!1,exports:{}};return n[i].call(o.exports,o,o.exports,t),o.l=!0,o.exports}t.m=n,t.c=e,t.d=function(n,e,i){t.o(n,e)||Object.defineProperty(n,e,{enumerable:!0,get:i})},t.r=function(n){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},t.t=function(n,e){if(1&e&&(n=t(n)),8&e)return n;if(4&e&&"object"==typeof n&&n&&n.__esModule)return n;var i=Object.create(null);if(t.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:n}),2&e&&"string"!=typeof n)for(var o in n)t.d(i,o,function(e){return n[e]}.bind(null,o));return i},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,e){return Object.prototype.hasOwnProperty.call(n,e)},t.p="",t(t.s=0)}([function(n,e,t){t(1),n.exports=t(3)},function(n,e,t){(function(){var e="undefined"!=typeof window?window.jQuery:t(2);n.exports.ThemeNav={navBar:null,win:null,winScroll:!1,winResize:!1,linkScroll:!1,winPosition:0,winHeight:null,docHeight:null,isRunning:!1,enable:function(n){var t=this;void 0===n&&(n=!0),t.isRunning||(t.isRunning=!0,e((function(e){t.init(e),t.reset(),t.win.on("hashchange",t.reset),n&&t.win.on("scroll",(function(){t.linkScroll||t.winScroll||(t.winScroll=!0,requestAnimationFrame((function(){t.onScroll()})))})),t.win.on("resize",(function(){t.winResize||(t.winResize=!0,requestAnimationFrame((function(){t.onResize()})))})),t.onResize()})))},enableSticky:function(){this.enable(!0)},init:function(n){n(document);var e=this;this.navBar=n("div.wy-side-scroll:first"),this.win=n(window),n(document).on("click","[data-toggle='wy-nav-top']",(function(){n("[data-toggle='wy-nav-shift']").toggleClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift")})).on("click",".wy-menu-vertical .current ul li a",(function(){var t=n(this);n("[data-toggle='wy-nav-shift']").removeClass("shift"),n("[data-toggle='rst-versions']").toggleClass("shift"),e.toggleCurrent(t),e.hashChange()})).on("click","[data-toggle='rst-current-version']",(function(){n("[data-toggle='rst-versions']").toggleClass("shift-up")})),n("table.docutils:not(.field-list,.footnote,.citation)").wrap("
"),n("table.docutils.footnote").wrap("
"),n("table.docutils.citation").wrap("
"),n(".wy-menu-vertical ul").not(".simple").siblings("a").each((function(){var t=n(this);expand=n(''),expand.on("click",(function(n){return e.toggleCurrent(t),n.stopPropagation(),!1})),t.prepend(expand)}))},reset:function(){var n=encodeURI(window.location.hash)||"#";try{var e=$(".wy-menu-vertical"),t=e.find('[href="'+n+'"]');if(0===t.length){var i=$('.document [id="'+n.substring(1)+'"]').closest("div.section");0===(t=e.find('[href="#'+i.attr("id")+'"]')).length&&(t=e.find('[href="#"]'))}if(t.length>0){$(".wy-menu-vertical .current").removeClass("current").attr("aria-expanded","false"),t.addClass("current").attr("aria-expanded","true"),t.closest("li.toctree-l1").parent().addClass("current").attr("aria-expanded","true");for(let n=1;n<=10;n++)t.closest("li.toctree-l"+n).addClass("current").attr("aria-expanded","true");t[0].scrollIntoView()}}catch(n){console.log("Error expanding nav for anchor",n)}},onScroll:function(){this.winScroll=!1;var n=this.win.scrollTop(),e=n+this.winHeight,t=this.navBar.scrollTop()+(n-this.winPosition);n<0||e>this.docHeight||(this.navBar.scrollTop(t),this.winPosition=n)},onResize:function(){this.winResize=!1,this.winHeight=this.win.height(),this.docHeight=$(document).height()},hashChange:function(){this.linkScroll=!0,this.win.one("hashchange",(function(){this.linkScroll=!1}))},toggleCurrent:function(n){var e=n.closest("li");e.siblings("li.current").removeClass("current").attr("aria-expanded","false"),e.siblings().find("li.current").removeClass("current").attr("aria-expanded","false");var t=e.find("> ul li");t.length&&(t.removeClass("current").attr("aria-expanded","false"),e.toggleClass("current").attr("aria-expanded",(function(n,e){return"true"==e?"false":"true"})))}},"undefined"!=typeof window&&(window.SphinxRtdTheme={Navigation:n.exports.ThemeNav,StickyNav:n.exports.ThemeNav}),function(){for(var n=0,e=["ms","moz","webkit","o"],t=0;t