forked from NCAS-CMS/cf-plot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutility.py
More file actions
1547 lines (1337 loc) · 47.5 KB
/
Copy pathutility.py
File metadata and controls
1547 lines (1337 loc) · 47.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
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
90
91
92
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
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
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
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
333
334
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
374
375
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
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
452
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
501
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
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
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
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
709
710
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
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
870
871
872
873
874
875
876
877
878
879
880
881
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
923
924
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
989
990
991
992
993
994
995
996
997
998
999
1000
"""Utility functions for plotting.
Pure utility functions with no global state dependencies.
These are designed to be used by any plotting module.
"""
from __future__ import annotations
import os
from copy import deepcopy
from typing import Any
import cartopy.util as cartopy_util
import numpy as np
def to_float_or_none(value: Any) -> float | None:
"""Convert numeric-like metadata values to float, else return None."""
if value is None:
return None
try:
return float(value)
except (TypeError, ValueError):
return None
def resolve_colour_scale_file(scale: str) -> str:
"""Resolve a named colour scale or explicit file path."""
package_path = os.path.dirname(__file__)
file_path = os.path.join(package_path, "colour", "colourmaps", f"{scale}.rgb")
if os.path.isfile(file_path):
return file_path
if os.path.isfile(scale):
return scale
errstr = (
"\ncscale error - colour scale not found:\n"
f"File {file_path} not found\n"
f"Scale {scale} not found\n"
)
raise Warning(errstr)
def load_colour_scale_rgb(scale: str) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Load RGB channels for a colour scale."""
with open(resolve_colour_scale_file(scale), "r", encoding="ascii") as handle:
lines = handle.read().splitlines()
red: list[int] = []
green: list[int] = []
blue: list[int] = []
for line in lines:
vals = line.split()
red.append(int(vals[0]))
green.append(int(vals[1]))
blue.append(int(vals[2]))
return (
np.asarray(red, dtype=float),
np.asarray(green, dtype=float),
np.asarray(blue, dtype=float),
)
def interpolate_colour_channels(
red: np.ndarray,
green: np.ndarray,
blue: np.ndarray,
positions: np.ndarray,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Interpolate RGB channels to the requested positions."""
xpts = np.arange(np.size(red), dtype=float)
return (
np.interp(positions, xpts, red),
np.interp(positions, xpts, green),
np.interp(positions, xpts, blue),
)
def ndecs(data: np.ndarray | list) -> int:
"""Find the maximum number of decimal places in an array.
Data with more decimal places will determine the result.
Used to format colorbar and line labels consistently.
Parameters
----------
data : array-like
Input array of numeric values
Returns
-------
int
Maximum number of decimal places found
"""
maxdecs = 0
for value in data:
parts = str(value).split(".")
if len(parts) == 2:
number_decs = len(parts[1])
if number_decs > maxdecs:
maxdecs = number_decs
return maxdecs
def gvals(
dmin: float | None = None,
dmax: float | None = None,
mystep: float | None = None,
mod: bool = True,
) -> tuple[np.ndarray, int]:
"""Generate sensible tick values between two limits.
Works out appropriate step size and generates values,
optionally scaling with a power-of-10 multiplier.
Used for contour levels and axis labelling.
Parameters
----------
dmin : float
Minimum value
dmax : float
Maximum value
mystep : float, optional
Use this step instead of auto-calculating
mod : bool
If True, apply multiplier for small/large ranges
Returns
-------
vals : ndarray
Array of tick values
mult : int
Multiplier exponent (10^mult) applied to values
"""
# Copies of inputs as these might be changed
dmin1 = deepcopy(dmin)
dmax1 = deepcopy(dmax)
# Swap if dmin1 > dmax1
if dmax1 < dmin1:
dmin1, dmax1 = dmax1, dmin1
# Data range
data_range = dmax1 - dmin1
# field multiplier
mult = 0
vals = None
# Return some values if dmin1 = dmax1
if dmin1 == dmax1:
vals = np.array([dmin1 - 1, dmin1, dmin1 + 1])
mult = 0
return vals, mult
# Modify if requested or if out of range 0.001 to 2000000
if data_range < 0.001:
while dmax1 <= 3:
dmin1 = dmin1 * 10.0
dmax1 = dmax1 * 10.0
data_range = dmax1 - dmin1
mult = mult - 1
if data_range > 2000000:
while dmax1 > 10:
dmin1 = dmin1 / 10.0
dmax1 = dmax1 / 10.0
data_range = dmax1 - dmin1
mult = mult + 1
if data_range >= 0.001 and data_range <= 2000000:
# Calculate an appropriate step
step = None
test_steps = [
0.0001,
0.0002,
0.0005,
0.001,
0.002,
0.005,
0.01,
0.02,
0.05,
0.1,
0.2,
0.5,
1,
2,
5,
10,
20,
50,
100,
200,
500,
1000,
2000,
5000,
10000,
20000,
50000,
100000,
]
if mystep is not None:
step = mystep
else:
for val in test_steps:
nvals = data_range / val
if val < 1:
if nvals > 8:
step = val
else:
if nvals > 11:
step = val
# Return an error if no step found
if step is None:
errstr = "\n\n cfp.gvals - no valid step values found \n\n"
errstr += "cfp.gvals(" + str(dmin1) + "," + str(dmax1) + ")\n\n"
raise ValueError(errstr)
# values < 0.0
vals = None
vals1 = None
if dmin1 < 0.0:
vals1 = (np.arange(-dmin1 / step) * -step)[::-1] - step
# values >= 0.0
vals2 = None
if dmax1 >= 0.0:
vals2 = np.arange(dmax1 / step + 1) * step
if vals1 is not None and vals2 is None:
vals = vals1
if vals2 is not None and vals1 is None:
vals = vals2
if vals1 is not None and vals2 is not None:
vals = np.concatenate((vals1, vals2))
# Round off decimal numbers
if step < 1:
vals = vals.round(6)
# Change values to integers for values >= 1
if step >= 1:
vals = vals.astype(int)
pts = np.where(np.logical_and(vals >= dmin1, vals <= dmax1))
if np.min(pts) > -1:
vals = vals[pts]
if mod is False:
vals = vals * 10**mult
mult = 0
# Catch if no values have been defined
if vals is None:
vals = np.array([dmin, dmax])
return (vals, mult)
def mapaxis(
min_val: float | None = None,
max_val: float | None = None,
axis_type: int | None = None,
degsym: bool = True,
) -> tuple[list, list]:
"""Generate longitude or latitude axis ticks and labels.
Works out sensible tick marks and labels for geographic axes.
Parameters
----------
min_val : float
Minimum axis value
max_val : float
Maximum axis value
axis_type : int
1 = longitude, 2 = latitude
degsym : bool
If True, use degree symbol in labels
Returns
-------
ticks : list
Tick positions
labels : list
Tick labels
"""
degsym_str = r"$\degree$" if degsym else ""
if axis_type == 1:
# Longitude
lonmin = min_val
lonmax = max_val
lonrange = lonmax - lonmin
lonstep = 60
if lonrange <= 180:
lonstep = 30
if lonrange <= 90:
lonstep = 10
if lonrange <= 30:
lonstep = 5
if lonrange <= 10:
lonstep = 2
if lonrange <= 5:
lonstep = 1
lons = np.arange(-720, 720 + lonstep, lonstep)
lonticks = []
for lon in lons:
if lon >= lonmin and lon <= lonmax:
lonticks.append(lon)
lonlabels = []
for lon in lonticks:
lon2 = np.mod(lon + 180, 360) - 180
if lon2 < 0 and lon2 > -180:
if lon != 180:
lonlabels.append(str(abs(int(lon2))) + degsym_str + "W")
if lon2 > 0 and lon2 <= 180:
lonlabels.append(str(int(lon2)) + degsym_str + "E")
if lon2 == 0:
lonlabels.append("0" + degsym_str)
if lon == 180 or lon == -180:
lonlabels.append("180" + degsym_str)
return (lonticks, lonlabels)
if axis_type == 2:
# Latitude
latmin = min_val
latmax = max_val
latrange = latmax - latmin
latstep = 30
if latrange <= 90:
latstep = 10
if latrange <= 30:
latstep = 5
if latrange <= 10:
latstep = 2
if latrange <= 5:
latstep = 1
lats = np.arange(-90, 90 + latstep, latstep)
latticks = []
for lat in lats:
if lat >= latmin and lat <= latmax:
latticks.append(lat)
latlabels = []
for lat in latticks:
if lat < 0:
latlabels.append(str(abs(int(lat))) + degsym_str + "S")
if lat > 0:
latlabels.append(str(int(lat)) + degsym_str + "N")
if lat == 0:
latlabels.append("0" + degsym_str)
return (latticks, latlabels)
return ([], [])
def fix_floats(data: list) -> list:
"""Fix numpy rounding issues where e.g. 0.4 becomes 0.3999999999.
Returns data unchanged if any values contain an exponent ('e').
"""
has_e = any("e" in str(val) for val in data)
if has_e:
return data
data_ndecs = np.zeros(len(data))
for i in np.arange(len(data)):
data_ndecs[i] = len(str(float(data[i])).split(".")[1])
if max(data_ndecs) >= 10:
if min(data_ndecs) < 10:
pts = np.where(data_ndecs >= 10)
data_ndecs[pts] = 0
ndecs_max = int(max(data_ndecs))
for i in np.arange(len(data)):
data[i] = round(data[i], ndecs_max)
else:
nd = 2
data_range = 0.0
data_temp = data
while data_range == 0.0:
data_temp = deepcopy(data)
for i in np.arange(len(data_temp)):
data_temp[i] = round(data_temp[i], nd)
data_range = np.max(data_temp) - np.min(data_temp)
nd = nd + 1
data = data_temp
return data
def calculate_levels(
field: np.ndarray,
level_spacing: str = "linear",
levels_step: Any | None = None,
verbose: bool | None = None,
) -> tuple[np.ndarray, int, float]:
"""Calculate contour levels automatically from field data.
Parameters
----------
field : ndarray
The data field to generate levels for.
level_spacing : str
One of 'linear', 'outlier', 'inspect', 'log', 'loglike'.
levels_step : scalar or None
If given, generate levels with this step size instead of auto.
verbose : bool or None
If True, print diagnostic messages.
Returns
-------
clevs : ndarray
Array of contour levels.
mult : int
Multiplier exponent applied (10 ** mult).
fmult : float
Inverse multiplier (10 ** -mult).
"""
dmin = np.nanmin(field)
dmax = np.nanmax(field)
tight = True
field2 = deepcopy(field)
mult = 0
fmult = 1.0
clevs: Any = []
if levels_step is None:
if verbose:
print("calculate_levels - generating automatic contour levels")
if level_spacing in ("outlier", "inspect"):
hist = np.histogram(field, 100)[0]
pts_arr = np.size(field)
rate = 0.01
if sum(hist[1:-2]) == 0:
if hist[0] / hist[-1] < rate:
pts = np.where(field == dmin)
field2[pts] = dmax
dmin = np.nanmin(field2)
if hist[-1] / hist[0] < rate:
pts = np.where(field == dmax)
field2[pts] = dmin
dmax = np.nanmax(field2)
clevs, mult = gvals(dmin=dmin, dmax=dmax)
fmult = 10**-mult
tight = False
if level_spacing == "linear":
if isinstance(np.ma.min(dmin), np.ma.core.MaskedConstant) or isinstance(
np.ma.min(dmax), np.ma.core.MaskedConstant
):
if verbose:
print(
"calculate_levels warning - data is entirely masked; "
"setting levels to 0 and 0.1"
)
dmin = 0.0
dmax = 0.1
clevs, mult = gvals(dmin=dmin, dmax=dmax)
fmult = 10**-mult
tight = False
if level_spacing in ("log", "loglike"):
if dmin < 0.0 and dmax < 0.0:
dmin1 = abs(dmax)
dmax1 = abs(dmin)
elif dmin > 0.0 and dmax > 0.0:
dmin1 = abs(dmin)
dmax1 = abs(dmax)
else:
dmax1 = max(abs(dmin), dmax)
pts_neg = np.where(field < 0.0)
close_below = np.max(field[pts_neg])
pts_pos = np.where(field > 0.0)
close_above = np.min(field[pts_pos])
dmin1 = min(abs(close_below), close_above)
if level_spacing == "log":
clevs = []
for i in np.arange(31):
val = 10 ** (i - 30.0)
clevs.append("{:.0e}".format(val))
else:
clevs = []
for i in np.arange(61):
val = 10 ** (i - 30.0)
clevs.append("{:.0e}".format(val))
clevs.append("{:.0e}".format(val * 2))
clevs.append("{:.0e}".format(val * 5))
clevs = np.float64(clevs)
pts = np.where(np.logical_and(clevs >= abs(dmin1), clevs <= abs(dmax1)))
clevs = clevs[pts]
if dmin < 0.0 and dmax < 0.0:
clevs = -1.0 * clevs[::-1]
if dmin <= 0.0 and dmax >= 0.0:
clevs = np.concatenate([-1.0 * clevs[::-1], [0.0], clevs])
else:
if verbose:
print("calculate_levels - using specified step to generate contour levels")
step = levels_step
if isinstance(step, int):
dmin = int(dmin)
dmax = int(dmax)
clevs_list = []
if dmin < 0:
clevs_list = list((np.arange(-1 * dmin / step + 1) * -step)[::-1])
if dmax > 0:
pos = list(np.arange(dmax / step + 1) * step)
if len(clevs_list) > 0:
clevs_list = list(clevs_list[:-1]) + pos
else:
clevs_list = pos
clevs = np.array(clevs_list)
if isinstance(step, int):
clevs = clevs.astype(int)
# Remove out-of-range values if tight mode
if tight:
pts = np.where(np.logical_and(clevs >= dmin, clevs <= dmax))
clevs = clevs[pts]
# Ensure at least two levels
clevs = list(clevs)
if len(clevs) < 2:
clevs.append(clevs[0] + 0.001 if clevs else 0.001)
# Fix floating-point rounding noise
if isinstance(clevs[0], float):
clevs = fix_floats(clevs)
return (np.asarray(clevs), mult, fmult)
def timeaxis(
dtimes: Any,
user_gset: int = 0,
xmin: Any = None,
xmax: Any = None,
ymin: Any = None,
ymax: Any = None,
tspace_year: int | None = None,
tspace_hour: int | None = None,
tspace_day: int | None = None,
) -> tuple[list, list, str]:
"""Calculate time axis ticks and labels for a CF time coordinate.
Parameters
----------
dtimes : cf time coordinate
The time dimension of the CF field.
user_gset : int
Non-zero if the user has set axis limits via gset.
xmin, xmax, ymin, ymax : scalar or str or None
User-specified axis limits (possibly date strings).
tspace_year, tspace_hour, tspace_day : int or None
Override auto-calculated spacing for year/hour/day axes.
Returns
-------
time_ticks : list
time_labels : list
axis_label : str
"""
import cf as _cf
time_units = dtimes.Units
time_ticks: list = []
time_labels: list = []
axis_label = "Time"
yearmin = min(dtimes.year.array)
yearmax = max(dtimes.year.array)
tmin = min(dtimes.dtarray)
tmax = max(dtimes.dtarray)
calendar = getattr(dtimes, "calendar", "standard")
if user_gset != 0:
if isinstance(xmin, str):
t = _cf.Data(_cf.dt(xmin), units=time_units, calendar=calendar)
yearmin = int(t.year)
t = _cf.Data(_cf.dt(xmax), units=time_units, calendar=calendar)
yearmax = int(t.year)
tmin = _cf.dt(xmin, calendar=calendar)
tmax = _cf.dt(xmax, calendar=calendar)
if isinstance(ymin, str):
t = _cf.Data(_cf.dt(ymin), units=time_units, calendar=calendar)
yearmin = int(t.year)
t = _cf.Data(_cf.dt(ymax), units=time_units, calendar=calendar)
yearmax = int(t.year)
tmin = _cf.dt(ymin, calendar=calendar)
tmax = _cf.dt(ymax, calendar=calendar)
# Years
span = yearmax - yearmin
if span > 4 and span < 3000:
axis_label = "Time (year)"
if span <= 15:
step = 1
elif span <= 30:
step = 2
elif span <= 60:
step = 5
elif span <= 160:
step = 10
elif span <= 300:
step = 20
elif span <= 600:
step = 50
elif span <= 1300:
step = 100
else:
step = 200
if tspace_year is not None:
step = tspace_year
years = np.arange(yearmax / step + 2) * step
tvals = years[np.where((years >= yearmin) & (years <= yearmax))]
if np.size(tvals) < 2:
tvals = gvals(dmin=yearmin, dmax=yearmax)[0]
for year in tvals:
time_ticks.append(
np.min(
_cf.Data(
_cf.dt(f"{int(year)}-01-01 00:00:00"),
units=time_units,
calendar=calendar,
).array
)
)
time_labels.append(str(int(year)))
# Months
if yearmax - yearmin <= 4:
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
tsteps = 0
for year in np.arange(yearmax - yearmin + 1) + yearmin:
for month in np.arange(12):
mytime = _cf.dt(f"{year}-{month + 1}-01 00:00:00", calendar=calendar)
if mytime >= tmin and mytime <= tmax:
tsteps += 1
mvals = np.arange(12) if tsteps < 17 else np.arange(4) * 3
for year in np.arange(yearmax - yearmin + 1) + yearmin:
for month in mvals:
mytime = _cf.dt(f"{year}-{month + 1}-01 00:00:00", calendar=calendar)
if mytime >= tmin and mytime <= tmax:
time_ticks.append(
np.min(
_cf.Data(mytime, units=time_units, calendar=calendar).array
)
)
time_labels.append(str(months[month]) + " " + str(int(year)))
# Days and hours
if np.size(time_ticks) <= 2:
myday = _cf.dt(int(tmin.year), int(tmin.month), int(tmin.day), calendar=calendar)
not_found = 0
hour_counter = 0
span = 0
while not_found <= 48:
mydate = _cf.Data(myday, dtimes.Units) + _cf.Data(hour_counter, "hour")
if mydate >= tmin and mydate <= tmax:
span += 1
else:
not_found += 1
hour_counter += 1
step = 1
if span > 13:
step = 1
if span > 13:
step = 4
if span > 25:
step = 6
if span > 100:
step = 12
if span > 200:
step = 24
if span > 400:
step = 48
if span > 800:
step = 96
if tspace_hour is not None:
step = tspace_hour
if tspace_day is not None:
step = tspace_day * 24
not_found = 0
hour_counter = 0
axis_label = "Time (hour)"
if span >= 24:
axis_label = "Time"
time_ticks = []
time_labels = []
while not_found <= 48:
mytime = _cf.Data(myday, dtimes.Units) + _cf.Data(hour_counter, "hour")
if mytime >= tmin and mytime <= tmax:
time_ticks.append(np.min(mytime.array))
label = f"{mytime.year}-{mytime.month}-{mytime.day}"
if hour_counter / 24 != int(hour_counter / 24):
label += f" {mytime.hour}:00:00"
time_labels.append(label)
else:
not_found += 1
hour_counter += step
return (time_ticks, time_labels, axis_label)
def _pressure_axis_ticks(ymin: float, ymax: float, ylog: bool) -> list[float] | np.ndarray:
"""Generate pressure-like Y ticks used by ptypes 2 and 3."""
if ylog:
ylo = min(ymin, ymax)
yhi = max(ymin, ymax)
return [tick for tick in (1000, 100, 10, 1) if ylo <= tick <= yhi]
ystep = 100.0
yrange = abs(ymax - ymin)
if yrange < 1:
ystep = yrange / 10.0 if yrange != 0 else 0.1
if yrange > 1:
ystep = 1.0
if yrange > 10:
ystep = 10.0
if yrange > 100:
ystep = 100.0
if yrange > 1000:
ystep = 200.0
if yrange > 2000:
ystep = 500.0
if yrange > 5000:
ystep = 1000.0
if yrange > 15000:
ystep = 5000.0
return gvals(
dmin=min(ymin, ymax),
dmax=max(ymin, ymax),
mystep=ystep,
mod=False,
)[0]
def compute_xy_ticks(
*,
ptype: int,
xmin: float,
xmax: float,
ymin: float,
ymax: float,
ylog: bool,
degsym: bool,
xticks: Any,
yticks: Any,
xticklabels: Any,
yticklabels: Any,
default_xlabel: str,
default_ylabel: str,
time_ticks: list | None = None,
time_labels: list | None = None,
time_label: str | None = None,
) -> tuple[Any, Any, Any, Any, str, str]:
"""Compute non-map axis ticks/labels for refactored contour rendering.
Handles ptypes 2-5 plus generic Cartesian fallback used by ptypes 0/7.
"""
if ptype in (4, 5) and time_ticks is not None and time_labels is not None:
if ptype == 4:
lonlat_ticks, lonlat_labels = mapaxis(
min_val=xmin, max_val=xmax, axis_type=1, degsym=degsym
)
default_xlabel = default_xlabel or "Longitude"
else:
lonlat_ticks, lonlat_labels = mapaxis(
min_val=xmin, max_val=xmax, axis_type=2, degsym=degsym
)
default_xlabel = default_xlabel or "Latitude"
default_ylabel = time_label or default_ylabel or "time"
if xticks is None:
xticks = lonlat_ticks
xticklabels = lonlat_labels
if yticks is None:
yticks = time_ticks
yticklabels = time_labels
return xticks, yticks, xticklabels, yticklabels, default_xlabel, default_ylabel
if ptype == 2:
if xticks is None:
xticks, xticklabels = mapaxis(
min_val=xmin,
max_val=xmax,
axis_type=2,
degsym=degsym,
)
if yticks is None:
yticks = _pressure_axis_ticks(ymin=ymin, ymax=ymax, ylog=ylog)
elif ptype == 3:
if xticks is None:
xticks, xticklabels = mapaxis(
min_val=xmin,
max_val=xmax,
axis_type=1,
degsym=degsym,
)
if yticks is None:
yticks = _pressure_axis_ticks(ymin=ymin, ymax=ymax, ylog=ylog)
else:
if xticks is None:
xticks = gvals(dmin=xmin, dmax=xmax, mod=False)[0]
if yticks is None:
yticks = gvals(dmin=ymax, dmax=ymin, mod=False)[0]
return xticks, yticks, xticklabels, yticklabels, default_xlabel, default_ylabel
# ---------------------------------------------------------------------------
# CF field extraction helpers
# ---------------------------------------------------------------------------
def _supscr(text: str) -> str:
"""Format superscript notation for units strings (``**`` and ``^``)."""
tform = ""
sup = 0
for i in text:
if i == "^":
sup = 2
if i == "*":
sup = sup + 1
if sup == 0:
tform = tform + i
if sup == 1:
if i not in "*":
tform = tform + "*" + i
sup = 0
if sup == 3:
if i in "-0123456789":
tform = tform + i
else:
tform = tform + "}$" + i
sup = 0
if sup == 2:
tform = tform + "$^{"
sup = 3
if sup == 3:
tform = tform + "}$"
tform = tform.replace("m2", "m$^{2}$")
tform = tform.replace("m3", "m$^{3}$")
tform = tform.replace("m-2", "m$^{-2}$")
tform = tform.replace("m-3", "m$^{-3}$")
tform = tform.replace("s-1", "s$^{-1}$")
tform = tform.replace("s-2", "s$^{-2}$")
return tform
def cf_var_name(field: Any, dim: str) -> str:
"""Return the best available name for a CF field dimension coordinate.
Names are checked in priority order: ncvar, short_name, long_name,
standard_name.
"""
# If multiple Z coordinates exist, use the last one
if dim == "Z":
z_names = [
mycoord
for mycoord in list(field.coords())
if field.coord(mycoord).Z
]
if len(z_names) > 1:
dim = z_names[-1]
construct = field.construct(dim)
id_ = getattr(construct, "id", False)
ncvar = construct.nc_get_variable(False)
short_name = getattr(construct, "short_name", False)
long_name = getattr(construct, "long_name", False)
standard_name = getattr(construct, "standard_name", False)
name = "No Name"
if id_:
name = id_
if ncvar:
name = ncvar
if short_name:
name = short_name
if long_name:
name = long_name
if standard_name:
name = standard_name
return name
def cf_var_name_titles(field: Any, dim: str) -> tuple[str | None, str | None]:
"""Return preferred coordinate name/units for dimension-title rendering."""
name = None
units = None
if field.has_construct(dim):
construct = field.construct(dim)
id_ = getattr(construct, "id", False)
ncvar = construct.nc_get_variable(False)
short_name = getattr(construct, "short_name", False)
long_name = getattr(construct, "long_name", False)
standard_name = getattr(construct, "standard_name", False)
if id_:
name = id_
if ncvar:
name = ncvar
if short_name:
name = short_name
if long_name:
name = long_name
if standard_name:
name = standard_name
units = getattr(construct, "units", "")
if len(units) > 0:
units = f"({units})"
return name, units
def generate_titles(f: Any = None) -> str:
"""Generate dimension/cell-method title text for plot annotation."""
import cf
from .validate import check_well_formed
mycoords = find_dim_names(f)
# Preserve legacy side effect/validation behavior.
check_well_formed(f)
title_dims = ""
if isinstance(f, cf.Field):
for idim in np.arange(len(mycoords)):
mycoord = mycoords[idim]
if mycoord == "Z":
mycoord = find_z(f)
title, units = cf_var_name_titles(f, mycoord)
if not f.coord(mycoord).T:
values = f.construct(mycoord).array
if len(values) > 1:
value = ""
else:
value = str(values)
title_dims += f"{mycoord}: {title} {value} {units}\n"
else:
values = f.construct(mycoord).dtarray
if len(values) > 1:
value = ""
else:
value = str(cf.Data(values).datetime_as_string)
title_dims += f"{mycoord}: {title} {value}\n"
if len(f.cell_methods()) > 0:
title_dims += "cell_methods: "
i = 0
for method in f.cell_methods():
if len(f.cell_methods()[method].get_axes()) > 0:
axis = f.cell_methods()[method].get_axes()[0]
try:
myid = f.constructs.domain_axis_identity(axis)
except ValueError:
myid = axis
value = ""