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. |
|
A time series dataset with a datetime-indexed variable. |
|
The |
|
A collection of time series objects with associated metadata. |
|
Collection of same-variable time series from the same underlying process, treated as statistical samples. |
|
Spatial extension of |
|
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.- _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
- 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.
- 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=True)[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 True.
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.
- 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. Several other methods (e.g.get_epochs,interpolate_gaps) check this flag and callstandardize()automatically if it’sFalse.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 361 >>> ts.data[ts.varfield].isna().sum() 50
- 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.
- update_epochs_stats()[source]#
Update all epochs statistics.
Notes
This function updates statistics for all epochs in the time series.
Ensures that the data is standardized by calling the
standardizemethod if it’s not already standardized.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
This function handles time series data, standardizing it if necessary before performing interpolation. 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.
- view(show=True, return_fig=False)[source]#
View the TimeSeries data.
Note
Use values in the
view_specs()attribute for plotting- Parameters:
show (bool) – option for showing instead of saving.
return_fig (bool) – option for returning the figure object itself.
- view_epochs(show=True)[source]#
Get a basic visualization. Expected to overwrite superior methods.
- Parameters:
show (bool) – option for showing instead of saving.
Notes
Uses values in the
view_specs()attribute for plotting
- 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.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 make_synthetic_tsn(start, end, base, trend, amplitude, noise_sd, freq='10min', seasonal_period='YS', minor_seasonal_period='D', minor_amplitude=0, variable='level')[source]#
Generates a synthetic time series pandas.DataFrame incorporating trend, dual seasonality, and Gaussian noise.
- Parameters:
start (str or
pandas.Timestamp) – The starting date for the time series.end (str or
pandas.Timestamp) – The ending date for the time series.base (float) – The initial base level of the series.
trend (float) – The linear change applied per time step.
amplitude (float) – The amplitude of the primary (major) seasonal sine wave.
noise_sd (float) – The standard deviation of the normal distribution used for noise.
freq (str) – The frequency string for the date range. Default value =
10minseasonal_period (str) – The period string for the major seasonality. Default value =
YSminor_seasonal_period (str) – The period string for the secondary seasonality. Default value =
Dminor_amplitude (float) – The amplitude of the secondary seasonal sine wave. Default value = 0
variable (str) – The name of the column containing the generated values. Default value =
level
- Returns:
A DataFrame containing the
datetimeindex and the generated synthetic values.- Return type:
pandas.DataFrame
- 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- __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()[source]#
Merge data from every series in the collection into one DataFrame, aligned by an outer join on the datetime field.
- 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) andTimeSeries.interpolate_gaps()(close its own small gaps), and its own epoch stats are refreshed.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().
- _get_fig_specs()[source]#
Merge
view_specswith the chosen namedlayout’s sizing and with the shared grid defaults (viewer.GRID_SPECS).
- _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.
- 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.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().- 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:
TimeSeriesCollectionThe
TimeSeriesClusterinstance is desgined for holding a collection of same variable time series. That is, no miscellaneus data is allowed.
- class plans.datasets.core.TimeSeriesSamples(name='myTimeSeriesSamples', base_object=None)[source]#
Bases:
TimeSeriesClusterCollection of same-variable time series from the same underlying process, treated as statistical samples. Supports ensemble reduction via
reducer().- __init__(name='myTimeSeriesSamples', 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 row-wise reducer functions across all merged sample data.
- Parameters:
reducer_funcs (dict) – Mapping of output column 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.
- Return type:
pandas.DataFrame
- percentile(p=90)[source]#
Return the time-step-wise p-th percentile across all samples.
- Parameters:
p (int) – Percentile value (0–100). Default is 90.
- class plans.datasets.core.TimeSeriesSpatialSamples(name='myTimeSeriesSpatialSample', base_object=None)[source]#
Bases:
TimeSeriesSamplesSpatial extension of
TimeSeriesSamplesfor geolocated station data. Supports spatial interpolation viaregionalize()and distance-based weighting.- __init__(name='myTimeSeriesSpatialSample', 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_weights_by_name(name, method='average')[source]#
Compute interpolation weights for all stations relative to a named station.
- Parameters:
name (str) – Name of the target station (excluded from the weight set).
method (str) – Weighting scheme:
"average"(uniform) or"idw"(inverse-distance). Default is"average".
- Returns:
Weight array for the remaining stations.
- Return type:
numpy.ndarray
- regionalize(method='average')[source]#
Regionalize the time series data using a specified method.
- Parameters:
method (str) – Method for regionalization, default is “average”.
Notes
This method handles standardization. If the time series data is not standardized, it applies standardization.
Computes epochs for the time series data.
Iterates through each time series in the collection and performs regionalization.
For each time series, sets up source and destination vectors, computes weights, and calculates regionalized values.
Updates the destination column in-place with the regionalized values and updates epochs statistics.
Updates the collection catalog with details.
- class plans.datasets.core.Raster(name='myRasterMap', alias='Rst', dtype='float32')[source]#
Bases:
DataSetThe basic Raster map dataset.
- 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_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_univar()[source]#
Creates and returns a Univar object initialized with the current object’s grid data.
- Returns:
A Univar object containing the grid data for univariate analysis.
- Return type:
- 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_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)[source]#
Load only metadata from files to the raster object.
- Parameters:
file_data (str) – The path to the raster file.
- 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]#
Generates a plot visualizing the Raster data.
- 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
- view(show=True, return_fig=False, helper_geometry=None)[source]#
Displays or returns a visualization of the spatial data.
- Parameters:
show (bool) – If True, the plot is displayed. Default value = True
return_fig (bool) – If True, the matplotlib figure object is returned. Default value = False
helper_geometry (object) – [optional] An optional geometry object to overlay on the map.
- Returns:
The matplotlib figure object if return_fig is True, otherwise None.
- Return type:
matplotlib.figure.Figureor None
- static plot_metadata(fig, metadata, x=0.0, y=0.1)[source]#
Adds raster metadata as text annotations to a matplotlib figure.
- Parameters:
fig (
matplotlib.figure.Figure) – The matplotlib figure object to which metadata will be added.metadata (dict) – A dictionary containing raster metadata (e.g., ‘nrows’, ‘ncols’, ‘cellsize’, ‘xllcorner’, ‘yllcorner’, ‘NODATA_value’).
x (float) – The x-coordinate (figure fraction) for the left-most column of metadata. Default value = 0.0
y (float) – The y-coordinate (figure fraction) for the top row of metadata. Default value = 0.1
- Returns:
The modified matplotlib figure object.
- Return type:
matplotlib.figure.Figure
- 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
- static make_square(grid_input)[source]#
Reshapes a 2D input grid into a square array, padding with NaNs or masked values if necessary.
- Parameters:
grid_input (
numpy.ndarray) – The input 2D array (grid).- Returns:
A square array containing the original grid, padded with NaNs or masked values.
- 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_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]#
Generates a plot visualizing the spatial data and its area distribution.
This method creates a figure with a map of the spatial data and a horizontal bar chart showing the percentage area of each unique class. It can aggregate smaller classes into an “others” category and displays raster metadata.
- 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
- view(show=True, return_fig=False, helper_geometry=None)[source]#
Displays or returns a visualization of the spatial data and its area distribution.
This method orchestrates the plotting process by setting up figure specifications, calling the internal plotting function (_plot), and then either displaying or saving the generated figure.
- Parameters:
show (bool) – If True, the plot is displayed. Default value = True
return_fig (bool) – If True, the matplotlib figure object is returned. Default value = False
helper_geometry (object) – [optional] An optional geometry object to overlay on the map.
- Returns:
The matplotlib figure object if return_fig is True, otherwise 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