Skip to content

Spatial-Temporal Experiment

In this notebook, I will be walking through how we can estimate different methods based on the density cubes that we derive.

import sys
from pyprojroot import here
sys.path.append(str(here()))

import numpy as np
import pathlib
import xarray as xr
import holoviews as hv
import geoviews as gv
import geoviews.feature as gf

from geoviews import opts
from cartopy import crs as ccrs

gv.extension('matplotlib', 'bokeh')
gv.output(size=200)
import sys, os
from pyprojroot import here
root = here(project_files=[".here"])
sys.path.append(str(here()))

import pathlib

# standard python packages
import xarray as xr
import pandas as pd
import numpy as np

# 
# Experiment Functions
from src.data.esdc import get_dataset
from src.features import Metrics
from sklearn.preprocessing import StandardScaler
from src.models.density import get_rbig_model
from src.features.temporal import select_period, get_smoke_test_time, TimePeriod
from src.features.spatial import select_region, get_europe, get_spain
from src.models.train_models import get_similarity_scores
from src.experiments.utils import dict_product, run_parallel_step

from src.features import Metrics
from src.features.density import get_density_cubes
from src.features.preprocessing import standardizer_data, get_reference_cube, get_common_indices
from src.models.similarity import cka_coefficient, rv_coefficient, rbig_it_measures

# # esdc tools
# from src.esdc.subset import select_pixel
# from src.esdc.shape import ShapeFileExtract, rasterize
# from esdc.transform import DensityCubes

from typing import List, Dict
import xarray as xr

from tqdm import tqdm
import time

import cartopy
import cartopy.crs as ccrs

# NUMPY SETTINGS
import numpy as onp
onp.set_printoptions(precision=3, suppress=True)

# MATPLOTLIB Settings
import matplotlib as mpl
import matplotlib.pyplot as plt
# %matplotlib inline
# %config InlineBackend.figure_format = 'retina'

# GEOVIEWS
import holoviews as hv
import geoviews as gv
import geoviews.feature as gf
from cartopy import crs
from geoviews import opts
gv.extension('matplotlib')
gv.output(size=150)

# SEABORN SETTINGS
import seaborn as sns
sns.set_context(context='talk',font_scale=0.7)
# sns.set(rc={'figure.figsize': (12, 9.)})
# sns.set_style("whitegrid")

# PANDAS SETTINGS
import pandas as pd
pd.set_option("display.max_rows", 120)
pd.set_option("display.max_columns", 120)

# LOGGING SETTINGS
import sys
import logging
logging.basicConfig(
    level=logging.INFO, 
    stream=sys.stdout,
    format='%(asctime)s: %(levelname)s: %(message)s'
)
logger = logging.getLogger()
#logger.setLevel(logging.INFO)

import warnings
warnings.simplefilter("ignore")

%load_ext autoreload
%autoreload 2
The autoreload extension is already loaded. To reload it, use:
  %reload_ext autoreload
## Results
RES_PATH = pathlib.Path(str(here())).joinpath("data/spa_temp/info_earth")
FIG_PATH = pathlib.Path(str(here())).joinpath("reports/figures/spa_temp/demos/infoearth/spain")
!ls $RES_PATH/probs
europe_gpp_2002_2010_v0_s200000_d111.csv
europe_gpp_2010_v0_s200000_d111.csv
gpp_spain_vgpp_r2010_v0.csv
rm_spain_vrm_r2002_2010_v0.csv
rm_spain_vrm_r2010_v0.csv
spain_gpp_2002_2010_v0_222.csv
spain_gpp_2002_2010_v0_5000_222.csv
spain_gpp_2002_2010_v0_s200000_d111.csv
spain_gpp_2002_2010_v0_s200000_d113.csv
spain_gpp_2002_2010_v0_s200000_d116.csv
spain_gpp_2002_2010_v0_s200000_d222.csv
spain_gpp_2002_2010_v0_s200000_d331.csv
spain_gpp_2002_2010_v0_s200000_d333.csv
spain_vgpp_r2002_2010_v0_111.csv
spain_vrm_r2010_v0.csv
spain_vrm_r2010_v0336.csv
spain_vrm_r2010_v0_222.csv
spain_vsm_r2010_v0_222.csv
### Experiment I - Spain, 2010, Cube 1x1x1 For this first experiment, I did something very simple and looked at the density of ESDC as samples.
region = "europe"
period = "2002_2010"
samples = "200000"
dimensions = "111"
variable = 'gpp'
filename = f"{region}_{variable}_{period}_v0_s{samples}_d{dimensions}"

# read csv file
probs_df = pd.read_csv(str(RES_PATH.joinpath(f'probs/{filename}'+".csv")))

# convert to datetime
probs_df['time'] = pd.to_datetime(probs_df['time'])

# create dataframe in the format for xarray
probs_df = probs_df.set_index(['time', 'lat', 'lon']).rename(columns={"0": 'probs'})


# remove probabilities greater than 1
probs_df['probs'][probs_df['probs'] >= 1.0] = np.nan

# create xarray cubes
probs_cubes = xr.Dataset.from_dataframe(probs_df)

# resample monthly
probs_cubes = probs_cubes.resample(time='1MS').mean()

# shannon info
probs_cubes['shannon_info'] = np.log(1 / probs_cubes['probs'])

