-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.py
More file actions
2632 lines (2236 loc) · 114 KB
/
run.py
File metadata and controls
2632 lines (2236 loc) · 114 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
#!/usr/bin/env python
# coding: utf-8
import os
import sys
import io
import base64
import json
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg') # Use non-interactive backend
os.environ['QT_QPA_PLATFORM'] = '' # Disable Qt platform detection
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.figure import Figure
from matplotlib.patches import Polygon
from flask import Flask, render_template, request, redirect, url_for, jsonify, send_file, session
from werkzeug.utils import secure_filename
import zipfile
from io import BytesIO
import re
# Import necessary GeoPyTool modules
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# Create a modified version of ImportDependence for web
class WebDependence:
pass
# Create a simplified CustomClass for web
class WebCustomClass:
pass
# Function to standardize column names
def standardize_column_names(df):
"""
Standardize column names by removing units and converting to standard chemical notation
"""
# Define mapping for major elements
major_elements_map = {
# SiO2 variations
'sio2': 'SiO2', 'SIO2': 'SiO2', 'si02': 'SiO2', 'SI02': 'SiO2',
'sio2(wt%)': 'SiO2', 'sio2(wt.%)': 'SiO2', 'sio2(%)': 'SiO2',
'sio2_wt%': 'SiO2', 'sio2_wt': 'SiO2', 'sio2_weight%': 'SiO2',
# TiO2 variations
'tio2': 'TiO2', 'TIO2': 'TiO2', 'ti02': 'TiO2', 'TI02': 'TiO2',
'tio2(wt%)': 'TiO2', 'tio2(wt.%)': 'TiO2', 'tio2(%)': 'TiO2',
'tio2_wt%': 'TiO2', 'tio2_wt': 'TiO2', 'tio2_weight%': 'TiO2',
# Al2O3 variations
'al2o3': 'Al2O3', 'AL2O3': 'Al2O3', 'al203': 'Al2O3', 'AL203': 'Al2O3',
'al2o3(wt%)': 'Al2O3', 'al2o3(wt.%)': 'Al2O3', 'al2o3(%)': 'Al2O3',
'al2o3_wt%': 'Al2O3', 'al2o3_wt': 'Al2O3', 'al2o3_weight%': 'Al2O3',
# Fe2O3 variations
'fe2o3': 'Fe2O3', 'FE2O3': 'Fe2O3', 'fe203': 'Fe2O3', 'FE203': 'Fe2O3',
'fe2o3(wt%)': 'Fe2O3', 'fe2o3(wt.%)': 'Fe2O3', 'fe2o3(%)': 'Fe2O3',
'fe2o3_wt%': 'Fe2O3', 'fe2o3_wt': 'Fe2O3', 'fe2o3_weight%': 'Fe2O3',
# FeO variations
'feo': 'FeO', 'FEO': 'FeO',
'feo(wt%)': 'FeO', 'feo(wt.%)': 'FeO', 'feo(%)': 'FeO',
'feo_wt%': 'FeO', 'feo_wt': 'FeO', 'feo_weight%': 'FeO',
# MnO variations
'mno': 'MnO', 'MNO': 'MnO',
'mno(wt%)': 'MnO', 'mno(wt.%)': 'MnO', 'mno(%)': 'MnO',
'mno_wt%': 'MnO', 'mno_wt': 'MnO', 'mno_weight%': 'MnO',
# MgO variations
'mgo': 'MgO', 'MGO': 'MgO',
'mgo(wt%)': 'MgO', 'mgo(wt.%)': 'MgO', 'mgo(%)': 'MgO',
'mgo_wt%': 'MgO', 'mgo_wt': 'MgO', 'mgo_weight%': 'MgO',
# CaO variations
'cao': 'CaO', 'CAO': 'CaO',
'cao(wt%)': 'CaO', 'cao(wt.%)': 'CaO', 'cao(%)': 'CaO',
'cao_wt%': 'CaO', 'cao_wt': 'CaO', 'cao_weight%': 'CaO',
# Na2O variations
'na2o': 'Na2O', 'NA2O': 'Na2O', 'na20': 'Na2O', 'NA20': 'Na2O',
'na2o(wt%)': 'Na2O', 'na2o(wt.%)': 'Na2O', 'na2o(%)': 'Na2O',
'na2o_wt%': 'Na2O', 'na2o_wt': 'Na2O', 'na2o_weight%': 'Na2O',
# K2O variations
'k2o': 'K2O', 'K2O': 'K2O', 'k20': 'K2O', 'K20': 'K2O',
'k2o(wt%)': 'K2O', 'k2o(wt.%)': 'K2O', 'k2o(%)': 'K2O',
'k2o_wt%': 'K2O', 'k2o_wt': 'K2O', 'k2o_weight%': 'K2O',
# P2O5 variations
'p2o5': 'P2O5', 'P2O5': 'P2O5', 'p205': 'P2O5', 'P205': 'P2O5',
'p2o5(wt%)': 'P2O5', 'p2o5(wt.%)': 'P2O5', 'p2o5(%)': 'P2O5',
'p2o5_wt%': 'P2O5', 'p2o5_wt': 'P2O5', 'p2o5_weight%': 'P2O5',
}
# Define mapping for trace elements
trace_elements_map = {
# Rb variations
'rb': 'Rb', 'RB': 'Rb',
'rb(ppm)': 'Rb', 'rb(ppb)': 'Rb', 'rb(ppt)': 'Rb',
'rb_ppm': 'Rb', 'rb_ppb': 'Rb', 'rb_ppt': 'Rb',
# Ba variations
'ba': 'Ba', 'BA': 'Ba',
'ba(ppm)': 'Ba', 'ba(ppb)': 'Ba', 'ba(ppt)': 'Ba',
'ba_ppm': 'Ba', 'ba_ppb': 'Ba', 'ba_ppt': 'Ba',
# Th variations
'th': 'Th', 'TH': 'Th',
'th(ppm)': 'Th', 'th(ppb)': 'Th', 'th(ppt)': 'Th',
'th_ppm': 'Th', 'th_ppb': 'Th', 'th_ppt': 'Th',
# U variations
'u': 'U', 'U': 'U',
'u(ppm)': 'U', 'u(ppb)': 'U', 'u(ppt)': 'U',
'u_ppm': 'U', 'u_ppb': 'U', 'u_ppt': 'U',
# Nb variations
'nb': 'Nb', 'NB': 'Nb',
'nb(ppm)': 'Nb', 'nb(ppb)': 'Nb', 'nb(ppt)': 'Nb',
'nb_ppm': 'Nb', 'nb_ppb': 'Nb', 'nb_ppt': 'Nb',
# Ta variations
'ta': 'Ta', 'TA': 'Ta',
'ta(ppm)': 'Ta', 'ta(ppb)': 'Ta', 'ta(ppt)': 'Ta',
'ta_ppm': 'Ta', 'ta_ppb': 'Ta', 'ta_ppt': 'Ta',
# K variations (when as trace element)
'k': 'K', 'K': 'K',
'k(ppm)': 'K', 'k(ppb)': 'K', 'k(ppt)': 'K',
'k_ppm': 'K', 'k_ppb': 'K', 'k_ppt': 'K',
# La variations
'la': 'La', 'LA': 'La',
'la(ppm)': 'La', 'la(ppb)': 'La', 'la(ppt)': 'La',
'la_ppm': 'La', 'la_ppb': 'La', 'la_ppt': 'La',
# Ce variations
'ce': 'Ce', 'CE': 'Ce',
'ce(ppm)': 'Ce', 'ce(ppb)': 'Ce', 'ce(ppt)': 'Ce',
'ce_ppm': 'Ce', 'ce_ppb': 'Ce', 'ce_ppt': 'Ce',
# Pr variations
'pr': 'Pr', 'PR': 'Pr',
'pr(ppm)': 'Pr', 'pr(ppb)': 'Pr', 'pr(ppt)': 'Pr',
'pr_ppm': 'Pr', 'pr_ppb': 'Pr', 'pr_ppt': 'Pr',
# Nd variations
'nd': 'Nd', 'ND': 'Nd',
'nd(ppm)': 'Nd', 'nd(ppb)': 'Nd', 'nd(ppt)': 'Nd',
'nd_ppm': 'Nd', 'nd_ppb': 'Nd', 'nd_ppt': 'Nd',
# P variations (when as trace element)
'p': 'P', 'P': 'P',
'p(ppm)': 'P', 'p(ppb)': 'P', 'p(ppt)': 'P',
'p_ppm': 'P', 'p_ppb': 'P', 'p_ppt': 'P',
# Sm variations
'sm': 'Sm', 'SM': 'Sm',
'sm(ppm)': 'Sm', 'sm(ppb)': 'Sm', 'sm(ppt)': 'Sm',
'sm_ppm': 'Sm', 'sm_ppb': 'Sm', 'sm_ppt': 'Sm',
# Eu variations
'eu': 'Eu', 'EU': 'Eu',
'eu(ppm)': 'Eu', 'eu(ppb)': 'Eu', 'eu(ppt)': 'Eu',
'eu_ppm': 'Eu', 'eu_ppb': 'Eu', 'eu_ppt': 'Eu',
# Gd variations
'gd': 'Gd', 'GD': 'Gd',
'gd(ppm)': 'Gd', 'gd(ppb)': 'Gd', 'gd(ppt)': 'Gd',
'gd_ppm': 'Gd', 'gd_ppb': 'Gd', 'gd_ppt': 'Gd',
# Tb variations
'tb': 'Tb', 'TB': 'Tb',
'tb(ppm)': 'Tb', 'tb(ppb)': 'Tb', 'tb(ppt)': 'Tb',
'tb_ppm': 'Tb', 'tb_ppb': 'Tb', 'tb_ppt': 'Tb',
# Dy variations
'dy': 'Dy', 'DY': 'Dy',
'dy(ppm)': 'Dy', 'dy(ppb)': 'Dy', 'dy(ppt)': 'Dy',
'dy_ppm': 'Dy', 'dy_ppb': 'Dy', 'dy_ppt': 'Dy',
# Ho variations
'ho': 'Ho', 'HO': 'Ho',
'ho(ppm)': 'Ho', 'ho(ppb)': 'Ho', 'ho(ppt)': 'Ho',
'ho_ppm': 'Ho', 'ho_ppb': 'Ho', 'ho_ppt': 'Ho',
# Er variations
'er': 'Er', 'ER': 'Er',
'er(ppm)': 'Er', 'er(ppb)': 'Er', 'er(ppt)': 'Er',
'er_ppm': 'Er', 'er_ppb': 'Er', 'er_ppt': 'Er',
# Tm variations
'tm': 'Tm', 'TM': 'Tm',
'tm(ppm)': 'Tm', 'tm(ppb)': 'Tm', 'tm(ppt)': 'Tm',
'tm_ppm': 'Tm', 'tm_ppb': 'Tm', 'tm_ppt': 'Tm',
# Yb variations
'yb': 'Yb', 'YB': 'Yb',
'yb(ppm)': 'Yb', 'yb(ppb)': 'Yb', 'yb(ppt)': 'Yb',
'yb_ppm': 'Yb', 'yb_ppb': 'Yb', 'yb_ppt': 'Yb',
# Lu variations
'lu': 'Lu', 'LU': 'Lu',
'lu(ppm)': 'Lu', 'lu(ppb)': 'Lu', 'lu(ppt)': 'Lu',
'lu_ppm': 'Lu', 'lu_ppb': 'Lu', 'lu_ppt': 'Lu',
# Sr variations
'sr': 'Sr', 'SR': 'Sr',
'sr(ppm)': 'Sr', 'sr(ppb)': 'Sr', 'sr(ppt)': 'Sr',
'sr_ppm': 'Sr', 'sr_ppb': 'Sr', 'sr_ppt': 'Sr',
# Zr variations
'zr': 'Zr', 'ZR': 'Zr',
'zr(ppm)': 'Zr', 'zr(ppb)': 'Zr', 'zr(ppt)': 'Zr',
'zr_ppm': 'Zr', 'zr_ppb': 'Zr', 'zr_ppt': 'Zr',
# Hf variations
'hf': 'Hf', 'HF': 'Hf',
'hf(ppm)': 'Hf', 'hf(ppb)': 'Hf', 'hf(ppt)': 'Hf',
'hf_ppm': 'Hf', 'hf_ppb': 'Hf', 'hf_ppt': 'Hf',
# Ti variations (when as trace element)
'ti': 'Ti', 'TI': 'Ti',
'ti(ppm)': 'Ti', 'ti(ppb)': 'Ti', 'ti(ppt)': 'Ti',
'ti_ppm': 'Ti', 'ti_ppb': 'Ti', 'ti_ppt': 'Ti',
# Y variations
'y': 'Y', 'Y': 'Y',
'y(ppm)': 'Y', 'y(ppb)': 'Y', 'y(ppt)': 'Y',
'y_ppm': 'Y', 'y_ppb': 'Y', 'y_ppt': 'Y',
# Additional elements
# Sc variations
'sc': 'Sc', 'SC': 'Sc',
'sc(ppm)': 'Sc', 'sc(ppb)': 'Sc', 'sc(ppt)': 'Sc',
'sc_ppm': 'Sc', 'sc_ppb': 'Sc', 'sc_ppt': 'Sc',
# V variations
'v': 'V', 'V': 'V',
'v(ppm)': 'V', 'v(ppb)': 'V', 'v(ppt)': 'V',
'v_ppm': 'V', 'v_ppb': 'V', 'v_ppt': 'V',
# Cr variations
'cr': 'Cr', 'CR': 'Cr',
'cr(ppm)': 'Cr', 'cr(ppb)': 'Cr', 'cr(ppt)': 'Cr',
'cr_ppm': 'Cr', 'cr_ppb': 'Cr', 'cr_ppt': 'Cr',
# Co variations
'co': 'Co', 'CO': 'Co',
'co(ppm)': 'Co', 'co(ppb)': 'Co', 'co(ppt)': 'Co',
'co_ppm': 'Co', 'co_ppb': 'Co', 'co_ppt': 'Co',
# Ni variations
'ni': 'Ni', 'NI': 'Ni',
'ni(ppm)': 'Ni', 'ni(ppb)': 'Ni', 'ni(ppt)': 'Ni',
'ni_ppm': 'Ni', 'ni_ppb': 'Ni', 'ni_ppt': 'Ni',
# Cu variations
'cu': 'Cu', 'CU': 'Cu',
'cu(ppm)': 'Cu', 'cu(ppb)': 'Cu', 'cu(ppt)': 'Cu',
'cu_ppm': 'Cu', 'cu_ppb': 'Cu', 'cu_ppt': 'Cu',
# Zn variations
'zn': 'Zn', 'ZN': 'Zn',
'zn(ppm)': 'Zn', 'zn(ppb)': 'Zn', 'zn(ppt)': 'Zn',
'zn_ppm': 'Zn', 'zn_ppb': 'Zn', 'zn_ppt': 'Zn',
# Ga variations
'ga': 'Ga', 'GA': 'Ga',
'ga(ppm)': 'Ga', 'ga(ppb)': 'Ga', 'ga(ppt)': 'Ga',
'ga_ppm': 'Ga', 'ga_ppb': 'Ga', 'ga_ppt': 'Ga',
# Cs variations
'cs': 'Cs', 'CS': 'Cs',
'cs(ppm)': 'Cs', 'cs(ppb)': 'Cs', 'cs(ppt)': 'Cs',
'cs_ppm': 'Cs', 'cs_ppb': 'Cs', 'cs_ppt': 'Cs',
# Pb variations
'pb': 'Pb', 'PB': 'Pb',
'pb(ppm)': 'Pb', 'pb(ppb)': 'Pb', 'pb(ppt)': 'Pb',
'pb_ppm': 'Pb', 'pb_ppb': 'Pb', 'pb_ppt': 'Pb',
}
# Combine all mappings
all_mappings = {**major_elements_map, **trace_elements_map}
# Create a new dataframe with standardized column names
new_columns = []
for col in df.columns:
# First, try direct mapping
col_clean = col.strip()
if col_clean.lower() in all_mappings:
new_columns.append(all_mappings[col_clean.lower()])
else:
# Try to extract element name using regex
# Remove common units and symbols
cleaned_col = re.sub(r'\s*\([^)]*\)\s*', '', col_clean) # Remove anything in parentheses
cleaned_col = re.sub(r'[_\-]\s*(ppm|ppb|ppt|wt%?|weight%?|%)\s*$', '', cleaned_col, flags=re.IGNORECASE) # Remove units at end
cleaned_col = cleaned_col.strip()
if cleaned_col.lower() in all_mappings:
new_columns.append(all_mappings[cleaned_col.lower()])
else:
# Keep original column name if no mapping found
new_columns.append(col)
# Create new dataframe with standardized column names
df_standardized = df.copy()
df_standardized.columns = new_columns
return df_standardized
# Function to load background image for diagrams
def load_background_image(diagram_type):
"""
Load background image for different diagram types
"""
bg_path = None
# Define background image paths for different diagrams
bg_paths = {
'tas': 'PNG to Load/TAS.png',
'pearce': 'PNG to Load/Pearce.png',
'qapf': 'PNG to Load/QAPF.png',
'harker': 'PNG to Load/Harker.png'
}
if diagram_type in bg_paths:
bg_path = bg_paths[diagram_type]
# Check if background image exists
if bg_path and os.path.exists(bg_path):
try:
return mpimg.imread(bg_path)
except Exception as e:
print(f"Error loading background image: {e}")
return None
return None
# Color assignment utility function
def get_color_mapping(df):
"""
Get color mapping for data points based on data file content
Returns: (colors_list, legend_labels)
"""
colors_list = []
legend_labels = []
# Enhanced default color palette with better contrast
default_colors = ['red', 'blue', 'green', 'orange', 'purple', 'brown', 'pink', 'gray', 'olive', 'cyan',
'magenta', 'darkblue', 'darkgreen', 'darkred', 'lightblue', 'lightgreen',
'coral', 'gold', 'indigo', 'crimson', 'forestgreen', 'navy', 'maroon', 'teal',
'slategray', 'chocolate', 'mediumorchid', 'darkorange', 'steelblue', 'darkslategray']
# Check for color-related columns (case insensitive)
color_columns = []
for col in df.columns:
col_lower = col.lower().strip()
if col_lower in ['color', 'colour', 'colors', 'colours', 'type', 'label', 'group', 'groups',
'category', 'categories', 'class', 'classification', 'rock_type', 'rocktype',
'sample_type', 'sampletype', 'formation', 'unit', 'lithology']:
color_columns.append(col)
if color_columns:
# Use the first color-related column found
color_col = color_columns[0]
unique_values = pd.Series(df[color_col].unique()).dropna().tolist()
# Add NaN values if they exist
if df[color_col].isna().any():
unique_values.append(np.nan)
# Create color mapping for unique values
color_map = {}
# Define standard color names that can be used directly
standard_colors = ['red', 'blue', 'green', 'orange', 'purple', 'brown', 'pink', 'gray', 'grey',
'olive', 'cyan', 'magenta', 'yellow', 'black', 'white', 'darkblue', 'darkgreen',
'darkred', 'lightblue', 'lightgreen', 'coral', 'gold', 'indigo', 'crimson',
'forestgreen', 'navy', 'maroon', 'teal', 'chocolate', 'darkorange']
for i, value in enumerate(unique_values):
if pd.isna(value):
color_map[value] = 'gray'
else:
# Check if the value itself is a recognizable color name
value_str = str(value).lower().strip()
if value_str in standard_colors:
color_map[value] = value_str if value_str != 'grey' else 'gray'
else:
color_map[value] = default_colors[i % len(default_colors)]
# Assign colors to each data point
for idx, row in df.iterrows():
value = row[color_col]
colors_list.append(color_map.get(value, 'gray'))
if pd.isna(value):
legend_labels.append(f'Sample {idx+1} (Undefined)')
else:
# Clean label for better display
clean_label = str(value).strip()
legend_labels.append(clean_label)
else:
# No color column found, use default coloring by sample
for i in range(len(df)):
colors_list.append(default_colors[i % len(default_colors)])
legend_labels.append(f'Sample {i+1}')
return colors_list, legend_labels
# We'll implement our own simplified versions of the GeoPyTool modules
# instead of importing them directly to avoid dependencies issues
# Base class for all plot types
class BasePlot:
def __init__(self, df=None, fig=None):
self.df = df
self.fig = fig or plt.figure(figsize=(10, 8))
self.colors, self.legend_labels = get_color_mapping(df) if df is not None else ([], [])
def plot(self):
pass
# TAS diagram implementation based on Wilson et al. 1989
class TAS(BasePlot):
def plot(self):
if self.df is None or self.fig is None:
return
# Check if required columns exist
required_cols = ['SiO2', 'Na2O', 'K2O']
if not all(col in self.df.columns for col in required_cols):
plt.text(0.5, 0.5, 'Missing required columns: SiO2, Na2O, K2O',
horizontalalignment='center', verticalalignment='center', transform=self.fig.transFigure)
return
# Get the axes
ax = self.fig.add_subplot(111)
# Set proper axis ranges and ticks according to TAS.py
ax.set_xlim(30, 90)
ax.set_ylim(0, 20)
ax.set_xticks([30, 40, 50, 60, 70, 80, 90])
ax.set_xticklabels([30, 40, 50, 60, 70, 80, 90])
ax.set_yticks([0, 5, 10, 15, 20])
ax.set_yticklabels([0, 5, 10, 15, 20])
# Try to load background image
bg_img = load_background_image('tas')
if bg_img is not None:
ax.imshow(bg_img, extent=[30, 90, 0, 20], aspect='auto', alpha=0.3)
# Draw TAS classification lines (exact coordinates from TAS.py)
self.draw_tas_lines(ax)
# Draw Irvine-Baragar line
self.draw_irvine_line(ax)
# Plot the data points
for i, (idx, row) in enumerate(self.df.iterrows()):
color = self.colors[i] if i < len(self.colors) else 'blue'
label = self.legend_labels[i] if i < len(self.legend_labels) else f'Sample {i+1}'
ax.scatter(row['SiO2'], row['Na2O'] + row['K2O'],
marker='o', color=color, s=60, alpha=0.8,
label=label, edgecolors='black', linewidth=0.5)
# Add field labels (exact coordinates from TAS.py)
self.add_tas_labels(ax)
# Set labels and title
ax.set_xlabel('SiO₂ wt%', fontsize=12)
ax.set_ylabel('Na₂O + K₂O wt%', fontsize=12)
ax.set_title('TAS (Total Alkali–Silica) Diagram Volcanic (Wilson et al. 1989)', fontsize=14, fontweight='bold')
# Remove top and right spines
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# Add a grid
ax.grid(True, linestyle='--', alpha=0.3)
# Add legend if multiple samples
if len(self.df) > 1 and len(self.df) <= 10:
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=8)
# Add reference
ax.text(0.02, 0.98, 'Reference: Wilson et al. (1989)', transform=ax.transAxes,
fontsize=8, verticalalignment='top', style='italic')
def draw_tas_lines(self, ax):
"""Draw TAS classification boundary lines using exact coordinates from TAS.py"""
# Exact boundary lines from TAS.py
lines = [
[(41, 0), (41, 3), (45, 3)],
[(45, 0), (45, 3), (45, 5), (49.4, 7.3), (53, 9.3), (57.6, 11.7), (61, 13.5), (63, 16.2)],
[(52, 5), (57, 5.9), (63, 7), (69, 8), (71.8, 13.5), (61, 8.6)],
[(45, 2), (45, 5), (52, 5), (45, 2)],
[(69, 8), (77.3, 0), (87.5, 4.7), (85.9, 6.8), (71.8, 13.5), (63, 16.2), (57, 18), (52.5, 18), (37, 14), (35, 9), (37, 3), (41, 3)],
[(63, 0), (63, 7), (57.6, 11.7), (52.5, 14), (52.5, 18)],
[(57, 0), (57, 5.9), (53, 9.3), (48.4, 11.5)],
[(52, 0), (52, 5), (49.4, 7.3), (45, 9.4)],
[(41, 3), (41, 7), (45, 9.4)],
[(45, 9.4), (48.4, 11.5), (52.5, 14)]
]
for line in lines:
x_coords = [point[0] for point in line]
y_coords = [point[1] for point in line]
ax.plot(x_coords, y_coords, 'k-', linewidth=1, alpha=0.8)
def draw_irvine_line(self, ax):
"""Draw Irvine-Baragar line using exact formula from TAS.py"""
y_irvine = np.arange(0, 10.2, 0.1)
x_irvine = []
# Exact Irvine formula from TAS.py
a, b, c, d, e, f, g = 39.0, 3.9492, -2.1111, 0.86096, -0.15188, 0.012030, -(3.3539 / 10000)
for y in y_irvine:
x = a + b * np.power(y, 1) + c * np.power(y, 2) + d * np.power(y, 3) + e * np.power(y, 4) + f * np.power(y, 5) + g * np.power(y, 6)
x_irvine.append(x)
ax.plot(x_irvine, y_irvine, color='black', linewidth=1,
linestyle=':', alpha=0.6, label='Irvine & Baragar (1971)')
def add_tas_labels(self, ax):
"""Add rock type labels using exact coordinates from TAS.py"""
# Exact label positions from TAS.py
locations = [(39, 10), (43, 1.5), (44, 6), (47.5, 3.5), (49.5, 1.5), (49, 5.2), (49, 9.5),
(54, 3), (53, 7), (53, 12), (60, 4), (57, 8.5), (57, 14), (67, 5), (65, 12),
(67, 9), (75, 9), (85, 1), (55, 18.5)]
# Volcanic labels from TAS.py
labels = ['F', 'Pc', 'U1', 'Ba', 'Bs', 'S1', 'U2', 'O1', 'S2', 'U3', 'O2', 'S3',
'Ph', 'O3', 'T', 'Td', 'R', 'Q', 'S/N/L']
# Full names for tooltips
full_names = {
'F': 'Foidite', 'Ph': 'Phonolite', 'Pc': 'Picrobasalt',
'U1': 'Tephrite/Basanite', 'U2': 'Phonotephrite', 'U3': 'Tephriphonolite',
'Ba': 'Alkalic Basalt', 'Bs': 'Subalkalic Basalt',
'S1': 'Trachybasalt', 'S2': 'Basaltic Trachyandesite', 'S3': 'Trachyandesite',
'O1': 'Basaltic Andesite', 'O2': 'Andesite', 'O3': 'Dacite',
'T': 'Trachyte', 'Td': 'Trachydacite', 'R': 'Rhyolite', 'Q': 'Silexite',
'S/N/L': 'Sodalitite/Nephelinolith/Leucitolith'
}
x_offset, y_offset = -6, 3
for i, (location, label) in enumerate(zip(locations, labels)):
if i < len(locations) and i < len(labels):
x, y = location
if 30 <= x <= 90 and 0 <= y <= 20: # Within plot bounds
ax.annotate(label, (x, y), xytext=(x_offset, y_offset),
textcoords='offset points', fontsize=9,
color='grey', alpha=0.8, fontweight='bold')
# Add description text
description = ('F: Foidite, Ph: Phonolite, Pc: Picrobasalt, U1: Tephrite (ol < 10%) Basanite(ol > 10%),\n'
'U2: Phonotephrite, U3: Tephriphonolite, Ba: alkalic basalt, Bs: subalkalic basalt,\n'
'S1: Trachybasalt, S2: Basaltic Trachyandesite, S3: Trachyandesite,\n'
'O1: Basaltic Andesite, O2: Andesite, O3: Dacite, T: Trachyte, Td: Trachydacite,\n'
'R: Rhyolite, Q: Silexite, S/N/L: Sodalitite/Nephelinolith/Leucitolith')
ax.text(0.02, 0.02, description, transform=ax.transAxes, fontsize=7,
verticalalignment='bottom', style='italic',
bbox=dict(boxstyle='round,pad=0.3', facecolor='white', alpha=0.8))
# Harker diagram implementation
class Harker(BasePlot):
def plot(self):
if self.df is None or self.fig is None:
return
# Check if SiO2 column exists
if 'SiO2' not in self.df.columns:
plt.text(0.5, 0.5, 'Missing required column: SiO2',
horizontalalignment='center', verticalalignment='center', transform=self.fig.transFigure)
return
# Define oxides to plot against SiO2
oxides = ['Al2O3', 'Fe2O3', 'MgO', 'CaO', 'Na2O', 'K2O', 'TiO2', 'P2O5', 'MnO']
available_oxides = [oxide for oxide in oxides if oxide in self.df.columns]
if not available_oxides:
plt.text(0.5, 0.5, 'No oxide columns found to plot against SiO2',
horizontalalignment='center', verticalalignment='center', transform=self.fig.transFigure)
return
# Create subplots
num_oxides = len(available_oxides)
rows = (num_oxides + 2) // 3 # Ceiling division
cols = min(3, num_oxides)
# Create a figure with subplots
for i, oxide in enumerate(available_oxides):
ax = self.fig.add_subplot(rows, cols, i+1)
# Plot each sample with consistent colors
for j, (idx, row) in enumerate(self.df.iterrows()):
color = self.colors[j] if j < len(self.colors) else 'blue'
label = self.legend_labels[j] if j < len(self.legend_labels) else f'Sample {j+1}'
ax.scatter(row['SiO2'], row[oxide], marker='o', color=color, alpha=0.6,
label=label if i == 0 else '', s=40, edgecolors='black', linewidth=0.3)
ax.set_xlabel('SiO2 (wt%)')
ax.set_ylabel(f'{oxide} (wt%)')
ax.grid(True, linestyle='--', alpha=0.5)
# Add legend to the entire figure if multiple samples with distinct groups
if len(self.df) > 1 and len(self.df) <= 10:
# Create a legend for the whole figure using unique labels
handles, labels = [], []
unique_labels = []
for i, label in enumerate(self.legend_labels):
if label not in unique_labels:
unique_labels.append(label)
color = self.colors[i] if i < len(self.colors) else 'blue'
# Create a dummy scatter plot for the legend
from matplotlib.lines import Line2D
handles.append(Line2D([0], [0], marker='o', color='w', markerfacecolor=color,
markersize=8, alpha=0.8, markeredgecolor='black'))
labels.append(label)
if handles:
self.fig.legend(handles, labels, loc='center right', bbox_to_anchor=(0.98, 0.5),
fontsize=10, frameon=True, fancybox=True, shadow=True)
self.fig.tight_layout()
self.fig.suptitle('Harker Diagrams', fontsize=16)
self.fig.subplots_adjust(top=0.92, right=0.85 if len(self.df) > 1 and len(self.df) <= 10 else 0.95)
# REE diagram implementation based on REE.py
class REE(BasePlot):
def __init__(self, df=None, fig=None, standard='C1 Chondrite Sun and McDonough,1989'):
super().__init__(df, fig)
self.standard = standard
# All available standards from REE.py
self.standards = {
'C1 Chondrite Sun and McDonough,1989': {
'La': 0.237, 'Ce': 0.612, 'Pr': 0.095, 'Nd': 0.467, 'Sm': 0.153,
'Eu': 0.058, 'Gd': 0.2055, 'Tb': 0.0374, 'Dy': 0.254, 'Ho': 0.0566,
'Er': 0.1655, 'Tm': 0.0255, 'Yb': 0.17, 'Lu': 0.0254
},
'Chondrite Taylor and McLennan,1985': {
'La': 0.367, 'Ce': 0.957, 'Pr': 0.137, 'Nd': 0.711, 'Sm': 0.231,
'Eu': 0.087, 'Gd': 0.306, 'Tb': 0.058, 'Dy': 0.381, 'Ho': 0.0851,
'Er': 0.249, 'Tm': 0.0356, 'Yb': 0.248, 'Lu': 0.0381
},
'Chondrite Haskin et al.,1966': {
'La': 0.32, 'Ce': 0.787, 'Pr': 0.112, 'Nd': 0.58, 'Sm': 0.185, 'Eu': 0.071,
'Gd': 0.256, 'Tb': 0.05, 'Dy': 0.343, 'Ho': 0.07, 'Er': 0.225, 'Tm': 0.03,
'Yb': 0.186, 'Lu': 0.034
},
'Chondrite Nakamura,1977': {
'La': 0.33, 'Ce': 0.865, 'Pr': 0.112, 'Nd': 0.63, 'Sm': 0.203, 'Eu': 0.077,
'Gd': 0.276, 'Tb': 0.047, 'Dy': 0.343, 'Ho': 0.07, 'Er': 0.225, 'Tm': 0.03,
'Yb': 0.22, 'Lu': 0.034
},
'MORB Sun and McDonough,1989': {
'La': 2.5, 'Ce': 7.5, 'Pr': 1.32, 'Nd': 7.3, 'Sm': 2.63, 'Eu': 1.02, 'Gd': 3.68,
'Tb': 0.67, 'Dy': 4.55, 'Ho': 1.052, 'Er': 2.97, 'Tm': 0.46, 'Yb': 3.05,
'Lu': 0.46
},
'UCC_Rudnick & Gao2003': {
'La': 31, 'Ce': 63, 'Pr': 7.1, 'Nd': 27, 'Sm': 4.7, 'Eu': 1, 'Gd': 4, 'Tb': 0.7,
'Dy': 3.9, 'Ho': 0.83, 'Er': 2.3, 'Tm': 0.3, 'Yb': 1.96, 'Lu': 0.31
}
}
def plot(self):
if self.df is None or self.fig is None:
return
# REE elements in exact order from REE.py
ree_elements = ['La', 'Ce', 'Pr', 'Nd', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu']
available_rees = [ree for ree in ree_elements if ree in self.df.columns]
if not available_rees:
plt.text(0.5, 0.5, 'No REE columns found\nRequired: La, Ce, Pr, Nd, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb, Lu',
horizontalalignment='center', verticalalignment='center', transform=self.fig.transFigure,
fontsize=12, bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))
return
# Get the axes
ax = self.fig.add_subplot(111)
# Get the selected normalization standard
normalization_values = self.standards.get(self.standard, self.standards['C1 Chondrite Sun and McDonough,1989'])
# Track Y range for proper scaling
y_bottom, y_top = float('inf'), float('-inf')
# Plot each sample
for i, (idx, row) in enumerate(self.df.iterrows()):
color = self.colors[i] if i < len(self.colors) else 'blue'
label = self.legend_labels[i] if i < len(self.legend_labels) else f'Sample {i+1}'
# Calculate normalized values and log transform
lines_x = []
lines_y = []
for j, ree in enumerate(available_rees):
if ree in normalization_values and not pd.isna(row[ree]) and row[ree] > 0:
try:
normalized_value = row[ree] / normalization_values[ree]
log_value = np.log10(normalized_value)
lines_x.append(j + 1) # X positions start from 1
lines_y.append(log_value)
# Track Y range
if log_value < y_bottom:
y_bottom = log_value
if log_value > y_top:
y_top = log_value
# Plot points
ax.scatter(j + 1, log_value, marker='o', color=color, s=50,
alpha=0.8, edgecolors='black', linewidth=0.5)
except (ValueError, ZeroDivisionError):
continue
# Connect points with lines (exact behavior from REE.py)
if len(lines_x) > 1:
ax.plot(lines_x, lines_y, color=color, linewidth=1.5,
alpha=0.8, label=label)
# Set proper axis ranges and ticks according to REE.py
xticks = list(range(1, len(available_rees) + 1))
ax.set_xticks(xticks)
ax.set_xticklabels(available_rees, rotation=45, fontsize=10)
# Set Y axis with proper range
if y_bottom != float('inf') and y_top != float('-inf'):
y_range = y_top - y_bottom
ax.set_ylim(y_bottom - y_range * 0.1, y_top + y_range * 0.1)
# Create Y tick labels showing actual values (not log values)
y_ticks = ax.get_yticks()
y_tick_labels = [f'{10**tick:.2g}' for tick in y_ticks]
ax.set_yticklabels(y_tick_labels, fontsize=8)
# Remove top and right spines
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# Set labels and title
ax.set_xlabel('REE Standardized Pattern', fontsize=12)
ax.set_ylabel(f'Sample/{self.standard.split(" ")[0]}', fontsize=12)
ax.set_title('REE Standardized Pattern Diagram', fontsize=14, fontweight='bold')
# Add a grid
ax.grid(True, linestyle='--', alpha=0.3)
# Add legend if multiple samples
if len(self.df) > 1 and len(self.df) <= 10:
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=8)
# Add reference
ax.text(0.02, 0.98, f'Standard: {self.standard}',
transform=ax.transAxes, fontsize=8, verticalalignment='top', style='italic')
# Trace element diagram implementation based on Trace.py and TraceNew.py
class Trace(BasePlot):
def __init__(self, df=None, fig=None, standard='PM', element_set='cs_lu'):
super().__init__(df, fig)
self.standard = standard
self.element_set = element_set
# All available standards from Trace.py
self.standards = {
'PM': {
'Cs': 0.032, 'Tl': 0.005, 'Rb': 0.635, 'Ba': 6.989, 'W': 0.02, 'Th': 0.085, 'U': 0.021, 'Nb': 0.713,
'Ta': 0.041, 'K': 250, 'La': 0.687, 'Ce': 1.775, 'Pb': 0.185, 'Pr': 0.276, 'Mo': 0.063, 'Sr': 21.1,
'P': 95, 'Nd': 1.354, 'F': 26, 'Sm': 0.444, 'Zr': 11.2, 'Hf': 0.309, 'Eu': 0.168, 'Sn': 0.17,
'Sb': 0.005, 'Ti': 1300, 'Gd': 0.596, 'Tb': 0.108, 'Dy': 0.736, 'Li': 1.6, 'Y': 4.55, 'Ho': 0.164,
'Er': 0.48, 'Tm': 0.074, 'Yb': 0.493, 'Lu': 0.074
},
'OIB': {
'Cs': 0.387, 'Tl': 0.077, 'Rb': 31, 'Ba': 350, 'W': 0.56, 'Th': 4, 'U': 1.02, 'Nb': 48, 'Ta': 2.7,
'K': 12000, 'La': 36, 'Ce': 80, 'Pb': 3.2, 'Pr': 9.7, 'Mo': 2.4, 'Sr': 660, 'P': 2700, 'Nd': 38.5,
'F': 1150, 'Sm': 10, 'Zr': 280, 'Hf': 7.8, 'Eu': 3, 'Sn': 2.7, 'Sb': 0.03, 'Ti': 17200, 'Gd': 7.62,
'Tb': 1.05, 'Dy': 5.6, 'Li': 5.6, 'Y': 29, 'Ho': 1.06, 'Er': 2.62, 'Tm': 0.35, 'Yb': 2.16, 'Lu': 0.3
},
'EMORB': {
'Cs': 0.063, 'Tl': 0.013, 'Rb': 5.04, 'Ba': 57, 'W': 0.092, 'Th': 0.6, 'U': 0.18, 'Nb': 8.3,
'Ta': 0.47, 'K': 2100, 'La': 6.3, 'Ce': 15, 'Pb': 0.6, 'Pr': 2.05, 'Mo': 0.47, 'Sr': 155, 'P': 620,
'Nd': 9, 'F': 250, 'Sm': 2.6, 'Zr': 73, 'Hf': 2.03, 'Eu': 0.91, 'Sn': 0.8, 'Sb': 0.01, 'Ti': 6000,
'Gd': 2.97, 'Tb': 0.53, 'Dy': 3.55, 'Li': 3.5, 'Y': 22, 'Ho': 0.79, 'Er': 2.31, 'Tm': 0.356,
'Yb': 2.36, 'Lu': 0.354
},
'C1': {
'Cs': 0.188, 'Tl': 0.14, 'Rb': 2.32, 'Ba': 2.41, 'W': 0.095, 'Th': 0.029, 'U': 0.008, 'Nb': 0.246,
'Ta': 0.014, 'K': 545, 'La': 0.236, 'Ce': 0.612, 'Pb': 2.47, 'Pr': 0.095, 'Mo': 0.92, 'Sr': 7.26,
'P': 1220, 'Nd': 0.467, 'F': 60.7, 'Sm': 0.153, 'Zr': 3.87, 'Hf': 0.1066, 'Eu': 0.058, 'Sn': 1.72,
'Sb': 0.16, 'Ti': 445, 'Gd': 0.2055, 'Tb': 0.0364, 'Dy': 0.254, 'Li': 1.57, 'Y': 1.57, 'Ho': 0.0566,
'Er': 0.1655, 'Tm': 0.0255, 'Yb': 0.17, 'Lu': 0.0254
},
'NMORB': {
'Cs': 0.007, 'Tl': 0.0014, 'Rb': 0.56, 'Ba': 6.3, 'W': 0.01, 'Th': 0.12, 'U': 0.047, 'Nb': 2.33,
'Ta': 0.132, 'K': 600, 'La': 2.5, 'Ce': 7.5, 'Pb': 0.3, 'Pr': 1.32, 'Mo': 0.31, 'Sr': 90, 'P': 510,
'Nd': 7.3, 'F': 210, 'Sm': 2.63, 'Zr': 74, 'Hf': 2.05, 'Eu': 1.02, 'Sn': 1.1, 'Sb': 0.01, 'Ti': 7600,
'Gd': 3.68, 'Tb': 0.67, 'Dy': 4.55, 'Li': 4.3, 'Y': 28, 'Ho': 1.01, 'Er': 2.97, 'Tm': 0.456,
'Yb': 3.05, 'Lu': 0.455
},
'UCC_Rudnick & Gao2003': {
'K': 23244.13676, 'Ti': 3835.794545, 'P': 654.6310022, 'Li': 24, 'Be': 2.1, 'B': 17, 'N': 83, 'F': 557, 'S': 62, 'Cl': 360, 'Sc': 14, 'V': 97, 'Cr': 92,
'Co': 17.3, 'Ni': 47, 'Cu': 28, 'Zn': 67, 'Ga': 17.5, 'Ge': 1.4, 'As': 4.8, 'Se': 0.09,
'Br': 1.6, 'Rb': 84, 'Sr': 320, 'Y': 21, 'Zr': 193, 'Nb': 12, 'Mo': 1.1, 'Ru': 0.34,
'Pd': 0.52, 'Ag': 53, 'Cd': 0.09, 'In': 0.056, 'Sn': 2.1, 'Sb': 0.4, 'I': 1.4, 'Cs': 4.9,
'Ba': 628, 'La': 31, 'Ce': 63, 'Pr': 7.1, 'Nd': 27, 'Sm': 4.7, 'Eu': 1, 'Gd': 4, 'Tb': 0.7,
'Dy': 3.9, 'Ho': 0.83, 'Er': 2.3, 'Tm': 0.3, 'Yb': 1.96, 'Lu': 0.31, 'Hf': 5.3, 'Ta': 0.9,
'W': 1.9, 'Re': 0.198, 'Os': 0.031, 'Ir': 0.022, 'Pt': 0.5, 'Au': 1.5, 'Hg': 0.05, 'Tl': 0.9,
'Pb': 17, 'Bi': 0.16, 'Th': 10.5, 'U': 2.7
}
}
# Element sequences (exact order from Trace.py and TraceNew.py)
self.element_sets = {
'cs_lu': ['Cs', 'Tl', 'Rb', 'Ba', 'W', 'Th', 'U', 'Nb', 'Ta', 'K', 'La', 'Ce', 'Pb', 'Pr', 'Mo',
'Sr', 'P', 'Nd', 'F', 'Sm', 'Zr', 'Hf', 'Eu', 'Sn', 'Sb', 'Ti', 'Gd', 'Tb', 'Dy',
'Li', 'Y', 'Ho', 'Er', 'Tm', 'Yb', 'Lu'],
'rb_lu': ['Rb', 'Ba', 'Th', 'U', 'Nb', 'Ta', 'K', 'La', 'Ce', 'Pr', 'Sr', 'P', 'Nd',
'Zr', 'Hf', 'Sm', 'Eu', 'Ti', 'Tb', 'Dy', 'Y', 'Ho', 'Er', 'Tm', 'Yb', 'Lu']
}
def plot(self):
if self.df is None or self.fig is None:
return
# Get element sequence and normalization values
element_sequence = self.element_sets.get(self.element_set, self.element_sets['cs_lu'])
normalization_values = self.standards.get(self.standard, self.standards['PM'])
# Find available elements in data
available_elements = []
missing_elements = []
for element in element_sequence:
if element in self.df.columns:
available_elements.append(element)
elif element == 'K' and 'K2O' in self.df.columns:
available_elements.append(element) # We'll convert K2O to K
elif element == 'Ti' and 'TiO2' in self.df.columns:
available_elements.append(element) # We'll convert TiO2 to Ti
else:
missing_elements.append(element)
if not available_elements:
plt.text(0.5, 0.5, f'No trace element columns found\nRequired elements from {element_set_name} sequence not available\nMissing elements: {", ".join(missing_elements[:10])}{"..." if len(missing_elements) > 10 else ""}',
horizontalalignment='center', verticalalignment='center', transform=self.fig.transFigure,
fontsize=12, bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))
return
# Get the axes
ax = self.fig.add_subplot(111)
# Track Y range for proper scaling
y_bottom, y_top = float('inf'), float('-inf')
# Plot each sample
for i, (idx, row) in enumerate(self.df.iterrows()):
color = self.colors[i] if i < len(self.colors) else 'blue'
label = self.legend_labels[i] if i < len(self.legend_labels) else f'Sample {i+1}'
# Calculate normalized values and log transform
lines_x = []
lines_y = []
for j, element in enumerate(available_elements):
if element in normalization_values:
# Get the raw value
if element in self.df.columns and not pd.isna(row[element]) and row[element] > 0:
raw_value = row[element]
elif element == 'K' and 'K2O' in self.df.columns and not pd.isna(row['K2O']):
# Convert K2O to K (from Trace.py)
raw_value = row['K2O'] * (2 * 39.0983 / 94.1956) * 10000
elif element == 'Ti' and 'TiO2' in self.df.columns and not pd.isna(row['TiO2']):
# Convert TiO2 to Ti (from Trace.py)
raw_value = row['TiO2'] * (47.867 / 79.865) * 10000
else:
continue
try:
normalized_value = raw_value / normalization_values[element]
log_value = np.log10(normalized_value)
lines_x.append(j + 1) # X positions start from 1
lines_y.append(log_value)
# Track Y range
if log_value < y_bottom:
y_bottom = log_value
if log_value > y_top:
y_top = log_value
# Plot points
ax.scatter(j + 1, log_value, marker='o', color=color, s=50,
alpha=0.8, edgecolors='black', linewidth=0.5)
except (ValueError, ZeroDivisionError):
continue
# Connect points with lines
if len(lines_x) > 1:
ax.plot(lines_x, lines_y, color=color, linewidth=1.5,
alpha=0.8, label=label)
# Set proper axis ranges and ticks
xticks = list(range(1, len(available_elements) + 1))
ax.set_xticks(xticks)
ax.set_xticklabels(available_elements, rotation=-45, fontsize=10)
# Set Y axis with proper range
if y_bottom != float('inf') and y_top != float('-inf'):
y_range = y_top - y_bottom
ax.set_ylim(y_bottom - y_range * 0.1, y_top + y_range * 0.1)
# Create Y tick labels showing actual values (not log values)
y_ticks = ax.get_yticks()
y_tick_labels = [f'{10**tick:.2g}' for tick in y_ticks]
ax.set_yticklabels(y_tick_labels, fontsize=8)
# Remove top and right spines
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# Set labels and title
element_set_name = 'Cs-Lu (36 Elements)' if self.element_set == 'cs_lu' else 'Rb-Lu (26 Elements)'
ax.set_xlabel(f'Trace Elements Standardized Pattern', fontsize=12)
ax.set_ylabel(f'Sample/{self.standard}', fontsize=12)
ax.set_title(f'Trace Element Standardized Pattern Diagram\n{element_set_name} - {len(available_elements)} Elements Available',
fontsize=14, fontweight='bold')
# Add a grid
ax.grid(True, linestyle='--', alpha=0.3)
# Add legend if multiple samples
if len(self.df) > 1 and len(self.df) <= 10:
ax.legend(bbox_to_anchor=(1.05, 1), loc='upper left', fontsize=8)
# Add comprehensive reference information
reference_map = {
'PM': 'Sun, S.S. & McDonough, W.F. (1989)',
'OIB': 'Sun, S.S. & McDonough, W.F. (1989)',
'EMORB': 'Sun, S.S. & McDonough, W.F. (1989)',
'C1': 'Sun, S.S. & McDonough, W.F. (1989)',
'NMORB': 'Sun, S.S. & McDonough, W.F. (1989)',
'UCC_Rudnick & Gao2003': 'Rudnick, R.L. & Gao, S. (2003)'
}
reference_text = f'Standard: {self.standard} ({reference_map.get(self.standard, "")}) \nElements: {len(available_elements)} of {element_set_name}'
ax.text(0.02, 0.98, reference_text,
transform=ax.transAxes, fontsize=8, verticalalignment='top', style='italic')
# Pearce diagram implementation based on Pearce.py
class Pearce(BasePlot):
def __init__(self, df=None, fig=None):
super().__init__(df, fig)
# Define the four different conditions from Pearce.py
self.conditions = [
{
'BaseLines': [[(2, 80), (55, 300)],
[(55, 300), (400, 2000)],
[(55, 300), (51.5, 8)],
[(51.5, 8), (50, 1)],
[(51.5, 8), (2000, 400)]],
'xLabel': 'Y+Nb (ppm)',
'yLabel': 'Rb (ppm)',
'Labels': ['syn-COLG', 'VAG', 'WPG', 'ORG'],
'Locations': [(1, 3), (1, 1), (2.4, 2.4), (3, 1)],
'xlim': (0.3, 3.2),
'ylim': (0, 3.2),
'xticks': [1, 2, 3],
'xticklabels': [10, 100, 1000],
'yticks': [0, 1, 2, 3],
'yticklabels': [1, 10, 100, 1000]
},
{
'BaseLines': [[(0.5, 140), (6, 200)],
[(6, 200), (50, 2000)],
[(6, 200), (6, 8)],
[(6, 8), (6, 1)],
[(6, 8), (200, 400)]],
'xLabel': 'Yb+Ta (ppm)',
'yLabel': 'Rb (ppm)',
'Labels': ['syn-COLG', 'VAG', 'WPG', 'ORG'],
'Locations': [(0.5, 3), (0.5, 1), (1.5, 2.4), (2, 1)],
'xlim': (-0.2, 2.5),
'ylim': (0, 3.2),
'xticks': [0, 1, 2],
'xticklabels': [1, 10, 100],
'yticks': [0, 1, 2, 3],
'yticklabels': [1, 10, 100, 1000]