Skip to main content

Maximum Covariance Analysis in Python

Project description

xMCA | Maximum Covariance Analysis in Python

version CircleCI downloads

Maximum Covariance Analysis (MCA) maximises the temporal covariance between two different data fields and is closely related to Principal Component Analysis (PCA) / Empirical Orthogonal Function (EOF) analysis, which maximises the variance within a single data field. MCA allows to extract the dominant co-varying patterns between two different data fields.

The module xmca works with numpy.ndarray and xarray.DataArray as input fields.

Installation

pip install xmca

Dependencies

The file requirements.txt lists all the dependencies. For automatic installation, you may want to clone and run

pip install -r requirements.txt

Known Issues

The dependencies of cartopy themselves are not installed via pip which is why the setup will fail if some dependencies are not met. In this case, please install cartopy first before installing xmca.

Testing

After cloning the repository

python -m unittest discover -v -s tests/

Core Features

  • Standard PCA/MCA
  • Rotated PCA/MCA
  • Complex PCA/MCA (also known as Hilbert EOF analysis)
  • normalization of input data
  • latitude correction to compensate for stretched areas in higher latitutes

Getting started

Import the module for xarray via

from xmca.xarray import xMCA

Create some dummy data, which should be of type xr.DataArray.

import numpy as np
import xarray as xr

t = 300                 # number of time steps
lat1, lon1 = 20, 30     # number of latitudes/longitudes of field A
lat2, lon2 = 15, 10     # number of latitudes/longitudes of field B
A = xr.DataArray(np.random.randn(t,lat1,lon1)) # dummy field A
B = xr.DataArray(np.random.randn(t,lat1,lon2)) # dummy field B

Principal Component Analysis

pca = xMCA(A)                       # PCA on field A
pca.solve(complexfify=False)        # True for complex PCA
#pca.rotate(10)                     # optional; Varimax rotated solution
                                    # using 10 first EOFs
eigenvalues = pca.singular_values() # singular vales = eigenvalues for PCA
pcs         = pca.pcs()             # Principal component scores (PCs)
eofs        = pca.eofs()            # spatial patterns (EOFs)

Maximum Covariance Analysis

mca = xMCA(A,B)                     # MCA of field A and B
mca.solve(complexfify=False)        # True for complex MCA
#mca.rotate(10)                     # optional; Varimax rotated solution
                                    # using 10 first EOFs
eigenvalues = mca.singular_values() # singular vales
pcs = mca.pcs()                     # expansion coefficient (PCs)
eofs = mca.eofs()                   # spatial patterns (EOFs)

Save/load an analysis

mca.save_analysis()                 # this will save the data and a respective
                                    # info file. The files will be stored in a
                                    # special directory
mca2 = xMCA()                       # create a new, empty instance
mca2.load_analysis('./mca/left_right/mca_c0_r00_p00.info') # analysis can be
                                    # loaded via specifying the path to the
                                    # info file created earlier
mca2.plot(mode=1)

Plot your results

The package provides a method to visually inspect the individual modes, e.g. for mode 2.

Note: The following plots use real data (ERA5 SST & precipitation) instead of the toy data shown at the beginning of the tutorial. Apart from that the figures show exactly what is produced by calling the convenience plotting method.

mca2.set_field_names('SST', 'Precipitation')  # add variable names, optional
mca2.plot(mode=2)

example-plot1

You may want to modify the plot for some better optics:

import cartopy.crs as ccrs  # for different map projections

# map projections for "left" and "right" field
projections = {
    'left': ccrs.EqualEarth(central_longitude=200),
    'right': ccrs.EqualEarth(central_longitude=160)
}

plot_kwargs = {
    "figsize"     : (8, 5),
    "threshold"   : 0.25,       # mask out values < 0.25 max-normalised amplitude
    "orientation" : 'vertical',
    'cmap_eof'    : 'viridis',  # colormap amplitude
    'cmap_phase'  : 'twilight', # colormap phase
    "phase_shift" : 2.2,        # apply phase shift to PCs
    "projection"  : projections,
}
mca2.plot(mode=2, **plot_kwargs)

example-plot2

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

save_kwargs={'dpi':200, 'transparent':True}
mca2.save_plot(mode=2, plot_kwargs=plot_kwargs, save_kwargs=save_kwargs)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

xmca-0.2.0.post25.tar.gz (26.1 kB view hashes)

Uploaded Source

Built Distribution

xmca-0.2.0.post25-py3-none-any.whl (30.0 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page