probs_cubes
/home/emmanuel/.conda/envs/rbig_eo/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice
  return np.nanmean(a, axis=axis, dtype=dtype)
Show/Hide data repr Show/Hide attributes
xarray.Dataset
    • lat: 142
    • lon: 220
    • time: 108
    • time
      (time)
      datetime64[ns]
      2002-01-01 ... 2010-12-01
      array(['2002-01-01T00:00:00.000000000', '2002-02-01T00:00:00.000000000',
             '2002-03-01T00:00:00.000000000', '2002-04-01T00:00:00.000000000',
             '2002-05-01T00:00:00.000000000', '2002-06-01T00:00:00.000000000',
             '2002-07-01T00:00:00.000000000', '2002-08-01T00:00:00.000000000',
             '2002-09-01T00:00:00.000000000', '2002-10-01T00:00:00.000000000',
             '2002-11-01T00:00:00.000000000', '2002-12-01T00:00:00.000000000',
             '2003-01-01T00:00:00.000000000', '2003-02-01T00:00:00.000000000',
             '2003-03-01T00:00:00.000000000', '2003-04-01T00:00:00.000000000',
             '2003-05-01T00:00:00.000000000', '2003-06-01T00:00:00.000000000',
             '2003-07-01T00:00:00.000000000', '2003-08-01T00:00:00.000000000',
             '2003-09-01T00:00:00.000000000', '2003-10-01T00:00:00.000000000',
             '2003-11-01T00:00:00.000000000', '2003-12-01T00:00:00.000000000',
             '2004-01-01T00:00:00.000000000', '2004-02-01T00:00:00.000000000',
             '2004-03-01T00:00:00.000000000', '2004-04-01T00:00:00.000000000',
             '2004-05-01T00:00:00.000000000', '2004-06-01T00:00:00.000000000',
             '2004-07-01T00:00:00.000000000', '2004-08-01T00:00:00.000000000',
             '2004-09-01T00:00:00.000000000', '2004-10-01T00:00:00.000000000',
             '2004-11-01T00:00:00.000000000', '2004-12-01T00:00:00.000000000',
             '2005-01-01T00:00:00.000000000', '2005-02-01T00:00:00.000000000',
             '2005-03-01T00:00:00.000000000', '2005-04-01T00:00:00.000000000',
             '2005-05-01T00:00:00.000000000', '2005-06-01T00:00:00.000000000',
             '2005-07-01T00:00:00.000000000', '2005-08-01T00:00:00.000000000',
             '2005-09-01T00:00:00.000000000', '2005-10-01T00:00:00.000000000',
             '2005-11-01T00:00:00.000000000', '2005-12-01T00:00:00.000000000',
             '2006-01-01T00:00:00.000000000', '2006-02-01T00:00:00.000000000',
             '2006-03-01T00:00:00.000000000', '2006-04-01T00:00:00.000000000',
             '2006-05-01T00:00:00.000000000', '2006-06-01T00:00:00.000000000',
             '2006-07-01T00:00:00.000000000', '2006-08-01T00:00:00.000000000',
             '2006-09-01T00:00:00.000000000', '2006-10-01T00:00:00.000000000',
             '2006-11-01T00:00:00.000000000', '2006-12-01T00:00:00.000000000',
             '2007-01-01T00:00:00.000000000', '2007-02-01T00:00:00.000000000',
             '2007-03-01T00:00:00.000000000', '2007-04-01T00:00:00.000000000',
             '2007-05-01T00:00:00.000000000', '2007-06-01T00:00:00.000000000',
             '2007-07-01T00:00:00.000000000', '2007-08-01T00:00:00.000000000',
             '2007-09-01T00:00:00.000000000', '2007-10-01T00:00:00.000000000',
             '2007-11-01T00:00:00.000000000', '2007-12-01T00:00:00.000000000',
             '2008-01-01T00:00:00.000000000', '2008-02-01T00:00:00.000000000',
             '2008-03-01T00:00:00.000000000', '2008-04-01T00:00:00.000000000',
             '2008-05-01T00:00:00.000000000', '2008-06-01T00:00:00.000000000',
             '2008-07-01T00:00:00.000000000', '2008-08-01T00:00:00.000000000',
             '2008-09-01T00:00:00.000000000', '2008-10-01T00:00:00.000000000',
             '2008-11-01T00:00:00.000000000', '2008-12-01T00:00:00.000000000',
             '2009-01-01T00:00:00.000000000', '2009-02-01T00:00:00.000000000',
             '2009-03-01T00:00:00.000000000', '2009-04-01T00:00:00.000000000',
             '2009-05-01T00:00:00.000000000', '2009-06-01T00:00:00.000000000',
             '2009-07-01T00:00:00.000000000', '2009-08-01T00:00:00.000000000',
             '2009-09-01T00:00:00.000000000', '2009-10-01T00:00:00.000000000',
             '2009-11-01T00:00:00.000000000', '2009-12-01T00:00:00.000000000',
             '2010-01-01T00:00:00.000000000', '2010-02-01T00:00:00.000000000',
             '2010-03-01T00:00:00.000000000', '2010-04-01T00:00:00.000000000',
             '2010-05-01T00:00:00.000000000', '2010-06-01T00:00:00.000000000',
             '2010-07-01T00:00:00.000000000', '2010-08-01T00:00:00.000000000',
             '2010-09-01T00:00:00.000000000', '2010-10-01T00:00:00.000000000',
             '2010-11-01T00:00:00.000000000', '2010-12-01T00:00:00.000000000'],
            dtype='datetime64[ns]')
    • lon
      (lon)
      float64
      -17.88 -17.62 ... 39.62 39.88
      array([-17.875, -17.625, -17.375, ...,  39.375,  39.625,  39.875])
    • lat
      (lat)
      float64
      35.88 36.12 36.38 ... 70.88 71.12
      array([35.875, 36.125, 36.375, 36.625, 36.875, 37.125, 37.375, 37.625, 37.875,
             38.125, 38.375, 38.625, 38.875, 39.125, 39.375, 39.625, 39.875, 40.125,
             40.375, 40.625, 40.875, 41.125, 41.375, 41.625, 41.875, 42.125, 42.375,
             42.625, 42.875, 43.125, 43.375, 43.625, 43.875, 44.125, 44.375, 44.625,
             44.875, 45.125, 45.375, 45.625, 45.875, 46.125, 46.375, 46.625, 46.875,
             47.125, 47.375, 47.625, 47.875, 48.125, 48.375, 48.625, 48.875, 49.125,
             49.375, 49.625, 49.875, 50.125, 50.375, 50.625, 50.875, 51.125, 51.375,
             51.625, 51.875, 52.125, 52.375, 52.625, 52.875, 53.125, 53.375, 53.625,
             53.875, 54.125, 54.375, 54.625, 54.875, 55.125, 55.375, 55.625, 55.875,
             56.125, 56.375, 56.625, 56.875, 57.125, 57.375, 57.625, 57.875, 58.125,
             58.375, 58.625, 58.875, 59.125, 59.375, 59.625, 59.875, 60.125, 60.375,
             60.625, 60.875, 61.125, 61.375, 61.625, 61.875, 62.125, 62.375, 62.625,
             62.875, 63.125, 63.375, 63.625, 63.875, 64.125, 64.375, 64.625, 64.875,
             65.125, 65.375, 65.625, 65.875, 66.125, 66.375, 66.625, 66.875, 67.125,
             67.375, 67.625, 67.875, 68.125, 68.375, 68.625, 68.875, 69.125, 69.375,
             69.625, 69.875, 70.125, 70.375, 70.625, 70.875, 71.125])
    • probs
      (time, lat, lon)
      float64
      nan nan nan nan ... nan nan nan nan
      array([[[       nan,        nan,        nan, ..., 0.57288113,
               0.61084716, 0.47756488],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 0.52151268],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]],
      
             [[       nan,        nan,        nan, ..., 0.37416079,
               0.405819  , 0.31461894],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 0.38118546],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]],
      
             [[       nan,        nan,        nan, ..., 0.27152267,
               0.28039287, 0.23067921],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 0.26529173],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]],
      
             ...,
      
             [[       nan,        nan,        nan, ..., 0.31224139,
               0.27931834, 0.38838262],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 0.35469821],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]],
      
             [[       nan,        nan,        nan, ..., 0.44312263,
               0.43753239, 0.46795105],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 0.40673681],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]],
      
             [[       nan,        nan,        nan, ..., 0.47562021,
               0.54471721, 0.4929582 ],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 0.49287461],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]]])
    • shannon_info
      (time, lat, lon)
      float64
      nan nan nan nan ... nan nan nan nan
      array([[[       nan,        nan,        nan, ..., 0.55707703,
               0.49290849, 0.73905526],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 0.6510217 ],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]],
      
             [[       nan,        nan,        nan, ..., 0.98306966,
               0.90184804, 1.15639309],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 0.96446925],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]],
      
             [[       nan,        nan,        nan, ..., 1.30370966,
               1.27156357, 1.46672724],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 1.3269252 ],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]],
      
             ...,
      
             [[       nan,        nan,        nan, ..., 1.16397872,
               1.27540313, 0.94576428],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 1.03648796],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]],
      
             [[       nan,        nan,        nan, ..., 0.81390872,
               0.82660454, 0.75939157],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 0.89958897],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]],
      
             [[       nan,        nan,        nan, ..., 0.74313562,
               0.6074885 , 0.7073309 ],
              [       nan,        nan,        nan, ...,        nan,
                      nan, 0.70750047],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              ...,
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan],
              [       nan,        nan,        nan, ...,        nan,
                      nan,        nan]]])
