.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/fits/fit_binfittercp.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_fits_fit_binfittercp.py: ================================== Binned Curve Fitting (BinFitterCP) ================================== Demonstrates fitting polynomial functions to binned time series data with confidence and prediction intervals. BinFitterCP is useful for analyzing physical relationships and driver-response functions in environmental data. This example shows how to: - Bin data into quantile bins (about the same number of records per bin) - Fit polynomial equations (linear, quadratic, cubic) - Extract and interpret results (fit parameters, confidence intervals, binned data) - Visualize fitted curves with uncertainty bands Best for: Understanding nonlinear relationships between variables with quantified uncertainty. .. GENERATED FROM PYTHON SOURCE LINES 21-30 Overview: Why Binned Fitting? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Binning data before fitting provides several benefits: 1. **Noise reduction** — Averaging within bins reduces scatter 2. **Relationship clarity** — Nonlinear patterns become visible 3. **Weighted fitting** — Each bin contributes equally regardless of density 4. **Uncertainty quantification** — Confidence and prediction intervals 5. **Visual clarity** — Binned points are easier to interpret than raw scatter .. GENERATED FROM PYTHON SOURCE LINES 32-35 Load and Prepare Data ^^^^^^^^^^^^^^^^^^^^^ Filter for specific conditions (summer daytime with adequate radiation). .. GENERATED FROM PYTHON SOURCE LINES 35-57 .. code-block:: Python import diive as dv # Load example data df = dv.load_exampledata_parquet() # Filter for summer months (June-September) with adequate radiation df = df.loc[(df.index.month >= 6) & (df.index.month <= 9)].copy() df = df.loc[df['Rg_f'] > 20] # Daytime data only print(f"Data Summary:") print(f" Records: {len(df)}") print(f" Time range: {df.index.min().date()} to {df.index.max().date()}") # Select variables for analysis xcol = 'Tair_f' # Air temperature (°C) ycol = 'VPD_f' # Vapor pressure deficit (hPa) print(f"\nVariables:") print(f" X (independent): {xcol} - {df[xcol].min():.1f} to {df[xcol].max():.1f} °C") print(f" Y (dependent): {ycol} - {df[ycol].min():.2f} to {df[ycol].max():.2f} hPa") .. rst-class:: sphx-glr-script-out .. code-block:: none > Loaded .parquet file /home/docs/checkouts/diive/checkouts/latest/diive/configs/exampledata/exampledat a_PARQUET_CH-DAV_FP2022.5_2013-2022_ID20230206154316_30MIN.parquet (0.050 seconds). Data Summary: Records: 31230 Time range: 2013-06-01 to 2022-09-30 Variables: X (independent): Tair_f - -3.1 to 28.7 °C Y (dependent): VPD_f - 0.00 to 32.12 hPa .. GENERATED FROM PYTHON SOURCE LINES 58-61 Create and Run Fitter ^^^^^^^^^^^^^^^^^^^^^ Configure BinFitterCP with binning and fitting parameters. .. GENERATED FROM PYTHON SOURCE LINES 61-81 .. code-block:: Python bf = dv.analysis.BinFitterCP( df=df, xcol=xcol, # X variable (predictor) ycol=ycol, # Y variable (response) predict_max_x=None, # Use data max for predictions predict_min_x=None, # Use data min for predictions n_predictions=1000, # Number of fit points for smooth curve n_bins_x=10, # Divide X data into 10 quantile bins bins_y_agg='mean', # Aggregate Y values by mean per bin ('mean' or 'median') fit_type='quadratic_offset' # Polynomial: y = ax² + bx + c ) bf.run() print(f"\nFitting Configuration:") print(f" Number of bins: 10") print(f" Aggregation method: mean") print(f" Fit type: quadratic_offset (y = ax² + bx + c)") .. rst-class:: sphx-glr-script-out .. code-block:: none Fitting Configuration: Number of bins: 10 Aggregation method: mean Fit type: quadratic_offset (y = ax² + bx + c) .. GENERATED FROM PYTHON SOURCE LINES 82-85 Access Fit Results ^^^^^^^^^^^^^^^^^^ Results are stored in a dictionary accessible via get_results(). .. GENERATED FROM PYTHON SOURCE LINES 85-91 .. code-block:: Python results = bf.get_results() print(f"\nAvailable results:") print(f" Keys: {list(results.keys())}") .. rst-class:: sphx-glr-script-out .. code-block:: none Available results: Keys: ['input_df', 'xvar', 'yvar', 'fit_df', 'fit_equation', 'fit_equation_str', 'fit_type', 'fit_params_opt', 'fit_params_cov', 'fit_r2', 'bin_df', 'bins_x', 'bins_y', 'n_vals_per_bin'] .. GENERATED FROM PYTHON SOURCE LINES 92-95 Examine Input Data and Binning ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ See how the original data was binned into groups. .. GENERATED FROM PYTHON SOURCE LINES 95-115 .. code-block:: Python input_df = results['input_df'] print(f"\nInput Data (with bin assignments):") print(f" Shape: {input_df.shape}") print(f" Columns: {list(input_df.columns)}") print(f" First 5 rows:") print(input_df.head()) print(f"\nBinned X values (means per bin):") bins_x = results['bins_x'] print(f" {bins_x.values}") print(f"\nBinned Y values (means per bin):") bins_y = results['bins_y'] print(f" {bins_y.values}") print(f"\nValues per bin:") n_vals = results['n_vals_per_bin'] print(f" Min: {int(n_vals['min'])}, Max: {int(n_vals['max'])}") .. rst-class:: sphx-glr-script-out .. code-block:: none Input Data (with bin assignments): Shape: (31230, 3) Columns: ['Tair_f', 'VPD_f', 'group'] First 5 rows: Tair_f VPD_f group TIMESTAMP_MIDDLE 2013-06-01 05:15:00 0.100 0.082 (-3.0909999999999997, 6.858] 2013-06-01 05:45:00 -0.200 0.011 (-3.0909999999999997, 6.858] 2013-06-01 06:15:00 0.000 0.020 (-3.0909999999999997, 6.858] 2013-06-01 06:45:00 0.233 0.062 (-3.0909999999999997, 6.858] 2013-06-01 07:15:00 0.333 0.065 (-3.0909999999999997, 6.858] Binned X values (means per bin): [ 4.74938168 7.97715651 9.76241329 11.1900638 12.58768212 14.16395609 15.76245811 17.4405537 19.36710961 22.61115343] Binned Y values (means per bin): [ 1.13526961 1.63216952 2.33286969 3.15543815 4.34440614 5.99933462 7.81956579 10.04197435 12.49759531 17.78006406] Values per bin: Min: 3088, Max: 3150 .. GENERATED FROM PYTHON SOURCE LINES 116-119 Examine Fit Equation and Parameters ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Extract the fitted polynomial equation and its parameters. .. GENERATED FROM PYTHON SOURCE LINES 119-138 .. code-block:: Python fit_eq_str = results['fit_equation_str'] fit_type = results['fit_type'] params_opt = results['fit_params_opt'] params_cov = results['fit_params_cov'] r2 = results['fit_r2'] print(f"\nFit Equation: {fit_eq_str}") print(f"Fit Type: {fit_type}") print(f"\nOptimal Parameters:") for i, p in enumerate(params_opt): print(f" Parameter {i}: {p:.6f}") print(f"\nParameter Covariance Matrix:") print(params_cov) print(f"\nGoodness of Fit:") print(f" R²: {r2:.6f}") .. rst-class:: sphx-glr-script-out .. code-block:: none Fit Equation: y = 0.0503x^2-0.4238x+1.8422 Fit Type: quadratic_offset Optimal Parameters: Parameter 0: 0.050262 Parameter 1: -0.423810 Parameter 2: 1.842239 Parameter Covariance Matrix: [[ 4.97036666e-06 -1.36281813e-04 8.02001815e-04] [-1.36281813e-04 3.89109034e-03 -2.40837962e-02] [ 8.02001815e-04 -2.40837962e-02 1.61905323e-01]] Goodness of Fit: R²: 0.998909 .. GENERATED FROM PYTHON SOURCE LINES 139-142 Examine Fitted Curve with Intervals ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The fit_df contains the smooth fitted curve and uncertainty bands. .. GENERATED FROM PYTHON SOURCE LINES 142-160 .. code-block:: Python fit_df = results['fit_df'] print(f"\nFitted Curve Data:") print(f" Shape: {fit_df.shape}") print(f" Columns: {list(fit_df.columns)}") print(f"\nFirst 5 fitted values:") print(fit_df.head()) print(f"\nLast 5 fitted values (high X end):") print(fit_df.tail()) print(f"\nInterval Interpretation:") print(f" fit_y: Fitted mean value ± standard error") print(f" nom: Nominal (central) fitted value") print(f" nom_lower_ci95 / nom_upper_ci95: 95% confidence interval (mean prediction)") print(f" lower_predband / upper_predband: 95% prediction interval (individual values)") .. rst-class:: sphx-glr-script-out .. code-block:: none Fitted Curve Data: Shape: (1000, 8) Columns: ['fit_x', 'fit_y', 'std', 'nom', 'lower_predband', 'upper_predband', 'nom_lower_ci95', 'nom_upper_ci95'] First 5 fitted values: fit_x fit_y ... nom_lower_ci95 nom_upper_ci95 0 4.749382 0.96+/-0.17 ... 0.621306 1.304995 1 4.767261 0.96+/-0.17 ... 0.623513 1.304738 2 4.785141 0.97+/-0.17 ... 0.625749 1.304516 3 4.803021 0.97+/-0.17 ... 0.628013 1.304330 4 4.820900 0.97+/-0.17 ... 0.630305 1.304180 [5 rows x 8 columns] Last 5 fitted values (high X end): fit_x fit_y ... nom_lower_ci95 nom_upper_ci95 995 22.539635 17.82+/-0.17 ... 17.487118 18.162341 996 22.557514 17.86+/-0.17 ... 17.518867 18.196493 997 22.575394 17.89+/-0.17 ... 17.550644 18.230680 998 22.593274 17.92+/-0.17 ... 17.582449 18.264903 999 22.611153 17.96+/-0.17 ... 17.614282 18.299163 [5 rows x 8 columns] Interval Interpretation: fit_y: Fitted mean value ± standard error nom: Nominal (central) fitted value nom_lower_ci95 / nom_upper_ci95: 95% confidence interval (mean prediction) lower_predband / upper_predband: 95% prediction interval (individual values) .. GENERATED FROM PYTHON SOURCE LINES 161-164 Comparison: Central Estimate vs Intervals ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Understand the difference between confidence and prediction intervals. .. GENERATED FROM PYTHON SOURCE LINES 164-177 .. code-block:: Python idx_mid = len(fit_df) // 2 # Middle of the curve row = fit_df.iloc[idx_mid] print(f"\nAt X ~= {row['fit_x']:.2f}:") print(f" Fitted value (nom): {row['nom']:.3f}") print(f" Std error: {row['std']:.3f}") print(f" 95% CI (confidence interval): [{row['nom_lower_ci95']:.3f}, {row['nom_upper_ci95']:.3f}]") print(f" (Uncertainty in the mean fit)") print(f" 95% PI (prediction interval): [{row['lower_predband']:.3f}, {row['upper_predband']:.3f}]") print(f" (Uncertainty for individual new values)") print(f"\nNote: Prediction interval is always wider than confidence interval") .. rst-class:: sphx-glr-script-out .. code-block:: none At X ~= 13.69: Fitted value (nom): 5.459 Std error: 0.087 95% CI (confidence interval): [5.288, 5.631] (Uncertainty in the mean fit) 95% PI (prediction interval): [4.957, 5.962] (Uncertainty for individual new values) Note: Prediction interval is always wider than confidence interval .. GENERATED FROM PYTHON SOURCE LINES 178-181 Create Visualization ^^^^^^^^^^^^^^^^^^^^ Generate a plot showing binned data, fit curve, and uncertainty bands. .. GENERATED FROM PYTHON SOURCE LINES 181-204 .. code-block:: Python print(f"\nGenerating visualization...") bf.showplot( show_unbinned_data=True, # Show original scatter show_bin_variation=True, # Show variation within bins highlight_year=None, # Don't highlight specific year bin_size=90, # Bin marker size bin_color='black', # Bin point color bin_edgecolor='None', # No edge around points bin_alpha=0.9, # Transparency of bins fitline_color='red', # Fitted curve color showfit=True, # Show the fit curve show_prediction_interval=True, # Show uncertainty bands xlim=None, # Auto-scale X axis ylim=None, # Auto-scale Y axis title='Air Temperature vs Vapor Pressure Deficit\n(Summer Daytime, 2013-2022)', xlabel='Air Temperature (°C)', ylabel='VPD (hPa)' ) print("[Plot displayed]") .. image-sg:: /auto_examples/fits/images/sphx_glr_fit_binfittercp_001.png :alt: Air Temperature vs Vapor Pressure Deficit (Summer Daytime, 2013-2022) :srcset: /auto_examples/fits/images/sphx_glr_fit_binfittercp_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none Generating visualization... [Plot displayed] .. GENERATED FROM PYTHON SOURCE LINES 205-208 Summary ^^^^^^^ Key takeaways from binned curve fitting: .. GENERATED FROM PYTHON SOURCE LINES 208-230 .. code-block:: Python print(f"\n" + "=" * 60) print(f"SUMMARY") print(f"=" * 60) print(f"\n1. DATA BINNING:") print(f" - Divided {len(df)} records into 10 quantile bins") print(f" - Each bin contains {int(n_vals['min'])}-{int(n_vals['max'])} values") print(f"\n2. RELATIONSHIP:") print(f" - Equation: {fit_eq_str}") print(f" - Explains {100 * r2:.2f}% of variance (R²)") print(f"\n3. UNCERTAINTY:") print(f" - Confidence interval: Uncertainty in the fitted mean") print(f" - Prediction interval: Uncertainty for future observations") print(f" - Both reflect inherent variability in the data") print(f"\n4. APPLICATIONS:") print(f" - Parameterize ecosystem models") print(f" - Understand driver-response relationships") print(f" - Compare relationships across sites/periods") print(f" - Generate synthetic data within uncertainty bounds") .. rst-class:: sphx-glr-script-out .. code-block:: none ============================================================ SUMMARY ============================================================ 1. DATA BINNING: - Divided 31230 records into 10 quantile bins - Each bin contains 3088-3150 values 2. RELATIONSHIP: - Equation: y = 0.0503x^2-0.4238x+1.8422 - Explains 99.89% of variance (R²) 3. UNCERTAINTY: - Confidence interval: Uncertainty in the fitted mean - Prediction interval: Uncertainty for future observations - Both reflect inherent variability in the data 4. APPLICATIONS: - Parameterize ecosystem models - Understand driver-response relationships - Compare relationships across sites/periods - Generate synthetic data within uncertainty bounds .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.572 seconds) .. _sphx_glr_download_auto_examples_fits_fit_binfittercp.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: fit_binfittercp.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: fit_binfittercp.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: fit_binfittercp.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_