Package: xmca
xMCA | Maximum Covariance Analysis in PythonThe aim of this package is to provide a flexible tool for the climate science community to performMaximum Covariance Analysis (MCA)in a simple and consistent way. Given the huge popularity ofxarrayin the climate science community,xmcasupportsxarray.DataArrayas well asnumpy.ndarrayas input formats.Mode 2 of complex rotated Maximum Covariance Analysis showing the shared dynamics of SST and continental precipitation associated to ENSO between 1980 and 2020.:beginner: What is MCA?MCA maximises the temporal covariance between two different
data fields and is closely related to Principal Component Analysis (PCA) / Empirical
Orthogonal Function analysis (EOF analysis). While EOF analysis maximises the variance within a single data
field, MCA allows to extract the dominant co-varying patterns between two different data
fields. When the two input fields are the same, MCA reduces to standard EOF analysis.For the mathematical understanding please have a look at e.g.Bretherton et al.or thelecture materialwritten by C. Bretherton.:star: New in release 1.4.xMuch faster and more memory-efficient algorithmSignificance testing of individual modes viaRule N(Overland & Preisendorfer 1982)Bootstrapping/permutation schemes + block-wise approach for autocorrelated dataIterative permutation (Winkler et al. 2020)Period parameter ofsolvemethod provides more flexibility to exponential extension, making complex MCA more stableFixed missing coslat weighting when saving a model (Issue 25):pushpin: Core FeaturesStandardRotatedComplexComplex RotatedEOF analysis:heavy_check_mark::heavy_check_mark::heavy_check_mark::heavy_check_mark:MCA:heavy_check_mark::heavy_check_mark::heavy_check_mark::heavy_check_mark:*click on check marks for reference**Complex rotated MCA is also available as a pre-print onarXiv.:wrench: InstallationInstallation is simply done viapip install xmcaIf you have problems during the installation please consult the documentation or raise an issue here on Github.:newspaper: DocumentationA tutorial to get you started as well as the full API can be found in thedocumentation.:zap: QuickstartImport the packagefromxmca.arrayimportMCA# use with np.ndarrayfromxmca.xarrayimportxMCA# use with xr.DataArrayAs an example, we take North American surface temperatures shipped withxarray.Note: only works withxr.DataArray, notxr.Dataset.importxarrayasxr# only needed to obtain test data# split data arbitrarily into west and east coastdata=xr.tutorial.open_dataset('air_temperature').airwest=data.sel(lon=slice(200,260))east=data.sel(lon=slice(260,360))PCA / EOF analysisConstruct a model with only one field and solve it to perform standard PCA /
EOF analysis.pca=xMCA(west)# PCA of west coastpca.solve(complexify=False)# True for complex PCAsvals=pca.singular_values()# singular vales = eigenvalues for PCAexpvar=pca.explained_variance()# explained variancepcs=pca.pcs()# Principal component scores (PCs)eofs=pca.eofs()# spatial patterns (EOFs)Obtaining aVarimax/Promax-rotatedsolution can be achieved by rotating
the model choosing the number of EOFs to be rotated (n_rot) as well as the
Promax parameter (power). Here,power=1equals a Varimax-rotated solution.pca.rotate(n_rot=10,power=1)expvar_rot=pca.explained_variance()# explained variancepcs_rot=pca.pcs()# Principal component scores (PCs)eofs_rot=pca.eofs()# spatial patterns (EOFs)MCASame as for PCA / EOF analysis, but with two input fields instead of
one.mca=xMCA(west,east)# MCA of field A and Bmca.solve(complexify=False)# True for complex MCAeigenvalues=mca.singular_values()# singular valespcs=mca.pcs()# expansion coefficient (PCs)eofs=mca.eofs()# spatial patterns (EOFs)Significance analysisA simple way of estimating the significance of the obtained modes is by
running Monte Carlo simulations based on uncorrelated Gaussian white
noise known asRule N(Overland and Preisendorfer 1982). Here we create 200 of such synthetic data sets and compare the synthetic with the real singular spectrum to assess significance.surr=mca.rule_n(200)median=surr.median('run')q99=surr.quantile(.99,dim='run')q01=surr.quantile(.01,dim='run')cutoff=np.sum((svals-q99>0)).values# first 8 modes significantfig=plt.figure(figsize=(10,4))ax=fig.add_subplot(111)svals.plot(ax=ax,yscale='log',label='true')median.plot(ax=ax,yscale='log',color='.5',label='rule N')q99.plot(ax=ax,yscale='log',color='.5',ls=':')q01.plot(ax=ax,yscale='log',color='.5',ls=':')ax.axvline(cutoff+0.5,ls=':')ax.set_xlim(-2,200)ax.set_ylim(1e-1,2.5e4)ax.set_title('Significance based on Rule N')ax.legend()The first 8 modes are significant according to rule N using 200 synthetic runs.Saving/loading an analysismca.save_analysis('my_analysis')# this will save the data and a respective# info file. The files will be stored in a# special directorymca2=xMCA()# create a new, empty instancemca2.load_analysis('my_analysis/info.xmca')# analysis can be# loaded via specifying the path to the# info file created earlierQuickly inspect your results visuallyThe package provides a method to plot individual modes.mca2.set_field_names('West','East')pkwargs={'orientation':'vertical'}mca2.plot(mode=1,**pkwargs)Result of default plot method after performing MCA on T2m of North American west and east coast showing mode 1.You may want to modify the plot for some better optics:fromcartopy.crsimportEqualEarth# for different map projections# map projections for "left" and "right" fieldprojections={'left':EqualEarth(),'right':EqualEarth()}pkwargs={"figsize":(8,5),"orientation":'vertical','cmap_eof':'BrBG',# colormap amplitude"projection":projections,}mca2.plot(mode=3,**pkwargs)You can save the plot to your local disk as a.pngfile viaskwargs={'dpi':200}mca2.save_plot(mode=3,plot_kwargs=pkwargs,save_kwargs=skwargs):bookmark: Please citeI am just starting my career as a scientist. Feedback on my scientific work is therefore important to me in order to assess which of my work advances the scientific community. As such, if you use the package for your own research and find it helpful, I would appreciate feedback here onGithub, viaemail, or as acitation:Niclas Rieger, 2021: nicrie/xmca: version x.y.z. doi:10.5281/zenodo.4749830.:muscle: CreditsKudos to the developers and contributors of the following Github projects which I initially used myself and used as an inspiration:ajdawson/eofsYefee/xMCAAnd of course credits to the developers of the extremely useful packagesxarraycartopy