### Figure I - Probability Estimates
kdims = ['time', 'lon', 'lat']
vdims = ['shannon_info']

sub_cube = probs_cubes#.resample(time='1MS').mean()

xr_dataset = gv.Dataset(sub_cube.sel(time=slice('2010','2010')), kdims=kdims, vdims=vdims)

qmesh = xr_dataset.to(gv.QuadMesh, ["lon", "lat"])
qmesh.opts(colorbar=True, cmap='Reds')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-19-a605cd744733> in <module>
      7 
      8 qmesh = xr_dataset.to(gv.QuadMesh, ["lon", "lat"])
----> 9 qmesh.opts(colorbar=True, cmap='Blues', robust=True)

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/accessors.py in pipelined_call(*args, **kwargs)
     35             if not hasattr(inst._obj, '_pipeline'):
     36                 # Wrapped object doesn't support the pipeline property
---> 37                 return __call__(*args, **kwargs)
     38 
     39             inst_pipeline = copy.copy(inst._obj. _pipeline)

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/accessors.py in __call__(self, *args, **kwargs)
    555                 param.main.warning(msg)
    556 
--> 557         return self._dispatch_opts( *args, **kwargs)
    558 
    559     def _dispatch_opts(self, *args, **kwargs):

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/accessors.py in _dispatch_opts(self, *args, **kwargs)
    561             return self._base_opts(*args, **kwargs)
    562         elif self._mode == 'holomap':
