-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoptapm.py
1630 lines (1092 loc) · 63.5 KB
/
optapm.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
# Copyright (C) 2016 Michael G. Tetley
# EarthByte Group, University of Sydney / Seismological Laboratory, California Institute of Technology
# Contact email: [email protected] / [email protected]
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from HotSpotLoader import GetHotSpotTrailsFromGeoJSON, GetHotSpotLocationsFromGeoJSON
import geoTools
import isopolate
import json
import math
import numpy as np
import pandas as pd
import pickle
import pmagpy.ipmag as ipmag
import pmagpy.pmag as pmag
import pygplates as pgp
import random
import textwrap
# The optimization workflow doesn't actually need to plot so we won't require user to install these modules.
# If the user plots then we'll get an AttributeError, in which case the try/except part should be removed.
try:
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from IPython.display import display, HTML
except ImportError:
pass
class ModelSetup():
@staticmethod
def dataLoaderHelp():
print(textwrap.dedent("""
Data Loader
Loads all required data for optimisation routine.
Arguments:
----------
datadir : Absolute path to data directory
rot_file : GPlates rotation *.rot file
Optional arguments:
nnr_rotfile : GPlates no net-rotation *.rot file. Required for net rotation calculations.
tm_file : Trench migration data for the current reconstruction time. Required for trench migration calculations.
pv_file : Plate velocity data (points and associated plate IDs) for the current reconstruction time.
Required for plate velocity calculations.
ridge_file : GPlates *.gpml ridge file. Required for fracture zone calculations.
isochron_file : GPlates *.gpml isochron file. Required for fracture zone calculations.
isocob_file : GPlates *.gpml isocob file. Required for fracture zone calculations.
hst_file : GeoJSON hotspot trail data. Relative path to datadir.
hs_file : GeoJSON hotspot location data. Relative path to datadir.
"""))
@staticmethod
def dataLoader(datadir, rot_file, ref_rot_file=None, tm_file=None, pv_file=None, nnr_rotfile=None,
ridge_file=None, isochron_file=None, isocob_file=None, hst_file=None, hs_file=None,
interpolated_hotspots=None):
# Create rotation model
rotation_file = datadir + rot_file
rotation_model = pgp.RotationModel(rotation_file)
# Create reference rotation model
if ref_rot_file:
ref_rotation_file = datadir + ref_rot_file
ref_rotation_model = pgp.RotationModel(ref_rotation_file)
# Check for and load optional arguments
if tm_file:
trench_migration_file = datadir + tm_file
if pv_file:
plate_velocity_file = datadir + pv_file
if nnr_rotfile:
no_net_rotation_file = datadir + nnr_rotfile
if ridge_file:
features_ri = pgp.FeatureCollection(datadir + ridge_file)
RidgeFile_subset = pgp.FeatureCollection()
if isochron_file:
features_iso = pgp.FeatureCollection(datadir + isochron_file)
IsochronFile_subset = pgp.FeatureCollection()
if isocob_file:
features_isocob = pgp.FeatureCollection(datadir + isocob_file)
IsoCOBFile_subset = pgp.FeatureCollection()
if hst_file:
hst_datafile = hst_file
hs_trails = GetHotSpotTrailsFromGeoJSON(datadir + hst_datafile)
if hs_file:
hs_datafile = hs_file
hotspots = GetHotSpotLocationsFromGeoJSON(datadir + hs_datafile)
if interpolated_hotspots:
interpolated_hotspot_data = pd.read_excel(
datadir + interpolated_hotspots,
# pyGPlates (via boost.python) cannot convert numpy.int64 to regular Python float.
# Not sure if happens only in 32-bit versions of pyGPlates (ie, on Windows).
# So convert here instead...
converters = {'Hotspot_lat' : float, 'Hotspot_lon' : float})
# Return all loaded data
data = [rotation_model, rotation_file, trench_migration_file, plate_velocity_file, no_net_rotation_file,
features_ri, RidgeFile_subset, features_iso, IsochronFile_subset, features_isocob, IsoCOBFile_subset,
hs_trails, hotspots, ref_rotation_model, ref_rotation_file, interpolated_hotspot_data]
print("- Data loaded")
print(" ")
return data
@staticmethod
def modelParametersHelp():
print(textwrap.dedent("""
Model Parameters
Sets all user-selected parameters for the mode run
Arguments:
----------
geographical_uncertainty : Number that approximately represents geographical uncertainty - 95% confidence limit around ref pole location
rotation_uncertainty : Number that represents the upper and lower bounds of the optimisation's angle variation
sample_space : Selects the sampling method to be used to generate start seeds. "Fisher" (spherical distribution) by default.
models : The total number of models to be produced. 1 model = 1 complete optimisation from 1 starting location
model_stop_condition : Type of condition to be used to terminate optimisation. "threshold" or "max_iter". Threshold by default.
max_iter : IF "max_iter" selected, sets maximum iterations regardless of successful convergence.
ref_rotation_plate_id : Plate to be used as fixed reference. 701 (Africa) by default.
ref_rotation_start_age : Rotation begin age.
ref_rotation_end_age : Rotation end age.
rotation_age_of_interest : The result we are interested in. Allows for 'windowed mean' approach. It is the midpoint between the start and end ages by default.
Data to be included in optimisation: True by default.
enable_fracture_zones : Boolean
enable_net_rotation : Boolean
enable_trench_migration : Boolean
enable_hotspot_trails : Boolean
enable_plate_velocity : Boolean
"""))
@staticmethod
def modelStartConditions(params, data, plot=True):
# Translate data array
(rotation_model,
rotation_file,
trench_migration_file,
plate_velocity_file,
no_net_rotation_file,
features_ri,
RidgeFile_subset,
features_iso,
IsochronFile_subset,
features_isocob,
IsoCOBFile_subset,
hs_trails,
hotspots,
ref_rotation_model,
ref_rotation_file,
interpolated_hotspot_data) = data[:16]
# Translate params array
(geographical_uncertainty,
rotation_uncertainty,
search_type,
models,
model_stop_condition,
max_iter,
ref_rotation_plate_id,
ref_rotation_start_age,
ref_rotation_end_age,
interpolation_resolution,
rotation_age_of_interest,
enable_fracture_zones, enable_net_rotation, enable_trench_migration, enable_hotspot_trails, enable_plate_velocity,
fz_weight, nr_weight, tm_weight, hs_weight, pv_weight,
fracture_zone_cost_func, net_rotation_cost_func, trench_migration_cost_func, hotspot_trails_cost_func, plate_velocity_cost_func,
fracture_zone_bounds, net_rotation_bounds, trench_migration_bounds, hotspot_trails_bounds, plate_velocity_bounds,
ref_rot_longitude,
ref_rot_latitude,
ref_rot_angle,
auto_calc_ref_pole,
search,
include_chains,
interpolated_hotspot_trails,
tm_method) = params[:39]
#print(fz_weight, nr_weight, tm_weight, hs_weight, pv_weight)
# Set rotation age of interest
rotation_age_of_interest_age = ref_rotation_start_age - (0.5 * (ref_rotation_start_age - ref_rotation_end_age))
# Optimisation data array
data_array_labels = ['Fracture zone orientation', 'Net rotation', 'Trench migration',
'Hotspot trails', 'Plate velocity']
weights_array = [fz_weight, nr_weight, tm_weight, hs_weight, pv_weight]
data_array_labels_short = ['FZ', 'NR', 'TM', 'HS', 'PV']
data_array = [enable_fracture_zones, enable_net_rotation, enable_trench_migration, enable_hotspot_trails, enable_plate_velocity]
cost_func_array = [fracture_zone_cost_func, net_rotation_cost_func, trench_migration_cost_func, hotspot_trails_cost_func, plate_velocity_cost_func]
bounds_array = [fracture_zone_bounds, net_rotation_bounds, trench_migration_bounds, hotspot_trails_bounds, plate_velocity_bounds]
# Array containing the name of all chains to be included in optimisation
if ref_rotation_start_age <= 80:
pass
# chains including the pacific
#include_chains = ['Reunion', 'Louisville', 'Tristan', 'St_Helena', 'Foundation', 'Samoa', 'Cobb', 'Caroline', 'Tasmantid']
#print("Hotspot chains used:", str(include_chains))
#else:
# chains excluding the pacific
#include_chains = ['Reunion', 'Tristan', 'St_Helena', 'Tasmantid']
#print("Hotspot chains used:", str(include_chains))
print("Optimisation parameters:")
print(" ")
print("Data constraints:")
for i in range(0, len(data_array)):
if data_array[i] == True:
print("- " + data_array_labels[i] + ": weight(" + str(weights_array[i]) + ")")
if bounds_array[i]:
print(" - bounds" + str(bounds_array[i]))
print(" ")
print("Termination:")
if model_stop_condition == "max_iter":
print("- Maximum iteration: " + str(max_iter))
else:
print("- Threshold")
print(" ")
print("Sampling method:")
print("- " + search_type)
print(" ")
print("Reference rotation type:")
# Prepare rotation model for updates during optimisation - keeps rotations in memory
# rotation_model_tmp = pgp.FeatureCollection(rotation_file)
# Calculate initial reference rotation for the reference plate (eg, Africa) from selected rotation model
if auto_calc_ref_pole == True:
print("- Auto-calc palaeomagnetic")
ref_rot = ref_rotation_model.get_rotation(np.double(ref_rotation_start_age), ref_rotation_plate_id, 0)
ref_rot_pole, ref_rot_angle = ref_rot.get_euler_pole_and_angle()
ref_rot_of_interest = ref_rotation_model.get_rotation(np.double(rotation_age_of_interest_age), ref_rotation_plate_id, 0)
ref_rot_of_interest_pole, ref_rot_of_interest_angle = ref_rot_of_interest.get_euler_pole_and_angle()
# Convert finite rotations to lat, lon and degrees
ref_rot_pole = pgp.convert_point_on_sphere_to_lat_lon_point(ref_rot_pole)
ref_rot_longitude = ref_rot_pole.get_longitude()
ref_rot_latitude = ref_rot_pole.get_latitude()
ref_rot_angle = np.rad2deg(ref_rot_angle)
elif auto_calc_ref_pole == False:
print("- User reference")
ref_rot_longitude = ref_rot_longitude
ref_rot_latitude = ref_rot_latitude
ref_rot_angle = ref_rot_angle
ref_rot_of_interest = ref_rotation_model.get_rotation(np.double(rotation_age_of_interest_age), ref_rotation_plate_id, 0)
ref_rot_of_interest_pole, ref_rot_of_interest_angle = ref_rot_of_interest.get_euler_pole_and_angle()
# else:
# print("Reference rotation type: EarthByte model")
# ref_rot = rotation_model.get_rotation(np.double(ref_rotation_start_age), ref_rotation_plate_id, 0)
# ref_rot_pole, ref_rot_angle = ref_rot.get_euler_pole_and_angle()
# ref_rot_of_interest = rotation_model.get_rotation(np.double(rotation_age_of_interest_age), ref_rotation_plate_id, 0)
# ref_rot_of_interest_pole, ref_rot_of_interest_angle = ref_rot_of_interest.get_euler_pole_and_angle()
# Convert finite rotations to lat, lon and degrees
# ref_rot_pole = pgp.convert_point_on_sphere_to_lat_lon_point(ref_rot_pole)
# ref_rot_longitude = ref_rot_pole.get_longitude()
# ref_rot_latitude = ref_rot_pole.get_latitude()
# ref_rot_angle = np.rad2deg(ref_rot_angle)
print(" ")
print("Reference finite rotation pole for reference plate", ref_rotation_plate_id, "at", ref_rotation_start_age, "Ma:")
print("- Lon:", ref_rot_longitude)
print("- Lat:", ref_rot_latitude)
print("- Angle:", ref_rot_angle)
print(" ")
ref_rot_of_interest_pole = pgp.convert_point_on_sphere_to_lat_lon_point(ref_rot_of_interest_pole)
ref_rot_longitude_of_interest = ref_rot_of_interest_pole.get_longitude()
ref_rot_latitude_of_interest = ref_rot_of_interest_pole.get_latitude()
ref_rot_angle_of_interest = np.rad2deg(ref_rot_of_interest_angle)
# print("Reference finite rotation pole for reference plate", ref_rotation_plate_id, "at", rotation_age_of_interest_age, "Ma:")
# print("- Lon:", ref_rot_longitude_of_interest)
# print("- Lat:", ref_rot_latitude_of_interest)
# print("- Angle:", ref_rot_angle_of_interest)
# Calculate start seeds (reference + (models - 1) random starting rotations within uncertainty limits)
start_seeds_rotated = []
start_seeds = []
seed_history = []
seed_lons = []
seed_lats = []
seed_angs = []
# Generate uniform random distribution of start seeds
if search_type == 'Random':
if search == "Initial":
num_points = models * 5
#num_points = models
lons = []
lats = []
for i in range(0, num_points):
# Generate uniformly distributed random points on a unit sphere.
theta = 2 * np.pi * np.random.random()
phi = np.arccos(2 * np.random.random() - 1.0)
x = np.cos(theta) * np.sin(phi)
y = np.sin(theta) * np.sin(phi)
z = np.cos(phi)
point = pgp.convert_point_on_sphere_to_lat_lon_point((x,y,z))
lats.append(point.get_latitude())
lons.append(point.get_longitude())
# Extract points within latitudinal zone of interest
sample_lats = []
sample_lons = []
for i in range(0, len(lats)):
if lats[i] > 90 - geographical_uncertainty:
sample_lats.append(lats[i])
sample_lons.append(lons[i])
#print(len(sample_lats))
# Rotate points from pole to reference start seed
for i in range(0, len(sample_lats)):
start_seeds_rotated.append(pmag.dodirot(sample_lons[i], sample_lats[i], ref_rot_longitude, ref_rot_latitude))
# Trim start seed array to match number of requested models
if len(start_seeds_rotated) > models:
trim = len(start_seeds_rotated) - models
start_seeds_rotated = start_seeds_rotated[:-trim]
# Sample gaussian array of angles using standard deviation of ref angle and uncertainty limits
ang_array = [(ref_rot_angle - rotation_uncertainty), ref_rot_angle, (ref_rot_angle + rotation_uncertainty)]
ang_array_sd = np.std(ang_array)
ang_gaussian_array = []
ang_gaussian_array.append(np.random.normal(ref_rot_angle, ang_array_sd, models))
# Create start seeds array
for i in range(0, len(start_seeds_rotated)):
seed = [start_seeds_rotated[i][0], start_seeds_rotated[i][1], ref_rot_angle]
seed_lons.append(start_seeds_rotated[i][0])
seed_lats.append(start_seeds_rotated[i][1])
seed_angs.append(ref_rot_angle)
if seed not in seed_history:
start_seeds.append(seed)
seed_history.append(seed)
#print(len(start_seeds_rotated))
#print(len(start_seeds))
#print(len(seed_history))
# For secondary minimisation, add inital min result to start seeds
if auto_calc_ref_pole == False:
seed = [ref_rot_longitude, ref_rot_latitude, ref_rot_angle]
seed_lons.append(ref_rot_longitude)
seed_lats.append(ref_rot_latitude)
seed_angs.append(ref_rot_angle)
if seed not in seed_history:
start_seeds.append(seed)
seed_history.append(seed)
# (Lon, Lat, Ang)
start_seeds = np.array(start_seeds)
#print(start_seeds)
#print(len(start_seeds))
# Set N to number of models to be run (optimisations)
N = len(start_seeds[0])
# Set lon, lat and angle error bounds.
lb = []
lb.append(np.min(seed_lons) - geographical_uncertainty)
lb.append(np.min(seed_lats) - geographical_uncertainty)
lb.append(np.min(seed_angs) - rotation_uncertainty)
ub = []
ub.append(np.max(seed_lons) + geographical_uncertainty)
ub.append(np.max(seed_lats) + geographical_uncertainty)
ub.append(np.max(seed_angs) + rotation_uncertainty)
# print('max_lons', np.max(seed_lons))
# print('max_lats', np.max(seed_lats))
# print('min_lons', np.min(seed_lons))
# print('min_lats', np.min(seed_lats))
# print(" ")
# print(seed_lons)
# print(" ")
# Generate uniform non-random distribution of points on a unit sphere.
elif search_type == 'Uniform':
#if search == "Initial":
#
# # Works for search radius of 60
# #num_points = models * 4
# num_points = models * 5
#
#elif search == "Secondary":
#
# if geographical_uncertainty == 30:
#
# num_points = models * 15
#
# elif geographical_uncertainty == 15:
#
# num_points = models * 60
# angle = np.pi * (3 - np.sqrt(5))
# theta = angle * np.arange(num_points)
# z = np.linspace(1 - 1.0 / num_points, 1.0 / num_points - 1, num_points)
# radius = np.sqrt(1 - z * z)
#
# points = np.zeros((num_points, 3))
# points[:,0] = radius * np.cos(theta)
# points[:,1] = radius * np.sin(theta)
# points[:,2] = z
#
# lons = []
# lats = []
#
# for i in range(0, len(points)):
#
# point = pgp.convert_point_on_sphere_to_lat_lon_point((points[i][0], points[i][1], points[i][2]))
# lats.append(point.get_latitude())
# lons.append(point.get_longitude())
# 'models' points covers a search radius of 'geographical_uncertainty' so
# number points covering entire globe is 1/search_area.
num_points_float = models * 1.0 / (0.5*(1-math.cos(math.radians(geographical_uncertainty))))
num_longitude_points = int(math.ceil(math.sqrt(num_points_float)))
num_latitude_points = num_longitude_points
num_points = num_longitude_points * num_latitude_points
#print('num_points:', num_points)
lons = []
lats = []
for lon_index in range(0, num_longitude_points):
for lat_index in range(0, num_latitude_points):
theta = 2 * np.pi * ((lon_index + 0.5) / float(num_longitude_points))
phi = np.arccos(2 * ((lat_index + 0.5) / float(num_latitude_points)) - 1.0)
#print(' ', theta, phi)
x = np.cos(theta) * np.sin(phi)
y = np.sin(theta) * np.sin(phi)
z = np.cos(phi)
point = pgp.convert_point_on_sphere_to_lat_lon_point((x,y,z))
lats.append(point.get_latitude())
lons.append(point.get_longitude())
# Extract points within latitudinal zone of interest
sample_lats = []
sample_lons = []
for i in range(0, len(lats)):
if lats[i] > 90 - geographical_uncertainty:
sample_lats.append(lats[i])
sample_lons.append(lons[i])
#print(len(sample_lats))
# Rotate points from pole to reference start seed
for i in range(0, len(sample_lats)):
start_seeds_rotated.append(pmag.dodirot(sample_lons[i], sample_lats[i], ref_rot_longitude, ref_rot_latitude))
# Sample gaussian array of angles using standard deviation of ref angle and uncertainty limits
ang_array = [(ref_rot_angle - rotation_uncertainty), ref_rot_angle, (ref_rot_angle + rotation_uncertainty)]
ang_array_sd = np.std(ang_array)
ang_gaussian_array = []
ang_gaussian_array.append(np.random.normal(ref_rot_angle, ang_array_sd, models))
# Create start seeds array
for i in range(0, len(start_seeds_rotated)):
seed = [start_seeds_rotated[i][0], start_seeds_rotated[i][1], ref_rot_angle]
seed_lons.append(start_seeds_rotated[i][0])
seed_lats.append(start_seeds_rotated[i][1])
seed_angs.append(ref_rot_angle)
if seed not in seed_history:
start_seeds.append(seed)
seed_history.append(seed)
#print(len(start_seeds_rotated))
#print(len(start_seeds))
#print(len(seed_history))
# For secondary minimisation, add inital min result to start seeds
if auto_calc_ref_pole == False:
seed = [ref_rot_longitude, ref_rot_latitude, ref_rot_angle]
seed_lons.append(ref_rot_longitude)
seed_lats.append(ref_rot_latitude)
seed_angs.append(ref_rot_angle)
if seed not in seed_history:
start_seeds.append(seed)
seed_history.append(seed)
# (Lon, Lat, Ang)
start_seeds = np.array(start_seeds)
#print(start_seeds)
#print(len(start_seeds))
# Set N to number of models to be run (optimisations)
N = len(start_seeds[0])
# Set lon, lat and angle error bounds.
lb = []
lb.append(np.min(seed_lons) - geographical_uncertainty)
lb.append(np.min(seed_lats) - geographical_uncertainty)
lb.append(np.min(seed_angs) - rotation_uncertainty)
ub = []
ub.append(np.max(seed_lons) + geographical_uncertainty)
ub.append(np.max(seed_lats) + geographical_uncertainty)
ub.append(np.max(seed_angs) + rotation_uncertainty)
# print('max_lons', np.max(seed_lons))
# print('max_lats', np.max(seed_lats))
# print('min_lons', np.min(seed_lons))
# print('min_lats', np.min(seed_lats))
# print(" ")
# print(seed_lons)
# print(" ")
# Generate a gaussian distribution of start seeds
elif search_type == 'Fisher':
# Calculate Fisher kappa distribution on sphere to represent geographical uncertainty
if models == 100:
k = geoTools.calcKfromA95(geographical_uncertainty / 9, models)
elif models == 1000:
k = geoTools.calcKfromA95(geographical_uncertainty / 22, models)
else:
k = geoTools.calcKfromA95(geographical_uncertainty / 6, models)
# Draw fisher distributed start seeds [lon lat] around pole
if auto_calc_ref_pole == True:
fdist = ipmag.fishrot(k, models, 0)
elif auto_calc_ref_pole == False:
# Subtract array with models - 1 as initial optimised minimum result is appended
fdist = ipmag.fishrot(k, models - 1, 0)
# Rotate start seeds to center on reference location
for i in range(0, len(fdist)):
start_seeds_rotated.append(pmag.dodirot(fdist[i][0], fdist[i][1], ref_rot_longitude, ref_rot_latitude))
# Sample gaussian array of angles using standard deviation of ref angle and uncertainty limits
ang_array = [(ref_rot_angle - rotation_uncertainty), ref_rot_angle, (ref_rot_angle + rotation_uncertainty)]
ang_array_sd = np.std(ang_array)
ang_gaussian_array = []
ang_gaussian_array.append(np.random.normal(ref_rot_angle, ang_array_sd, models))
# Create start seeds array
for i in range(0, len(start_seeds_rotated)):
if search == "Secondary":
seed = [start_seeds_rotated[i][0], start_seeds_rotated[i][1], ref_rot_angle]
else:
seed = [start_seeds_rotated[i][0], start_seeds_rotated[i][1], ang_gaussian_array[0][i]]
seed_lons.append(start_seeds_rotated[i][0])
seed_lats.append(start_seeds_rotated[i][1])
seed_angs.append(ang_gaussian_array[0][i])
if seed not in seed_history:
start_seeds.append(seed)
seed_history.append(seed)
# For secondary minimisation, add inital min result to start seeds
if auto_calc_ref_pole == False:
seed = [ref_rot_longitude, ref_rot_latitude, ref_rot_angle]
seed_lons.append(ref_rot_longitude)
seed_lats.append(ref_rot_latitude)
seed_angs.append(ref_rot_angle)
if seed not in seed_history:
start_seeds.append(seed)
seed_history.append(seed)
# (Lon, Lat, Ang)
start_seeds = np.array(start_seeds)
#print(start_seeds)
#print(len(start_seeds))
# Set N to number of models to be run (optimisations)
N = len(start_seeds[0])
# Set lon, lat and angle error bounds.
lb = []
lb.append(np.min(seed_lons) - geographical_uncertainty)
lb.append(np.min(seed_lats) - geographical_uncertainty)
lb.append(np.min(seed_angs) - rotation_uncertainty)
ub = []
ub.append(np.max(seed_lons) + geographical_uncertainty)
ub.append(np.max(seed_lats) + geographical_uncertainty)
ub.append(np.max(seed_angs) + rotation_uncertainty)
elif search_type == '2D_cartesian':
# Using a while loop here ensures total start seeds = model iterations even if duplicates are found
while len(start_seeds) != models:
tmp_seed = []
# Set first seed to known reference plate rotation
if len(start_seeds) < 1:
lon_rand = ref_rot_longitude
lat_rand = ref_rot_latitude
angle_rand = ref_rot_angle
seed = [[lon_rand], [lat_rand], [angle_rand]]
start_seeds.append(seed)
seed_history.append(seed)
elif len(start_seeds) >= 1:
# Generate random start seeds from geographic uncertainty ranges for initial longitude and latitude
lon_rand = random.sample(range((int(ref_rot_longitude) - int(geographical_uncertainty)),
(int(ref_rot_longitude) + int(geographical_uncertainty))), 1)
lat_rand = random.sample(range((int(ref_rot_latitude) - int(geographical_uncertainty)),
(int(ref_rot_latitude) + int(geographical_uncertainty))), 1)
angle_rand = random.sample(range((int(ref_rot_angle) - int(rotation_uncertainty)),
(int(ref_rot_angle) + int(rotation_uncertainty))), 1)
seed = [lon_rand, lat_rand, angle_rand]
# Check to make sure latitude seed is > 0 and < 90
if seed[1][0] >= 90:
seed[1][0] = 89
elif seed[1][0] <= -90:
seed[1][0] = 1
# Check all seeds are within upper and lower bounds
if seed[0][0] >= ref_rot_longitude - geographical_uncertainty and \
seed[0][0] <= ref_rot_longitude + geographical_uncertainty and \
seed[1][0] >= ref_rot_latitude - geographical_uncertainty and \
seed[1][0] <= ref_rot_latitude + geographical_uncertainty and \
seed[2][0] >= ref_rot_angle - rotation_uncertainty and \
seed[2][0] <= ref_rot_angle + rotation_uncertainty:
if seed not in seed_history:
start_seeds.append(seed)
seed_history.append(seed)
else:
continue
# (Lon, Lat, Ang)
start_seeds = np.array(start_seeds)
# Set N to number of models to be run (optimisations)
N = len(start_seeds[0])
# Set lon, lat and angle error bounds.
lb = []
lb.append(ref_rot_longitude - geographical_uncertainty)
lb.append(ref_rot_latitude - geographical_uncertainty)
lb.append(ref_rot_angle - rotation_uncertainty)
ub = []
ub.append(ref_rot_longitude + geographical_uncertainty)
ub.append(ref_rot_latitude + geographical_uncertainty)
ub.append(ref_rot_angle + rotation_uncertainty)
# Append lon, lat and angle to make x = 3N elements for all start seeds (optimisation vector input)
x = []
x_ = []
for i in range(0, len(start_seeds)):
x_ = []
x_.append(np.append(start_seeds[i][0], start_seeds[i][1]))
x.append(np.append(x_, start_seeds[i][2]))
opt_n = len(x[0])
hs_eval_data = []
# Build feature subset lists
for feature in features_iso:
if feature.get_valid_time()[1] <= ref_rotation_start_age:
IsochronFile_subset.add(feature)
for feature in features_ri:
if feature.get_valid_time()[1] <= ref_rotation_start_age:
RidgeFile_subset.add(feature)
for feature in features_isocob:
if feature.get_valid_time()[1] <= ref_rotation_start_age:
IsoCOBFile_subset.add(feature)
# This is where intertec is actually called - note that these one line interpolates the isochrons,
# but does not reconstruct them
recon_interpolated_isochrons = []
output_features = isopolate.interpolate_isochrons(rotation_model,
[RidgeFile_subset, IsochronFile_subset, IsoCOBFile_subset],
interpolate=range(ref_rotation_end_age, ref_rotation_start_age + 1, interpolation_resolution),
#interpolate=0.01,
tessellate_threshold_radians=math.radians(0.5),
output_scalar_spreading_direction=True,
output_scalar_spreading_rate=True,
output_scalar_spreading_asymmetry=True,
output_scalar_age=True,
print_debug_output=0)
# Here we do the last step that the old intertec did, reconstructing the interpolated
# isochrons to the selected time.
pgp.reconstruct(output_features, rotation_file, recon_interpolated_isochrons, ref_rotation_start_age, 0)
## Step2
# Take the coverage that intertec produced, and use it to derive arrays of data more easily analysed using numpy commands
Lats = []
Lons = []
spreading_directions = []
spreading_rates = []
spreading_asymmetries = []
seafloor_ages = []
PID = []
CPID = []
for recon_interpolated_isochron in recon_interpolated_isochrons:
tmp = recon_interpolated_isochron.get_feature()
tmp2 = tmp.get_geometry(coverage_return=pgp.CoverageReturn.geometry_and_scalars)
if tmp2:
coverage_geometry, coverage_scalars = tmp2
coverage_points = coverage_geometry.get_points()
#tmp3 = coverage_points.get_points()
for scalar in coverage_scalars.get(pgp.ScalarType.create_gpml('SpreadingDirection')):
spreading_directions.append(scalar)
#spreading_directions.append(coverage_scalars.get(pgp.ScalarType.create_gpml('SpreadingDirection')))
for scalar in coverage_scalars.get(pgp.ScalarType.create_gpml('SpreadingRate')):
spreading_rates.append(scalar)
for scalar in coverage_scalars.get(pgp.ScalarType.create_gpml('SpreadingAsymmetry')):
spreading_asymmetries.append(scalar)
for scalar in coverage_scalars.get(pgp.ScalarType.create_gpml('Age')):
seafloor_ages.append(scalar)
for point in coverage_points.get_points().to_lat_lon_array():
Lats.append(point[0])
Lons.append(point[1])
PID.append(tmp.get_reconstruction_plate_id())
CPID.append(tmp.get_conjugate_plate_id())
# TRENCH MIGRATION
# Load pre-computed migration data if needed (net rotation or trench migration)
if tm_method == 'convergence':
# DEPRECATED: We currently use "tm_method == 'convergence'" so this code is essentially deprecated.
# However, if it's brought then we need access to 'datadir' and 'data_model' (via function arguments).
raise DeprecationWarning("Using the old 'convergence' of trench statistics is deprecated - use 'pygplates' instead.")
nnr_datadir = datadir + 'TMData/' + data_model + '/'
FNAME = nnr_datadir + 'data_%s_%s.txt' % (int(ref_rotation_start_age), int(ref_rotation_end_age))
with open(FNAME, 'r') as f:
reformArray = json.load(f)
elif tm_method == 'pygplates':
reformArray = []
# HOTSPOT CHAINS
# Get hotspot chain data into Dataframe
trails_list = []
for item in hs_trails:
trails_list.append({ 'Chain': str(item) , 'Lon': hs_trails[item]['lon'], 'Lat': hs_trails[item]['lat'],
'Age': hs_trails[item]['age'], 'Age_error': hs_trails[item]['age_error'],
'PlateID': hs_trails[item]['plateid'], 'Geo_error': geographical_uncertainty,
'Rot_error': rotation_uncertainty})
hs_trailsDF = pd.DataFrame(trails_list)
# Add geographical location of each hotspot to existing chains list
for i, item in enumerate(hs_trailsDF['Chain']):
for j, hotspot in enumerate(hotspots):
if item == hotspot:
trails_list[i].update({'Hotspot': (hotspots[hotspot]['lat'], hotspots[hotspot]['lon'])})
hs_trailsDF = pd.DataFrame(trails_list)
# Build trail data subset
if interpolated_hotspot_trails == False:
print('- Using raw hotspot trail data')
trail_data = []
for i, item in enumerate(hs_trailsDF.Chain):
if item in include_chains:
#print(item)
trail_data.append({'Chain': hs_trailsDF.Chain[i], 'Lon': hs_trailsDF.Lon[i], 'Lat': hs_trailsDF.Lat[i],
'Age': hs_trailsDF.Age[i], 'Age_err': hs_trailsDF.Age_error[i], 'PlateID': hs_trailsDF.PlateID[i],
'Hotspot_Location': hs_trailsDF.Hotspot[i], 'Geo_err': hs_trailsDF.Geo_error[i],
'Rot_err': hs_trailsDF.Rot_error[i]})
if interpolated_hotspot_trails == True:
print('- Using interpolated hotspot trail data')
trail_data = []
for i, item in enumerate(include_chains):