Package: mhw-detect
MHW DetectorMarine heatwaves detector based onhttps://github.com/ecjoliver/marineHeatWaves.This package integrates a numba optimised version of ecjoliver's implementation for MHW detection with multiprocessing capabilities to compute detection over every coordinates of the dataset.This code is not only for detecting MHW. It can also be used to detect extrem events of any variables like chla, pH, O2, etc ...Installationpip install mhw-detectDependenciesxarraynumbascipydasknumpypandasnetcdf4clickpyarrowUsageConfiguration fileWith mhw-detect no need for kilometers of parameters in command line. You just need to write a configuration file in which you put every parameters like an identity card of your next detection.data:data:path:'/folder/sst.nc'var:'sst'clim:path:'/folder_clim/clim.nc'var:'sst'percent:path:'/folder_percent/percentile.nc'var:'sst'# Optionnaloffset:path:'/folder_offset/offset.nc'var:'sst'params:depth:0climatologyPeriod:[null,null]# ex: [1983, 2012]pctile:90windowHalfWidth:5smoothPercentile:TruesmoothPercentileWidth:31minDuration:5joinAcrossGaps:TruemaxGap:2maxPadLength:FalsecoldSpells:FalseLy:Falsecut:nb_lat:157nb_lon:72output_detection:'/my/path/to/folder_result/'data: specifies the paths and variables you want to use. Do not specify clim and percent if you want them to be computed during the detection. Offset is an optionnal parameter as a 2D dataset to add an offset to the percentile.params: specifies the parameters of the detection. See section below.cut: specifies the number of latitude and longitude for geospatial dataset cutting.output_detection: specifies the folder in which to save the results.Detection parametersFromhttps://github.com/ecjoliver/marineHeatWaves.climatologyPeriod      Period over which climatology is calculated, specified
                        as list of start and end years. Default ([null, null]) is to calculate
                        over the full range of years in the supplied time series.
                        Alternate periods suppled as a list e.g. [1983,2012].
                        Unused if precalculated clim and percentile are set.

pctile                 Threshold percentile (%) for detection of extreme values
                        (DEFAULT = 90)

windowHalfWidth        Width of window (one sided) about day-of-year used for
                        the pooling of values and calculation of threshold percentile
                        (DEFAULT = 5 [days])

smoothPercentile       Boolean switch indicating whether to smooth the threshold
                        percentile timeseries with a moving average (DEFAULT = True)

smoothPercentileWidth  Width of moving average window for smoothing threshold
                        (DEFAULT = 31 [days])

minDuration            Minimum duration for acceptance detected MHWs
                        (DEFAULT = 5 [days])

joinAcrossGaps         Boolean switch indicating whether to join MHWs
                        which occur before/after a short gap (DEFAULT = True)

maxGap                 Maximum length of gap allowed for the joining of MHWs
                        (DEFAULT = 2 [days])

maxPadLength           Specifies the maximum length [days] over which to interpolate
                        (pad) missing data (specified as nans) in input temp time series.
                        i.e., any consecutive blocks of NaNs with length greater
                        than maxPadLength will be left as NaN. Set as an integer.
                        (DEFAULT = False, interpolates over all missing values).

coldSpells             Specifies if the code should detect cold events instead of
                        heat events. (DEFAULT = False)Datasets coordinatesAll datasets must have lat/latitude, lon/longitude and time as coordinates.depthcoordinate is allowed for the main dataset. Currently, the depth as to be specified via its index in the coordinate array. Giving directly the wanted depth will be added later.The percentile dataset (and offset if used) must have aquantilecoordinate as a dimension for the variable. It is useful in the case you want to do the detection with different quantile (90, 99).Step 1 : Geospatial cutting (optionnal but recommended)To use multiprocessing efficiently, the datasets must be cut in several smaller datasets over the lat/lon dimensions. Callmhw-cutwith your config file to make it happen. Each sub-datasets will be called Cut_X.nc where X is the number of the cut (that is why your datasets (data, clim, percentile) must be in different folders).The number of cuts does not matter, chunk size does. To find suitables nb_lat and nb_lon, it is better to use a notebook.import xarray as xr
ds = xr.open_dataset('dataset.nc', chunks={'latitude': nb_lat, 'longitude': nb_lon})
dsnb_lat and nb_lon should be multiples of the latitude and longitude dimensions and choose carefully to have chunks of size over 10Mb (see Dask documentation for more details). Printing ds on a notebook gives you the size of the chunk (cut).Please note that this step will double the space used in your disk.Step 2 : DetectionCallmhw-detectto detect MHW. With multiprocessing, each cut is processed in parallel. For a cut, you will get inoutput_detectiona text file with the results of the detection. Finally, when all the detections are done, every text files are concatenated into one csv (with ; as a separator).If you do not want to use multiprocessing just to make a detection on a small geospatial subset, you can give the option-g lat_min lat_max lon_min lon_maxto the command.CommandsGeospatial cutUsage: mhw-cut [OPTIONS]

  Cut datasets in multiple files

Options:
  -c, --config PATH  Specify configuration file  [required]
  --help             Show this message and exit.DetectionUsage: mhw-detect [OPTIONS]

  Detect extreme events

Options:
  -c, --config PATH               Specify configuration file  [required]

  -g, --geographical-subset <FLOAT RANGE FLOAT RANGE FLOAT RANGE FLOAT RANGE>...
                                  The geographical subset as minimal latitude,
                                  maximal latitude, minimal longitude and
                                  maximal longitude.

                                  If set, the detection will be done on the
                                  subsetted global dataset given in config
                                  file (not the cuts) and sequentially.

  --categ-map TEXT                Generate category map in a netcdf file.

  --output-df TEXT                Give a name to the output dataframe. Two
                                  extensions are available: csv and parquet
                                  (default).     Save in csv if you want to
                                  open the dataframe with excel. Parquet is
                                  more efficient and takes less disk space.
                                  [default: data.parquet]

  --help                          Show this message and exit.OutputHere is an example of the output csv file. Every detected MHW are listed.latlontime_debtime_endtime_peakdurationduration_modduration_strduration_sevduration_extcategimaximeanivarrate_onsetrate_decline0-76.916664-180.02003-01-012003-01-182003-01-04185.02.05.06.04.02.3415431.4156630.5519710.18670.20491-76.916664-180.02003-04-102003-10-232003-04-131970.00.00.00.04.04.2300e-8-4.8800e-107.0377e-91.5032e-82.7109e-102-76.916664-180.02003-12-182003-12-232003-12-2160.01.02.03.04.02.3252111.8583830.3679690.4829870.6131323-76.916664-179.91662003-01-012003-01-182003-01-04185.02.05.06.04.02.3271721.4208170.5442480.1826040.203315To doAdd shapefile usage.Add an option to remove text files.ContributionInstallpoetryin your python/conda environment.Clone this repository and checkout to your branch.Create a poetry environment for dev by runningpoetry install.Make your dev.Test your dev with the commandpoetry run python monscript.py ....Commit and push.Ask for a merge request.ReferencesHobday, A.J. et al. (2016), A hierarchical approach to defining marine heatwaves, Progress in Oceanography, 141, pp. 227-238, doi: 10.1016/j.pocean.2015.12.014pdf