Flux processing (dv.flux)¶
Eddy covariance fluxes: the post-processing chain, u* threshold detection, NEE partitioning and uncertainty.
Imported as diive.flux, reached as dv.flux after import diive as dv.
FLUX: EDDY COVARIANCE PROCESSING¶
Low-resolution flux analysis, USTAR filtering, NEE partitioning and uncertainty. High-frequency raw-data tooling moved to the dyco package: https://github.com/holukas/dyco Swiss FluxNet post-processing chain for levels L2-L4.2.
Part of the diive library: https://github.com/holukas/diive
- class diive.flux.NighttimePartitioningOneFlux(nee, ta, sw_in, nee_f, ta_f, lat, verbose=2)[source]¶
Bases:
objectPartition NEE into GPP and RECO with the nighttime method (ONEFlux).
Faithful, vectorized port of the ONEFlux nighttime partitioning (Reichstein et al. 2005). Each calendar year in the input is partitioned independently.
Timestamps: the input index is diive’s TIMESTAMP_MIDDLE and the results are returned on it. Internally, as in ONEFlux, the hour and day of year used for the sunrise/sunset test and the fitting windows are those of the period END, and the year’s last record, whose END falls on 1 January, is counted as day 366 (367 in a leap year). A record with missing
sw_instays eligible as night, as the ONEFlux -9999 sentinel does; the sunrise/sunset test then decides. On days without sunrise or sunset (polar day and polar night) no record is night, as in ONEFlux, where the day/night flag is missing there.Hourly data are partitioned on their own records, as in ONEFlux. ONEFlux puts an hourly year onto a half-hourly grid only for its daytime method (
library.create_data_structures), not for this one.Numerics follow ONEFlux: working arrays are float32, as ONEFlux stores them (
FLOAT_PREC = 'f4'), with the dtype of every intermediate as ONEFlux gets it on NumPy 1, and Rref is fitted withleastsqas in ONEFlux rather than solved.NEE_NIGHT_OFkeeps the input’s float64 values; all other columns hold float32 values.Measured agreement, CH-DAV 2016 and 2019 and CH-LAE 2017-2019 half-hourly, and US-Ha1 2023-2024, US-MMS 2022-2023 and CH-DAV 2016 averaged to hourly records, against a native ONEFlux 1.3.7 run (NumPy 1.26, SciPy 1.17): RECO, GPP (ordinary and robust), Rref and E0 are bitwise identical in every record, also with gaps in measured TA, SW_IN and nighttime NEE, and at CH-LAE, where only 17-20 % of NEE is measured. The same holds for the FLUXNET v1.3 sites FI-Hyy, FI-Var, IL-Yat, AU-GWW and GF-Guy (2023, 2024) and DE-Hai (2020, 2024). This relies on SciPy’s
leastsqandinterp1dbehaving as in that version.Example:
examples/flux/partitioning/partitioning_nighttime_oneflux.pyExample
>>> import diive as dv >>> df = dv.load_exampledata_parquet() >>> part = dv.flux.NighttimePartitioningOneFlux( ... nee=df['NEE_CUT_REF_orig'], ta=df['Tair_orig'], sw_in=df['Rg_orig'], ... nee_f=df['NEE_CUT_REF_f'], ta_f=df['Tair_f'], lat=46.815) >>> part.run() # then part.results -> DataFrame with RECO_NT_OF, GPP_NT_OF, ...
- Parameters:
- __init__(nee, ta, sw_in, nee_f, ta_f, lat, verbose=2)[source]¶
- Parameters:
nee (
Series) – Measured net ecosystem exchange (umol m-2 s-1). Gaps (NaN) are the records that were not measured / did not pass QC.ta (
Series) – Measured air temperature (degC), gaps as NaN.sw_in (
Series) – Incoming shortwave radiation (W m-2), used for the day/night split. Gaps as NaN.nee_f (
Series) – Gap-filled NEE (umol m-2 s-1) - used for the GPP residual.ta_f (
Series) – Gap-filled air temperature (degC) - used to compute RECO at every record.lat (
float) – Site latitude in decimal degrees.verbose (
int) – Console verbosity level (0 silent, 1 warnings, 2 progress + report, 3 debug). Default 2.
- property results: DataFrame¶
DataFrame of partitioning results (aligned to the input index).
Columns:
NEE_NIGHT_OF(nighttime NEE used),RECO_NT_OF/RECO_NT_OF_ROB(ecosystem respiration, ordinary / outlier-robust),GPP_NT_OF/GPP_NT_OF_ROB(gross primary production),RREF_NT_OF(interpolated reference respiration),E0_NT_OF(per-year temperature sensitivity).
- diive.flux.partition_nee_nighttime_oneflux(nee, ta, sw_in, nee_f, ta_f, lat, verbose=2)[source]¶
Functional wrapper around
NighttimePartitioningOneFlux.See
NighttimePartitioningOneFluxfor argument semantics.
- class diive.flux.NighttimePartitioningReddyProc(nee, ta, sw_in, nee_f, ta_f, lat, lon, utc_offset, verbose=2)[source]¶
Bases:
objectPartition NEE into GPP and RECO with the nighttime method (REddyProc).
Faithful, vectorized port of REddyProc’s
sMRFluxPartition(Reichstein et al. 2005). Unlike the ONEFlux variant, the whole record is partitioned at once with a single temperature sensitivity E0, matching REddyProc.Example:
examples/flux/partitioning/partitioning_nighttime_reddyproc.pyExample
>>> import diive as dv >>> df = dv.load_exampledata_parquet() >>> part = dv.flux.NighttimePartitioningReddyProc( ... nee=df['NEE_CUT_REF_orig'], ta=df['Tair_orig'], sw_in=df['Rg_orig'], ... nee_f=df['NEE_CUT_REF_f'], ta_f=df['Tair_f'], ... lat=46.815, lon=9.855, utc_offset=1) >>> part.run() # then part.results -> DataFrame with RECO_NT_RP, GPP_NT_RP, ...
- Parameters:
- __init__(nee, ta, sw_in, nee_f, ta_f, lat, lon, utc_offset, verbose=2)[source]¶
- Parameters:
nee (
Series) – Measured net ecosystem exchange (umol m-2 s-1). Gaps (NaN) are the records that were not measured / did not pass QC.ta (
Series) – Measured air temperature (degC), gaps as NaN.sw_in (
Series) – Incoming shortwave radiation (W m-2), used for the day/night split. Gaps as NaN.nee_f (
Series) – Gap-filled NEE (umol m-2 s-1) - used for the GPP residual.ta_f (
Series) – Gap-filled air temperature (degC) - used to compute RECO at every record.lat (
float) – Site latitude in decimal degrees.lon (
float) – Site longitude in decimal degrees (REddyProc needs longitude and the UTC offset for the solar-time day/night split).utc_offset (
float) – Time zone offset from UTC in hours (e.g. +1 for CET).verbose (
int) – Console verbosity level (0 silent, 1 warnings, 2 progress + report, 3 debug). Default 2.
- property results: DataFrame¶
DataFrame of partitioning results (aligned to the input index).
Columns:
NEE_NIGHT_RP(nighttime NEE used),RECO_NT_RP(ecosystem respiration),GPP_NT_RP(gross primary production),RREF_NT_RP(interpolated reference respiration),E0_NT_RP(single temperature sensitivity for the whole record).
- diive.flux.partition_nee_nighttime_reddyproc(nee, ta, sw_in, nee_f, ta_f, lat, lon, utc_offset, verbose=2)[source]¶
Functional wrapper around
NighttimePartitioningReddyProc.See
NighttimePartitioningReddyProcfor argument semantics.
- class diive.flux.DaytimePartitioningReddyProc(nee, ta, vpd, sw_in, lat, lon, utc_offset, nee_sd=None, vpd_in_kpa=True, verbose=2)[source]¶
Bases:
objectPartition NEE into GPP and RECO with the daytime method (REddyProc).
Faithful, vectorized port of REddyProc’s
partitionNEEGL(Lasslop et al. 2010 light-response-curve method). Fits a rectangular-hyperbola LRC to daytime NEE in short windows with the temperature sensitivityE0fixed from nighttime data, then predicts GPP and RECO for every record. Emits*_DT_RPcolumns, mirroring the nighttime REddyProc port’s*_NT_RP.Example:
examples/flux/partitioning/partitioning_daytime_reddyproc.pyExample
>>> import diive as dv >>> df = dv.load_exampledata_parquet() >>> part = dv.flux.DaytimePartitioningReddyProc( ... nee=df['NEE_CUT_REF_orig'], ta=df['Tair_f'], vpd=df['VPD_f'], ... sw_in=df['Rg_f'], lat=46.815, lon=9.855, utc_offset=1, ... vpd_in_kpa=False) # VPD_f is in hPa in the example data >>> part.run() # then part.results -> DataFrame with RECO_DT_RP, GPP_DT_RP, ...
- Parameters:
- __init__(nee, ta, vpd, sw_in, lat, lon, utc_offset, nee_sd=None, vpd_in_kpa=True, verbose=2)[source]¶
- Parameters:
nee (
Series) – Measured net ecosystem exchange (umol m-2 s-1). Gaps (NaN) are the records that were not measured / did not pass QC; the daytime LRC is fitted on the measured daytime values only.ta (
Series) – Gap-filled air temperature (degC). REddyProc’s daytime method uses the gap-filled meteo drivers throughout (both for fitting and for prediction), quality-filtering only NEE.vpd (
Series) – Gap-filled vapour pressure deficit. By default in kPa (diive convention) and converted internally to hPa, the unit REddyProc’s Lasslop LRC expects (VPD0 = 10 hPa). Passvpd_in_kpa=Falseifvpdis already in hPa.sw_in (
Series) – Gap-filled incoming shortwave radiation (W m-2). Used both for the day/night split and as the LRC light driver.lat (
float) – Site latitude in decimal degrees.lon (
float) – Site longitude in decimal degrees (needed for the solar-time day/night split).utc_offset (
float) – Time zone offset from UTC in hours (e.g. +1 for CET).nee_sd (
Series|None) – Per-record NEE uncertainty (umol m-2 s-1) used to weight the LRC fit. IfNone, REddyProc’s default is reproduced: missing uncertainties are set tomax(0.7, 0.2*|NEE|).vpd_in_kpa (
bool) – If True (default),vpdis in kPa and multiplied by 10 to hPa internally.verbose (
int) – Console verbosity level (0 silent, 1 warnings, 2 progress + report, 3 debug). Default 2.
- property results: DataFrame¶
DataFrame of partitioning results (aligned to the input index).
Columns:
RECO_DT_RP(ecosystem respiration),GPP_DT_RP(gross primary production), and the fitted LRC parametersK_DT_RP,BETA_DT_RP,ALPHA_DT_RP,RREF_DT_RP,E0_DT_RPreported at the central record of each window (NaN elsewhere).
- diive.flux.partition_nee_daytime_reddyproc(nee, ta, vpd, sw_in, lat, lon, utc_offset, nee_sd=None, vpd_in_kpa=True, verbose=2)[source]¶
Functional wrapper around
DaytimePartitioningReddyProc.See
DaytimePartitioningReddyProcfor argument semantics.
- class diive.flux.DaytimePartitioningOneFlux(nee, ta, sw_in, ta_f, sw_in_f, vpd, vpd_in_kpa=True, reject_alpha_at_start=False, nee_f=None, verbose=2)[source]¶
Bases:
objectPartition NEE into GPP and RECO with the daytime method (ONEFlux).
Faithful, vectorized port of the ONEFlux
flux_part_gl2010(Lasslop et al. 2010 light-response-curve method). Each calendar year is partitioned independently. Emits*_DT_OFcolumns, mirroring the nighttime ONEFlux port’s*_NT_OFand the daytime REddyProc port’s*_DT_RP.The method uses ONEFlux’s measured-radiation day/night threshold for fitting (
Rg > 4day,Rg <= 4night) and does not use latitude / solar geometry. It needs both the measured (gappy) and gap-filled drivers, as ONEFlux does: measured Rg/TA classify records and feed the internal NEE uncertainty look-up, while the gap-filled drivers feed the fits and the flux prediction.Input resolution: hourly data are partitioned the way ONEFlux partitions an hourly site. ONEFlux’s daytime method works on a half-hourly grid. It repeats every hourly record, and the first copy stands for the half-hour that ends 30 minutes earlier. The windows are fitted on this grid, which holds every measured record twice, and ONEFlux’s pipeline keeps the first copy of each record for its hourly output. diive does the same, so an hourly year gives ONEFlux’s hourly result. The window parameters are reported at their central records on the hourly index. Half-hourly data are partitioned as they are. Other resolutions, which ONEFlux does not process, are partitioned at their own resolution.
Measured agreement against a native ONEFlux 1.3.7 run (NumPy 1.26, SciPy 1.17) on the same arrays: half-hourly CH-DAV 2016 and 2019 and CH-LAE 2017-2019 (where only 17-20 % of NEE is measured), also with gaps in measured TA, SW_IN and nighttime NEE, and hourly US-Ha1 2023-2024, US-MMS 2022-2023 and CH-DAV 2016 averaged to hourly records. The per-record NEE uncertainty is identical bit for bit, and so is every light-response fit and every window parameter (143 windows on CH-DAV 2016, 77-123 per CH-LAE run, 142-162 per hourly run). Per record, GPP and RECO differ by at most 8e-6 umol m-2 s-1, float32 rounding, and the annual sums agree to 0.0001%. On the FLUXNET v1.3 sites FI-Hyy, FI-Var, IL-Yat, AU-GWW and GF-Guy (2023, 2024) and DE-Hai (2020, 2024) every fit is bitwise identical as well.
A fit that returns no covariance matrix (
leastsqdid not converge) makes ONEFlux abort the year. Its pipeline then removes the measured NEE on the days that window’s nighttime fit uses (about 12 days) and runs the year again, until no fit fails. diive does the same, so the NEE uncertainty and the windows around the failed one change too; the removed day ranges are inremoved_days. In ONEFlux the removed days apply to all u* percentiles of that year and product. This class partitions one NEE series and removes only the days its own fits need. To share the removed days between u* scenarios, usepartition_nee_daytime_oneflux_scenarios(), which Level 4.2 of the post-processing chain (run_level42_daytime_oneflux) does. That equals ONEFlux only when the scenarios are ONEFlux’s percentile set in its order ('1.25','3.75', … inPERC_TO_COMPARE).ONEFlux’s own output depends on the NumPy version it runs under. NumPy 2 changed scalar type promotion (NEP 50), and that moves ONEFlux in two places: the SD in its uncertainty look-up rounds differently in a fifth of the records, and its alpha check starts to reject windows (see
reject_alpha_at_start). On CH-DAV 2016, ONEFlux under NumPy 2 fits 7 fewer windows and its annual GPP rises by 5.8%. With the alpha check held at its NumPy-1 result, 17 windows still change, most of them windows wherekconverges to zero and the model cascade branches on its sign. diive reproduces ONEFlux under NumPy 1.Example:
examples/flux/partitioning/partitioning_daytime_oneflux.pyExample
>>> import diive as dv >>> df = dv.load_exampledata_parquet() >>> part = dv.flux.DaytimePartitioningOneFlux( ... nee=df['NEE_CUT_REF_orig'], ta=df['Tair_orig'], sw_in=df['Rg_orig'], ... ta_f=df['Tair_f'], sw_in_f=df['Rg_f'], vpd=df['VPD_f'], ... vpd_in_kpa=False) # VPD_f is in hPa in the example data >>> part.run() # then part.results -> DataFrame with RECO_DT_OF, GPP_DT_OF, ...
- Parameters:
- __init__(nee, ta, sw_in, ta_f, sw_in_f, vpd, vpd_in_kpa=True, reject_alpha_at_start=False, nee_f=None, verbose=2)[source]¶
- Parameters:
nee (
Series) – Measured net ecosystem exchange (umol m-2 s-1). Gaps (NaN) are the records that were not measured / did not pass QC; the daytime LRC is fitted on the measured daytime values only.ta (
Series) – Measured air temperature (degC), gaps as NaN. Used for the day/night classification and the internal NEE-uncertainty look-up.sw_in (
Series) – Measured incoming shortwave radiation (W m-2), gaps as NaN. Used for theRg-threshold day/night split and the uncertainty look-up.ta_f (
Series) – Gap-filled air temperature (degC) - used in the fits and to compute RECO at every record.sw_in_f (
Series) – Gap-filled incoming shortwave radiation (W m-2) - the LRC light driver, used in the fits and the flux prediction.vpd (
Series) – Gap-filled vapour pressure deficit. By default in kPa (diive convention) and converted internally to hPa, the unit ONEFlux’s Lasslop LRC expects (VPD0 = 10 hPa). Passvpd_in_kpa=Falseifvpdis already in hPa.vpd_in_kpa (
bool) – If True (default),vpdis in kPa and multiplied by 10 to hPa internally.reject_alpha_at_start (
bool) – ONEFlux’s window check is meant to reject a window whose alpha never moved off its starting value of 0.01, but in ONEFlux 1.3.7 the check compares a float32 against a float64 and never fires. False (default) reproduces ONEFlux, so the results match its output. True applies the check as ONEFlux’s own comment intends. On CH-DAV 2016 that rejects 7 more windows and raises annual GPP by 5.7%, in ONEFlux and here alike. ONEFlux run under NumPy 2 behaves like True, because there the comparison happens in float32.nee_f (
Series|None) – Gap-filled NEE (umol m-2 s-1), optional. ONEFlux uses it in one place only: a window without any measured nighttime record takes the gap-filled NEE of the year’s first record as its Rref starting guess (ONEFlux’s selection falls back to that record when it would be empty) and is fitted. Withnee_fdiive does the same. Without it such windows are not fitted and a warning lists them. This happens at high latitudes in summer (FI-Hyy, FI-Var) and in long gaps of nighttime NEE.verbose (
int) – Console verbosity level (0 silent, 1 warnings, 2 progress + report, 3 debug). Default 2.
- run()[source]¶
Run the partitioning and populate
resultsandremoved_days.- Return type:
- property removed_days: dict[int, list[tuple[int, int]]]¶
Day ranges whose measured NEE was removed after a failed fit.
{year: [(begin, end), ...]}for every partitioned year, in the order the ranges were found (empty list when no fit failed). Each range covers the days of yearbegin < day <= end, the night range of the window whose fit failed, as in ONEFlux’s error file. Afterpartition_nee_daytime_oneflux_scenarios(), all scenarios carry the same ranges.
- property results: DataFrame¶
DataFrame of partitioning results (aligned to the input index).
Columns:
RECO_DT_OF(ecosystem respiration),GPP_DT_OF(gross primary production),SE_GPP_DT_OF(GPP standard error), and the fitted LRC parametersALPHA_DT_OF,BETA_DT_OF,K_DT_OF,RREF_DT_OF,E0_DT_OFreported at the central record of each window (NaN elsewhere).
- diive.flux.partition_nee_daytime_oneflux(nee, ta, sw_in, ta_f, sw_in_f, vpd, vpd_in_kpa=True, reject_alpha_at_start=False, nee_f=None, verbose=2)[source]¶
Functional wrapper around
DaytimePartitioningOneFlux.See
DaytimePartitioningOneFluxfor argument semantics.
- diive.flux.partition_nee_daytime_oneflux_scenarios(nee, ta, sw_in, ta_f, sw_in_f, vpd, vpd_in_kpa=True, reject_alpha_at_start=False, nee_f=None, verbose=2)[source]¶
Partition several NEE series (u* scenarios) that share drivers and removed days.
Runs
DaytimePartitioningOneFluxon each series, but with the removed days shared, as ONEFlux’s pipeline shares its error file between the u* percentiles of a year and product. Per year, the series are partitioned in the order ofnee. When a fit fails, the night range of its window is removed from the measured NEE of every series and the same series is partitioned again. After a pass in which a fit failed, the series whose result predates the last removed range are partitioned again, in order, until a pass runs through without a failed fit. When no fit fails, each series is partitioned once, as with the class.With one series the result equals the class. The result equals ONEFlux only when the series are ONEFlux’s u* percentiles in its order (
'1.25','3.75', … inPERC_TO_COMPARE) and of one product (CUT or VUT): the order decides which fits fail.- Parameters:
nee (
dict[str,Series]) –{label: measured NEE}, one Series per scenario, all with the same index. The order is the partitioning order.ta (
Series) – As inDaytimePartitioningOneFlux, shared by all series.sw_in (
Series) – As inDaytimePartitioningOneFlux, shared by all series.ta_f (
Series) – As inDaytimePartitioningOneFlux, shared by all series.sw_in_f (
Series) – As inDaytimePartitioningOneFlux, shared by all series.vpd (
Series) – As inDaytimePartitioningOneFlux, shared by all series.vpd_in_kpa (
bool) – As inDaytimePartitioningOneFlux, shared by all series.reject_alpha_at_start (
bool) – As inDaytimePartitioningOneFlux, shared by all series.verbose (
int) – As inDaytimePartitioningOneFlux, shared by all series.nee_f (
dict[str,Series] |None) –{label: gap-filled NEE}, optional, the gap-filled NEE of each scenario (seeDaytimePartitioningOneFlux). A label missing from it partitions without gap-filled NEE.
- Returns:
resultsandremoved_daysare populated, andremoved_daysis the same for every series.- Return type:
- class diive.flux.PartitioningNEE(nee, *, method, mode='oneflux', ta=None, sw_in=None, ta_f=None, sw_in_f=None, nee_f=None, vpd=None, lat=None, lon=None, utc_offset=None, vpd_in_kpa=True, verbose=2, **backend_kwargs)[source]¶
Bases:
objectPartition NEE into GPP and RECO, with the method and mode as switches.
One entry point for the four partitioning ports.
methodpicks the algorithm:'nighttime'(Reichstein et al. 2005, temperature response of nighttime NEE) or'daytime'(Lasslop et al. 2010, light-response curve of daytime NEE).modepicks the reference implementation:'oneflux'(default, the ICOS and FLUXNET2015 approach) or'reddyproc'. The work is done by the matching class, which is available asbackend. Its columns carry its suffix:nighttime / oneflux:
NighttimePartitioningOneFlux,*_NT_OFnighttime / reddyproc:
NighttimePartitioningReddyProc,*_NT_RPdaytime / oneflux:
DaytimePartitioningOneFlux,*_DT_OFdaytime / reddyproc:
DaytimePartitioningReddyProc,*_DT_RP
The results are those of the backend, unchanged. Their column names keep the backend suffix, so results of different modes can sit side by side in one DataFrame.
recoandgppreturn RECO and GPP for any method and mode.Inputs each method/mode needs (besides
nee):nighttime / oneflux:
ta,sw_in,nee_f,ta_f,latnighttime / reddyproc:
ta,sw_in,nee_f,ta_f,lat,lon,utc_offsetdaytime / oneflux:
ta,sw_in,ta_f,sw_in_f,vpddaytime / reddyproc:
ta_f,sw_in_f,vpd,lat,lon,utc_offset
Daytime / oneflux also takes
nee_fwhen given: ONEFlux reads the gap-filled NEE for windows without measured nighttime NEE (seeDaytimePartitioningOneFlux). Without it those windows are not fitted and a warning lists them.partitioning_optional_inputs()lists such inputs.Inputs the chosen method/mode does not use are ignored, so the same call can switch between modes. A missing input raises a
ValueErrorthat names it.Example
>>> import diive as dv >>> df = dv.load_exampledata_parquet() >>> part = dv.flux.PartitioningNEE( ... nee=df['NEE_CUT_REF_orig'], method='daytime', mode='oneflux', ... ta=df['Tair_orig'], sw_in=df['Rg_orig'], ta_f=df['Tair_f'], ... sw_in_f=df['Rg_f'], vpd=df['VPD_f'], vpd_in_kpa=False).run() # VPD_f in hPa >>> part.gpp # GPP_DT_OF, and part.results holds all backend columns
- Parameters:
- __init__(nee, *, method, mode='oneflux', ta=None, sw_in=None, ta_f=None, sw_in_f=None, nee_f=None, vpd=None, lat=None, lon=None, utc_offset=None, vpd_in_kpa=True, verbose=2, **backend_kwargs)[source]¶
- Parameters:
nee (
Series) – Measured NEE (umol m-2 s-1), gaps as NaN.method (
str) –'nighttime'(Reichstein et al. 2005) or'daytime'(Lasslop et al. 2010).mode (
str) –'oneflux'(default) or'reddyproc'.ta (
Series|None) – Measured air temperature (degC), gaps as NaN.sw_in (
Series|None) – Measured incoming shortwave radiation (W m-2), gaps as NaN.sw_in_f (
Series|None) – Gap-filled incoming shortwave radiation (W m-2).nee_f (
Series|None) – Gap-filled NEE (umol m-2 s-1), for the GPP residual of the nighttime method. Optional for daytime / oneflux, which reads it for windows without measured nighttime NEE, as ONEFlux does.vpd (
Series|None) – Gap-filled vapour pressure deficit, for the daytime method. In kPa by default, seevpd_in_kpa.utc_offset (
float|None) – Time zone offset of the timestamps from UTC in hours.vpd_in_kpa (
bool) – If True (default),vpdis in kPa. Set False if it is in hPa. Used by the daytime method only.verbose (
int) – Console verbosity level (0 silent, 1 warnings, 2 progress + report, 3 debug). Default 2.**backend_kwargs – Options only one backend has, passed on to it:
reject_alpha_at_start(daytime / oneflux, seeDaytimePartitioningOneFlux) andnee_sd(daytime / reddyproc, seeDaytimePartitioningReddyProc). Any other keyword raises aTypeError.
- diive.flux.partition_nee(nee, *, method, mode='oneflux', ta=None, sw_in=None, ta_f=None, sw_in_f=None, nee_f=None, vpd=None, lat=None, lon=None, utc_offset=None, vpd_in_kpa=True, verbose=2, **backend_kwargs)[source]¶
Functional wrapper around
PartitioningNEE.See
PartitioningNEEfor argument semantics.- Return type:
- Returns:
The backend results DataFrame (e.g. RECO_NT_OF, GPP_NT_OF, …).
- Parameters:
- class diive.flux.FluxConfig(fluxcol, ustar_detection_mode='constant', ustar_thresholds=None, ustar_labels=None, ustar_bootstrap_ta_col=None, ustar_bootstrap_swin_col=None, ustar_bootstrap_n_iter=100, ustar_bootstrap_n_jobs=1, ustar_bootstrap_percentiles=(16, 50, 84), level2_test_settings=None, signal_strength_col=None, outlier_sigma_daytime=None, outlier_sigma_nighttime=None, gapfilling_features=None, set_storage_to_zero=False, gapfill_storage_term=True, outlier_window_length=None, gapfill_rf=True, gapfill_xgb=False, gapfill_mds=True, gapfill_reduce_features=True, mds_swin=None, mds_ta=None, mds_vpd=None, mds_mode='diive', mds_swin_qc=None, mds_ta_qc=None, mds_vpd_qc=None, partition_nighttime_oneflux=False, partition_nighttime_reddyproc=False, partition_daytime_reddyproc=False, partition_daytime_oneflux=False, partition_method=None, partition_mode='oneflux', partition_gapfill_method='mds', partition_ta=None, partition_sw_in=None, partition_ta_f=None, partition_sw_in_f=None, partition_vpd_f=None, partition_nee_sd=None, partition_vpd_in_kpa=True)[source]¶
Bases:
objectPer-flux configuration for multi-flux processing loops.
Captures every setting that differs between fluxes (CO2, H, LE, N2O, CH4, …) so that a composable-function loop can process each variable without repeating site-level parameters.
Consumed by
run_chain(). The per-levelrun_level*functions take their own specific arguments — they do not accept aFluxConfig. Userun_chain(data, config)for the standard pipeline, or drop down to the composable per-level API for custom L3.2 outlier logic or custom feature engineering.Scope.
FluxConfigcaptures the high-level decisions a typical user makes per flux — which L2 tests, which USTAR-detection mode, which gap-filling methods, which MDS / ML driver columns. It does not cover every knob each level exposes: Hampel sub-options (use_differencing,repeat,k), non-Hampel L3.2 detectors, MDS tolerances, ML hyperparameters, customFeatureEngineerconfigurations, and L3.3 diagnostic plotting are all reachable only via the composable per-level API. Seerun_chain()for the full list of what is and is not exposed. The composable per-level callables are the path to full control.Only
fluxcolis always required.run_chainchecks the other fields only for the features they serve:ustar_thresholdsin the defaultustar_detection_mode='constant',gapfilling_featureswhengapfill_rforgapfill_xgbisTrue,mds_swin/mds_ta/mds_vpdwhengapfill_mds=True, and thepartition_*driver columns for each enabled partitioning variant. Theoutlier_*fields are optional overrides of the Hampel defaults (L3.2 always runs). So each flux declaration needs only the fields for the features it enables.Example — NEE, H, and N2O configs:
from diive.flux.postprocessingchain import FluxConfig fc_cfg = FluxConfig( fluxcol='FC', ustar_thresholds=[0.30], ustar_labels=['CUT_50'], outlier_sigma_daytime=5.5, outlier_sigma_nighttime=5.5, gapfilling_features=['TA_1_1_1', 'SW_IN_1_1_1', 'VPD_1_1_1'], level2_test_settings={ 'ssitc': {'apply': True, 'setflag_timeperiod': None}, 'gas_completeness': {'apply': True}, 'spectral_correction_factor': {'apply': True}, }, mds_swin='SW_IN_1_1_1', mds_ta='TA_1_1_1', mds_vpd='VPD_kPa_1_1_1', ) h_cfg = FluxConfig( fluxcol='H', ustar_thresholds=[0.0], # energy flux — no USTAR filtering ustar_labels=['CUT_NONE'], outlier_sigma_daytime=5.5, outlier_sigma_nighttime=5.5, gapfilling_features=['TA_1_1_1', 'SW_IN_1_1_1'], level2_test_settings={ 'ssitc': {'apply': True, 'setflag_timeperiod': None}, }, mds_swin='SW_IN_1_1_1', mds_ta='TA_1_1_1', mds_vpd='VPD_kPa_1_1_1', ) n2o_cfg = FluxConfig( fluxcol='N2O', ustar_thresholds=[0.30], ustar_labels=['CUT_50'], outlier_sigma_daytime=4.0, # chosen by inspecting the N2O record outlier_sigma_nighttime=3.5, # trace gases typically need lower sigma gapfilling_features=['TA_1_1_1', 'SW_IN_1_1_1'], level2_test_settings={ 'ssitc': {'apply': True, 'setflag_timeperiod': None}, 'gas_completeness': {'apply': True}, }, gapfill_mds=False, # MDS not appropriate for N2O without dedicated drivers )
Example — detect USTAR thresholds via bootstrap (FLUXNET standard):
nee_boot_cfg = FluxConfig( fluxcol='FC', ustar_detection_mode='bootstrap', ustar_bootstrap_ta_col='TA_1_1_1', ustar_bootstrap_swin_col='SW_IN_1_1_1', ustar_bootstrap_percentiles=(16, 50, 84), # produces CUT_16/50/84 outlier_sigma_daytime=5.5, outlier_sigma_nighttime=5.5, gapfilling_features=['TA_1_1_1', 'SW_IN_1_1_1', 'VPD_1_1_1'], level2_test_settings={'ssitc': {'apply': True, 'setflag_timeperiod': None}}, mds_swin='SW_IN_1_1_1', mds_ta='TA_1_1_1', mds_vpd='VPD_kPa_1_1_1', ) # The fitted bootstrap instance is available on data.levels.ustar_detection # after run_chain() for inspection of annual/per-year statistics.
- Parameters:
fluxcol (str)
ustar_detection_mode (str)
ustar_thresholds (list | None)
ustar_labels (list | None)
ustar_bootstrap_ta_col (str | None)
ustar_bootstrap_swin_col (str | None)
ustar_bootstrap_n_iter (int)
ustar_bootstrap_n_jobs (int)
ustar_bootstrap_percentiles (tuple)
level2_test_settings (dict | None)
signal_strength_col (str | None)
outlier_sigma_daytime (float | None)
outlier_sigma_nighttime (float | None)
gapfilling_features (list | None)
set_storage_to_zero (bool)
gapfill_storage_term (bool)
outlier_window_length (int | None)
gapfill_rf (bool)
gapfill_xgb (bool)
gapfill_mds (bool)
gapfill_reduce_features (bool)
mds_swin (str | None)
mds_ta (str | None)
mds_vpd (str | None)
mds_mode (str)
mds_swin_qc (str | None)
mds_ta_qc (str | None)
mds_vpd_qc (str | None)
partition_nighttime_oneflux (bool)
partition_nighttime_reddyproc (bool)
partition_daytime_reddyproc (bool)
partition_daytime_oneflux (bool)
partition_method (str | None)
partition_mode (str)
partition_gapfill_method (str)
partition_ta (str | None)
partition_sw_in (str | None)
partition_ta_f (str | None)
partition_sw_in_f (str | None)
partition_vpd_f (str | None)
partition_nee_sd (str | None)
partition_vpd_in_kpa (bool)
- ustar_detection_mode: str = 'constant'¶
How USTAR thresholds are obtained for Level-3.3.
'constant'(default) — use the values you provide inustar_thresholdsdirectly (e.g. previously computed by REddyProc). Fastest; no per-call computation. Required field:ustar_thresholds.'bootstrap'— detect thresholds from the data itself via multi-year bootstrap (ONEFlux moving-point method by default, Papale et al. 2006). Slower but fully reproducible within the pipeline. Required fields:ustar_bootstrap_ta_colandustar_bootstrap_swin_col.ustar_thresholds/ustar_labelsare ignored in this mode — thresholds andCUT_<p>labels are produced fromustar_bootstrap_percentiles.
- ustar_thresholds: list | None = None¶
USTAR threshold(s) in m s-1 — one per scenario. Required when
ustar_detection_mode='constant'. Use[0.0]for energy fluxes (H, LE) to keep all records.
- ustar_labels: list | None = None¶
Short label per threshold (e.g.
['CUT_50'];['CUT_NONE']for H/LE).With a single threshold,
Noneis allowed:run_chainlets the underlying function auto-generate the label as['CUT_0'].With multiple thresholds,
run_chainrequires explicit labels to avoid silently emitting non-percentile names (CUT_0,CUT_1, …) for what are typically percentile-based thresholds. Pass e.g.['CUT_16', 'CUT_50', 'CUT_84']to match the percentile semantics used everywhere else in the chain.
Ignored when
ustar_detection_mode='bootstrap'— labels are derived fromustar_bootstrap_percentiles(e.g.CUT_16/CUT_50/CUT_84).
- ustar_bootstrap_ta_col: str | None = None¶
Air temperature column (deg C) in
data.full_dfused by the bootstrap detector to stratify nighttime records into temperature classes. Required whenustar_detection_mode='bootstrap'; ignored otherwise.
- ustar_bootstrap_swin_col: str | None = None¶
Shortwave incoming radiation column (W m-2) in
data.full_dfused by the bootstrap detector to identify nighttime periods. Required whenustar_detection_mode='bootstrap'; ignored otherwise.
- ustar_bootstrap_n_iter: int = 100¶
Bootstrap iterations per year window. Larger values give tighter percentile estimates at proportional runtime cost. Used only when
ustar_detection_mode='bootstrap'.
- ustar_bootstrap_n_jobs: int = 1¶
Parallel workers for the bootstrap (1 = sequential, -1 = all CPUs). Used only when
ustar_detection_mode='bootstrap'.
- ustar_bootstrap_percentiles: tuple = (16, 50, 84)¶
Bootstrap percentiles to compute and use as separate USTAR scenarios. Each value
pproduces one scenario labelledCUT_<p>. Used only whenustar_detection_mode='bootstrap'.
- level2_test_settings: dict | None = None¶
Which Level-2 quality tests to run, and the settings for each.
Shape is a dict-of-dicts: each top-level key is a test name, each value is that test’s settings dict (always including
'apply': Trueto enable it). Example:level2_test_settings = { 'ssitc': {'apply': True, 'setflag_timeperiod': None}, 'gas_completeness': {'apply': True}, 'spectral_correction_factor': {'apply': True}, }
Recognised top-level keys (each name selects a Level-2 test; omit a key to skip that test):
ssitc,gas_completeness,spectral_correction_factor,signal_strength,raw_data_screening_vm97,angle_of_attack,steadiness_of_horizontal_wind. Seerun_level2()for the settings each test accepts.None(the default) runs the four universal tests baked intoDEFAULT_LEVEL2_TEST_SETTINGS:ssitc,gas_completeness,spectral_correction_factor, andraw_data_screening_vm97(with spikes + dropout enabled). Pass an explicit dict to take full control; pass{}to disable every test except the always-on missing-values one (a warning fires in that case).Use the separate
signal_strength_colfield to opt into the analyzer-specific signal-strength test on top of the defaults — that test is not included unconditionally because it depends on a column name and threshold direction the chain can’t infer.
- signal_strength_col: str | None = None¶
Column name of the IRGA signal-strength / AGC diagnostic (e.g.
'CUSTOM_SIGNAL_STRENGTH_IRGA72_MEAN'). When set,run_chainadds the Level-2signal_strengthtest on top oflevel2_test_settings(or on top of the defaults iflevel2_test_settingsisNone) withmethod='discard below'andthreshold=60— sensible for the LI-7200 / LI-7500 family where low AGC signals optical contamination. For a different method/threshold (e.g.'discard above'for some analyzer firmwares), supply the fullsignal_strengthentry insidelevel2_test_settingsand leave this fieldNone. Ignored whenlevel2_test_settingsalready contains a'signal_strength'key (the user’s explicit config wins; a warning is emitted to surface the conflict).
- outlier_sigma_daytime: float | None = None¶
Hampel filter sigma override for daytime outlier detection.
None(the default) defers toHampel’s ownn_sigmadefault (currently 5.5). Override only when you have inspected the flux record and have a reason to pick a different threshold — typical bands are 5–6 for CO2/H/LE and 3–5 for trace gases (N2O, CH4). L3.2 always runs inrun_chainbecause L3.3 USTAR filtering depends on outlier-screened data; the override knob does not let you skip L3.2.
- outlier_sigma_nighttime: float | None = None¶
Hampel filter sigma override for nighttime outlier detection.
None(the default) defers toHampel’s ownn_sigmadefault (currently 5.5). Override only when you have a deliberate reason to choose a different nighttime threshold; seeoutlier_sigma_daytimefor typical ranges.
- gapfilling_features: list | None = None¶
Predictor column names for ML gap-filling (RF, XGBoost). Must exist in
data.full_df. Required whengapfill_rf=Trueorgapfill_xgb=True; ignored otherwise.
- set_storage_to_zero: bool = False¶
Set to
Truewhen no storage measurement is available for this flux. The storage correction (L3.1) still runs; it just adds zero.
- gapfill_storage_term: bool = True¶
Whether L3.1 should gap-fill missing storage values with a rolling median before adding the storage term to the flux. Default
Truematchesrun_level31’s own default. Set toFalseto add only the raw (non-gap-filled) storage term — any nighttime record with missing storage then becomes NaN. Ignored whenset_storage_to_zero=True.
- outlier_window_length: int | None = None¶
Hampel filter rolling window length override, expressed as a record count (not a duration).
None(the default) defers toHampel’s ownwindow_lengthdefault,48 * 13 = 624records — that’s 13 days of half-hourly data, matching Papale et al. 2006. Override only when you have a reason to widen or narrow the local-window MAD computation.For non-half-hourly inputs (the chain is designed for 30-min EddyPro output), scale this value yourself — e.g. for hourly data use
24 * 13to preserve a 13-day window. The value is forwarded verbatim toStepwiseOutlierDetection.flag_outliers_hampel_test()and is always interpreted in records, never in time units.
- gapfill_reduce_features: bool = True¶
SHAP-based feature reduction for the ML gap-fillers (RF / XGBoost). Default
True— the chain’s L4.1 ML methods are designed around SHAP importance ranking; with reduction disabled the model trains on every engineered feature regardless of contribution and is typically weaker. Set toFalseonly when you want the raw (unreduced) feature set, e.g. for diagnostic comparison. Ignored when bothgapfill_rfandgapfill_xgbareFalse.
- mds_swin: str | None = None¶
Shortwave incoming radiation column for MDS (W m-2; must be in
data.full_df).
- mds_mode: str = 'diive'¶
'diive'(default, Vekuri et al. 2023 symmetric mean in daytime),'oneflux'(bit for bit as ONEFlux) or'reddyproc'(as REddyProc). Seediive.gapfilling.mds.FluxMDS.- Type:
MDS mode
- mds_swin_qc: str | None = None¶
Optional QC flag column of
mds_swin(0 = measured, above 0 = gap-filled, e.g.FLAG_..._ISFILLEDor FLUXNETSW_IN_F_QC; must be indata.full_df). Only records with flag 0 serve as similar samples, as in ONEFlux’s NEE gap-filling. DefaultNone: no QC.
- partition_nighttime_oneflux: bool = False¶
Run nighttime partitioning, ONEFlux port (Reichstein 2005) — emits
*_NT_OFcolumns. Needspartition_ta/partition_sw_in(measured) andpartition_ta_f(gap-filled), plus a gap-filled NEE from L4.1 (partition_gapfill_method).
- partition_nighttime_reddyproc: bool = False¶
Run nighttime partitioning, REddyProc port (Reichstein 2005) — emits
*_NT_RPcolumns. Same inputs as the ONEFlux nighttime variant; uses the sitelat/lon/utc_offsetfrominit_flux_data.
- partition_daytime_reddyproc: bool = False¶
Run daytime partitioning, REddyProc port (Lasslop 2010) — emits
*_DT_RPcolumns. Needs gap-filled meteo only:partition_ta_f/partition_vpd_f/partition_sw_in_f(and the optionalpartition_nee_sd). Measured NEE per USTAR scenario comes from L3.3 — no L4.1 gap-filled NEE needed.
- partition_daytime_oneflux: bool = False¶
Run daytime partitioning, ONEFlux port (Lasslop 2010) — emits
*_DT_OFcolumns. Needspartition_ta/partition_sw_in(measured) andpartition_ta_f/partition_sw_in_f/partition_vpd_f(gap-filled). Measured NEE per USTAR scenario comes from L3.3. If L4.1 ranpartition_gapfill_method, its gap-filled NEE is passed on: ONEFlux reads it for windows without measured nighttime NEE.
- partition_method: str | None = None¶
Select one partitioning variant with two switches instead of a flag:
'nighttime'or'daytime', combined withpartition_mode. It turns on the matchingpartition_*flag and needs the same driver columns.None(default): only the flags decide. Flags that are also set still run, so the variants add up, and a variant selected both ways runs once.
- partition_mode: str = 'oneflux'¶
'oneflux'(default, the ICOS and FLUXNET2015 approach) or'reddyproc'. Ignored whilepartition_methodisNone.- Type:
Reference implementation for
partition_method
- partition_gapfill_method: str = 'mds'¶
Which L4.1 gap-filled NEE feeds the nighttime partitioning variants (they need a gap-filled NEE for the GPP residual):
'mds'(default, FLUXNET standard),'rf', or'xgb'. The chosen method must have run at L4.1. Daytime ONEFlux uses it too where that method ran (for windows without measured nighttime NEE), daytime REddyProc ignores it.
- partition_ta: str | None = None¶
Measured air temperature column (deg C) for partitioning, in
data.full_df. Required by the nighttime variants and daytime ONEFlux.
- partition_sw_in: str | None = None¶
Measured shortwave incoming radiation column (W m-2) for partitioning, in
data.full_df. Required by the nighttime variants and daytime ONEFlux.
- partition_ta_f: str | None = None¶
Gap-filled air temperature column (deg C) for partitioning, in
data.full_df. Required by every partitioning variant.
- partition_sw_in_f: str | None = None¶
Gap-filled shortwave incoming radiation column (W m-2) for partitioning, in
data.full_df. Required by the daytime variants.
- partition_vpd_f: str | None = None¶
Gap-filled VPD column for partitioning, in
data.full_df. kPa by default (partition_vpd_in_kpa=True). Required by the daytime variants.
- partition_nee_sd: str | None = None¶
Optional per-record NEE uncertainty column (umol m-2 s-1) in
data.full_df, used to weight the daytime REddyProc LRC fit.Nonereproduces REddyProc’s defaultmax(0.7, 0.2*|NEE|).
- partition_vpd_in_kpa: bool = True¶
Whether
partition_vpd_fis in kPa (default). The daytime LRC ports expect hPa and convert internally; setFalseif the column is already hPa.
- __init__(fluxcol, ustar_detection_mode='constant', ustar_thresholds=None, ustar_labels=None, ustar_bootstrap_ta_col=None, ustar_bootstrap_swin_col=None, ustar_bootstrap_n_iter=100, ustar_bootstrap_n_jobs=1, ustar_bootstrap_percentiles=(16, 50, 84), level2_test_settings=None, signal_strength_col=None, outlier_sigma_daytime=None, outlier_sigma_nighttime=None, gapfilling_features=None, set_storage_to_zero=False, gapfill_storage_term=True, outlier_window_length=None, gapfill_rf=True, gapfill_xgb=False, gapfill_mds=True, gapfill_reduce_features=True, mds_swin=None, mds_ta=None, mds_vpd=None, mds_mode='diive', mds_swin_qc=None, mds_ta_qc=None, mds_vpd_qc=None, partition_nighttime_oneflux=False, partition_nighttime_reddyproc=False, partition_daytime_reddyproc=False, partition_daytime_oneflux=False, partition_method=None, partition_mode='oneflux', partition_gapfill_method='mds', partition_ta=None, partition_sw_in=None, partition_ta_f=None, partition_sw_in_f=None, partition_vpd_f=None, partition_nee_sd=None, partition_vpd_in_kpa=True)¶
- Parameters:
fluxcol (str)
ustar_detection_mode (str)
ustar_thresholds (list | None)
ustar_labels (list | None)
ustar_bootstrap_ta_col (str | None)
ustar_bootstrap_swin_col (str | None)
ustar_bootstrap_n_iter (int)
ustar_bootstrap_n_jobs (int)
ustar_bootstrap_percentiles (tuple)
level2_test_settings (dict | None)
signal_strength_col (str | None)
outlier_sigma_daytime (float | None)
outlier_sigma_nighttime (float | None)
gapfilling_features (list | None)
set_storage_to_zero (bool)
gapfill_storage_term (bool)
outlier_window_length (int | None)
gapfill_rf (bool)
gapfill_xgb (bool)
gapfill_mds (bool)
gapfill_reduce_features (bool)
mds_swin (str | None)
mds_ta (str | None)
mds_vpd (str | None)
mds_mode (str)
mds_swin_qc (str | None)
mds_ta_qc (str | None)
mds_vpd_qc (str | None)
partition_nighttime_oneflux (bool)
partition_nighttime_reddyproc (bool)
partition_daytime_reddyproc (bool)
partition_daytime_oneflux (bool)
partition_method (str | None)
partition_mode (str)
partition_gapfill_method (str)
partition_ta (str | None)
partition_sw_in (str | None)
partition_ta_f (str | None)
partition_sw_in_f (str | None)
partition_vpd_f (str | None)
partition_nee_sd (str | None)
partition_vpd_in_kpa (bool)
- Return type:
None
- class diive.flux.FluxLevelData(fpc_df, full_df, filteredseries, meta, levels=LevelResults(), level_ids=list(), added_columns=dict())[source]¶
Bases:
objectContainer passed between composable level callables.
Each level callable returns a new
FluxLevelData; the input is never mutated.Two DataFrames — which one to use?
fpc_df— the processing dataframe. Starts with just the flux and USTAR columns, then grows as each level appends its flag, QCF, and gap-filled columns. Use this for inspecting chain outputs, exporting results, or plotting quality-controlled fluxes.full_df— the full input dataframe (original EddyPro columns plus potential radiation and day/night flags added byinit_flux_data). Level-2 reads EddyPro diagnostic columns from here. Level-4.1 reads meteorological driver columns (e.g.TA_1_1_1,SW_IN) from here as gap-filling features, and Level-4.2 its partitioning drivers. Do not modify this dataframe. Level callables use it read-only.
Need a new driver mid-pipeline (e.g. a computed VPD column for MDS)? Use
add_driver(data, series, name=...)— it adds the column tofull_dfwhere L4.1 and L4.2 look for it, not tofpc_df.- Parameters:
- __init__(fpc_df, full_df, filteredseries, meta, levels=<factory>, level_ids=<factory>, added_columns=<factory>)¶
- filteredseries: Series | None¶
QCF-filtered flux from the most recently completed level (accepted-quality threshold, not QCF=0-only).
Nonebefore any level has run.
- meta: FluxMeta¶
- levels: LevelResults¶
- level_ids: list[str]¶
Ordered list of level idstrs that have run (
'L2','L3.1','L3.2','L3.3','L4.1','L4.2'). Records the cascade-aware level boundaries only. For L4.1 the single entry'L4.1'is appended whichever subset of MDS / RF / XGBoost ran, so it does not tell you which methods produced output, and the same holds for the L4.2 variants. To find out, usegapfilled_cols()/LevelResults.level41_methods()andpartitioned_cols()/LevelResults.level42_variants(). Cleared by the re-run cascade (seelevels/_rerun.py).
- added_columns: dict[str, list[str]]¶
Columns each level added to
fpc_df, keyed by level idstr ('L2','L3.1','L3.2','L3.3'), per-method L4.1 key ('L4.1_mds','L4.1_rf','L4.1_xgb') or per-variant L4.2 key ('L4.2_nt_of','L4.2_nt_rp','L4.2_dt_rp','L4.2_dt_of'). Used to clean up stale columns when a level is re-run.
- summary()[source]¶
Return a concise data-availability summary across all completed levels.
Shows the number of valid (non-NaN) records per QCF-filtered series, split by daytime and nighttime where available. Useful for quickly assessing how much data each level removes.
- Return type:
- Returns:
Multi-line string ready for
print().
- gap_stats(level='L3.3', long_gap_records=48)[source]¶
Return gap statistics for the QCF-filtered series at the given level.
Creates a
GapStatsinstance for each series available at the requested level. For levels with USTAR scenarios (L3.3) one entry is returned per scenario.- Parameters:
level (
str) – Level whose QCF-filtered series to analyse. Use the dotted idstrs that match the rest of the chain:'L2','L3.1','L3.2','L3.3'. Defaults to'L3.3'— the series that goes into gap-filling.long_gap_records (
int) – Gaps >= this many consecutive records are flagged as long gaps in the report and figure. Default 48 equals one day at 30-min resolution.
- Return type:
- Returns:
{label: GapStats}— a flat mapping whose keys are whichever label uniquely identifies each result at that level:L2 / L3.1 / L3.2: one entry keyed by the level name itself (
{'L2': gs}/{'L3.1': gs}/{'L3.2': gs}).L3.3: one entry per USTAR scenario keyed by the scenario label (
{'CUT_16': gs, 'CUT_50': gs, 'CUT_84': gs}).
The label vocabulary differs by level on purpose: at L2/L3.1/L3.2 there is only one filtered series so the level name is the natural key, whereas at L3.3 the scenario label is the distinguishing axis. A generic loop
for label, gs in data.gap_stats(level).items(): ...therefore works at every level — thelabelyou get back is the right caption to render alongside eachGapStats.- Raises:
ValueError – If the requested level has not been run yet, or if an unknown level idstr is passed.
Example:
# Analyse gaps just before gap-filling for scen, gs in data.gap_stats('L3.3').items(): print(scen) gs.report() gs.showfig(title=f"Gap stats -- {scen}") # Single-level access gs = data.gap_stats('L2')['L2'] gs.report()
- plot_cumulative_comparison(ustar_scenario=None, conv_factor=1.0, units='', show_measured=True, title=None, saveplot=False, path=None, showplot=True, ax=None, fig=None)[source]¶
Overlay cumulative sums of all gap-filled methods for direct comparison.
Plots one line per gap-filling method (RF, XGBoost, MDS — whichever have been run) for the requested USTAR scenario on the same axes. Optionally adds a dashed reference line for the measured-only series (gaps contribute zero, leaving flat segments) so the impact of gap-filling is visible.
Call this after at least one
run_level41_*function has completed.- Parameters:
ustar_scenario (
str|None) – USTAR scenario label to compare across methods (e.g.'CUT_50'). Defaults to the first available scenario.conv_factor (
float) – Multiply every flux value by this factor before accumulating. For 30-min NEE in µmol CO₂ m⁻² s⁻¹ → gC m⁻², use12.011 * 1e-6 * 1800. Default 1.0 (no conversion).units (
str) – Unit string shown in the y-axis label and legend, e.g.'gC m-2'.show_measured (
bool) – Add a dashed grey reference line for the L3.3 QCF-filtered series before gap-filling (gaps counted as zero). Defaults toTrue.title (
str|None) – Figure title. Defaults to an auto-generated title.saveplot (
bool) – Save the figure to disk. Defaults toFalse.showplot (
bool) – Callplt.show()after rendering. Set toFalsefor headless / batch use or when embedding the figure into a larger composite. Defaults toTrue.ax – Existing matplotlib
Axesto draw into (two-phase pattern, for embedding in a GUI canvas). A new figure is created whenNone. When supplied,tight_layout/plt.showare skipped — the host owns the figure layout.fig – Figure that owns
ax(only used together withaxforsaveplot). Defaults toax.figure.
- Raises:
RuntimeError – If no L4.1 method has been run yet.
ValueError – If the requested USTAR scenario is not found.
- Return type:
Example:
UMOL_TO_GC = 12.011 * 1e-6 * 1800 data.plot_cumulative_comparison( ustar_scenario='CUT_50', conv_factor=UMOL_TO_GC, units='gC m-2', )
- plot_gapfilled_heatmaps(ustar_scenario=None, vmin=None, vmax=None, cmap='RdYlBu_r', units='', title=None, saveplot=False, path=None, showplot=True, fig=None)[source]¶
Multi-panel heatmap: measured flux + one panel per gap-filling method.
Shows the L3.3 QCF-filtered (pre-gap-filling) series in the top panel, followed by one heatmap per gap-filling method that has been run (RF, XGBoost, MDS). All panels share the same colour scale so differences between methods are visually comparable.
Call this after at least one
run_level41_*function has completed.- Parameters:
ustar_scenario (
str|None) – USTAR scenario label (e.g.'CUT_50'). Defaults to the first available scenario.vmin (
float|None) – Minimum colour value. Auto-computed (2nd percentile of all series) whenNone.vmax (
float|None) – Maximum colour value. Auto-computed (98th percentile) whenNone.cmap (
str) – Matplotlib colourmap. Defaults to'RdYlBu_r'.units (
str) – Unit string shown on each colourbar (e.g.'umol m-2 s-1').title (
str|None) – Figure suptitle. Auto-generated whenNone.saveplot (
bool) – Save the figure to disk. Defaults toFalse.showplot (
bool) – Callplt.show()after rendering. Set toFalsefor headless / batch use or when embedding the figure into a larger composite. Defaults toTrue.fig – Existing matplotlib
Figureto render into (two-phase pattern, for embedding in a GUI canvas — mirrorsRidgeLinePlot.plot(fig=...)). The whole figure is used for the side-by-side gridspec, so exactly one USTAR scenario may resolve; passustar_scenariowhen several exist. The figure is cleared before drawing;plt.showis skipped.
- Raises:
RuntimeError – If no L4.1 method has been run yet.
ValueError – If the requested USTAR scenario is not found, or if
figis supplied while more than one scenario resolves.
- Return type:
Example:
data.plot_gapfilled_heatmaps( ustar_scenario='CUT_50', units='umol m-2 s-1', )
- gapfilled_cols()[source]¶
Return the gap-filled output column names per L4.1 method and USTAR scenario.
Saves the user from digging into the level instances to find which column in
fpc_dfholds the gap-filled flux.- Return type:
- Returns:
Nested dict
{method: {ustar_scenario: column_name}}. Keys present only when that method has been run.
Example:
cols = data.gapfilled_cols() # {'mds': {'CUT_50': 'NEE_L3.1_L3.3_CUT_50_QCF_gfMDS'}, # 'rf': {'CUT_50': 'NEE_L3.1_L3.3_CUT_50_QCF_gfRF'}, # 'xgb': {'CUT_50': 'NEE_L3.1_L3.3_CUT_50_QCF_gfXG'}} # The 'L3.1' tag is the storage-correction provenance (kept through # every later level); 'L3.3_CUT_50' is the USTAR scenario. gapfilled = data.fpc_df[cols['rf']['CUT_50']]
- nongapfilled_cols()[source]¶
Return the measured target column each L4.1 method gap-filled.
The symmetric twin of
gapfilled_cols(): same keys, but the column holding the flux before gap-filling. Several methods usually share one target — they all fill the same QCF-filtered series.- Return type:
- Returns:
Nested dict
{method: {ustar_scenario: column_name}}. Keys present only when that method has been run.
Example:
data.nongapfilled_cols() # {'rf': {'CUT_50': 'NEE_L3.1_L3.3_CUT_50_QCF'}}
- merged_df(verbose=None)[source]¶
Return the full input data with every column the chain produced.
Combines
full_df(the untouched input) with the columnsfpc_dfadded along the way — flags, QCF, gap-filled series, partitioning output. Nothing in the input is overwritten; the chain only adds columns. This is the export path: one dataframe holding input and results together.- Parameters:
verbose (
int|bool|None) – Verbosity for the console listing of added columns.- Return type:
- Returns:
DataFrame with
full_df’s columns first, then the new ones.
Example:
df = data.merged_df() dv.save_parquet(data=df, filename='chain_results', outpath='.')
- partitioned_cols()[source]¶
Return the L4.2 partitioning output columns per variant and USTAR scenario.
Each partitioning variant emits a fixed set of result columns (
RECO_NT_OF,GPP_NT_OF, …); to coexist across USTAR scenarios every column is merged intofpc_dfwith the scenario label appended (RECO_NT_OF_CUT_50). This helper saves the user from reconstructing those names by hand.- Return type:
- Returns:
Nested dict
{variant: {ustar_scenario: [column_name, ...]}}. Variant keys are'nt_of'/'nt_rp'/'dt_rp'/'dt_of'and present only when that variant has been run.
Example:
cols = data.partitioned_cols() # {'nt_of': {'CUT_50': ['NEE_NIGHT_OF_CUT_50', 'RECO_NT_OF_CUT_50', # 'GPP_NT_OF_CUT_50', ...]}} reco = data.fpc_df[cols['nt_of']['CUT_50'][1]]
- diive.flux.add_driver(data, series, name=None)[source]¶
Add a Series as a driver column to
data.full_df.L4.1 gap-filling and L4.2 partitioning read their driver / feature columns from
data.full_df, notdata.fpc_df. This is easy to get wrong, because the working dataframe (fpc_df) is the one that grows level by level and feels like the natural place to add a new variable. Use this helper to put the column where L4.1 and L4.2 look for it.- Parameters:
data (
FluxLevelData) – Current FluxLevelData.series (
Series) – Driver series. Its index must matchdata.full_df.index.name (
str|None) – Column name to register the series under. Defaults toseries.name; required ifseries.nameisNone.
- Return type:
- Returns:
New
FluxLevelDatawith the column added tofull_df. The input is not mutated.- Raises:
ValueError – If
serieshas no name andnameis not supplied, its index does not matchdata.full_df.index, or a column with the resolved name already exists infull_df.
Example
>>> import diive as dv >>> vpd = dv.variables.calc_vpd_from_ta_rh(df=data.full_df, rh_col='RH', ta_col='TA') >>> data = dv.flux.add_driver(data, vpd, name='VPD_kPa')
- diive.flux.init_flux_data(df, fluxcol, site_lat, site_lon, utc_offset, nighttime_threshold=20, daytime_accept_qcf_below=1, nighttime_accept_qcf_below=1, ustarcol='USTAR', swin_col=None)[source]¶
Build the initial FluxLevelData container from raw EddyPro data.
Adds potential radiation and day/night flags to the working dataframe, assembles the frozen FluxMeta record, and returns a FluxLevelData ready for the first level callable.
- Parameters:
df (
DataFrame) – Input DataFrame containing flux and meteorological data.fluxcol (
str) – Name of the raw flux column (e.g. ‘FC’, ‘LE’, ‘H’).site_lat (
float) – Site latitude (decimal degrees).site_lon (
float) – Site longitude (decimal degrees).utc_offset (
int) – UTC offset in hours.nighttime_threshold (
float) – Potential radiation threshold (W m-2) below which records are treated as nighttime. Defaults to 20.daytime_accept_qcf_below (
int) –QCF threshold for daytime data retention. Records with QCF below this value are kept; those at or above are set to NaN. Allowed values:
1(default) — keep only QCF=0 (all tests pass). Strictest.2— keep QCF=0 and QCF=1 (soft warnings tolerated). This matches the conventional FLUXNET / Swiss FluxNet choice (Papale et al. 2006, Reichstein et al. 2005) and maximises data availability while still rejecting hard failures.
QCF value meanings:
QCF=0— all quality tests passed; highest confidence.QCF=1— one or more soft warnings (minor issues); marginal quality.QCF=2— at least one hard failure or many soft warnings; rejected.
nighttime_accept_qcf_below (
int) – Same asdaytime_accept_qcf_belowbut applied to nighttime records. Defaults to 1. Set to 2 for the conventional FLUXNET treatment.ustarcol (
str) – Name of the friction velocity column. Defaults to ‘USTAR’.swin_col (
str|None) – Optional name of a measured shortwave-incoming radiation column indf(W m-2) to use as the source for day / night flag derivation. WhenNone(default), the chain computes potential shortwave radiation fromsite_lat/site_lon/utc_offsetviapotrad()and writes it under the nameSW_IN_POT— this is the recommended choice because potential radiation is cloud- and sensor-independent and gives reliable diurnal classification even under heavy cloud cover. Override this only when you have a deliberate reason (e.g. high-latitude topographic shadowing thatpotradcannot resolve, or a pre-validated site-specific day / night source). The supplied column is then used directly (no copy renamed toSW_IN_POT) —data.meta.swinpot_colstores whichever column name actually drives the flags.
- Return type:
- Returns:
FluxLevelData ready to be passed to run_level2().
- Raises:
ValueError – If
df.indexhas no frequency set and its time resolution cannot be detected.
Note
Regular time grid: the levels need a timestamp index without missing timestamps. If
df.indexhas no frequency set, the data are put on a regular grid at the detected time resolution: missing timestamps are added as empty (NaN) records, and records that are not on the grid are removed with a warning that gives their number.dfitself is not changed.FC → NEE rename: when
fluxcol='FC', the output column produced by Level-3.1 (storage-corrected flux) is automatically namedNEEfollowing the FLUXNET convention. All subsequent level outputs and gap-filling results useNEEas the base name. For any other flux (e.g.'LE','H','FCH4'), the original column name is kept.
- diive.flux.run_chain(data, config)[source]¶
Drive the full post-processing chain (L2 -> L3.1 -> L3.2 -> L3.3 -> L4.1 -> L4.2).
Single-call convenience wrapper for the standard FLUXNET-style workflow. Each step is the same composable callable you would otherwise call by hand; this function only routes
FluxConfigfields to the per-level arguments it considers high-level enough to expose.``run_chain`` is intentionally simple. It picks fixed defaults for every per-level knob that is not on
FluxConfig. For full control over detectors, model hyperparameters, MDS tolerances, etc., call the per-level functions directly — they accept the full set of arguments thatrun_chainhides.Per-level behaviour¶
Level-2 (quality flags) — runs the tests listed in
config.level2_test_settings; the always-on missing-values test runs regardless. Whenlevel2_test_settings is None(default), the chain applies the universalDEFAULT_LEVEL2_TEST_SETTINGS(ssitc+gas_completeness+spectral_correction_factor+raw_data_screening_vm97with spikes + dropout). Settingconfig.signal_strength_coladds the analyzer-specificsignal_strengthtest on top withmethod='discard below'/threshold=60— sensible LI-7200-style defaults.Level-3.1 (storage correction) — controlled by
config.set_storage_to_zeroandconfig.gapfill_storage_term.Level-3.2 (outlier detection) — unconditional in ``run_chain`` because L3.3 USTAR filtering depends on outlier-screened data. Uses a single Hampel filter that ships its own sensible defaults (
window_length=48*13records = 13 days at 30-min sampling, Papale 2006;n_sigma_daytime=n_sigma_nighttime=5.5;use_differencing=True;separate_day_night=True;repeat=True). The optionalconfig.outlier_window_length/outlier_sigma_daytime/outlier_sigma_nighttimefields are overrides — set them only when you want to deviate from the defaults; leave themNone(the default) to defer toHampel. All other Hampel knobs (k,use_differencing,repeat, …) are fixed at the underlying function’s defaults. If you have screened outliers upstream and genuinely want to skip L3.2, use the composable per-level API instead ofrun_chain.Level-3.3 (USTAR filtering) — dispatches on
config.ustar_detection_mode:'constant'(default) — apply pre-computed thresholds fromconfig.ustar_thresholds(e.g. produced by REddyProc externally).'bootstrap'— detect thresholds from the data via multi-year bootstrap (FLUXNET standard, Papale et al. 2006). Requiresconfig.ustar_bootstrap_ta_col/..._swin_col; thresholds andCUT_<p>labels are generated fromconfig.ustar_bootstrap_percentiles(default(16, 50, 84)). The fittedUstarBootstrapThresholdsis attached todata.levels.ustar_detection.
Level-4.1 (gap-filling) — runs only the methods whose
config.gapfill_*flag isTrue. MDS runs inconfig.mds_mode(default'diive') with the optional driver QC columnsconfig.mds_*_qc, and uses theFluxMDSdefaults for tolerances andavg_min_n_vals. RF and XGBoost are built with a defaultFeatureEngineerthat ships with the symmetric lag window[-2, 2], first- and second-order differencing, 4 / 12 / 48-record rolling median + std, and vectorized timestamps (see_default_engineerfor the full rationale). SHAP-based feature reduction is on by default (controlled byconfig.gapfill_reduce_features) — set toFalsefor a diagnostic run with the raw engineered feature set. Model hyperparameters (n_estimators,max_depth, …) and customFeatureEngineerconfigurations remain reachable only via the composable API.Level-4.2 (NEE partitioning) — off by default. Runs each variant with its
config.partition_*flag set toTrue, plus the one selected byconfig.partition_method/config.partition_mode(ONEFlux by default). A variant selected both ways runs once.What
run_chaindoes not expose¶The following knobs are reachable only via the composable per-level API. If you need any of them, build the chain step by step with
run_level2/run_level31/make_level32_detector+run_level32/run_level33_constant_ustar(orrun_level33_ustar_detection) /run_level41_mds/run_level41_rf/run_level41_xgb/run_level42_partitioninginstead.L3.2 — non-Hampel detectors (z-score rolling, abslim, LocalSD, manual removal), multi-step pipelines (Hampel + something else with sequential
addflag()), and Hampel sub-options (use_differencing,repeat,k,window_lengthper call).L3.3 — diagnostic
showplot=Trueandverbose=True(both forced toFalsehere for non-interactive use), customdetector_class/detector_kwargsin bootstrap mode (defaults to ONEFlux moving-point), and VUT (mode='vut').L4.1 MDS —
swin_tol/ta_tol/vpd_tol/avg_min_n_vals(fixed atFluxMDSdefaults).L4.1 RF / XGBoost — model hyperparameters (
n_estimators,max_depth,learning_rate, …) and theFeatureEngineeritself (useengineer=on the per-level function for the full 8-stage configuration). SHAP feature reduction is reachable fromrun_chainviaconfig.gapfill_reduce_features.
Contextual field validation¶
FluxConfigmakes most fields optional andrun_chainvalidates that each enabled feature has the fields it needs:mds_swin/mds_ta/mds_vpdare required whengapfill_mds=True;gapfilling_featuresis required whengapfill_rforgapfill_xgbisTrue;ustar_thresholdsis required in'constant'mode;ustar_bootstrap_ta_col/..._swin_colare required in'bootstrap'mode. Each enabled partitioning variant needs itspartition_*driver columns, and the nighttime variants need the L4.1 method named bypartition_gapfill_methodto be on. A singleValueErrorlists every missing field.- type data:
- param data:
Initial container from
init_flux_data().- type config:
- param config:
Per-flux configuration object.
- rtype:
- returns:
New
FluxLevelDatawith all requested levels populated.- raises ValueError:
If
config.fluxcoldoes not matchdata.meta.fluxcol, or if any enabled feature is missing the fields it needs (see contextual-validation note above).
See also
examples/flux/postprocessingchain/postprocessingchain_runchain.pyfor a runnable end-to-end example.Example
>>> import diive as dv >>> cfg = dv.flux.FluxConfig( ... fluxcol='FC', ustar_thresholds=[0.18], ustar_labels=['CUT_50'], ... outlier_sigma_daytime=5.5, outlier_sigma_nighttime=5.5, ... gapfilling_features=['TA_1_1_1', 'SW_IN_1_1_1', 'VPD_kPa_1_1_1'], ... level2_test_settings={'ssitc': {'apply': True, 'setflag_timeperiod': None}}, ... mds_swin='SW_IN_1_1_1', mds_ta='TA_1_1_1', mds_vpd='VPD_kPa_1_1_1') >>> data = dv.flux.init_flux_data(df, fluxcol='FC', site_lat=46.6, site_lon=9.8, utc_offset=1) >>> data = dv.flux.run_chain(data, cfg)
- Parameters:
data (FluxLevelData)
config (FluxConfig)
- Return type:
- class diive.flux.TimeLagAnalysis(df, ignore_fringe_bins=None, lag_window_min=0.1, lag_window_max=1.0, histogram_start_seconds=0, histogram_end_seconds=10, gradient_threshold=0.15, zoom_margin=None, **legacy)[source]¶
Bases:
objectAnalyze and visualize time lags in eddy covariance flux measurements.
Detects optimal time lags for gas concentrations (CO2, H2O) relative to wind measurements using histogram-based analysis with gradient-based peak detection. Generates 4-panel visualizations showing overview and zoomed histogram/time series.
- Key Features:
Automated fringe bin exclusion for non-physical lag accumulations
Gradient-based peak range detection with configurable sensitivity
EddyPro-compatible lag range adjustment (0.05s discrete steps)
Dynamic tick spacing to prevent label overlap
Result caching for efficient reanalysis
- Parameters:
df (pd.DataFrame) – Dataframe with TLAG columns (e.g., ‘CO2_TLAG_ACTUAL’) and datetime index
ignore_fringe_bins (list, optional) – [i, j]: number of leading and trailing histogram bins to exclude. Default: None, which means [5, 10]
lag_window_min (float) – Reference acceptable lag range for visualization (seconds)
lag_window_max (float) – Reference acceptable lag range for visualization (seconds)
histogram_start_seconds (float) – Lag range in seconds kept for display and analysis. Default: 0 to 10
histogram_end_seconds (float) – Lag range in seconds kept for display and analysis. Default: 0 to 10
gradient_threshold (float) – Edge detection sensitivity; lower = stricter. Default: 0.15
zoom_margin (list, optional) – [before_peak, after_peak] offsets for zoomed view (seconds). Default: None, which means [0.5, 1.5]
Example
See examples/flux/lowres/flux_timelag_analysis.py for complete examples.
- __init__(df, ignore_fringe_bins=None, lag_window_min=0.1, lag_window_max=1.0, histogram_start_seconds=0, histogram_end_seconds=10, gradient_threshold=0.15, zoom_margin=None, **legacy)[source]¶
Initialize TimeLagAnalysis with data and parameters.
- Parameters:
df (pd.DataFrame) – Input dataframe with TLAG columns (e.g., ‘CO2_TLAG_ACTUAL’, ‘H2O_TLAG_ACTUAL’) and a datetime index. Expected to contain columns matching pattern ‘*_TLAG_ACTUAL’ for analysis.
ignore_fringe_bins (list, optional) – How many bins to drop from each end of the histogram, as [leading, trailing] counts — not bin indices. The outermost bins tend to accumulate non-physical lag values. Default: None, which means [5, 10]. Trimming is skipped, with a warning, if it would remove every bin.
lag_window_min (float) – Lower bound of physically acceptable lag range in seconds. Used for reference line visualization (typically ~0.10s). Default: 0.10
lag_window_max (float) – Upper bound of physically acceptable lag range in seconds. Used for reference line visualization (typically ~1.00s). Default: 1.00
histogram_start_seconds (float) – Lowest lag value in seconds kept for display and analysis. Bins are compared against their inclusive start, not their index. Default: 0
histogram_end_seconds (float) – Highest lag value in seconds kept for display and analysis. If fewer than two bins fall into the range, the whole lag range is kept and a warning is issued. Default: 10
gradient_threshold (float) – Threshold for gradient-based peak edge detection (0-1 range). Lower values = stricter edge detection. Controls where peak edges are identified based on histogram gradient magnitude. Default: 0.15
zoom_margin (list, optional) – Zoom range offsets [before_peak, after_peak] in seconds for zoomed subplots. Defines how far left/right of peak to display in zoom views. Default: [0.5, 1.5]
**legacy – Only accepted to reject renamed parameters with a message naming their replacement, see
_RENAMED_PARAMS.
- static adjust_range_for_eddypro(min_lag, max_lag, step=0.05)[source]¶
Widen a detected lag range by one EddyPro lag step on each side.
Returns
(min_lag - step, max_lag + step). EddyPro searches lags at fixed steps (default 0.05 s), so the widened range keeps both detected boundaries one step inside the range given to EddyPro.Example: To make sure EddyPro searches the range [0.10, 1.00] seconds:
min_detected = 0.10 max_detected = 1.00 min_input, max_input = adjust_range_for_eddypro(min_detected, max_detected) # Result: min_input=0.05, max_input=1.05
- Parameters:
- Returns:
eddypro_min (float) – Adjusted minimum for EddyPro input
eddypro_max (float) – Adjusted maximum for EddyPro input
Notes
This is a utility function independent of class state and does not require an instance. Can be called as TimeLagAnalysis.adjust_range_for_eddypro().
- static detect_peak_range(histogram_results, peakbins, gradient_threshold=0.15)[source]¶
Detect the range around a histogram peak using gradient-based edge detection.
Identifies peak boundaries by finding where the histogram gradient (first derivative) magnitude drops below a threshold. This method is robust to peak shape variations and works well for both symmetric and skewed distributions.
Algorithm:
Normalize counts to 0-1 range
Compute first derivative (gradient) of normalized counts
Locate peak bin (closest bin to peakbins[0])
Search left: find first bin where |gradient| < threshold
Search right: find first bin where |gradient| < threshold
Return boundaries at these indices
Gradient threshold interpretation:
0.15 (default): detects moderate slope changes, suited for moderately sharp peaks
< 0.10: stricter, captures narrower peaks, sensitive to noise
> 0.20: lenient, captures broader tails, includes more uncertainty range
- Parameters:
histogram_results (pd.DataFrame) –
Histogram bin data with required columns:
’BIN_START_INCL’ : bin boundaries (inclusive)
’COUNTS’ : bin counts/frequencies
peakbins (array-like) – Peak bin values where peakbins[0] is the primary peak lag (seconds)
gradient_threshold (float) – Threshold magnitude for gradient-based edge detection (0-1 range). Represents normalized gradient magnitude below which edges are detected. Lower values = stricter edge detection, narrower range. Default: 0.15
- Returns:
min_lag (float) – Detected minimum lag boundary (seconds)
max_lag (float) – Detected maximum lag boundary (seconds)
Notes
This is a utility function independent of class state and does not require an instance. Can be called as TimeLagAnalysis.detect_peak_range(…).
The method assumes peakbins[0] is valid and falls within histogram_results bins. Edge cases: if gradient never drops below threshold, returns peak_idx boundaries.
- analyze_gas(gas)[source]¶
Analyze time lags for a specific gas species.
Performs complete lag analysis workflow:
Extracts time lag series for specified gas (*_TLAG_ACTUAL column)
Creates histogram using unique value binning
Excludes specified fringe bins (non-physical accumulations)
Filters histogram to display range (histogram_start_seconds to histogram_end_seconds), skipping the filter with a warning if it would keep fewer than two bins
Detects peak lag using histogram maximum
Identifies peak range boundaries via gradient-based edge detection
Adjusts range for EddyPro’s discrete 0.05s steps
Results are cached internally to avoid recomputation on repeated calls.
- Parameters:
gas (str) – Gas name extracted from column prefix. Expected to match a column named ‘{gas}_TLAG_ACTUAL’ (e.g., ‘CO2’, ‘H2O’). Case-sensitive.
- Returns:
Complete analysis results with keys: - ‘gas’ : str – Gas name - ‘series’ : pd.Series – Full time lag series for gas - ‘histogram_results’ : pd.DataFrame – Histogram bins, counts - ‘peakbins’ : array – Peak bin values from Histogram class - ‘peak’ : float – Primary peak lag value (seconds) - ‘peak_min’, ‘peak_max’ : float – Detected peak range boundaries - ‘eddypro_min’, ‘eddypro_max’ : float – EddyPro-adjusted boundaries - ‘first_date’, ‘last_date’ : date – Data time span
- Return type:
- Raises:
ValueError – If column ‘{gas}_TLAG_ACTUAL’ not found in input dataframe, or if the lag values hold fewer than two distinct values. The peak range needs at least two histogram bins, one per distinct value.
Notes
Results are cached in self._analysis_cache. Subsequent calls with same gas return cached result without recomputation.
- plot_gas(gas, outdir=None, figsize=(18, 9), show=True, fig=None)[source]¶
Create comprehensive visualization of time lag analysis for a gas species.
Generates a 4-panel figure showing overview and zoomed perspectives:
Layout (2x2 grid): - Top-left: Overview histogram with all lag bins and detection ranges - Top-right: Zoomed histogram centered on detected peak - Bottom-left: Time series of all lag observations over study period - Bottom-right: Zoomed time series around detected peak range
Overlays (all panels): - Black line: Detected peak lag value - Teal shaded region + boundaries: Detected peak range (gradient-based) - Orange dashed lines + shaded region: EddyPro-adjusted input range - Purple dashed lines: Reference acceptable lag window
Legend (overview histogram only): Shows peak value, detected range, EddyPro input range, and reference window.
Automatically calls self.analyze_gas() if needed, using cached results if available.
- Parameters:
gas (str) – Gas name (e.g., ‘CO2’, ‘H2O’). Must match column prefix in data.
outdir (str, optional) – Output directory for saving figure. If provided, saves as ‘{outdir}/02_{gas}_TLAG_ACTUAL_{first_date}_{last_date}.png’ at 150 dpi. If None, figure not saved. Default: None
figsize (tuple) – Figure size as (width, height) in inches. Default: (18, 9)
show (bool) – If True, calls fig.show() to display the figure. If False, figure is created but not displayed (useful for batch processing). Default: True
fig (matplotlib.figure.Figure, optional) – Existing figure to draw into (cleared first). When provided, the 4-panel layout is built on it instead of a new pyplot figure — this is how the desktop GUI embeds the plot in its own canvas. The figsize argument is then ignored. Default: None (new figure).
- Returns:
fig – The created (or supplied) figure object. Can be further modified or saved.
- Return type:
- Raises:
ValueError – If gas analysis fails (e.g., column not found). Raised from
analyze_gas(). Onlyplot_all_gases()catches it.
Notes
Figure styling is applied for the duration of this call only, via
_PLOT_STYLE. Colors and fonts are consistent across this module’s plots and leave the caller’s matplotlib settings untouched.Examples
Create and save visualization for CO2:
analysis = TimeLagAnalysis(df) fig = analysis.plot_gas('CO2', outdir='output/', show=False)
Create multiple gas plots in batch:
for gas in ['CO2', 'H2O']: analysis.plot_gas(gas, outdir='output/', show=False)
- analyze_all_gases(gases=None)[source]¶
Analyze multiple gas species in batch mode.
Automatically detects all available gases (based on *_TLAG_ACTUAL column names) if not explicitly specified. Calls analyze_gas() for each gas and returns consolidated results. Errors in individual gas analyses are caught and reported without interrupting the batch process.
- Parameters:
gases (list, optional) – Explicit list of gas names to analyze (e.g., [‘CO2’, ‘H2O’]). Names must match column prefixes in data (case-sensitive). If None, automatically detects all gases from available TLAG_ACTUAL columns. Default: None (auto-detect)
- Returns:
Analysis results keyed by gas name. Each key maps to the dict returned by analyze_gas(). If a gas fails to analyze, it is excluded from results and a warning message is printed.
- Return type:
Examples
Auto-detect all available gases:
all_results = analysis.analyze_all_gases()
Analyze specific gases only:
results = analysis.analyze_all_gases(gases=['CO2', 'H2O'])
Notes
Failed analyses (e.g., missing columns) print warnings but do not raise exceptions. This allows batch processing to continue even if some gases cannot be analyzed.
- plot_all_gases(gases=None, outdir=None, figsize=(18, 9), show=True)[source]¶
Create and optionally save visualizations for multiple gas species.
Calls plot_gas() for each specified or auto-detected gas. Results in one 4-panel figure per gas. All parameters are passed through to plot_gas(). Errors in individual plots are caught and reported without interrupting the batch process.
- Parameters:
gases (list, optional) – Explicit list of gas names to plot (e.g., [‘CO2’, ‘H2O’]). Names must match column prefixes in data (case-sensitive). If None, automatically detects all gases from available TLAG_ACTUAL columns. Default: None (auto-detect)
outdir (str, optional) – Output directory for saving figures. Each figure saved as ‘{outdir}/02_{gas}_TLAG_ACTUAL_{first_date}_{last_date}.png’ at 150 dpi. If None, figures not saved (only displayed if show=True). Default: None
figsize (tuple) – Figure size as (width, height) in inches. Applied to all plots. Default: (18, 9)
show (bool) – If True, each figure is displayed via fig.show(). Useful for interactive analysis. If False, figures created but not displayed (for batch processing). Default: True
- Returns:
Matplotlib figure objects keyed by gas name. Each value is the Figure returned by plot_gas(). If a gas fails to plot, it is excluded from results and a warning message is printed.
- Return type:
Examples
Plot all detected gases and save to output directory:
figs = analysis.plot_all_gases(outdir='output/')
Plot specific gases without displaying:
figs = analysis.plot_all_gases( gases=['CO2', 'H2O'], outdir='output/', show=False )
Notes
If outdir is provided, creates figures even if show=False. This is useful for batch processing without blocking on figure display.
Failed plots (e.g., missing columns) print warnings but do not raise exceptions, allowing batch processing to continue.
- class diive.flux.RandomUncertaintyPAS20(df, fluxcol, fluxgapfilledcol, tacol, vpdcol, swincol, vpd_in_kpa=True)[source]¶
Bases:
objectHierarchical random uncertainty quantification for eddy covariance flux data.
Implements the PAS20 (Pastorello et al. 2020) uncertainty methodology which applies hierarchical methods to estimate random measurement uncertainty in flux measurements. The approach fills gaps and propagates uncertainties through gap-filling to produce cumulative uncertainty estimates.
Methods 1 and 2 are faithful ports of the ONEFlux C reference (
oneflux_steps/nee_proc/src/randunc.c, functionsrandom_method_1/random_method_2). Methods 3 and 4 are diive extensions (not in ONEFlux): ONEFlux leaves a record’s random uncertainty undefined when method 2 finds no similar fluxes, whereas methods 3 and 4 relax the matching further to guarantee every record gets an estimate.Core Methods:
Method 1 (ONEFlux) — standard deviation of measured fluxes in a sliding ±7-day / ±1-hour window under similar meteorological conditions (TA, VPD, SW_IN), requiring more than 5 matching values.
Method 2 (ONEFlux) — median of the method-1 uncertainties of similar fluxes (within ±20%, floor 2 µmol) in a ±14-day window.
Method 3 (diive extension) — median of method-1 uncertainties of similar fluxes over the whole record (no time window).
Method 4 (diive extension) — median of the uncertainties of the fluxes closest in magnitude, with no similarity restriction.
Key Features:
The hierarchy gives every record an uncertainty estimate.
The cumulative uncertainty adds the per-record uncertainties in quadrature and skips missing values, so one NaN does not make the rest of the cumulative NaN.
References
- Hollinger, D. Y., & Richardson, A. D. (2005). Uncertainty in eddy covariance measurements
and its application to physiological models. Tree Physiology, 25(7), 873–885. https://doi.org/10.1093/treephys/25.7.873
- Pastorello, G., Trotta, C., Canfora, E., Chu, H., Christianson, D., Cheah, Y.-W.,
Poindexter, C., Chen, J., Elbashandy, A., Humphrey, M., Isaac, P., Polidori, D., Reichstein, M., Ribeca, A., Van Ingen, C., Vuichard, N., Zhang, L., Amiro, B., Ammann, C., … Papale, D. (2020). The FLUXNET2015 dataset and the ONEFlux processing pipeline for eddy covariance data. Scientific Data, 7(1), 225. https://doi.org/10.1038/s41597-020-0534-3
Example
See examples/flux/lowres/flux_uncertainty.py for complete examples of random uncertainty calculation and cumulative uncertainty propagation.
- Parameters:
- __init__(df, fluxcol, fluxgapfilledcol, tacol, vpdcol, swincol, vpd_in_kpa=True)[source]¶
Random uncertainty estimation.
- Parameters:
df (
DataFrame) – DataFrame with the columns below and a regular datetime index.fluxcol (
str) – measured flux to estimate uncertainty for (umol CO2 m-2 s-1).fluxgapfilledcol (
str) – gap-filled flux (umol CO2 m-2 s-1).tacol (
str) – air temperature (deg C). Similarity tolerance: 2.5 deg C.vpdcol (
str) – vapor pressure deficit. Unit is set byvpd_in_kpa.swincol (
str) – short-wave incoming radiation (W m-2). Similarity tolerance: the record’s own SW_IN clamped into [20, 50] W m-2.vpd_in_kpa (
bool) – if True (default, diive convention, matching the MDS gap-filler)vpdcolis in kPa and is converted to hPa internally for the faithful ONEFlux 5-hPa similarity tolerance. Pass False ifvpdcolis already in hPa.
- property randunc_results¶
Results subset containing uncertainty and auxiliary variables
- property randunc_results_cumulatives¶
Cumulatives including random uncertainty propagation
- run(progress_callback=None)[source]¶
Run the 4-method hierarchical uncertainty quantification.
- Parameters:
progress_callback – optional
callable(phase, n_phases, done, total)for a GUI progress bar.phaseis 1..4 (the method being run),n_phasesis 4, anddone/totaltrack the per-record loop within that method. The per-record loops (method 1 especially) dominate runtime, hence the within-method reporting.
- report_cumulative_uncertainty_propagation()[source]¶
Report cumulative uncertainty propagation with formatted table output.
- report_method_summary()[source]¶
Report summary of 4-method hierarchical uncertainty quantification.
- class diive.flux.JointUncertaintyPAS20(df, randunccol, scenario_lower_col, scenario_upper_col, fluxgapfilledcol=None, divisor=2.0, name=None)[source]¶
Bases:
objectJoint uncertainty estimation (Pastorello et al. 2020 / ONEFlux
compute_join).Combines the per-record random measurement uncertainty (e.g.
{flux}_RANDUNCfromRandomUncertaintyPAS20) with the scenario-ensemble uncertainty from the flux-partitioning/filtering percentile scenarios, added in quadrature:JOINTUNC = sqrt( RANDUNC^2 + ((scenario_upper - scenario_lower) / divisor)^2 )
For NEE the scenario ensemble is the USTAR-threshold percentile scenarios and the 16th/84th percentiles bracket +/-1 sigma (
divisor=2, the default,JOINT_DIVISOR_1SIGMA); ONEFlux emits this as e.g.NEE_CUT_REF_JOINTUNC. For the energy fluxes LE/H the ensemble is the energy-balance-correction percentiles and the 25th/75th interquartile range is used (divisor=JOINT_DIVISOR_IQR=1.349), emitted asLE_CORR_JOINTUNC/H_CORR_JOINTUNC.Faithful port of the ONEFlux
compute_joinhelper (oneflux_steps/nee_proc/src/dataset.c) and its energy-flux variant (energy_proc/src/dataset.c).Cumulative propagation treats the two error sources differently, matching their nature: the random error is independent between records and propagates in quadrature, whereas the scenario (e.g. USTAR-threshold) choice is fully correlated across the record — the same threshold applies to every half-hour — so its cumulative uncertainty is the running spread of the cumulative scenario sums. The two cumulative terms are then combined in quadrature.
References
Pastorello et al. (2020), Scientific Data 7, 225. https://doi.org/10.1038/s41597-020-0534-3
Example
See
examples/flux/lowres/flux_uncertainty.py.- Parameters:
- __init__(df, randunccol, scenario_lower_col, scenario_upper_col, fluxgapfilledcol=None, divisor=2.0, name=None)[source]¶
Joint uncertainty estimation.
- Parameters:
df (
DataFrame) – DataFrame with the columns below and a regular datetime index.randunccol (
str) – per-record random uncertainty (e.g.NEE_CUT_REF_RANDUNC).scenario_lower_col (
str) – lower-percentile scenario flux (NEE: 16th, e.g.NEE_CUT_16; LE/H: 25th).scenario_upper_col (
str) – upper-percentile scenario flux (NEE: 84th, e.g.NEE_CUT_84; LE/H: 75th).fluxgapfilledcol (
str|None) – optional gap-filled flux for the cumulative propagation (the central line the cumulative band brackets). When omitted, only the per-record joint uncertainty is computed.divisor (
float) – percentile-range -> 1-sigma factor.JOINT_DIVISOR_1SIGMA(2.0, default) for the 16th/84th NEE percentiles,JOINT_DIVISOR_IQR(1.349) for the 25th/75th LE/H IQR.name (
str|None) – output column name. Defaults to the random-uncertainty column with a trailing_RANDUNCreplaced by_JOINTUNC(soNEE_CUT_REF_RANDUNC->NEE_CUT_REF_JOINTUNC), else{randunccol}_JOINTUNC.
- scenarionunccol¶
per-record scenario (e.g. USTAR-filtering) 1-sigma-equivalent term.
- property jointunc_results: DataFrame¶
random term, scenario term and the joint uncertainty.
- Type:
Results subset
- property jointunc_results_cumulatives: DataFrame¶
Cumulative flux with the propagated joint-uncertainty bounds.
- diive.flux.joint_uncertainty_pas20(randunc, scenario_lower, scenario_upper, divisor=2.0)[source]¶
Per-record joint uncertainty (Pastorello et al. 2020 / ONEFlux
compute_join).Combines, in quadrature, the random measurement uncertainty with the uncertainty from the flux-partitioning/filtering scenario ensemble (for NEE: the USTAR-threshold percentile scenarios; for LE/H: the energy-balance correction percentiles). The scenario spread is first converted to a 1-sigma-equivalent by
divisor:JOINTUNC = sqrt( RANDUNC^2 + ((scenario_upper - scenario_lower) / divisor)^2 )
Faithful port of ONEFlux
compute_join(oneflux_steps/nee_proc/src/dataset.c) and the energy-flux variant (energy_proc/src/dataset.c). ONEFlux returns an invalid value when any of the three inputs is invalid; here that maps to NaN, which numpy propagates throughsqrtautomatically.- Parameters:
randunc (
Series) – per-record random uncertainty (e.g.{flux}_RANDUNCfromRandomUncertaintyPAS20).scenario_lower (
Series) – lower-percentile scenario flux (NEE: 16th, e.g.NEE_CUT_16; LE/H: 25th, e.g.LEcorr25).scenario_upper (
Series) – upper-percentile scenario flux (NEE: 84th, e.g.NEE_CUT_84; LE/H: 75th, e.g.LEcorr75).divisor (
float) – percentile-range -> 1-sigma factor. UseJOINT_DIVISOR_1SIGMA(2.0) for the 16th/84th NEE percentiles andJOINT_DIVISOR_IQR(1.349) for the 25th/75th LE/H IQR.
- Return type:
- Returns:
The joint uncertainty as a Series aligned to
randunc’s index, NaN where any input is missing.
- class diive.flux.UstarBootstrapThresholds(df, detector_class, detector_kwargs=None, n_iter=100, percentiles=(16, 50, 84), n_jobs=1, random_state=42, verbose=0)[source]¶
Bases:
objectMulti-year bootstrap USTAR threshold estimation — VUT and CUT.
Wrapper around any USTAR detection class that implements detect() and get_annual_thresholds(). For each central year, bootstrap resampling is run on a 3-year window (central year plus its two neighbors); the distribution of annual thresholds is then summarized two ways, following the FLUXNET / ONEFlux convention:
VUT (Variable U* Threshold) — one threshold per year. Returned by
run()/get_vut_thresholds()(theannual_stats_table): each year’s row holds the requested percentiles of that year’s bootstrap distribution, so the threshold varies year to year.CUT (Constant U* Threshold) — one threshold for the whole record. Returned by
get_cut_threshold(): all bootstrap samples from every year are pooled into a single distribution and the percentiles taken once, giving one constant threshold applied uniformly to every year.
Note
VUT here is smoothed across a 3-year window, which differs from the strict ONEFlux VUT (each year estimated from that single year alone). The central year is pooled with its two neighbors (see Window rules) before bootstrapping, deliberately trading a little year-to-year resolution for a more stable, cleaner per-year threshold — sites often have too few good nighttime records in a single year for a robust single-year estimate. CUT (pooled across all years) matches the ONEFlux CUT meaning directly.
Window rules¶
Normal case: window = [year-1, year, year+1]
First year (no predecessor): window = [year, year+1, year+2]
Last year (no successor): window = [year-2, year-1, year]
2 years total: both years use the full 2-year dataset
3 years total: all years use the full 3-year dataset
1 year total: that year is used on its own
- param df:
Full time series data with DatetimeIndex. May span multiple years.
- type df:
- param detector_class:
USTAR detection class to use. Must implement detect() and get_annual_thresholds(). Supported: UstarMovingPointDetection, UstarVekuriThresholdDetection.
- type detector_class:
- param detector_kwargs:
Keyword arguments forwarded to the detector constructor (excluding verbose, which is always set to 0 for inner detectors).
- type detector_kwargs:
- param n_iter:
Bootstrap iterations per central year.
- type n_iter:
- param percentiles:
Percentiles to compute from the bootstrap distribution. p50 is the recommended threshold; p16/p84 bound the uncertainty.
- type percentiles:
- param n_jobs:
Number of parallel worker processes. Each window (central year) runs its full N iterations in one worker process. 1 = sequential; -1 = use all available CPUs; N = use N processes. Uses joblib/loky backend, which works correctly on Windows without requiring an if __name__ == ‘__main__’ guard in scripts.
- type n_jobs:
- param random_state:
Seed for the bootstrap resampling, so the same input gives the same VUT and CUT thresholds. Pass None for a fresh draw on every run. The seed is derived per window year, so results do not depend on
n_jobsor on the order in which windows finish, and separate years remain independent draws — a single shared seed would make every window resample the same positions.- type random_state:
- param verbose:
Verbosity: 0=silent, 1=progress per year.
- type verbose:
- ivar annual_stats_:
Per-year (VUT) bootstrap percentile thresholds. Also returned by
get_vut_thresholds(). Index: year (int), columns: p16, p50, p84 (or custom percentiles).- vartype annual_stats_:
pd.DataFrame
- ivar years_:
Calendar years present in the input data.
- vartype years_:
list of int
Examples
>>> import diive as dv >>> df = dv.load_exampledata_parquet_lae() >>> boot = dv.flux.UstarBootstrapThresholds( ... df, detector_class=dv.flux.UstarMovingPointDetection, ... n_iter=100, percentiles=(16, 50, 84)) >>> annual = boot.run() # then boot.get_cut_threshold() / boot.summary()
See also
UstarMovingPointDetectionONEFlux moving point detection (Papale et al. 2006).
UstarVekuriThresholdDetectionQuantile-based detection (Vekuri approach).
- __init__(df, detector_class, detector_kwargs=None, n_iter=100, percentiles=(16, 50, 84), n_jobs=1, random_state=42, verbose=0)[source]¶
Set up multi-year bootstrap USTAR threshold detection. See the class docstring.
random_stateseeds the resampling, so the same input gives the same VUT and CUT thresholds; pass None for the old per-run variation. The seed is derived per window year, so the result does not depend onn_jobsor on the order windows finish in, and separate years still draw independently.
- run()[source]¶
Run the VUT bootstrap using a 3-year sliding window.
For each central year, pools data from the window (central year plus its two neighbors, with edge-case handling), resamples N times with replacement, runs the detection method, collects the annual threshold, then computes percentiles from the resulting distribution. The result is the VUT (variable, per-year) threshold table; pool it across years with
get_cut_threshold()for the CUT (constant) threshold.- Returns:
Per-year (VUT) bootstrap percentile thresholds. Index: year (int), columns: p{percentile} for each requested percentile. p50 is the recommended annual USTAR threshold for filtering.
- Return type:
- get_vut_thresholds()[source]¶
Get VUT (variable, per-year) USTAR thresholds.
Convenience accessor returning
annual_stats_(the table produced byrun()): one row per year, columnsp{percentile}. Each year’s values are the percentiles of that year’s 3-year-window bootstrap distribution, so the threshold varies year to year.Note
Each year is estimated from a 3-year window (the year plus its two neighbors), not the single year alone, so this VUT is smoothed relative to the strict ONEFlux single-year VUT — a deliberate trade for a more stable per-year threshold. See the class docstring.
- Returns:
Per-year percentile thresholds (index: year; columns: p{percentile}).
- Return type:
- Raises:
RuntimeError – If run() has not been called yet.
- get_cut_threshold()[source]¶
Get CUT (constant) USTAR threshold pooled across all years.
Pools all bootstrap samples from all years into a single distribution and extracts the requested percentiles. This gives a single conservative threshold that is stable across the full measurement record. This matches the ONEFlux CUT (constant U* threshold) meaning directly.
- Returns:
Keys: ‘p{percentile}’ (e.g., ‘p16’, ‘p50’, ‘p84’). Values: USTAR threshold in m/s. p50 is the recommended CUT threshold.
- Return type:
- Raises:
RuntimeError – If run() has not been called yet.
- class diive.flux.UstarMovingPointDetection(df, nee_col=None, ta_col=None, ustar_col=None, swin_col=None, ta_classes_count=7, ustar_classes_count=20, forward_mode_n=2, season_groups=None, bootstrapping_times=100, random_state=42, verbose=0)[source]¶
Bases:
objectDetect USTAR threshold using ONEFlux moving point method (Papale et al., 2006).
This class implements the complete USTAR threshold detection workflow for eddy covariance flux measurements. It identifies the friction velocity (u*) above which flux measurements are reliable by analyzing the stability of nighttime respiration across USTAR classes.
The key insight is that during nighttime, without photosynthesis, NEE represents pure ecosystem respiration. At low u* (poor turbulence), measured respiration is systematically underestimated due to storage and vertical mixing limitations. At high u* (good turbulence), respiration stabilizes. The threshold is where respiration stops changing with increasing u*.
Algorithm steps (mirrors
ustar.c::ustar_threshold):FILTER DATA: Select nighttime records only (SW_IN < 10 W/m2) for pure respiration signal
STRATIFY BY SEASON: Divide year into 4 seasons (calendar quarters by default)
STRATIFY BY TEMPERATURE: Within each season, divide into 7 temperature classes
STRATIFY BY USTAR: Within each temperature class, divide into 20 USTAR classes
COMPUTE STATISTICS: Calculate mean respiration per USTAR class
VALIDATE: Check temperature-USTAR independence and first USTAR validity
DETECT THRESHOLD: Use forward mode detection (ascending search) to find stability point
AGGREGATE: Median across temperature classes gives season threshold; maximum across seasons gives the annual (conservative) threshold
Class boundaries are tie-aware: equal TA / USTAR values are never split across adjacent classes (matches the C boundary-extension loop), so quantized USTAR data is binned exactly as ONEFlux does.
- Parameters:
df (
DataFrame) – Time series data with datetime index and required columns: NEE, TA, USTAR, SW_INnee_col (
Optional[str]) – Net ecosystem exchange column name (auto-detected if None) Looks for columns containing ‘NEE’ and ‘QCF’ preferentiallyta_col (
Optional[str]) – Air temperature column name (auto-detected if None) Looks for columns containing ‘TA_’ or similarustar_col (
Optional[str]) – Friction velocity column name (auto-detected if None) Looks for columns containing ‘USTAR’ or ‘U_STAR’swin_col (
Optional[str]) – Shortwave radiation column name (auto-detected if None) Used to identify nighttime (SW_IN < 10 W/m2)ta_classes_count (
int) – Number of temperature stratification classes per season (matches ONEFlux default)ustar_classes_count (
int) – Number of USTAR stratification classes per temperature class (matches ONEFlux default)forward_mode_n (
int) – Number of consecutive USTAR classes that must satisfy the plateau condition before a threshold is accepted (forward-mode order). n=2 is “Fw2”, the default in both ONEFlux (only forward_mode_2 is enabled by default) and REddyProc (usEstUstarThresholdSingleFw2Binned). n=1 is “Fw1”: looser, fires on a single bin, and never yields a higher threshold than Fw2. Higher n is stricter (requires a longer confirmed plateau), giving an equal-or-higher threshold that is more robust to single-bin noise.season_groups (
Optional[List[List[int]]]) – Custom season grouping by month numbers [1-12]. Default: [[1,2,3], [4,5,6], [7,8,9], [10,11,12]] (calendar quarters), matching the ONEFlux defaultdefault_seasons_group = "1,2,3;4,5,6;7,8,9;10,11,12".bootstrapping_times (
int) – Number of bootstrap resampling iterations for uncertainty estimationrandom_state (
Optional[int]) – Seed for the bootstrap resampling, sobootstrap()returns the same distribution for the same input. Pass None for a fresh draw each call.detect()is deterministic and unaffected. Seeding selects which resamples are drawn, not how a threshold is computed, so ONEFlux parity is unaffected.verbose (
int) – Verbosity level: 0=silent, 1=progress, 2=detailed debug output
- Variables:
results (pd.DataFrame) – Detected thresholds with column: ‘threshold’ Index contains season labels (Season 1, 2, 3, 4) NaN for a season whose threshold could not be detected
annual_thresholds (dict) – Annual threshold with key: ‘threshold’ (maximum across seasons), NaN if no season yielded a threshold. Same value as
get_annual_thresholds()returns.
Examples
>>> import diive as dv >>> df = dv.load_exampledata_parquet_lae() >>> detector = dv.flux.UstarMovingPointDetection(df) >>> thresholds = detector.detect() # then detector.summary() / detector.bootstrap()
Notes
The algorithm requires:
At least 3000 valid records for valid detection (MIN_VALUE_PERIOD)
At least 700 (= 100 * 7) records per season for per-season detection (TA_CLASS_MIN_SAMPLE * ta_classes_count); seasons below this are skipped
If every season is below 700, all night data is pooled into one season (ONEFlux “second method”, one big season)
Nighttime filtering is critical: SW_IN < 10 W/m2 selects purely dark conditions where respiration is the only flux component, free from photosynthetic variability.
See also
UstarBootstrapThresholdsMulti-year sliding-window bootstrap wrapper.
Example
See examples/flux/lowres/flux_ustar_mp_detection.py for complete examples of USTAR threshold detection using the moving point method with bootstrap uncertainty estimation.
- NIGHT_THRESHOLD = 10.0¶
- MIN_SAMPLES_PERIOD = 3000¶
- MIN_SAMPLES_SEASON = 160¶
- MIN_SAMPLES_TA_CLASS = 100¶
- CORRELATION_CHECK = 0.5¶
- FIRST_USTAR_MEAN_CHECK = 0.2¶
- THRESHOLD_CHECK = 1.0¶
- WINDOW_SIZE_FORWARD_MODE = 10¶
- THRESHOLD_NOT_FOUND = 10.0¶
- __init__(df, nee_col=None, ta_col=None, ustar_col=None, swin_col=None, ta_classes_count=7, ustar_classes_count=20, forward_mode_n=2, season_groups=None, bootstrapping_times=100, random_state=42, verbose=0)[source]¶
Set up moving-point USTAR threshold detection. See the class docstring.
random_stateseeds the bootstrap resampling so a threshold is reproducible; pass None for a fresh draw on every call. It does not affectdetect(), which is deterministic. Seeding changes which resamples are drawn, not the algorithm, so ONEFlux parity is unaffected.
- detect()[source]¶
Detect USTAR thresholds for all seasons (Papale et al., 2006).
- Returns:
Seasonal thresholds with column ‘threshold’ (m/s), or NaN where detection failed. Rows: Season 1..N. Annual threshold (max across seasons) stored in
annual_thresholds_and retrievable viaget_annual_thresholds().- Return type:
- bootstrap_annual_samples(n_iter=None, rng=None)[source]¶
Bootstrap distribution of the annual (max-across-seasons) threshold.
Fast path consumed by
UstarBootstrapThresholds: build the detector once on the window, then call this to get the resampled annual thresholds directly from pre-extracted numpy arrays - avoiding aDataFrame.sample()copy and a fresh detector per iteration.- Parameters:
- Returns:
One annual threshold per successful resample (length <= n_iter).
- Return type:
- bootstrap(n_iter=None)[source]¶
Bootstrap resampling for USTAR threshold uncertainty.
Resamples the full record with replacement (matching ONEFlux: draw from all rows, keep night+valid ones), recomputes per-season and annual thresholds each iteration, and returns the resulting distributions. Operates entirely on pre-extracted numpy arrays - no per-iteration object construction or DataFrame copy.
- Parameters:
n_iter (
Optional[int]) – Number of bootstrap iterations (uses self.bootstrapping_times if None)- Returns:
Statistics (mean, std, p05, p50, p95) per season plus an ‘Annual’ row giving the distribution of the annual (max-across-seasons) threshold - the quantity used for filtering.
- Return type:
- get_annual_thresholds()[source]¶
Get annual USTAR threshold (maximum across all seasons).
- Returns:
Annual threshold with key ‘threshold’ (m/s), or NaN if detection failed.
- Return type:
Notes
Conservative approach: maximum of seasonal thresholds (Papale et al., 2006: “the whole data set is filtered according to the highest threshold found”).
- class diive.flux.UstarVekuriThresholdDetection(df, nee_col=None, ta_col=None, ustar_col=None, swin_col=None, par_col=None, n_temperature_classes=6, n_ustar_classes=20, season_groups=None, bootstrapping_times=100, random_state=42, verbose=0)[source]¶
Bases:
objectDetect USTAR threshold using quantile-based stratification approach.
This class implements a simplified USTAR threshold detection workflow that is more computationally efficient than the full ONEFlux method while maintaining robust stratification.
The key insight is stratifying by quantiles rather than equal-sized bins, ensuring each class has similar sample sizes regardless of the distribution of underlying variables.
Algorithm steps: 1. FILTER DATA: Select nighttime records only (SW_IN < 10 W/m² by default) 2. STRATIFY BY SEASON: Divide year into 4 seasons 3. STRATIFY BY TEMPERATURE: Within each season, divide into 6 quantile-based classes 4. STRATIFY BY USTAR: Within each temperature class, divide into 20 quantile-based classes 5. COMPUTE STATISTICS: Calculate mean respiration per USTAR class 6. VALIDATE: Check temperature-USTAR independence (correlation < 0.4) 7. DETECT THRESHOLD: Ascending search for flux stability point 8. AGGREGATE: Median across temperature classes gives season threshold 9. BOOTSTRAP: Repeat with resampled data for uncertainty estimation
- Parameters:
df (
DataFrame) – Time series data with datetime index and required columns: NEE, TA, USTAR, SW_INnee_col (
Optional[str]) – Net ecosystem exchange column name (auto-detected if None)ta_col (
Optional[str]) – Air temperature column name (auto-detected if None)ustar_col (
Optional[str]) – Friction velocity column name (auto-detected if None)swin_col (
Optional[str]) – Shortwave radiation column name (auto-detected if None)par_col (
Optional[str]) – Photosynthetically active radiation column (alternative nighttime filter)n_temperature_classes (
int) – Number of temperature quantile classes per seasonn_ustar_classes (
int) – Number of USTAR quantile classes per temperature classseason_groups (
Optional[List[List[int]]]) – Custom season grouping by month numbers [1-12] Default: [[12,1,2], [3,4,5], [6,7,8], [9,10,11]]bootstrapping_times (
int) – Number of bootstrap resampling iterations for uncertainty estimationverbose (
int) – Verbosity level: 0=silent, 1=progress, 2=detailed debug outputrandom_state (int | None)
- Variables:
results (pd.DataFrame) – Detected thresholds with column: ‘threshold’ Index contains season labels (Season 1, 2, 3, 4) Empty until detect() has run.
bootstrap_stats (pd.DataFrame) – Bootstrap statistics including mean, std, percentiles Empty until bootstrap() has run.
Examples
>>> import diive as dv >>> df = dv.load_exampledata_parquet_lae() >>> detector = dv.flux.UstarVekuriThresholdDetection(df) >>> thresholds = detector.detect() # then detector.summary() / detector.bootstrap()
Notes
The algorithm expects: - Pre-filtered or nighttime data (SW_IN < 10 W/m² or PAR < 20) - At least 100-200 records per season for valid detection
See also
UstarMovingPointDetectionFaithful port of the ONEFlux moving point method (forward mode).
FlagMultipleConstantUstarThresholdsApply detected USTAR thresholds to filter data.
- CORRELATION_CHECK = 0.4¶
- STABILITY_THRESHOLD = 0.95¶
- WINDOW_SIZE = 10¶
- __init__(df, nee_col=None, ta_col=None, ustar_col=None, swin_col=None, par_col=None, n_temperature_classes=6, n_ustar_classes=20, season_groups=None, bootstrapping_times=100, random_state=42, verbose=0)[source]¶
Set up Vekuri USTAR threshold detection. See the class docstring.
random_stateseeds the bootstrap resampling so a threshold is reproducible; pass None for a different draw on every call. It was previously unseeded, so the percentiles moved between runs.
- detect()[source]¶
Main entry point: Detect USTAR thresholds for all seasons.
- Returns:
Seasonal thresholds with column: ‘threshold’ Rows: Season 1, 2, 3, 4 Values: USTAR threshold in m/s, or NaN if detection failed
- Return type:
- class diive.flux.FlagMultipleConstantUstarThresholds(series, ustar, thresholds, threshold_labels, showplot=True, verbose=True, idstr=None)[source]¶
Bases:
objectApply multiple constant USTAR thresholds to filter low-turbulence flux data.
USTAR (friction velocity) threshold filtering removes unreliable nighttime flux measurements during low-turbulence conditions when turbulent mixing is insufficient to properly represent true surface exchange. This class applies multiple threshold scenarios (e.g., 16th, 50th, 84th percentiles) to quantify uncertainty in the filtering decision.
Critical Note (FLUXNET Standard): USTAR filtering should ONLY be applied to scalar fluxes (CO2, CH4, N2O), NOT to energy fluxes (H sensible heat, LE latent heat) because advective fluxes don’t proportionally affect energy balance at night.
Deliberate deviation from ONEFlux: ONEFlux also discards the first record above the threshold that follows a period below it, to drop the CO2 that accumulated under the canopy and is flushed past the sensor in one burst (Pastorello et al. 2020, Sci Data 7:225;
nee_proc/src/dataset.c). diive keeps that record. The ONEFlux rule is the stricter one and defensible; diive favours data availability here and leaves the trade-off to the user, who can drop those records afterwards if the burst matters for their analysis. Everything else about the comparison follows ONEFlux, including rejecting a record whose USTAR is missing. A threshold of 0 (CUT_NONEfor H and LE) means no u* filtering and rejects nothing.- Parameters:
series – pandas Series containing flux data
ustar – pandas Series containing USTAR (friction velocity) data
thresholds – list of float threshold values (e.g., [0.05, 0.07, 0.09])
threshold_labels – list of str labels for each threshold scenario
showplot (
bool) – If True, displays filtering results. Default True.verbose (
bool) – If True, prints filtering statistics. Default True.idstr (
str) – Optional identifier string for output columns
Example
See examples/flux/postprocessingchain/postprocessingchain_composable.py for complete examples of USTAR threshold detection and data filtering.
- __init__(series, ustar, thresholds, threshold_labels, showplot=True, verbose=True, idstr=None)[source]¶
Set up flagging for several constant USTAR thresholds. See the class docstring for parameters.
- class diive.flux.FlagMultipleVariableUstarThresholds(series, ustar, threshold_series, showplot=True, verbose=True, idstr=None)[source]¶
Bases:
objectApply multiple time-varying USTAR thresholds (e.g. per-year, VUT) to filter flux data.
Variable-threshold counterpart of
FlagMultipleConstantUstarThresholds: instead of one scalar per scenario, each scenario carries a full per-record threshold Series (aligned toseries/ustar). This is what the FLUXNET/ONEFlux VUT (Variable U* Threshold) approach needs — each year (or any sub-period) filtered by its own threshold. A constant threshold is just a constant Series, so this class can also express CUT scenarios when CUT and VUT are applied together.The element-wise comparison
ustar >= thresholdis identical to the constant case; only the threshold is broadcast per record rather than as a single value. That includes the deliberate deviation from ONEFlux described inFlagMultipleConstantUstarThresholds: the first record above the threshold after a period below it is kept, not discarded.- Parameters:
series – flux data (pandas Series).
ustar – USTAR / friction velocity (pandas Series).
threshold_series (
dict) – mapping{scenario_label: per_record_threshold_Series}. Each threshold Series must align toseries.indexand contain no NaN (the caller resolves any missing periods first).showplot (
bool) – as inFlagMultipleConstantUstarThresholds.verbose (
bool) – as inFlagMultipleConstantUstarThresholds.idstr (
str) – as inFlagMultipleConstantUstarThresholds.
- __init__(series, ustar, threshold_series, showplot=True, verbose=True, idstr=None)[source]¶
Set up flagging for per-record (variable) USTAR thresholds. See the class docstring.
- property results: DataFrame¶
Return the results DataFrame (flux, USTAR and one flag column per scenario).
- class diive.flux.FlagSingleConstantUstarThreshold(series, ustar, threshold, idstr=None, showplot=False, verbose=False)[source]¶
Bases:
FlagBaseFlag records below a single constant USTAR threshold. See
__init__().- Parameters:
- flagid = 'USTAR'¶
- __init__(series, ustar, threshold, idstr=None, showplot=False, verbose=False)[source]¶
Flag records below a single constant USTAR threshold.
A record is kept only where
ustar >= thresholdcan be shown, so a record with no USTAR measurement is rejected (as in ONEFlux, where a missing USTAR isINVALID_VALUEand therefore below every threshold). diive deliberately does not apply ONEFlux’s follow-up rule that also discards the first record above the threshold after a period below it — seeFlagMultipleConstantUstarThresholdsfor why.A threshold of 0 or below means no u* filtering and flags nothing, not even records without USTAR. This is the setting for H and LE (
thresholds=[0],threshold_labels=['CUT_NONE']).- Parameters:
series (
Series) – Flux series to flag.ustar (
Series) – Friction velocity (USTAR) series aligned to series.threshold (
float) – Records withustar < threshold, or with no USTAR at all, are flagged as rejected. A per-record threshold Series is also accepted. Records with a threshold of 0 or below are never rejected.idstr (
str) – Optional identifier string appended to the flag column name.showplot (
bool) – If True, show the default rejected-values plot.verbose (
bool) – If True, print detection statistics.
- class diive.flux.UstarThresholdConstantScenarios(series, ustar, swinpot)[source]¶
Bases:
objectCheck impact of different constant USTAR thresholds on available data
Constant means that the threshold is the same for all data, e.g. the same for all years. …
- Methods:
calc(ustarthresholds – list=None, showplot: bool = False, verbose: bool = False): Creates timeseries of series in after application of different USTAR thresholds given in ustarthresholds.
- Parameters:
- Properties:
- scenariosdf: DataFrame of the timeseries of series in different USTAR
scenarios. Records of series where USTAR was below the respective threshold or missing are set to missing.
- __init__(series, ustar, swinpot)[source]¶
Set up constant-threshold USTAR scenario testing. See the class docstring.
- property scenariosdf¶
Return timeseries of series of each USTAR threshold, values below the respective threshold were removed