aerosoltools.partector¶
Public class for Naneos Partector LDSA dosimeters (Partector).
Lung-deposited surface area (LDSA, nm²/cm³) plus a TEM sampling flag and flow.
The Partector reports no particle number, so total_concentration does not
apply; LDSA is the primary channel.
Module Contents¶
- class aerosoltools.partector.Partector(dataframe)[source]¶
Bases:
aerosoltools._core.nonparticle._NonParticleMixin,aerosoltools.aerosol1d.Aerosol1DPartector LDSA time series with TEM sampling metadata.
Reuses the
Aerosol1Dmachinery but does not exposetotal_concentration(the Partector reports no particle number). The primary channel isldsa.- Parameters:
dataframe (pandas.DataFrame) – Input data with a time column/index and
"LDSA"(and typically"TEM"/"Flow") columns.- Variables:
ldsa (pandas.Series) – Lung-deposited surface area (nm²/cm³).
flow (pandas.Series) – Sample flow (l/min), when present.
tem_samples (pandas.DataFrame | None) – TEM sampling summary (
Start/End/Sample_vol [ml]), from metadata.
- property ldsa: pandas.Series¶
Lung-deposited surface area (nm²/cm³).
- Return type:
- property flow: pandas.Series¶
Sample flow (l/min).
- Return type:
- property tem_samples: pandas.DataFrame | None¶
TEM sampling summary table, if the loader recorded one.
- Return type:
Optional[pandas.DataFrame]
- property total_concentration: pandas.Series¶
this instrument does not measure particle number.
- Raises:
AttributeError – Always. Use the class’s dedicated accessor (e.g.
.concentration/.ldsa/.ir_bcc) or a named channel indatainstead.- Type:
Not available
- Return type:
- property activities: List[str]¶
Names of all defined activity labels.
- Returns:
Activity names for which a boolean mask column exists in
data(for example"All data","Peak", or user-defined labels created viamark_activities()).- Return type:
- property activity_periods: Dict¶
Time periods associated with each activity label.
- Returns:
Mapping from activity name (str) to a list of
(start, end)timestamp tuples, where each tuple defines a contiguous period during which the activity is active.- Return type:
- property data: pandas.DataFrame¶
Main data frame with time index and measurement columns.
- Returns:
The full data table, including the time index, the primary measurement columns (for example total concentration), and any boolean activity mask columns.
- Return type:
- property dtype: str¶
Data type descriptor for the primary measurements.
- Returns:
A short description of the data type, for example
"dN"(number concentration),"dM"(mass concentration), or"dN/dlogDp"when normalized. Falls back to"Unknown dtype"if not set in the metadata.- Return type:
- property extra_data: pandas.DataFrame¶
Additional non-core data columns.
- Returns:
Data frame containing extra columns that were extracted from the raw data file but are not considered part of the core aerosol time series (for example environmental or metadata channels). The index is aligned with
data.- Return type:
- property instrument: str¶
Instrument used to acquire the measurements.
- Returns:
Instrument name or description (for example model/type). Falls back to
"Unknown instrument"if not set in the metadata.- Return type:
- property measurement¶
Human-readable name of the measured quantity, if known.
- Returns:
The label describing what the primary series represents — for example
"Cl₂"or"NO₂"for a gas monitor — as set by the loader inmetadata["measurement"]. ReturnsNonewhen no explicit label was stored (in which case callers fall back to a generic name such as"Total concentration"or the channel name). This is distinct fromdtype(dN/dM/…) andunit; it names the quantity rather than its basis or units.
- property metadata: Dict¶
Metadata associated with the dataset.
- Returns:
Dictionary containing metadata such as unit, data type, instrument type, and serial number. Internally stored in
self._meta.- Return type:
- property original_data: pandas.DataFrame¶
Unmodified original main data frame.
- Returns:
A copy of the raw data as it was immediately after loading and initial normalization of the time index and column names, before any further processing steps (such as cropping, smoothing, or rebinning).
- Return type:
- property original_extra_data: pandas.DataFrame¶
Unmodified original extra-data frame.
- Returns:
A copy of the raw extra-data table (if any) before any processing steps. This will typically be empty if no extra data were extracted at load time.
- Return type:
- property serial_number: str¶
Instrument serial number.
- Returns:
Serial number of the instrument, if available in the metadata. Falls back to
"Unknown serial number"if not set.- Return type:
- property time: pandas.DatetimeIndex¶
Time index of the measurements.
- Returns:
The time stamps corresponding to each row in
data. This is the index of the main data frame.- Return type:
- property column_units: dict¶
Canonical unit per column name (core and extra columns).
Populated by the loaders from the shared unit registry (see
aerosoltools._core.metrics.parse_header_unit()), so every column a loader could resolve carries one canonical unit string. A column that is absent from this map has no known unit — callers that need an honest “unknown” (e.g. an axis label) should show the header text alone rather than borrow the primary series’ unit. Emptydictfor objects built without unit resolution.- Returns:
{column_name: canonical_unit}(possibly empty).- Return type:
- unit_of(column=None)¶
Return the unit for
columnas a string (per-column aware).Prefers the canonical per-column unit from
column_unitswhen the loader resolved one forcolumn; otherwise handles both scalar and per-column-dictunitmetadata. Withcolumn=None(or an unknown column with nounitdict entry) returns the scalar unit, or the first per-column unit for a multi-channel instrument.
- dtype_of(column=None)¶
Return the dtype descriptor for
columnas a string.
- apply_calibration(model, *, inplace=False)¶
Apply a fitted calibration model to this dataset.
This is the single-dataset application half of the calibration workflow: the cross-dataset fitting lives in
aerosoltools.intercomparison.fit_calibration(), which produces theCalibrationModelapplied here. Fit once, apply to as many datasets as you like.- Parameters:
model (CalibrationModel | dict) – A model from
fit_calibration(or itsto_dict()form). A"total"model scales the total/primary series bygain(plusoffsetwhen the model includes one); a"per_bin"model scales each size bin by its own gain and re-sums the total, applying only the bins the fit accepted.inplace (bool) – Modify this object (
True) or a deep copy (False, the default — calibration returns a new object).
- Returns:
The calibrated object (
selfwheninplace).- Return type:
- Raises:
ValueError – If a per-bin model is applied to non-size-resolved data, or the model’s bin count does not match the dataset.
- copy_self()¶
Create and return a deep copy of the aerosol time-series object.
- Returns:
- A new object with independent copies of all data,
extra_data, metadata, and activity definitions.
- Return type:
Notes
- Detailed description:
The returned object is completely detached from the original: changing masks, cropping, rebinning, or smoothing on the copy does not affect the source instance, and vice versa. Both the original and the copy retain their own raw_data and raw_extra_data snapshots.
Examples
Use this when you want to experiment with processing steps without changing your original dataset:
cpc_raw = cpc_data cpc_proc = cpc_data.copy_self() cpc_proc.timerebin("1min").timesmooth(window=11)
- timecrop(start=None, end=None, inplace=True, focus=True, crop_extra=True)¶
Crop the time axis to include or exclude a time interval.
- Parameters:
start (str | pandas.Timestamp | None) – Start of the interval. If None, cropping starts at the first timestamp.
end (str | pandas.Timestamp | None) – End of the interval. If None, cropping ends at the last timestamp.
inplace (bool) – If True, modify the current object and return it. If False, return a cropped deep copy.
focus (bool) – If True, keep only the interval [start, end]. If False, remove that interval and keep data before start and after end.
crop_extra (bool) – If True, also crop extra_data to the same time mask (when inplace=True or on the copy).
- Returns:
- The cropped object (self when inplace=True, or a
new instance when inplace=False).
- Return type:
- Raises:
ValueError – May be raised by pandas.to_datetime if start or end strings cannot be parsed. Check the date format (for example “YYYY-MM-DD HH:MM:SS”).
Notes
- Detailed description:
A boolean mask is built over the current time index based on start and end. Depending on focus, this mask either selects or removes the specified interval. All columns in self.data are subset accordingly. When crop_extra is True, extra_data is cropped using the same mask, keeping time alignment between main and extra channels.
Examples
Drop a calibration period at the start of a measurement:
data.timecrop(end="2025-01-24 09:00", focus=False) data.plot_total_conc()
- timerebin(freq='s', start=None, end=None, method='mean', inplace=True)¶
Resample the time series to a new regular frequency.
- Parameters:
freq (str) – Target sampling interval as a pandas offset alias (for example “30s”, “1min”, “5min”, “1H”). Defaults to “s”.
start (datetime | pandas.Timestamp | None) – Optional start time for the resampling window. If None, the first timestamp is used.
end (datetime | pandas.Timestamp | None) – Optional end time for the resampling window. If None, the last timestamp is used.
method (str | Callable) – Aggregation function for numeric columns. Any aggregation accepted by pandas.DataFrame.resample (for example “mean”, “sum”, “median”) or a custom callable.
inplace (bool) – If True, update this object and return it. If False, leave this instance unchanged and return a rebinned deep copy.
- Returns:
- The rebinned object (self when inplace=True, or a
new instance otherwise) with a regular DatetimeIndex and resampled main and extra data.
- Return type:
- Raises:
ValueError – May be raised by pandas if freq is not a valid offset alias or if start/end cannot be interpreted as timestamps.
Notes
- Detailed description:
Numeric columns in self.data are resampled using the chosen method, while boolean columns are aggregated with a logical maximum so that any True within a bin keeps the bin True. The resulting DataFrame is reindexed to a fully regular time grid between the floored start and end times. Extra data, if present, are resampled in the same way and aligned to the new index. Activity masks such as “All data” are maintained and missing boolean values are filled with False.
Examples
Convert a high‑frequency logger to 1‑minute averages:
data.timerebin(freq="1min", method="mean") data.plot_total_conc()
- timeshift(seconds=0, minutes=0, hours=0, inplace=True, shift_extra=True)¶
Shift the time index by a constant offset.
- Parameters:
seconds (float) – Offset in seconds; positive shifts the series forward in time, negative backward. Defaults to 0.
minutes (float) – Offset in minutes, converted internally to seconds and added to seconds. Defaults to 0.
hours (float) – Offset in hours, converted internally to seconds and added to seconds. Defaults to 0.
inplace (bool) – If True, shift this object in place and return it. If False, return a shifted deep copy. Default is True.
shift_extra (bool) – If True, also shift the index of extra_data so that main and extra channels remain aligned. Default is True.
- Returns:
- Object with shifted time index (self when
inplace=True, otherwise a new instance).
- Return type:
- Raises:
None – Unless invalid types are passed for the offset arguments.
Notes
- Detailed description:
A pandas.Timedelta is constructed from the combined offset: total_shift = seconds + 60*minutes + 3600*hours. This timedelta is added to the index of self.data, and optionally to self.extra_data. Activity masks and other columns are left unchanged; only timestamps move.
Examples
Align measurements from two instruments with a known clock offset:
cpc.timeshift(minutes=+2) elpi.timeshift(minutes=-1) cpc.plot_total_conc() elpi.plot_total_conc()
- timesmooth(window=5, method='mean', inplace=True)¶
Apply a centered rolling smoother to numeric columns.
- Parameters:
window (int) – Rolling window size in number of samples. Defaults to 5.
method (str) – Aggregation used for smoothing, one of “mean”, “median”, “sum”, “min”, “max”. Defaults to “mean”.
inplace (bool) – If True, replace the numeric columns of this object with their smoothed versions. If False, return a smoothed deep copy.
- Returns:
- Object with smoothed numeric columns and unchanged
boolean/activity columns (self when inplace=True, otherwise a new instance).
- Return type:
- Raises:
ValueError – If method is not among the supported names. Choose one of “mean”, “median”, “sum”, “min”, “max”.
Notes
- Detailed description:
The method separates numeric and boolean columns in self.data. A centered rolling window with at least one valid sample (min_periods=1) is applied to numeric columns using the requested aggregation, producing a smoothed version of each numeric time series. Boolean columns untouched.
- Theory:
The smoothing is a simple moving-window operation. It can help reduce noise in total concentration or other instrument channels prior to further analysis.
Examples
Smooth a noisy CPC time series while preserving activities:
smooth = data.timesmooth(window=11, method="median", inplace=False) smooth.plot_total_conc(mark_activities=True)
- mark_activities(activity_periods, mode='union')¶
Define or update boolean activity masks on the time axis.
- Parameters:
activity_periods (dict) –
Mapping from activity name (str) to one of:
a (start, end) tuple,
a list of (start, end) tuples, or
None (no active periods).
Each start/end can be a pandas.Timestamp, datetime, or any string understood by pandas.to_datetime.
mode (str) –
How to combine new periods with existing masks of the same name. One of:
”union”: existing OR new periods (default),
”replace”: overwrite any existing mask,
”intersection”: keep only overlapping periods.
- Returns:
- The object is modified in place by adding/updating
boolean columns in self.data and entries in self.activity_periods.
- Return type:
None
- Raises:
ValueError – If mode is not “union”, “replace”, or “intersection”. Check the spelling of mode and choose among the supported options.
Notes
- Detailed description:
For each activity key, a boolean Series is built over the current time index. All timestamps falling between any of the supplied (start, end) pairs (inclusive) are set to True, and others to False. Depending on mode, this new mask is merged with any existing column of the same name. The normalized list of (start, end) periods is stored in self.activity_periods[activity].
- Theory:
The method implements generic time segmentation. Activities can represent tasks, locations, process states, or anything else defined by the user.
Examples
Mark a measurement into “Task” and “Background” segments:
periods = { "Task": [("2025-01-24 09:00", "2025-01-24 11:00"), ("2025-01-24 12:30", "2025-01-24 14:00") ], "Background": [("2025-01-24 08:30", "2025-01-24 09:00")] } data.mark_activities(periods, mode="replace") data.plot_total_conc(mark_activities=True)
- rename_activity(old_name, new_name)¶
Rename an existing activity, keeping its periods and mask intact.
- Parameters:
- Returns:
- The object is modified in place: the boolean mask column
in self.data and the entries in self.activities and self.activity_periods are renamed.
- Return type:
None
- Raises:
ValueError – If old_name is not a known activity, or new_name is already used by a different activity.
- get_activity_data(activity_name)¶
Return main data restricted to one or more activity periods.
- Parameters:
activity_name (str | Sequence[str]) – Name of the activity/boolean mask column to use, or multiple names. If multiple are provided, rows are returned only where all selected activities are True.
- Returns:
- Copy of the main data for time steps where the
selected activity (or combined activities) is True, with all activity mask columns removed.
- Return type:
- Raises:
ValueError – If any activity name is not present in self.activities.
TypeError – If activity_name is neither a string nor an iterable of strings.
- get_activity_extra_data(activity_name)¶
Return extra_data restricted to a given activity period.
- Parameters:
activity_name (str) – Name of the activity/boolean mask column in self.data to use as a selector.
- Returns:
- Subset of extra_data aligned to the time
periods where the chosen activity is True. If extra_data is empty, an empty DataFrame is returned.
- Return type:
- Raises:
ValueError – If activity_name is not present in self.activities.
Notes
- Detailed description:
The method uses the activity mask stored in self.data but returns rows from self.extra_data. This is useful to inspect auxiliary channels (for example temperature, pressure, or instrument status signals) corresponding to specific tasks or events, without mixing them with the primary aerosol time series.
Examples
Correlate environmental parameters with a task:
env_task = data.get_activity_extra_data("Task") env_task[["Temperature", "RelativeHumidity"]].plot()
- Peak_finder(window=15, ratio=2.5, method='median', specific_data='')¶
Detect peaks and mark them as an activity labeled ‘Peak’.
- Parameters:
window (int) – Rolling window size in number of samples used to compute the local baseline and spread. Defaults to 15.
ratio (float) – Threshold factor on the rolling standard deviation. A time step is flagged as peak when value - baseline > ratio * rolling_std. Defaults to 2.5.
method (str) – Aggregation used as the rolling baseline, one of “mean”, “median”, “sum”, “min”, “max”. Defaults to “median”.
specific_data (str) – Optional column name to use for peak detection. If empty, the dataset’s primary channel is used (total concentration for particle instruments). Otherwise, the name is looked up first in self.data (numeric columns) and then in extra_data.
- Returns:
- The method adds/updates a boolean “Peak” column in
self.data and updates self.activity_periods[“Peak”].
- Return type:
None
- Raises:
ValueError – If method is not one of the supported names. Choose one of “mean”, “median”, “sum”, “min”, “max”.
ValueError – If specific_data is not found as a numeric column in either self.data or extra_data. Check column names via data.columns or extra_data.columns.
Notes
- Detailed description:
The method computes a rolling baseline and rolling standard deviation over the chosen data series. Points where the deviation from the baseline exceeds ratio times the rolling standard deviation are marked as peaks. Contiguous True segments in this mask are converted to (start, end) time intervals and stored as the “Peak” activity.
- Theory:
This is a simple statistical peak detector based on local outlier detection relative to a moving baseline and spread. It highlights periods where the signal is unusually high compared to its recent history.
Examples
Automatically tag high-exposure episodes:
data.Peak_finder(window=31, ratio=3.0) data.plot_total_conc(mark_activities=["Peak"]) peak_df = data.get_activity_data("Peak")
- Mark_threshold(activity, threshold, metric=None, threshold_direction='above')¶
Mark every time step whose value lies on the requested side of a fixed threshold as an activity, and store the contiguous runs as its periods.
This is a threshold-based segmenter: unlike
Peak_finder()(which compares each point to a moving baseline), it tags samples purely by whether they exceed — or fall below — a single, constant limit. It is the natural way to flag exposures above an occupational exposure limit (OEL) or any other fixed concentration cut-off.- Parameters:
activity (str) – Name to give the marked activity (e.g.
"OEL").threshold (int, float) – The fixed limit each sample is compared to.
metric (str, optional) – Column to compare against the threshold. If
None(default), the first column ofself.data(the total concentration) is used. Otherwise the name is looked up first among the numeric columns ofself.dataand then ofextra_data.threshold_direction (str) – Which side of the threshold counts as the activity.
"above"or">"flags samples strictly greater thanthreshold;"below"or"<"flags samples strictly less than it. Defaults to"above".
- Returns:
- The method adds/updates a boolean column named
activityin self.dataand stores its contiguous runs inself.activity_periods[activity].
- The method adds/updates a boolean column named
- Return type:
None
- Raises:
ValueError – If
metricis not found as a numeric column in eitherself.dataorextra_data. Check column names viadata.columnsorextra_data.columns.ValueError – If
threshold_directionis not one of the supported names. Choose one of"above","below",">"or"<".
Notes
- Detailed description:
The chosen metric is compared element-wise to
thresholdto build a boolean mask (NaN samples compare False and are never flagged). The mask is stored as theactivitycolumn, and its contiguous True segments are converted to(start, end)time intervals and stored as the activity’s periods.
Examples
Flag the periods where the total concentration exceeds an OEL and shade them on the time series:
data.Mark_threshold("OEL", threshold=1e4) data.plot_total_conc(mark_activities=["OEL"]) oel_df = data.get_activity_data("OEL")
- peak_finder¶
- mark_threshold¶
- available_metrics()¶
List the quantities this dataset can be summarised on.
Each entry is a
MetricSpecwhosekeyis accepted bysummarize_activities()/summarize_exposure(). Thedefault=Trueentries are the instrument’s primary metrics (used when nometrics=is given, and pre-selected in the GUI picker). Size-resolved classes override this to add derived PNC/MASS/Pₓ metrics.- Returns:
The dataset’s compatible metrics.
- Return type:
list[MetricSpec]
- summarize(filename=None, *, parameter=0)¶
Summarise basic statistics of one channel by activity.
Reports
Min / Max / Mean / Std / Nper activity (including"All data") for the selected channel. Works for any dataset — for a single-quantity instrumentparameter=0is the primary series; for a multi-channel instrument pick the channel by index or name.- Parameters:
- Returns:
Columns
["Segment", "Min", "Max", "Mean", "Std", "N datapoints"].- Return type:
- Raises:
LookupError – If
parameteris not a valid index or column label.
- summarize_activities(filename=None, sheet_name=None, metrics=None, stats=None)¶
Summarize 1D aerosol metrics per activity.
- Parameters:
filename (str | None) – Optional path to a CSV or Excel file. If provided, the summary table is appended to the file (creating it if it does not exist). If None, nothing is written to disk.
List of metric names to summarize. If None, the dataset’s natural set is used (see
_default_metrics()):["PNC"]for particle data, every numeric channel for a multi-channel instrument, or the named primary channel otherwise.”PNC” refers to the primary channel (total_concentration for particle instruments).
Any other name is looked up in data or extra_data (numeric columns only).
stats (Sequence[str] | None) – Which per-activity statistics to report for each metric. If None, defaults to
["mean", "std"](the historical behaviour). Each entry must be one of “mean”, “std”, “min”, “max”, “median”.sheet_name (Optional[str])
- Returns:
Summary table with one row per activity and columns:
”Segment”
”Duration (HH:MM)”
For each metric M and requested stat S: “M [unit] S”.
- Return type:
- Raises:
ValueError – If a requested metric (other than “PNC”) cannot be found in data or extra_data, or if
statscontains an unrecognised name.
Notes
The per-activity statistics are simple sample statistics over the selected time steps. Durations are based on the actual sampling intervals (via _dt_minutes).
Examples
data.summarize_activities() data.summarize_activities(stats=["mean", "min", "max"])
- summarize_exposure(metric='PNC', background=None, exposure_hours=None, short_limit=1.0, long_limit=1.0, short_window='15min', twa_window='8h', peak_ratio=2.5, filename=None, activities=None)¶
Summarize exposure metrics for one 1D metric across activities.
- Parameters:
metric (str) –
Exposure metric name based on the underlying 1D time series. Default is “PNC”, corresponding to the total particle number concentration. Supported forms:
”PNC”: total number concentration, mapped to
total_concentration.Any other string: interpreted as the name of a numeric column in
dataorextra_data(case-sensitive). For example, “MASS” or “TEMP” if such columns exist.
background (float | str | None) –
Background level used when computing the time-weighted average over
twa_window. The same background level is used for all activities in the output. Possible entries are:None: assume zero background.
float: constant background level in metric units.
str: name of an activity; the TWA of
metricover that activity is used as background.
exposure_hours (float | None) – Assumed duration of exposure for each activity, in hours, when embedding it into the TWA window. If None, the measured activity duration is used for that activity. If a positive value is given, the same exposure duration is applied for all activities.
short_limit (float) – Short-term concentration limit in metric units (for example a 15-min STEL). This value is reported in the output as
"STEL [unit]".long_limit (float) – Long-term concentration limit in metric units (for example an 8-h OEL). This value is reported in the output as
"Exposure limit [unit]".short_window (str) – Rolling window used for short-term (STEL) evaluation, given as a pandas offset string (for example “15min”). This is reported as
"STEL window [offset]"and used to construct a time-based rolling mean.twa_window (str) – Total duration of the TWA window as a pandas offset string (for example “8h”). This is reported as
"TWA window [offset]"and used to embed the segment exposure into a reference window (for example an 8-h shift).peak_ratio (float) –
Factor used in peak detection; peaks are flagged when the metric exceeds:
baseline + peak_ratio * rolling_std
where
baselineis a rolling median androlling_stdis a rolling standard deviation over a short window.filename (str | None) – Optional path to a CSV/Excel file to which the non-transposed result rows are appended. If the file exists, rows are appended; otherwise the file is created with a header. Supported extensions are “.csv”, “.xls”, “.xlsx”.
activities (Sequence[str] | None) – Activities to summarize. If None (default), all defined activities in
activitiesare summarized (for example “All data”, “Background”, “Task”). Activities with no marked time steps are skipped.
- Returns:
One row per activity segment with summary statistics for the chosen metric. Column names embed their units in square brackets where applicable (for example “Max [µg/m³]”). The set of columns matches that of
Aerosol2D.summarize_exposure(), restricted to a single 1D metric.- Return type:
- Raises:
ValueError – If
metriccannot be found (except “PNC”).ValueError – If a background activity name is given but does not exist or has no samples.
ValueError – If
short_windowortwa_windowcannot be parsed as pandas-style durations.ValueError – If
exposure_hoursis negative.TypeError – If
backgroundis not None, float, or str.
Notes
- Detailed description:
The method first obtains the requested metric time series from the 1D data:
For “PNC”, the series is taken from
total_concentration.For any other metric name, the series is taken from a numeric column in
dataorextra_data(if present).
For each selected activity, the method:
Extracts the metric time series within the activity using the corresponding boolean mask.
Computes per-step durations from the actual sampling times via
_dt_minutes().Forms a time-weighted segment mean (using the per-step durations), which is used internally when embedding the activity into the TWA window.
Computes instantaneous percentiles, peaks, STEL-style exceedances, and long-term time-above-limit measures.
Combines the segment mean with the specified background level to obtain an overall TWA for the chosen window.
The returned DataFrame contains the following columns (per activity):
- “Segment”
Name of the activity segment.
- “Metric”
Name of the metric that was summarized, e.g. “PNC”, “MASS”, or any other 1D column name.
- “Duration [HH:MM]”
Duration of the activity derived from the actual sampling intervals, formatted as “HH:MM” (hours and minutes).
- “Max [unit]”
Maximum of the instantaneous metric values during the activity. The unit is the metric unit (for example “cm⁻³” or “µg/m³”).
“95th percentile [unit]”
“75th percentile [unit]”
“50th percentile [unit]”
“25th percentile [unit]”
- “5th percentile [unit]”
Percentiles of the instantaneous metric values during the activity, all in the same unit as the metric.
- “Peaks [count]”
Number of distinct peak events detected in the activity, where a peak is a contiguous period in which the metric exceeds:
baseline + peak_ratio * rolling_std
with
baselinethe rolling median androlling_stdthe rolling standard deviation over a short sliding window, covering at least 3 datapoints and at most 15 datapoints, depending on how many samples are available in the segment.
- “STEL [unit]”
Short-term exposure limit used in the STEL exceedance calculations (echoing
short_limit), with the same concentration unit as the metric.
- “STEL window [offset]”
Rolling window length used for STEL evaluation, echoing
short_window(for example “15min”).
- “STEL exceedance [min]”
Total time in minutes during the activity where the full-window rolling mean is greater than or equal to the STEL. Only complete windows are counted in this measure.
- “STEL episodes [count]”
Number of distinct STEL exceedance episodes based on the full-window rolling mean. Each contiguous block of time where the full-window mean is at or above the STEL is counted as one episode.
- “Exposure limit [unit]”
Long-term exposure limit value used in the long-term evaluation (echoing
long_limit), with the same unit as the metric.
- “Exposure limit exceedance [min]”
Total time in minutes during the activity where the instantaneous metric values are greater than or equal to the exposure limit.
- “TWA concentration [unit]”
Time-weighted average concentration of the metric over the full TWA window (
"TWA window [offset]"), combining the internal segment mean (optionally stretched toexposure_hours) with the specified background level for the remainder of the window:TWA = (segment_mean * exposure_minutes + background * (twa_minutes - exposure_minutes)) / twa_minutes
where
twa_minutesis the duration oftwa_windowin minutes andexposure_minutesis either the measured activity duration orexposure_hours * 60, whichever is used.
- “TWA window [offset]”
Duration of the TWA window over which “TWA concentration [unit]” is evaluated, echoing
twa_window(for example “8h”).
- Theory:
Conceptually, the method mirrors typical occupational hygiene practice for a single 1D metric:
Exposure within an activity is represented by time-weighted averages and distributional descriptors (max and percentiles).
Short-term limits (STEL) are evaluated using rolling means over a specified window, counting both total time above the limit and distinct exceedance episodes.
Long-term limits are represented by cumulative time-above-limit measures.
An overall TWA for an 8-h (or user-specified) reference period is constructed by mixing the task exposure with a background level for the rest of the window.
This ensures a transparent link between raw 1D time-series behaviour and regulatory-style metrics such as STEL and 8-hour OELs.
Examples
Summarize total particle number concentration (PNC) exposure for all activities in a CPC dataset, using the “Background” activity as background level and a 15-min STEL with an 8-h TWA window:
cpc.summarize_exposure( metric="PNC", background="Background", short_limit=5e4, long_limit=2e4, short_window="15min", twa_window="8h", )
Other 1D metrics stored as columns (for example “MASS”) can be handled in the same way simply by changing the
metricargument.
- plot_total_conc(ax=None, mark_activities=False, parameter=0)¶
Plot a selected scalar channel versus time for a multi-channel object.
- Parameters:
ax (matplotlib.axes.Axes | None, optional) – Existing Matplotlib axes to draw on. If
None, a new figure and axes are created. Defaults toNone.mark_activities (bool | Sequence[str], optional) –
Control highlighting of activity periods defined on the object:
False– no shading (default).True– shade all activities except"All data".sequence of str – shade only the named activities.
parameter (int | str, optional) – Index or column name of the signal to plot. If
int, it is interpreted as a positional index intodata.columns. Ifstr, it is treated as a column label. Defaults to0.
- Returns:
The figure and axes containing the time-series plot.
- Return type:
- Raises:
LookupError – If
parameterdoes not correspond to a valid column index or column label.
Notes
- Detailed description:
This method overrides
Aerosol1D.plot_total_conc()to allow plotting of any scalar column stored indata, not only"Total_conc". It is particularly useful when an instrument logs multiple scalar metrics alongside time.Internally, the method:
Resolves
parameter:if an integer, it is used as a positional index into
data.columns,if a string, it must match a column label.
Creates or reuses a Matplotlib axes (depending on
ax).Plots the selected column against the object’s time index.
Configures the x-axis with a concise datetime formatter via
matplotlib.dates.Determines the appropriate
dtypeandunit:if global (scalar), they are used as-is;
if per-column mappings, the entry for the chosen
parameteris used.
The y-axis label is constructed from the base dtype (e.g.
"dN"from"dN/dlogDp"when applicable) and the corresponding unit.Optionally shades activity periods defined by
Aerosol1D.mark_activities()whenmark_activitiesisTrueor a list of activity names. Each activity receives a distinct colour, and overlapping shaded regions are clipped to the data’s time extent.Calls
fig.tight_layout()when it creates the figure to ensure margins and labels do not overlap.
Examples
A typical use is to visualise one of several channels stored in a multi-channel object, optionally with activity periods highlighted:
import aerosoltools as at # Suppose 'alt' is a multi-channel object with columns: ["LDSA", "Flow", "Flag"] alt = at.load_partector_file("data/Partector_log.txt") # Plot LDSA with activity shading fig, ax = alt.plot_total_conc( parameter="LDSA", mark_activities=True, ) # Plot Flow on existing axes without activity shading fig2, ax2 = plt.subplots() alt.plot_total_conc(ax=ax2, parameter="Flow", mark_activities=False)
- fit_decay(period, metric='PNC', model='auto', volume=None, air_exchange_rate=None, emission_start=None, peak_time=None, background=None, peak_concentration=None, decay_rate=None, optimize=True, snap_to_samples=True, series=None, unit=None)¶
Fit a single-zone emission + decay peak to one time window of a concentration metric, estimating the emission/source strength and the loss kinetics (zeroth, first, second order, or combined).
The loss kinetics come from a robust fit of the decay (post-peak) part alone; the peak is anchored to the data and the emission rate is back-solved from it, so the fit does not undershoot the peak.
- Parameters:
period (str | tuple) – Either an activity name (a boolean column in
data) or a(start, end)pair (anythingpandas.Timestamp()accepts) selecting the window to fit. The window should span the background, the rise, the peak and the decay.metric (str) – Metric to fit, as resolved by the class’s metric lookup (for example “PNC”, “MASS”, “PM2.5”). Default “PNC”.
model (str) – Which loss model to fit:
"zeroth_order"(constant removal),"first_order"(air exchange + deposition),"second_order"(coagulation),"combined"(first + second), or"auto"(fit all and pick the best, favouring the simpler). Aliases such as “0”/”constant”, “first”/”exp”, “second”/”coagulation”, “combined”/”both” are accepted.volume (float | None) – Chamber/room volume in m³. When given, the fitted emission rate is reported as a source strength (
E * volume) and a total emitted amount.air_exchange_rate (float | None) – An independently known air exchange rate in 1/hour. When given and the model has a first-order loss term, the wall-loss/deposition rate is estimated as
(first-order loss) - air_exchange_rate.emission_start – Optional explicit start of the source-on phase (anything
pandas.Timestamp()accepts, within the window). WhenNoneit is detected from the rise. Only affects the emission durationtpand hence the emission rate/source strength, not the loss kinetics.peak_time – Optional explicit peak time (source-off) splitting the emission from the decay. When
Noneit is detected as the (smoothed) maximum.background (float | None) – Override the background concentration
P0instead of measuring it from the pre-emission baseline. Held fixed during the fit, exactly like the measured value.peak_concentration (float | None) – Override the peak concentration (so the peak excess is
peak_concentration - background) instead of measuring it at the source-off time. Held fixed.decay_rate (float | None) – Seed for the loss kinetics, given as a first-order-equivalent rate in 1/s (the
decay_ratekey a previous fit returns). Withoptimize=Trueit just seeds the optimiser; withoptimize=Falseit is the loss rate, so the returned curve is a pure manual guess. WhenNonethe rate is estimated from the decay slope.optimize (bool) – When True (default) the loss kinetics are optimised against the post-peak data. When False the fit is skipped and the model is evaluated directly from the seed/override values, so the caller gets a previewable “initial guess” (used by the GUI to show a live preview before optimising). The returned dict has the same shape either way;
errorsare zero for a guess.snap_to_samples (bool) – When True (default) an explicit
emission_start/peak_timeis quantised to the nearest sample time, so the reported timing lands exactly on a data point. When False the supplied timestamps are used as continuous times (an onset or source-off may fall between two samples), so the emission durationtpand the drawn markers vary smoothly rather than jumping from sample to sample. Only affects the two timing overrides; detection (when they areNone) is unchanged.series (pandas.Series | None) – Optional precomputed, time-indexed concentration series to fit instead of the named
metric— used to fit an arbitrary series such as a single size bin (for per-bin decay fitting) with the same window and overrides. When given,metricis used only for labelling.unit (str | None) – Unit string for
series; whenseriesis given butunitisNonethe named metric’s unit is used.
- Returns:
A typed record (also a read-only mapping, so
result["r_squared"]still works) with fields includingmodel,unit,metric,r_squared(whole window),decay_r_squared(post-peak fit),n_points,params,errors,background,peak_concentration,peak_excess,emission_rate/emission_rate_unit,decay_rate/decay_rate_per_hour(first-order-equivalent loss rate, for round-tripping intodecay_rate),loss_rate_per_hour/half_life_hours(first-order term),zeroth_order_rate,second_order_rate(second/combined),wall_loss_rate_per_hour(withair_exchange_rate),source_strength/total_emitted(withvolume), the timing (emission_start_s,emission_duration_s,peak_time_s,peak_time) and, for redrawing,window_startandmodel_popt(seedecay_curve()). Optional model-/volume- specific fields areNone(and omitted from the mapping view) when not applicable.- Return type:
DecayResult
- Raises:
ValueError – If
periodis neither a known activity nor a valid(start, end)pair, if the window has too few finite samples, ifmodelis unrecognised, or if no model could be fitted.
Examples
Fit a chamber emission peak and read the source strength:
res = data.fit_decay("Emission", metric="PNC", volume=20.0) print(res["source_strength"], res["source_strength_unit"])