Data Analysis Functions
Module containing functions for analysing, filtering, transforming, and processing climate data (written for use in e.g. analysis_T.ipynb, analysis_M.ipynb, analysis_MT.ipynb) .
dod2k_utilities.ut_analysis
Author: Lucie Luecke (includes functions by Feng Zhu)
Provides functions for filtering, homogenising, manipulating and analysing data(frames).
19/12/2025 last updated for publication for dod2k v2.0
PCA(covariance)
Perform Principal Component Analysis using singular value decomposition (SVD).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
covariance
|
ndarray
|
Covariance matrix of shape (n_records, n_records). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
eigenvalues |
ndarray
|
Eigenvalues from SVD (singular values), sorted in descending order as returned by numpy's SVD implementation. |
eigenvectors |
ndarray
|
Right singular vectors (Vh) corresponding to the eigenvectors of the covariance matrix. |
Notes
This function performs PCA on paleoclimate records. The SVD decomposition yields: - U: left singular vectors (not returned) - s: singular values (returned as eigenvalues) - Vh: right singular vectors (returned as eigenvectors)
The eigenvectors can be used to project the data onto principal components. The eigenvalues indicate the variance explained by each component.
Source code in dod2k_utilities/ut_analysis.py
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 | |
add_auxvars_plot_summary(df_filtered, key, mincount=0, col='k', **kwargs)
Add auxiliary variables to the DataFrame and generate summary plots.
Adds 'length', 'miny', and 'maxy' columns, then plots coverage, resolution, and length distributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df_filtered
|
DataFrame
|
DataFrame containing 'year' and 'paleoData_values'. |
required |
key
|
str
|
Title for plots and archiveType label. |
required |
mincount
|
int
|
Minimum count threshold for plotting resolution and length. Default is 0. |
0
|
col
|
str
|
Color for plotting. Default is 'k' (black). |
'k'
|
**kwargs
|
dict
|
Additional keyword arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The DataFrame with added auxiliary columns ('length', 'miny', 'maxy'). |
Notes
This function modifies the DataFrame in place by adding new columns and
also calls add_resolution_to_df to compute resolution.
Source code in dod2k_utilities/ut_analysis.py
453 454 455 456 457 458 459 460 461 462 463 464 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 | |
add_resolution_to_df(df, print_output=False, plot_output=False)
Compute the time resolution of each record and store in the DataFrame.
Sorts the time and data values, then calculates the resolution as the unique differences between consecutive years.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing 'year' and 'paleoData_values'. |
required |
print_output
|
bool
|
If True, prints debug information. Default is False. |
False
|
plot_output
|
bool
|
Currently unused; reserved for future plotting. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
None
|
The function updates the 'resolution' column of the DataFrame in place. |
Source code in dod2k_utilities/ut_analysis.py
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 | |
add_zscores_plot(df, key, plot_output=True)
Add z-scores of paleoData_values to the DataFrame.
This function calculates the z-score for each record and adds a new column 'paleoData_zscores'. Optionally plots the original values and z-scores.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing 'year' and 'paleoData_values'. |
required |
key
|
str
|
Title for the plot. |
required |
plot_output
|
bool
|
If True, generates a diagnostic plot. Default is True. |
True
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
The DataFrame with an added 'paleoData_zscores' column. |
Source code in dod2k_utilities/ut_analysis.py
410 411 412 413 414 415 416 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 | |
calc_covariance_matrix(df)
Compute the covariance matrix and overlapping years for all records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing homogenised z-score arrays ( |
required |
Returns:
| Name | Type | Description |
|---|---|---|
covariance |
ndarray
|
Covariance matrix of shape (n_records, n_records) between all records. |
overlap |
ndarray
|
Matrix of shape (n_records, n_records) containing the number of overlapping years between each pair of records. |
Source code in dod2k_utilities/ut_analysis.py
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 | |
calc_z_score(x)
Calculate the z-score of paleoData_values for a single record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Series
|
Series representing a single record with a 'paleoData_values' array. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Z-scored values of the record. |
Source code in dod2k_utilities/ut_analysis.py
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | |
convert_subannual_to_annual_res(df)
Convert sub-annual data to annual averages.
For each record in the DataFrame, this function computes yearly averages of the 'paleoData_values' and replaces the original 'year' array with integer years.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing 'year' and 'paleoData_values' columns, where 'year' may contain sub-annual (fractional) time values. |
required |
Returns:
| Type | Description |
|---|---|
None
|
The function modifies the DataFrame in place. |
Notes
For each record: - Years are floored to get integer year values - Data values are averaged within each integer year - Both 'year' and 'paleoData_values' columns are replaced with annual values
Source code in dod2k_utilities/ut_analysis.py
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 | |
filter_data_availability(df, mny, mxy)
Filter records based on data availability within a given year range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing a 'year' column, where each entry is an array-like of years available for the record. |
required |
mny
|
int
|
Start year of the range. |
required |
mxy
|
int
|
End year of the range. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A filtered DataFrame containing only records that have data available
between |
Notes
Removes records that have no data within the specified year range. Prints the indices of removed records and summary statistics.
Source code in dod2k_utilities/ut_analysis.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
filter_record_length(df, nyears, mny, mxy)
Filter records based on the number of years with data in a given range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing a 'year' column, where each entry is an array-like of years available for the record. |
required |
nyears
|
int
|
Minimum number of years required within the specified range. |
required |
mny
|
int
|
Start year of the range. |
required |
mxy
|
int
|
End year of the range. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A filtered DataFrame containing only records with at least |
Notes
Records are dropped in-place if they don't meet the minimum year requirement. Prints the number of records kept and excluded after filtering.
Source code in dod2k_utilities/ut_analysis.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
filter_resolution(df, maxres)
Filter records in a DataFrame based on maximum resolution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing a 'resolution' column, where each entry is a list of numeric resolution values. |
required |
maxres
|
int or float
|
Maximum allowed resolution. Records with all resolution values less than
or equal to |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A filtered DataFrame containing only records with resolution <= maxres. |
Notes
Prints the number of records kept and excluded after filtering.
Source code in dod2k_utilities/ut_analysis.py
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 | |
find_nearest2d(da, lat, lon, lat_name='lat', lon_name='lon', new_dim='sites', r=1)
Find nearest valid grid points in 2D xarray DataArray to given coordinates.
Selects the nearest grid point to specified lat/lon coordinates. If the nearest point is NaN, searches within a radius r for the closest valid point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray
|
Input DataArray with latitude and longitude dimensions. |
required |
lat
|
float or array - like
|
Target latitude(s) in decimal degrees. |
required |
lon
|
float or array - like
|
Target longitude(s) in decimal degrees. |
required |
lat_name
|
str
|
Name of latitude dimension in da. Default is 'lat'. |
'lat'
|
lon_name
|
str
|
Name of longitude dimension in da. Default is 'lon'. |
'lon'
|
new_dim
|
str
|
Name for new dimension when concatenating results for multiple sites. Default is 'sites'. |
'sites'
|
r
|
float
|
Search radius in degrees when nearest point is invalid. Default is 1. |
1
|
Returns:
| Type | Description |
|---|---|
DataArray
|
DataArray values at nearest valid grid points. If multiple lat/lon pairs provided, returns concatenated results along new_dim. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no valid values found within search radius. |
Notes
Author: Feng Zhu
The function uses great circle distance to find the closest valid grid point when the simple nearest neighbor is NaN.
Examples:
>>> # Extract data at single location
>>> temp_site = find_nearest2d(temp_data, 52.52, 13.40)
>>> # Extract data at multiple locations
>>> lats = [40.7, 51.5, 48.8]
>>> lons = [-74.0, -0.1, 2.3]
>>> temps_sites = find_nearest2d(temp_data, lats, lons, r=2)
Source code in dod2k_utilities/ut_analysis.py
786 787 788 789 790 791 792 793 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 843 844 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 | |
find_shared_period(df, minmax=False, time='year', data='paleoData_zscores')
Determine the shared time period across all records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing the records with time and data columns. |
required |
minmax
|
tuple or list
|
Year range to use for plotting if no shared period exists. Default is False. |
False
|
time
|
str
|
Name of the column containing the time axis. Default is 'year'. |
'year'
|
data
|
str
|
Name of the data column to plot if no shared period exists. Default is 'paleoData_zscores'. |
'paleoData_zscores'
|
Returns:
| Name | Type | Description |
|---|---|---|
miny |
int or float
|
Minimum year of the shared period, or np.nan if none. |
maxy |
int or float
|
Maximum year of the shared period, or np.nan if none. |
Source code in dod2k_utilities/ut_analysis.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | |
fraction_of_explained_var(covariance, eigenvalues, n_recs, title='', db_name='', col='tab:blue')
Compute and plot the fraction of variance explained by principal components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
covariance
|
ndarray
|
Covariance matrix of the records. |
required |
eigenvalues
|
ndarray
|
Eigenvalues from PCA/SVD. |
required |
n_recs
|
int
|
Number of records. |
required |
title
|
str
|
Title used in the plot. Default is empty string. |
''
|
db_name
|
str
|
Name suffix for saving the figure. Default is empty string. |
''
|
col
|
str
|
Color for plotting. Default is 'tab:blue'. |
'tab:blue'
|
Returns:
| Name | Type | Description |
|---|---|---|
frac_explained_var |
ndarray
|
Fraction of variance explained by each principal component. |
Notes
Creates a dual-axis plot showing both individual and cumulative fraction
of explained variance. The plot is saved using utf.figsave.
Source code in dod2k_utilities/ut_analysis.py
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 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 | |
gcd(lat1, lon1, lat2, lon2, radius=6378.137)
Calculate 2D great circle distance between points on Earth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lat1
|
float or array - like
|
Latitude(s) of first point(s) in decimal degrees. |
required |
lon1
|
float or array - like
|
Longitude(s) of first point(s) in decimal degrees. |
required |
lat2
|
float or array - like
|
Latitude(s) of second point(s) in decimal degrees. |
required |
lon2
|
float or array - like
|
Longitude(s) of second point(s) in decimal degrees. |
required |
radius
|
float
|
Earth radius in kilometers. Default is 6378.137 km (equatorial radius). |
6378.137
|
Returns:
| Type | Description |
|---|---|
float or ndarray
|
Great circle distance(s) in kilometers. |
Notes
Uses the haversine formula for calculating distances on a sphere. Supports vectorized operations for arrays of coordinates.
Examples:
>>> # Distance between London and Paris
>>> gcd(51.5074, -0.1278, 48.8566, 2.3522)
343.5...
>>> # Multiple distances at once
>>> lats1 = [40.7, 51.5, 48.8]
>>> lons1 = [-74.0, -0.1, 2.3]
>>> gcd(lats1, lons1, 52.52, 13.40) # Distances to Berlin
array([6385.7..., 930.3..., 877.4...])
Source code in dod2k_utilities/ut_analysis.py
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 | |
homogenise_data_dimensions(df, years_hom, title='', print_output=False, plot_output=True)
Homogenise the data arrays to a uniform time coordinate.
This function assigns paleoData values and z-scores from each record in the
DataFrame to a homogenised time axis (years_hom). Missing data are masked
as zeros using numpy masked arrays. Optional plotting and printing of
intermediate checks is provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing the records with columns: - 'year': array-like of years - 'paleoData_values': array-like of values - 'paleoData_zscores': array-like of z-scores |
required |
years_hom
|
array - like
|
Homogenised time coordinate to which all records are aligned. |
required |
title
|
str
|
Title used for the plot if |
''
|
print_output
|
bool
|
If True, prints debug information about array sizes and resolutions. Default is False. |
False
|
plot_output
|
bool
|
If True, generates diagnostic plots showing the homogenised and original paleoData values and z-scores. Default is True. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
paleoData_values_hom |
MaskedArray
|
Masked array of shape (n_records, n_years) containing homogenised paleoData values. Missing values are masked. |
paleoData_zscores_hom |
MaskedArray
|
Masked array of shape (n_records, n_years) containing homogenised paleoData z-scores. Missing values are masked. |
year_hom_avbl |
list of numpy.ma.MaskedArray
|
List of length n_records containing the homogenised data arrays for paleoData_values. |
zsco_hom_avbl |
list of numpy.ma.MaskedArray
|
List of length n_records containing the homogenised data arrays for paleoData_zscores. |
Source code in dod2k_utilities/ut_analysis.py
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 207 208 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 241 242 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 271 272 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 301 302 303 304 305 | |
homogenise_time(df, mny, mxy, minres)
Homogenise the time coordinate of records in a DataFrame.
This function creates a uniform time axis from mny to mxy with
steps of minres years and prints basic information about the
homogenised timeline. It also calls find_shared_period to report
the overlapping period across all records.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing climate or archive records. Must be compatible
with |
required |
mny
|
int
|
Start year of the homogenisation period. |
required |
mxy
|
int
|
End year of the homogenisation period. |
required |
minres
|
int
|
Minimum resolution (in years) for the homogenised timeline. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
df |
DataFrame
|
The input DataFrame (unchanged in this function). |
years_hom |
ndarray
|
Array of homogenised years from |
Source code in dod2k_utilities/ut_analysis.py
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 | |
smooth(data, time, res)
Apply simple moving average smoothing to time series data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ndarray
|
Time series data array (1D or 2D). If 2D, smoothing is applied along the first dimension (rows). |
required |
time
|
ndarray
|
Corresponding time axis array. Should have same length as first dimension of data. |
required |
res
|
int
|
Window size for smoothing (number of points). The moving average uses non-overlapping windows. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
smooth_time |
list
|
Smoothed time axis values, containing the mean time value for each window. |
smooth_data |
list
|
Smoothed data values, containing the mean data value for each window. |
Notes
This function uses a simple non-overlapping moving average with
window size res. The output length will be approximately
len(data) / res (rounded down).
Source code in dod2k_utilities/ut_analysis.py
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 709 710 711 | |