Saravanan666/pypi-org huggingface dataset:
Package: causal-ccm
causal_ccmPackage implementing Convergent Cross Mapping for causality inference in dynamical systems as defined bySugihara et al (2012)Example usageFor an example how to use, see:https://github.com/PrinceJavier/causal_ccm/blob/main/usage_sample.ipynbSource code:https://github.com/PrinceJavier/causal_ccmTo installpip install causal-ccmTo useSay we want to check if X drives Y. We first defineccmusing:XandY- time series datatau- time lag (iftau=1we get[t, t-1, t-2...]as our shadow manifold embeddingE- embedding dimension (default=2) for the shadow manifoldL- time horizon to consider, defaults at length of time series XWe import the packagefrom causal_ccm.causal_ccm import ccmWe defineccm:ccm1 = ccm(X, Y, tau, E, L) # define ccm with X, Y time seriesWe check the strength of causality measured as correlation in prediction vs true (see Sugihara (2012))ccm1.causality()We can visualize cross mapping between manifolds of X and Yccm1.visualize_cross_mapping()We visualize correlation of X->YWe stronger correlation = stronger causal relationshipccm1.plot_ccm_correls()Finally, we can check convergence in predictions (correlations) by computingccm1.causality()forccm1defined with different L values.Additional Feature (PAI)The pai class implements the Pairwise Asymmetric Inference (see McCracken (2014)). The major difference of pai to ccm is the shadow manifold used to predictX. To create the manifold, use themanifold_patternandtauparameters. For example,manifold_pattern=[[0, -1, -2],[0]], tau=2is the same as the shadow manifold(X_t, X_{t-1*2}, X_{t-2*2}, Y_t).If this package helped you in your work, pls. cite:@software{Javier_causal-ccm_a_Python_2021,
author = {Javier, Prince Joseph Erneszer},
month = {6},
title = {{causal-ccm a Python implementation of Convergent Cross Mapping}},
version = {0.3.3},
year = {2021}
}
Package: causal-chains
Causal Chain ExtractorThis code implements a tool to extract causal chains from text by summarizing the text using thebart-cause-effectmodel fromHugging Face Transformersand then linking the causes and effects with cosine similarity calculated using theSentence Transformermodel.InstallationLibrary can be installed withpip install causal-chainsUsageInitialize aCausalChainobject with a list of chunks of text as input.Run thecreate_effectsmethod to get the cause and effect pairs from the text and then link the events based on cosine similarity of their embeddings.Run thevisualizemethod to see the largest chain.Methods:The class "CausalChain" has the following methods:create_effects: This method uses the pipeline from the transformers library to analyze the text for cause-effect relationships. The text is first split into chunks, with each chunk containing a maximum of 3 sentences. This is done to limit the output length and avoid memory issues. The pipeline then generates summaries of the cause-effect relationships in the text. The triggers and effects of these relationships are stored in separate lists.create_connections: This method uses the SentenceTransformer from the sentence-transformers library to encode the triggers and effects generated in the create_effects method. The method then calculates the cosine similarity between the triggers and effects to determine if there is a cause-effect relationship between them. If the cosine similarity score is above a certain threshold (default is 0.6), a connection is established between the trigger and effect. The connections between triggers and effects are stored in a dictionary.find_biggest_chain: This method finds the longest chain of cause-effect relationships in the text. It starts from an effect and follows the connections stored in the connections dictionary to find other effects that are connected to it. The method continues this process until there are no more connections or the chain reaches a certain length (default is 10). The longest chain found is stored in the biggest_chain attribute.visualize: This method displays a given chain using pydot.Example Usage:fromcausal_chain_extractorimportCausalChain,utilimportwikipediatext=wikipedia.page("ChristopherColumbus").contentchunksutil.create_chunks(text)cc=CausalChain(chunks,device=0)cc.create_connections()biggest_chain=cc.biggest_chaincc.visualize(biggest_chain)The display that this code produces is shown at the top of this page.Google Colab Demo
Package: causal-conv1d
Causal depthwise conv1d in CUDA with a PyTorch interfaceFeatures:Support fp32, fp16, bf16.Kernel size 2, 3, 4.How to usefrom causal_conv1d import causal_conv1d_fndef causal_conv1d_fn(x, weight, bias=None, activation=None):
    """
    x: (batch, dim, seqlen)
    weight: (dim, width)
    bias: (dim,)
    activation: either None or "silu" or "swish"

    out: (batch, dim, seqlen)
    """Equivalent to:import torch.nn.functional as F