--> 563             return self._holomap_opts(*args, **kwargs)
    564         elif self._mode == 'dynamicmap':
    565             return self._dynamicmap_opts(*args, **kwargs)

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/accessors.py in _holomap_opts(self, *args, **kwargs)
    588         clone = kwargs.pop('clone', None)
    589         apply_groups, _, _ = util.deprecated_opts_signature(args, kwargs)
--> 590         data = OrderedDict([(k, v.opts(*args, **kwargs))
    591                              for k, v in self._obj.data.items()])
    592 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/accessors.py in <listcomp>(.0)
    588         clone = kwargs.pop('clone', None)
    589         apply_groups, _, _ = util.deprecated_opts_signature(args, kwargs)
--> 590         data = OrderedDict([(k, v.opts(*args, **kwargs))
    591                              for k, v in self._obj.data.items()])
    592 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/accessors.py in pipelined_call(*args, **kwargs)
     43 
     44             try:
---> 45                 result = __call__(*args, **kwargs)
     46 
     47                 if not in_method:

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/accessors.py in __call__(self, *args, **kwargs)
    555                 param.main.warning(msg)
    556 
--> 557         return self._dispatch_opts( *args, **kwargs)
    558 
    559     def _dispatch_opts(self, *args, **kwargs):

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/accessors.py in _dispatch_opts(self, *args, **kwargs)
    559     def _dispatch_opts(self, *args, **kwargs):
    560         if self._mode is None:
--> 561             return self._base_opts(*args, **kwargs)
    562         elif self._mode == 'holomap':
    563             return self._holomap_opts(*args, **kwargs)

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/accessors.py in _base_opts(self, *args, **kwargs)
    638 
    639         kwargs['clone'] = False if clone is None else clone
--> 640         return self._obj.options(*new_args, **kwargs)

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/data/__init__.py in pipelined_fn(*args, **kwargs)
    212 
    213             try:
--> 214                 result = method_fn(*args, **kwargs)
    215 
    216                 op = method_op.instance(

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/data/__init__.py in options(self, *args, **kwargs)
   1163     # will find them to wrap with pipeline support
   1164     def options(self, *args, **kwargs):
-> 1165         return super(Dataset, self).options(*args, **kwargs)
   1166     options.__doc__ = Dimensioned.options.__doc__
   1167 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/dimension.py in options(self, *args, **kwargs)
   1288             expanded_backends = opts._expand_by_backend(options, backend)
   1289         else:
-> 1290             expanded_backends = [(backend, opts._expand_options(options, backend))]
   1291 
   1292         obj = self

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/util/__init__.py in _expand_options(cls, options, backend)
    372                     valid_options += group_opts.allowed_keywords
    373                 if found: continue
--> 374                 cls._options_error(opt, objtype, backend, valid_options)
    375         return expanded
    376 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/util/__init__.py in _options_error(cls, opt, objtype, backend, valid_options)
    420                              (opt, objtype, current_backend, matches))
    421         else:
--> 422             raise ValueError('Unexpected option %r for %s type '
    423                              'across all extensions. No similar options '
    424                              'found.' % (opt, objtype))

ValueError: Unexpected option 'robust' for QuadMesh type across all extensions. No similar options found.
kdims = ['month', 'lon', 'lat']
vdims = ['probs']

sub_cube = probs_cubes.groupby('time.month').mean()

xr_dataset = gv.Dataset(sub_cube, kdims=kdims, vdims=vdims)

xr_dataset.to(gv.QuadMesh, ["lon", "lat"], dynamic=True) * gf.coastline
# qmesh 
# qmesh.opts(colorbar=True, cmap='Blues')
/home/emmanuel/.conda/envs/rbig_eo/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice
  return np.nanmean(a, axis=axis, dtype=dtype)
kdims = ['time', 'lon', 'lat']
vdims = ['probs']

sub_cube = probs_cubes#.resample(time='1MS').mean()

xr_dataset = gv.Dataset(sub_cube.sel(time=slice('2010','2010')), kdims=kdims, vdims=vdims)

temp_curve = hv.Curve(xr_dataset.reduce(['lon', 'lat'], np.mean), kdims=['time'])

temp_curve.opts(opts.Curve(aspect=2, xticks=4, xrotation=15))
kdims = ['time', 'lon', 'lat']
vdims = ['probs']

sub_cube = probs_cubes.resample(time='1MS').mean()

xr_dataset = gv.Dataset(sub_cube.sel(time=slice('2010','2010')), kdims=kdims, vdims=vdims)

xr_dataset.to(gv.QuadMesh, ["lon", "lat"])
### Figure II - Shannon Information
kdims = ['time', 'lon', 'lat']
vdims = ['shannon_info']

sub_cube = probs_cubes#.resample(time='1MS').mean()

xr_dataset = gv.Dataset(sub_cube.sel(time=slice('2010','2010')), kdims=kdims, vdims=vdims)

