Advanced Analysis Methods
Advanced analysis methods for weather and air quality, including temporal resampling, climatology, and Kolmogorov-Zurbenko (KZ) filters.
Advanced analysis methods for weather and air quality (Aero Protocol Compliant).
anomalies(data, freq='month', dim='time')
Compute anomalies by subtracting the climatology (Aero Protocol).
Parameters
data : xarray.DataArray or xarray.Dataset Input data with a time-like coordinate. freq : str, optional Climatology frequency ('season', 'month', 'dayofyear', 'hour'). Default is 'month'. dim : str, optional Dimension along which to compute the anomalies. Default is 'time'.
Returns
Union[xr.DataArray, xr.Dataset] Anomalies (data - climatology).
Examples
import xarray as xr import pandas as pd import numpy as np times = pd.date_range("2020-01-01", periods=366*2, freq="D") da = xr.DataArray(np.random.rand(732), coords={"time": times}, dims="time") monthly_anom = anomalies(da, freq="month")
Source code in src/monet_stats/analysis.py
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 | |
climatology(data, freq='season', method='mean', dim='time')
Compute climatological statistics (Aero Protocol).
Parameters
data : xarray.DataArray or xarray.Dataset Input data with a time-like coordinate. freq : str, optional Climatology frequency ('season', 'month', 'dayofyear', 'hour'). Default is 'season'. method : str, optional Statistical method to apply ('mean', 'std', 'min', 'max', 'median'). Default is 'mean'. dim : str, optional Dimension along which to compute climatology. Default is 'time'.
Returns
Union[xr.DataArray, xr.Dataset] Climatological statistics.
Examples
import xarray as xr import pandas as pd import numpy as np times = pd.date_range("2020-01-01", periods=365*2, freq="D") da = xr.DataArray(np.random.rand(730), coords={"time": times}, dims="time") seasonal_climo = climatology(da, freq="season", method="mean")
Source code in src/monet_stats/analysis.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | |
detrend(data, method='linear', dim='time')
Remove trend from data (Aero Protocol).
Parameters
data : xarray.DataArray or xarray.Dataset Input data. method : str, optional Detrending method ('linear', 'constant'). - 'linear': least-squares linear detrend. - 'constant': subtract mean. Default is 'linear'. dim : str, optional Dimension along which to detrend. Default is 'time'.
Returns
Union[xr.DataArray, xr.Dataset] Detrended data.
Examples
import xarray as xr import numpy as np da = xr.DataArray(np.arange(10) + np.random.randn(10), dims="time") detrended = detrend(da, method="linear")
Source code in src/monet_stats/analysis.py
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 | |
diurnal_cycle(data, method='mean', dim='time')
Compute the diurnal cycle (average hourly profile) (Aero Protocol).
Parameters
data : xarray.DataArray or xarray.Dataset Input data with a time-like coordinate. method : str, optional Statistical method to apply ('mean', 'median', 'std'). Default is 'mean'. dim : str, optional Dimension along which to compute the cycle. Default is 'time'.
Returns
Union[xr.DataArray, xr.Dataset] Diurnal cycle (24 values, one for each hour).
Examples
import xarray as xr import pandas as pd import numpy as np times = pd.date_range("2020-01-01", periods=24*10, freq="h") da = xr.DataArray(np.random.rand(240), coords={"time": times}, dims="time") cycle = diurnal_cycle(da, method="mean")
Source code in src/monet_stats/analysis.py
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
exceedance_count(data, threshold, dim='time', axis=None)
Count exceedances of a threshold (Aero Protocol).
Parameters
data : xarray.DataArray, xarray.Dataset, or numpy.ndarray Input data. threshold : float Value above which an exceedance is counted. dim : str, optional Dimension along which to count exceedances (xarray only). Default is 'time'. axis : int, optional Axis along which to count exceedances (numpy only). Default is None (all).
Returns
Union[xr.DataArray, xr.Dataset, np.ndarray] Number of exceedances.
Examples
import xarray as xr da = xr.DataArray([1, 5, 2, 6, 3]) exceedance_count(da, threshold=4)
array(2)
Source code in src/monet_stats/analysis.py
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | |
fft_analysis(data, dim='time', output='psd')
Perform Fast Fourier Transform (FFT) analysis (Aero Protocol).
Parameters
data : xarray.DataArray Input data. dim : str, optional Dimension along which to perform FFT. Default is 'time'. output : str, optional Type of output to return: - 'psd': Power Spectral Density (magnitude squared of FFT). - 'magnitude': Magnitude of FFT. - 'complex': Complex FFT results. Default is 'psd'.
Returns
xarray.DataArray FFT results. The coordinate for 'dim' is replaced by frequency indices.
Examples
import xarray as xr import numpy as np t = np.linspace(0, 10, 100) signal = np.sin(2 * np.pi * 1.5 * t) # 1.5 Hz signal da = xr.DataArray(signal, coords={"time": t}, dims="time") psd = fft_analysis(da, dim="time", output="psd")
Source code in src/monet_stats/analysis.py
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 | |
kz_filter(data, m, k, dim='time', axis=-1)
Kolmogorov-Zurbenko (KZ) filter (Aero Protocol).
The KZ filter is a low-pass filter implemented as k iterations of a moving average of window size m.
Parameters
data : xarray.DataArray, xarray.Dataset, or numpy.ndarray Input data. m : int Window size for the moving average (must be an odd integer for symmetry). k : int Number of iterations. dim : str, optional Dimension along which to apply the filter (xarray only). Default is 'time'. axis : int, optional Axis along which to apply the filter (numpy only). Default is -1.
Returns
Union[xr.DataArray, xr.Dataset, np.ndarray] Filtered data.
Notes
The KZ filter is widely used in air quality analysis to separate different time scales in a time series (e.g., seasonal, long-term, and short-term).
Examples
import numpy as np x = np.random.rand(100) filtered = kz_filter(x, m=5, k=3)
Source code in src/monet_stats/analysis.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
mda1(data, dim='time')
Compute Maximum Daily 1-hour Average (MDA1) (Aero Protocol).
Parameters
data : xarray.DataArray or xarray.Dataset Input data. Must have hourly frequency. dim : str, optional Dimension along which to compute. Default is 'time'.
Returns
Union[xr.DataArray, xr.Dataset] MDA1 values (one per day).
Examples
import xarray as xr import pandas as pd import numpy as np times = pd.date_range("2020-01-01", periods=24*5, freq="h") da = xr.DataArray(np.random.rand(120), coords={"time": times}, dims="time") mda1_vals = mda1(da)
Source code in src/monet_stats/analysis.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 | |
mda8(data, dim='time', min_periods=6, center=False)
Compute Maximum Daily 8-hour Average (MDA8) (Aero Protocol).
Parameters
data : xarray.DataArray or xarray.Dataset Input data. Must have hourly frequency. dim : str, optional Dimension along which to compute. Default is 'time'. min_periods : int, optional Minimum number of observations for the 8-hour rolling mean. Default is 6. center : bool, optional Whether to center the 8-hour rolling window. Regulatory MDA8 (e.g., EPA) typically uses a non-centered (trailing) window. Default is False.
Returns
Union[xr.DataArray, xr.Dataset] MDA8 values (one per day).
Examples
import xarray as xr import pandas as pd import numpy as np times = pd.date_range("2020-01-01", periods=24*5, freq="h") da = xr.DataArray(np.random.rand(120), coords={"time": times}, dims="time") ozone_mda8 = mda8(da)
Source code in src/monet_stats/analysis.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 | |
monthly_climatology(data, dim='time', method='mean')
Compute monthly climatology (Aero Protocol).
Parameters
data : xarray.DataArray or xarray.Dataset Input data with a time-like coordinate. dim : str, optional Dimension along which to compute the climatology. Default is 'time'. method : str, optional Statistical method to apply ('mean', 'std', 'min', 'max', 'median'). Default is 'mean'.
Returns
Union[xr.DataArray, xr.Dataset] Monthly climatology (12 values, one for each month).
Examples
import xarray as xr import pandas as pd import numpy as np times = pd.date_range("2020-01-01", periods=366*2, freq="D") da = xr.DataArray(np.random.rand(732), coords={"time": times}, dims="time") m_climo = monthly_climatology(da)
Source code in src/monet_stats/analysis.py
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 | |
peak_timing(data, dim='time')
Identify the coordinate value of the maximum (Aero Protocol).
Parameters
data : xarray.DataArray or xarray.Dataset Input data. dim : str, optional Dimension along which to find the peak. Default is 'time'.
Returns
Union[xr.DataArray, xr.Dataset] Coordinate values where the maximum occurs.
Examples
import xarray as xr import pandas as pd times = pd.date_range("2020-01-01", periods=24, freq="h") da = xr.DataArray(np.random.rand(24), coords={"time": times}, dims="time") peak_hour = peak_timing(da, dim="time")
Source code in src/monet_stats/analysis.py
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 | |
percentile(data, q, dim='time', axis=None, **kwargs)
Compute percentiles (Aero Protocol).
Parameters
data : xarray.DataArray, xarray.Dataset, or numpy.ndarray Input data. q : float or list of float Percentile(s) to compute (0-100). dim : str, optional Dimension(s) over which to compute percentiles (xarray only). Default is 'time'. axis : int, optional Axis over which to compute percentiles (numpy only). Default is None. **kwargs : Any Additional keyword arguments passed to xarray.quantile or np.percentile.
Returns
Union[xr.DataArray, xr.Dataset, np.ndarray] Computed percentiles.
Source code in src/monet_stats/analysis.py
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | |
power_spectrum(data, dim='time', fs=1.0, window='hann', nperseg=None, **kwargs)
Compute power spectrum using Welch's method (Aero Protocol).
Welch's method computes an estimate of the power spectral density by dividing the data into overlapping segments, computing a periodogram for each segment and averaging the results.
Parameters
data : xarray.DataArray Input data. dim : str, optional Dimension along which to compute the spectrum. Default is 'time'. fs : float, optional Sampling frequency. Default is 1.0. window : str, optional Desired window to use. Default is 'hann'. nperseg : int, optional Length of each segment. Default is None (256). **kwargs : Any Additional keyword arguments passed to scipy.signal.welch.
Returns
xarray.DataArray Power spectral density. The 'dim' dimension is replaced by 'frequency'.
Examples
import xarray as xr import numpy as np t = np.linspace(0, 100, 1000) signal = np.sin(2 * np.pi * 0.1 * t) + np.random.randn(1000) * 2 da = xr.DataArray(signal, coords={"time": t}, dims="time") psd = power_spectrum(da, dim="time", fs=10.0)
Source code in src/monet_stats/analysis.py
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 | |
resample_data(data, freq='MS', method='mean', dim='time', **kwargs)
Resample data to a new temporal frequency (Aero Protocol).
Parameters
data : xarray.DataArray, xarray.Dataset, pandas.Series, or pandas.DataFrame Input data with a time-like index or coordinate. freq : str, optional Resampling frequency (e.g., 'MS' for monthly start, 'W' for weekly, 'D' for daily). Default is 'MS'. method : str, optional Statistical method to apply ('mean', 'sum', 'min', 'max', 'std', 'median'). Default is 'mean'. dim : str, optional Dimension along which to resample (xarray only). Default is 'time'. **kwargs : Any Additional keyword arguments passed to the resample method.
Returns
Union[xr.DataArray, xr.Dataset, pd.Series, pd.DataFrame] Resampled data.
Examples
import xarray as xr import pandas as pd import numpy as np times = pd.date_range("2020-01-01", periods=100, freq="D") da = xr.DataArray(np.random.rand(100), coords={"time": times}, dims="time") monthly_mean = resample_data(da, freq="MS", method="mean")
Source code in src/monet_stats/analysis.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | |
rolling_mean_24h(data, dim='time', min_periods=18, center=True)
Compute rolling 24-hour mean (commonly for PM2.5) (Aero Protocol).
Parameters
data : xarray.DataArray or xarray.Dataset Input data. Must have hourly frequency. dim : str, optional Dimension along which to compute the mean. Default is 'time'. min_periods : int, optional Minimum number of observations in window required to have a value. Default is 18 (75% of 24 hours). center : bool, optional If True, set the labels at the center of the window. Default is True.
Returns
Union[xr.DataArray, xr.Dataset] Rolling 24-hour mean.
Source code in src/monet_stats/analysis.py
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | |
rolling_mean_8h(data, dim='time', min_periods=6, center=True)
Compute rolling 8-hour mean (commonly for Ozone) (Aero Protocol).
Parameters
data : xarray.DataArray or xarray.Dataset Input data. Must have hourly frequency. dim : str, optional Dimension along which to compute the mean. Default is 'time'. min_periods : int, optional Minimum number of observations in window required to have a value. Default is 6 (75% of 8 hours). center : bool, optional If True, set the labels at the center of the window. Default is True.
Returns
Union[xr.DataArray, xr.Dataset] Rolling 8-hour mean.
Source code in src/monet_stats/analysis.py
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | |
seasonal_mean(data, dim='time', weighted=True)
Compute seasonal mean (DJF, MAM, JJA, SON) (Aero Protocol).
Parameters
data : xarray.DataArray or xarray.Dataset Input data with a time-like coordinate. dim : str, optional Dimension along which to compute the seasonal mean. Default is 'time'. weighted : bool, optional If True, weight the mean by the number of days in each month for improved scientific accuracy. Default is True.
Returns
Union[xr.DataArray, xr.Dataset] Seasonal means.
Examples
import xarray as xr import pandas as pd import numpy as np times = pd.date_range("2020-01-01", periods=366, freq="D") da = xr.DataArray(np.random.rand(366), coords={"time": times}, dims="time") s_mean = seasonal_mean(da)
Source code in src/monet_stats/analysis.py
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 | |
weighted_spatial_mean(data, lat_dim='lat', lon_dim='lon', weights=None)
Compute area-weighted spatial mean (Aero Protocol).
Supports automatic detection of 'cell_area', custom weights, or falls back to cosine-latitude weighting for regular grids.
Parameters
data : xarray.DataArray or xarray.Dataset Input data with spatial coordinates. lat_dim : str, optional Name of the latitude dimension. Default is 'lat'. lon_dim : str, optional Name of the longitude dimension. Default is 'lon'. weights : xarray.DataArray or numpy.ndarray, optional Custom weights for the mean. If None, it tries to find 'cell_area' in the data or computes cos(lat) weights.
Returns
Union[xr.DataArray, xr.Dataset] Area-weighted spatial mean.
Notes
Aero Protocol: Targets high performance via xarray.weighted and handles Dask-backed arrays lazily.
Examples
import xarray as xr import numpy as np lats = np.arange(-90, 91, 1) lons = np.arange(-180, 181, 1) da = xr.DataArray(np.ones((len(lats), len(lons))), ... coords={"lat": lats, "lon": lons}, ... dims=("lat", "lon")) spatial_mean = weighted_spatial_mean(da)
Source code in src/monet_stats/analysis.py
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 | |