Every function and method NCToolkit exposes, grouped by what it does, with full parameter details. Unless shown as nc., calls are methods on a DataSet object (what open_data() and friends return) — expand "Parameters" on any entry for the complete argument list.
Define session options.
kwargsDefine options using key/value pairs. Set thread_safe=True if HDF5 was built to be thread-safe. Set lazy=False if you want methods to evaluate non-lazily. Set cores=n to process the individual files in a multi-file dataset in parallel — only affects multi-file datasets. Set temp_dir="/foo" to change the directory NCToolkit uses to save temporary files. Set progress to "on" or "off" to always or never show a progress bar for multi-file processing; defaults to "auto".
Read netCDF data as a Dataset object
xA string or list of netCDF files or a single url. The function will check the files exist. If x is not a list, but an iterable it will be converted to a list. If a *.nc style wildcard is supplied, open_data will use all files available. By default an empty dataset is created, ie. using open_data() will create an empty dataset that can then be expanded using append.
checksDo you want basic checks to ensure cdo can read files? Default to True. Setting to False can result in a minor speed up.
kwargsOptional arguments for internal use by open_thredds and open_url.
Read netCDF data from a url as a DataSet object
Required:
xrequiredA string with a url. Prior to processing data will be downloaded to a temp folder.
Optional:
ftp_detailsA dictionary giving the user name and password combination for ftp downloads: {"user":user, "password":pass}
waitTime to wait, in seconds, for data to download. A minimum of 3 attempts will be made to download the data.
file_stopTime limit, in minutes, for individual attempts at downloading data. This is useful to get around download freezes.
Read thredds data as a Dataset object
Required:
xrequiredA string or list of thredds urls, which must end with .nc.
Optional:
checksDo you want to check if data is available over thredds?
waitTime to wait for thredds server to be checked. Limitless if not supplied.
Open a geotiff and convert to a Dataset. This requires rioxarray to be installed.
xA string or list of geotiff files or a single url. This requires rioxarray to be installed.
Convert an xarray dataset to an nctoolkit dataset. This will first save the xarray dataset as a temporary netCDF file.
dsrequiredxarray dataset you want to convert to nctoolkit DataSet.
Make a deep copy of an DataSet object. Note: This will not make disk copies of the temporary files underlying datasets, so it will be disk-space efficient.
Generate an ensemble of files from a directory.
Required:
pathrequiredThe directory to search for netCDF files
Optional:
recursiveTrue/False depending on whether you want to search the path recursively. Defaults to True.
List variables contained in a dataset
Detailed list of variables contained in a dataset. This will only display the variables in the first file of an ensemble.
List times contained in a dataset
List years contained in a dataset
List months contained in a dataset
List levels contained in a dataset
The size of an object. This will print the number of files, total size, and smallest and largest files in an DataSet object.
The current file or files in the DataSet object
The history of operations on the DataSet
The starting file or files of the DataSet object
List calendars of dataset files
List formats of files contained in a dataset
A method for subsetting datasets to specific variables, years, longitudes etc. Operations are applied in the order supplied.
All arguments are optional keywords, applied in the order supplied. NCToolkit matches on partial names, so year, month, var etc. also work.
variablesA variable or list of variables to select. Accepts wildcards, e.g. "var*" selects every variable starting with var.
yearsYear(s) to select, as a list, range or int.
monthsMonth(s) to select, as a list, range or int.
daysDay(s) to select, as a list, range or int.
hoursHour(s) to select, as a list, range or int.
seasonsSeason(s) to select: "DJF", "MAM", "JJA" or "SON".
timestepsTime step(s) to select by index, e.g. 0 for the first time step.
rangeA [date_min, date_max] list selecting times on or after date_min and before date_max. Dates can be datetime objects or "DD/MM/YYYY"-style strings.
lonLongitude range to select, as [lon_min, lon_max] between -180 and 180.
latLatitude range to select, as [lat_min, lat_max] between -90 and 90.
levelsVertical level/depth range to select, as [min_level, max_level].
Crop to a rectangular longitude and latitude box
lonThe longitude range to select. This must be two variables, between -180 and 180 when nco = False.
latThe latitude range to select. This must be two variables, between -90 and 90 when nco = False.
ncoDo you want this to use NCO for cropping? Defaults to False, and uses CDO. Set to True if you want to call NCO. NCO is typically better at handling very large horizontal grids.
nco_varsif nco=TrueIf using NCO, the variables you want to select
Remove variables, days, months, years or time steps from a dataset. This will remove stated variables from files in the dataset.
All arguments are optional keywords, applied in the order supplied. NCToolkit matches on partial names, so year, month, variable etc. also work.
varA variable or list of variables to drop. Accepts wildcards, e.g. "var*".
yearYear(s) to drop.
monthMonth(s) to drop.
dayDay(s) to drop.
timeTime step(s) to drop by index. Negative indices are accepted.
Set the date in a dataset. You should only do this if you have to fix/change a dataset with a single, not multiple dates.
Required:
yearrequiredThe year
monthrequiredThe month
dayrequiredThe day
Optional:
base_yearThe base year for time creation in the netCDF. Defaults to 1900.
Set the day for each time step in a dataset
xrequiredDay to set dataset to
Shift times in dataset by a number of hours, days, months, or years. Operations are applied in the order supplied.
kwargshours maps to shift_hours days maps to shift_days months maps to shift_months years maps to shift_years. Note: this uses partial matches. So hour, day, month, year will also work.
Calculate the temporal correlation coefficient between two datasets. This will calculate the temporal correlation coefficient, for each time step, between two datasets. The datasets must either have the same variables or only have one variable.
xrequiredFirst dataset to use
yrequiredSecond dataset to use
Calculate the spatial correlation coefficient between two datasets. This will calculate the spatial correlation coefficient, for each time step, between two datasets. The datasets must either have the same variables or only have one variable.
xrequiredFirst dataset to use
yrequiredSecond dataset to use
Calculate a rolling mean based on a window
Required:
windowrequiredThe size of the window for the calculation of the rolling mean
Optional:
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
Calculate a rolling minimum based on a window
Required:
windowrequiredThe size of the window for the calculation of the rolling minimum
Optional:
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
Calculate a rolling maximum based on a window
Required:
windowrequiredThe size of the window for the calculation of the rolling maximum
Optional:
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
Calculate a rolling sum based on a window
Required:
windowrequiredThe size of the window for the calculation of the rolling sum
Optional:
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
Calculate a rolling range based on a window
Required:
windowrequiredThe size of the window for the calculation of the rolling range
Optional:
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
Calculate a rolling standard deviation based on a window
Required:
windowrequiredThe size of the window for the calculation of the rolling standard deviation
Optional:
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
Calculate a rolling variance based on a window
Required:
windowrequiredThe size of the window for the calculation of the rolling variance
Optional:
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
Calculate annual anomalies for each variable based on a baseline period. The anomaly is derived by first calculating the climatological annual mean for the given baseline period. Annual means are then calculated for each year and the anomaly is calculated compared with the baseline mean. This will be calculated on a per-file basis in a multi-file dataset.
Required:
baselinerequiredBaseline years. This needs to be the first and last year of the climatological period. Example: a baseline of [1980,1999] will result in anomalies against the 20 year climatology from 1980 to 1999.
Optional:
metricSet to "absolute" or "relative", depending on whether you want the absolute or relative anomaly to be calculated.
windowA window for the anomaly. By default window = 1, i.e. the annual anomaly is calculated. If, for example, window = 20, the 20 year rolling means will be used to calculate the anomalies.
monthly:anomaly: Calculate monthly anomalies based on a baseline period. The anomaly is derived by first calculating the climatological monthly mean for the given baseline period. Monthly means are then calculated for each year and the anomaly is calculated compared with the baseline mean. This is calculated separately for each file in a multi-file dataset.
baselinerequiredBaseline years. This needs to be the first and last year of the climatological period. Example: a baseline of [1985,2005] will result in anomolies against 20 year climatology from 1986 to 2005.
Calculate the temporal mean of all variables. Useful for: monthly mean, annual/yearly mean, seasonal mean, daily mean, daily climatology, monthly climatology, seasonal climatology
overTime periods to average over. Options are 'year', 'month', 'day'. This operates in a similar way to the groupby method in pandas or the tidyverse in R.
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
windowThis determines the number of time steps to calculate the mean over to calculate over, on a non-rolling basis. This is useful if you need to calculate the mean every 5 days, for example.
Calculate the temporal minimum of all variables. Useful for: monthly minimum, annual/yearly minimum, seasonal minimum, daily minimum, daily climatology, monthly climatology, seasonal climatology
overTime periods to average over. Options are 'year', 'month', 'day'. This operates in a similar way to the groupby method in pandas or the tidyverse in R, with over acting as the grouping.
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
windowThis determines the number of time steps to calculate the minimum over to calculate over, on a non-rolling basis. This is useful if you need to calculate the minimum every 5 days, for example.
Calculate the temporal median of all variables. Useful for: monthly median, annual/yearly median, seasonal median, daily median, daily climatology, monthly climatology, seasonal climatology
overTime periods to average over. Options are 'year', 'month', 'day'. This operates in a similar way to the groupby method in pandas or the tidyverse in R, with over acting as the grouping.
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
Calculate the temporal percentile of all variables. Useful for monthly percentile, annual/yearly percentile, seasonal percentile, daily percentile, daily climatology, monthly climatology, seasonal climatology
Required:
prequiredPercentile to calculate
Optional:
overTime periods to average over. Options are 'year', 'month', 'day'. This operates in a similar way to the groupby method in pandas or the tidyverse in R, with over acting as the grouping.
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
Calculate the temporal maximum of all variables. Useful for: monthly maximum, annual/yearly maximum, seasonal maximum, daily maximum, daily climatology, monthly climatology, seasonal climatology
overTime periods to average over. Options are 'year', 'month', 'day'. This operates in a similar way to the groupby method in pandas or the tidyverse in R, with over acting as the grouping.
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
windowThis determines the number of time steps to calculate the maximum over to calculate over, on a non-rolling basis. This is useful if you need to calculate the maximum every 5 days, for example.
Calculate the temporal sum of all variables.
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
overTime periods to count the sum over. Options are 'year', 'month', 'day'. This operates in a similar way to the groupby method in pandas or the tidyverse in R, so you can supply combinations of these to get the sum over each year, month or day.
windowThis determines the number of time steps to sum over, on a non-rolling basis. This is useful if you need to calculate the sum every 5 days, for example.
Calculate the temporal range of all variables. Useful for: monthly range, annual/yearly range, seasonal range, daily range, daily climatology, monthly climatology, seasonal climatology
overTime periods to average over. Options are 'year', 'month', 'day'. This operates in a similar way to the groupby method in pandas or the tidyverse in R, with over acting as the grouping.
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
windowThis determines the number of time steps to calculate the range over to calculate over, on a non-rolling basis. This is useful if you need to calculate the range every 5 days, for example.
Calculate the temporal standard deviation of all variables. Useful for: monthly standard deviation, annual/yearly standard deviation, seasonal standard deviation, daily standard deviation, daily climatology, monthly climatology, seasonal climatology
overTime periods to average over. Options are 'year', 'month', 'day'. This operates in a similar way to the groupby method in pandas or the tidyverse in R, with over acting as the grouping.
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
windowThis determines the number of time steps to calculate the standard deviation over to calculate over, on a non-rolling basis. This is useful if you need to calculate the standard deviation every 5 days, for example.
Calculate the temporal cumulative sum of all variables
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
Calculate the temporal variance of all variables. Useful for: monthly variance, annual/yearly variance, seasonal variance, daily variance, daily climatology, monthly climatology, seasonal climatology
overTime periods to average over. Options are 'year', 'month', 'day'. This operates in a similar way to the groupby method in pandas or the tidyverse in R, with over acting as the grouping.
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
windowThis determines the number of time steps to calculate the variance over to calculate over, on a non-rolling basis. This is useful if you need to calculate the variance every 5 days, for example.
Calculate the correlation correct between two variables in space. This is calculated for each time step. The correlation coefficient coefficient is calculated using values in all grid cells, ignoring missing values. This calculates the Pearson correlation coefficient.
var1requiredThe first variable
var2requiredThe second variable
Calculate the correlation correct in time between two variables. The correlation is calculated for each grid cell, ignoring missing values. This calculates the Pearson correlation coefficient.
var1requiredThe first variable
var2requiredThe second variable
Calculate the area weighted spatial mean for all variables. This is performed for each time step.
Calculate the spatial minimum for all variables. This is performed for each time step.
Calculate the spatial maximum for all variables. This is performed for each time step.
Calculate the spatial percentile for all variables. This is performed for each time step.
prequiredPercentile to calculate. 0<=p<=100.
Calculate the spatial range for all variables. This is performed for each time step.
Calculate the spatial sum for all variables. This is performed for each time step.
by_areaSet to True if you want to multiply the values by the grid cell area before summing over space. Default is False.
Calculate the spatial standard deviation for all variables. This is performed for each time step.
Calculate the spatial variance for all variables. This is performed for each time step.
Calculate the latitudinal or longitudinal centre for each year/month combination in files. This applies to each file in an ensemble.
bySet to 'latitude' if you want the latitudinal centre calculated. 'longitude' for longitudinal.
by_areaIf the variable is a value/m2 type variable, set to True, otherwise set to False.
Calculate the zonal mean for each time step
Calculate the zonal minimum for each time step
Calculate the zonal maximum for each time step
Calculate the zonal range for each time step
Calculate the zonal sum for each time step
by_areaSet to True if you want the cell value to be multiplied by the cell area prior to summing
Calculate the meridonial mean for each year/month combination in files. This applies to each file in an ensemble.
Calculate the meridonial minimum for each year/month combination in files. This applies to each file in an ensemble.
Calculate the meridonial maximum for each year/month combination in files. This applies to each file in an ensemble.
Calculate the meridonial range for each year/month combination in files. This applies to each file in an ensemble.
Extract the top/surface level from a dataset. This extracts the first vertical level from each file in a dataset. This method is most useful for things like oceanic data, where this method will extract the sea surface. You may need to double check that the first vertical level is the surface, as this is not always the case.
Extract the bottom level or value from a dataset. This extracts the bottom level or value from each netCDF file. Please note that for ensembles, it uses the first file to derive the index of the bottom level.
choiceSet to 'level' to extract the bottom level, or 'value' to extract the bottommost non-missing value.
Verticaly interpolate a dataset based on given vertical levels. Vertical interpolation is calculated for each time step and grid cell
Required:
levelsrequiredlist of vertical levels, for example depths for an ocean model, to vertically interpolate to. These must be floats or ints.
fixedrequiredDefine whether the vertical levels are the same in all spatial locations. Set to True if they are, e.g. you have z-levels. If you have the likes of sigma-coordinates, set this to False.
Optional:
thicknessif fixed=FalseThis or depths must be supplied if fixed is False, otherwise vertical thickness/depth cannot be known. Option argument when vertical levels vary in space. One of: a variable, in the dataset, which contains the variable thicknesses; a .nc file which contains the thicknesses; or a Dataset that contains the thicknesses. Note: the .nc file or Dataset must only contain one variable. Thickness should be in metres. Vertical interpolation will take the value from the mid-point of the level.
depthsif fixed=FalseThis or thickness must be supplied if fixed is False, otherwise vertical thickness/depth cannot be known. Option argument when vertical levels vary in space. One of: a variable, in the dataset, which contains the variable depths; a .nc file which contains the depths; or a Dataset that contains the depths. Note: the .nc file or Dataset must only contain one variable. Depths should be in metres, and be the mid-point of the level.
surfaceif thickness givenIf thickness is supplied you must also supply this to identify whether the top or bottom of the level is the surface, i.e. the lowest level. This must be one of 'top' or 'bottom'.
Calculate the depth-averaged mean for each variable. This is calculated for each time step and grid cell.
Required:
fixedrequiredDefine whether the vertical levels are the same in all spatial locations. Set to True if they are, e.g. you have z-levels. If you have the likes of sigma-coordinates, set this to True.
Optional:
thicknessif fixed=FalseThis must be supplied when vertical levels vary in space, i.e. fixed=False. One of: a variable, in the dataset, which contains the variable thicknesses; a .nc file which contains the thicknesses; or a Dataset that contains the thicknesses. Note: the .nc file or Dataset must only contain one variable.
depth_rangeOnly use when vertical levels vary in space. Set a depth range if desired. Should be of the form [min_depth, max_depth].
Calculate the vertical minimum of variable values. This is calculated for each time step and grid cell.
Calculate the vertical maximum of variable values. This is calculated for each time step and grid cell.
Calculate the vertical range of variable values. This is calculated for each time step and grid cell.
Calculate the vertical sum of variable values. This is calculated for each time step and grid cell.
Calculate the vertically integrated sum over the water column. This calculates the sum of the variable multiplied by the cell thickness
Required:
fixedrequiredDefine whether the vertical levels are the same in all spatial locations. Set to True if they are, e.g. you have z-levels. If you have the likes of sigma-coordinates, set this to True.
Optional:
thicknessif fixed=FalseThis must be supplied when vertical levels vary spatially. One of: a variable, in the dataset, which contains the variable thicknesses; a .nc file which contains the thicknesses; or a Dataset that contains the thicknesses. Note: the .nc file or DataSet must only contain one variable.
depth_rangeSet a depth range if desired. Should be of the form [min_depth, max_depth].
Calculate the vertical sum of variable values. This is calculated for each time step and grid cell.
Invert the levels of 3D variables. This is calculated for each time step and grid cell.
Create a mask identifying the deepest cell without missing values.. This converts a dataset to a mask identifying which cell represents the bottom, for example the seabed. 1 identifies the deepest cell with non-missing values. Everything else is 0, or missing.
Regrid a dataset to a target grid. Horizontal interpolation
Required:
gridrequiredThe grid to remap to
Optional:
methodRemapping method. Defaults to "bil". Methods available are: bilinear - "bil"; nearest neighbour - "nn" - "nearest neighbour" bicubic interpolation - "bic". Distance-weighted average - "dis". First order conservative remapping - "con". Second order conservative remapping - "con2". Large area fraction remapping - "laf"
recycleSet to True if you want to re-use the remapping weights when you are regridding another dataset.
one_gridSet to True if all files in multi-file dataset have the same grid, to speed things up.
kwargsInstead of supplying a grid using 'grid', you can supply `lon` and `lat`. These must be equally lengthed lists or arrays that will be used to generate the grid. If you want to regrid to a single location you can just supply a float to lon and lat.
Regrid a dataset to a regular latlon grid
Required:
lonrequired2 element list giving minimum and maximum longitude of target grid
latrequired2 element list giving minimum and maximum latitude of target grid
resrequiredIf float or int given, this will be the horizontal and vertical resolution of the target grid. If 2 element list is given, the first element is the longitudinal resolution and the second is the latitudinal resolution.
Optional:
methodRemapping method. Defaults to "bil". Methods available are: bilinear - "bil"; nearest neighbour - "nn" - "nearest neighbour" bicubic interpolation - "bic". Distance-weighted average - "dis". First order conservative remapping - "con". Second order conservative remapping - "con2". Large area fraction remapping - "laf"
recycleDo you want the grid and weights to be available for recycling and use in regrid? Defaults to False
one_gridSet to True if all files in multi-file dataset have the same grid, to speed things up.
Resample the horizontal grid of a dataset
factorrequiredThe resampling factor. Must be a positive integer. No interpolation occurs. Example: factor of 2 will sample every other grid cell
Temporally interpolate variables based on date range and time resolution
Required:
startrequiredStart date for interpolation. Needs to be of the form YYYY/MM/DD or YYYY-MM-DD.
Optional:
endEnd date for interpolation. Needs to be of the form YYYY/MM/DD or YYYY-MM-DD. If end is not given interpolation will be to the final available time in the dataset.
resolutionTime steps used for interpolation. Needs to be "daily", "weekly", "monthly" or "yearly". Defaults to monthly.
Temporally interpolate a dataset to given number of time steps between existing time steps
stepsrequiredNumber of time steps to interpolate between existing time steps. For example, if you wanted to go from daily to hourly data you would set steps=24.
Fill missing values with a distance-weighted average. This carries out infilling for each time step and vertical level. Filling only uses horizontal neighbours, not vertical.
nNumber of nearest neighbours to use. Defaults to 1. To
Calculate the grid box mean for all variables. This is performed for each time step.
xNumber of boxes in the x, e.g. east-west direction
yNumber of boxes in the y, e.g. north-south direction
Calculate the grid box max for all variables. This is performed for each time step.
xNumber of boxes in the x, e.g. east-west direction
yNumber of boxes in the y, e.g. north-south direction
Calculate the grid box min for all variables. This is performed for each time step.
xNumber of boxes in the x, e.g. east-west direction
yNumber of boxes in the y, e.g. north-south direction
Calculate the grid box sum for all variables. This is performed for each time step.
xNumber of boxes in the x, e.g. east-west direction
yNumber of boxes in the y, e.g. north-south direction
Calculate the grid box range for all variables. This is performed for each time step.
xNumber of boxes in the x, e.g. east-west direction
yNumber of boxes in the y, e.g. north-south direction
Mask a lon/lat box
lonLongitude range to mask. Must be of the form: [lon_min, lon_max]
latLatitude range to mask. Must be of the form: [lat_min, lat_max]
Match dataset to a spatiotemporal points dataframe
Required:
dfrequiredThe column names must be made up of a subset of "lon", "lat", "year", "month", "day" and "depth". Pressure (in dbars), named "pressure", can also be used instead of "depth", which will require the optional dependency seawater to be installed.
Optional:
variablesStr or list of variables. All variables are matched up if this is not supplied. This can include variables generated by assign using kwargs.
depthsIf each cell has different vertical levels, this must be provided as a dataset. If each cell has the same vertical levels, provide it as a list. If this is not supplied nctoolkit will try to figure out what they are. Only required if carrying out vertical matchups.
tmeanSet to True or False, depending on whether you want temporal averaging at the temporal resolution given by df. For example, if you only had months in df, but had daily data in ds, you might want to calculate a daily average in the monthly dataset. This is equivalent to apply `ds.tmean(..)` to the dataset.
topSet to True if you want only the top/surface level of the dataset to be selected for matching.
nanValue or range of values to set to nan. Defaults to 0. Only required if values in dataset need changed to missing
regridRegridding method. Defaults to "bil". Options available are those in nctoolkit regrid method. "nn" for nearest neighbour.
max_extrapMaximum distance for extrapolation. Defaults to 5.
quietSet to True to suppress output
kwargsAdditional arguments to send to assign
Calculate phenologies from a dataset. Each file in an ensemble must only cover a single year, and ideally have all days. The method assumes datasets have daily resolution.
Required:
varrequiredVariable to analyze.
metricrequiredMust be peak, middle, start or end. Peak is defined as the day of the maximum value. Middle is the day when the cumulative total of the variable first exceeds the cumulative total for the entire year. Start or end is defined as the first day when the cumulative total exceeds a percentile p of the maximum cumulative total.
Optional:
pfor metric='start'/'end'Percentile to use for start or end.
Merge datasets
datasetsDatasets to merge.
matchTemporal matching criteria. This is a list which must be made up of a subset of day, year, month. This checks that the datasets have compatible times. For example, if you want to ensure the datasets have the same years, then use match = ["year"].
Add new file(s) to a dataset.
xrequiredFile path(s) to add to the dataset
Remove file(s) from a dataset
xrequiredFile path(s) to remove from a dataset
Calculate an ensemble mean. This operates on a grid cell by grid cell basis.
ncoDo you want to use NCO for the calculation? Default is False, i.e. CDO is used. Modify default if run time is an issue.
ignore_timeIf True the mean is calculated over all time steps. If False, the ensemble mean is calculated for each time steps; for example, if the ensemble is made up of monthly files the mean for each month will be calculated.
Calculate an ensemble minimum. This operates on a grid cell by grid cell basis.
ncoDo you want to use NCO for the calculation? Default is False, i.e. CDO is used. Modify default if run time is an issue.
ignore_timeIf True the min is calculated over all time steps. If False, the ensemble min is calculated for each time steps; for example, if the ensemble is made up of monthly files the min for each month will be calculated.
Calculate an ensemble maximum. This operates on a grid cell by grid cell basis.
ncoDo you want to use NCO for the calculation? Default is False, i.e. CDO is used. Modify default if run time is an issue.
ignore_timeIf True the max is calculated over all time steps. If False, the ensemble max is calculated for each time steps; for example, if the ensemble is made up of monthly files the max for each month will be calculated.
Calculate an ensemble percentile. This will calculate the percentiles for each time step in the files. For example, if you had an ensemble of files where each file included 12 months of data, it would calculate the percentile for each month. This operates on a grid cell by grid cell basis.
prequiredpercentile to calculate. 0<=p<=100.
Calculate an ensemble range. The range is calculated for each time step; for example, if each file in the ensemble has 12 months of data the statistic will be calculated for each month. This operates on a grid cell by grid cell basis.
Calculate an ensemble standard deviation. The ensemble standard deviation is calculated for each time steps; for example, if the ensemble is made up of monthly files the standard deviation for each month will be calculated. This operates on a grid cell by grid cell basis.
Calculate an ensemble sum. The sum is calculated for each time step; for example, if each file in the ensemble has 12 months of data the statistic will be calculated for each month. This operates on a grid cell by grid cell basis.
Calculate an ensemble variance. The ensemble variance is calculated for each time steps; for example, if the ensemble is made up of monthly files the standard deviation for each month will be calculated. This operates on a grid cell by grid cell basis.
Merge a multi-file ensemble into a single file. 2 methods are available. 1) merging files with different variables, but the same time steps. 2) merging files with the same variables, with different times.
joinThis defines the type of merging to carry out. "variables": this will merge by variable, so that an ensemble with different variables, but the same number of time steps is merged to a single file. "time": this will merge files with the same variables, but different times to a single file, into a single file with ordered times. join defaults to "variables", and uses partial matches, so "var" will give variable based merging.
matchOptional argument when join = 'variables'. A list or str stating what must match in the netCDF files. Defaults to year/month/day. This list must be some combination of year/month/day. An error will be thrown if the elements of time in match do not match across all netCDF files. The only exception is if there is a single date file in the ensemble.
checkBy default nctoolkit out checks in case files do not have the same variables etc. Set check to False if you are confident merging will be problem free. If you are unsure if files have the same variables, set check to True to find out. Note: if you do not explicitly provide check and there are more than 30 files in a dataset, checks will be turned off.
Split the dataset. Each file in the ensemble will be separated into new files based on the splitting argument.
byrequiredAvailable by arguments are 'year', 'month', 'yearmonth', 'season', 'day' 'name', "timestep". year will split files by year, month will split files by month, yearmonth will split files by year and month; season will split files by year, day will split files by day. Using "timestep" will split files by timestep. 'name' will split by variable name
Method to get the absolute value of variables
Add to a dataset. This will add a constant, another dataset or a netCDF file to the dataset. nctoolkit will automatically determine the appropriate comparison required.
Required:
xrequiredAn int, float, single file dataset or netCDF file to add to the dataset. If a dataset or netCDF file is supplied, this must have only one variable, unless var is provided. The grids must be the same.
Optional:
varA variable in the x to use for the operation
Create new variables using mathematical operations on existing variables. Existing columns that are re-assigned will be overwritten. This method operators in a similar fashion to the pandas assign method.
dropSet to True if you want existing variables to be removed once the new ones have been created. Defaults to False.
kwargsNew variable names are keywords. All terms in the equation given by the lambda function should evaluate to a numeric. New variables are calculated for each grid cell and time step.
Method to get the exponential of variables
Method to get the natural log, ln, of variables
Method to get the base 10 log, log10, of variables
Multiply a dataset. This will multiply a dataset by a constant, another dataset or a netCDF file.
Required:
xrequiredAn int, float, single file dataset or netCDF file to multiply the dataset by. If multiplying by a dataset or single file there must only be a single variable in it, unless var is supplied. The grids must be the same.
Optional:
varA variable in the x to multiply the dataset by
Powers of variables in dataset
xrequiredAn int or float to take the variables to the power of
Method to get the square root of variables
Method to get the square of variables
Subtract from a dataset. This will subtract a constant, another dataset or a netCDF file from the dataset.
Required:
xrequiredAn int, float, single file dataset or netCDF file to subtract from the dataset. If a dataset or netCDF is supplied this must only have one variable, unless var is provided. The grids must be the same.
Optional:
varA variable in the x to use for the operation
Divide the data. This will divide the dataset by a constant, another dataset or a netCDF file.
Required:
xrequiredAn int, float, single file dataset or netCDF file to divide the dataset by. If a dataset or netCDF file is supplied, this must have only one variable, unless var is provided. The grids must be the same.
Optional:
varA variable in the x to use for the operation
These can be used inside the lambda functions passed to assign():
| Function | Description | Example |
|---|---|---|
abs | Absolute value | abs(x.sst) |
ceiling / floor | Ceiling / floor of a variable | ceiling(x.sst - 1) |
sqrt / exp / log / log10 | Square root, exponential, natural log, base-10 log | log10(x.sst + 1) |
sin / cos / tan | Trigonometric functions | cos(x.var) |
isnan | Is the value missing? | isnan(x.var) |
cell_area | Grid-cell area (m²) | cell_area(x.var) |
latitude / longitude | Coordinates of the grid cell | latitude(x.var) |
level | Vertical level of the variable | level(x.var) |
year / month / day / hour | Date/time components of the variable | month(x.var) |
timestep | Time step index (Python indexing) | timestep(x.var) |
spatial_mean / spatial_max / spatial_min / spatial_sum | Spatial statistic at each time-step | spatial_mean(x.var) |
zonal_mean / zonal_max / zonal_min / zonal_sum | Zonal statistic at each time-step | zonal_mean(x.var) |
Rename variables in a dataset
newnamesDictionary with key-value pairs being original and new variable names * kwargs. Alternative method for renaming
Change a range or individual value to missing.
valuerequiredIf int/float is provided, the missing value will be set to that. If a list is provided, values between the two values (inclusive) of the list are set to missing.
Convert missing values to a constant
valuerequiredIf int/float is provided, the missing value will be converted to that.
Set the fill value
valuerequiredThe fill value to set.
Calculate the sum of all variables for each time step
dropDo you want to keep variables?
new_nameIf you want to name the output of sum_all to a specific name
Set the long names of variables
name_dictDictionary with key, value pairs representing the variable names and their long names * kwargs. Alternative method for setting units
Set the units for variables
unit_dictA dictionary where the key-value pairs are the variables and new units respectively. * kwargs. Alternative method for setting units using direct assignment
Automatically plot a dataset.
varsA string or list of the variables to plot
autoscaleSet to True if you want the colorbar to be scaled to the min/max of the data. Default is True
outName of output file if you want to save as html. Defaults to None.
coastSet to True if you want a coastline to show up on spatial map. Default is True if a working version of cartopy is available. It is False otherwise.
kwargsOptional args to be sent to hvplot
Static plotting. This requires datasets to have regular latlon grids. Plots a static map, and requires only one variable, time step and vertical level
Required:
varrequiredVariable to plot
Optional:
dsDataset to plot
extentList with [lon_min, lon_max, lat_min, lat_max] for plotting extent
titleCharacter string with plot title
legendCharacter string with legend title
sizeList with [xsize, ysize] for plotting size
landCharacter string with colour required for land. Set to None if you do not want land to show.
coloursCharacter string with colour map to use. Set to None if you do not want to use a colour map.
normNorm to use for colour bar
limitsList with [min, max] for colour bar limits. Please note that if the colour scale passes through zero, the colour scale will be symmetrical around zero. So the limits will be reset to the maximum absolute value of the data.
projectionCartopy projection to use.
coastSet to "coarse", "low", "intermediate", "high" or "full" if you want to use GSHHS coastlines
scale"low", "medium" or "high"
gridSet to False if you do not want grid lines.
legend_position= "auto"
robustWhether to use robust statistics for the colour scale or not
outOutput file name
breaksList of breaks for the colour bar
dpiDPI for output file. Default is "figure".
kwargskwargs to allow slight misspelling of arguments -------------
Save a dataset to a named file. This will only work with single file datasets.
Required:
outrequiredOutput file name.
Optional:
zipTrue/False depending on whether you want to zip the file. Default is True.
overwriteIf out file exists, do you want to overwrite it? Default is False.
kwargsOptional arguments to be sent to subset.
Open a dataset as an xarray object
decode_timesSet to False if you do not want xarray to decode the times. Default is True. If xarray cannot decode times, CDO will be used.
kwargsOptional arguments to be sent to subset.
Convert a dataset to a pandas data frame
decode_timesSet to False if you do not want xarray to decode the times prior to conversion to data frame. Default is True.
drop_bndsSet to False if you do not want to drop the bounds from the data frame. Variables/coordinates with '_bnds' in their names will be dropped. Default is True.
kwargsOptional arguments to be sent to subset.
Zip the dataset. This will compress the files within the dataset. This will occur lazily, so will only occur after everything has been evaluated.
Change the netCDF format of a dataset. This will compress the files within the dataset. This works lazily.
extrequiredNew format. Must be one of "nc", "nc1", "nc2", "nc4" and "nc5" . netCDF = nc1 netCDF version 2 (64-bit offset) = nc2/nc netCDF4 (HDF5) = nc4 netCDF4-classi = nc4c netCDF version 5 (64-bit data) = nc5
Run all stored commands in a dataset
Temp file cleaner. Remove all files created during the session that are now out of use
Deep temp file cleaner. Remove all temporary files ever created by nctoolkit across all previous and current sesions
Calculate the number of missing values.
overTime periods to to the count over over. Options are 'time', 'year', 'month', 'day'.
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
windowThis determines the number of time steps to calculate, on a non-rolling basis. This is useful if you need to calculate the sum every 5 days, for example.
Calculate the fraction of missing values in each grid cell across all time steps.
overTime periods to to the count over over. Options are 'time', 'year', 'month', 'day'.
alignThis determines whether the output time is at the left, centre or right hand side of the time window. Options are "left", "centre" and "right"
windowThis determines the number of time steps to calculate over, on a non-rolling basis. This is useful if you need to calculate the fraction for every non-overlapping 5 day periods, for example.
Split the dataset into multiple evenly sized horizontal and vertical new files
mNumber of rows
nNumber of columns
Collect a dataset that has been split using distribute
Calculate the area of grid cells. Area of grid cells is given in square meters.
joinSet to False if you only want the cell areas to be in the output. join=True adds the areas as a variable to the dataset. Defaults to True.
Identify the time step when a value is first above a threshold. This will do the comparison with either a number, a Dataset or a netCDF file.
xrequiredAn int, float, single file dataset or netCDF file to use for the threshold(s). If comparing with a dataset or single file there must only be a single variable in it. The grids must be the same.
Identify the time step when a value is first below a threshold. This will do the comparison with either a number, a Dataset or a netCDF file.
xrequiredAn int, float, single file dataset or netCDF file to use for the threshold(s). If comparing with a dataset or single file there must only be a single variable in it. The grids must be the same.
Identify the final time step when a value is above a threshold. This will do the comparison with either a number, a Dataset or a netCDF file.
xrequiredAn int, float, single file dataset or netCDF file to use for the threshold(s). If comparing with a dataset or single file there must only be a single variable in it. The grids must be the same.
Identify the last time step when a value is below a threshold. This will do the comparison with either a number, a Dataset or a netCDF file.
xrequiredAn int, float, single file dataset or netCDF file to use for the threshold(s). If comparing with a dataset or single file there must only be a single variable in it. The grids must be the same.
Apply a cdo command
Required:
commandrequiredcdo command to call. This command must be such that "cdo {command} infile outfile" will run.
Optional:
ensembleIs this an ensemble method command? For example ensmean, mergetime, etc.
checkCheck whether the command is valid
Apply an nco command
Required:
commandrequirednco command to call. This must be of a form such that "nco {command} infile outfile" will run.
Optional:
ensembleSet to True if you want the command to take all of the files as input. This is useful for ensemble methods.
Compare all variables to a constant
expressionrequiredThis a regular comparison such as "<0", ">0", "==0"
Method to calculate if variable in dataset is greater than that in another file or dataset. This currently only works with single file datasets
xrequiredFile path or nctoolkit dataset
Method to calculate if variable in dataset is less than that in another file or dataset. This currently only works with single file datasets
xrequiredFile path or nctoolkit dataset
Reduce dimensions of data. This will remove any dimensions with only one value. For example, if only selecting one vertical level, the vertical dimension will be removed.
Reduce the dataset to non-zero locations in a mask
maskrequiredsingle variable dataset or path to .nc file. The mask must have an identical grid to the dataset.
Set the precision in a dataset
xrequiredThe precision. One of 'I8', 'I16', 'I32', 'F32', 'F64'.
Check contents of files for common data problems.
Check if files are corrupt
A quick hack to change the grid file in North West European shelf Nemo grids.
Set the grid type. Only use this if, for example, the grid is "generic" when it should be lonlat.
gridrequiredGrid type. Needs to be one of "curvilinear", "unstructured", "dereference", "regular", "regularnn" or "lonlat".
Create a mask identifying the shallowest cell without missing values. This converts a dataset to a mask identifying which cell represents top level, for example the sea surface. 1 identifies the shallowest cell with non-missing values. Everything else is 0, or missing. At present this method only uses the first available variable from netCDF files, so it may not be suitable for all data
Remove any variables, such as bnds etc., from variables. This should probably only be done at the end of a processing chain before converting to a dataframe etc., as it is stripping away critical info for netCDF operations.
varsindividual or list of variables to select and strip. All variables will be stripped if this is not defined.
Remove leap years. This uses an undocumented CDO feature to remove Feb 29 and sets the calendar to leap year free
Set a variable/dimension to double. This is mostly useful for cases when time is stored as an int, but you need a double
xrequiredA list of variable/dimensions you want to convert to floats
Cast one or more variables/dimensions to a specific numeric type.
xrequiredA dictionary mapping variables to type. Values in dict must be one of 'int', 'float32' and 'float64'.
Simple method to fully reset a datset