xr_dataset.to(gv.QuadMesh, ["lon", "lat"])

---------------------------------------------------------------------------
DataError                                 Traceback (most recent call last)
~/.conda/envs/rbig_eo/lib/python3.8/site-packages/IPython/core/formatters.py in __call__(self, obj, include, exclude)
    968 
    969             if method is not None:
--> 970                 return method(include=include, exclude=exclude)
    971             return None
    972         else:

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/dimension.py in _repr_mimebundle_(self, include, exclude)
   1302         combined and returned.
   1303         """
-> 1304         return Store.render(self)
   1305 
   1306 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/options.py in render(cls, obj)
   1393         data, metadata = {}, {}
   1394         for hook in hooks:
-> 1395             ret = hook(obj)
   1396             if ret is None:
   1397                 continue

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/ipython/display_hooks.py in pprint_display(obj)
    280     if not ip.display_formatter.formatters['text/plain'].pprint:
    281         return None
--> 282     return display(obj, raw_output=True)
    283 
    284 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/ipython/display_hooks.py in display(obj, raw_output, **kwargs)
    256     elif isinstance(obj, (HoloMap, DynamicMap)):
    257         with option_state(obj):
--> 258             output = map_display(obj)
    259     elif isinstance(obj, Plot):
    260         output = render(obj)

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/ipython/display_hooks.py in wrapped(element)
    144         try:
    145             max_frames = OutputSettings.options['max_frames']
--> 146             mimebundle = fn(element, max_frames=max_frames)
    147             if mimebundle is None:
    148                 return {}, {}

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/ipython/display_hooks.py in map_display(vmap, max_frames)
    204         return None
    205 
--> 206     return render(vmap)
    207 
    208 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/ipython/display_hooks.py in render(obj, **kwargs)
     66         renderer = renderer.instance(fig='png')
     67 
---> 68     return renderer.components(obj, **kwargs)
     69 
     70 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/plotting/renderer.py in components(self, obj, fmt, comm, **kwargs)
    374             doc = Document()
    375             with config.set(embed=embed):
--> 376                 model = plot.layout._render_model(doc, comm)
    377             if embed:
    378                 return render_model(model, comm)

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/panel/viewable.py in _render_model(self, doc, comm)
    415         if comm is None:
    416             comm = state._comm_manager.get_server_comm()
--> 417         model = self.get_root(doc, comm)
    418 
    419         if config.embed:

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/panel/viewable.py in get_root(self, doc, comm)
    640         """
    641         doc = doc or _curdoc()
--> 642         root = self._get_model(doc, comm=comm)
    643         self._preprocess(root)
    644         ref = root.ref['id']

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/panel/layout.py in _get_model(self, doc, root, parent, comm)
    118         if root is None:
    119             root = model
--> 120         objects = self._get_objects(model, [], doc, root, comm)
    121         props = dict(self._init_properties(), objects=objects)
    122         model.update(**self._process_param_change(props))

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/panel/layout.py in _get_objects(self, model, old_objects, doc, root, comm)
    108             else:
    109                 try:
--> 110                     child = pane._get_model(doc, root, model, comm)
    111                 except RerenderError:
    112                     return self._get_objects(model, current_objects[:i], doc, root, comm)

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/panel/pane/holoviews.py in _get_model(self, doc, root, parent, comm)
    225             plot = self.object
    226         else:
--> 227             plot = self._render(doc, comm, root)
    228 
    229         plot.pane = self

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/panel/pane/holoviews.py in _render(self, doc, comm, root)
    284             kwargs = {}
    285 
--> 286         return renderer.get_plot(self.object, **kwargs)
    287 
    288     def _cleanup(self, root):

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/plotting/renderer.py in get_plot(self_or_cls, obj, doc, renderer, comm, **kwargs)
    230             init_key = tuple(v if d is None else d for v, d in
    231                              zip(plot.keys[0], defaults))
--> 232             plot.update(init_key)
    233         else:
    234             plot = obj

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/plotting/mpl/plot.py in update(self, key)
    250         if len(self) == 1 and ((key == 0) or (key == self.keys[0])) and not self.drawn:
    251             return self.initialize_plot()
--> 252         return self.__getitem__(key)
    253 
    254 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/plotting/plot.py in __getitem__(self, frame)
    435         if isinstance(frame, int) and frame > len(self):
    436             self.param.warning("Showing last frame available: %d" % len(self))
--> 437         if not self.drawn: self.handles['fig'] = self.initialize_plot()
    438         if not isinstance(frame, tuple):
    439             frame = self.keys[frame]

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/plotting/mpl/plot.py in wrapper(self, *args, **kwargs)
     45     def wrapper(self, *args, **kwargs):
     46         with _rc_context(self.fig_rcparams):
---> 47             return f(self, *args, **kwargs)
     48     return wrapper
     49 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/plotting/mpl/element.py in initialize_plot(self, ranges)
    508             style['label'] = element.label
    509 
--> 510         plot_data, plot_kwargs, axis_kwargs = self.get_data(element, ranges, style)
    511 
    512         with abbreviated_exception():

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/geoviews/plotting/mpl/__init__.py in get_data(self, element, ranges, style)
    253     def get_data(self, element, ranges, style):
    254         if self._project_operation and self.geographic:
