-
Notifications
You must be signed in to change notification settings - Fork 1
/
nsb_adp_wx.py
2298 lines (2146 loc) · 109 KB
/
nsb_adp_wx.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
# -*- coding: utf-8 -*-
import os, sys, subprocess
reload(sys)
sys.setdefaultencoding("utf-8")
# Basic modules
import decimal, string, datetime
import re, math
from bisect import bisect_left
import csv
# Math & DB-related modules
import numpy as np
import pandas as pd
import pandas.io.sql as psql
from sqlalchemy import create_engine
# GUI modules
import wx, wx.html
# Plot-related modules
import matplotlib
matplotlib.use('wxAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
# QUERY_ functions
def query_loc(engine,holeID):
"""Query LOC from database."""
sqlRev = "SELECT c.site_hole as sh, c.revision_no as rn, current_flag, age_quality, interpreted_by, date_worked, remark FROM neptune_age_model_history as c, neptune_hole_summary as b WHERE c.site_hole=b.site_hole AND b.hole_id='%s' ORDER BY current_flag, rn DESC;" % (holeID,)
revision_no = psql.read_sql_query(sqlRev, engine)
if len(revision_no):
revdial = RevisionDialog(None,revision_no)
if revdial.ShowModal() == wx.ID_OK:
sel = revdial.list_ctrl.GetFirstSelected()
rev = revdial.amList[sel]
sqlLOC = "SELECT age_ma, depth_mbsf, revision_no FROM neptune_age_model b WHERE b.site_hole = '%s' AND revision_no=%i ORDER BY age_ma, depth_mbsf;" % (rev['sh'],int(rev['rn']))
dfLOC = psql.read_sql_query(sqlLOC, engine)
else: dfLOC = []
else: dfLOC = []
return dfLOC
def query_events(engine,data): #Query events from tables in NSB Berlin database.
sqlDATUM = """SELECT top_hole_id AS hole_id,
event_group AS fossil_group,
event_group AS plot_fossil_group,
event_name AS datum_name,
event_type AS datum_type,
event_extent,
plotcode AS plot_code,
CASE
WHEN bottom_depth_mbsf IS NOT NULL THEN
bottom_depth_mbsf
WHEN sample_bottom IS NOT NULL THEN
neptuneCoreDepth(top_hole_id,sample_bottom)
END AS bottom_depth,
CASE
WHEN top_depth_mbsf IS NOT NULL THEN
top_depth_mbsf
WHEN sample_top IS NOT NULL THEN
neptuneCoreDepth(top_hole_id,sample_top)
END AS top_depth,
a.event_id AS event_id
FROM neptune_event a, neptune_event_def c
WHERE a.event_id = c.event_id
AND top_hole_id = '%s';""" % (data['holeID'],)
sqlCALIB = """SELECT event_id, calibration_scale AS scale, calibration_year, young_age_ma AS datum_age_min_ma, old_age_ma AS datum_age_max_ma
FROM neptune_event_calibration
WHERE (event_id,calibration_year) IN (
SELECT DISTINCT event_id,MAX(calibration_year) AS calibration_year
FROM neptune_event_calibration
GROUP BY event_id)
UNION
SELECT event_id, scale, NULL AS calibration_year, age_ma AS datum_age_min_ma, age_ma AS datum_age_max_ma
FROM neptune_gpts
WHERE scale = '%s';""" % (data['toScale'],)
datums = psql.read_sql_query(sqlDATUM, engine)
calibs = psql.read_sql_query(sqlCALIB, engine)
dfDATUMS = pd.merge(datums, calibs, how='left', on='event_id')
dfDATUMS = dfDATUMS.where((pd.notnull(dfDATUMS)), None)
for i in range(0,len(dfDATUMS)):
if dfDATUMS['top_depth'][i] is None:
dfDATUMS['top_depth'][i] = dfDATUMS['bottom_depth'][i]
elif dfDATUMS['bottom_depth'][i] is None:
dfDATUMS['bottom_depth'][i] = dfDATUMS['top_depth'][i]
dfDATUMS['datum_name'][i] = dfDATUMS['datum_name'][i].encode('utf-8')
if dfDATUMS['datum_age_min_ma'][i] is None:
dfDATUMS['datum_age_min_ma'][i] = dfDATUMS['datum_age_max_ma'][i]
if dfDATUMS['datum_age_max_ma'][i] is None:
dfDATUMS['datum_age_max_ma'][i] = dfDATUMS['datum_age_min_ma'][i]
return dfDATUMS
def query_cores(engine,holeID): #Work
"""Query for cores from database."""
sqlCORE = """SELECT core,core_top_mbsf AS top_depth, (core_top_mbsf + core_length) AS bottom_depth
FROM neptune_core WHERE hole_id = '%s' ORDER BY top_depth;""" % (holeID,)
dfCORES = psql.read_sql_query(sqlCORE,engine)
dfCORES = dfCORES[dfCORES.core.str.contains('^[0-9]+$')]
dfCORES.core = dfCORES.core.astype(int)
dfCORES = dfCORES.sort_values('core')
dfCORES['newIndex'] = range(0,len(dfCORES))
dfCORES = dfCORES.set_index('newIndex')
return dfCORES
def query_paleomag_interval(engine,holeID): #Work
"""Query for paleomag intervals from database."""
sqlPMAG = """SELECT top_depth,bottom_depth,color,pattern,width
FROM neptune_paleomag_interval
WHERE hole_id = '%s';""" % (holeID,)
dfPMAGS = psql.read_sql_query(sqlPMAG,engine)
return dfPMAGS
# FIX_ functions:
def fix_null(t,fixType):
"""Fix missing values."""
if pd.isnull(t):
t = None
elif type(t) == str and t.strip() == '':
t = None
if fixType and t is not None: # Ages (fixType = 1), return a float value
return float(t)
else:
return t
# CALC_ functions:
def calc_core_depth(origCore,dfCORES):
"""Calculate mbsf depth for cores (core-section,int)."""
ccFlag = 0
origCore = origCore.strip()
if origCore[0] == '-':
origCore = origCore[1:]
if origCore[0] == '?':
origCore = origCore[1:]
if origCore.find('(') > 0:
origCore = origCore[0:origCore.find('(')-1]
coreIdx = int(origCore[0:origCore.find('-')])-1
topDepth = dfCORES['top_depth'][coreIdx]
botDepth = dfCORES['bottom_depth'][coreIdx]
section = origCore[origCore.find('-')+1:]
if section[0] == 'C': # Is this a core-catcher?
if section.find(',') > 0: # CC,int
topDepth = dfCORES['bottom_depth'][coreIdx]
section = '1'
ccFlag = 1
else:
depth = dfCORES['bottom_depth'][coreIdx] # CC but not CC,int
return abs(depth)
if ccFlag == 0:
section = section[0:section.find(',')]
interval = origCore[origCore.find(',')+1:]
depth = topDepth + (int(section)-1) * 1.5 + .01 * float(interval)
return abs(depth)
def calc_depth_ma(depth,x,y):
"""Calculate age from depth along LOC"""
if depth < abs(y[0]) or depth > abs(y[len(y)-1]): # Outside of LOC range
return None
i = 0
while (depth >= abs(y[i])):
i += 1
ma = x[i-1]
ratio = (depth - abs(y[i-1])) / (abs(y[i]) - abs(y[i-1]))
if ratio > 0:
ma += ratio * (abs(x[i]) - abs(x[i-1]))
return ma
def age_convert(age, fromScale, toScale):
"""
Convert an age from one timescale to another.
Based on Johan Renaudie code in AgeScaleTransform.py .
"""
conv = []
for i in [k['event_id'] for k in fromScale]:
if i in [k['event_id'] for k in toScale]:
conv.append({'event_id':i,
'fromScale': [k['age_ma'] for k in fromScale if k['event_id']==i][0],
'toScale':[k['age_ma'] for k in toScale if k['event_id']==i][0]})
conv = sorted(conv,key=lambda x:float(x['fromScale']))
old = map(float,[k['fromScale'] for k in conv])
new = map(float,[k['toScale'] for k in conv])
m = bisect_left(old, age)
if m == 0:
n = new[0]
elif m == len(fromScale):
n = new[-1]
else:
n = new[m-1] + (age - old[m-1])*(new[m]-new[m-1])/(old[m]-old[m-1])
return n
def uploadAgeModel(engine, data, x, y, currentFlag):
new = list(zip(x,y))
hole = data['holeID']
date = datetime.date.today()
username = data['user']
model = 'Seton et al. 2012'
revq = "SELECT revision_no FROM neptune_age_model_history WHERE site_hole='%s';" % (hole,)
rev = psql.read_sql_query(revq,engine)
rev = rev['revision_no']
new_rev = max(rev)+1 if len(rev) else 0
to_upload = [{'rev': new_rev, 'hole':hole, 'age':k, 'mbsf':m} for k,m in new]
cf = 'Y' if currentFlag else 'N'
with engine.begin() as con:
if len(rev) and currentFlag:
con.execute("UPDATE neptune_age_model_history SET current_flag='N' WHERE site_hole='%s';" % (hole,))
con.execute("INSERT INTO neptune_age_model_history (site_hole, revision_no, current_flag,interpreted_by, date_worked) VALUES ('%s',%s,'%s','%s','%s');" % (hole,new_rev,cf,username,date))
iq = ["INSERT INTO neptune_age_model (site_hole, revision_no, age_ma, depth_mbsf) VALUES ('%s',%s,%s,%s);" % (hole, new_rev, k, m) for k,m in new]
for q in iq:
con.execute(q)
errmsg = 'Age model successfully uploaded.\n'
if currentFlag:
mbsf = map(float,[k[0] for k in new])
age = map(float,[k[1] for k in new])
# Upgrade sample age
hole_id = psql.read_sql_query("SELECT hole_id FROM neptune_hole_summary WHERE site_hole='%s';" % (hole,), engine)
samples = psql.read_sql_query("SELECT sample_id, sample_depth_mbsf FROM neptune_sample WHERE hole_id='%s';" % (hole_id['hole_id'], ), engine)
samp_id = samples['sample_id']
samp_mbsf = samples['sample_depth_mbsf']
samp_age = []
for i in xrange(len(samp_mbsf)):
if samp_mbsf[i] < mbsf[0]:
samp_age.append({'age':None,'id':samp_id[i]})
elif samp_mbsf[i] > mbsf[-1]:
samp_age.append({'age':None,'id':samp_id[i]})
else:
m = bisect_left(mbsf,samp_mbsf[i])
samp_age.append({'age':age[m-1] + (samp_mbsf[i] - mbsf[m-1])*(age[m]-age[m-1])/(mbsf[m]-mbsf[m-1]),'id':samp_id[i]})
up_q1 = ['UPDATE neptune_sample SET sample_age_ma=%s WHERE sample_id=%s;' % (k['age'],k['id']) for k in samp_age]
# Upgrade sample paleocoordinates
pg = psql.read_sql_query("SELECT reconstructed_age_ma, paleo_latitude, paleo_longitude FROM neptune_paleogeography WHERE hole_id=%s AND rotation_source=%s;" % (hole_id['hole_id'],model,), engine)
pg = pg.sort_values('reconstructed_age_ma')
rage = pg['reconstructed_age_ma']
lat = pg['paleo_latitude']
lon = pg['paleo_longitude']
samp_coord = []
for i in xrange(len(samp_age)):
if samp_age[i] > rage[-1]:
samp_coord.append({'paleo_latitude':None,'paleo_longitude':None,'id':samp_id[i]})
else:
m = bisect_left(age,samp_age[i])
samp_coord.append({'paleo_latitude':lat[m-1]+(samp_age[i]-rage[m-1])*(lat[m]-lat[m-1])/(rage[m]-rage[m-1]),
'paleo_longitude':lon[m-1]+(samp_age[i]-rage[m-1])*(lon[m]-lon[m-1])/(rage[m]-rage[m-1]),
'id':samp_id[i]})
up_q2 = ['UPDATE neptune_sample SET paleo_latitude=%s, paleo_longitude=%s WHERE sample_id=%s;'% (k['paleo_latitude'],k['paleo_longitude'],k['id']) for k in samp_coord]
with engine.begin() as con:
con.execute("UPDATE neptune_age_model_history SET current_flag='Y' WHERE site_hole='%s' and revision_no <> %s;" % (hole, new_rev))
con.executemany(up_q1)
con.executemany(up_q2)
errmsg = errmsg + 'Sample ages and paleocoordinates successfully updated.\n'
return errmsg
# PLOT_ functions:
def get_plot_groups(dfDATUMS,plotCodes):
"""Get unique plot groups (fossilGroup and datumType) from datums dataframe
and setup as list with [group,plot,label,highlight].
Use plotCodes argument to set the initial label state.
"""
plotGroups = []
datumGroups = pd.unique(dfDATUMS['plot_fossil_group'].tolist())
for i in range (0,len(datumGroups)):
plotGroups.append([datumGroups[i],1,plotCodes,0,'T']) # Top
plotGroups.append([datumGroups[i],1,plotCodes,0,'B']) # Base
plotGroups.append([datumGroups[i],1,plotCodes,0,'x']) # Other
return plotGroups
def plot_datums(data,fig,ax,canvas):
"""Plot strat datums by fossil group (color) and top/base (symbol)."""
dfDATUMS = data['dfDATUMS']
plotGroups = data['plotGroups']
plotCodes = data['plotCodes']
# Setup lists for using with AnnoteFinder
xdata = []
ydata = []
plotCodeID = []
# Save the processed data into lists for using later
saveGroups = []
saveRangeGroups = []
saveRangeBoxes = []
# Read in config file
configfile = os.environ['NSBPATH'] + "/REF/plot_config.txt"
with open(configfile,'rU') as f:
r = csv.reader(f,delimiter='\t')
h = r.next()
stdMarkers = []
stdColors = []
for row in r:
stdMarkers.append([row[0],row[2],row[2]])
if data['plotColorType'] == 1:
stdColors.append([row[0],'k'])
else:
stdColors.append([row[0], row[3]])
tops = ['ACME','DISP','LCO','TOP','T','Z']
bases = ['BOT','REAP','FCO','EVOL','B']
for i in range(0,len(dfDATUMS)):
# Defaults for non-configured eent groups.
marker = '*'
color = 'k'
lcolor = 'k'
fillstyle = 'full'
fossilGroup = dfDATUMS['plot_fossil_group'][i]
datumType = dfDATUMS['datum_type'][i]
if datumType in tops:
datumType = 'T'
elif datumType in bases:
datumType = 'B'
else: datumType = 'x'
# Match fossilGroup with plotGroups for controls for plot,label,highlight ...
plotGroupIdx = [ind for ind, k in enumerate(plotGroups) if k[0] == fossilGroup and k[4] == datumType][0]
# Match datum fossil_group to stdMarkers fossil_group
if fossilGroup in [k[0] for k in stdMarkers]:
marker = [k[1] for k in stdMarkers if k[0]==fossilGroup][0]
if data['plotColorType'] != 2:
color = [k[1] for k in stdColors if k[0]==fossilGroup][0]
lcolor = color
fillstyle = 'top' if datumType == 'T' else 'bottom' if datumType =='B' else 'full'
else:
fillstyle = 'full'
lcolor = [k[1] for k in stdColors if k[0]==fossilGroup][0]
color = lcolor if datumType =='B' else 'white'
# Calculate average depth and average age
if dfDATUMS['top_depth'][i] is not None and dfDATUMS['bottom_depth'][i] is not None:
avg_depth = (dfDATUMS['top_depth'][i] + dfDATUMS['bottom_depth'][i]) / 2.
yHeight = abs(dfDATUMS['top_depth'][i] - dfDATUMS['bottom_depth'][i])
else:
avg_depth = None
yHeight = 0
if dfDATUMS['datum_age_max_ma'][i] is not None and dfDATUMS['datum_age_min_ma'][i] is not None:
avg_age = (dfDATUMS['datum_age_max_ma'][i] + dfDATUMS['datum_age_min_ma'][i]) / 2.
xWidth = dfDATUMS['datum_age_max_ma'][i] - dfDATUMS['datum_age_min_ma'][i]
elif dfDATUMS['datum_age_max_ma'][i] is not None:
avg_age = dfDATUMS['datum_age_max_ma'][i]
xWidth = 0
else:
avg_age = dfDATUMS['datum_age_min_ma'][i]
xWidth = 0
# Set the markersize
if plotGroups[plotGroupIdx][3] == 1:
markersize = 9 # Highlight
else:
markersize = 7 # No highlight
# Save data to lists for AnnoteFinder
xdata.append(avg_age)
ydata.append(avg_depth)
label = dfDATUMS['plot_code'][i] + ':' + dfDATUMS['datum_name'][i]
plotCodeID.append((dfDATUMS['plot_code'][i],dfDATUMS['datum_name'][i], lcolor))
fd = fossilGroup+':'+datumType
# Plot range as box
if yHeight > 0 and xWidth > 0: saveRangeBoxes.append([plotGroupIdx, fd, dfDATUMS['datum_age_min_ma'][i], dfDATUMS['top_depth'][i], xWidth, yHeight, 'white'])
if yHeight > 0: saveRangeGroups.append([plotGroupIdx, fd, [avg_age,avg_age], [dfDATUMS['top_depth'][i],dfDATUMS['bottom_depth'][i]], lcolor])
if xWidth > 0: saveRangeGroups.append([plotGroupIdx, fd, [dfDATUMS['datum_age_max_ma'][i],dfDATUMS['datum_age_min_ma'][i]], [avg_depth,avg_depth], lcolor])
# Annotate the datums with the plotCode
# DEV: might fix this section to only use plotGroups ... either you
# DEV: are plotting the symbol and the code, or else just the symbol ...
if plotCodes == 1:
# DEV: testing box around label
#plt.annotate(dfDATUMS['plot_code'][i], xy=(avg_age + 0.1, avg_depth), size=8.,ha='left', color=lcolor, bbox=props)
plt.annotate(dfDATUMS['plot_code'][i], xy=(avg_age + 0.1,avg_depth), size=7.,ha='left',color=lcolor)
elif plotGroups[plotGroupIdx][2] == 1:
plt.annotate(dfDATUMS['plot_code'][i],xy=(avg_age+0.1,avg_depth), size=7.,ha='left',color=lcolor)
# Save group plotting data to list
saveGroups.append([plotGroupIdx,fossilGroup,datumType,avg_age, avg_depth,marker,markersize,color,fillstyle,label])
# Add avg_age, avg_depth to dfDATUMS
dfDATUMS['plot_age'] = xdata
dfDATUMS['plot_depth'] = ydata
# Turn lists into dataframe
headers = ['plotGroupIdx','fossilGroup','datumType','avg_age','avg_depth',
'marker','markersize','color','fillstyle','label']
dfGROUPS = pd.DataFrame(saveGroups, columns=headers)
# If any of the datums had a range, save to a group for line toggling
dfRangeGROUPS = pd.DataFrame(saveRangeGroups, columns=['plotGroupIdx','rangeGroup', 'xline', 'yline', 'color']) if len(saveRangeGroups) > 0 else []
# If any of the datums had a box range, save to a group for rectangle toggling
dfRangeBOXES = pd.DataFrame(saveRangeBoxes, columns=['plotGroupIdx','boxGroup', 'xmin', 'ymax', 'xWidth','yHeight', 'color']) if len(saveRangeBoxes) > 0 else []
# Extract line groups from dataframe, sort for legend
lines = []
lineGroups = pd.unique(dfGROUPS['plotGroupIdx'].tolist())
lineGroups.sort()
linesr = [] # Lines for ranges
boxesr = [] # Boxes for ranges
# Re-organize, plot, and save lines to list
for i in range(0,len(lineGroups)):
pltLine = dfGROUPS[(dfGROUPS.plotGroupIdx == lineGroups[i])]
newIndex=range(0,len(pltLine))
pltLine['newIndex'] = newIndex
pltLine = pltLine.set_index('newIndex')
xd = zip(pltLine['avg_age'])
yd = zip(pltLine['avg_depth'])
lid = 'line'+str(i)
gid = str(lineGroups[i])
lid, = plt.plot(xd, yd, marker=pltLine['marker'][0], markersize=pltLine['markersize'][0],
color=pltLine['color'][0], fillstyle=pltLine['fillstyle'][0], lw=0,
label=pltLine['fossilGroup'][0]+":"+ pltLine['datumType'][0],gid=gid)
lines.append(lid)
# Plot and save age-depth ranges to lines list
for i in range(0,len(dfRangeGROUPS)):
xd = dfRangeGROUPS['xline'][i]
yd = dfRangeGROUPS['yline'][i]
color = dfRangeGROUPS['color'][i]
lidr = dfRangeGROUPS['rangeGroup'][i]+'.'+str(i)
gid = str(dfRangeGROUPS['plotGroupIdx'][i])
lidr, = plt.plot(xd, yd, color, linewidth=0.5, gid=gid)
linesr.append(lidr)
# Plot and save age-depth ranges box to boxes list
for i in range(0,len(dfRangeBOXES)):
xmin = dfRangeBOXES['xmin'][i]
ymax = dfRangeBOXES['ymax'][i]
xWidth = dfRangeBOXES['xWidth'][i]
yHeight = dfRangeBOXES['yHeight'][i]
color = dfRangeBOXES['color'][i]
bidr = dfRangeBOXES['boxGroup'][i]+'.'+str(i)
gid = str(dfRangeBOXES['plotGroupIdx'][i])
rectangle = plt.Rectangle((xmin,ymax), xWidth, yHeight, facecolor=color, gid=gid)
plt.gca().add_patch(rectangle)
boxesr.append(rectangle)
# Plot legend
leg = plt.legend(bbox_to_anchor=(1.0025,0.75), loc=2, borderaxespad=0., numpoints=1)
leg.get_frame().set_alpha(0.4)
lined = dict()
for legline, origline in zip(leg.get_lines(), lines):
legline.set_picker(5) # 5 pts tolerance
lined[legline] = origline
def on_legend_pick(event, lined):
"""Match picked legend line to original line and toggle visibility."""
legline = event.artist
origline = lined[legline]
# Get texts of legend
ltexts = leg.get_texts()
# Get label of picked legend line
legLabel = origline.get_label()
# Toggle visibility of the picked line (fossil_group/datum_type)
vis = not origline.get_visible()
origline.set_visible(vis)
# Get the gid of the line being toggled
# Match to range lines, and toggle them too
gid = origline.get_gid()
for i in range(0,len(linesr)):
theLine = linesr[i]
if theLine.get_gid() == gid:
theLine.set_visible(vis)
# Match to range boxes, and toggle them too
for i in range(0,len(boxesr)):
theBox = boxesr[i]
if theBox.get_gid() == gid:
theBox.set_visible(vis)
if vis:
#legline.set_alpha(1.0) # Doesn't help, markers not lines...
# Set color of legend text to black (on)
for i in range(0,len(ltexts)):
if legLabel == ltexts[i].get_text():
ltexts[i].set_color('black')
break
else:
#legline.set_alpha(0.1) # Doesn't help, markers not lines...
# Set color of legend text to red (off)
for i in range(0,len(ltexts)):
if legLabel == ltexts[i].get_text():
ltexts[i].set_color('red')
break
fig.canvas.draw()
# Register the callback for picking a line legend
#canvas = ax.figure.canvas
canvas.mpl_connect('pick_event', lambda e:on_legend_pick(e, lined))
# Use AnnoteFinder to identify datums on plot
af = AnnoteFinder(xdata, ydata, plotCodeID)
# Register the callback for AnnoteFinder
canvas.mpl_connect('button_press_event',af)
def plot_cores(dfCORES,xMin,xMax,yMin,yMax):
"""Plot the cores and core sections."""
# Calculate width of rectangle for plotting cores
cWidth = (xMax - xMin) * .025
# Build x values for rectangles
xline=[]
xline.append(xMax - cWidth / 5.)
xline.append(xMax)
for i in range(0,len(dfCORES)):
if dfCORES['top_depth'][i] >= yMin and dfCORES['bottom_depth'][i] <= yMax:
cHeight = abs((dfCORES['bottom_depth'][i] - dfCORES['top_depth'][i]))
rectangle = plt.Rectangle((xMax - cWidth, dfCORES['top_depth'][i]),
cWidth, cHeight, fc='none')
plt.gca().add_patch(rectangle)
plt.annotate(dfCORES['core'][i],xy=(xMax -cWidth / 2.,
dfCORES['top_depth'][i] + (cHeight / 2.)), size=6.,
ha='center', va='center')
# Plot the section subdivisions
sections = int(abs((dfCORES['top_depth'][i] -
dfCORES['bottom_depth'][i]) / 1.5))
for j in range(1,sections+1):
yline=[]
yline.append(dfCORES['top_depth'][i] + j * 1.5)
yline.append(dfCORES['top_depth'][i] + j * 1.5)
plt.plot(xline, yline, 'r-', linewidth=1.0)
def plot_time_scale(dfTIME,xMin,xMax,yMin,yMax):
"""Plot the time scale boundaries."""
scaleName = dfTIME['time_scale_name']
ageLevel = dfTIME['age_level_name']
ageName = dfTIME['age_name']
ageMinMa = dfTIME['age_min_ma']
ageMaxMa = dfTIME['age_max_ma']
for i in range(0,len(ageName)):
# Extract and clean up ageName (Upper/Middle/Early)
if ageLevel[i] == 'Subepoch':
ageName[i] = ageName[i][ageName[i].find(' ') + 1:]
if ageName[i] == 'Upper':
ageName[i] = 'Late'
elif ageName[i] == 'Lower':
ageName[i] = 'Early'
# Pad on y-axis
cHeight = -abs((yMax - yMin)*.025)
yMinPad = yMin - (abs(yMax - yMin)*.05)
# DEV: make a function to determine position relative to axes, and use
# DEV: for stages and chrons, and...
for i in range(0,len(dfTIME)):
if (ageMinMa[i] >= xMin and ageMinMa[i] <= xMax and ageMaxMa[i] >= xMin and ageMaxMa[i] <= xMax) or (ageMinMa[i] < xMin and ageMaxMa[i] > xMin) or (ageMinMa[i] < xMax and ageMaxMa[i] > xMax):
if ageLevel[i] == 'Epoch':
rectangle = plt.Rectangle((ageMinMa[i],yMinPad-cHeight),ageMaxMa[i]-ageMinMa[i],cHeight,fc='none')
plt.gca().add_patch(rectangle)
rectangle = plt.Rectangle((ageMinMa[i],yMinPad-(cHeight*2.)),ageMaxMa[i]-ageMinMa[i],cHeight,fc='none')
plt.gca().add_patch(rectangle)
if ageMinMa[i] < xMin and ageName[i] != 'Holocene':
plt.annotate(ageName[i],xy=((xMin+ageMaxMa[i])/2.,yMinPad-(cHeight/2.)),size=9.,ha='center',va='center')
elif ageMaxMa[i] > xMax and ageName[i] != 'Holocene':
plt.annotate(ageName[i],xy=((xMax+ageMinMa[i])/2.,yMinPad-(cHeight/2.)),size=9.,ha='center',va='center')
elif ageName[i] != 'Holocene':
plt.annotate(ageName[i],xy=((ageMinMa[i]+ageMaxMa[i])/2.,yMinPad-(cHeight/2.)),size=9.,ha='center',va='center')
elif ageLevel[i] == 'Subepoch':
#elif (ageLevel[i] == 'Stage'): # DEV: testing Stages, maybe an option?
rectangle = plt.Rectangle((ageMinMa[i],yMinPad-(cHeight*2.)),ageMaxMa[i]-ageMinMa[i],cHeight,fc='none')
plt.gca().add_patch(rectangle)
if ageMinMa[i] < xMin:
plt.annotate(ageName[i],xy=((xMin+ageMaxMa[i])/2.,yMinPad-(cHeight*1.2)),size=8.,ha='center',va='top')
elif ageMaxMa[i] > xMax:
plt.annotate(ageName[i],xy=((xMax+ageMinMa[i])/2.,yMinPad-(cHeight*1.2)),size=8.,ha='center',va='top')
else:
plt.annotate(ageName[i],xy=((ageMinMa[i]+ageMaxMa[i])/2.,yMinPad-(cHeight*1.2)),size=8.,ha='center',va='top')
def plot_paleomag_interval(dfPMAGS,xMin,xMax,yMin,yMax):
"""Plot the pmag intervals."""
xWidth = abs(xMax - xMin) * .0275
topDepth = dfPMAGS['top_depth']
bottomDepth = dfPMAGS['bottom_depth']
intColor = dfPMAGS['color']
for i in range(0,len(topDepth)):
yHeight = abs(topDepth[i] - bottomDepth[i])
if intColor[i] == 1:
color='black'
else:
color='white'
rectangle = plt.Rectangle((xMin, topDepth[i]), xWidth, yHeight,
facecolor=color)
plt.gca().add_patch(rectangle)
def plot_chrons(dfCHRONS,xMin,xMax,yMin,yMax):
"""Plot the paleomagnetic chrons."""
# Plot the chrons
# DEV: plot_chrons(dfCHRONS,xMin,xMax,yMin,yMax): clean this up,
# DEV: as in stages ... to make it easier to read and understand ...
# DEV: note: later might have all scales read, need to extract
# DEV: current one being plotted ...
# Calculate height of rectangle from Y axis range
cHeight = -abs((yMax-yMin)*.025)
for i in range(0,len(dfCHRONS)):
if ((dfCHRONS['chron_age_min_ma'][i] >= xMin and dfCHRONS['chron_age_min_ma'][i] <= xMax
and dfCHRONS['chron_age_max_ma'][i] >= xMin and dfCHRONS['chron_age_max_ma'][i] <= xMax)
or (dfCHRONS['chron_age_min_ma'][i] <= xMin and dfCHRONS['chron_age_max_ma'][i] > xMin)
or (dfCHRONS['chron_age_min_ma'][i] < xMax and dfCHRONS['chron_age_max_ma'][i] > xMax)):
if dfCHRONS['chron_polarity_dir'][i] == None or pd.isnull(dfCHRONS['chron_polarity_dir'][i]): # None/NaN/NULL
rectangle = plt.Rectangle((dfCHRONS['chron_age_min_ma'][i],yMax-cHeight),dfCHRONS['chron_age_max_ma'][i]-dfCHRONS['chron_age_min_ma'][i],cHeight,fc='none')
plt.gca().add_patch(rectangle)
rectangle = plt.Rectangle((dfCHRONS['chron_age_min_ma'][i],yMax-(cHeight*2.)),dfCHRONS['chron_age_max_ma'][i]-dfCHRONS['chron_age_min_ma'][i],cHeight,fc='none')
plt.gca().add_patch(rectangle)
if dfCHRONS['chron_age_min_ma'][i] < xMin:
plt.annotate(dfCHRONS['chron_name'][i][1:],xy=((xMin+dfCHRONS['chron_age_max_ma'][i])/2.,yMax-(cHeight/2.)),size=6.,ha='center',va='center')
elif dfCHRONS['chron_age_max_ma'][i] > xMax:
plt.annotate(dfCHRONS['chron_name'][i][1:],xy=((xMax+dfCHRONS['chron_age_min_ma'][i])/2.,yMax-(cHeight/2.)),size=6.,ha='center',va='center')
else:
plt.annotate(dfCHRONS['chron_name'][i][1:],xy=((dfCHRONS['chron_age_min_ma'][i]+dfCHRONS['chron_age_max_ma'][i])/2.,yMax-(cHeight/2.)),size=6.,ha='center',va='center')
elif dfCHRONS['chron_polarity_dir'][i] == 'N': # Normal polarity
rectangle = plt.Rectangle((dfCHRONS['chron_age_min_ma'][i],yMax-(cHeight*2.)),dfCHRONS['chron_age_max_ma'][i]-dfCHRONS['chron_age_min_ma'][i],cHeight,fc='black')
plt.gca().add_patch(rectangle)
def plot_metadata(parent, xMin, xMax, yMin, yMax, data):
"""Plot metadata."""
userName = data['user']
stratFileName = data['stratFileName']
locFileName = data['LOCFileName'][parent.locIdx] if type(data['LOCFileName']) is list else data['LOCFileName']
# Plot userName, stratFileName, locFileName, and timestamp
# Get the current timestamp
stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Strip path from stratFileName and plot
if '/' in stratFileName:
stratFileName = stratFileName[stratFileName.rfind('/')+1:]
plt.text(xMax,yMax - (abs(yMin)-abs(yMax))*.125,'Strat: ' + stratFileName,size=8., ha='right')
# Strip path from locFileName and plot
if '/' in locFileName:
locFileName = locFileName[locFileName.rfind('/')+1:]
# If locFileName plot
if len(data['phantom']):
plt.text(xMax,yMax - (abs(yMin)-abs(yMax))*.150,'Active LOC: ' + locFileName + ' | Phantom LOC: ' + data['phantom']['loc_name'],size=8., ha='right')
else:
plt.text(xMax,yMax - (abs(yMin)-abs(yMax))*.150,'LOC: ' + locFileName,size=8., ha='right')
plt.text(xMax,yMin + (abs(yMin)-abs(yMax))*.10,userName,size=8., ha='right')
plt.text(xMax,yMin + (abs(yMin)-abs(yMax))*.075,stamp,size=8., ha='right')
def set_labels(labels):
"""Set axes values for plot."""
new_labels = LabelDialog(labels)
if new_labels.ShowModal()== wx.ID_OK:
title = str(new_labels.title.GetValue())
xaxis = str(new_labels.xaxis.GetValue())
yaxis = str(new_labels.yaxis.GetValue())
return [title,xaxis,yaxis]
else:
return labels
def set_axes(parent, axes):
"""Set axes values for plot."""
while 1:
new_axes = AxisDialog([axes[0], axes[1], axes[3], axes[2]])
if new_axes.ShowModal()== wx.ID_OK:
xmin = float(new_axes.xmin.GetValue())
xmax = float(new_axes.xmax.GetValue())
ymax = float(new_axes.ymin.GetValue())
ymin = float(new_axes.ymax.GetValue())
fieldValues = [xmin, xmax, ymin, ymax]
if fieldValues is None:
fieldValues = axes
break
errmsg = ""
if fieldValues[0] >= fieldValues[1]: errmsg = 'youngest age should be < to oldest age.\n'
if fieldValues[2] >= fieldValues[3]: errmsg = 'higher depth should be < to lower depth.\n'
if errmsg == "": break
else: parent.messageboard.WriteText("Error: " + errmsg)
else:
fieldValues = axes
break
return fieldValues
class AnnoteFinder: #Pat's code, largely untouched
"""
Callback for matplotlib to display an annotation when points are clicked on.
The point which is closest to the click and within xtol and ytol is
identified.
Register this function like this:
scatter(xdata, ydata)
af = AnnoteFinder(xdata, ydata, annotes)
connect('button_press_event', af)
"""
# DEV: class AnnoteFinder: code copied, modified from jkitchin
# DEV: see jkitchin on GitHub
# DEV: John Kitchin, Carnegie Mellon University ([email protected])
# DEV: code from annotate_picks.py and mmapsrep.py
def __init__(self,xdata,ydata,annotes,axis=None,xtol=None,ytol=None):
self.ANN = zip(xdata,ydata,annotes)
if xtol is None:
xtol = 0.1
if ytol is None:
ytol = 1.5
self.xtol = xtol
self.ytol = ytol
self.axis = axis if axis is not None else plt.gca()
self.drawnAnnotations = {}
self.links = []
def __call__(self,event):
if event.inaxes:
clickX = event.xdata
clickY = event.ydata
if self.axis is None or self.axis==event.inaxes:
annotes = []
for x,y,a in self.ANN:
if clickX-self.xtol < x < clickX+self.xtol and clickY-self.ytol < y < clickY+self.ytol:
# DEV: added button check
if event.button == 1 or event.button == 2:
a = a[0]+":"+a[2] # For plot_code, plot_color
btn = event.button
else:
a = a[0]+":"+a[1]+":"+a[2] # For plot_code, datum_name, color
btn = 3
annotes.append((math.hypot(x - clickX, y - clickY),x,y,a))
if annotes:
# DEV: modification: report all at x,y
for i in range(0,len(annotes)):
distance, x, y, annote = annotes[i]
#self.drawAnnote(event.inaxes,x,y,annote) # Modification
self.drawAnnote(event.inaxes,x,y,annote,clickX,clickY,i,btn)
for j in self.links:
j.drawSpecificAnnote(annote)
# Modification: added clickX,clickY,idx
def drawAnnote(self,axis,x,y,annote,clickX,clickY,idx,btn):
"""
Draw the annotation on the plot
"""
if self.drawnAnnotations.has_key((x,y)): # Modification
markers = self.drawnAnnotations[(x,y)]
for m in markers:
m.set_visible(not m.get_visible())
self.axis.figure.canvas.draw()
del self.drawnAnnotations[(x,y)] # Modification
else:
color = annote[annote.rfind(':',0)+1:]
annote = annote[0:annote.rfind(':',0)]
if clickX <= x: # DEV: figure quadrant to post text
xpos = x - .10
ha = 'right'
else:
xpos = x + .10
ha = 'left'
if clickY <= y:
ypos = y - .10
va = 'top' if idx == 0 else 'bottom'
else:
ypos = y + .10
va = 'bottom' if idx == 0 else 'top'
if btn == 1:
t = axis.text(xpos,ypos,"%s"%(annote),size=7.,color=color,horizontalalignment=ha,verticalalignment=va)
else:
t = axis.text(xpos,ypos,"%s (%6.3f, %8.3f)"%(annote,x,y),size=7.,color=color,horizontalalignment=ha,verticalalignment=va)
#m = axis.scatter([x],[y],marker='o',s=128,alpha=0.4,c='yellow') # DEV: highlight with yellow circle
m = axis.scatter([x],[y],marker='.',s=0,c='k',zorder=100) # DEV: modified, s=0 to show text only
self.drawnAnnotations[(x,y)]=(t,m)
self.axis.figure.canvas.draw()
# DEV: can use this code with modification to toggle on/off all annotations
# DEV: modify code for event with key_pressed 't' or 'a' ....
# DEV: see annotation_picks_ALL.py that shows modifications (don't check for distance/xtol/ytol)
def drawSpecificAnnote(self,annote):
annotesToDraw = [(x,y,a) for x,y,a in self.data if a==annote]
for x,y,a in annotesToDraw:
self.drawAnnote(self.axis,x,y,a)
# Pat functions adapted to wx by JR:
# READ_ functions:
def read_gpts(parent):
"""Read GPTS from file."""
parent.messageboard.WriteText('reading GPTS for converting ages\n')
fileName = os.environ['NSBPATH'] + "/REF/gpts.txt"
dfGPTS = pd.read_csv(fileName, delimiter='\t', header=0, skiprows=1,
names=['event_id', 'event_type', 'event_name',
'age_ma', 'scale'],
usecols=[0,1,2,3,4])
return dfGPTS
def read_paleomag_scale(parent,toScale):
"""Read CHRON intervals from file."""
parent.messageboard.WriteText('reading paleomag scale data file\n')
fileName = os.environ['NSBPATH'] + "/REF/paleomagscale.txt"
dfCHRONS = pd.read_csv(fileName, delimiter='\t', header=0, skiprows=1,
names=['paleomag_scale_name',
'chron_name', 'chron_alias',
'chron_polarity_dir', 'chron_age_min_ma',
'chron_age_max_ma', 'chron_id',
'parent_chron_id'],
usecols=[0,1,2,3,4,5,6,7])
df = dfCHRONS[dfCHRONS.paleomag_scale_name == toScale]
newIndex=range(0,len(df))
df['newIndex'] = newIndex
df = df.set_index('newIndex')
return df
def read_time_scale(parent, toScale):
"""Read geological timescale data from a file."""
parent.messageboard.WriteText('reading timescale data file\n')
fileName = os.environ['NSBPATH'] + "/REF/timescale.txt"
dfTIME = pd.read_csv(fileName, delimiter='\t', header=0, skiprows=1,
names=['time_scale_name', 'age_level_name',
'age_name', 'age_min_ma', 'age_max_ma',
'age_id', 'parent_age_id'],
usecols=[0,1,2,3,4,5,6])
df = dfTIME[dfTIME.time_scale_name == toScale]
newIndex=range(0,len(df))
df['newIndex'] = newIndex
df = df.set_index('newIndex')
return df
def read_datums(parent,fileName, data):
"""Read datum strat events from file."""
df = [] # Return empty if Cancel on read
parent.messageboard.WriteText('reading strat (datums) data file\n')
datumType = []
if fileName == '.':
parent.messageboard.WriteText('no strat datums read\n')
return df
r = csv.reader(open(fileName,'rU'),delimiter='\t')
d = []
n = 0
for row in r:
n += 1
if n == 1: # Header
check_holeID = row[0].upper()
if check_holeID != data['holeID']:
parent.messageboard.WriteText("*** Wrong holeID: " + check_holeID + " ***\n")
parent.messageboard.WriteText("*** Skipping read strat file, will not plot ***\n")
return df
#timescale = row[1] # Not used but for clarification on time scale ...
data['fromScale'] = row[2] # Global fromScale for paleomag age conversions
if data['fromScale'] not in set(data['dfGPTS']['scale']):
parent.messageboard.WriteText("*** Unknown GPTS scale: " + data['fromScale'] + " ***\n")
return df
if n > 2 and len(row)>1 and not(row[0].startswith("#")): # Data
d.append({'plot_fossil_group':row[0], 'datum_name':row[1],
'plot_code':row[2], 'datum_age_min_ma':row[3],
'datum_age_max_ma':row[4], 'top_depth':row[5],
'bottom_depth':row[6]})
df = pd.DataFrame(d, columns = ['plot_fossil_group', 'datum_name',
'plot_code', 'datum_age_min_ma',
'datum_age_max_ma', 'top_depth',
'bottom_depth'])
for i in range(len(df)):
df['plot_fossil_group'][i] = df['plot_fossil_group'][i].strip()
df['plot_code'][i] = df['plot_code'][i].strip()
df['datum_name'][i] = df['datum_name'][i].strip()
df['top_depth'][i] = df['top_depth'][i].strip()
df['bottom_depth'][i] = fix_null(df['bottom_depth'][i],0)
if df['bottom_depth'][i] is None:
df['bottom_depth'][i] = df['top_depth'][i]
df['top_depth'][i] = fix_null(df['top_depth'][i],0)
df['bottom_depth'][i] = fix_null(df['bottom_depth'][i],0)
df['datum_age_min_ma'][i] = fix_null(df['datum_age_min_ma'][i],1)
df['datum_age_max_ma'][i] = fix_null(df['datum_age_max_ma'][i],1)
if df['datum_age_min_ma'][i] is None:
df['datum_age_min_ma'][i] = df['datum_age_max_ma'][i]
elif df['datum_age_max_ma'][i] is None:
df['datum_age_max_ma'][i] = df['datum_age_min_ma'][i]
if df['top_depth'][i].find('-') > 0:
if df['top_depth'][i] == '0-0,0':
df['top_depth'][i] = 0.
else:
df['top_depth'][i] = calc_core_depth(df['top_depth'][i],data['dfCORES'])
else:
df['top_depth'][i] = float(df['top_depth'][i])
if df['bottom_depth'][i].find('-') > 0:
df['bottom_depth'][i] = calc_core_depth(df['bottom_depth'][i],data['dfCORES'])
else:
df['bottom_depth'][i] = float(df['bottom_depth'][i])
typDat = df['plot_code'][i][0].upper() if len(df['plot_code'][i]) else ''
datumType.append(typDat)
df['datum_type'] = datumType
return df
def read_cores(parent,fileName,data):
"""Read cores file."""
df = [ ] # Return empty if cancel on read
parent.messageboard.WriteText('reading core data file\n')
if fileName == '.':
parent.messageboard.WriteText('no cores read\n')
return df
r = csv.reader(open(fileName,'rU'),delimiter='\t')
d = []
n = 0
for row in r:
n += 1
if n == 1: # Extract global holeID
data['holeID'] = row[0].upper()
if n > 2 and len(row)>1 and not(row[0].startswith("#")): # Data lines
d.append({'core':int(row[0]), 'top_depth':float(row[1]),
'bottom_depth':float(row[2])})
df = pd.DataFrame(d, columns = ['core', 'top_depth', 'bottom_depth'])
return df
def read_paleomag_interval(parent,fileName):
"""Read PMAG intervals from file."""
df = [ ] # Return empty if cancel on read
parent.messageboard.WriteText('reading paleomag interval data file\n')
if fileName != '.':
r = csv.reader(open(fileName,'rU'),delimiter='\t')
d = []
n = 0
for row in r:
n += 1
if n == 1: # Check that the holeID is the correct one
check_holeID = row[0].upper()
if check_holeID != holeID:
parent.messageboard.WriteText("*** Wrong PMAG holeID: " + check_holeID + " ***\n")
parent.messageboard.WriteText("*** Skipping read PMAG file, will not plot ***\n")
return df
if n > 2 and len(row)>1 and not(row[0].startswith("#")): # Data lines
d.append({'top_depth':float(row[0]),
'bottom_depth':float(row[1]), 'color':int(row[2]),
'pattern':row[3], 'width':float(row[4])})
df = pd.DataFrame(d, columns = ['top_depth', 'bottom_depth',
'color', 'pattern', 'width'])
return df
def read_loc(parent,fileName, data):
""" Read LOC from file.""" # To extract from file for age conversions (paleomag scale)
df = [] # Return empty if Cancel on read
parent.messageboard.WriteText('reading LOC data file\n')
if fileName != '.': # Check for Cancel
r = csv.reader(open(fileName,'rU'),delimiter='\t')
d = []
n = 0
for row in r:
n += 1
if n == 1: # Check that the holeID is the correct one
check_holeID = row[0].upper()
if check_holeID != data['holeID']:
parent.messageboard.WriteText("*** Wrong LOC holeID: " + check_holeID + " ***\n")
parent.messageboard.WriteText("*** Beware that this LOC was not prepared for this hole! ***\n")
parent.messageboard.WriteText("*** If this was not intentional, you can add the correct LOC using the menu option. ***\n")
#parent.messageboard.WriteText("*** Skipping read LOC file, will not plot ***\n")
#return df
#timeScale = row[1] # Time scale, e.g., Berg95
fromScale = row[1] # Paleomag chron scale, e.g., CK95
if fromScale not in set(data['dfGPTS']['scale']):
parent.messageboard.WriteText("*** Unknown GPTS scale: " + fromScale + " ***\n")
return df
if n > 2 and len(row)>1 and not(row[0].startswith("#")): # Data lines
try:
d.append({'age_ma':float(row[0]), 'depth_mbsf':float(row[1])})
except:
parent.messageboard.WriteText("*** Non-numerical value in row " + str(n) + ", LOC not plotting ***\n")
return []
df = pd.DataFrame(d, columns = ['age_ma', 'depth_mbsf'])
for i in range(len(df)):
df['depth_mbsf'][i] = fix_null(df['depth_mbsf'][i],1)
if fromScale != data['toScale']:
fromAgeDict = data['dfGPTS'][['event_id','age_ma']][data['dfGPTS'].scale == fromScale].to_dict('records')
toAgeDict = data['dfGPTS'][['event_id','age_ma']][data['dfGPTS'].scale == data['toScale']].to_dict('records')
for i in range(0,len(df)):
locAge = df['age_ma'][i]
df['age_ma'][i] = float(str(round(age_convert(locAge, fromAgeDict, toAgeDict),3)))
return df
#SAVE_ functions:
def upload_loc(parent, data, x, y):
if 'pw' not in data.keys():
db_login = dbDialog(self,data)
if db_login.ShowModal() == wx.ID_OK: # When OK clicked:
# Collect and save data entered, for later connexions
data['server'] = db_login.source.GetStringSelection()
data['user'] = db_login.username.GetValue()
data['pw'] = db_login.password.GetValue()
else:
return
server = "212.201.100.111" if data['server'] == "external" else "localhost" if data['server'] == "local copy" else "192.168.101.133"
theEngine = "postgresql://%s:%s@%s/nsb" % (data['user'],data['pw'],server)
engine = None
try: # Try to connect
engine = create_engine(theEngine, client_encoding='latin1')
engine.connect()
except: # If unsuccessfull, say so and go back to Welcome window.
parent.messageboard.WriteText('Login failed.\n')
return
ud = UploadDialog(data,engine,x,y)
if ud.ShowModal() == wx.ID_OK:
upload = True if ud.upload.GetStringSelection() == 'Yes' else False
currentFlag = True if ud.current.GetStringSelection() == "Yes" else False
if upload:
errmsg = uploadAgeModel(engine, data, x, y, currentFlag)
parent.messageboard.WriteText(errmsg)
return
def save_loc(parent, holeID, x, y): #Rewritten
"""Write the current LOC to a file."""
file = holeID + "_loc.txt"
default = os.environ['NSBPATH'] + "/LOC/"
wildcard = "Tab-separated files (*.txt)|*.txt"
dlg = wx.FileDialog(None, 'Save your file', defaultDir =default, defaultFile=file, wildcard=wildcard, style=wx.FD_SAVE)
if dlg.ShowModal() == wx.ID_OK:
fileName = dlg.GetPath()
toScale = data['toScale'] # For timescale and paleomag chron scale
date = datetime.date.today().isoformat()
fo = open(fileName,"w")
fo.write(holeID+"\t"+toScale+"\t"+toScale+"\t"+date+"\n")
fo.write("AGE"+"\t"+"DEPTH"+"\n")
for i in range (len(x)):
fo.write(str(round(x[i],6))+"\t"+str(abs(round(y[i],3)))+"\n")
fo.close()