forked from bcych/TROUT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trout.py
2698 lines (2223 loc) · 90.6 KB
/
trout.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
import numpy as np
import pandas as pd
import emcee
import matplotlib.pyplot as plt
import jax.numpy as jnp
from jax import grad, jit, vmap, jacrev
import jax.scipy.special as jsp
from jax.scipy.stats import uniform, multivariate_normal, norm, beta
from jax.numpy import heaviside
from scipy.optimize import minimize
from pmagpy import pmag,ipmag
from pmagpy import contribution_builder as cb
from itertools import combinations
from adjustText import adjust_text
from matplotlib.collections import LineCollection
import warnings
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from scipy.stats import truncnorm
from functools import lru_cache
from jax.flatten_util import ravel_pytree
from matplotlib.colors import hsv_to_rgb
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
@jit
def SGG_cdf(x,mu,sigma,p,q):
"""
Calculates the cumulative density function of the skew
generalized gaussian (SGG) distribution (Egli, 2003)
Inputs
------
x: float or array
x value at which to evaluate SGG distribution
mu: float
mu parameter (controls location) of SGG distribution
sigma: float
sigma parameter (controls scale) of SGG distribution
p: float
p parameter (controls kurtosis) of SGG distribution
q: float
q parameter (controls skewness) of SGG distribution
Returns
-------
G: float or array
Value of SGG cdf at x
"""
z=(x-mu)/sigma
u=jnp.log((jnp.exp(q*z)+jnp.exp(z/q))/2)
#Regularized Upper Incomplete Gamma Function (1/p,0.5*abs(u)**p)
inc_gam_part=jsp.gammaincc(1/p,(jnp.abs(u)**p)/2)
heaviside_part=heaviside(u,0.5)
sign_part=jnp.sign(u)/2
G=1-heaviside(q,0.5)+jnp.sign(q)*(heaviside_part-sign_part*inc_gam_part)
return(G)
@jit
def SGG_pdf(x, mu, sigma, p, q):
"""
Calculates the cumulative density function of the skew
generalized gaussian (SGG) distribution (Egli, 2003)
Inputs
------
x: float or array
x value at which to evaluate SGG distribution
mu: float
mu parameter (controls location) of SGG distribution
sigma: float
sigma parameter (controls scale) of SGG distribution
p: float
p parameter (controls kurtosis) of SGG distribution
q: float
q parameter (controls skewness) of SGG distribution
Returns
-------
g: float or array
Value of SGG pdf at x
"""
z=(x-mu)/sigma
prefac=1/(2**(1+1/p)*sigma*jnp.exp(jsp.gammaln(1+1/p)))
skewpart=jnp.abs(q*jnp.exp(q*z)+jnp.exp(z/q)/q)/(jnp.exp(q*z)+jnp.exp(z/q))
exponential=jnp.exp(-0.5*jnp.abs(jnp.log((jnp.exp(q*z)+jnp.exp(z/q))/2))**p)
return(prefac*skewpart*exponential)
@jit
def construct_pred_data(Bs,Ts,cs,mus,sds,ps,qs):
"""
Uses the TROUT model parameters and the
temperatures/fields of the demag data to
predict data from the TROUT model.
Inputs
------
Bs: kx3 array
Set of cartesian field directions for the
different components in the TROUT model.
Ts: length n array
Set of temperatures/fields used to demag
the specimen.
cs: length k array
Magnitude of each component
mus: length k array
SGG "mu" parameter for each component
sds: length k array
SGG "sigma" parameter for each component
ps: length k array
SGG "p" parameter for each component
qs: length k array
SGG "q" parameter for each component
Returns
-------
data_pred: nx3 array
Predicted data from the TROUT model
"""
n=Ts.shape[0] #number of demag data
k=cs.shape[0] #number of components
Bs_scaled=jnp.empty(Bs.shape) #Scaled Bs
Fs=jnp.empty((k,n)) #Scaled Fs
data_pred=jnp.zeros((n,3)) #Predicted data
for i in range(k):
#Create SGG cdf values.
Fs=Fs.at[i].set(1-SGG_cdf(Ts,mus[i],sds[i],ps[i],qs[i]))
for j in range(3):
#Scaled Bs is cs*Bs
Bs_scaled=Bs_scaled.at[i,j].set(cs[i]*Bs[i,j])
#predicted data is cs*Bs*Fs
data_pred=data_pred.at[:,j].add(Bs_scaled[i,j]*Fs[i])
return(data_pred)
@jit
def cdf_misfit(pars,data,Ts):
"""
Calculates misfit from a set of data to an SGG cdf
for initialization of TROUT model
Inputs
------
pars: length 4 array
mu, sd, p_star,q_star parameters for SGG distribution
data: length n array
data to fit to SGG cdf
Ts: length n array
Temperatures at which cdf is evaluated
Returns
-------
like: float
likelihood of cdf given data
"""
mu,sd,p_star,q_star=pars
#Calculate p and q parameters
p=jnp.exp(p_star)
q=2/jnp.pi*jnp.arctan(1/q_star)
#Calculate predicted data
pred_data=1-SGG_cdf(Ts,mu,sd,p,q)
#Calculate likelihood (misfit to data)
like=len(pred_data)*jnp.log(jnp.sum((data-pred_data)**2))/2-uniform.logpdf(p_star,0,5)-uniform.logpdf(q_star,-5,10)
return(like)
def import_direction_data(wd):
"""
Imports directions from magic tables
Inputs
------
wd: string
working directory containing magic tables
Returns
-------
data: pandas DataFrame
specimen table with added samples/sites
sample_data: pandas DataFrame
sample table
site_data: pandas DataFrame
site table
"""
status,data=cb.add_sites_to_meas_table(wd)
sample_data=pd.read_csv(wd+'samples.txt',skiprows=1,sep='\t')
site_data=pd.read_csv(wd+'sites.txt',skiprows=1,sep='\t')
return(data,sample_data,site_data)
@jit
def scale_xs(xs_base,expon):
"""
Scales temperatures/AF fields/microwave power
used in demagnetization experiment to make
TROUT model easier to fit.
Inputs
------
xs_base: length n array
temperatures/AF fields to scale
expon: float
exponent to scale data by. If expon > 0 then
data are scaled by their distance from the
highest temperature/field.
Returns
-------
xs_scaled: length n array
scaled x values.
"""
exponexpon=jnp.exp(-jnp.abs(expon))
xs_scaled=(jnp.heaviside(expon,0)*jnp.max(xs_base)-(jnp.heaviside(expon,0)*2-1)*xs_base)**exponexpon
xs_scaled=jnp.heaviside(expon,0)*jnp.max(xs_scaled)-(jnp.heaviside(expon,0)*2-1)*xs_scaled
return(xs_scaled)
@jit
def unscale_xs(xs_scaled,expon):
"""
Inverse function of scale_xs. Corrects scaled
temperature/fields back to original values.
Inputs
------
xs_scaled: length n array
scaled x values.
expon: float
exponent to scale data by. If expon > 0 then
data are scaled by their distance from the
highest temperature/field.
Returns
-------
xs_base: length n array
original x values
"""
exponexpon=jnp.exp(-jnp.abs(expon))
xs_base=(jnp.heaviside(expon,0)*jnp.max(xs_scaled)-(jnp.heaviside(expon,0)*2-1)*xs_scaled)**exponexpon
xs_base=jnp.heaviside(expon,0)*jnp.max(xs_base)-(jnp.heaviside(expon,0)*2-1)*xs_base
return(xs_base)
@jit
def bestfit_tanh(pars,x,y):
"""
Calculates misfit to a tanh function
Inputs:
-------
pars: length 2 array
scale and location parameters of
tanh function
x: length n array
x values
y: length n array
y values
Returns
-------
diff: float
sum of squared differences from tanh
function.
"""
xp=scale_xs(x,pars[1])
tanhfunc=(1-jnp.tanh(pars[0]*(xp-jnp.min(xp))/(jnp.max(xp)-jnp.min(xp))-pars[0]/2))/2
diff=jnp.sum((y-tanhfunc)**2)
return diff
@jit
def calculate_gradient_covariances(zijd_data,Ts_data,sigma,psi):
"""
Calculates covariances of gradients of vector demagnetization
data, given a diagonal gaussian noise given by "sigma" and
a scale dependent noise (attitude) given by "psi"
"""
n=zijd_data.shape[0]
#Array of original covariances
Cs=jnp.empty((3,3,n))
#Populate covariance matrices
for l in range(len(zijd_data)):
BB=jnp.outer(zijd_data[l],zijd_data[l])
B2=jnp.linalg.norm(zijd_data[l])**2
C=jnp.identity(3)*(sigma**2+B2*psi**2)-BB*psi**2
Cs=Cs.at[:,:,l].set(C)
#Get Cs for summing covariances
Cs_i=Cs[:,:,1:-1]
Cs_plus=Cs[:,:,2:]
Cs_minus=Cs[:,:,:-2]
#Get spacing for multiplying variances
T_is=Ts_data[1:-1]
Ts_plus=Ts_data[2:]
Ts_minus=Ts_data[:-2]
hs=T_is-Ts_minus
hd=Ts_plus-T_is
#Create covariances of numerical gradient
Cs_grad=jnp.empty(Cs.shape)
Cs_grad=Cs_grad.at[:,:,1:-1].set((Cs_plus*hs**4+Cs_minus*hd**4+Cs_i*jnp.abs(hd**2-hs**2)**2)/(hs*hd*(hd+hs))**2)
Cs_grad=Cs_grad.at[:,:,0].set((Cs[:,:,1]+Cs[:,:,0])/(Ts_data[1]-Ts_data[0])**2)
Cs_grad=Cs_grad.at[:,:,-1].set((Cs[:,:,-2]+Cs[:,:,-1])/(Ts_data[-1]-Ts_data[-2])**2)
return(Cs_grad.T)
@jit
def construct_pred_diffs(Bs,Ts,cs,mus,sds,ps,qs):
"""
Constructs predicted data values from the TROUT
model.
Inputs
------
Bs: K by 3 array
Cartesian direction vector for each of the
K components.
Ts: length N array
Temperatures for thermal demag or coercivities
for AF demag
cs: length K array
Magnitudes of each component
mus: length k array
"mu" parameter of SGG distribution for each
component
sds: length k array
"sd" parameter of SGG distribution for each component
ps: length k array
"p" parameter of SGG distribution for each component
qs: length k array
"q" parameter of SGG distribution for each component
Returns
-------
data_pred: nx3 array
Predicted demagnetization data.
"""
n=Ts.shape[0]
k=cs.shape[0]
Bs_scaled=jnp.empty(Bs.shape)
Fs=jnp.empty((k,n))
data_pred=jnp.zeros((n,3))
for i in range(k):
Fs=Fs.at[i].set(jnp.nan_to_num(SGG_pdf(Ts,mus[i],sds[i],ps[i],qs[i]),0))
for j in range(3):
Bs_scaled=Bs_scaled.at[i,j].set(cs[i]*Bs[i,j])
data_pred=data_pred.at[:,j].add(Bs_scaled[i,j]*Fs[i])
return(data_pred)
@jit
def like_func_grad(zijd_data,zijd_diffs,Ts_data,Bs,cs,mus,sds,p_stars,q_stars,sigma,psi):
"""
Likelihood function using gradients of demagnetization data (deprecated)
"""
ps=jnp.exp(p_stars)
qs=2/jnp.pi*jnp.arctan(1/q_stars)
Trange=jnp.ptp(Ts_data)
Ts_data/=Trange
mus/=Trange
sds/=Trange
pred_diffs=construct_pred_diffs(Bs,Ts_data,cs,mus,sds,ps,qs)
Cs_grad=calculate_gradient_covariances(zijd_data,Ts_data,sigma,psi)
llike_=0
for l in range(len(zijd_data)):
llike_+=multivariate_normal.logpdf(pred_diffs[l],zijd_diffs[l],Cs_grad[l])
return(llike_)
@jit
def post_func_grad(par_dict,zijd_data,zijd_diffs,Ts_data):
"""
Posterior distribution for using gradients of demagnetization data
(deprecated).
"""
Bs=(par_dict['Ms'].T/jnp.linalg.norm(par_dict['Ms'],axis=1)).T
cs=jnp.linalg.norm(par_dict['Ms'],axis=1)
c_norm=jnp.sum(cs)/vds
lp=prior_func_sigma_psi(
c_norm,par_dict['sigma'])
ll=like_func_grad(
zijd_data,zijd_diffs,Ts_data,Bs,cs,
par_dict['mus'],par_dict['sds'],
par_dict['p_stars'],par_dict['q_stars'],
par_dict['sigma'],par_dict['psi'])
return(jnp.nan_to_num(ll+lp,nan=-jnp.inf))
def prepare_specimen_data(specimen,data,sample_data,site_data,normalize=True):
"""
Process data from a specimen for use with TROUT. Rotates into geographical
coordinates if applicable.
Inputs
------
specimen: string
name of specimen being processed
data: pandas DataFrame
magic specimens table imported to DataFrame
sample_data: pandas DataFrame
magic samples table imported to DataFrame
site_data: pandas DataFrame
magic sites table imported to DataFrame
normalize: bool
Whether or not to normalize the temperatures or coer80ivities for better
fitting with TROUT (should be left at True)
Returns
-------
zijd_data: nx3 array
Set of demagnetization data the TROUT model will be applied to
Ts_base: length n array
Original Temperature steps (or coercivities).
Ts_data: length n array
Scaled Temperature steps or coercivities
Ts: length 100 array
Interpolation on range of temperature steps
datatype: string
Type of demagnetization, currently "AF" or "Thermal"
expon: float
Exponent parameter used to scale the data.
"""
specframe=data[(data.specimen==specimen)&((data.method_codes.str.contains('LP-DIR'))|(data.method_codes.str.contains('LT-T-Z')|(data.method_codes.str.contains('LT-NO'))|(data.method_codes.str.contains('LP-NO'))))]
sample=specframe['sample'].iloc[0]
site=specframe['site'].iloc[0]
specdata_dir=np.array([specframe['dir_dec'].values,specframe['dir_inc'].values,specframe['magn_moment'].values]).T
sampleframe=sample_data[sample_data['sample']==sample]
try:
sampleframe.dropna(subset=['azimuth'],inplace=True)
specdata_dir_corr=np.array([pmag.dogeo(specdata_dir[i,0],specdata_dir[i,1],sampleframe['azimuth'].values[0],sampleframe['dip'].values[0]) for i in range(len(specdata_dir))])
specdata_dir_corr=np.append(specdata_dir_corr,specdata_dir[:,2][:,np.newaxis],axis=1)
specdata=pmag.dir2cart(specdata_dir_corr)
except:
specdata=pmag.dir2cart(specdata_dir)
zijd_data=specdata/max(np.sqrt(np.sum(specdata**2,axis=1)))
if specframe.method_codes.str.contains('LP-DIR-AF').iloc[0]:
datatype='af'
Ts_base=specframe.treat_ac_field.values*1e3
elif (specframe.method_codes.str.contains('LP-DIR-T').iloc[0])|(specframe.method_codes.str.contains('LT-NO').iloc[0]):
Ts_base=specframe.treat_temp.values-273
datatype='thermal'
else:
datatype='unspecified'
Ts_base=specframe.treat_temp.values-273
max_data=max(Ts_base)
Ts_base=Ts_base/max(Ts_base)
flipped_data=np.flip(zijd_data,axis=0)
diff_data=np.diff(flipped_data,axis=0)
appended_data=np.append([[0,0,0]],diff_data,axis=0)
norm_data=np.linalg.norm(appended_data,axis=1)+np.linalg.norm(zijd_data[-1])
cumulative_data=np.cumsum(norm_data)
Ms=np.flip(cumulative_data)
Ms_scaled=Ms/max(Ms)
if normalize==True:
minimizer=minimize(bestfit_tanh,x0=[1.,0.1],args=(Ts_base,Ms_scaled),method='L-BFGS-B',bounds=([1,100],[-10,10]),options={'eps':np.sqrt(np.finfo('float32').eps)})
expon=minimizer.x[1]
Ts_data=np.array(scale_xs(Ts_base,expon))
else:
Ts_data=Ts_base
expon=0
Ts=np.linspace(min(Ts_data),max(Ts_data),100)
return(zijd_data,Ts_base,Ts_data,Ts,datatype,expon)
def simple_fit(zijd_data,Ts_data,break_points):
"""
A simple way of getting a best guess for TROUT initialization
(deprecated)
"""
endpoints=[]
dirs=[]
cs=[]
for i in range(len(break_points)-1):
zijd_data_trunc=zijd_data[(Ts_data<=break_points[i+1])&(Ts_data>=break_points[i])]
endpoints.append(zijd_data_trunc[0])
if i==(len(break_points)-2):
zijd_data_trunc=np.append(zijd_data_trunc,[[0,0,0]],axis=0)
endpoints.append(zijd_data_trunc[-1])
direction=zijd_data_trunc[0]-zijd_data_trunc[-1]
c=np.linalg.norm(zijd_data_trunc[0]-zijd_data_trunc[-1])
dirs.append(direction/c)
cs.append(c)
d2=0
for i in range(len(dirs)):
zijd_data_trunc=zijd_data[(Ts_data<=break_points[i+1])&(Ts_data>=break_points[i])]
if i!=0:
zijd_data_trunc=zijd_data_trunc[1:]
line=endpoints[i+1]-endpoints[i]
linept=endpoints[i]-zijd_data_trunc
d2s=np.linalg.norm(np.cross(line,linept),axis=1)**2/np.linalg.norm(line)**2
ts=-np.dot(linept,line)/np.linalg.norm(line)**2
d2s[ts<0]=np.linalg.norm(zijd_data_trunc[ts<0]-endpoints[i],axis=1)**2
d2s[ts>1]=np.linalg.norm(zijd_data_trunc[ts>1]-endpoints[i+1],axis=1)**2
d2+=np.sum(d2s)
return(np.array(dirs),np.array(cs),d2)
def pca_fit(zijd_data,Ts_data,break_points):
"""
Performs a PCA analysis on a specimen with multiple components.Attempts to
minimize the misfit by finding the closest point to the intersection of
each component's segment. The "break_points" parameter specifies the points
at which the component "changes" (assuming no overlap)
Inputs
------
zijd_data: nx3 array
demagnetization data for a specimen
Ts_data: length n array
scaled temperature data for a specimen.
break_points: length (k-1) array
Temperatures/coercivities at which component changes
Returns
-------
dirs: length k array
Directions of principal components
cs: length k array
Magnitudes of principal components
d2: float
Sum of squared distances of points to principal axis.
"""
#Set up PCA fits
cs=[]
dirs=np.empty((len(break_points)-1,3))
means=np.empty((len(break_points)-1,3))
vs=[]
for i in range(len(break_points)-1):
zijd_data_trunc=zijd_data[(Ts_data<=break_points[i+1])&(Ts_data>=break_points[i])]
if i==(len(break_points)-2):
zijd_data_trunc=np.append(zijd_data_trunc,[[0,0,0]],axis=0)
if len(zijd_data_trunc)==2:
cs.append(np.linalg.norm(np.diff(zijd_data_trunc,axis=0)))
dirs[i]=np.diff(np.flip(zijd_data_trunc,axis=0),axis=0)/cs[i]
vs.append(np.array([cs[i]/2*dirs[i],-cs[i]/2*dirs[i]]))
means[i]=(zijd_data_trunc[0]+zijd_data_trunc[1])/2
else:
pca=PCA(n_components=3)
pca=pca.fit(zijd_data_trunc)
length, vector=pca.explained_variance_[0], pca.components_[0]
vals=pca.transform(zijd_data_trunc)[:,0]
v = np.outer(vals,vector)
vs.append(v)
means[i]=pca.mean_
cs.append(np.linalg.norm((pca.mean_+v[-1])-(pca.mean_+v[0])))
dirs[i]=((pca.mean_+v[0])-(pca.mean_+v[-1]))/cs[i]
#Correct PCA fits so that lines intersect.
for i in range(len(dirs)-1):
offdist=np.cross(dirs[i],dirs[i+1])
offdist/=np.linalg.norm(offdist)
closestpt=np.linalg.solve(np.array([dirs[i],-dirs[i+1],offdist]).T,(means[i+1]+vs[i+1][0])-(means[i]+vs[i][-1]))
cs[i+1]+=closestpt[1]
cs[i]-=closestpt[0]
endpoints=np.empty((len(break_points),3))
for i in range(len(dirs)):
endpoints[i]=np.sum(np.transpose(dirs[i:].T*cs[i:]),axis=0)
endpoints[-1]=[0,0,0]
d2=0
for i in range(len(dirs)):
zijd_data_trunc=zijd_data[(Ts_data<=break_points[i+1])&(Ts_data>=break_points[i])]
if i!=0:
zijd_data_trunc=zijd_data_trunc[1:]
line=endpoints[i+1]-endpoints[i]
linept=endpoints[i]-zijd_data_trunc
d2s=np.linalg.norm(np.cross(line,linept),axis=1)**2/np.linalg.norm(line)**2
ts=-np.dot(linept,line)/np.linalg.norm(line)**2
d2s[ts<0]=np.linalg.norm(zijd_data_trunc[ts<0]-endpoints[i],axis=1)**2
d2s[ts>1]=np.linalg.norm(zijd_data_trunc[ts>1]-endpoints[i+1],axis=1)**2
d2+=np.sum(d2s)
return(np.array(dirs),np.array(cs),d2)
def find_best_dist(zijd_data,Ts_data,break_points):
"""
Finds the best fitting SGG distribution to a set of demagnetization data,
assuming no overlap between components which change at temperatures or
coercivities specified in "break_points".
Inputs
------
zijd_data: nx3 array
demagnetization data for a specimen
Ts_data: length n array
scaled temperature data for a specimen.
break_points: length (k-1) array
Temperatures/coercivities at which component changes
Returns
-------
mus: length k array
Best fitting SGG "mu" parameters
sds: length k array
Best fitting SGG "sd" parameters
ps: length k array
Best fitting SGG "p" parameters
qs: length k array
Best fitting SGG "q" parameters
"""
#Minimize SGG distribution
mus=[]
sds=[]
p_stars=[]
q_stars=[]
for i in range(len(break_points)-1):
zijd_data_trunc=zijd_data[(Ts_data<=break_points[i+1])&(Ts_data>=break_points[i])]
zijd_data_trunc=zijd_data_trunc-zijd_data_trunc[-1]
flipped_zijd=np.flip(zijd_data_trunc)
mags_trunc=np.append(0,np.cumsum(np.linalg.norm(np.diff(flipped_zijd,axis=0),axis=1)))
mags_trunc/=np.amax(mags_trunc)
mags_trunc=np.flip(mags_trunc)
Ts_data_trunc=Ts_data[(Ts_data<=break_points[i+1])&(Ts_data>=break_points[i])]
sorted_mags=mags_trunc[np.argsort(mags_trunc)]
trunc_Ts_scaled=(Ts_data_trunc-break_points[i])/(break_points[i+1]-break_points[i])
sorted_Ts=trunc_Ts_scaled[np.argsort(mags_trunc)]
start_sd=(jnp.interp(0.16,sorted_mags,sorted_Ts)-jnp.interp(0.84,sorted_mags,sorted_Ts))/2
start_mu=jnp.interp(0.5,sorted_mags,sorted_Ts)
start_p_star=2.
start_q_star=0.01
start_pars=[start_mu,start_sd,start_p_star,start_q_star]
result=minimize(cdf_misfit,start_pars,jac=jacrev(cdf_misfit),args=(mags_trunc,trunc_Ts_scaled),method='BFGS',options={'eps':np.sqrt(np.finfo('float32').eps)})
mus.append(result.x[0]*(break_points[i+1]-break_points[i])+break_points[i])
sds.append(result.x[1]*(break_points[i+1]-break_points[i]))
p_stars.append(result.x[2])
q_stars.append(result.x[3])
return(np.array(mus),np.array(sds),np.array(p_stars),np.array(q_stars))
def find_naive_fit(zijd_data,Ts_data,n_components,bpoints=None,anchored=False):
"""
Attempts to find a best fitting TROUT solution to a set of demagnetization
data assuming no unblocking temperature overlap.
Inputs
------
zijd_data: nx3 array
demagnetization data for a specimen
Ts_data: length n array
scaled temperature data for a specimen.
n_components: int
number of components (k) expected for this specimen.
bpoints: len (k-1) array
Forces fit to assume a change in component at a particular temperature or
coercivity (if set to None, this is already chosen). This should probably
be set to None.
anchored: bool
When True, performs the TROUT fit to all data. TROUT assumes that at high
temperatures, the magnetization goes to zero. With Anchored=False, the
origin is moved to the final demagnetization step so this requirement is
not met. With Anchored=True an additional component may be needed for
specimens where the magnetization does not trend towards the origin.
Returns
-------
Bs: nx3 array
Best guess field directions
cs: nx3 array
Best guess component magnitudes
mus: length k array
Best guess SGG "mu" parameters
sds: length k array
Best guess SGG "sd" parameters
ps: length k array
Best guess SGG "p" parameters
qs: length k array
Best guess SGG "q" parameters
"""
d2=np.inf
numbers = Ts_data[1:-1]
Bs=[]
cs=[]
if anchored==False:
zijd_data-=zijd_data[-1]
if bpoints==None:
for item in combinations(numbers, n_components-1):
break_points=[Ts_data[0]]+sorted(item)+[Ts_data[-1]]
Bs_new,cs_new,d2_new=pca_fit(zijd_data,Ts_data,break_points)
if d2_new<d2:
d2=d2_new
Bs=Bs_new
cs=cs_new
break_points_final=break_points
else:
break_points=[Ts_data[0]]+sorted(bpoints)+[Ts_data[-1]]
Bs_new,cs_new,d2=pca_fit(zijd_data,Ts_data,break_points)
Bs=Bs_new
cs=cs_new
break_points_final=break_points
mus,sds,p_stars,q_stars=find_best_dist(zijd_data,Ts_data,break_points_final)
return(Bs,cs,mus,sds,p_stars,q_stars)
@jit
def like_func_notol(Ms,Ts,Bs,cs,mus,sds,p_stars,q_stars):
n=Ts.shape[0]
ps=jnp.exp(p_stars)
qs=2/jnp.pi*jnp.arctan(1/q_stars)
Bs=(Bs.T/jnp.linalg.norm(Bs,axis=1)).T
data_pred=construct_pred_data(Bs,Ts,cs,mus,sds,ps,qs)
llike_=0
for l in range(n):
llike_+=jnp.sum((data_pred[l]-Ms[l])**2)
llike_=-3*n*jnp.log(llike_)/2
return(llike_)
@jit
def like_func_sigma_psi(Ms,Ts,Bs,cs,mus,sds,p_stars,q_stars,sigma,psi):
"""
Likelihood function for the TROUT model, gives the log likelihood of a set
of demagnetization data, given the model parameters.
Inputs
------
Ms: nx3 array
Demagnetization data.
Ts: length n array
Temperatures at which demag data is evaluated.
Bs: length k array
Field directions for each component of demag data
cs: length k array
Magnitudes of each component of demag data
mus: length k array
"mu" parameters of SGG distribution for each component
sds: length k array
"s" parameters of SGG distribution for each component
p_stars: length k array
"p_star" parameters (can be transformed to "p") of SGG distribution for
each component
q_stars: length k array
"q_star" parameters (can be transformed to "q") of SGG distribution for
each component
sigma: float>0
Standard deviation of cartesian noise on demagnetization data.
psi: float>0
Angular uncertainty (in radians) of demagnetization data.
Returns
-------
llike_: float
log-likelihood of parameters given data.
"""
#Shapes of data/model
n=Ms.shape[0]
k=cs.shape[0]
m=Ms.shape[1]
#Transform SGG Parameters
ps=jnp.exp(p_stars)
qs=2/jnp.pi*jnp.arctan(1/q_stars)
#Predict mean values of data from model
data_pred=construct_pred_data(Bs,Ts,cs,mus,sds,ps,qs)
llike_=0
for l in range(n):
#Calculate Covariance matrix for this data point
BB=jnp.outer(Ms[l],Ms[l])
B2=jnp.linalg.norm(Ms[l])**2
C=jnp.identity(3)*(sigma**2+B2*psi**2)-BB*psi**2
#Log likelihood is probability of observed data given covariance matrix
#and predicted mean data values
llike_+=multivariate_normal.logpdf(data_pred[l],Ms[l],C)
#Return log-likelihood
return(llike_)
@jit
def like_func_sigma_chi(Ms,Ts,Bs,cs,mus,sds,p_stars,q_stars,sigma,chi):
"""
Deprecated likelihood function (assuming all angular uncertainty in the
x-y plane).
"""
n=Ms.shape[0]
k=cs.shape[0]
m=Ms.shape[1]
ps=jnp.exp(p_stars)
qs=2/jnp.pi*jnp.arctan(1/q_stars)
data_pred=construct_pred_data(Bs,Ts,cs,mus,sds,ps,qs)
llike_=0
for l in range(n):
Mval=jnp.cross(jnp.array([0,0,1]),Ms[l])
BB=jnp.outer(Mval,Mval)
C=jnp.identity(3)*(sigma**2)+BB*chi**2
Cinv=jnp.linalg.inv(C)
diff=data_pred[l]-Ms[l]
llike_+=-diff.T@Cinv@diff/2-jnp.log(jnp.linalg.det(2*jnp.pi*C))/2
return(llike_)
@jit
def alt_prior_sigma_psi(Ts_data,cs,mus,sds,p_stars,q_stars,sigma):
"""
Prior used for the TROUT model. The prior is calculated using the overlap
between two SGG distributions.
Inputs
------
Ts_data: length n array
Temperatures at which demag data is evaluated. (This is included in the
prior only to set a range for the acceptable bounds of mu)
Bs: length k array
Field directions for each component of demag data
cs: length k array
Magnitudes of each component of demag data
mus: length k array
"mu" parameters of SGG distribution for each component
sds: length k array
"s" parameters of SGG distribution for each component
p_stars: length k array
"p_star" parameters (can be transformed to "p") of SGG distribution for
each component
q_stars: length k array
"q_star" parameters (can be transformed to "q") of SGG distribution for
each component
sigma: float>0
Standard deviation of cartesian noise on demagnetization data.
Returns
-------
lp: float
log prior distribution
"""
#Transform SGG parameters
ps=jnp.exp(p_stars)
qs=2/np.pi*jnp.arctan(1/q_stars)
#Set of xs to evaluate
xs=jnp.linspace(jnp.min(Ts_data),jnp.max(Ts_data),1000)
#Probability density function
pdfs=jnp.empty((len(cs),1000))
#Start with log prior of 0 and add to it
lp=0
for k in range(len(cs)):
#Evaluate pdf over temperature range
pdf=cs[k]*SGG_pdf(xs,mus[k],sds[k],ps[k],qs[k])
pdfs=pdfs.at[k].set(pdf)
#Find all combinations of two pdfs and calculate their overlap
for ks in combinations(range(len(pdfs)),2):
ks=jnp.array(ks)
pdf_pair=pdfs[ks]
#Minimum of the two pdfs at all temperatures
cmin=np.amin(jnp.array([cs]).T[ks])
overlap=jnp.amin(pdf_pair,axis=0)
#Calculate the overlap coefficient
overlap_sum=jnp.trapz(overlap,xs)/cmin
#Prior is a beta distribution
lp+=beta.logpdf(overlap_sum,1,10)
#Prior on sigma is 1/sigma
lp-=jnp.log(sigma)
#Set bounds for SGG parameters
Tmin=jnp.min(Ts_data)
Tmax=jnp.max(Ts_data)
lp+=sum(uniform.logpdf(mus,Tmin,Tmax-Tmin))
lp+=sum(uniform.logpdf(sds,0,(Tmax-Tmin)*10/6))
lp+=sum(uniform.logpdf(p_stars,0,5))
lp+=sum(uniform.logpdf(q_stars,-5,10))
lp+=sum(uniform.logpdf(cs,0,2))
#Constraint that mu_0<mu_1<...<mu_k - avoids label degeneracy
lp+=sum(uniform.logpdf(jnp.diff(mus),0,Tmax-Tmin))
return(lp)
@jit
def prior_func_sigma_psi(c_norm,sigma):
lp=norm.logpdf(jnp.amax(jnp.array([c_norm,1])),1,0.1)-jnp.log(sigma)
return(lp)
@jit
def prior_func_notol(c_norm):
lp=norm.logpdf(c_norm,1,0.1)
return(lp)
@jit
def post_func_sigma_chi(pars,zijd_data,Ts_data):
par_dict=par_vec_to_named_pars_sigma_chi(pars)
Tmax=jnp.max(Ts_data)
Tmin=jnp.min(Ts_data)
norms=jnp.sum(jnp.linalg.norm(par_dict['Bs'],axis=1))
lp=prior_func_sigma_chi(
Tmax,Tmin,norms,par_dict['mus'],par_dict['sds'],par_dict['p_stars'],
par_dict['q_stars'],par_dict['cs'],par_dict['sigma'],par_dict['chi'])
ll=like_func_sigma_chi(
zijd_data,Ts_data,par_dict['Bs'],par_dict['cs'],par_dict['mus'],
par_dict['sds'],par_dict['p_stars'],par_dict['q_stars'],par_dict['sigma'],
par_dict['chi'])
return(jnp.nan_to_num(ll+lp,nan=-np.inf))
@jit
def post_func_sigma_psi(par_dict,zijd_data,Ts_data):
"""
Posterior distribution function used in the TROUT model. Finds the relative
probability of a set of TROUT parameters, given the demag data.
Inputs
------
par_dict: dictionary
dictionary of parameters supplied to the posterior function