Corrections (dv.corrections)¶
Offset and gain corrections applied to measured series.
Imported as diive.corrections, reached as dv.corrections after import diive as dv.
CORRECTIONS: VALUE CORRECTIONS¶
Public namespace dv.corrections: offset and value corrections.
Part of the diive library: https://github.com/holukas/diive
- class diive.corrections.MeasurementOffsetFromReplicate(measurement, replicate, offset_start=-100, offset_end=100, offset_stepsize=0.1, verbose=None)[source]¶
Bases:
objectDetect and remove a constant additive offset between a measurement and a co-located replicate.
Scans candidate offsets and selects the one that minimizes the summed absolute difference between the offset-shifted measurement and the replicate, then returns the corrected measurement (
measurement + offset). A single global offset is applied — no per-year handling and no gain term.Example
See examples/preprocessing/corrections/correction_measurement_offset_replicate.py
- Parameters:
- __init__(measurement, replicate, offset_start=-100, offset_end=100, offset_stepsize=0.1, verbose=None)[source]¶
Find the additive offset that best aligns measurement with replicate.
For each offset in
arange(offset_start, offset_end, offset_stepsize), the measurement is shifted by that offset and the summed absolute difference to the replicate is computed. The offset with the smallest summed absolute difference is selected and added to the measurement.- Parameters:
measurement (
Series) – Time series to be corrected.replicate (
Series) – Co-located reference series the measurement is aligned to.offset_start (
int) – Smallest offset to try (same units as the data).offset_end (
int) – Largest offset to try (exclusive).offset_stepsize (
float) – Step between candidate offsets.verbose (
int|bool|None) – Verbosity for the console helpers. The line printed for each candidate offset appears atVERBOSE_DEBUG(3). None uses the level set withset_verbosity().
- Raises:
ValueError – If measurement and replicate have no timestamp at which both have a value, so no offset can be compared.
- class diive.corrections.NighttimeZeroOffsetPlot(result, records=None)[source]¶
Bases:
objectDiagnostic figure of the nighttime zero-offset correction.
Two-phase like the other diive plots: the constructor takes the result of
nighttime_zero_offset_diagnostics,plot()draws. A strip at the top shows the five steps of the correction in order, each with its count:Night: records with potential radiation below 0.001 W m-2.
Daily offset: the mean of the night values of each calendar day (the night before sunrise and the night after sunset of that date). Every record of the day gets this value, there is no interpolation between days. Days without night values get the median of all daily offsets.
The offset is subtracted from every record of the day.
Night records are set to 0.
Values still below 0 (daytime, e.g. at dawn and dusk) are set to 0, unless
clamp_negatives=Falsekept them.
Panels below the strip, titled with the steps they show:
Series: measured and corrected high-res data.
Daily offset: one value per calendar day, drawn as a step line, with the standard deviation of the day’s night values as a band, the median as a line, and days without nighttime data (median offset) marked.
Diel cycle near zero: median of each time of day, measured, after subtracting the offset (step 3) and final (steps 4 and 5), limited to the low range where the offset matters, with the times of day that are mostly night shaded.
Nighttime values: distribution of the measured nighttime values and of their residuals after subtracting the day’s offset. A narrow residual distribution means one offset per day describes the night well.
Summary: records, nighttime share, offset statistics, records below zero before and after, daytime records clamped to zero, and mean, min and max before and after.
Example
>>> import diive as dv, numpy as np, pandas as pd >>> idx = pd.date_range('2024-06-01', periods=48 * 5, freq='30min', name='TIMESTAMP_MIDDLE') >>> pot = dv.variables.potrad(timestamp_index=idx, lat=47.1, lon=8.5, utc_offset=1) >>> sw = pd.Series(np.where(pot > 0.001, 0.7 * pot, 0) - 8.0, index=idx, name='SW_IN') >>> res = dv.corrections.nighttime_zero_offset_diagnostics(sw, lat=47.1, lon=8.5, utc_offset=1) >>> fig = dv.corrections.NighttimeZeroOffsetPlot(res).plot(showplot=False)
- Parameters:
result (NighttimeZeroOffsetResult)
records (Series | None)
- __init__(result, records=None)[source]¶
Prepare the figure data.
- Parameters:
result (
NighttimeZeroOffsetResult) – Output ofnighttime_zero_offset_diagnostics.records (
Series|None) – Optional boolean Series on the index of result, True for rows that are records. Rows that are no record (empty grid slots between coarse records in meteo screening) are left out of the line plots, so lines join neighbouring records. Missing records stay NaN and break the lines.
- class diive.corrections.NighttimeZeroOffsetResult(input, offset, corrected_by_offset, corrected, nighttime_flag, n_below_zero_before, n_below_zero_before_night, n_below_zero_after, n_below_zero_after_night, n_night)[source]¶
Bases:
objectIntermediate series + below-zero stats of the nighttime zero-offset correction, for inspection/plotting.
correctedis identical toremove_nighttime_zero_offset()’s output.- Variables:
input (
Series) – Original (uncorrected) series.offset (
Series) – Daily nighttime-mean offset broadcast to the hires timestamps (days without nighttime data filled with the median daily offset, 0 when there is no nighttime data at all).corrected_by_offset (
Series) –input - offset, before nighttime is forced to zero and remaining negatives are clamped.corrected (
Series) – Final corrected series (nighttime forced to zero, remaining negative values clamped to zero whenclamp_negatives).nighttime_flag (
Series) – 1 where nighttime, 0 where daytime.n_below_zero_before (
int) – Records below zero ininput.n_below_zero_before_night (
int) – Nighttime records below zero ininput.n_below_zero_after (
int) – Records below zero incorrected(expected 0 whenclamp_negatives).n_below_zero_after_night (
int) – Nighttime records below zero incorrected(expected 0).n_night (
int) – Number of nighttime records.
- Parameters:
- __init__(input, offset, corrected_by_offset, corrected, nighttime_flag, n_below_zero_before, n_below_zero_before_night, n_below_zero_after, n_below_zero_after_night, n_night)¶
- class diive.corrections.RelativeHumidityOffsetPlot(result, records=None)[source]¶
Bases:
objectDiagnostic figure of the relative humidity offset correction.
Two-phase like the other diive plots: the constructor takes the result of
relativehumidity_offset_diagnostics,plot()draws. A strip at the top shows the five steps of the correction in order, each with its count:Find the values above 100 %.
Daily offset: for each day with such values, their mean minus 100. Every record of the day gets it.
Other days get the offset interpolated linearly, record by record, between the nearest days with values above 100 %, and carried before the first and after the last such day. Without any value above 100 % the offset is 0.
The offset is subtracted from every record.
Values still above 100 % are set to 100 %.
Panels below the strip, titled with the steps they show:
Series: measured and corrected high-res data, with the 100 % line.
Offset: the offset of each record. Days with values above 100 % are drawn as one value per day with the standard deviation of their values above 100 % as a band, the interpolated and carried offset as a dashed line.
Near 100 %: distribution of the upper range, measured, after subtracting the offset and final. A pile just below 100 % without values above it means the sensor or logger caps the readings, so the correction cannot find an offset.
Daily maximum: before and after the correction, with the 100 % line.
Summary: records, values above, at and just below 100 %, offset statistics, capped records, and mean, min and max before and after.
Example
>>> import diive as dv, numpy as np, pandas as pd >>> idx = pd.date_range('2024-06-01', periods=48 * 10, freq='30min', name='TIMESTAMP_MIDDLE') >>> rh = pd.Series(80 + 22 * np.sin(np.arange(len(idx)) / 48 * 2 * np.pi), index=idx, name='RH') >>> res = dv.corrections.relativehumidity_offset_diagnostics(rh) >>> fig = dv.corrections.RelativeHumidityOffsetPlot(res).plot(showplot=False)
- Parameters:
result (RelativeHumidityOffsetResult)
records (Series | None)
- __init__(result, records=None)[source]¶
Prepare the figure data.
- Parameters:
result (
RelativeHumidityOffsetResult) – Output ofrelativehumidity_offset_diagnostics.records (
Series|None) – Optional boolean Series on the index of result, True for rows that are records. Rows that are no record (empty grid slots between coarse records in meteo screening) are left out of the line plots, so lines join neighbouring records. Missing records stay NaN and break the lines.
- class diive.corrections.RelativeHumidityOffsetResult(input, above_100, daily_offset, offset, corrected_by_offset, corrected, n_above_100_before, n_capped)[source]¶
Bases:
objectIntermediate series of the relative humidity offset correction, for inspection and plotting.
correctedis identical toremove_relativehumidity_offset()’s output.- Variables:
input (
Series) – Original (uncorrected) series.above_100 (
Series) – True where input is above 100.daily_offset (
Series) – Offset of the days with values above 100 (the mean of these values minus 100), on every record of such a day, NaN on other days.offset – Offset of every record: daily_offset, linearly interpolated between the days with values above 100 and carried before the first and after the last such day. 0 without any value above 100.
corrected_by_offset (
Series) –input - offset, before values above 100 are capped.corrected (
Series) – Final corrected series, values above 100 set to 100.n_above_100_before (
int) – Records above 100 in input.n_capped (
int) – Records above 100 after the offset, set to 100.
- Parameters:
- __init__(input, above_100, daily_offset, offset, corrected_by_offset, corrected, n_above_100_before, n_capped)¶
- class diive.corrections.WindDirOffset(winddir, hist_ref_years, offset_start=-100, offset_end=100, hist_n_bins=360, verbose=None)[source]¶
Bases:
objectCompare yearly wind direction histograms to reference, detect offset in comparison to reference and correct wind directions for offset per year
Example
See examples/preprocessing/corrections/correction_winddir_offset.py
- Parameters:
- __init__(winddir, hist_ref_years, offset_start=-100, offset_end=100, hist_n_bins=360, verbose=None)[source]¶
Build histogram of wind directions for each year and compare to reference histogram built from data in reference years
Build reference histogram of wind directions from reference years
For each year: 2a: Add constant offset to wind directions, starting with offset_start 2b: Build histogram of wind directions 2c: Calculate absolute correlation between 2b and reference 2d: Continue with next offset, ending with offset_end 2e: Detect offset that yielded maximum absolute correlation with reference
A year without a valid correlation for any offset (e.g. a year without data, or a reference histogram with the same count in every bin) gets NaN as offset and a warning, and its wind directions are not corrected.
- Parameters:
winddir (
Series) – Time series of wind directions in degreeshist_ref_years (
list) – List of years for building reference histogram, e.g. “[2021, 2022]”offset_start (
int) – Minimum offset in degrees to shift winddiroffset_end (
int) – Maximum offset in degrees to shift winddirhist_n_bins (
int) – Number of bins for building histograms. The bins always span the full compass circle [0, 360), so the default 360 gives one bin per degree and e.g. 36 gives one per 10 degrees.verbose (
int|bool|None) – Verbosity for the console helpers. The line printed for each year appears atVERBOSE_DEBUG(3). None uses the level set withset_verbosity().
- Raises:
ValueError – If winddir has no data in hist_ref_years.
- diive.corrections.nighttime_zero_offset_diagnostics(series, lat, lon, utc_offset, clamp_negatives=True, swin_pot=None, swin_pot_period_sec=None)[source]¶
Nighttime zero-offset correction with every intermediate series exposed.
Same computation as
remove_nighttime_zero_offset()(result.correctedis identical), but additionally returns the daily offset, the offset-subtracted series, the nighttime flag, and the count of below-zero records before/after the correction (overall and nighttime) — for inspection and plotting.- Parameters:
series (
Series) – Data for the variable that is corrected.lat (
float) – Latitude of the location where data were recorded.lon (
float) – Longitude of the location where data were recorded.utc_offset (
int) – UTC offset of the timestamp index, e.g. 1 for UTC+01:00.clamp_negatives (
bool) – If True (default), clamp remaining negatives to zero (seeremove_nighttime_zero_offset()). With False,n_below_zero_afterreflects the daytime negatives that were kept.swin_pot (
Series|None) – Potential radiation on the index of series, used instead of computing it (seeremove_nighttime_zero_offset()).swin_pot_period_sec (
Series|None) – Seconds each record of swin_pot averages (seeremove_nighttime_zero_offset()).
- Return type:
- Returns:
- diive.corrections.relativehumidity_offset_diagnostics(series)[source]¶
Relative humidity offset correction with every intermediate series exposed.
Same computation as
remove_relativehumidity_offset()(result.correctedis identical), but additionally returns the offsets of the days above 100, the offset of every record, the offset-subtracted series and the counts, for inspection and plotting (RelativeHumidityOffsetPlot).- Parameters:
series (
Series) – Relative humidity in %.- Return type:
- Returns:
- diive.corrections.remove_nighttime_zero_offset(series, lat, lon, utc_offset, showplot=False, clamp_negatives=True, swin_pot=None, swin_pot_period_sec=None)[source]¶
Remove a nighttime zero-offset from a variable that should read zero at night
General-purpose: works for any variable expected to be zero during nighttime (e.g. shortwave radiation, PPFD). A nighttime flag is calculated and used to detect nighttime data. Then, for each calendar day, the mean of that day’s nighttime values (before sunrise and after sunset of that date) is the offset by which all of the day’s records are corrected. The offset is constant within the day, without interpolation between days (days without nighttime data use the median of all daily offsets, and with no nighttime value at all the offset is 0). Finally, after the offset is applied, nighttime values are set to zero and (when
clamp_negatives) any remaining negative values are clamped to zero, enforcing the variable’s physical floor of zero.Nighttime is where potential radiation is below 0.001 W m-2.
potradgives 0 for the minutes its solar-noon shift vacates at the start or end of each calendar day. Where the sun is up then (polar day, or a short night next to midnight), a record in these minutes counts as daytime if the sun’s curve across midnight brings its potential radiation to 0.001 W m-2 or more. It is then not zeroed and gives no offset. A polar day has no nighttime data and gets the median offset, or 0 if no day in the series has nighttime data. The offset cannot be estimated in polar day.- Parameters:
series (
Series) – Data for the variable that is correctedlat (
float) – Latitude of the location where data were recordedlon (
float) – Longitude of the location where data were recordedutc_offset (
int) – UTC offset of the timestamp index of series, e.g. 1 for UTC+01:00. Used to find nighttime; the returned Series keeps the index of series.showplot (
bool) – Show the diagnostic figure (NighttimeZeroOffsetPlot): the five steps with their counts, series, daily offset, diel cycle near zero, nighttime values and a summary.clamp_negatives (
bool) – If True (default), set remaining negative values (daytime included) to zero after the offset is removed, enforcing a physical floor of zero. If False, keep those negatives (nighttime is still forced to zero).swin_pot (
Series|None) – Potential radiation (W m-2) aligned to the index of series, used for the day/night split instead of computing it from lat, lon and utc_offset. These still give the midnight zeros described above. Pass it when the potential radiation must be computed differently, e.g. per time resolution. It must contain every timestamp of series and may contain more. Timestamps are record middles. Each record’s period is its value in swin_pot_period_sec, else its spacing to the nearer neighbouring record. A record with a period longer than the grid of swin_pot is taken to end half a grid step after its timestamp, as on meteo screening’s grids with several time resolutions. NaN means not a record. None (default) computes it withpotrad.swin_pot_period_sec (
Series|None) – Seconds each record of swin_pot averages, on its index (e.g. meteo screening’s FREQ_AUTO_SEC). Only used with swin_pot, to find the midnight zeros described above. NaN or a missing timestamp falls back to the spacing to the nearer neighbouring record. That spacing is too short for the last coarse record before a finer block, so pass this when the records have several time resolutions. None (default) uses the spacing.
- Return type:
- Returns:
Corrected series
Example
See examples/preprocessing/corrections/correction_radiation_offset.py
- diive.corrections.remove_relativehumidity_offset(series, showplot=False)[source]¶
Correct relative humidity offset > 100%
Works for relative humidity data where maximum values should not exceed 100%. The correction runs in this order:
Find the values above 100%.
For each day with such values, the offset is the mean of these values minus 100. Every record of the day gets it.
Days without values above 100% get the offset interpolated linearly, record by record, between the nearest earlier and later days with such values. Before the first and after the last such day, the offset of that day is carried. Without any value above 100% the offset is 0.
The offset is subtracted from every record.
Values still above 100% are set to 100%.
A single day above 100% (e.g. two hours of fog) thus lowers every record of the series by its offset. This assumes that a sensor reading too high when saturated reads too high on every day. The result depends on the period screened.
- Parameters:
- Return type:
- Returns:
Corrected series
Example
See examples/preprocessing/corrections/correction_relativehumidity_offset.py
- diive.corrections.set_exact_values_to_missing(series, values, showplot=False, verbose=None)[source]¶
Set records matching values to missing values.
A record matches when it equals the value within a relative tolerance of 1e-6 (
np.isclosewithrtol=1e-6, atol=0), so data stored as float32 still match: float32 0.1 is 0.10000000149 as float64 and does not equal 0.1. The tolerance is below the resolution of measurements (-9999 matches values within 0.01 of it). 0 matches only 0.- Parameters:
series (
Series) – Data for variable that is correctedvalues (
list) – List of numbers that will be set to missing values. Any other entry (None, pd.NA, a string such as ‘-9999’, a bool) raises a ValueError before anything is changed, because a value that is silently skipped would leave e.g. -9999 in the data. NaN is a number and matches nothing.showplot (
bool) – Show plotverbose (
int|bool|None) – Verbosity for the console helpers. The report appears atVERBOSE_PROGRESS(2) and above, the locations of the records atVERBOSE_DEBUG(3). 0 prints nothing. None (default) uses the level set withset_verbosity().
- Return type:
- Returns:
Corrected series
Example
See examples/preprocessing/corrections/correction_set_exact_values_to_missing.py
- diive.corrections.setto_threshold(series, threshold, type, showplot=False, verbose=None)[source]¶
Set values above or below a threshold value to threshold value
- Parameters:
series (
Series) – Data for variable that is correctedthreshold (
float) – Threshold valuetype (
str) – min sets series values below threshold to threshold, ‘max’ sets series values above threshold to thresholdshowplot (
bool) – Show plotverbose (
int|bool|None) – Verbosity for the console helpers. The report appears atVERBOSE_PROGRESS(2) and above, 0 prints nothing. None (default) uses the level set withset_verbosity().
- Return type:
- Returns:
Corrected series (float64 if series is integer and threshold is not a whole number)
Example
See examples/preprocessing/corrections/correction_setto_threshold.py
- diive.corrections.setto_value(series, dates, value=0, verbose=0)[source]¶
Set time range(s) to specific value
- Parameters:
series (
Series) – time series. The index does not need to be sorted.dates (
list) – list of the date(times) of records that are set to value. A string is a single date(time); a range is a nested[start, end]list, both ends inclusive. A bare date covers the whole day. Example dates=[‘2022-06-30 23:58:30’, [‘2022-06-05 00:00:30’, ‘2022-06-07 14:30:00’]] will select the record for ‘2022-06-30 23:58:30’ and all records between ‘2022-06-05 00:00:30’ (inclusive) and ‘2022-06-07 14:30:00’ (inclusive). A flat list such as dates=[‘2006-05-01’, ‘2006-07-18’] selects the two days 2006-05-01 and 2006-07-18; dates=[[‘2006-05-01’, ‘2006-07-18’]] selects all records from 2006-05-01 to the end of 2006-07-18.value (
float) – the value filled in for all records that fall within the specified time range(s)verbose (
int) – more text output to console if verbose > 0
- Returns:
series with records in time range dates set to value (float64 if series is integer and value is not a whole number)
Example
See examples/preprocessing/corrections/correction_setto_value.py
- diive.corrections.apply_corrections(series, corrections, *, lat=None, lon=None, utc_offset=None, showplot=False)[source]¶
Apply an ordered list of corrections to a series.
- Parameters:
series (
Series) – Series to correct.corrections (
list[dict]) – Ordered list of{"key": str, "kwargs": dict}dicts.keyis one of theCORR_*constants indiive.preprocessing.qaqc.measurements;kwargsare the correction-specific parameters (e.g.{"threshold": 30}for the set-to-max correction).lat (
float|None) – Site latitude (required for the radiation zero-offset correction).lon (
float|None) – Site longitude (required for the radiation zero-offset correction).utc_offset (
int|None) – UTC offset of the timestamp index (required for the radiation zero-offset correction).showplot (
bool) – Show a plot for each correction.
- Return type:
- Returns:
The corrected series (named like the input).