plans.datasets.core#
Primitive classes for handling datasets.
Functions
|
Utility function for dataframe pre-processing. |
|
Utility function to get a list of random colors |
Classes
|
A Quali-Hard is a hard-coded qualitative map (that is, the table is pre-set) |
|
Basic qualitative raster map dataset. |
|
The raster collection base dataset. |
|
A |
|
The basic Raster map dataset. |
|
The raster collection base dataset. |
|
A |
|
Scientific (float32) raster dataset with a configurable nodata value and display range. |
|
Ensemble of the years of a single series, for seasonal plots. |
|
A time series dataset with a datetime-indexed variable. |
|
Collection of same-variable time series from different sites (e.g., a network of rain gauges). |
|
A collection of time series objects with associated metadata. |
|
Collection of same-variable time series as realizations of the same series (same site and time), e.g., stochastic draws or model runs. |
|
Zones map dataset is a QualiRaster designed to handle large volume of positive integer numbers (ids of zones) |
- plans.datasets.core.dataframe_prepro(dataframe)[source]#
Utility function for dataframe pre-processing.
- Parameters:
dataframe (
pandas.DataFrame) – incoming dataframe- Returns:
prepared dataframe
- Return type:
pandas.DataFrame
- plans.datasets.core.get_colors(size=10, cmap='tab20', randomize=True)[source]#
Utility function to get a list of random colors
- Parameters:
size (int) – Size of list of colors
cmap (str) – Name of matplotlib color map (cmap)
- Returns:
list of random colors
- Return type:
list
- class plans.datasets.core.TimeSeries(name='MyTimeSeries', alias='TS0')[source]#
Bases:
UnivarA time series dataset with a datetime-indexed variable.
Extends
Univarwith temporal structure: frequency detection, standardization, gap analysis, and scaling.- EPOCHS_ROWS = 14#
- _set_frequency()[source]#
Infer the datetime frequency of the time series from the spacing between consecutive timestamps.
The mode (most common value) of consecutive timestamp deltas is used to determine the frequency, rather than checking which calendar components (seconds, minutes, hours, …) vary across the series. This makes detection robust to a small minority of jittered or missing timestamps: as long as the majority of gaps between consecutive records share the same spacing, that spacing wins, even if a few records are irregular.
Sets
self.dtfreqto one of the supported Pandas-like frequency aliases ("1min","20min","h","D","MS","YS") based on which boundary the modal delta falls into, andself.dtresto the corresponding resolution label ("second","minute","hour","day","month","year").For
"MS"and"YS"frequencies,self.gapsizeis also forced to1, since a single missing month or year is already a meaningful gap at that resolution.Note
Detection is based on the majority delta, not a strict consistency check. If irregular spacing accounts for more than half of the deltas in the series, the detected frequency will reflect that majority rather than the “intended” sampling rate. Always sanity-check
self.dtfreqafter loading unfamiliar or untrusted data.- Returns:
None. Updates
self.dtfreq,self.dtres, and possiblyself.gapsizein place.- Return type:
None
- get_metadata()[source]#
Get a dictionary with object metadata. Expected to increment superior methods.
Note
Metadata does not necessarily inclue all object attributes.
- Returns:
dictionary with all metadata
- Return type:
dict
- get_range_datetime()[source]#
Return the [start, end] datetime extent of the loaded data.
- Returns:
Two-element list of [min, max] Timestamps.
- Return type:
list
- get_seasonal_ensemble(year_start=1)[source]#
Get an ensemble with one member per year of the series.
- Parameters:
year_start (int) – first month of the year, from 1 to 12. Default is 1.
- Returns:
ensemble with members of the same type as this series
- Return type:
- update()[source]#
Update internal attributes based on the current data.
Notes
Calls the
set_frequencymethod to update the datetime frequency attribute.Updates the
startattribute with the minimum datetime value in the data.Updates the
endattribute with the maximum datetime value in the data.Updates the
var_minattribute with the minimum value of the variable field in the data.Updates the
var_maxattribute with the maximum value of the variable field in the data.Updates the
data_sizeattribute with the length of the data.Refreshes the default
view_specs. Specs set by the user are kept.
- setter(dict_setter, load_data=True)[source]#
Set selected attributes based on an incoming dictionary. Expected to increment superior methods.
- Parameters:
dict_setter (dict) – incoming dictionary with attribute values
load_data (bool) – option for loading data from incoming file. Default is True.
- set_data(input_df, input_dtfield, input_varfield, filter_dates=None, dropnan=False)[source]#
Set time series data from an inputs DataFrame.
- Parameters:
input_df (
pandas.DataFrame) – Input DataFrame containing time series data.input_dtfield (str) – Name of the datetime field in the inputs DataFrame.
input_varfield (str) – Name of the variable field in the inputs DataFrame.
filter_dates – List of [Start, End] used for filtering date range.
dropnan (bool) – If True, drop NaN values from the DataFrame. Default is False.
Notes
Assumes the inputs DataFrame has a datetime column in the format “YYYY-mm-DD HH:MM:SS”.
Renames columns to standard format (datetime:
self.dtfield, variable:self.varfield).Converts the datetime column to standard format.
- load_data(file_data, input_dtfield=None, input_varfield=None, in_sep=';', filter_dates=None)[source]#
Load data from file. Expected to overwrite superior methods.
- Parameters:
file_data (str) – Absolute Path to the
csvinputs file.input_varfield (str) – Name of the incoming varfield.
input_dtfield (str) – Name of the incoming datetime field. Default is “datetime”.
sep (list) – String separator. Default is
;.filter_dates – List of start and end date to filter. Default is None
Notes
Assumes the inputs file is in
csvformat.Expects a datetime column in the format
YYYY-mm-DD HH:MM:SS.
- cut_edges(inplace=False)[source]#
Cut off initial and final NaN records in a given time series.
- Parameters:
inplace (bool) – If True, the operation will be performed in-place, and the original data will be modified. If False, a new DataFrame with cut edges will be returned, and the original data will remain unchanged. Default is False.
- Returns:
If inplace is False, a new DataFrame with cut edges. If inplace is True, returns None, and the original data is modified in-place.
- Return type:
pandas.DataFrame``or None
Notes
This function removes leading and trailing rows with NaN values in the specified variable field.
The operation is performed on a copy of the original data, and the original data remains unchanged.
- _cut_edges(df)[source]#
Get a dataframe without its initial and final NaN records.
- Parameters:
df (
pandas.DataFrame) – dataframe with the variable field- Returns:
copy of the dataframe, unchanged if all records are NaN
- Return type:
pandas.DataFrame
- standardize()[source]#
Force the time series onto a regular datetime grid at its detected frequency.
This builds a full, evenly-spaced date range spanning the series’ start to end (at day resolution) and left-merges the existing data onto it. Any regular-grid slot that has no matching timestamp in the original data becomes a row with a null value in
varfield– i.e. standardizing an irregular series (one with missing timestamps) is what turns those missing timestamps into explicit gaps.If multiple original records fall within the same grid slot (e.g. two readings a few minutes apart, both bucketed into the same hour), they are aggregated using the
aggattribute (e.g."mean") before being placed in that slot.Notes
The target frequency is read from
self.dtfreq, which is set by_set_frequency()(called automatically on load, based on the mode of consecutive timestamp deltas – robust to a handful of jittered or missing timestamps, but not to a majority of them).Bucketing uses
.dt.floor()for fixed-frequency grids (1min,20min,h,D) and calendar-aware period flooring for calendar-variable grids (MS,YS), so each timestamp is always bucketed independently based on its own value, never merged with unrelated timestamps in the same coarser unit.Sets
self.is_standard = Trueon completion. Methods that need the regular grid (e.g.get_epochs,interpolate_gaps) work on a regular copy while this flag isFalse, leavingself.dataas it is.Calls
self.update()at the end, refreshing derived statistics to reflect the new (possibly larger, possibly gap-containing) data.
Warning
This method modifies
self.datain place (there is noinplaceparameter). If you need the original, irregular data preserved, keep a separate reference or acopy.deepcopyof the object before calling this method.Warning
Row count generally increases after standardizing an irregular series, since missing grid slots are inserted as null rows. Review
len(self.data)and the null count after calling this method rather than assuming they’re unchanged.- Returns:
None. Updates
self.dataandself.is_standardin place.- Return type:
None
- Example:
>>> ts.is_standard False >>> len(ts.data) 311 >>> ts.standardize() >>> ts.is_standard True >>> len(ts.data) # now includes inserted null rows 360 >>> ts.data[ts.varfield].isna().sum() 49
- _get_standard_data(cut=False)[source]#
Get a copy of the data on the regular grid. The series is not changed.
- Parameters:
cut (bool) – If True, also cut off the initial and final NaN records.
- Returns:
data on the regular grid
- Return type:
pandas.DataFrame
- clear_outliers(inplace=False)[source]#
Clears outlier values from the specified variable field in the DataFrame.
- Parameters:
inplace (if inplace is True, otherwise the DataFrame with outliers cleared.) – If True, the operation is performed in-place, modifying the DataFrame directly. If False, a new DataFrame with outliers removed is returned. Default value = False
- Return type:
pandas.DataFrameor None
- get_epochs(inplace=False)[source]#
Get Epochs (periods) for continuous time series (0 = gap epoch).
- Parameters:
inplace (bool) – Option to set Epochs inplace. Default is False.
- Returns:
A DataFrame if inplace is False or None.
- Return type:
pandas.DataFrame`, None
Notes
This function labels continuous chunks of data as Epochs, with Epoch 0 representing gaps in the time series. Missing timestamps count as gaps, since the labels are made on the regular grid.
With
inplace=True, the data becomes the labeled regular grid.
- _label_epochs(df)[source]#
Label the records of a dataframe by epoch (0 = gap epoch).
- Parameters:
df (
pandas.DataFrame) – dataframe with the variable field, one record per time step- Returns:
copy of the dataframe with the epoch field
- Return type:
pandas.DataFrame
- update_epochs_stats()[source]#
Update all epochs statistics.
Notes
This function updates statistics for all epochs in the time series.
Works on a regular copy of the data without its NaN edges. The data itself is not changed.
Removes epoch 0 from the statistics since it typically represents non-standardized or invalid data.
Groups the data by and calculates statistics such as count, start, and end timestamps for each epoch.
Generates random colors for each epoch using the
get_random_colorsfunction with a specified colormap (cmap` attribute).Includes the time series name in the statistics for identification.
Organizes the statistics DataFrame to include relevant columns
Updates the attribute with the number of epochs in the statistics.
- interpolate_gaps(method='linear', constant=0, inplace=False)[source]#
Fills gaps in a time series using various interpolation methods.
- Parameters:
method (str) – Specifies the interpolation method. The default value is
linear.constant (float) – The constant value used when the
constantmethod is selected. Default value = 0.inplace (bool) – If True, modifies the original DataFrame in-place. Default value = False.
- Returns:
A new
pandas.DataFramewith interpolated values and anis_interpolationflag column (1 where the value was filled by interpolation, 0 where it was already present) if inplace is False, otherwise None.- Return type:
pandas.DataFrameor None
Notes
The interpolation runs on the regular grid. The series is only standardized if
inplaceis True. The process is applied to each unique epoch within the series.linear: linear interpolationnearest: uses the value of the closest data point.zero: fills gaps with zeros.constant: fills gaps with a constant value provided in method parameterslinear: first order spline interpolationquadratic: second order spline interpolationcubic: third order spline interpolation
- aggregate(freq, bad_max, agg_funcs=None)[source]#
Aggregate the time series data based on a specified frequency using various aggregation functions.
- Parameters:
freq (str) – Pandas-like alias frequency at which to aggregate the time series data.
bad_max (int) – The maximum number of
Badrecords allowed in a time window for aggregation. Records with moreBadentries will be excluded from the aggregated result. Default is 7.agg_funcs (dict) – A dictionary specifying customized aggregation functions for each variable. Default is None, which uses standard aggregation functions (sum, mean, median, min, max, std, var, percentiles).
- Returns:
A new pandas.DataFrame with aggregated values based on the specified frequency.
- Return type:
pandas.DataFrame
Notes
Resamples the time series data to the specified frequency using Pandas-like alias strings. Aggregates the values using the specified aggregation functions. Counts the number of
Badrecords in each time window and excludes time windows with moreBadentries than the specified threshold.- Common options include:
hfor hourly frequencyDfor daily frequencyWfor weekly frequencyMSfor monthly/start frequencyQSfor quarterly/start frequencyYSfor yearly/start frequency
More options and details can be found in the Pandas documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases.
- scale_up(freq, bad_max, inplace=True)[source]#
Upscale time series for larger time steps. This method uses the agg attribute. See the aggregate method.
- Parameters:
freq (str) –
Pandas-like alias frequency at which to aggregate the time series data. Common options include: -
hfor hourly frequency -Dfor daily frequency -Wfor weekly frequency -MSfor monthly/start frequency -QSfor quarterly/start frequency -YSfor yearly/start frequency More options and details can be found in the Pandas documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#timeseries-offset-aliases.Anchoring behavior – this affects where each aggregation window starts/ends:
Plain multiples of a base unit (e.g.
"5D"for a pentad,"10D") are data-start-anchored: bins are chunked every N units starting from wherever the series begins, not from a fixed calendar boundary.Calendar units (
W,MS,QS,YS, etc.) are calendar-anchored: bins snap to fixed real-world boundaries regardless of where the data starts.Wdefaults toW-SUN(weeks ending Sunday). Anchor to any weekday with a suffix, e.g.W-MON,W-WED,W-FRI.YS/YEdefault to the calendar year (start Jan 1 / end Dec 31). Anchor to any month with a suffix to define e.g. a hydrological/water year:"YS-OCT"(year starting Oct 1, e.g. US water year convention) or"YE-SEP"(year ending Sep 30). The suffix month plusYS-/YE-together set whether that month is the start or the end of the bin.
bad_max (int) – The maximum number of
Badrecords allowed in a time window for aggregation. Records with moreBadentries will be excluded from the aggregated result.inplace (bool) – option for overwrite data, default True. When False, returns a new
TimeSeriesobject (an exact copy ofself) holding the upscaled data, instead of a bare DataFrame.
- Returns:
Noneifinplace=True(data is overwritten in place), otherwise a newTimeSeriesinstance of the same subclass asself, with identical metadata and the upscaled data/derived stats.- Return type:
None or TimeSeries
- Example:
>>> # Pentad upscale (data-start-anchored) >>> ts_pentad = ts.scale_up(freq="5D", bad_max=0, inplace=False) >>> # Weekly upscale, anchored to Monday-ending weeks >>> ts_weekly = ts.scale_up(freq="W-MON", bad_max=0, inplace=False) >>> # Hydrological year, Oct-Sep >>> ts_hydro = ts.scale_up(freq="YS-OCT", bad_max=0, inplace=False)
- scale_down(freq, covariate=None, align='center', inplace=False)[source]#
Downscale the time series to a finer time step.
For non-flow variables (
self.agg != "sum"), each coarse data point is first repositioned in time according toalign(see below), then linearly interpolated onto the finer grid. Because this repositioning shifts the interpolation anchors away from a naive “value at period start” assumption, a single global multiplicative correction is applied afterward so that the downscaled series’ overall mean exactly matches the original series’ overall mean. Note this conserves the mean of the whole series, not each individual period – an earlier, stricter per-period mean-preserving approach was found to produce unstable, oscillating results with volatile inputs and was intentionally not used here.The
alignparameter controls where each coarse point is assumed to sit within the period it represents:"start": at the period’s own timestamp (no shift). E.g. a daily value stays anchored at00:00."center"(default): at the middle of the period. E.g. a daily value is anchored at12:00of that day."end": at the end of the period. E.g. a daily value is anchored at the following day’s00:00.
Anchor placement leaves flat (constant) values outside the earliest/latest anchor – e.g. with
align="center", there is no data before the first period’s midpoint, so the interpolated series holds that first value flat until the midpoint is reached.For flow/sum variables (
self.agg == "sum", e.g. precipitation totals), each source period’s total is distributed across its fine sub-steps such that the sub-steps sum back to exactly that period’s original total – no mass leaks across period boundaries.alignis not used in this case (sum conservation is enforced directly at the level of each time step, not via anchor placement). Two modes:Uniform split (default,
covariate=None): each period’s total is split evenly across its fine sub-steps.Covariate-weighted (
covariategiven): each period’s total is distributed proportionally to a covariate signal’s own shape within that period, e.g. using a higher-resolution proxy (radar or satellite precipitation) to shape how a daily gauge total is spread across finer time steps. The covariate is linearly interpolated onto the target grid first if it isn’t already sampled atfreq. Any period where the covariate is entirely zero or missing falls back to a uniform split for that period, so covariate gaps never produceNaNor divide-by-zero results.
In both branches, the fine grid is extended one full period past the series’ last timestamp so the final period is subdivided the same way as every other period, rather than being collapsed into a single fine step holding that whole period’s value.
- Parameters:
freq (str) – new time step frequency
covariate (TimeSeries or None) – optional higher-resolution
TimeSerieswhose values are used to shape the within-period distribution for flow/sum variables. Ignored whenself.agg != "sum".align (str) – for non-sum variables, where each coarse point is anchored within its period:
"start","center"(default), or"end". Ignored whenself.agg == "sum".inplace (bool) – option for overwrite data, default False. When
True, overwritesself.datawith the downscaled result and returnsNone. WhenFalse(default), returns a newTimeSeriesinstance (an exact copy ofself) holding the downscaled data, instead of a bare DataFrame.
- Returns:
Noneifinplace=True(data is overwritten in place), otherwise a newTimeSeriesinstance of the same subclass asself, with identical metadata and the downscaled data/derived stats.- Return type:
None or TimeSeries
- Example:
>>> # non-sum variable, e.g. daily-average water level -> hourly, >>> # anchored at midday, overall mean preserved >>> ts_level_hourly = ts_level.scale_down(freq="1h") >>> # uniform split: each day's total spread evenly across hours >>> ts_flat = ts_daily.scale_down(freq="1h") >>> # covariate-weighted: shaped by an hourly satellite proxy >>> ts_shaped = ts_daily.scale_down(freq="1h", covariate=ts_satellite)
- assess_extreme_values(eva_freq='YS', eva_agg='max')[source]#
Run Extreme Values Analysis (EVA) over the Time Series and set the
evaattribute- Parameters:
eva_freq (str) – standard pandas frequency alias for upscaling data
eva_agg (str) – standard pandas aggregation alias for upscaling (expected:
maxormin)
- _build_axes(fig, gs, specs)[source]#
Add subplots to the figure grid according to the active layout.
- _plot(fig, gs, specs)[source]#
Plot on figure based on layout.
- Parameters:
fig (
matplotlib.figure.Figure) – figure objectgs (
matplotlib.gridspec.GridSpec) – grid of the figurespecs (dict) – plot specification dictionary
- Returns:
figure object
- Return type:
matplotlib.figure.Figure
- view(show=True, return_fig=False)[source]#
View the TimeSeries data.
Note
Use values in the
view_specs()attribute for plottingLayouts, set by
view_specs["layout"]:Layout
Panels
fullSeries, histogram and CDF, with the statistics table.
miniSeries, histogram and CDF.
simpleSeries only.
simple-shallowSeries only, in a shallow figure.
epochsSeries with epochs in colors and gaps in the background, and the list of epochs.
defaultSame panels of
mini, in the figure offull.View specs, set by
view_specs[key] = valuebefore the call:Key
Default
Description
style"wien"Name of the plot style. See
plans.viewer.set_style().folderauto
Folder of the saved figure.
filenameauto
Name of the saved figure, without extension.
fig_format"jpg"Format of the saved figure.
dpi300Resolution of the saved figure.
titleauto
Title of the figure.
xvarauto
Internal. Column of dates.
yvarauto
Internal. Column of values.
xlabelauto
Label of the x axis.
ylabelauto
Label of the y axis.
color"gray"Color of the line.
xminNone
Not in use.
xmaxNone
Not in use.
ymin0Bottom of the fill.
ymaxNone
Not in use.
layout"full"Name of the layout. See the table of layouts.
data_plot"scatter"Plot of the data panel:
"scatter"or"boxplot".subtitle_data"Time Series"Title of the series panel. None hides it.
subtitle_box"Boxplot"Title of the data panel, if a boxplot.
subtitle_hist"Histogram"Title of the histogram. None hides it.
subtitle_cdf"CDF"Title of the CDF. None hides it.
subtitle_qq"Q-Q"Title of the Q-Q panel. None hides it.
yvar_fieldauto
Column of values. Set with the data.
xlabel_cdf"P(X)"Label of the x axis of the CDF.
xlabel_qqauto
Label of the x axis of the Q-Q panel.
data_labelauto
Label of the data in the legend.
data_legendFalseShow the legend of the data panel.
color_hist"tab:grey"Color of the histogram.
color_cdf"black"Color of the CDF.
color_mean"red"Color of the mean line.
color_mean_textNone
Color of the mean label. None is gray.
scheme_cmap"equal"Classes of the color map:
"equal","quantiles"or other schemes ofplans.stochastic.binning.get_bins().n_classes_cmap5Number of classes of the color map.
cmap"viridis"Name of the color map.
alpha1Opacity of the line.
alpha_hist1Opacity of the histogram.
alpha_cdf1Opacity of the CDF.
rangeNone
Range of the y axis, as
[low, high]. None is set from the data.range_xNone
Range of the x axis, as
[low, high]. None is the time span withpad_x.plot_meanTrueShow the mean line.
plot_mean_dataFalseShow the mean line also on the data panel.
linestyle_mean"solid"Line style of the mean.
pad_mean1Spaces between the mean label and its line.
plot_mean_labelTrueShow the mean label.
hist_densityTrueNot in use.
bins20Number of histogram bins, or the width of the bins if
bins_density.bins_densityFalseTake
binsas the width of the bins.ax_data0Internal. Index of the data axis.
ax_hist1Internal. Index of the histogram axis. False has no histogram.
ax_cdf2Internal. Index of the CDF axis. False has no CDF.
x_stats0.73Horizontal position of the statistics table, as a share of the figure.
x_stats_sep0.12Space between columns of the statistics table.
y_stats0.28Vertical position of the statistics table, as a share of the figure.
zorder_data1Drawing order of the data.
zorder_histh1Drawing order of the histogram.
zorder_cdf1Drawing order of the CDF.
scatter_factor4Size of the scatter markers.
colorize_scatterFalseColor the scatter markers by the color map.
box_width0.4Width of the boxplot.
box_showfliersTrueShow the outliers of the boxplot.
subtitle_epochs"Epochs"Title of the list of epochs, in the
epochslayout.color_aux"gray"Not in use.
color_fillNone
Color of the fill. None is the color of the line.
color_eva"blue"Color of the annual maxima.
legend_eva"Annual Maxima"Label of the annual maxima.
alpha_aux1Not in use.
alpha_fill1Opacity of the fill.
fillFalseFill below the line, down to
ymin.fill_onlyFalseWith
fill, hide the line.color_gaps"tab:red"Color of the gaps, in the
epochslayout.alpha_gaps0.6Opacity of the gaps, in the
epochslayout.linewidth_gaps0.5Width of the edge of the gaps, which keeps short ones visible.
xmax_aux20Not in use.
pad_x0.05Share of the time span added on each side of the x axis, if
range_xis None.linestyle"solid"Line style.
markerNone
Marker of the line.
marker_eva"."Not in use.
drawstyleNone
Draw style of the line, such as
"steps-mid".n_bins100Not in use.
n_dates5Number of date ticks, evenly spaced in time. None chooses them automatically.
format_dates"%Y-%m-%d"Format of the date labels.
include_evaFalseShow the annual maxima and their model. Needs the extreme values analysis.
gs_*auto
Internal. Replaced by the shared grid of
plans.viewer.- Parameters:
show (bool) – option for showing instead of saving.
return_fig (bool) – option for returning the figure object itself.
- _plot_epochs(ax, ax_legend, specs)[source]#
Plot each epoch in its own color and the gaps in the background, with the list of epochs on the side. The series is not changed.
- Parameters:
ax (
matplotlib.axes.Axes) – axis of the seriesax_legend (
matplotlib.axes.Axes) – axis of the legendspecs (dict) – plot specification dictionary
- Returns:
None
- Return type:
None
- static get_range_x(xmin, xmax, pad)[source]#
Get the range of a time axis with a padding on each side.
- Parameters:
xmin (
pandas.Timestamp) – first datexmax (
pandas.Timestamp) – last datepad (float) – share of the time span added on each side
- Returns:
first and last date of the range
- Return type:
list
- static set_date_ticks(ax, xmin, xmax, n_dates, format_dates)[source]#
Set ticks evenly spaced in calendar time on a time axis, within its limits.
- Parameters:
ax (
matplotlib.axes.Axes) – target axisxmin (
pandas.Timestamp) – date of the first tickxmax (
pandas.Timestamp) – date of the last tickn_dates (int) – number of ticks. If None, they are chosen automatically
format_dates (str) – format of the dates. If None, it is the current one
- Returns:
None
- Return type:
None
- static plot_series(data, ax, specs)[source]#
Draw a time series line (and optional fill) onto an existing axes.
- Parameters:
data (
pandas.DataFrame) – DataFrame containing the series to plot.ax (
matplotlib.axes.Axes) – Target Matplotlib axes.specs (dict) – Plot specification dictionary (from
view_specs).
- static add_hour(df, hour=12, dt_field='datetime')[source]#
Set the time component of a date-only datetime column to a fixed hour.
- Parameters:
df (
pandas.DataFrame) – DataFrame with a datetime column to modify.hour (int) – Hour to set. Default is 12 (noon).
dt_field (str) – Name of the datetime column. Default is
"datetime".
- Returns:
DataFrame with the datetime column updated.
- Return type:
pandas.DataFrame
- static view_compare_times_series(ts_first, ts_second, specs, show=False, return_fig=False)[source]#
Plot two
TimeSeriesobjects together for visual comparison.Renders a three-panel figure – the two series overlaid on a shared time axis, a horizontal histogram, and a CDF – using
ts_first’s panel layout as the base and drawingts_secondon top of it. Both series are shown with their own colors (taken from each object’sview_specs["color"]) and labeled with their respectivenameattributes; each series’ mean is annotated on the CDF panel.- Parameters:
ts_first (TimeSeries) – The first time series to plot. Its own
view_specssupplies the base panel layout (axes, figure size, etc.); setts_first.view_specs["color"]before calling to control its plotted color.ts_second (TimeSeries) – The second time series to plot on top of the first. Likewise, set
ts_second.view_specs["color"]to control its color.specs (dict) – Plot overrides applied to both series before plotting (merged into each series’
view_specs). Must include"title". Ifreturn_figisFalse, must also include"folder"and"filename"(used to build the output file path);"dpi"and"fig_format"are taken fromts_first.view_specsregardless of what is passed inspecs. Without"range", the y axis of all panels covers both series.show (bool) – If
return_figisFalse, whether to display the figure interactively in addition to saving it. Ignored ifreturn_figisTrue.return_fig (bool) – If
True, return the MatplotlibFigureinstead of saving it to disk. Useful for inline display (e.g. in a notebook) or for further customization before saving.
- Returns:
The
Figureifreturn_fig=True, otherwiseNone(the figure is saved to"{folder}/{filename}.{fig_format}").- Return type:
matplotlib.figure.Figureor None
Note
Both input objects’
view_specsare mutated in place by this method (colors, labels, layout, and the contents ofspecsare all written intots_first.view_specs/ts_second.view_specs). If you need the originals preserved, pass copies.- Example:
>>> ts1.view_specs["color"] = "tab:blue" >>> ts2.view_specs["color"] = "tab:orange" >>> fig = TimeSeries.view_compare_times_series( ... ts1, ts2, specs={"title": "Site A vs Site B"}, return_fig=True ... )
- static _get_steps_per_year(freq)[source]#
Get the number of time steps in a year for a frequency.
- Parameters:
freq (str) – frequency alias
- Returns:
steps per year, a whole number when the steps follow the calendar
- Return type:
float
- _get_generator_params(start, freq, n)[source]#
Convert
generator_specsto the parameters of a given time step.\[\varphi = e^{-\Delta t / \tau}, \qquad \sigma = s \sqrt{1 - \varphi^2}\]- Parameters:
start (
pandas.Timestamp) – first date of the seriesfreq (str) – frequency alias
n (int) – number of steps
- Returns:
parameters. See
plans.stochastic.arma.fit_params().- Return type:
dict
- generate(start, end, freq=None, params=None, seed=None, inplace=False)[source]#
Generate a synthetic series with trend, a yearly cycle and AR(1) memory.
Without
params, it uses thegenerator_specsattribute, which each child class sets for its own variable and which can be edited. These specs are in physical terms, so they apply to any time step:baselineandtopline: lowest and highest points of the yearly cycle, at the middle of the record. Per day if the object aggregates by sum.peak_day: day of the year of the peak.power: shape of the cycle. Seeplans.stochastic.arma.cycle_shape().memory_days: time for the memory of the remainder to decay by a factor of e.remainder_sd: standard deviation of the remainder. Per day if aggregated by sum.change_per_year: change of the trend per year. Per day if aggregated by sum.
Values below
generator_floorare pruned to it, if it is set.Warning
Default specs are plausible values for examples, not climatology. There is no daily cycle at any time step, since sub-daily series are meant to come from downscaling a daily series.
- Parameters:
start (str or
pandas.Timestamp) – first dateend (str or
pandas.Timestamp) – last datefreq (str) – frequency alias. By default, it is the one in
paramsorD.params (dict) – parameters, usually from
fit(). Those fromfit()follow the calendar, so the cycle and trend carry over to anystart.seed (int) – random seed
inplace (bool) – If True, sets the data of this object. Default value = False
- Returns:
generated data if inplace is False, otherwise None.
- Return type:
pandas.DataFrameor None
- static _move_params(params, start)[source]#
Move step 0 of the parameters from their origin, if any, to a new start.
- Parameters:
params (dict) – parameters
start (
pandas.Timestamp) – new first date
- Returns:
parameters that apply from the new start
- Return type:
dict
- decompose(params=None)[source]#
Split the data into trend, cycle, remainder and shocks. The data is not changed. The remainder holds the memory and the shocks, so that
trend + cycle + remainderrebuilds the data.- Parameters:
params (dict) – parameters. By default, they come from
fit().- Returns:
dates and components, in columns
trend,cycle,remainderandshocks- Return type:
pandas.DataFrame
- fit()[source]#
Fit the generator parameters to the data. The data is not changed.
The time step comes from the timestamps, so the data must be regular and without gaps. Use
standardize()andinterpolate_gaps()first if needed.- Returns:
parameters from
plans.stochastic.arma.fit_params(), and alsooriginandfreq, sogenerate()can use them from any date.- Return type:
dict
- class plans.datasets.core.TimeSeriesCollection(name='myTSCollection', base_object=None)[source]#
Bases:
CollectionA collection of time series objects with associated metadata.
The
TimeSeriesCollectionclass extends theCollectionclass and is designed to handle time series data. It can be miscellaneous datasets.Note
See
TimeSeriesClusterfor managing time series of the same variable- PANEL_ROWS = 5#
- PANEL_GAP_ROWS = 2#
- ROW_HEIGHT = 5#
- __init__(name='myTSCollection', base_object=None)[source]#
Initialize the
Collectionobject.- Parameters:
base_object (
MbaE) –MbaE-based object for collectionname (str) – unique object name
alias (str) – unique object alias.
- update(details=False)[source]#
Update the time series collection.
- Parameters:
details (bool) – bool, optional If True, update additional details. Default is False.
Examples
- load_data(table_file, filter_dates=None)[source]#
Load data from table file (information table) into the time series collection.
- Parameters:
table_file (str) – Path to file. Expected to be a
csvtable.
- set_data(df_info, src_dir=None, filter_dates=None)[source]#
Set data for the time series collection from a info class:pandas.DataFrame.
- Parameters:
df_info (class:pandas.DataFrame) – This DataFrame is expected to have matching fields to the metadata keys.
src_dir (str) – Path for inputs directory in the case for only file names in
Filecolumn.filter_dates (str) – List of Start and End dates for filter data
Notes
The
set_datamethod populates the time series collection with data based on the provided DataFrame.It creates time series objects, loads data, and performs additional processing steps.
Adjust
skip_processaccording to your data processing needs.
- clear_outliers()[source]#
Clear outliers in the collection based on the
datarange_minanddatarange_maxattributes.
- merge_data(standard=False)[source]#
Merge data from every series in the collection into one DataFrame, aligned by an outer join on the datetime field.
- Parameters:
standard (bool) – If True, merge the data of each series on its regular grid, so missing timestamps show up. The series are not changed.
- Returns:
A merged DataFrame with one datetime column and one value column per series (named
"{variable_field}_{alias}").- Return type:
pandas.DataFrame
Notes
This is a passive alignment: the datetime axis is the union of every series’ own timestamps, nothing more. It does not assume, pick, or resample onto any single frequency – a collection is explicitly allowed to mix a daily and an hourly series, and each keeps its own native timestamps here. A daily series simply has no row (NaN) at the hourly series’ intermediate timestamps, and vice versa; nothing is invented and nothing is thrown away. This also means the result is read-only with respect to the members: it is a view for reporting/analysis, and is never written back into any series’ own
.data(seestandardize()).
- standardize()[source]#
Standardize every series in the collection, independently.
- Notes:
This is deliberately just a batched per-series operation: each member calls its own
TimeSeries.standardize()(regularize onto its own native time step), and its own epoch stats are refreshed. Gaps stay as they are. Filling them is a separate decision, seeTimeSeries.interpolate_gaps().No cross-series merge happens here, and no series’
.datais touched by any other series. A collection is explicitly allowed to mix frequencies (e.g. hourly temperature alongside daily rainfall), so there is no single shared grid to standardize onto – that would mean picking one series’ frequency as authoritative and silently resampling everyone else onto it, corrupting their native resolution. Cross-series alignment for reporting/analysis is a separate, non-destructive concern: seemerge_data()andget_epochs().
- merge_local_epochs()[source]#
Merge local epochs statistics from individual time series within the collection.
- Returns:
Merged
pandas.DataFrame``containing epochs statistics.- Return type:
pandas.DataFrame
Notes
This method creates an empty list to store individual epochs statistics dataframes.
It iterates through each time series in the collection.
For each time series, it updates the local epochs statistics using the :meth:
update_epochs_statsmethod.The local epochs statistics dataframes are then appended to the list.
Finally, the list of dataframes is concatenated into a single dataframe.
- get_epochs()[source]#
Calculate epochs for the time series data.
- Returns:
DataFrame with epochs information.
- Return type:
pandas.DataFrame
Notes
This method merges the time series data to create a working DataFrame.
It creates a copy of the DataFrame for NaN-value calculation.
Converts non-NaN values to 1 and NaN values to 0.
Calculates the sum of non-NaN values for each row and updates the DataFrame with the result.
Extracts relevant columns for epoch calculation.
Sets 0 values in the specified
overfieldcolumn to NaN.Creates a new
TimeSeries`instance for epoch calculation using theoverfieldvalues.Calculates epochs using the :meth:
get_epochsmethod of the newTimeSeries`instance.Updates the original DataFrame with the calculated epochs.
- _set_view_specs()[source]#
Set view specifications for the collection dashboard plot (Gantt chart of per-series epochs + cross-series overlap + series prevalence). Mirrors the
TimeSeries/Univarpattern: everything the plot needs lives inself.view_specsand is consumed by_get_fig_specs()/_plot().
- _set_series_layouts()[source]#
Register the
serieslayouts. Meant for same-variable subclasses only, since series of different variables can not share axes.
- _get_fig_specs()[source]#
Merge
view_specswith the chosen namedlayout’s sizing and with the shared grid defaults (viewer.GRID_SPECS).
- _get_panels(specs)[source]#
Get the names of series in each panel, checking them. Series in a panel share an axis, so they must have the same units.
- Parameters:
specs (dict) – plot specification dictionary
- Returns:
names of series, for each panel
- Return type:
list
- _get_panel_rows(specs)[source]#
Get the grid rows of each panel, by share of the total height.
- Parameters:
specs (dict) – plot specification dictionary
- Returns:
number of rows, for each panel
- Return type:
list
- _plot(fig, gs, specs)[source]#
Draw the Gantt / overlap / prevalence panels onto
figusing proper Axes objects (ax.set_xlim(...)etc.) rather than statefulplt.*calls, so this composes safely with other plots and is safe to call more than once per session.
- _get_range_x(specs)[source]#
Get the time axis: from the first date to the last one of all series, with a padding on the sides not set by
xminandxmax.- Parameters:
specs (dict) – plot specification dictionary
- Returns:
first and last tick, and the range of the axis
- Return type:
tuple
- _plot_series(axes, specs, extra=None, force_background=False)[source]#
Plot all series overlaid: series, and (if axes are given) horizontal histograms and CDFs. Reuses the single
TimeSeriesplotters.Series in
highlightare drawn in color on top of the others, drawn in background style. Aboven_series_maxseries without highlights, all series are background. Withplot_backgroundoff, background series leave the series panel, but stay in the histograms and CDFs.Layers, from the bottom: background, bands (from the ensemble), extras and members in color.
- Parameters:
axes (list) – axes to plot on (1 or 3)
specs (dict) – plot specification dictionary
extra (list) – [optional] foreground series that are not members (e.g., ensemble reducers)
force_background (bool) – option to draw all non-highlighted members in background style
- Returns:
None
- Return type:
None
- _set_series_legend(axes, specs)[source]#
Set the legend of labeled (foreground) artists of the series panel.
- _clear_title(fig, title)[source]#
Lower the top of all panels if legend rows reach the figure title.
- Parameters:
fig (
matplotlib.figure.Figure) – figure with the panels, the first one having the legendtitle (
matplotlib.text.Text) – figure title
- Returns:
None
- Return type:
None
- _plot_stacked(axes, specs)[source]#
Plot series on stacked panels with a shared time axis, and (if axes are given) their histograms and CDFs. A lone series looks as in its own view, from its
view_specs. Series sharing a panel have overlaid histograms and CDFs in the color of the series. Colors repeated in a panel are replaced, and the y range covers all series of the panel.- Parameters:
axes (list) – axes to plot on, by panel: series, or series, histogram and CDF
specs (dict) – plot specification dictionary
- Returns:
None
- Return type:
None
- static _get_panel_colors(ls_series, specs)[source]#
Get the color of each series in a panel. A series with a color already in use takes the color of
cmap_seriesfarthest from those in use.- Parameters:
ls_series (list) – series of the panel
specs (dict) – plot specification dictionary
- Returns:
colors, for each series
- Return type:
list
- view(show=True, return_fig=False)[source]#
Visualize the time series collection: a Gantt chart of each series’ own epochs, the cross-series overlap over time, and (in the
"full"layout) each series’ data prevalence. The"stacked"and"stacked-simple"layouts draw series on panels instead, set byview_specs["panels"]andview_specs["panel_heights"].Every knob previously passed as a loose keyword (
folder,filename,dpi,fig_format,usealias, colors, titles, axis ranges, layout choice…) now lives inself.view_specs– set it before calling, exactly likeTimeSeries.view().Layouts, set by
view_specs["layout"]:Layout
Panels
fullGantt chart, overlap and prevalence.
simpleGantt chart and overlap.
defaultSame as
full.stackedA panel for each entry of
panels, with histograms and CDFs, on a shared time axis.stacked-simpleA panel for each entry of
panels, on a shared time axis.View specs, set by
view_specs[key] = valuebefore the call:Key
Default
Description
layout"full"Name of the layout. See the table of layouts.
style"wien"Name of the plot style. See
plans.viewer.set_style().titleauto
Title of the figure.
ganttauto
Title of the Gantt chart.
overauto
Title of the overlap panel.
prevauto
Title of the prevalence panel.
xlabelauto
Label of the time axis.
ylabel_over"%"Label of the y axis of the overlap panel.
xlabel_prev"%"Label of the x axis of the prevalence panel.
usealiasFalseUse aliases instead of names in labels.
n_dates5Number of date ticks, evenly spaced in time. None chooses them automatically.
format_dates"%Y-%m-%d"Format of the date labels.
xtick_rotation0Rotation of the date labels in the
fullandsimplelayouts.color_over"tab:blue"Color of the overlap panel.
alpha_over0.4Opacity of the fill of the overlap panel.
color_prev"tab:gray"Color of the prevalence bars.
gantt_linewidth6Largest width of the Gantt lines. It shrinks to fit many series.
n_series_max10Above this many series, labels are hidden and series lines go to the background.
xminNone
Start of the time axis. None is the first date of all series, with
pad_x.xmaxNone
End of the time axis. None is the last date of all series, with
pad_x.yminNone
Bottom of the overlap panel. None is automatic.
ymaxNone
Top of the overlap panel. None is automatic.
pad_x0.05Share of the time span added on each side of the time axis not set by
xminorxmax.folderauto
Folder of the saved figure.
filenameauto
Name of the saved figure, without extension. None is the name of the collection.
suff""Suffix of the saved figure, if
filenameis None.dpi300Resolution of the saved figure.
fig_format"jpg"Format of the saved figure.
series"Series"Title of the series panel, in the
serieslayouts.subtitle_hist"Histogram"Title of the histograms.
subtitle_cdf"CDF"Title of the CDFs.
ylabelauto
Label of the y axis, in the
serieslayouts. None comes from the variable.rangeNone
Common y range, in the
serieslayouts. None is set from the data.cmap_series"tab10"Color map of the series. In
serieslayouts, None uses the color of each series.linewidth0.8Width of the series lines, in the
serieslayouts.alpha_hist0.4Opacity of overlaid histograms.
histtype"bar"Type of overlaid histograms.
"step"draws outlines only.bins30Number of common bins of overlaid histograms.
plot_meanTrueShow mean lines on overlaid histograms and CDFs.
legendTrueShow the legend of overlaid series.
highlightNone
Names of the series drawn in color, in the
serieslayouts.plot_backgroundTrueShow the background lines on the series panel.
color_background"silver"Color of the background series.
linewidth_background0.5Width of the background lines.
alpha_background0.6Opacity of the background lines.
alpha_hist_background0.1Opacity of the background histograms.
panelsNone
Names of the series in each panel, as a list of lists. None is one series per panel.
panel_heightsNone
Relative heights of the panels, like
[3, 1]. None is equal.- Parameters:
show (bool) – option for showing instead of saving.
return_fig (bool) – option for returning the figure object itself.
- Returns:
the
matplotlib.figure.Figureifreturn_figis True, otherwise None (the figure is shown or saved to"{folder}/{filename or name+suff}.{fig_format}").- Return type:
matplotlib.figure.Figureor None
- view_old(show=True, folder='./output', filename=None, dpi=300, fig_format='jpg', suff='', usealias=False)[source]#
Visualize the time series collection.
- Parameters:
show (bool) – bool, optional If True, the plot will be displayed interactively. If False, the plot will be saved to a file. Default is True.
folder (str) – str, optional The folder where the plot file will be saved. Used only if show is False. Default is “./output”.
filename (str or None) – str, optional The base name of the plot file. Used only if show is False. If None, a default filename is generated. Default is None.
dpi (int) – int, optional The dots per inch (resolution) of the plot file. Used only if show is False. Default is 300.
fig_format (str) – str, optional The format of the plot file. Used only if show is False. Default is “jpg”.
usealias – bool, optional Option for using the Alias instead of Name in the plot. Default is False.
- export_views(folder, dpi=300, fig_format='jpg', suff='', skip_main=False, raw=False)[source]#
Export views of time series data and individual time series within the collection.
- Parameters:
folder (str) – The folder path where the views will be exported.
dpi (int) – Dots per inch (resolution) for the exported images, default is 300.
fig_format (str) – Format for the exported figures, default is “jpg”.
suff (str) – Suffix to be appended to the exported file names, default is an empty string.
skip_main (bool) – Option for skipping the main plot (pannel)
raw (str) – Option for considering a raw data series. No epochs analysis. Default is False.
Notes
Updates the collection details and epoch statistics.
Calls the
viewmethod for the entire collection and individual time series with specified parameters.Sets view specifications for individual time series, such as y-axis limits and time range.
- export_data(folder, filename=None, merged=True)[source]#
Export collection data as CSV files in the given folder.
- Parameters:
folder (str) – Output folder path.
filename (str or None) – Base filename; defaults to
self.namewhenNone.merged (bool) – If
True, exports a merged data CSV and an epochs summary CSV. IfFalse, exports each series individually.
- class plans.datasets.core.TimeSeriesCluster(name='myTimeSeriesCluster', base_object=None)[source]#
Bases:
TimeSeriesCollectionCollection of same-variable time series from different sites (e.g., a network of rain gauges). No miscellaneous data is allowed.
Supports cross-site analysis: correlation between sites via
get_correlation()and gap filling from neighboring sites viaregionalize(). Site coordinates are read from thexandyattributes of each series.Note
See
TimeSeriesEnsemblefor many realizations of the same series (same site and time).- __init__(name='myTimeSeriesCluster', base_object=None)[source]#
Initialize the
Collectionobject.- Parameters:
base_object (
MbaE) –MbaE-based object for collectionname (str) – unique object name
alias (str) – unique object alias.
- get_correlation(method='pearson', min_overlap=30)[source]#
Get the correlation matrix between all series, on their overlapping time steps.
- Parameters:
method (str) – correlation method. Options:
pearsonorspearmanmin_overlap (int) – minimum number of overlapping time steps. Pairs with less overlap are set to NaN.
- Returns:
square correlation matrix, indexed by series names
- Return type:
pandas.DataFrame
- get_weights_by_name(name, method='average')[source]#
Compute interpolation weights of all other series relative to a named series.
- Parameters:
name (str) – name of the target series (excluded from the weight set)
method (str) – weighting scheme:
average(uniform) oridw(inverse-distance). Default isaverage.
- Returns:
weights for the other series, in catalog order
- Return type:
numpy.ndarray
- regionalize(method='average')[source]#
Fill gaps of every series with a weighted average of the other series.
- Parameters:
method (str) – weighting scheme:
average(uniform) oridw(inverse-distance). Default isaverage.- Returns:
None
- Return type:
None
Notes
Series are standardized first, if not yet.
Only gaps are filled; observed values are never changed.
Values are taken as they are, so sites with different levels (e.g., temperature at different elevations) will bias the filling.
All fillings use the original data, so filled values do not cascade.
- view(show=True, return_fig=False)[source]#
Get the visualization, which also has the correlation between series.
Layouts, set by
view_specs["layout"]:Layout
Panels
fullGantt chart, overlap and prevalence.
simpleGantt chart and overlap.
defaultSame as
full.stackedA panel for each entry of
panels, with histograms and CDFs, on a shared time axis.stacked-simpleA panel for each entry of
panels, on a shared time axis.seriesAll series overlaid, with histograms and CDFs.
series-simpleAll series overlaid.
correlationCorrelation matrix.
View specs, set by
view_specs[key] = valuebefore the call:Key
Default
Description
layout"full"Name of the layout. See the table of layouts.
style"wien"Name of the plot style. See
plans.viewer.set_style().titleauto
Title of the figure.
ganttauto
Title of the Gantt chart.
overauto
Title of the overlap panel.
prevauto
Title of the prevalence panel.
xlabelauto
Label of the time axis.
ylabel_over"%"Label of the y axis of the overlap panel.
xlabel_prev"%"Label of the x axis of the prevalence panel.
usealiasFalseUse aliases instead of names in labels.
n_dates5Number of date ticks, evenly spaced in time. None chooses them automatically.
format_dates"%Y-%m-%d"Format of the date labels.
xtick_rotation0Rotation of the date labels in the
fullandsimplelayouts.color_over"tab:blue"Color of the overlap panel.
alpha_over0.4Opacity of the fill of the overlap panel.
color_prev"tab:gray"Color of the prevalence bars.
gantt_linewidth6Largest width of the Gantt lines. It shrinks to fit many series.
n_series_max10Above this many series, labels are hidden and series lines go to the background.
xminNone
Start of the time axis. None is the first date of all series, with
pad_x.xmaxNone
End of the time axis. None is the last date of all series, with
pad_x.yminNone
Bottom of the overlap panel. None is automatic.
ymaxNone
Top of the overlap panel. None is automatic.
pad_x0.05Share of the time span added on each side of the time axis not set by
xminorxmax.folderauto
Folder of the saved figure.
filenameauto
Name of the saved figure, without extension. None is the name of the collection.
suff""Suffix of the saved figure, if
filenameis None.dpi300Resolution of the saved figure.
fig_format"jpg"Format of the saved figure.
series"Series"Title of the series panel, in the
serieslayouts.subtitle_hist"Histogram"Title of the histograms.
subtitle_cdf"CDF"Title of the CDFs.
ylabelauto
Label of the y axis, in the
serieslayouts. None comes from the variable.rangeNone
Common y range, in the
serieslayouts. None is set from the data.cmap_series"tab10"Color map of the series. In
serieslayouts, None uses the color of each series.linewidth0.8Width of the series lines, in the
serieslayouts.alpha_hist0.4Opacity of overlaid histograms.
histtype"bar"Type of overlaid histograms.
"step"draws outlines only.bins30Number of common bins of overlaid histograms.
plot_meanTrueShow mean lines on overlaid histograms and CDFs.
legendTrueShow the legend of overlaid series.
highlightNone
Names of the series drawn in color, in the
serieslayouts.plot_backgroundTrueShow the background lines on the series panel.
color_background"silver"Color of the background series.
linewidth_background0.5Width of the background lines.
alpha_background0.6Opacity of the background lines.
alpha_hist_background0.1Opacity of the background histograms.
panelsNone
Names of the series in each panel, as a list of lists. None is one series per panel.
panel_heightsNone
Relative heights of the panels, like
[3, 1]. None is equal.correlation"Correlation"Title of the correlation panel.
corr_method"pearson"Correlation method:
"pearson","kendall"or"spearman".corr_min_overlap30Fewest common records for a correlation.
cmap_corr"RdBu_r"Color map of the correlation.
range_corr[-1, 1]Range of the color map. Narrow it to reveal structure.
annotateTrueShow values on the correlation cells.
- Parameters:
show (bool) – option for showing instead of saving
return_fig (bool) – option for returning the figure object
- Returns:
figure object if
return_figis True, else None- Return type:
matplotlib.figure.Figureor None
- class plans.datasets.core.TimeSeriesEnsemble(name='myTimeSeriesEnsemble', base_object=None)[source]#
Bases:
TimeSeriesCollectionCollection of same-variable time series as realizations of the same series (same site and time), e.g., stochastic draws or model runs.
Supports ensemble reduction across members at each time step via
reducer()and its shortcuts (mean(),percentiles(),stats(), etc.). Reducers ignore missing values. Theseriesview draws members in background style, with reducers and percentile bands on top.Note
See
TimeSeriesClusterfor same-variable series from different sites.- __init__(name='myTimeSeriesEnsemble', base_object=None)[source]#
Initialize the
Collectionobject.- Parameters:
base_object (
MbaE) –MbaE-based object for collectionname (str) – unique object name
alias (str) – unique object alias.
- reducer(reducer_funcs=None, stepwise=False)[source]#
Apply reducer functions across all members at each time step.
- Parameters:
reducer_funcs (dict) – mapping of output name to a dict with
"Func"(callable) and"Args"(extra scalar argument or None).stepwise (bool) – if True, apply each function row-by-row rather than vectorized along axis 1. Default is False.
- Returns:
DataFrame with datetime and one column per reducer function, named
"{varalias}_{name}"- Return type:
pandas.DataFrame
- percentile(p=90)[source]#
Return the time-step-wise p-th percentile across all members.
- Parameters:
p (float) – percentile value (0-100). Default is 90.
- Returns:
DataFrame with datetime and the
"{varalias}_p{p}"column- Return type:
pandas.DataFrame
- percentiles(values=None)[source]#
Return time-step-wise percentiles across all members.
- Parameters:
values (list) – percentile values to compute. Default is
[1, 5, 10, 25, 50, 75, 90, 95, 99].- Returns:
DataFrame with datetime and one
"{varalias}_p{p}"column per value (e.g.,p05,p50)- Return type:
pandas.DataFrame
- stats(basic=False)[source]#
Return a combined DataFrame of common statistics and percentiles across all members.
- Parameters:
basic (bool) – if True, compute only quartile percentiles (25, 50, 75).
- Returns:
DataFrame with datetime, sum, mean, std, min, max and percentiles
- Return type:
pandas.DataFrame
- get_reducer_series(name)[source]#
Get a reducer as a series object of the ensemble base type.
- Parameters:
name (str) – reducer name:
mean,median,min,maxor a percentile such asp90- Returns:
series holding the reducer values
- Return type:
- _plot_series(axes, specs, extra=None, force_background=False)[source]#
Plot members in background style, with reducers and bands on top.
- view(show=True, return_fig=False)[source]#
Get the visualization, with members in the background and reducers and bands on top.
Layouts, set by
view_specs["layout"]:Layout
Panels
fullGantt chart, overlap and prevalence.
simpleGantt chart and overlap.
defaultSame as
full.stackedA panel for each entry of
panels, with histograms and CDFs, on a shared time axis.stacked-simpleA panel for each entry of
panels, on a shared time axis.seriesAll series overlaid, with histograms and CDFs.
series-simpleAll series overlaid.
View specs, set by
view_specs[key] = valuebefore the call:Key
Default
Description
layout"series"Name of the layout. See the table of layouts.
style"wien"Name of the plot style. See
plans.viewer.set_style().titleauto
Title of the figure.
ganttauto
Title of the Gantt chart.
overauto
Title of the overlap panel.
prevauto
Title of the prevalence panel.
xlabelauto
Label of the time axis.
ylabel_over"%"Label of the y axis of the overlap panel.
xlabel_prev"%"Label of the x axis of the prevalence panel.
usealiasFalseUse aliases instead of names in labels.
n_dates5Number of date ticks, evenly spaced in time. None chooses them automatically.
format_dates"%Y-%m-%d"Format of the date labels.
xtick_rotation0Rotation of the date labels in the
fullandsimplelayouts.color_over"tab:blue"Color of the overlap panel.
alpha_over0.4Opacity of the fill of the overlap panel.
color_prev"tab:gray"Color of the prevalence bars.
gantt_linewidth6Largest width of the Gantt lines. It shrinks to fit many series.
n_series_max10Above this many series, labels are hidden and series lines go to the background.
xminNone
Start of the time axis. None is the first date of all series, with
pad_x.xmaxNone
End of the time axis. None is the last date of all series, with
pad_x.yminNone
Bottom of the overlap panel. None is automatic.
ymaxNone
Top of the overlap panel. None is automatic.
pad_x0.05Share of the time span added on each side of the time axis not set by
xminorxmax.folderauto
Folder of the saved figure.
filenameauto
Name of the saved figure, without extension. None is the name of the collection.
suff""Suffix of the saved figure, if
filenameis None.dpi300Resolution of the saved figure.
fig_format"jpg"Format of the saved figure.
series"Series"Title of the series panel, in the
serieslayouts.subtitle_hist"Histogram"Title of the histograms.
subtitle_cdf"CDF"Title of the CDFs.
ylabelauto
Label of the y axis, in the
serieslayouts. None comes from the variable.rangeNone
Common y range, in the
serieslayouts. None is set from the data.cmap_series"tab10"Color map of the series. In
serieslayouts, None uses the color of each series.linewidth0.8Width of the series lines, in the
serieslayouts.alpha_hist0.4Opacity of overlaid histograms.
histtype"bar"Type of overlaid histograms.
"step"draws outlines only.bins30Number of common bins of overlaid histograms.
plot_meanTrueShow mean lines on overlaid histograms and CDFs.
legendTrueShow the legend of overlaid series.
highlightNone
Names of the series drawn in color, in the
serieslayouts.plot_backgroundTrueShow the background lines on the series panel.
color_background"silver"Color of the background series.
linewidth_background0.5Width of the background lines.
alpha_background0.6Opacity of the background lines.
alpha_hist_background0.1Opacity of the background histograms.
panelsNone
Names of the series in each panel, as a list of lists. None is one series per panel.
panel_heightsNone
Relative heights of the panels, like
[3, 1]. None is equal.reducers["mean"]Names of the reducers drawn in color, such as
mean. None hides them.bands[[5, 95]]Percentile bands, as
[low, high]pairs. None hides them.color_band"#8db4dc"Color of the bands.
alpha_band0.6Opacity of the bands.
- Parameters:
show (bool) – option for showing instead of saving
return_fig (bool) – option for returning the figure object
- Returns:
figure object if
return_figis True, else None- Return type:
matplotlib.figure.Figureor None
- class plans.datasets.core.SeasonalEnsemble(name='mySeasonalEnsemble', base_object=None)[source]#
Bases:
TimeSeriesEnsembleEnsemble of the years of a single series, for seasonal plots.
Each year becomes a member, with dates moved onto one reference year, so reducers, bands and
highlightwork across years. Works with any time step that repeats each year: sub-daily, daily or monthly.Note
Dates in members and reducers are placeholders. The reference year is a leap year, so 29 Feb has its own step, filled only by leap years. To join reducers by calendar date, use the month and day, as in
df["datetime"].dt.strftime("%m-%d").- MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']#
- __init__(name='mySeasonalEnsemble', base_object=None)[source]#
Initialize the
Collectionobject.- Parameters:
base_object (
MbaE) –MbaE-based object for collectionname (str) – unique object name
alias (str) – unique object alias.
- set_series(ts, year_start=1)[source]#
Split a series into one member per year, replacing current members.
Members are named by year, like
2021. When the year does not start in January (e.g., a water year), names hold both years, like2020-21. Incomplete years are kept, and count in the reducers.- Parameters:
ts (
TimeSeries) – series to splityear_start (int) – first month of the year, from 1 to 12. Default is 1.
- Returns:
None
- Return type:
None
- _get_reference_start()[source]#
Get the first date of the reference year, chosen so it holds 29 Feb.
- _plot_series(axes, specs, extra=None, force_background=False)[source]#
Plot as in the ensemble, with the x axis of the reference year.
- view(show=True, return_fig=False)[source]#
Get the visualization, with the years of the series on the same calendar.
Layouts, set by
view_specs["layout"]:Layout
Panels
fullGantt chart, overlap and prevalence.
simpleGantt chart and overlap.
defaultSame as
full.stackedA panel for each entry of
panels, with histograms and CDFs, on a shared time axis.stacked-simpleA panel for each entry of
panels, on a shared time axis.seriesAll series overlaid, with histograms and CDFs.
series-simpleAll series overlaid.
View specs, set by
view_specs[key] = valuebefore the call:Key
Default
Description
layout"series"Name of the layout. See the table of layouts.
style"wien"Name of the plot style. See
plans.viewer.set_style().titleauto
Title of the figure.
ganttauto
Title of the Gantt chart.
overauto
Title of the overlap panel.
prevauto
Title of the prevalence panel.
xlabelauto
Label of the time axis.
ylabel_over"%"Label of the y axis of the overlap panel.
xlabel_prev"%"Label of the x axis of the prevalence panel.
usealiasFalseUse aliases instead of names in labels.
n_dates5Number of date ticks, evenly spaced in time. None chooses them automatically.
format_dates"%Y-%m-%d"Format of the date labels.
xtick_rotation0Rotation of the date labels in the
fullandsimplelayouts.color_over"tab:blue"Color of the overlap panel.
alpha_over0.4Opacity of the fill of the overlap panel.
color_prev"tab:gray"Color of the prevalence bars.
gantt_linewidth6Largest width of the Gantt lines. It shrinks to fit many series.
n_series_max10Above this many series, labels are hidden and series lines go to the background.
xminNone
Start of the time axis. None is the first date of all series, with
pad_x.xmaxNone
End of the time axis. None is the last date of all series, with
pad_x.yminNone
Bottom of the overlap panel. None is automatic.
ymaxNone
Top of the overlap panel. None is automatic.
pad_x0Share of the time span added on each side of the time axis not set by
xminorxmax.folderauto
Folder of the saved figure.
filenameauto
Name of the saved figure, without extension. None is the name of the collection.
suff""Suffix of the saved figure, if
filenameis None.dpi300Resolution of the saved figure.
fig_format"jpg"Format of the saved figure.
series"Series"Title of the series panel, in the
serieslayouts.subtitle_hist"Histogram"Title of the histograms.
subtitle_cdf"CDF"Title of the CDFs.
ylabelauto
Label of the y axis, in the
serieslayouts. None comes from the variable.rangeNone
Common y range, in the
serieslayouts. None is set from the data.cmap_series"tab10"Color map of the series. In
serieslayouts, None uses the color of each series.linewidth0.8Width of the series lines, in the
serieslayouts.alpha_hist0.4Opacity of overlaid histograms.
histtype"bar"Type of overlaid histograms.
"step"draws outlines only.bins30Number of common bins of overlaid histograms.
plot_meanTrueShow mean lines on overlaid histograms and CDFs.
legendTrueShow the legend of overlaid series.
highlightNone
Names of the series drawn in color, in the
serieslayouts.plot_backgroundTrueShow the background lines on the series panel.
color_background"silver"Color of the background series.
linewidth_background0.5Width of the background lines.
alpha_background0.6Opacity of the background lines.
alpha_hist_background0.1Opacity of the background histograms.
panelsNone
Names of the series in each panel, as a list of lists. None is one series per panel.
panel_heightsNone
Relative heights of the panels, like
[3, 1]. None is equal.reducers["mean"]Names of the reducers drawn in color, such as
mean. None hides them.bands[[5, 95]]Percentile bands, as
[low, high]pairs. None hides them.color_band"#8db4dc"Color of the bands.
alpha_band0.6Opacity of the bands.
xaxis"month-alias"Labels of the x axis:
"days","month","month-letter"or"month-alias".- Parameters:
show (bool) – option for showing instead of saving
return_fig (bool) – option for returning the figure object
- Returns:
figure object if
return_figis True, else None- Return type:
matplotlib.figure.Figureor None
- class plans.datasets.core.Raster(name='myRasterMap', alias='Rst', dtype='float32')[source]#
Bases:
GeoUnivarThe basic Raster map dataset. A
GeoUnivarwith a grid as data, in place of a table with geometries.- N_DRAW = 5000#
- var_min#
Attribute computed from the data on first use, and kept until it is set to None.
- var_max#
Attribute computed from the data on first use, and kept until it is set to None.
- property data#
The grid. A new grid drops the statistics of the previous one.
- _reset_stats()[source]#
Drop the statistics, to be computed again on next use.
- Returns:
None
- Return type:
None
- _get_values()[source]#
Get the values of the grid, flat and cleared.
- Returns:
vector of values
- Return type:
numpy.ndarray
- _thin(data)[source]#
Get evenly spaced records of a sequence, since a screen shows no more than a few thousand. Panels of statistics and the histogram still use all data.
- Parameters:
data (
numpy.ndarrayorpandas.DataFrame) – vector or dataframe, with one record for each value- Returns:
thinned sequence
- Return type:
numpy.ndarrayorpandas.DataFrame
- get_metadata()[source]#
Get a dictionary with object metadata. Expected to increment superior methods.
Note
Metadata does not necessarily inclue all object attributes.
- Returns:
dictionary with all metadata
- Return type:
dict
- get_bbox()[source]#
Get the Bounding Box of the map.
- Returns:
Dictionary of xmin, xmax, ymin, and ymax. - “xmin” (float): Minimum x-coordinate. - “xmax” (float): Maximum x-coordinate. - “ymin” (float): Minimum y-coordinate. - “ymax” (float): Maximum y-coordinate.
- Return type:
dict
- get_extent()[source]#
Get the Extent of the map. See get_bbox.
- Returns:
list of [xmin, xmax, ymin, ymax]
- Return type:
list
- get_crs_info()[source]#
Get the EPSG code and the units of the cells, from the CRS or the projection file. Without the database of PROJ, a CRS may lose its EPSG code.
- Returns:
dictionary of
epsgandunits,"m"or"deg.". None if unknown.- Return type:
dict
- get_metadata_lines()[source]#
Get the lines of text of the metadata, for the annotations of the view.
- Returns:
lines of text
- Return type:
list
- get_grid_datapoints(drop_nan=False)[source]#
Get flat and cleared grid data points (x, y, and z).
Notes This function extracts coordinates (x, y, and z) from the raster grid. The x and y coordinates are determined based on the grid cell center positions. If drop_nan is True, nan values are ignored in the resulting DataFrame. The resulting DataFrame includes columns for x, y, z, i, and j coordinates.
- Parameters:
drop_nan (bool) – Option to ignore nan values.
- Returns:
DataFrame of x, y, and z fields.
- Return type:
pandas.DataFrame``or None. If the grid is None, returns None.
- get_grid_data()[source]#
Get flat and cleared grid values.
- Returns:
1D vector of cleared sample.
- Return type:
numpy.ndarray`or None. If the grid is None, returns None.
Notes
This function extracts and flattens the grid, removing any masked or NaN values.
For integer grids, the masked values are ignored.
For floating-point grids, both masked and NaN values are ignored.
- get_stats(inplace=False)[source]#
Get basic statistics from flat and cleared grid.
- Returns:
Dict of basic statistics. If the grid is None, returns None.
- Return type:
dict or None
- get_stats_df()[source]#
Get
pandas.DataFramestatistics from flat and cleared grid.- Returns:
DataFrame of basic statistics. If the grid is None, returns None.
- Return type:
pandas.DataFrameor None
- get_aoi(by_value_lo, by_value_hi)[source]#
Get the AOI map from an interval of values (values are expected to exist in the raster).
- Parameters:
by_value_lo (float) – Number for the lower bound (inclusive).
by_value_hi (float) – Number for the upper bound (inclusive).
- Returns:
AOI map.
- Return type:
AOI`object
Notes
This function creates an AOI (Area of Interest) map based on a specified value range.
The AOI map is constructed as a binary grid where values within the specified range are set to 1, and others to 0.
- update()[source]#
Refresh all mutable attributes based on data (includins paths). Expected to be incremented downstream.
- set_data(grid)[source]#
Set the data grid for the raster object. This function allows setting the data grid for the raster object. The incoming grid should be a NumPy array.
- Parameters:
grid (
numpy.ndarray) – The data grid to be set for the raster.
Notes
The function overwrites the existing data grid in the raster object with the incoming grid, ensuring that the data type matches the raster’s dtype.
Nodata values are masked after setting the grid.
- set_array(array)[source]#
Set the data grid for the raster object. See
set_data().- Parameters:
array (
numpy.ndarray) – The data grid to be set for the raster.- Returns:
None
- Return type:
None
- set_raster_metadata(metadata)[source]#
Set metadata for the raster object based on incoming metadata. This function allows setting metadata for the raster object from an incoming metadata dictionary. The metadata should include information such as the number of columns, number of rows, corner coordinates, cell size, and nodata value.
- Parameters:
metadata (dict) – A dictionary containing metadata for the raster.
- load_data(file_data, file_prj=None, id_band=1)[source]#
Load data and metadata from files to the Raster object.
- Parameters:
file_data (str) – The path to the raster file.
file_prj (str) – The path to the ‘.prj’ projection file. If not provided, an attempt is made to use the same path and name as the
.ascfile with the ‘.prj’ extension.id_band (int) – Band id to read for GeoTIFF. Default value = 1
- load_metadata(file_data, id_band=1)[source]#
Load only metadata from files to the raster object.
- Parameters:
file_data (str) – The path to the raster file.
id_band (int) – Band id to read for GeoTIFF. Default value = 1
- load_image(file_input, xxl=False)[source]#
Load data from an image ‘.tif’ raster files.
- Parameters:
file_input (str) – The file path of the ‘.tif’ raster file.
xxl (bool) – option flag for very large images
Notes
The function uses the Pillow (PIL) library to open the ‘.tif’ file and converts it to a NumPy array.
Metadata may need to be provided separately, as this function focuses on loading raster data.
The loaded data grid is set using the
set_gridmethod of the raster object.
- load_tif(file_input, id_band=1)[source]#
Load data and metadata from .tif raster file.
- Parameters:
file_input (str) – The file path to the
.tifraster file.
- load_tif_metadata(file_input, id_band=1)[source]#
Load only metadata from .tif raster file.
- Parameters:
file_input (str) – The file path to the
.tifraster file.
- load_asc(file_input)[source]#
Load data and metadata from .asc raster file.
- Parameters:
file_input (str) – The file path to the
.ascraster file.
- load_asc_metadata(file_input)[source]#
Load only metadata from
.ascraster files.- Parameters:
file_input (str) – The file path to the
.ascraster file.
- load_prj(file_input)[source]#
Load ‘.prj’ auxiliary file to the ‘prj’ attribute.
- Parameters:
file_input (str) – The file path to the ‘.prj’ auxiliary file.
- copy_structure(raster_ref, n_nodatavalue=None)[source]#
Copy structure (metadata and prj) from another raster object.
- Parameters:
raster_ref (
datasets.Raster) – The reference incoming raster object from which to copy.n_nodatavalue (float) – The new nodata value for different raster objects. If None, the nodata value remains unchanged.
- export(folder, filename=None, mode='tif')[source]#
Exports the raster to a specified file format and location.
- Parameters:
folder (str) – The destination folder for the exported file.
filename (str) – [optional] The name of the output file. If None, the original raster name is used.
mode (str) – The export format, either “tif” (default) or “asc”. Default value = “tif”
- Returns:
file path to output file
- Return type:
str
- export_tif(folder, filename=None)[source]#
Export an
.tifraster file..- Parameters:
folder (str) – The directory path to export the raster file.
filename (str) – The name of the exported file without extension. If None, the name of the raster object is used.
- Returns:
The full file name (path and extension) of the exported raster file.
- Return type:
str
- export_asc(folder, filename=None)[source]#
Export an
.ascraster file.- Parameters:
folder (str) – The directory path to export the raster file.
filename (str) – The name of the exported file without extension. If None, the name of the raster object is used.
- Returns:
The full file name (path and extension) of the exported raster file.
- Return type:
str
- export_prj(folder, filename=None)[source]#
Export a ‘.prj’ file. This function exports the coordinate system information to a ‘.prj’ file in the specified folder.
- Parameters:
folder (str) – The directory path to export the ‘.prj’ file.
filename (str) – The name of the exported file without extension. If None, the name of the raster object is used.
- Returns:
The full file name (path and extension) of the exported ‘.prj’ file, or None if no coordinate system information is available.
- Return type:
str or None
- reset_nodata(new_nodata, ensure=True)[source]#
Resets the no-data value in the raster metadata and updates the data mask accordingly.
This method first ensures the current no-data values are masked, then updates the NODATA_value in the raster metadata, and finally re-applies the mask based on the new no-data value.
- Parameters:
new_nodata (int or float) – The new no-data value to set.
ensure (bool) – If True, ensures the current no-data values are masked before resetting. Default value = True
- mask_nodata()[source]#
Mask grid cells as NaN where data is NODATA.
Notes
The function masks grid cells as NaN where the data is equal to the specified NODATA value.
If NODATA value is not set, no masking is performed.
- load_aoi_mask(file_raster, inplace=False)[source]#
Loads an Area of Interest (AOI) mask from a raster file and applies it to the current object’s data.
- Parameters:
file_raster (str) – The file path to the AOI raster.
inplace (bool) – If True, the mask is applied in-place to the current object’s data. Default value = False
- apply_aoi_mask(grid_aoi, inplace=False)[source]#
Apply AOI (area of interest) mask to the raster map. This function applies an AOI (area of interest) mask to the raster map, replacing values outside the AOI with the NODATA value.
Notes The function replaces values outside the AOI (where grid_aoi is 0) with the NODATA value. If NODATA value is not set, no replacement is performed. If inplace is True, the main grid is modified. If False, a backup of the grid is created before modification. This function is useful for focusing analysis or visualization on a specific area within the raster map.
- Parameters:
grid_aoi (
numpy.ndarray) – Map of AOI (masked array or pseudo-boolean). Expected to have the same grid shape as the raster.inplace (bool) – If True, overwrite the main grid with the masked values. If False, create a backup and modify a copy of the grid. Default is False.
- release_aoi_mask()[source]#
Release AOI mask from the main grid. Backup grid is restored.
This function releases the AOI (area of interest) mask from the main grid, restoring the original values from the backup grid.
Notes If an AOI mask has been applied, this function restores the original values to the main grid from the backup grid. If no AOI mask has been applied, the function has no effect. After releasing the AOI mask, the backup grid is set to None, and the raster object is no longer considered to have an AOI mask.
- rebase_grid(base_raster, inplace=False, method='linear_model')[source]#
Rebase the grid of a raster. This function creates a new grid based on a provided reference raster. Both rasters are expected to be in the same coordinate system and have overlapping bounding boxes.
- Parameters:
base_raster (
datasets.Raster) – The reference raster used for rebase. It should be in the same coordinate system and have overlapping bounding boxes.inplace (bool) – If True, the rebase operation will be performed in-place, and the original raster’s grid will be modified. If False, a new rebased grid will be returned, and the original data will remain unchanged. Default is False.
method (str) – Interpolation method for rebasing the grid. Options include “linear_model,” “nearest,” and “cubic.” Default is “linear_model.”
- Returns:
If inplace is False, a new rebased grid as a NumPy array. If inplace is True, returns None, and the original raster’s grid is modified in-place.
- Return type:
numpy.ndarray`or None
Notes
The rebase operation involves interpolating the values of the original grid to align with the reference raster’s grid.
The method parameter specifies the interpolation method and can be “linear_model,” “nearest,” or “cubic.”
The rebase assumes that both rasters are in the same coordinate system and have overlapping bounding boxes.
- cut_edges(upper, lower, inplace=False)[source]#
Cutoff upper and lower values of the raster grid.
- Parameters:
upper (float or int) – The upper value for the cutoff.
lower (float or int) – The lower value for the cutoff.
inplace (bool) – If True, modify the main grid in-place. If False, create a processed copy of the grid. Default is False.
- Returns:
The processed grid if inplace is False. If inplace is True, returns None.
- Return type:
Union[None, np.ndarray]
Notes Values in the raster grid below the lower value are set to the lower value. Values in the raster grid above the upper value are set to the upper value. If inplace is False, a processed copy of the grid is returned, leaving the original grid unchanged. This function is useful for clipping extreme values in the raster grid.
- _plot(fig, gs, specs)[source]#
Plot the panels of the family, with the raster on the map panel.
- Parameters:
fig (
matplotlib.figure.Figure) – The matplotlib figure object.gs (
matplotlib.gridspec.GridSpec) – The matplotlib gridspec object for arranging subplots.specs (dict) – A dictionary containing plotting specifications and options.
- Returns:
The modified matplotlib figure object with the plots.
- Return type:
matplotlib.figure.Figure
- _get_annotation_columns()[source]#
Get the columns of annotations, with the metadata next to the statistics.
- Returns:
list of columns, each one a list of lines of text
- Return type:
list
- _draw_map(ax, cmap, norm, specs)[source]#
Draw the grid on the map panel, in map coordinates.
- Parameters:
ax (
matplotlib.axes.Axes) – axis to plot oncmap (
matplotlib.colors.Colormap) – color mapnorm (
matplotlib.colors.Normalize) – norm of the color schemespecs (dict) – plot specification dictionary
- Returns:
None
- Return type:
None
- view(show=True, return_fig=False)[source]#
Get the visualization, with the raster on the map panel. All layouts and view specs of
plans.datasets.analyst.GeoUnivar.view()are available, except for those of points. These are the differences:Key
Default
Description
scheme_cmap"continuous"Color scheme. Classes are also available, such as
"equal".cmapauto
Name of the color map, from the
cmapattribute.rangeauto
Range of the y axis and of continuous colors. None is set from the data.
zoom_windowNone
Part of the grid on the map, as a dictionary of
i_min,i_max,j_minandj_max.zorder_map0Drawing order of the raster, which stays below the grid of the map.
alphaNone
Opacity of the data panel. None sets it by the number of points.
run_idNone
Not in use.
The data and CDF panels draw evenly spaced records, up to about
N_DRAWof them. The histogram and the statistics use all data.- Parameters:
show (bool) – option for showing instead of saving
return_fig (bool) – option for returning the figure object
- Returns:
figure object if
return_figis True, else None- Return type:
matplotlib.figure.Figureor None
- static read_tif_metadata(file_input, n_band=1)[source]#
Read raster metadata from a file.
- Parameters:
file_input (str) – Path to the input raster file.
n_band (int) – [optional] Band number to read. Default value = 1
- Returns:
Dictionary containing raster metadata.
- Return type:
dict
- static read_tif(file_input, dtype='float', id_band=1, metadata=True)[source]#
Read a raster band from a file.
- Parameters:
file_input (str) – Path to the input raster file.
dtype (str) – Data type for the output grid. Default value = “float”
id_band (int) – Band id to read. Default value = 1
metadata (bool) – Whether to include metadata in the output dictionary. Default value = True
- Returns:
Dictionary containing the raster grid and optionally its metadata.
- Return type:
dict
- static write_tif(grid_output, dc_metadata, file_output, dtype='float32', n_bands=1, id_band=1)[source]#
Write a raster band to a file.
- Parameters:
grid_output (
numpy.ndarray) – The grid data to write.dc_metadata (dict) – Dictionary containing the raster metadata.
file_output (str) – Path to the output raster file.
dtype (str) – Data type alias for the output grid (numpy standard). Default value = “float32”
n_bands (int) – Number of bands in the output raster. Default value = 1
id_band (int) – Band ID to write the data to. Default value = 1
- Returns:
Path to the output raster file. (echo)
- Return type:
str
- static read_asc_metadata(file_input)[source]#
Reads metadata from an ASCII raster file.
- Parameters:
file_input (str) – Path to the input ASCII file.
- Returns:
A dictionary containing the metadata.
- Return type:
dict
- static read_asc(file_input, dtype='float32', metadata=True)[source]#
Reads an ASCII raster file into a dictionary.
- Parameters:
file_input (str) – Path to the input ASCII file.
dtype (str) – Data type for the raster data. Default value = “float32”
metadata (bool) – Whether to read and include metadata from the ASCII file. Default value = True
- Returns:
A dictionary containing the raster data and optionally its metadata.
- Return type:
dict
- static write_asc(grid_output, dc_metadata, file_output, dtype='float32')[source]#
Writes a raster grid and its metadata to an ASCII file.
- Parameters:
grid_output (
numpy.ndarray) – The raster data to write.dc_metadata (dict) – Dictionary containing the metadata for the ASCII file.
file_output (str) – Path for the output ASCII file.
dtype (str) – Data type for the raster data in the output file. Default value = “float32”
- Returns:
The path of the generated output ASCII file.
- Return type:
str
- static apply_nodata(grid_input, nodatavalue=None)[source]#
Applies a nodata value to the input grid.
- Parameters:
grid_input (
numpy.ndarray) – The input grid.nodatavalue (int or float) – [optional] The nodata value to apply. Default value = None
- Returns:
The grid with the nodata value applied.
- Return type:
numpy.ndarray
- class plans.datasets.core.SciRaster(name='MySciRaster', alias=None)[source]#
Bases:
RasterScientific (float32) raster dataset with a configurable nodata value and display range.
- set_raster_metadata(metadata)[source]#
Set metadata for the raster object based on incoming metadata. This function allows setting metadata for the raster object from an incoming metadata dictionary. The metadata should include information such as the number of columns, number of rows, corner coordinates, cell size, and nodata value.
- Parameters:
metadata (dict) – A dictionary containing metadata for the raster.
- class plans.datasets.core.QualiRaster(name='QualiMap', dtype='uint8')[source]#
Bases:
RasterBasic qualitative raster map dataset. todo [docstring] – examples
- get_areas(inplace=False)[source]#
Get areas in map of each category in table.
- Parameters:
inplace (bool, defaults to False) – option to merge data with raster table
- Returns:
areas dataframe
- Return type:
pandas.DataFrame
- get_normality(clevel=0.95)[source]#
Not available, since category IDs have no distribution.
- Parameters:
clevel (float) – confidence level
- Raises:
ValueError – always
- get_cdf_gumbel()[source]#
Not available, since category IDs have no maxima.
- Raises:
ValueError – always
- get_zonal_stats(raster_sample, merge=False, skip_count=False)[source]#
Get zonal stats from other raster map to sample.
- Parameters:
raster_sample (
datasets.Raster) – raster map to samplemerge (bool) – option to merge data with raster table, defaults to False
skip_count (bool) – set True to skip count, defaults to False
- Returns:
dataframe of zonal stats
- Return type:
pandas.DataFrame
- get_aoi(by_value_id=None)[source]#
Get the AOI map from a specific value id (value is expected to exist in the raster) :param by_value_id: category id value :type by_value_id: int :return: AOI map :rtype:
AOI`object
- set_raster_metadata(metadata)[source]#
Set metadata for the raster object based on incoming metadata. This function allows setting metadata for the raster object from an incoming metadata dictionary. The metadata should include information such as the number of columns, number of rows, corner coordinates, cell size, and nodata value.
- Parameters:
metadata (dict) – A dictionary containing metadata for the raster.
- set_table(dataframe)[source]#
Set attributes dataframe from incoming
pandas.DataFrame.- Parameters:
dataframe (
pandas.DataFrame) – incoming pandas dataframe
- load_data(file_data, file_table=None, file_prj=None, id_band=1)[source]#
Load data from files to the raster object.
- Parameters:
file_data (str) – The path to the raster file.
file_table (str) – path to table file
file_prj (str) – The path to the ‘.prj’ projection file. If not provided, an attempt is made to use the same path and name as the
.ascfile with the ‘.prj’ extension.id_band (int) – Band id to read for GeoTIFF. Default value = 1
- load_table(file_table)[source]#
Load attributes dataframe from table file.
- Parameters:
file_table (str) – path to to file
- export(folder, filename=None)[source]#
Export raster sample
- Parameters:
folder (str) – path to folder,
filename (str) – string of file without extension, defaults to None
- export_table(folder, filename=None)[source]#
Export table file.
- Parameters:
folder (str) – path to folde
filename (str) – string of file without extension
- Returns:
full file name (path to and extension) string
- Return type:
str
- rebase_grid(base_raster, inplace=False)[source]#
This method calls the rebase_grid method of the superclass to perform the grid rebasement using the “nearest” interpolation method.
- reclassify(dict_ids, df_new_table, talk=False)[source]#
Reclassify QualiRaster Ids in grid and table
- Parameters:
dict_ids (dict) – dictionary to map from “Old_Id” to “New_id”
df_new_table (
pandas.DataFrame) – new table for QualiRastertalk (bool) – option for printing messages
- _plot(fig, gs, specs)[source]#
Plot the map panel of the family, with the areas of each class in place of the panels of statistics.
- Parameters:
fig (
matplotlib.figure.Figure) – The matplotlib figure object.gs (
matplotlib.gridspec.GridSpec) – The matplotlib gridspec object for arranging subplots.specs (dict) – A dictionary containing plotting specifications and options.
- Returns:
The modified matplotlib figure object with the plots.
- Return type:
matplotlib.figure.Figure
- _get_annotation_columns()[source]#
Get the columns of annotations. Here, only the metadata.
- Returns:
list of columns, each one a list of lines of text
- Return type:
list
- _get_cmap_norm(specs)[source]#
Get the color map and the norm of the map panel, one color for each ID.
- Parameters:
specs (dict) – plot specification dictionary
- Returns:
color map and norm
- Return type:
tuple
- view(show=True, return_fig=False)[source]#
Get the visualization, with the map and the areas of each class. All layouts of
plans.datasets.analyst.GeoUnivar.view()and the keys of the map panel are available. These are the differences:Key
Default
Description
cmapauto
Colors of the classes, from the table.
rangeauto
Range of the IDs, from the table.
cbar_mapFalseShow the color bar of the map. The areas take its role.
color"tab:gray"Color of the bars of areas.
use_aliasFalseLabel the bars with the alias of the classes.
cutoffTrueHide classes without area.
max_classes15Number of classes shown. Others are aggregated.
subtitle_areas"Aereal ratios"Title of the panel of areas. None hides it.
area_unit"km2"Unit of the total area:
"m2","ha"or"km2".total_area"Total area"Label of the total area.
- Parameters:
show (bool) – option for showing instead of saving
return_fig (bool) – option for returning the figure object
- Returns:
figure object if
return_figis True, else None- Return type:
matplotlib.figure.Figureor None
- class plans.datasets.core.QualiHard(name='qualihard')[source]#
Bases:
QualiRasterA Quali-Hard is a hard-coded qualitative map (that is, the table is pre-set)
- get_table()[source]#
Retrieves a DataFrame representing a classification table.
- Returns:
A DataFrame with classification data.
- Return type:
pandas.DataFrame
- load_data(file_data, file_prj=None, id_band=1, file_table=None)[source]#
Load data from file to the raster object.
- Parameters:
file_data (str) – The path to the raster file.
file_prj (str) – The path to the ‘.prj’ projection file. If not provided, an attempt is made to use the same path and name as the
.ascfile with the ‘.prj’ extension.id_band (int) – Band id to read for GeoTIFF. Default value = 1
- class plans.datasets.core.Zones(name='ZonesMap')[source]#
Bases:
QualiRasterZones map dataset is a QualiRaster designed to handle large volume of positive integer numbers (ids of zones)
- compute_table()[source]#
Computes an internal table summarizing unique values in the spatial data, assigns aliases, names, and sets up viewing specifications.
- set_data(grid)[source]#
Sets the spatial data for the object and recomputes the internal table.
- Parameters:
grid (
numpy.ndarray) – The input grid data.
- load_data(asc_file, prj_file)[source]#
Load data from files to raster
- Parameters:
asc_file (str) – path to raster file
prj_file (str) – path to projection file
- get_aoi(zone_id)[source]#
Get the AOI map from a zone id
- Parameters:
zone_id (int) – number of zone ID
- Returns:
AOI map
- Return type:
AOI`object
- view(show=True, folder='./output', filename=None, specs=None, dpi=150, fig_format='jpg')[source]#
Plot a basic pannel of raster map.
- Parameters:
show (bool) – boolean to show plot instead of saving, defaults to False
folder (str) – path to output folder, defaults to
./outputfilename (str) – name of file, defaults to None
specs (dict) – specifications dictionary, defaults to None
dpi (int) – image resolution, defaults to 96
fig_format (str) – image fig_format (ex: png or jpg). Default jpg
- class plans.datasets.core.RasterCollection(name='myRasterCollection')[source]#
Bases:
CollectionThe raster collection base dataset. This data strucute is designed for holding and comparing
Raster`objects.- __init__(name='myRasterCollection')[source]#
Deploy the raster collection data structure.
- Parameters:
name (str) – name of raster collection
- load_data(name, file_data, file_prj=None, varname=None, varalias=None, units=None, datetime=None, dtype='float32', skip_grid=False)[source]#
Load a
Raster`base_object from a raster file.- Parameters:
name (str) –
Raster.name`name attributefile_data (str) – path to raster file
varname (str) –
Raster.varname`variable name attribute, defaults to Nonevaralias (str) –
Raster.varalias`variable alias attribute, defaults to Noneunits (str) –
Raster.units`units attribute, defaults to Nonedatetime (str) –
Raster.date`date attribute, defaults to Noneskip_grid (bool) – option for loading only the metadata
- load_folder(folder, name_pattern, is_series=False, file_table=None, verbose=False, file_format='tif', logger=None)[source]#
Load all rasters from a folder by following a name pattern.
- Parameters:
folder (str) – path to folder
name_pattern (str) – name pattern. example map_*
is_series (bool) – flag to handle datetime
file_table (str or Path) – file path to qualiraster table
verbose (bool) – option for printing messages
file_format (str) – file extension.
- is_same_grid()[source]#
Checks if all datasets in the catalog have the same grid dimensions (number of columns and rows).
- Returns:
True if all datasets have the same grid dimensions, False otherwise.
- Return type:
bool
- reduce(reducer_func, reduction_name, extra_arg=None, skip_nan=False, talk=False)[source]#
This method reduces the collection by applying a numpy broadcasting function (example: np.mean)
- Parameters:
reducer_func (numpy function) – reducer numpy function (example: np.mean)
reduction_name (str) – name for the output raster
extra_arg (any) – extra argument for function (example: np.percentiles) - Default: None
skip_nan (bool) – Option for skipping NaN values in map
talk (bool) – option for printing messages
- Returns:
raster object based on the first object found in the collection
- Return type:
- to_mean(skip_nan=False, talk=False)[source]#
Reduce Collection to the Mean raster
- Parameters:
skip_nan (bool) – Option for skipping NaN values in map
talk (bool) – option for printing messages
- Returns:
raster object based on the first object found in the collection
- Return type:
- to_sd(skip_nan=False, talk=False)[source]#
Reduce Collection to the Standard Deviation raster
- Parameters:
skip_nan (bool) – Option for skipping NaN values in map
talk (bool) – option for printing messages
- Returns:
raster object based on the first object found in the collection
- Return type:
- to_min(skip_nan=False, talk=False)[source]#
Reduce Collection to the Min raster
- Parameters:
skip_nan (bool) – Option for skipping NaN values in map
talk (bool) – option for printing messages
- Returns:
raster object based on the first object found in the collection
- Return type:
- to_max(skip_nan=False, talk=False)[source]#
Reduce Collection to the Max raster
- Parameters:
skip_nan (bool) – Option for skipping NaN values in map
talk (bool) – option for printing messages
- Returns:
raster object based on the first object found in the collection
- Return type:
- to_sum(skip_nan=False, talk=False)[source]#
Reduce Collection to the Sum raster
- Parameters:
skip_nan (bool) – Option for skipping NaN values in map
talk (bool) – option for printing messages
- Returns:
raster object based on the first object found in the collection
- Return type:
- to_percentile(percentile, skip_nan=False, talk=False)[source]#
Reduce Collection to the Nth Percentile raster
- Parameters:
percentile (float) – Nth percentile (from 0 to 100)
skip_nan (bool) – Option for skipping NaN values in map
talk (bool) – option for printing messages
- Returns:
raster object based on the first object found in the collection
- Return type:
- to_median(skip_nan=False, talk=False)[source]#
Reduce Collection to the Median raster
- Parameters:
skip_nan (bool) – Option for skipping NaN values in map
talk (bool) – option for printing messages
- Returns:
raster object based on the first object found in the collection
- Return type:
- get_collection_stats()[source]#
Get basic statistics from collection.
- Returns:
statistics sample
- Return type:
pandas.DataFrame
- get_views(show=False, folder='./output', dpi=300, fig_format='jpg', talk=False, specs=None, suffix=None)[source]#
Plot all basic pannel of raster maps in collection.
- Parameters:
show (bool) – boolean to show plot instead of saving,
folder (str) – path to output folder, defaults to
./outputdpi (int) – image resolution, defaults to 96
fig_format (str) – image fig_format (ex: png or jpg). Default jpg
talk (bool) – option for print messages
- view_bboxes(colors=None, datapoints=False, show=True, folder='./output', filename=None, dpi=150, fig_format='jpg')[source]#
View Bounding Boxes of Raster collection
- Parameters:
colors (list) – list of colors for plotting. expected to be the same runsize of catalog
datapoints (bool) – option to plot datapoints as well, defaults to False
show (bool) – option to show plot instead of saving, defaults to False
folder (str) – path to output folder, defaults to
./outputfilename (str) – name of file, defaults to None
dpi (int) – image resolution, defaults to 96
fig_format (str) – image fig_format (ex: png or jpg). Default jpg
- Return type:
none
- get_catalog(mode='full')[source]#
Retrieves the data catalog in different modes.
- Parameters:
mode (str) – The mode of the catalog to retrieve. Can be “full” for the complete catalog, “short” for a truncated version, or any other value to filter by a list ls. Default value = “full”
- Returns:
The requested data catalog.
- Return type:
pandas.DataFrame
- class plans.datasets.core.QualiRasterCollection(name)[source]#
Bases:
RasterCollectionThe raster collection base dataset.
This data strucute is designed for holding and comparing
QualiRaster`objects.
- class plans.datasets.core.RasterSeries(name, varname, varalias, units, dtype='float32')[source]#
Bases:
RasterCollectionA
RasterCollection`where datetime matters and all maps in collections are expected to be the same variable, same projection and same grid.- __init__(name, varname, varalias, units, dtype='float32')[source]#
Deploy RasterSeries
- Parameters:
name (str) –
RasterSeries.name`name attributevarname (str) –
Raster.varname`variable name attribute, defaults to Nonevaralias (str) –
Raster.varalias`variable alias attribute, defaults to Noneunits (str) –
Raster.units`units attribute, defaults to None
- load_data(name, datetime, file_data, prj_file=None, dtype='float32', skip_grid=False)[source]#
Load a
Raster`object from raster file.- Parameters:
name (str) –
Raster.name`name attributedatetime (str) –
Raster.date`date attribute, defaults to Nonefile_data (str) – path to raster file
prj_file (str) – path to projection file
skip_grid (bool) – option for loading only the metadata
- load_folder(folder, name_pattern, file_table=None, verbose=False, file_format='tif', logger=None)[source]#
Load all rasters from a folder by following a name pattern.
- Parameters:
folder (str) – path to folder
name_pattern (str) – name pattern. example map_*
is_series (bool) – flag to handle datetime
file_table (str or Path) – file path to qualiraster table
verbose (bool) – option for printing messages
file_format (str) – file extension.
- apply_aoi_masks(grid_aoi, inplace=False)[source]#
Batch method to apply AOI mask over all maps in collection
- Parameters:
grid_aoi (
numpy.ndarray) – aoi gridinplace (bool) – overwrite the main grid if True, defaults to False
- rebase_grids(base_raster, talk=False)[source]#
Batch method for rebase all maps in collection
- Parameters:
base_raster (
datasets.Raster) – base raster for rebasingtalk (bool) – option for print messages
- get_series_stats()[source]#
Get the raster series statistics
- Returns:
dataframe of raster series statistics
- Return type:
pandas.DataFrame
- view_series_stats(statistic='mean', folder='./output', filename=None, specs=None, show=True, dpi=150, fig_format='jpg')[source]#
View raster series statistics
- Parameters:
statistic (str) – statistc to view. Default mean
show (bool) – option to show plot instead of saving, defaults to False
folder (str) – path to output folder, defaults to
./outputfilename (str) – name of file, defaults to None
specs (dict) – specifications dictionary, defaults to None
dpi (int) – image resolution, defaults to 96
fig_format (str) – image fig_format (ex: png or jpg). Default jpg
- class plans.datasets.core.QualiRasterSeries(name, varname, varalias, dtype='uint8')[source]#
Bases:
RasterSeriesA
RasterSerieswhere date matters and all maps in collections are expected to beQualiRaster`with the same variable, same projection and same grid.- __init__(name, varname, varalias, dtype='uint8')[source]#
Deploy Qualitative Raster Series
- Parameters:
name (str) –
RasterSeries.name`name attributevarname (str) –
Raster.varnamevariable name attribute, defaults to Nonevaralias (str) –
Raster.varaliasvariable alias attribute, defaults to None
- update_table(clear=True)[source]#
Update series table (attributes)
- Parameters:
clear (bool) – option for clear table from unfound values. default: True
- append(raster)[source]#
Append a new object to the
Collection.- Parameters:
new_object (object) – Object to append.
Important
The object is expected to have a
.get_metadata()method that returns a dictionary with metadata keys and values.
- load_data(name, datetime, file_data, prj_file=None, table_file=None)[source]#
Load a
QualiRasterbase_object from raster file.- Parameters:
name (str) –
Raster.namename attributedatetime (str) –
Raster.datedate attributefile_data (str) – path to raster file
prj_file (str) – path to projection file
table_file (str) – path to
.txttable file
- load_folder(folder, name_pattern, file_table, verbose=False, file_format='tif', logger=None)[source]#
Load all rasters from a folder by following a name pattern.
- Parameters:
folder (str) – path to folder
name_pattern (str) – name pattern. example map_*
is_series (bool) – flag to handle datetime
file_table (str or Path) – file path to qualiraster table
verbose (bool) – option for printing messages
file_format (str) – file extension.
- get_series_areas()[source]#
Get areas prevalance for all series
- Returns:
dataframe of series areas
- Return type:
pandas.DataFrame
- static view_series_areas(df_table, df_areas, specs=None, show=True, export_areas=True, folder='./output', filename=None, dpi=300, fig_format='jpg')[source]#
View series areas
- Parameters:
specs (dict) – specifications dictionary, defaults to None
show (bool) – option to show plot instead of saving, defaults to False
folder (str) – path to output folder, defaults to
./outputfilename (str) – name of file, defaults to None
dpi (int) – image resolution, defaults to 96
fig_format (str) – image fig_format (ex: png or jpg). Default jpg