-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathearth.py
1799 lines (1543 loc) · 60.5 KB
/
earth.py
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
# https://github.com/sunset1995/py360convert
# #!pip install py360convert
import datetime
import glob
import gzip
import math
import os
from contextlib import closing
from io import BytesIO
from pathlib import Path
import lavavu
import matplotlib
import numpy as np
import py360convert
import quaternion as quat
import xarray as xr
from PIL import Image
from .utils import download, is_notebook, pushd
Image.MAX_IMAGE_PIXELS = None
MtoLL = 1.0 / 111133 # Rough conversion from metres to lat/lon units
class Settings:
# Texture and geometry resolutions
RES = 0
# Equirectangular res in y (x=2*y)
FULL_RES_Y = 10800
# Cubemap res
TEXRES = 2048
GRIDRES = 1024
MAXGRIDRES = 4096
# INSTALL_PATH is used for files such as sea-water-normals.png
INSTALL_PATH = Path(__file__).parents[0]
# Default to non-headless mode
HEADLESS = False
hostname = os.getenv("HOSTNAME", "")
gadi = "gadi.nci.org.au" in hostname
if gadi:
# Enable headless via moderngl when running on gadi
HEADLESS = True
# Where data is stored, should use public cache dir on gadi
# Check if the data directory is specified in environment variables
envdir = os.getenv("ACCESSVIS_DATA_DIR")
if envdir:
DATA_PATH = Path(envdir)
else:
# Check if running on "gadi.nci.org.au"
if gadi:
# Use public shared data cache on gadi
DATA_PATH = Path("/g/data/xp65/public/apps/access-vis-data")
if not os.access(DATA_PATH, os.R_OK):
# Use /scratch
project = os.getenv("PROJECT")
user = os.getenv("USER")
DATA_PATH = Path(f"/scratch/{project}/{user}/.accessvis")
else:
DATA_PATH = Path.home() / ".accessvis"
os.makedirs(DATA_PATH, exist_ok=True)
GEBCO_PATH = DATA_PATH / "gebco" / "GEBCO_2020.nc"
def __repr__(self):
return f"resolution {self.RES}, {self.FULL_RES_Y}, texture {self.TEXRES}, grid {self.GRIDRES}, maxgrid {self.MAXGRIDRES} basedir {self.DATA_PATH}"
settings = Settings()
def get_viewer(*args, **kwargs):
"""
Parameters
----------
arguments for lavavu.Viewer().
See https://lavavu.github.io/Documentation/lavavu.html#lavavu.Viewer for more documentation.
Returns
-------
return: lavavu.Viewer
"""
if settings.HEADLESS:
from importlib import metadata, util
try:
# If this fails, lavavu-osmesa was installed
# headless setting not required as implicitly in headless mode
metadata.metadata("lavavu")
# Also requires moderngl for EGL headless context
settings.HEADLESS = util.find_spec("moderngl") is not None
except (metadata.PackageNotFoundError):
settings.HEADLESS = False
if settings.HEADLESS:
return lavavu.Viewer(*args, context="moderngl", **kwargs)
else:
return lavavu.Viewer(*args, **kwargs)
def set_resolution(val):
"""
Sets the resolution of the following:
settings.RES, settings.TEXRES, settings.FULL_RES_Y, settings.GRIDRES
Parameters
----------
val: Texture and geometry resolution
"""
settings.RES = val
settings.TEXRES = pow(2, 10 + val)
settings.FULL_RES_Y = pow(2, max(val - 2, 0)) * 10800
settings.GRIDRES = min(pow(2, 9 + val), settings.MAXGRIDRES)
def resolution_selection(default=1):
"""
Parameters
----------
default: resolution 1=low ... 4=high
Returns
-------
widget: ipython.widgets.Dropdown
Allows a user to select their desired resolution.
"""
# Output texture resolution setting
desc = """Low-res 2K - fast for testing
Mid-res 4K - good enough for full earth views
High res 8K - better if showing close up at country scale
Ultra-high 16K - max detail but requires a fast GPU with high memory"""
if settings.RES == 0:
set_resolution(default)
if not is_notebook():
return None
print(desc)
# from IPython.display import display
import ipywidgets as widgets
w = widgets.Dropdown(
options=[
("Low-res 2K", 1),
("Mid-res 4K", 2),
("High-res 8K", 3),
("Ultra-high-res 16K", 4),
],
value=settings.RES,
description="Detail:",
)
def on_change(change):
if change and change["type"] == "change" and change["name"] == "value":
set_resolution(w.value)
w.observe(on_change)
set_resolution(default)
return w
def read_image(fn):
"""
Reads an image and returns as a numpy array,
also supporting gzipped images (.gz extension)
Parameters
----------
fn: str|Path
The file path to an image
Returns
-------
image: numpy.ndarray
"""
# supports .gz extraction on the fly
p = Path(fn)
# print(p.suffixes, p.suffixes[-2].lower())
if p.suffix == ".gz" and p.suffixes[-2].lower() in [
".tif",
".tiff",
".png",
".jpg",
".jpeg",
]:
with gzip.open(fn, "rb") as f:
file_content = f.read()
buffer = BytesIO(file_content)
image = Image.open(buffer)
return np.array(image)
else:
image = Image.open(fn)
return np.array(image)
def paste_image(fn, xpos, ypos, out):
"""
#Read an image from filename then paste a tile into a larger output image
#Assumes output is a multiple of source tile image size and matching data type
Parameters
----------
fn: str|Path
file name
xpos: int
ypos: int
out: np.ndarray
image to update
"""
col = read_image(fn)
# print(fn, col.shape)
xoff = xpos * col.shape[0]
yoff = ypos * col.shape[1]
# print(f"{yoff}:{yoff+col.shape[1]}, {xoff}:{xoff+col.shape[0]}")
out[yoff : yoff + col.shape[1], xoff : xoff + col.shape[0]] = col
def lonlat_to_3D(lon, lat, alt=0):
"""
Convert lat/lon coord to 3D coordinate for visualisation
Uses simple spherical earth rather than true ellipse
see http://www.mathworks.de/help/toolbox/aeroblks/llatoecefposition.html
https://stackoverflow.com/a/20360045
"""
return lonlat_to_3D_true(lon, lat, alt, flattening=0.0)
def latlon_to_3D(lat, lon, alt=0, flattening=0.0):
"""
Convert lon/lat coord to 3D coordinate for visualisation
Provided for backwards compatibility as main function now reverses arg order of
(lat, lon) to (lon, lat)
"""
return lonlat_to_3D_true(lon, lat, alt, flattening)
def lonlat_to_3D_true(lon, lat, alt=0, flattening=1.0 / 298.257223563):
"""
Convert lon/lat coord to 3D coordinate for visualisation
Now using longitude, latitude, altitude order for more natural argument order
longitude=x, latitude=y, altitude=z
Uses flattening factor for elliptical earth
see http://www.mathworks.de/help/toolbox/aeroblks/llatoecefposition.html
https://stackoverflow.com/a/20360045
"""
rad = np.float64(6.371) # Radius of the Earth (in 1000's of kilometers)
lat_r = np.radians(lat)
lon_r = np.radians(lon)
cos_lat = np.cos(lat_r)
sin_lat = np.sin(lat_r)
# Flattening factor WGS84 Model
FF = (1.0 - np.float64(flattening)) ** 2
C = 1 / np.sqrt(cos_lat**2 + FF * sin_lat**2)
S = C * FF
x = (rad * C + alt) * cos_lat * np.cos(lon_r)
y = (rad * C + alt) * cos_lat * np.sin(lon_r)
z = (rad * S + alt) * sin_lat
# Coord order swapped to match our coord system
return np.array([y, z, x])
# return (x, y, z)
def split_tex(data, res, flip=[]):
"""
Convert a texture image from equirectangular to a set of 6 cubemap faces
(requires py360convert)
"""
if len(data.shape) == 2:
data = data.reshape(data.shape[0], data.shape[1], 1)
channels = data.shape[2]
# Convert equirectangular to cubemap
out = py360convert.e2c(data, face_w=res, mode="bilinear", cube_format="dict")
tiles = {}
for o in out:
# print(o, out[o].shape)
tiles[o] = out[o].reshape(res, res, channels)
if True: # o in flip:
tiles[o] = np.flipud(tiles[o])
# tiles[o] = np.fliplr(tiles[o])
return tiles
def draw_latlon_grid(base_img, out_fn, lat=30, lon=30, linewidth=5, colour=0):
"""
Create lat/lon grid image over provided base image
"""
from PIL import Image
# Open base image
image = Image.open(base_img)
# Set the gridding interval
x_div = 360.0 / lat # degrees grid in X [0,360]
y_div = 180.0 / lon # degree grid in Y [-90,90]
interval_x = round(image.size[0] / x_div)
interval_y = round(image.size[1] / y_div)
# Vertical lines
lw = round(linewidth / 2)
for i in range(0, image.size[0], interval_x):
for j in range(image.size[1]):
for k in range(-lw, lw):
if i + k < image.size[0]:
image.putpixel((i + k, j), colour)
# Horizontal lines
for i in range(image.size[0]):
for j in range(0, image.size[1], interval_y):
# image.putpixel((i, j), colour)
for k in range(-lw, lw):
if j + k < image.size[1]:
image.putpixel((i, j + k), colour)
# display(image)
image.save(out_fn)
def latlon_to_uv(lat, lon):
"""
Convert a decimal longitude, latitude coordinate
to a tex coord in an equirectangular image
"""
# X/u E-W Longitude - [-180,180]
u = 0.5 + lon / 360.0
# Y/v N-S Latitude - [-90,90]
v = 0.5 - lat / 180.0
return u, v
def uv_to_pixel(u, v, width, height):
"""
Convert tex coord [0,1]
to a raster image pixel coordinate for given width/height
"""
return int(u * width), int(v * height)
def latlon_to_pixel(lat, lon, width, height):
"""
Convert a decimal latitude/longitude coordinate
to a raster image pixel coordinate for given width/height
"""
u, v = latlon_to_uv(lat, lon)
return uv_to_pixel(u, v, width, height)
def crop_img_uv(img, cropbox):
"""
Crop an image (PIL or numpy array) based on corner coords
Provide coords as texture coords in [0,1]
"""
top_left, bottom_right = cropbox
u0 = top_left[0]
u1 = bottom_right[0]
v0 = top_left[1]
v1 = bottom_right[1]
# Swap coords if order incorrect
if u0 > u1:
u0, u1 = u1, u0
if v0 > v1:
v0, v1 = v1, v0
# Supports numpy array or PIL image
if isinstance(img, np.ndarray):
# Assumes [lat][lon]
lat = int(v0 * img.shape[0]), int(v1 * img.shape[0])
lon = int(u0 * img.shape[1]), int(u1 * img.shape[1])
print(lat, lon)
return img[lat[0] : lat[1], lon[0] : lon[1]]
elif hasattr(img, "crop"):
area = (
int(u0 * img.size[0]),
int(v0 * img.size[1]),
int(u1 * img.size[0]),
int(v1 * img.size[1]),
)
return img.crop(area)
else:
print("Unknown type: ", type(img))
def crop_img_lat_lon(img, cropbox):
"""
Crop an equirectangular image (PIL or numpy array) based on corner coords
Provide coords as lat/lon coords in decimal degrees
"""
a = latlon_to_uv(*cropbox[0])
b = latlon_to_uv(*cropbox[1])
return crop_img_uv(img, (a, b))
def sphere_mesh(radius=1.0, quality=256, cache=True):
"""
Generate a simple spherical mesh, not suitable for plotting accurate texture/data at the
poles as there will be visible pinching artifacts,
see: cubemap_sphere_vertices() for mesh without artifacts
Parameters
----------
radius: float
Radius of the sphere
quality: int
Sphere mesh quality (higher = more triangles)
cache: bool
If true will attempt to load cached data and if not found will generate
and save the data for next time
"""
# Generate cube face grid
fn = f"Sphere_{quality}_{radius:.4f}"
if cache and os.path.exists(fn + ".npz"):
sdata = np.load(fn + ".npz")
else:
lv = get_viewer()
tris0 = lv.spheres(
"sphere",
scaling=radius,
segments=quality,
colour="grey",
vertices=[0, 0, 0],
fliptexture=False,
)
tris0["rotate"] = [
0,
-90,
0,
] # This rotates the sphere coords to align with [0,360] longitude texture
tris0[
"texture"
] = "data/blank.png" # Need an initial texture or texcoords will not be generated
tris0["renderer"] = "sortedtriangles"
lv.render()
# Generate and extract sphere vertices, texcoords etc
lv.bake() # 1)
sdata = {}
element = tris0.data[0]
keys = element.available.keys()
for k in keys:
sdata[k] = tris0.data[k + "_copy"][0]
# Save compressed vertex data
if cache:
np.savez_compressed(fn, **sdata)
return sdata
def cubemap_sphere_vertices(
radius=1.0,
resolution=None,
heightmaps=None,
vertical_exaggeration=1.0,
cache=True,
hemisphere=None,
):
"""
Generate a spherical mesh from 6 cube faces, suitable for cubemap textures and
without stretching/artifacts at the poles
Parameters
----------
radius: float
Radius of the sphere
resolution: int
Each face of the cube will have this many vertices on each side
Higher for more detailed surface features
heightmaps: dictionary of numpy.ndarrays [face](resolution,resolution)
If provided will add the heights for each face to the radius to provide
surface features, eg: topography/bathymetry for an earth sphere
vertical_exaggeration: float
Multiplier to exaggerate the heightmap in the vertical axis,
eg: to highlight details of topography and bathymetry
cache: bool
If true will attempt to load cached data and if not found will generate
and save the data for next time
hemisphere: str
Crop the data to show a single hemisphere
"N" = North polar
"S" = South polar
"EW" = Antimeridian at centre (Oceania/Pacific)
"WE" = Prime meridian at centre (Africa/Europe)
"E" = Eastern hemisphere - prime meridian to antimeridian (Indian ocean)
"W" = Western hemisphere - antimeridian to prime meridian (Americas)
"""
if resolution is None:
resolution = settings.GRIDRES
# Generate cube face grid
sdata = {}
cdata = {}
fn = f"{settings.DATA_PATH}/sphere/cube_sphere_{resolution}"
if cache and os.path.exists(fn + ".npz"):
cdata = np.load(fn + ".npz")
cache = False # Don't need to write again
os.makedirs(settings.DATA_PATH / "sphere", exist_ok=True)
# For each cube face...
minmax = []
for f in ["F", "R", "B", "L", "U", "D"]:
if f in cdata:
verts = cdata[f]
else:
ij = np.linspace(-1.0, 1.0, resolution, dtype="float32")
ii, jj = np.meshgrid(ij, ij) # 2d grid
zz = np.zeros(shape=ii.shape, dtype="float32") # 3rd dim
if f == "F": ##
vertices = np.dstack((ii, jj, zz + 1.0))
elif f == "B":
vertices = np.dstack((ii, jj, zz - 1.0))
elif f == "R":
vertices = np.dstack((zz + 1.0, jj, ii))
elif f == "L": ##
vertices = np.dstack((zz - 1.0, jj, ii))
elif f == "U":
vertices = np.dstack((ii, zz + 1.0, jj))
elif f == "D": ##
vertices = np.dstack((ii, zz - 1.0, jj))
# Normalise the vectors to form spherical patch (normalised cube)
V = vertices.ravel().reshape((-1, 3))
norms = np.sqrt(np.einsum("...i,...i", V, V))
norms = norms.reshape(resolution, resolution, 1)
verts = vertices / norms
cdata[f] = verts.copy()
# Scale and apply surface detail?
if heightmaps:
# Apply radius and heightmap
verts *= heightmaps[f] * vertical_exaggeration + radius
minmax += [heightmaps[f].min(), heightmaps[f].max()]
else:
# Apply radius only
verts *= radius
sdata[f] = verts
# Save height range
minmax = np.array(minmax)
sdata["range"] = (minmax.min(), minmax.max())
# Hemisphere crop?
half = resolution // 2
if hemisphere == "N": # U
del sdata["D"] # Delete south
for f in ["F", "R", "B", "L"]:
sdata[f] = sdata[f][half::, ::, ::] # Crop bottom section
elif hemisphere == "S": # D
del sdata["U"] # Delete north
for f in ["F", "R", "B", "L"]:
sdata[f] = sdata[f][0:half, ::, ::] # Crop top section
elif hemisphere == "E": # R
del sdata["L"] # Delete W
for f in ["F", "B", "U", "D"]:
sdata[f] = sdata[f][::, half::, ::] # Crop left section
elif hemisphere == "W": # L
del sdata["R"] # Delete E
for f in ["F", "B", "U", "D"]:
sdata[f] = sdata[f][::, 0:half, ::] # Crop right section
elif hemisphere == "EW": # B
del sdata["F"] # Delete prime meridian
for f in ["R", "L"]:
sdata[f] = sdata[f][::, 0:half, ::] # Crop right section
for f in ["U", "D"]:
sdata[f] = sdata[f][0:half, ::, ::] # Crop top section
elif hemisphere == "WE": # F
del sdata["B"] # Delete antimeridian
for f in ["R", "L"]:
sdata[f] = sdata[f][::, half::, ::] # Crop left section
for f in ["U", "D"]:
sdata[f] = sdata[f][half::, ::, ::] # Crop bottom section
# Save compressed un-scaled vertex data
if cache:
np.savez_compressed(fn, **cdata)
return sdata
def load_topography_cubemap(
resolution=None,
radius=6.371,
vertical_exaggeration=1,
bathymetry=True,
hemisphere=None,
):
"""
Load topography from pre-saved data
TODO: Support land/sea mask, document args
Parameters
----------
resolution: int
Each face of the cube will have this many vertices on each side
Higher for more detailed surface features
vertical_exaggeration: number
Multiplier to topography/bathymetry height
radius: float
Radius of the sphere, defaults to 6.371 Earth's approx radius in Mm
hemisphere: str
Crop the data to show a single hemisphere
"N" = North polar
"S" = South polar
"EW" = Antimeridian at centre (Oceania/Pacific)
"WE" = Prime meridian at centre (Africa/Europe)
"E" = Eastern hemisphere - prime meridian to antimeridian (Indian ocean)
"W" = Western hemisphere - antimeridian to prime meridian (Americas)
"""
# Load detailed topo data
if resolution is None:
resolution = settings.GRIDRES
process_gebco() # Ensure data exists
fn = f"{settings.DATA_PATH}/gebco/gebco_cubemap_{resolution}.npz"
if not os.path.exists(fn):
raise (Exception("GEBCO data not found"))
heights = np.load(fn)
# Apply to cubemap sphere
return cubemap_sphere_vertices(
radius, resolution, heights, vertical_exaggeration, hemisphere=hemisphere
)
def load_topography(resolution=None, subsample=1, cropbox=None, bathymetry=True):
"""
Load topography from pre-saved equirectangular data, can be cropped for regional plots
TODO: document args
"""
if resolution is None:
resolution = settings.FULL_RES_Y
heights = None
# Load medium-detail topo data
if resolution > 21600:
# Attempt to load full GEBCO
if not settings.GEBCO_PATH or not os.path.exists(settings.GEBCO_PATH):
resolution = 21600
print("Please pass path to GEBCO_2020.nc in settings.GEBCO_PATH")
print("https://www.bodc.ac.uk/data/open_download/gebco/gebco_2020/zip/")
print(f"Dropping resolution to {resolution} in order to continue...")
else:
ds = xr.open_dataset(settings.GEBCO_PATH)
heights = ds["elevation"][::subsample, ::subsample].to_numpy()
heights = np.flipud(heights)
if heights is None:
process_gebco() # Ensure data exists
basefn = f"gebco_equirectangular_{resolution * 2}_x_{resolution}.npz"
fn = f"{settings.DATA_PATH}/gebco/{basefn}"
if not os.path.exists(fn):
raise (Exception("GEBCO data not found"))
else:
heights = np.load(fn)
heights = heights["elevation"]
if subsample > 1:
heights = heights[::subsample, ::subsample]
if cropbox:
heights = crop_img_lat_lon(heights, cropbox)
# Bathymetry?
if not bathymetry or not isinstance(bathymetry, bool):
# Ensure resolution matches topo grid res
# res_y = resolution//4096 * 10800
# res_y = max(resolution,2048) // 2048 * 10800
mask = load_mask(
res_y=resolution, subsample=subsample, cropbox=cropbox, masktype="oceanmask"
)
# print(type(mask), mask.dtype, mask.min(), mask.max())
if bathymetry == "mask":
# Return a masked array
return np.ma.array(heights, mask=(mask < 255), fill_value=0)
elif not isinstance(bathymetry, bool):
# Can pass a fill value, needs to return as floats instead of int though
ma = np.ma.array(heights.astype(float), mask=(mask < 255))
return ma.filled(bathymetry)
else:
# Zero out to sea level
# Use the mask to zero the bathymetry
heights[mask < 255] = 0
return heights # * vertical_exaggeration
def plot_region(
lv=None,
cropbox=None,
vertical_exaggeration=10,
texture="bluemarble",
lighting=True,
when=None,
waves=False,
blendtex=True,
bathymetry=False,
name="surface",
uniforms={},
shaders=None,
background="black",
*args,
**kwargs,
):
"""
Plots a flat region of the earth with topography cropped to specified region (lat/lon bounding box coords)
uses bluemarble textures by default and sets up seasonal texture blending based on given or current date and time
Uses lat/lon as coordinate system, so no use for polar regions, scales heights to equivalent
TODO: support using km as unit or other custom units instead with conversions from lat/lon
TODO: FINISH DOCUMENTING PARAMS
Parameters
----------
texture: str
Path to textures, face label and texres will be applied with .format(), eg:
texture='path/{face}_mytexture_{texres}.png'
with: texture.format(face='F', texres=settings.TEXRES)
to:'path/F_mytexture_1024.png'
name: str
Append this label to each face object created
vertical_exaggeration: number
Multiplier to topography/bathymetry height
"""
if lv is None:
lv = get_viewer(
border=False, axis=False, resolution=[1280, 720], background=background
)
# Custom uniforms / additional textures
uniforms = {}
"""
#TODO: wave shader etc for regional sections
if waves:
uniforms["wavetex"] = f"{settings.INSTALL_PATH}/data/sea-water-1024x1024_gs.png"
uniforms["wavenormal"] = f"{settings.INSTALL_PATH}/data/sea-water_normals.png"
uniforms["waves"] = True
if shaders is None:
shaders = [f"{settings.INSTALL_PATH}/data/earth_shader.vert", f"{settings.INSTALL_PATH}/data/earth_shader.frag"]
"""
# Split kwargs into global props, object props and uniform values
objargs = {}
for k in kwargs:
if k in lv.properties:
if "object" in lv.properties[k]["target"]:
objargs[k] = kwargs[k]
else:
lv[k] = kwargs[k]
else:
uniforms[k] = kwargs[k]
# Load topo and crop via lat/lon boundaries of data
topo = load_topography(cropbox=cropbox, bathymetry=bathymetry)
height = np.array(topo)
# Scale and apply vertical exaggeration
height = height * MtoLL * vertical_exaggeration
D = [height.shape[1], height.shape[0]]
sverts = np.zeros(shape=(height.shape[0], height.shape[1], 3))
lat0, lon0 = cropbox[0]
lat1, lon1 = cropbox[1]
xy = lv.grid2d(corners=((lon0, lat1), (lon1, lat0)), dims=D)
sverts[::, ::, 0:2] = xy
sverts[::, ::, 2] = height[::, ::]
if texture == "bluemarble":
# TODO: support cropping tiled high res blue marble textures
# Also download relief textures if not found or call process_bluemarble
# TODO2: write a process_relief function for splitting/downloading relief from Earth_Model.ipynb
# colour_tex = f"{settings.DATA_PATH}/relief/4_no_ice_clouds_mts_16k.jpg"
colour_tex = f"{settings.DATA_PATH}/bluemarble/source_full/world.200412.3x21600x10800.jpg"
# colour_tex = f"{settings.DATA_PATH}/landmask/world.oceanmask.21600x10800.png"
uniforms["bluemarble"] = True
elif texture == "relief":
colour_tex = f"{settings.DATA_PATH}/relief/4_no_ice_clouds_mts_16k.jpg"
else:
colour_tex = texture
surf = lv.triangles(
name, vertices=sverts, uniforms=uniforms, cullface=True, opaque=True
) # , fliptexture=False)
img = Image.open(colour_tex)
cropped_img = crop_img_lat_lon(img, cropbox)
arr = np.array(cropped_img)
surf.texture(arr, flip=False)
return lv
def plot_earth(
lv=None,
radius=6.371,
vertical_exaggeration=10,
texture="bluemarble",
lighting=True,
when=None,
hour=None,
minute=None,
waves=None,
sunlight=False,
blendtex=True,
name="",
uniforms={},
shaders=None,
background="black",
hemisphere=None,
*args,
**kwargs,
):
"""
Plots a spherical earth using a 6 face cubemap mesh with bluemarble textures
and sets up seasonal texture blending and optionally, sun position,
based on given or current date and time
TODO: FINISH DOCUMENTING PARAMS
Parameters
----------
texture: str
Path to textures, face label and texres will be applied with .format(), eg:
texture="path/{face}_mytexture_{texres}.png"
with: texture.format(face="F", texres=settings.TEXRES)
to:"path/F_mytexture_1024.png"
radius: float
Radius of the sphere, defaults to 6.371 Earth's approx radius in Mm
vertical_exaggeration: number
Multiplier to topography/bathymetry height
texture: str
Texture set to use, "bluemarble" for the 2004 NASA satellite data, "relief" for a basic relief map
or provide a custom set of textures using a filename template with the following variables, only face is required
{face} (F/R/B/L/U/D) {month} (name of month, capitialised) {texres} (2048/4096/8192/16384)
lighting: bool
Enable lighting, default=True, disable for flat rendering without light and shadow, or to set own lighting params later
when: datetime
Provide a datetime object to set the month for texture sets that vary over the year and time for
position of sun and rotation of earth when calculating sun light position
hour: int
If not providing "when" datetime, provide just the hour and minute
minute: int
If not providing "when" datetime, provide just the hour and minute
waves: bool
When plotting ocean as surface, set this to true to render waves
sunlight: bool
Enable sun light based on passed time of day args above, defaults to disabled and sun will follow the viewer,
always appearing behind the camera position to provide consistant illumination over accurate positioning
blendtex: bool
When the texture set has varying seasonal images, enabling this will blend between the current month and next
months texture to smoothly transition between them as the date changes, defaults to True
name: str
Append this label to each face object created
uniforms: dict
Provide a set of uniform variables, these can be used to pass data to a custom shader
shaders: list
Provide a list of two custom shader file paths eg: ["vertex_shader.glsl", "fragment_shader.glsl"]
background: str
Provide a background colour string, X11 colour name or hex RGB
hemisphere: str
Crop the data to show a single hemisphere
"N" = North polar
"S" = South polar
"EW" = Antimeridian at centre (Oceania/Pacific)
"WE" = Prime meridian at centre (Africa/Europe)
"E" = Eastern hemisphere - prime meridian to antimeridian (Indian ocean)
"W" = Western hemisphere - antimeridian to prime meridian (Americas)
"""
if lv is None:
lv = get_viewer(
border=False, axis=False, resolution=[1280, 720], background=background
)
topo = load_topography_cubemap(
settings.GRIDRES, radius, vertical_exaggeration, hemisphere=hemisphere
)
if when is None:
when = datetime.datetime.now()
month = when.strftime("%B")
# Custom uniforms / additional textures
uniforms["radius"] = radius
if texture == "bluemarble":
texture = "{basedir}/bluemarble/cubemap_{texres}/{face}_blue_marble_{month}_{texres}.png"
uniforms["bluemarble"] = True
if waves is None:
waves = True
elif texture == "relief":
process_relief() # Ensure images available
texture = "{basedir}/relief/cubemap_{texres}/{face}_relief_{texres}.png"
# Waves - load textures as shared
lv.texture("wavetex", f"{settings.INSTALL_PATH}/data/sea-water-1024x1024_gs.png")
lv.texture("wavenormal", f"{settings.INSTALL_PATH}/data/sea-water_normals.png")
# Need to set the property too or will not know to load the texture
if waves is None:
waves = False
uniforms["wavetex"] = ""
uniforms["wavenormal"] = ""
uniforms["waves"] = waves
# Pass in height range of topography as this is dependent on vertical exaggeration
# Convert metres to Mm and multiply by vertical exag
# hrange = np.array([-10952, 8627]) * 1e-6 * vertical_exaggeration
hrange = np.array(topo["range"]) * vertical_exaggeration
uniforms["heightmin"] = hrange[0]
uniforms["heightmax"] = hrange[1]
if shaders is None:
shaders = [
f"{settings.INSTALL_PATH}/data/earth_shader.vert",
f"{settings.INSTALL_PATH}/data/earth_shader.frag",
]
# Split kwargs into global props, object props and uniform values
objargs = {}
for k in kwargs:
if k in lv.properties:
if "object" in lv.properties[k]["target"]:
objargs[k] = kwargs[k]
else:
lv[k] = kwargs[k]
else:
uniforms[k] = kwargs[k]
for f in ["F", "R", "B", "L", "U", "D"]:
if f not in topo:
continue # For hemisphere crops
verts = topo[f]
texfn = texture.format(
basedir=settings.DATA_PATH, face=f, texres=settings.TEXRES, month=month
)
lv.triangles(
name=f + name,
vertices=verts,
texture=texfn,
fliptexture=False,
flip=f in ["F", "L", "D"], # Reverse facing
renderer="simpletriangles",
opaque=True,
cullface=True,
shaders=shaders,
uniforms=uniforms,
**objargs,
)
# Setup seasonal texture for blue marble
if "bluemarble" in texture:
update_earth_datetime(lv, when, name, texture, sunlight, blendtex)
# Default light props
if lighting:
lp = sun_light(time=when if sunlight else None, hour=hour, minute=minute)
# lv.set_properties(diffuse=0.5, ambient=0.5, specular=0.05, shininess=0.06, light=[1,1,0.98,1])
# lv.set_properties(diffuse=0.6, ambient=0.1, specular=0.0, shininess=0.01, light=[1,1,0.98,1])
lv.set_properties(
diffuse=0.6,
ambient=0.6,
specular=0.3,
shininess=0.04,
light=[1, 1, 0.98, 1],
lightpos=lp,
)
# Hemisphere crop? Alter texcoords to fix half cubemap sections
def replace_texcoords(f, idx, lr):
obj = lv.objects[f + name]
el = np.copy(obj.data["texcoords"][0])
obj.cleardata("texcoords")
col = el[::, ::, idx]
if lr == "r":
el[::, ::, idx] = col * 0.5 + 0.5
elif lr == "l":
el[::, ::, idx] = col * 0.5
obj.texcoords(el)
if hemisphere is not None:
lv.render() # Display/update
if hemisphere == "N":
for f in ["F", "R", "B", "L"]:
replace_texcoords(f, 1, "r")
lv.rotation(90.0, 0.0, 0.0)
elif hemisphere == "S":
for f in ["F", "R", "B", "L"]:
replace_texcoords(f, 1, "l")
lv.rotation(-90.0, 0.0, 0.0)
elif hemisphere == "E":
for f in ["F", "B", "U", "D"]:
replace_texcoords(f, 0, "r")
lv.rotation(0.0, -90.0, 0.0)