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 details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

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

Uploaded Python 3

File details

Details for the file xmca-0.2.0.post25.tar.gz.

File metadata

  • Download URL: xmca-0.2.0.post25.tar.gz
  • Upload date:
  • Size: 26.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/3.7.3 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.7.10

File hashes

Hashes for xmca-0.2.0.post25.tar.gz
Algorithm Hash digest
SHA256 f51cacadd80b7faf8c84a51451f500de6146fc60022d1183d1ff24076d0732d9
MD5 977e4f0e7640f522561c3357d3c31034
BLAKE2b-256 86855fa00cde8e84c4013a012cd530c96076bfd6fb8e8ae4e4324e8a5106c659

See more details on using hashes here.

File details

Details for the file xmca-0.2.0.post25-py3-none-any.whl.

File metadata

  • Download URL: xmca-0.2.0.post25-py3-none-any.whl
  • Upload date:
  • Size: 30.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.1 importlib_metadata/3.7.3 pkginfo/1.7.0 requests/2.25.1 requests-toolbelt/0.9.1 tqdm/4.59.0 CPython/3.7.10

File hashes

Hashes for xmca-0.2.0.post25-py3-none-any.whl
Algorithm Hash digest
SHA256 393f0415741c47daf38c357e124b72fbb14e896f85eb73ca42f9106e01f804c9
MD5 153bbfa9a16c01ecba9355b5fc818c86
BLAKE2b-256 3170dc9f4f60d4146a33b8e798bbdd428be5948b819a1e567f4b86f340c4eafc

See more details on using hashes here.

Supported by

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