F.conv1d(x, weight.unsqueeze(1), bias, padding=width - 1, groups=dim)[..., :seqlen]
Package: causal-curve
causal-curvePython tools to perform causal inference when the treatment of interest is continuous.Table of ContentsOverviewInstallationDocumentationContributingCitationReferencesOverview(Version 1.0.0 released in January 2021!)There are many implemented methods to perform causal inference when your intervention of interest is binary,
but few methods exist to handle continuous treatments.This is unfortunate because there are many scenarios (in industry and research) where these methods would be useful.
For example, when you would like to:Estimate the causal response to increasing or decreasing the price of a product across a wide range.Understand how the number of minutes per week of aerobic exercise causes positive health outcomes.Estimate how decreasing order wait time will impact customer satisfaction, after controlling for confounding effects.Estimate how changing neighborhood income inequality (Gini index) could be causally related to neighborhood crime rate.This library attempts to address this gap, providing tools to estimate causal curves (AKA causal dose-response curves).
Both continuous and binary outcomes can be modeled against a continuous treatment.InstallationAvailable via PyPI:pip install causal-curveYou can also get the latest version of causal-curve by cloning the repository::git clone -b main https://github.com/ronikobrosly/causal-curve.git
cd causal-curve
pip install .DocumentationDocumentation is available at readthedocs.orgContributingYour help is absolutely welcome! Please do reach out or create a feature branch!CitationKobrosly, R. W., (2020). causal-curve: A Python Causal Inference Package to Estimate Causal Dose-Response Curves. Journal of Open Source Software, 5(52), 2523,https://doi.org/10.21105/joss.02523ReferencesGalagate, D. Causal Inference with a Continuous Treatment and Outcome: Alternative
Estimators for Parametric Dose-Response function with Applications. PhD thesis, 2016.Hirano K and Imbens GW. The propensity score with continuous treatments.
In: Gelman A and Meng XL (eds) Applied bayesian modeling and causal inference
from incomplete-data perspectives. Oxford, UK: Wiley, 2004, pp.73–84.Imai K, Keele L, Tingley D. A General Approach to Causal Mediation Analysis. Psychological
Methods. 15(4), 2010, pp.309–334.Kennedy EH, Ma Z, McHugh MD, Small DS. Nonparametric methods for doubly robust estimation
of continuous treatment effects. Journal of the Royal Statistical Society, Series B. 79(4), 2017, pp.1229-1245.Moodie E and Stephens DA. Estimation of dose–response functions for
longitudinal data using the generalised propensity score. In: Statistical Methods in
Medical Research 21(2), 2010, pp.149–166.van der Laan MJ and Gruber S. Collaborative double robust penalized targeted
maximum likelihood estimation. In: The International Journal of Biostatistics 6(1), 2010.van der Laan MJ and Rubin D. Targeted maximum likelihood learning. In: ​U.C. Berkeley Division of
Biostatistics Working Paper Series, 2006.
Package: causal-discovery
Causal discoveryCausal discovery is the process of inferring causal relationships between variables from observational data. This repository aims to provide a collection of causal discovery algorithms implemented in Python.Development setupThis repository usesPoetryas a dependency manager. To install the dependencies, run:$poetryinstallUsageYou can install the package from PyPI:$pipinstallcausal-discoveryexample usage:fromcausal_discovery.algos.notearsimportNoTears# load datasetdataset=...# initialize modelmodel=NoTears(rho=1,alpha=0.1,l1_reg=0,lr=1e-2)# learn the graph_=model.learn(dataset)# adjacency matrixprint(model.get_result())AlgorithmsAlgorithmReferenceNOTEARSDAGs with NO TEARS: Continuous Optimization for Structure Learning, 2019ResultsThis is the example of the results of the algorithm.How to read this figure: for any value in coordinate (x, y) means the causal effect from y -> x.
Package: causalforge
CausalForgeCausalForge is a Python package that provides a suite of modeling & causal inference methods using machine learning algorithms based on Elevence Health recent research. It provides convenient APIs that allow to estimate Propensity Score, Average Treatment Effect (ATE), Conditional Average Treatment Effect (CATE) or Individual Treatment Effect (ITE)
from experimental or observational data. Methods have been redesigned for production.Check out the documentation.Installing Python PackageWe recommend to create a proper enviroment with tensorflow and pytorch
installed. For example, for a local Mac enviroment without GPUs:condaenvcreate-fenv_mac.yml
condaactivatecausalforgeYou can install it after cloning this repository, i.e.gitclonehttps://github.com/anthem-ai/causalforgecdcausalforge[sudo]pipinstall-e.[--trusted-hostpypi.org--trusted-hostfiles.pythonhosted.org]or directly from the repository (development), i.e.pipinstall--upgradegit+https://github.com/anthem-ai/causalforge[--trusted-hostpypi.org--trusted-hostfiles.pythonhosted.org]or directly from PyPI, i.e.pipinstallcausalforgeAfter installing you can import classes and methods, e.g.importcausalforgecausalforge.__version__Testingcdtests
pytest--disable-warningsCitation@article{tesei2023learning,title={Learning end-to-end patient representations through self-supervised covariate balancing for causal treatment effect estimation},author={Tesei, Gino and Giampanis, Stefanos and Shi, Jingpu and Norgeot, Beau},journal={Journal of Biomedical Informatics},volume={140},pages={104339},year={2023},publisher={Elsevier}}
Package: causalgraphicalmodels
# CausalGraphicalModels## Introduction`causalgraphicalmodels` is a python module for describing and manipulating [Causal Graphical Models](https://en.wikipedia.org/wiki/Causal_graph) and [Structural Causal Models](https://en.wikipedia.org/wiki/Structural_equation_modeling). Behind the scenes it is a light wrapper around the python graph library [networkx](https://networkx.github.io/), together with some CGM specific tools.It is currently in a very early stage of development. All feedback is welcome.## ExampleFor a quick overview of `CausalGraphicalModel`, see [this example notebook](https://github.com/ijmbarr/causalgraphicalmodels/blob/master/notebooks/cgm-examples.ipynb).## Install```pip install causalgraphicalmodels```## ResourcesMy understanding of Causality comes mainly from the reading of the follow work:- Causality, Pearl, 2009, 2nd Editing. (An overview available [here](http://ftp.cs.ucla.edu/pub/stat_ser/r350.pdf))- A fantastic blog post, [If correlation doesn’t imply causation, then what does?](http://www.michaelnielsen.org/ddi/if-correlation-doesnt-imply-causation-then-what-does/) from Michael Nielsen- [These lecture notes](http://www.math.ku.dk/~peters/jonas_files/scriptChapter1-4.pdf) from Jonas Peters- The draft of [Elements of Causal Inference](http://www.math.ku.dk/~peters/jonas_files/bookDRAFT5-online-2017-02-27.pdf)- http://mlss.tuebingen.mpg.de/2017/speaker_slides/Causality.pdf## Related Packages- [Causality](https://github.com/akelleh/causality)- [CausalInference](https://github.com/laurencium/causalinference)- [DoWhy](https://github.com/Microsoft/dowhy)
Package: causalimpact
CausalImpactA Python package for causal inference using Bayesian structural time-series modelsThis is a port of the R package CausalImpact, see:https://github.com/google/CausalImpact.This package implements an approach to estimating the causal effect of a designed intervention on a time series. For example, how many additional daily clicks were generated by an advertising campaign? Answering a question like this can be difficult when a randomized experiment is not available. The package aims to address this difficulty using a structural Bayesian time-series model to estimate how the response metric might have evolved after the intervention if the intervention had not occurred.As with all approaches to causal inference on non-experimental data, valid conclusions require strong assumptions. The CausalImpact package, in particular, assumes that the outcome time series can be explained in terms of a set of control time series that were themselves not affected by the intervention. Furthermore, the relation between treated series and control series is assumed to be stable during the post-intervention period. Understanding and checking these assumptions for any given application is critical for obtaining valid conclusions.Try it out in the browserInstallationinstall the latest release via pippipinstallcausalimpactGetting startedDocumentation and examplesFurther resourcesManuscript:Brodersen et al., Annals of Applied Statistics (2015)BugsThe issue tracker is athttps://github.com/jamalsenouci/causalimpact/issues. Please report any bugs that you find. Or, even better, fork the repository on GitHub and create a pull request.
Package: causal-inference
Causal InferenceCausal InferenceInstallationpipinstallcausal-inferenceUsageimportcausal_inferenceasciimportnumpyasnpprobs={'A':[1,0.1],'B':[1,0.1],'C':[1,0.1],'D':[1,0.1]}xy={"mean":np.array([[1,2],[2,4]]),"dev":np.array([[.1,.2],[.2,.4]])}new_xv=ci.next_position_scm(xy,probs)print(new_xv["mean"])print(new_xv["dev"])CitationPlease cite following document if you use this python package:TBDImage source:https://www.pexels.com/photo/blue-water-2695624/
Package: causal-inference-aagm
# CAUSAL INFERENCE AAGM# Background
Propensity score matching is a statistical technique used to estimate the effect of a treatment or intervention on an outcome of interest. It is commonly used in observational studies, where the assignment of treatment or exposure to a particular group is not randomized.The idea behind propensity score matching is to balance the characteristics of the treatment and control groups by matching individuals with similar propensity scores, which are the probabilities of receiving the treatment or intervention based on observed covariates. This helps to control for confounding factors and reduce selection bias, allowing for a more accurate estimation of the treatment effect.Overall, propensity score matching is a useful tool for researchers to make causal inferences in observational studies, although it is important to consider the limitations and assumptions of this method.# Requirements Library
This python requires related package more importantly python_requires=’>=3.1’, so that package can be install Make sure the other packages meet the requirements below
- pandas>=1.1.5,
- numpy>=1.18.5,
- scipy>=1.2.0,
- matplotlib>=3.1.0,
- statsmodels>=0.8.0# Usage Guide
This is a Python class named PropensityScoreMatch. It is designed to perform propensity score matching, a technique used to balance the distribution of confounding variables between treatment and control groups in observational studies. The class has four input arguments:df: a pandas DataFrame containing the data to be analyzed.features: a list of column names in df that contain the variables used to calculate propensity scores.treatment: a string that specifies the name of the column in df that contains the treatment variable.outcome: a string that specifies the name of the column in df that contains the outcome variable.The output of the class is two pandas DataFrames:df_matched: a DataFrame containing the data for the matched pairs of treated and control observations.df_TE: a DataFrame containing the treatment effect estimates for each variable in features.In addition to these output DataFrames, the class provides two methods for visualizing the results of the analysis:plot_smd(): a method that generates a plot of standardized mean differences (SMDs) between the treatment and control groups for each variable in features.plot_individual_treatment(): a method that generates a plot of the individual treatment effects for each observation in df_matched.For Analysis:
- plot_smd() : plotting the df_smd
Package: causal-inference-population-dynamics
Causal-inference-population-dynamicsCausal-inference-population-dynamics is a library to simulate and infer population dynamics models.The currently imlemented population dynamics models areLotka-Volterra modelRunning the codeYou can run the simulator directly from terminal by runningpython causal/base/lotka_volterra.pyThe simulation statistics will be saved in therepo/resultsdirectory.
Package: causalipy
CausaliPyCausal Methods implemented in Python.InstallationInstall viapip install causalipyIt might make sense to add the py-arrow dependency (which is currently required
for the example):pip install pyarrowExampleTo run a version of the multi-period difference-in-difference estimator as
proposed by Callaway and Sant’Anna (2020)  (this requires additionally pyarrow  - e.g. viapip install pyarrow- to be installed currently):fromcausalipy.did.multi_periodsimportMultiPeriodDidimportpandasaspdurl="https://github.com/mohelm/causalipy-datasets/raw/main/mpdta-sample.feather"data=pd.read_feather(url)mpd_minimum_wage=MultiPeriodDid(data,outcome="lemp",treatment_indicator="treat",time_period_indicator="year",group_indiciator="first.treat",formula="~ 1",)mpd_minimum_wage.plot_treatment_effects()This will give:LicenseThis project is licensed under the terms of the MIT license.
Package: causal-lasso
Causal LassoThis repository implements paper "A Bregman Method for Structure Learning on Sparse Directed Acyclic Graphs" by Manon Romain and Alexandre d'Aspremont.InstallThough pipRunpip install causal-lassofrom Terminal.From sourcesRungit clone https://github.com/manon643/causal_lasso.git. Install dependencies thoughpip install -r docs/requirements.txt.SolverFor now, the default solver used at each iteration is Mosek. We plan to provide an open source implementation in the near future.MOSEK's license is free for academic use, first obtain your licensehereusing institutional email and place the obtained filemosek.licin a file called:%USERPROFILE%\mosek\mosek.lic           (Windows)
$HOME/mosek/mosek.lic                   (Linux, MacOS)Further information availablehere.UseMinimal testing code is:import numpy as np
import networkx as nx
from causal_lasso.solver import CLSolver
X = np.random.random((1000, 30)) # Replace with your data
lasso = CLSolver()
W_est = lasso.fit(X)
nx.draw(nx.DiGraph(W_est))A more detailed tutorial with synthetic data is available inexamples/tutorial.ipynb.
If you want to apply the algorithm to your own data, you should check outexamples/real_datasets.ipynb
Package: causal-learn
causal-learn: Causal Discovery in PythonCausal-learn is a python package for causal discovery that implements both classical and state-of-the-art causal discovery algorithms, which is a Python translation and extension ofTetrad.The package is actively being developed. Feedbacks (issues, suggestions, etc.) are highly encouraged.Package OverviewOur causal-learn implements methods for causal discovery:Constraint-based causal discovery methods.Score-based causal discovery methods.Causal discovery methods based on constrained functional causal models.Hidden causal representation learning.Permutation-based causal discovery methods.Granger causality.Multiple utilities for building your own method, such as independence tests, score functions, graph operations, and evaluations.InstallCausal-learn needs the following packages to be installed beforehand:python 3 (>=3.7)numpynetworkxpandasscipyscikit-learnstatsmodelspydot(For visualization)matplotlibgraphvizTo use causal-learn, we could install it usingpip:pip install causal-learnDocumentationPlease kindly refer tocausal-learn Docfor detailed tutorials and usages.Running examplesFor search methods in causal discovery, there are various running examples in the‘tests’directory, such as TestPC.py and TestGES.py.For the implemented modules, such as (conditional) independent test methods, we provide unit tests for the convenience of developing your own methods.BenchmarksFor the convenience of our community,CMU-CLeaRgroup maintains a list of benchmark datasets including real-world scenarios and various learning tasks. Please refer to the following links:https://github.com/cmu-phil/example-causal-datasets(maintained by Joseph Ramsey)https://www.cmu.edu/dietrich/causality/projects/causal_learn_benchmarksPlease feel free to let us know if you have any recommendation regarding causal datasets with high-quality. We are grateful for any effort that benefits the development of causality community.ContributionPlease feel free to open an issue if you find anything unexpected.
And please create pull requests, perhaps after passing unittests in 'tests/', if you would like to contribute to causal-learn.
We are always targeting to make our community better!Running Tetrad in PythonAlthough causal-learn provides python implementations for some causal discovery algorithms, there are currently a lot more in the classical Java-basedTetradprogram. For users who would like to incorporate arbitrary Java code in Tetrad as part of a Python workflow, we strongly recommend consideringpy-tetrad. Here is a list ofreusable examplesof how to painlessly benefit from the most comprehensive Tetrad Java codebase.CitationPlease cite as:@article{causallearn,
  title={Causal-learn: Causal Discovery in Python},
  author={Yujia Zheng and Biwei Huang and Wei Chen and Joseph Ramsey and Mingming Gong and Ruichu Cai and Shohei Shimizu and Peter Spirtes and Kun Zhang},
  journal={arXiv preprint arXiv:2307.16405},
  year={2023}
}
Package: causalmodels
causalmodels in Python.instalation$ pip install causalmodelsusage>>> import numpy as np
>>> import pandas as pd
>>> import causalmodels as cm
>>> a = np.random.laplace(size=500)
>>> b = np.random.laplace(size=500) + a
>>> c = np.random.laplace(size=500) + a + b
>>> data = pd.DataFrame({'a': a, 'b': b, 'c': c})
>>> model = cm.DirectLiNGAM(data.values, data.columns)
>>> results = model.fit()
>>> results.order
[2, 1, 0]
>>> result.plot()
Package: causal-selection
This package has two interfaces:score_vocab(): Given text (T), vocab (V), outcome(s) Y, and
confound(s) (C), this method will score each element of the
vocab according to how well it explains each Y, controlling
for all of the C’s.evaluate_vocab(): Measure’s the strength of a vocab’s causal
effects on Y (controlling for C).(c) Reid Pryzant 2019https://cs.stanford.edu/~rpryzant/May be used and distributed under the MIT license.