项目作者: nicrie

项目描述 :
Canonical Correlation Analysis in Python
高级语言: Python
项目地址: git://github.com/nicrie/pycca.git
创建时间: 2020-07-08T16:00:48Z
项目社区:https://github.com/nicrie/pycca

开源协议:GNU General Public License v3.0

下载


Warning: This package is no longer actively maintained. Please use xeofs instead.

xMCA | Maximum Covariance Analysis in Python

version
GitHub Workflow Status
Documentation Status
codecov.io
downloads
DOI

The aim of this package is to provide a flexible tool for the climate science community to perform Maximum Covariance Analysis (MCA) in a simple and consistent way. Given the huge popularity of xarray in the climate science community, xmca supports xarray.DataArray as well as numpy.ndarray as input formats.

Example Figure
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 the lecture material written by C. Bretherton.

:star: New in release 1.4.x

  • Much faster and more memory-efficient algorithm
  • Significance testing of individual modes via
    • Rule N ([Overland & Preisendorfer 1982][ruleN])
    • Bootstrapping/permutation schemes + block-wise approach for autocorrelated data
    • Iterative permutation (Winkler et al. 2020)
  • Period parameter of solve method provides more flexibility to exponential extension, making complex MCA more stable
  • Fixed missing coslat weighting when saving a model (Issue 25)

:pushpin: Core Features

Standard Rotated Complex Complex Rotated
EOF 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 on arXiv.*

:wrench: Installation

Installation is simply done via

  1. pip install xmca

If you have problems during the installation please consult the documentation or raise an issue here on Github.

:newspaper: Documentation

A tutorial to get you started as well as the full API can be found in the documentation.

:zap: Quickstart

Import the package

  1. from xmca.array import MCA # use with np.ndarray
  2. from xmca.xarray import xMCA # use with xr.DataArray

As an example, we take North American surface temperatures shipped with
xarray. Note: only works with xr.DataArray, not xr.Dataset.

  1. import xarray as xr # only needed to obtain test data
  2. # split data arbitrarily into west and east coast
  3. data = xr.tutorial.open_dataset('air_temperature').air
  4. west = data.sel(lon=slice(200, 260))
  5. east = data.sel(lon=slice(260, 360))

PCA / EOF analysis

Construct a model with only one field and solve it to perform standard PCA /
EOF analysis.

  1. pca = xMCA(west) # PCA of west coast
  2. pca.solve(complexify=False) # True for complex PCA
  3. svals = pca.singular_values() # singular vales = eigenvalues for PCA
  4. expvar = pca.explained_variance() # explained variance
  5. pcs = pca.pcs() # Principal component scores (PCs)
  6. eofs = pca.eofs() # spatial patterns (EOFs)

Obtaining a Varimax/Promax-rotated solution 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=1 equals a Varimax-rotated solution.

  1. pca.rotate(n_rot=10, power=1)
  2. expvar_rot = pca.explained_variance() # explained variance
  3. pcs_rot = pca.pcs() # Principal component scores (PCs)
  4. eofs_rot = pca.eofs() # spatial patterns (EOFs)

MCA

Same as for PCA / EOF analysis, but with two input fields instead of
one.

  1. mca = xMCA(west, east) # MCA of field A and B
  2. mca.solve(complexify=False) # True for complex MCA
  3. eigenvalues = mca.singular_values() # singular vales
  4. pcs = mca.pcs() # expansion coefficient (PCs)
  5. eofs = mca.eofs() # spatial patterns (EOFs)

Significance analysis

A simple way of estimating the significance of the obtained modes is by
running Monte Carlo simulations based on uncorrelated Gaussian white
noise known as Rule 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.

  1. surr = mca.rule_n(200)
  2. median = surr.median('run')
  3. q99 = surr.quantile(.99, dim='run')
  4. q01 = surr.quantile(.01, dim='run')
  5. cutoff = np.sum((svals - q99 > 0)).values # first 8 modes significant
  6. fig = plt.figure(figsize=(10, 4))
  7. ax = fig.add_subplot(111)
  8. svals.plot(ax=ax, yscale='log', label='true')
  9. median.plot(ax=ax, yscale='log', color='.5', label='rule N')
  10. q99.plot(ax=ax, yscale='log', color='.5', ls=':')
  11. q01.plot(ax=ax, yscale='log', color='.5', ls=':')
  12. ax.axvline(cutoff + 0.5, ls=':')
  13. ax.set_xlim(-2, 200)
  14. ax.set_ylim(1e-1, 2.5e4)
  15. ax.set_title('Significance based on Rule N')
  16. ax.legend()

Example Figure Mode1
The first 8 modes are significant according to rule N using 200 synthetic runs.

Saving/loading an analysis

  1. mca.save_analysis('my_analysis') # this will save the data and a respective
  2. # info file. The files will be stored in a
  3. # special directory
  4. mca2 = xMCA() # create a new, empty instance
  5. mca2.load_analysis('my_analysis/info.xmca') # analysis can be
  6. # loaded via specifying the path to the
  7. # info file created earlier

Quickly inspect your results visually

The package provides a method to plot individual modes.

  1. mca2.set_field_names('West', 'East')
  2. pkwargs = {'orientation' : 'vertical'}
  3. mca2.plot(mode=1, **pkwargs)

Example Figure Mode1
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:

  1. from cartopy.crs import EqualEarth # for different map projections
  2. # map projections for "left" and "right" field
  3. projections = {
  4. 'left': EqualEarth(),
  5. 'right': EqualEarth()
  6. }
  7. pkwargs = {
  8. "figsize" : (8, 5),
  9. "orientation" : 'vertical',
  10. 'cmap_eof' : 'BrBG', # colormap amplitude
  11. "projection" : projections,
  12. }
  13. mca2.plot(mode=3, **pkwargs)

Example Figure Mode 3

You can save the plot to your local disk as a .png file via

  1. skwargs={'dpi':200}
  2. mca2.save_plot(mode=3, plot_kwargs=pkwargs, save_kwargs=skwargs)

:bookmark: Please cite

I 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 on Github, via email, or as a citation:

Niclas Rieger, 2021: nicrie/xmca: version x.y.z. doi:10.5281/zenodo.4749830.

:muscle: Credits

Kudos to the developers and contributors of the following Github projects which I initially used myself and used as an inspiration:

And of course credits to the developers of the extremely useful packages

[ruleN]: https://doi.org/10.1175/1520-0493(1982)110<0001:ASTFPC>2.0.CO;2