Package: psmpy
PsmPyMatching techniques for epidemiological observational studies as carried out in Python. Propensity score matching is a statistical matching technique   used   with   observational   data   that   attempts   to ascertain the validity of concluding there is a potential causal link between a treatment or intervention and an outcome(s) of interest. It does so by accounting for a set of covariates between a binary treatment state (as would occur in a randomized control trial, either received the intervention or not), and control for potential confounding (covariates) in outcome measures between the treatment and control groups such as death, or length of stay etc. It is using this technique on observational data that we gain an insight into the effects or lack thereof of an interventional state.Citing this work:A. Kline and Y. Luo,PsmPy: A Package for Retrospective Cohort Matching in Python,2022 44th Annual International Conference of the IEEE Engineering in Medicine & Biology Society (EMBC), 2022, pp. 1354-1357, doi: 10.1109/EMBC48229.2022.9871333.Integration with Jupyter NotebooksAdditional plotting functionality to assess balance before and afterA more modular, user-specified matching processAbility to define 1:1 or 1:many matchingInstallationInstall the package through pip:$pipinstallpsmpyInstallationData PreparationPredict ScoresMatching algorithmGraphical OutputsExtra AttributesCohen D FunctionConclusionData PrepImport psmpy class and functions# import relevant librariesfrompsmpyimportPsmPyfrompsmpy.functionsimportcohenDfrompsmpy.plottingimport*sns.set(rc={'figure.figsize':(10,8)},font_scale=1.3)# read in your datadata=pd.read_csv(path)Initialize PsmPy ClassInitialize thePsmPyclass:psm=PsmPy(df,treatment='treatment',indx='pat_id',exclude=[])Note:PsmPy- The class. It will use all covariates in the dataset unless formally excluded in theexcludeargument.df- the dataframe being passed to the classexclude- (optional) parameter and will ignore any covariates (columns) passed to the it during the model fitting process. This will be a list of strings. Note, it is not necessary to pass the unique index column here. That process will be taken care of within the code after specifying your index column.indx- required parameter that references a unique ID number for each case in the dataset.Predict ScoresCalculate logistic propensity scores/logits:psm.logistic_ps(balance=True)Note:balance- Whether the logistic regression will run in a balanced fashion, default = True.There often exists a significantClass Imbalancein the data. This will be detected automatically in the software where the majority group has more records than the minority group. We account for this by settingbalance=Truewhen callingpsm.logistic_ps(). This tellsPsmPyto sample from the majority group when fitting the logistic regression model so that the groups are of equal size. This process is repeated until all the entries of the major class have been regressed on the minor class in equal paritions. This calculates both the logistic propensity scores and logits for each entry.Review values in dataframe:psm.predicted_dataMatching algorithm - version 1Perform KNN matching.psm.knn_matched(matcher='propensity_logit',replacement=False,caliper=None,drop_unmatched=True)Note:matcher-propensity_logit(default) and generated inprevious  step  alternative  option  ispropensity_score, specifies the argument on which matching will proceedreplacement-False(default),   determines   whethermacthing  will  happen  with  or  without  replacement,when replacement is false matching happens 1:1caliper-None(default), user can specify caliper size relative  to  std.  dev  of  the  control  sample,  restricting neighbors eligible to match within a certain distance.drop_unmatched-True(default) In the event that indexes do not have a match due to caliper size it will remove them from the 'matched_df', 'matched_ids' and subsequent calculations of effect sizeMatching algorithm - version 2Perform KNN matching 1:manypsm.knn_matched_12n(matcher='propensity_logit',how_many=1)Note:matcher-propensity_logit(default) and generated inprevious  step  alternative  option  ispropensity_score, specifies the argument on which matching will proceedhow_many-1(default) performs 1:n matching, where 'n' is specified by the user and matched the minor class 'n' times to the major classGraphical OutputsPlot the propensity score or propensity logitsPlot the distribution of the propensity scores (or logits) for the two groups side by side. Note that here the names are coded as 'treatment' and 'control' under the assumption that the majority class you are sampling from is the control group. If this is not the case you will need to flip the order of these.psm.plot_match(Title='Side by side matched controls',Ylabel='Number ofpatients',Xlabel='Propensity logit',names=['treatment','control'],colors=['#E69F00','#56B4E9'],save=True)Note:title-    'Side   by   side   matched   controls' (default),creates plot titleYlabel-  'Number  of  patients'  (default),  string,  labelfor y-axisXlabel-  'Propensity logit' (default), string, label for x-axisnames- ['treatment', 'control'] (default), list of strings for legendcolors- ['#E69F00', '#56B4E9'] (default) plotting colors defaultsave-  False  (default),  saves  the  figure  generated  to current working directory if TruePlot the effect sizespsm.effect_size_plot(title='Standardized Mean differences accross covariates before and after matching',before_color='#FCB754',after_color='#3EC8FB',save=False)Note:title- Title of the plotbefore_color- color (hex) for before matching effect sizeafter_color- color (hex) for after macthing effect sizesave-  False  (default),  saves  the  figure  generated  tocurrent working directory if TrueExtra AttributesOther attributes available to user:Matched IDspsm.matched_idsmatched_ids- returns  a  dataframe  of  indicies from  the  minor  class  and  their  associated  matched indice from the major class psm.Major_IDMinor_ID6781943232647624Note:That not all matches will be unique ifreplacement=FalseMatched Dataframepsm.df_matcheddf_matched- returns a subset of the original dataframe using indices that were matched. This works regardless of which matching protocol is used.Effect sizes per variablepsm.effect_sizeeffect_size- returns  dataframe  with  columns 'variable', 'matching' (before or after), and 'effect_size'variablematchingeffect_sizehypertensionbefore0.5hypertensionafter0.01age76249432age76249432sex76249432Note:The thresholds for a small, medium and large effect size were characterizedby Cohen in: J. Cohen, "A Power Primer", Quantitative Methods in Psychology, vol.111, no. 1, pp. 155-159, 1992Relative SizeEffect Sizesmall≤ 0.2medium≤ 0.5large≤0.8Cohen D FunctionA function to calculate effect size (Cohen D) can be imported alone should the user have a need for it. A floating point number is returned. This floating point number represents the effect size of a variable on a binary outcome.frompsmpy.functionsimportcohenDcohenD(df,treatment,metricName)df- dataframe with data under investigationtreatment- name of binary treatment/intervention under investigationmetricName- variable user wishes to check the influence of on treatment/interventionConclusionThis package offers a user friendly propensity score matching protocol created for a Python environment. In this we have tried to capture automatic figure generation, contextualization of the results and flexibility in the matching and modeling protocol to serve a wide base.