--> 255             element = self._project_operation(element, projection=self.projection)
    256         return super(GeoPlot, self).get_data(element, ranges, style)
    257 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/param/parameterized.py in __new__(class_, *args, **params)
   2810         inst = class_.instance()
   2811         inst.param._set_name(class_.__name__)
-> 2812         return inst.__call__(*args,**params)
   2813 
   2814     def __call__(self,*args,**kw):

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/operation.py in __call__(self, element, **kwargs)
    194             kwargs['streams'] = self.p.streams
    195         kwargs['per_element'] = self._per_element
--> 196         return element.apply(self, **kwargs)
    197 
    198 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/accessors.py in pipelined_call(*args, **kwargs)
     43 
     44             try:
---> 45                 result = __call__(*args, **kwargs)
     46 
     47                 if not in_method:

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/accessors.py in __call__(self, apply_function, streams, link_inputs, dynamic, per_element, **kwargs)
    196             if hasattr(apply_function, 'dynamic'):
    197                 inner_kwargs['dynamic'] = False
--> 198             return apply_function(self._obj, **inner_kwargs)
    199         elif self._obj._deep_indexable:
    200             mapped = []

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/operation.py in __call__(self, element, **kwargs)
    190             elif ((self._per_element and isinstance(element, Element)) or
    191                   (not self._per_element and isinstance(element, ViewableElement))):
--> 192                 return self._apply(element)
    193         elif 'streams' not in kwargs:
    194             kwargs['streams'] = self.p.streams

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/operation.py in _apply(self, element, key)
    130         element_pipeline = getattr(element, '_pipeline', None)
    131 
--> 132         ret = self._process(element, key)
    133         for hook in self._postprocess_hooks:
    134             ret = hook(self, ret, **kwargs)

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/geoviews/operation/projection.py in _process(self, element, key)
     38 
     39     def _process(self, element, key=None):
---> 40         return element.map(self._process_element, self.supported_types)
     41 
     42 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/data/__init__.py in pipelined_fn(*args, **kwargs)
    212 
    213             try:
