Definitions
Setup and basic functions
This file contains commonly used definitions of paths and compute options, gotten from the file $HOME/.jetutils.ini if it exists, otherwise guessed.
It also contains all the constants to do physics, the common timeranges, the full names of jet variables as well as their units, default values and LaTeX symbols.
Finally, it contains a few functions that are useful all over.
Timer
dataclass
This is stolen from a gist somewhere I don't remember. Nice context manager timer.
Raises:
| Type | Description |
|---|---|
TimerError
|
|
Examples:
>>> with Timer():
... do_something_long()
"elapsed time: 5.3s"
```
Source code in jetutils/definitions.py
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 | |
__enter__()
Start a new timer as a context manager
Source code in jetutils/definitions.py
1397 1398 1399 1400 | |
__exit__(*exc_info)
Stop the context manager timer
Source code in jetutils/definitions.py
1402 1403 1404 | |
__post_init__()
Add timer to dict of timers after initialization
Source code in jetutils/definitions.py
1368 1369 1370 1371 | |
start()
Start a new timer
Source code in jetutils/definitions.py
1373 1374 1375 1376 1377 1378 | |
stop()
Stop the timer, and report the elapsed time
Source code in jetutils/definitions.py
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 | |
TimerError
Bases: Exception
A custom exception used to report errors in use of Timer class
Source code in jetutils/definitions.py
1342 1343 | |
case_insensitive_equal(str1, str2)
Returns whether two strings are equal if all letters are lowercased.
Examples:
>>> case_insensitive_equal("AbC", "aBc")
True
Source code in jetutils/definitions.py
711 712 713 714 715 716 717 718 719 720 | |
compute(obj, progress_flag=False, **kwargs)
Computes a Dask object. If a dask client named client exists in the globals, uses it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
Any
|
Dask object to force compute |
required |
progress_flag
|
bool
|
Whether to show a progress bar, by default False |
False
|
kwargs
|
Keyword arguments passed to |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
obj |
Any
|
Computed object. |
Source code in jetutils/definitions.py
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 | |
degcos(x)
Cosine of an angle expressed in degrees
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
float
|
Angle in degrees |
required |
Returns:
| Type | Description |
|---|---|
float
|
Cosine result |
Source code in jetutils/definitions.py
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | |
degsin(x)
Sine of an angle expressed in degrees
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
float
|
Angle in degrees |
required |
Returns:
| Type | Description |
|---|---|
float
|
Sine results |
Source code in jetutils/definitions.py
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | |
do_rle_fill_hole(df, condition_expr, group_by=None, hole_size=4, unwrap=False)
Wraps around polars' pl.Expr.rle() to find runs of identical values, potentially interrupted by a different value, as long as this interruption is shorter than hole_size.
It can do it for the whose DataFrame or in groups specified by group_by.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input DataFrame |
required |
condition_expr
|
Expr
|
Expression that evaluates to True or False from one or several columns of |
required |
group_by
|
Sequence[str] | Sequence[Expr] | str | Expr
|
Columns to group by, by default None |
None
|
hole_size
|
int | timedelta
|
Maximum authorized size of holes than can be in a run without interrupting it, by default 4 |
4
|
unwrap
|
bool
|
If False, returns the whole data as a modified run length encoded DataFrame. If True, returns the True runs exploded. By default False |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Modified-run-length-encoded input, or exploded True runs. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in jetutils/definitions.py
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 | |
extract_season_from_df(df, season=None)
Subsets a DataFrame containing a "time" column to a given season.
Source code in jetutils/definitions.py
679 680 681 682 683 684 685 686 687 688 689 690 691 692 | |
first_elements(arr, n_elements, sort=False)
Get the smallest n_elements of arr, along the last axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Any array |
required |
n_elements
|
int
|
Number of elements to return along each axis |
required |
sort
|
bool
|
Sort the output, only valid for 1D |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
RuntimeWarning
|
If |
Source code in jetutils/definitions.py
861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 | |
get_index_columns(df, potentials=None)
Finds columns in df that represent an index imformation more than a data information in the context of this package.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Any DataFrame |
required |
potentials
|
tuple
|
Potential names of column indices, by default ( "member", "time", "cluster", "jet ID", "spell", "relative_index", "relative_time", "sample_index", "inside_index", ) |
None
|
Returns:
| Type | Description |
|---|---|
list
|
list of columns in |
Source code in jetutils/definitions.py
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 | |
get_region(da)
Extracts the lon-lat region spanned by an xarray object containing the "lon" and "lat" dimensions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray | Dataset
|
Xarray object |
required |
Returns:
| Name | Type | Description |
|---|---|---|
minlon |
float
|
minimum longitude |
maxlon |
float
|
maximum longitude |
minlat |
float
|
minimum latitude |
maxlat |
float
|
maximum latitude |
Source code in jetutils/definitions.py
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 | |
get_runs(mask, cyclic=True)
Obsolete basic implementaion of the Run Length Encoding algorithm using itertools.groupby.
With the cyclic argument on, runs are allowed to wrap around the end of the list to its start. For instance, list [True, True, False, ..., False, True, True] will have a True run going from indices -2 to 1 included if cyclic=True.
Source code in jetutils/definitions.py
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 | |
get_runs_fill_holes(mask, cyclic=True, hole_size=8)
Obsolete algorithm to get potentially interrupted runs of True values. The runs can be uninterrupted like the basic algorithm, or interrupted by False values if the run of False values within the run of True values is shorter than hole_size.
The algorithm first performs RLE using get_runs, then fills the short False runs with True and applies get_runs a second time on the modified input.
Source code in jetutils/definitions.py
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 | |
infer_direction(to_plot)
Infers the direction of an arbitrary array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
to_plot
|
Any
|
Array or list of arrays |
required |
Returns:
| Type | Description |
|---|---|
int
|
-1 if the data is mostly negative, +1 if it is mostly positive and 0 if the data is symmetric |
Source code in jetutils/definitions.py
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 | |
iterate_over_year_maybe_member(df=None, da=None, several_years=1, several_members=1)
Constructs iterators over time and member, for up to a polars DataFrame and a xarray DataArray that have the same indices.
Source code in jetutils/definitions.py
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 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 | |
labels_to_mask(labels, as_da=False)
Turns an array of labels into a mask
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
DataArray | ndarray
|
Array of labels. |
required |
as_da
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
xr.DataArray | np.ndarray of shape (*labels.shape, n_unique_labels)
|
Boolean mask, of the same shape as labels plus one dimension / axis at position 0. If turned into a DataArray, that new dimension is named "cluster". |
Examples:
>>> labels_to_mask([1, 3, 2, 1])
array([[True, False, False],
[False, False, True],
[False, True, False],
[True, False, False]])
Source code in jetutils/definitions.py
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 | |
last_elements(arr, n_elements, sort=False)
Get the largest n_elements of arr, along the last axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ndarray
|
Any array |
required |
n_elements
|
int
|
Number of elements to return along each axis |
required |
sort
|
bool
|
Sort the output, only valid for 1D |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
RuntimeWarning
|
If |
Source code in jetutils/definitions.py
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 923 924 925 926 927 928 929 | |
load_pickle(filename)
Save a pickleable object to file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str | Path
|
path, it's better if it ends in |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Pickled object |
Source code in jetutils/definitions.py
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 | |
map_maybe_parallel(iterator, func, len_, processes=N_WORKERS, chunksize=None, progress=True, pool_kwargs=None, ctx=None)
Maps a function on the components of an Iterable. Can be parallel if processes is greater than one. In this case the other arguments are used to create a multiprocessing.Pool. In most cases, I recommend using ctx = get_context("spawn") instead of the default (on linux) fork.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iterator
|
Iterable
|
Data |
required |
func
|
Callable
|
Function to apply to each element of |
required |
len_
|
int
|
len of the |
required |
processes
|
int
|
Number of parallel processes, will not create a |
N_WORKERS
|
chunksize
|
int
|
How many elements to send to a worker at once, by default 100 |
None
|
progress
|
bool
|
Show a progress bar using |
True
|
pool_kwargs
|
dict | None
|
Keyword arguments passed to |
None
|
ctx
|
optional
|
Multiporcessing context, created using |
None
|
Returns:
| Type | Description |
|---|---|
list
|
result of the map coerced into a list. |
Source code in jetutils/definitions.py
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 | |
maybe_circular_mean(x)
Circular mean of a number already converted to radians
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
float
|
Angle in degrees |
required |
Returns:
| Type | Description |
|---|---|
float
|
Circular mean |
Source code in jetutils/definitions.py
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | |
normalize(X)
Normalizes an arbitrary polars DataFrame or numpy Array to a standard normal along one axis. The 0 axis if numpy, the columns if polars. Returns the original minimum and maximum to be able to revert.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray | DataFrame
|
Input array |
required |
Returns:
| Name | Type | Description |
|---|---|---|
X |
same as input
|
Input normalised to a standard normal |
meanX |
same as input, with one fewer dimension
|
Original minimum of the data, used to revert this function |
stdX |
same as input, with one fewer dimension
|
Original maximum of the data, used to revert this function |
Source code in jetutils/definitions.py
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 | |
polars_to_xarray(df, index_columns)
Turns a polars DataFrame into a xarray DataArray if possible, a Dataset otherwise. Which columns of df will be dimensions of the xarray output cannot be inferred from df and have to be passed as index_columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Input array |
required |
index_columns
|
list[str]
|
Which columns of |
required |
Returns:
| Name | Type | Description |
|---|---|---|
da |
DataArray or Dataset
|
Data transformed in to a xarray object. If |
Source code in jetutils/definitions.py
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 | |
revert_normalize(X, meanX, stdX)
Reverts the function normalize().
Source code in jetutils/definitions.py
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 | |
revert_zero_one(X, Xmin, Xmax)
Reverts the function to_zero_one().
Source code in jetutils/definitions.py
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 | |
save_pickle(to_save, filename)
Save a pickleable object to file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
to_save
|
Any
|
Pickleable |
required |
filename
|
str | Path
|
path, it's better if it ends in |
required |
Source code in jetutils/definitions.py
429 430 431 432 433 434 435 436 437 438 439 440 441 | |
slice_1d(da, indexers, dim='points')
Gets a (N - n + 1) dimensional slice from a N dimensional Xarray object using Xarray's advanced indexing, by passing n indexers in a dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
DataArray | Dataset
|
Xarray object |
required |
indexers
|
dict
|
Dictionnary whose keys must be dimensions of |
required |
dim
|
str
|
Name of the newly created dimension in the output, that will be of the same length as all of the (equally sized) arrays in |
'points'
|
Returns:
| Name | Type | Description |
|---|---|---|
da_slice |
same as `da`
|
Input DataArray interpolated on the points specified by |
References
https://docs.xarray.dev/en/latest/user-guide/indexing.html#more-advanced-indexing
Source code in jetutils/definitions.py
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 | |
to_expr(expr)
Make sure it's an Expr.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
expr
|
Expr | str
|
Either already an |
required |
Returns:
| Type | Description |
|---|---|
Expr
|
Same as input or |
Source code in jetutils/definitions.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 | |
to_zero_one(X)
Normalizes an arbitrary polars DataFrame or numpy Array to the range [0, 1] along one axis. The 0 axis if numpy, the columns if polars. Returns the original minimum and maximum to be able to revert.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
ndarray | DataFrame
|
Input array |
required |
Returns:
| Name | Type | Description |
|---|---|---|
X |
same as input
|
Input normalised to the range [0, 1] |
Xmin |
same as input, with one fewer dimension
|
Original minimum of the data, used to revert this function |
Xmax |
same as input, with one fewer dimension
|
Original maximum of the data, used to revert this function |
Source code in jetutils/definitions.py
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 | |