--> 214                 result = method_fn(*args, **kwargs)
    215 
    216                 op = method_op.instance(

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/data/__init__.py in map(self, *args, **kwargs)
   1167 
   1168     def map(self, *args, **kwargs):
-> 1169         return super(Dataset, self).map(*args, **kwargs)
   1170     map.__doc__ = LabelledData.map.__doc__
   1171 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/dimension.py in map(self, map_fn, specs, clone)
    703             return deep_mapped
    704         else:
--> 705             return map_fn(self) if applies else self
    706 
    707 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/geoviews/operation/projection.py in _process_element(self, element)
    288 
    289         params = get_param_values(element)
--> 290         return element.clone((PX, PY, zs), crs=self.p.projection, **params)
    291 
    292 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/geoviews/element/geo.py in clone(self, data, shared_data, new_type, *args, **overrides)
    115         if 'crs' not in overrides and (not new_type or isinstance(new_type, _Element)):
    116             overrides['crs'] = self.crs
--> 117         return super(_Element, self).clone(data, shared_data, new_type,
    118                                            *args, **overrides)
    119 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/data/__init__.py in clone(self, data, shared_data, new_type, link, *args, **overrides)
   1154                 overrides['dataset'] = self.dataset
   1155 
-> 1156         new_dataset = super(Dataset, self).clone(
   1157             data, shared_data, new_type, *args, **overrides
   1158         )

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/dimension.py in clone(self, data, shared_data, new_type, link, *args, **overrides)
    569         # Apply name mangling for __ attribute
    570         pos_args = getattr(self, '_' + type(self).__name__ + '__pos_params', [])
--> 571         return clone_type(data, *args, **{k:v for k,v in settings.items()
    572                                           if k not in pos_args})
    573 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/geoviews/element/geo.py in __init__(self, data, kdims, vdims, **kwargs)
    108         elif isinstance(data, _Element):
    109             kwargs['crs'] = data.crs
--> 110         super(_Element, self).__init__(data, kdims=kdims, vdims=vdims, **kwargs)
    111 
    112 

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/element/raster.py in __init__(self, data, kdims, vdims, **params)
    782         if data is None or isinstance(data, list) and data == []:
    783             data = ([], [], np.zeros((0, 0)))
--> 784         super(QuadMesh, self).__init__(data, kdims, vdims, **params)
    785         if not self.interface.gridded:
    786             raise DataError("%s type expects gridded data, %s is columnar."

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/data/__init__.py in __init__(self, data, kdims, vdims, **kwargs)
    336 
    337         validate_vdims = kwargs.pop('_validate_vdims', True)
--> 338         initialized = Interface.initialize(type(self), data, kdims, vdims,
    339                                            datatype=kwargs.get('datatype'))
    340         (data, self.interface, dims, extra_kws) = initialized

~/.conda/envs/rbig_eo/lib/python3.8/site-packages/holoviews/core/data/interface.py in initialize(cls, eltype, data, kdims, vdims, datatype)
    290                 error = ' '.join([error, priority_error])
    291                 raise six.reraise(DataError, DataError(error, intfc), sys.exc_info()[2])
--> 292             raise DataError(error)
    293 
    294         return data, interface, dims, extra_kws

DataError: None of the available storage backends were able to support the supplied data format.
:HoloMap   [time]
   :QuadMesh   [lon,lat]   (probs,shannon_info)
from typing import Optional
def plot_map(xr_data, measure: str, save_name: Optional[str]=None):
    fig, ax = plt.subplots()

    if measure == 'probs':
        xr_data.probs.mean(dim='time').plot(
            ax=ax,
            vmin=0, robust=True, cmap='Reds', 
            cbar_kwargs={'label': "Probability"}
        )
    elif measure == 'info':
        xr_data.shannon_info.mean(dim='time').plot(
            ax=ax,
            vmin=0, robust=True, cmap='Reds', 
            cbar_kwargs={'label': "Shannon Information"}
        )
    else:
        raise ValueError(f"Unrecognized measure: {measure}")

    ax.set(
        xlabel='Longitude',
        ylabel='Latitude'
    )
    plt.tight_layout()
    if save_name:
        fig.savefig(FIG_PATH.joinpath(f"{measure}_{save_name}.png"))


def plot_ts(xr_data, measure: str, save_name: Optional[str]=None):
    fig, ax = plt.subplots()

    if measure == 'probs':
        xr_data.probs.mean(dim=['lon', 'lat']).plot.line(ax=ax, color='black', linewidth=3)
        ylabel = 'Probability'
    elif measure == 'info':
        xr_data.shannon_info.mean(dim=['lon', 'lat']).plot.line(ax=ax, color='black', linewidth=3)
        ylabel = 'Shannon Information'
    else:
        raise ValueError(f"Unrecognized measure: {measure}")

    ax.set(
        xlabel='Time',
        ylabel=ylabel
    )

    ax.legend(['Mean Predictions'])
    plt.tight_layout()
    if save_name:
        fig.savefig(FIG_PATH.joinpath(f"{measure}_ts_{save_name}.png"))

def plot_ts_error(xr_data, measure: str, save_name: Optional[str]=None):

    if measure == 'probs':
        predictions = xr_data.probs.mean(dim=['lat','lon'])
        std = xr_data.probs.std(dim=['lat','lon'])
        ylabel = 'Probabilities'
    elif measure == 'info':
        predictions = xr_data.shannon_info.mean(dim=['lat','lon'])
        std = xr_data.shannon_info.std(dim=['lat','lon'])
        ylabel = 'Shannon Information'
    else:
        raise ValueError(f"Unrecognized measure: {measure}")


    fig, ax = plt.subplots()
    ax.plot(xr_data.coords['time'].values, predictions)
    ax.fill_between(
        predictions.coords['time'].values,
        predictions - std,
        predictions + std,
        alpha=0.7, color='orange'
    )
    ax.set(
        xlabel='Time',
        ylabel=ylabel,
    )
    ax.legend(['Mean_predictions'])
    plt.tight_layout()
    if save_name:
        fig.savefig(FIG_PATH.joinpath(f"{measure}_ts_err_{save_name}.png"))

def plot_monthly_map(xr_data, measure: str, save_name: Optional[str]=None):
    plt.figure()
    xr_data.probs.groupby('time.month').mean().plot.pcolormesh(x='lon', y='lat', col='month', col_wrap=3, vmin=0, robust=True, cmap='Reds')
    plt.savefig(FIG_PATH.joinpath(f"monthly_{save_name}.png"))
### Figure I - Probability Maps
plot_map(probs_cubes, 'probs',  None)
plot_map(probs_cubes, 'info',  None)
### Figure II - Probability Maps, Per Month
plot_monthly_map(probs_cubes, 'probs', None)
plot_monthly_map(probs_cubes, 'info', None)
<Figure size 432x288 with 0 Axes>
<Figure size 432x288 with 0 Axes>
### Figure 2.1 - Time Series (Probability)
plot_ts(probs_cubes, 'probs', None)
plot_ts(probs_cubes, 'info', None)
### Figure 2.2 - Time Series w. Variance
plot_ts_error(probs_cubes, 'probs', None); 
plot_ts_error(probs_cubes, 'info', None)
### Other Plots


### Information $$ I(\mathbf{X}) = - \log p(\mathbf{X}) $$
probs_cubes['shannon_info'] = - np.log(probs_cubes.probs) #* np.log(2)
fig, ax = plt.subplots()
probs_cubes.shannon_info.mean(dim='time').plot(
    ax=ax,
    robust=True, cmap='Reds', 
    cbar_kwargs={'label': "Shannon Information"}
)
ax.set(
    xlabel='Longitude',
    ylabel='Latitude',
)
plt.tight_layout()
plt.figure(figsize=(10,10))
probs_cubes.shannon_info.groupby('time.month').mean().plot.pcolormesh(x='lon', y='lat', col='month', col_wrap=3, robust=True, cmap='Reds')
<xarray.plot.facetgrid.FacetGrid at 0x7f8b177c51c0>
<Figure size 720x720 with 0 Axes>
## Experiment II - Spain, 2010, Cube 2x2x2
!ls $RES_PATH/probs
gpp_spain_vgpp_r2010_v0.csv      spain_vrm_r2010_v0.csv
rm_spain_vrm_r2002_2010_v0.csv    spain_vrm_r2010_v0336.csv
rm_spain_vrm_r2010_v0.csv     spain_vrm_r2010_v0_222.csv
spain_gpp_2002_2010_v0_222.csv    spain_vsm_r2010_v0_222.csv
spain_vgpp_r2002_2010_v0_111.csv
probs_df.head()
probs
time lat lon
2002-01-05 43.625 -8.125 0.241431
-7.875 0.258389
-7.625 0.239796
-7.375 0.164524
-6.875 0.339672
filename = "spain_gpp_2002_2010_v0_222.csv"

# read csv file
probs_df = pd.read_csv(str(RES_PATH.joinpath(f'probs/{filename}')))

# convert to datetime
probs_df['time'] = pd.to_datetime(probs_df['time'])


# create dataframe in the format for xarray
probs_df = probs_df.set_index(['time', 'lat', 'lon']).rename(columns={"0": 'probs'})

# remove probabilities greater than 1
probs_df['probs'][probs_df['probs'] >= 1.0] = np.nan

# create xarray cubes
probs_cubes = xr.Dataset.from_dataframe(probs_df, )
probs_cubes
Show/Hide data repr Show/Hide attributes
xarray.Dataset
    • lat: 30
    • lon: 49
    • time: 413
    • time
      (time)
      datetime64[ns]
      2002-01-13 ... 2010-12-31
      array(['2002-01-13T00:00:00.000000000', '2002-01-21T00:00:00.000000000',
             '2002-01-29T00:00:00.000000000', ..., '2010-12-15T00:00:00.000000000',
             '2010-12-23T00:00:00.000000000', '2010-12-31T00:00:00.000000000'],
            dtype='datetime64[ns]')
    • lat
      (lat)
      float64
      36.12 36.38 36.62 ... 43.12 43.38
      array([36.125, 36.375, 36.625, 36.875, 37.125, 37.375, 37.625, 37.875, 38.125,
             38.375, 38.625, 38.875, 39.125, 39.375, 39.625, 39.875, 40.125, 40.375,
             40.625, 40.875, 41.125, 41.375, 41.625, 41.875, 42.125, 42.375, 42.625,
             42.875, 43.125, 43.375])
    • lon
      (lon)
      float64
      -8.875 -8.625 ... 2.875 3.125
      array([-8.875, -8.625, -8.375, -8.125, -7.875, -7.625, -7.375, -7.125, -6.875,
             -6.625, -6.375, -6.125, -5.875, -5.625, -5.375, -5.125, -4.875, -4.625,
             -4.375, -4.125, -3.875, -3.625, -3.375, -3.125, -2.875, -2.625, -2.375,
             -2.125, -1.875, -1.625, -1.375, -1.125, -0.875, -0.625, -0.375, -0.125,
              0.125,  0.375,  0.625,  0.875,  1.125,  1.375,  1.625,  1.875,  2.125,
              2.375,  2.625,  2.875,  3.125])
    • probs
      (time, lat, lon)
      float64
      nan nan nan nan ... nan nan nan nan
      array([[[  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              ...,
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan]],
      
             [[  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              ...,
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan]],
      
             [[  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              ...,
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan, 0.584,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan]],
      
             ...,
      
             [[  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              ...,
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan, 0.196,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan]],
      
             [[  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              ...,
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan, 0.03 ,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan]],
      
             [[  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              ...,
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan],
              [  nan,   nan,   nan, ...,   nan,   nan,   nan]]])
fig, ax = plt.subplots()
probs_cubes.probs.mean(dim='time').plot(
    ax=ax,
    vmin=0, robust=True, cmap='Reds', 
    cbar_kwargs={'label': "Probabilities"}
)
ax.set(
    xlabel='Longitude',
    ylabel='Latitude'
)
plt.tight_layout()
fig, ax = plt.subplots()
probs_cubes.probs.mean(dim=['lon', 'lat']).plot.line(ax=ax, color='black', linewidth=3)
ax.set(
    xlabel='Time',
    ylabel='Probabilities'
)
ax.legend(['Mean Predictions'])
plt.tight_layout()
plt.show()
probs_cubes.probs.groupby('time.month').mean().plot.pcolormesh(
    x='lon', y='lat', 
    col='month', col_wrap=3, 
    vmin=0, robust=True, cmap='Reds',
    cbar_kwargs={
        'label': 'Probabilities', 
        'location':'bottom', 
        'shrink': 0.7, 
        'pad': 0.075
    }
)
<xarray.plot.facetgrid.FacetGrid at 0x7f8b17bed880>
### Anomalies
probs_cubes['shannon_info'] = - np.log(probs_cubes.probs) #* np.log(2)
fig, ax = plt.subplots()
probs_cubes.shannon_info.mean(dim='time').plot(
    ax=ax,
    robust=True, cmap='Reds', 
    cbar_kwargs={'label': "Shannon Information"}
)
ax.set(
    xlabel='Longitude',
    ylabel='Latitude',
)
plt.tight_layout()
plt.figure(figsize=(10,10))
probs_cubes.shannon_info.groupby('time.month').mean().plot.pcolormesh(
    x='lon', y='lat', 
    col='month', col_wrap=3, 
    robust=True, cmap='Reds',
    cbar_kwargs={
        'label': 'Shannon Entropy', 
        'location':'bottom', 
        'shrink': 0.7, 
        'pad': 0.075
    }
)
<xarray.plot.facetgrid.FacetGrid at 0x7f8b17391c10>
<Figure size 720x720 with 0 Axes>
# define threshold
instances = 4

# calculate densities

# calculate density threshold
## Experiment Steps