-
Notifications
You must be signed in to change notification settings - Fork 104
/
Proton_processing.py
executable file
·1786 lines (1033 loc) · 47.3 KB
/
Proton_processing.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
from matplotlib import pyplot as plt
import numpy as np
from scipy.stats import gmean
from lmfit import Minimizer, Parameters, report_fit
import nmrglue as ng
from scipy.stats import norm
import pickle
try:
from openbabel.openbabel import OBConversion, OBMol, OBAtomAtomIter, OBMolAtomIter
except ImportError:
from openbabel import *
from scipy.optimize import linear_sum_assignment as optimise
import copy
from scipy.interpolate import InterpolatedUnivariateSpline
import pathos.multiprocessing as mp
import time
import itertools
import os
def process_proton(NMR_file, settings, datatype):
total_spectral_ydata, spectral_xdata_ppm, corr_distance, uc, noise_std, peak_regions = spectral_processing(NMR_file,
datatype)
gradient_peaks, gradient_regions, gradient_groups, std = gradient_peak_picking(total_spectral_ydata, corr_distance,
uc, noise_std, peak_regions)
import time
start = time.time()
picked_peaks, grouped_peaks, peak_regions, sim_y, total_params = multiproc_BIC_minimisation(gradient_regions,
gradient_groups,
total_spectral_ydata,
corr_distance,
uc, noise_std)
end = time.time()
print("minimisation time = " + str((end - start) / 60) + " mins")
peak_regions, picked_peaks, grouped_peaks, spectral_xdata_ppm, solvent_region_ind = editsolvent_removal2(
settings.Solvent, total_spectral_ydata, spectral_xdata_ppm, picked_peaks, peak_regions, grouped_peaks,
total_params,
uc)
sim_regions, full_sim_data = simulate_regions(total_params, peak_regions, grouped_peaks, total_spectral_ydata,
spectral_xdata_ppm)
peak_regions, grouped_peaks, sim_regions, integral_sum, cummulative_vectors, integrals, number_of_protons_structure, optimum_proton_number, total_integral = find_integrals(
settings.InputFiles[0], peak_regions, grouped_peaks, sim_regions, picked_peaks, total_params,
total_spectral_ydata, solvent_region_ind)
# find region centres
centres = weighted_region_centres(peak_regions, total_spectral_ydata)
################
exp_peaks = []
integrals = np.array([int(i) for i in integrals])
for ind, peak in enumerate(centres):
exp_peaks += [peak] * integrals[ind]
integrals = integrals[integrals > 0.5]
exp_peaks = spectral_xdata_ppm[exp_peaks]
exp_peaks = np.array([ round(i,4) for i in exp_peaks])
return exp_peaks, spectral_xdata_ppm, total_spectral_ydata, integrals, peak_regions, centres, cummulative_vectors, integral_sum, picked_peaks, total_params, sim_regions
def guess_udic(dic, data):
"""
Guess parameters of universal dictionary from dic, data pair.
Parameters
----------
dic : dict
Dictionary of JCAMP-DX parameters.
data : ndarray
Array of NMR data.
Returns
-------
udic : dict
Universal dictionary of spectral parameters.
"""
# create an empty universal dictionary
udic = ng.fileiobase.create_blank_udic(1)
# update default values (currently only 1D possible)
# "label"
try:
label_value = dic[".OBSERVENUCLEUS"][0].replace("^", "")
udic[0]["label"] = label_value
except KeyError:
# sometimes INSTRUMENTAL PARAMETERS is used:
try:
label_value = dic["INSTRUMENTALPARAMETERS"][0].replace("^", "")
udic[0]["label"] = label_value
except KeyError:
pass
# "obs"
obs_freq = None
try:
obs_freq = float(dic[".OBSERVEFREQUENCY"][0])
udic[0]["obs"] = obs_freq
except KeyError:
pass
# "size"
if isinstance(data, list):
data = data[0] # if list [R,I]
if data is not None:
udic[0]["size"] = len(data)
# "sw"
# get firstx, lastx and unit
firstx, lastx, isppm = ng.jcampdx._find_firstx_lastx(dic)
# ppm data: convert to Hz
if isppm:
if obs_freq:
firstx = firstx * obs_freq
lastx = lastx * obs_freq
else:
firstx, lastx = (None, None)
if firstx is not None and lastx is not None:
udic[0]["sw"] = abs(lastx - firstx)
# keys not found in standard&required JCAMP-DX keys and thus left default:
# car, complex, encoding
udic[0]['car'] = firstx - abs(lastx - firstx) / 2
return udic
def spectral_processing(file, datatype):
print('Processing Proton Spectrum')
if datatype == 'jcamp':
dic, total_spectral_ydata = ng.jcampdx.read(file) # read file
total_spectral_ydata = total_spectral_ydata[0] + 1j * total_spectral_ydata[1]
total_spectral_ydata = ng.proc_base.ifft_positive(total_spectral_ydata)
else:
dic, total_spectral_ydata = ng.bruker.read(file) # read file
total_spectral_ydata = ng.bruker.remove_digital_filter(dic, total_spectral_ydata) # remove the digital filter
total_spectral_ydata = ng.proc_base.zf_double(total_spectral_ydata, 4)
total_spectral_ydata = ng.proc_base.fft_positive(total_spectral_ydata) # Fourier transform
corr_distance = estimate_autocorrelation(total_spectral_ydata)
# normalise the data
m = max(np.max(abs(np.real(total_spectral_ydata))), np.max(abs(np.imag(total_spectral_ydata))))
total_spectral_ydata = np.real(total_spectral_ydata / m) + 1j * np.imag(total_spectral_ydata / m)
if datatype == 'jcamp':
udic = guess_udic(dic, total_spectral_ydata)
else:
udic = ng.bruker.guess_udic(dic, total_spectral_ydata) # sorting units
uc = ng.fileiobase.uc_from_udic(udic) # unit conversion element
spectral_xdata_ppm = uc.ppm_scale() # ppmscale creation
# baseline and phasing
tydata = ACMEWLRhybrid(total_spectral_ydata, corr_distance)
# find final noise distribution
classification, sigma = baseline_find_signal(tydata, corr_distance, True, 1)
# fall back phasing if fit doesnt converge
# calculate negative area
# draw regions
peak_regions = []
c1 = np.roll(classification, 1)
diff = classification - c1
s_start = np.where(diff == 1)[0]
s_end = np.where(diff == -1)[0] - 1
for r in range(len(s_start)):
peak_regions.append(np.arange(s_start[r], s_end[r]))
tydata = tydata / np.max(abs(tydata))
return tydata, spectral_xdata_ppm, corr_distance, uc, sigma, peak_regions
def estimate_autocorrelation(total_spectral_ydata):
# note this region may have a baseline distortion
y = np.real(total_spectral_ydata[0:10000])
params = Parameters()
# define a basleine polnomial
order = 6
for p in range(order + 1):
params.add('p' + str(p), value=0)
def poly(params, order, y):
bl = np.zeros(len(y))
x = np.arange(len(y))
for p in range(order + 1):
bl += params['p' + str(p)] * x ** (p)
return bl
def res(params, order, y):
bl = poly(params, order, y)
r = abs(y - bl)
return r
out = Minimizer(res, params,
fcn_args=(order, y))
results = out.minimize()
bl = poly(results.params, order, y)
y = y - bl
t0 = np.sum(y * y)
c = 1
tc = 1
t = []
while tc > 0.36:
tc = np.sum(np.roll(y, c) * y) / t0
t.append(tc)
c += 1
return c
def acme(y, corr_distance):
params = Parameters()
phase_order = 3
for p in range(phase_order + 1):
params.add('p' + str(p), value=0, min=-np.pi, max=np.pi)
def acmescore(params, im, real, phase_order):
"""
Phase correction using ACME algorithm by Chen Li et al.
Journal of Magnetic Resonance 158 (2002) 164-168
Parameters
----------
pd : tuple
Current p0 and p1 values
data : ndarray
Array of NMR data.
Returns
-------
score : float
Value of the objective function (phase score)
"""
data = ps(params, im, real, phase_order)
##########
# calculate entropy of non corrected data, calculate penalty for baseline corrected data
# - keep as vector to use the default lmfit method
# Calculation of first derivatives of signal regions
ds1 = np.abs((data[1:] - data[:-1]))
p1 = ds1 / np.sum(ds1)
# Calculation of entropy
p1[p1 == 0] = 1
h1 = -p1 * np.log(p1)
# h1s = np.sum(h1)
# Calculation of penalty
pfun = 0.0
as_ = data - np.abs(data)
# as_ = databl - np.abs(databl)
sumas = np.sum(as_)
if sumas < 0:
# pfun = pfun + np.sum((as_ / 2) ** 2)
pfun = (as_[1:] / 2) ** 2
p = 1000 * pfun
return h1 + p
out = Minimizer(acmescore, params,
fcn_args=(np.imag(y), np.real(y), phase_order))
results = out.minimize()
p = results.params
p.pretty_print()
y = ps(p, np.imag(y), np.real(y), phase_order)
classification, sigma = baseline_find_signal(y, corr_distance, True, 1)
r = gen_baseline(np.real(y), classification, corr_distance)
y -= r
return y
def ACMEWLRhybrid(y, corr_distance):
def residual_function(params, im, real):
# phase the region
data = ps(params, im, real, 0)
# make new baseline for this region
r = np.linspace(data[0], data[-1], len(real))
# find negative area
data -= r
ds1 = np.abs((data[1:] - data[:-1]))
p1 = ds1 / np.sum(ds1)
# Calculation of entropy
p1[p1 == 0] = 1
h1 = -p1 * np.log(p1)
h1s = np.sum(h1)
# Calculation of penalty
pfun = 0.0
as_ = data - np.abs(data)
sumas = np.sum(as_)
if sumas < 0:
pfun = (as_[1:] / 2) ** 2
p = np.sum(pfun)
return h1s + 1000 * p
# find regions
classification, sigma = baseline_find_signal(y, corr_distance, True, 1)
c1 = np.roll(classification, 1)
diff = classification - c1
s_start = np.where(diff == 1)[0]
s_end = np.where(diff == -1)[0] - 1
peak_regions = []
for r in range(len(s_start)):
peak_regions.append(np.arange(s_start[r], s_end[r]))
# for region in peak_regions:
# plt.plot(region,y[region],color = 'C1')
# phase each region independently
phase_angles = []
weights = []
centres = []
for region in peak_regions:
params = Parameters()
params.add('p0', value=0, min=-np.pi, max=np.pi)
out = Minimizer(residual_function, params,
fcn_args=(np.imag(y[region]), np.real(y[region])))
results = out.minimize('brute')
p = results.params
phase_angles.append(p['p0'] * 1)
# find weight
data = ps(p, np.imag(y[region]), np.real(y[region]), 0)
# make new baseline for this region
r = np.linspace(data[0], data[-1], len(data))
# find negative area
res = data - r
weights.append(abs(np.sum(res[res > 0] / np.sum(y[y > 0]))))
centres.append(np.median(region) / len(y))
sw = sum(weights)
weights = [w / sw for w in weights]
# do weighted linear regression on the regions
# do outlier analysis
switch = 0
centres = np.array(centres)
weights = np.array(weights)
sweights = np.argsort(weights)[::-1]
phase_angles = np.array(phase_angles)
ind1 = 0
while switch == 0:
intercept, gradient = np.polynomial.polynomial.polyfit(centres, phase_angles, deg=1, w=weights)
predicted_angles = gradient * centres + intercept
weighted_res = np.abs(predicted_angles - phase_angles) * weights
# find where largest weighted residual is
max_res = sweights[ind1]
s = 0
if phase_angles[max_res] > 0:
s = -1
phase_angles[max_res] -= 2 * np.pi
else:
s = +1
phase_angles[max_res] += 2 * np.pi
intercept1, gradient1 = np.polynomial.polynomial.polyfit(centres, phase_angles, deg=1, w=weights)
new_predicted_angles = gradient1 * centres + intercept1
new_weighted_res = np.abs(new_predicted_angles - phase_angles) * weights
if np.sum(new_weighted_res) > np.sum(weighted_res):
switch = 1
phase_angles[max_res] += -2*np.pi*s
ind1 +=1
# phase the data
p_final = Parameters()
p_final.add('p0', value=intercept)
p_final.add('p1', value=gradient)
# p_final.pretty_print()
y = ps(p_final, np.imag(y), np.real(y), 1)
classification, sigma = baseline_find_signal(y, corr_distance, True, 1)
r = gen_baseline(np.real(y), classification, corr_distance)
y -= r
return np.real(y)
def ps(param, im, real, phase_order):
x = np.linspace(0, 1, len(real))
angle = np.zeros(len(x))
for p in range(phase_order + 1):
angle += param['p' + str(p)] * x ** (p)
# phase the data
R = real * np.cos(angle) - im * np.sin(angle)
return R
def baseline_find_signal(y_data, cdist, dev, t):
wd = int(cdist) * 10
sd_all = _get_sd(y_data, wd)
snvectort = np.zeros(len(y_data))
sv = []
for i in range(0, 4 * cdist):
x = np.arange(i + wd, len(y_data) - wd, 4 * cdist)
sample = y_data[x]
sd_set = _get_sd(sample, wd)
s = _find_noise_sd(sd_set, 0.999)
sv.append(s)
sigma = np.mean(sv)
b = np.linspace(-0.001, 0.001, 1000)
if dev == True:
w = np.where(sd_all > t * sigma)[0]
else:
w = np.where(y_data > t * sigma)[0]
snvectort[w] = 1
sn_vector = np.zeros(len(y_data))
w = cdist
for i in np.arange(len(sn_vector)):
if snvectort[i] == 1:
sn_vector[np.maximum(0, i - w):np.minimum(i + w, len(sn_vector))] = 1
return sn_vector, sigma
def gen_baseline(y_data, sn_vector, corr_distance):
points = np.arange(len(y_data))
spl = InterpolatedUnivariateSpline(points[sn_vector == 0], y_data[sn_vector == 0], k=1)
r = spl(points)
# is corr distance odd or even
if corr_distance % 2 == 0:
kernel = np.ones((corr_distance + 1) * 10) / ((corr_distance + 1) * 10)
else:
kernel = np.ones((corr_distance) * 10) / ((corr_distance) * 10)
r = np.convolve(r, kernel, mode='same')
return r
def _rolling_window(a, window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
def _get_sd(data, k):
return np.std(_rolling_window(data, k), -1)
def _find_noise_sd(sd_set, ratio):
'''Calculate the median m1 from SDset. exclude the elements greater
than 2m1from SDset and recalculate the median m2. Repeat until
m2/m1 converge(sd_set)'''
m1 = np.median(sd_set)
S = sd_set <= 2.0 * m1
tmp = S * sd_set
sd_set = tmp[tmp != 0]
m2 = np.median(sd_set)
while m2 / m1 < ratio:
m1 = np.median(sd_set)
S = sd_set <= 2.0 * m1
tmp = S * sd_set
sd_set = tmp[tmp != 0]
return m2
########################################################################################################################
# peak picking and minimisation
########################################################################################################################
def p7(x, mu, std, v, A):
x1 = (mu - x) / (std / 2)
y = (1 - v) * (1 / (1 + (x1) ** 2)) + (v) * ((1 + ((x1) ** 2) / 2) / (1 + (x1) ** 2 + (x1) ** 4))
y *= A
return y
def p7residual(params, x, picked_points, y_data, region, differential):
y = np.zeros(len(x))
for peak in picked_points:
y += p7(x, params['mu' + str(peak)], params['std' + str(peak)], params['vregion' + str(region)],
params['A' + str(peak)])
if differential == True:
res = abs(y - y_data)
av = np.average(res)
av2 = np.average(res ** 2)
difference = (res ** 2 - av2) - (res - av) ** 2
else:
difference = (y - y_data) ** 2
return difference
def p7residualsolvent(params, x, picked_points, y_data, region, differential):
y = np.zeros(len(x))
for peak in picked_points:
y += p7(x, params['mu' + str(peak)], params['std' + str(peak)], params['vregion' + str(region)],
params['A' + str(peak)] * params['global_amp'])
if differential == True:
dy = np.gradient(y)
ddy = np.gradient(y)
dy_ydata = np.gradient(y_data)
ddy_ydata = np.gradient(dy_ydata)
difference = (y - y_data) ** 2 + (dy_ydata - dy) ** 2 + (ddy_ydata - ddy) ** 2
else:
difference = abs(y - y_data)
return difference
def p7simsolvent(params, x, picked_points, region):
y = np.zeros(len(x))
for peak in picked_points:
y += p7(x, params['mu' + str(peak)], params['std' + str(peak)], params['vregion' + str(region)],
params['A' + str(peak)] * params['global_amp'])
return y
def p7sim(params, x, picked_points, region):
y = np.zeros(len(x))
for peak in picked_points:
y += p7(x, params['mu' + str(peak)], params['std' + str(peak)], params['vregion' + str(region)],
params['A' + str(peak)])
return y
def p7plot(params, region, group, ind, xppm):
region_j = np.zeros(len(region))
for peak in group:
j = p7(region, params['mu' + str(peak)], params['std' + str(peak)], params['vregion' + str(ind)],
params['A' + str(peak)])
region_j += j
return region_j
############
###########
###########
def gradient_peak_picking(y_data, corr_distance, uc, std, binary_map_regions):
final_peaks = []
# estimate std of second derivative data
ddy = np.diff(y_data, 2)
ddy = ddy / np.max(ddy)
# find peaks
classification, sigma = baseline_find_signal(-1 * ddy, corr_distance, False, 2)
ddy1 = np.roll(ddy, 1)
ddyn1 = np.roll(ddy, -1)
p = np.where((ddy < ddy1) & (ddy < ddyn1))[0]
peaks = p[classification[p] == 1]
peaks1 = np.roll(peaks, 1)
distance = np.min(abs(peaks1 - peaks))
# must make sure the convolution kernel is odd in length to prevent the movement of the peaks
peaks = np.sort(peaks)
peakscopy = copy.copy(peaks)
ddycopy = copy.copy(ddy[peaks] / np.max(ddy))
while distance < corr_distance:
# roll the peaks one forward
peakscopy1 = np.roll(peakscopy, 1)
# find distances between peaks
diff = np.abs(peakscopy - peakscopy1)
# find where in the array the smallest distance is
mindist = np.argmin(diff)
# what is this distance
distance = diff[mindist]
# compare the values of the second derivative at the closest two peaks
compare = np.argmax(ddycopy[[mindist, mindist - 1]])
peakscopy = np.delete(peakscopy, mindist - compare)
ddycopy = np.delete(ddycopy, mindist - compare)
# remove any peaks that fall into the noise
n = y_data[peakscopy]
w = n > 5 * std
peakscopy = peakscopy[w]
final_peaks = sorted(list(peakscopy))
# draw new regions symmetrically around the newly found peaks
dist_hz = uc(0, "Hz") - uc(9, "Hz")
peak_regions = []
for peak in final_peaks:
l = np.arange(peak + 1, min(peak + dist_hz + 1, len(y_data))).tolist()
m = np.arange(max(peak - dist_hz, 0), peak).tolist()
region = m + [peak] + l
peak_regions.append(region)
final_regions = [peak_regions[0]]
final_peaks_seperated = [[final_peaks[0]]]
for region in range(1, len(peak_regions)):
if peak_regions[region][0] <= final_regions[-1][-1]:
final_regions[-1] += peak_regions[region]
final_peaks_seperated[-1].append(final_peaks[region])
else:
final_regions += [peak_regions[region]]
final_peaks_seperated.append([final_peaks[region]])
final_regions = [np.arange(min(region), max(region) + 1).tolist() for region in final_regions]
return final_peaks, final_regions, final_peaks_seperated, std
def multiproc_BIC_minimisation(peak_regions, grouped_peaks, total_spectral_ydata, corr_distance, uc, std):
maxproc = 5
pool = mp.Pool(maxproc)
new_grouped_peaks = [[] for i in range(len(peak_regions))]
new_grouped_params = [[] for i in range(len(peak_regions))]
new_sim_y = [[] for i in range(len(peak_regions))]
def BIC_minimisation_region_full(ind1, uc, peak_regions, grouped_peaks, total_spectral_ydata, corr_distance, std):
################################################################################################################
# initialise process
################################################################################################################
# print("minimising region " + str(ind1) + " of " + str(len(peak_regions)))
BIC_param = 15
region = np.array(peak_regions[ind1])
region_y = total_spectral_ydata[region]
fit_y = np.zeros(len(region_y))
copy_peaks = np.array(grouped_peaks[ind1])
params = Parameters()
fitted_peaks = []
ttotal = 0
################################################################################################################
# build initial model
################################################################################################################
# params.add('vregion' + str(ind1), value=2.5, max=5, min=1)
params.add('vregion' + str(ind1), value=0.5, max=1, min=0)
distance = uc(0, "hz") - uc(5, "hz")
std_upper = uc(0, "hz") - uc(1, "hz")
av_std = uc(0, "hz") - uc(0.2, "hz")
std_lower = uc(0, "hz") - uc(0.1, "hz")
# build model
while (len(copy_peaks) > 0):
# pick peak that is furthest from fitted data:
diff_array = region_y - fit_y
ind2 = np.argmax(diff_array[copy_peaks - region[0]])
maxpeak = copy_peaks[ind2]
copy_peaks = np.delete(copy_peaks, ind2)
# only allow params < distance away vary at a time
# add new params
fitted_peaks.append(maxpeak)
fitted_peaks = sorted(fitted_peaks)
params.add('A' + str(maxpeak), value=total_spectral_ydata[maxpeak], min=0, max=1, vary=True)
# params.add('std' + str(maxpeak), value=av_std, vary=True, min = std_lower,
# max = std_upper)
params.add('std' + str(maxpeak), value=av_std, vary=True)
params.add('mu' + str(maxpeak), value=maxpeak, vary=True
, min=maxpeak - 4 * corr_distance, max=maxpeak + 4 * corr_distance)
# adjust amplitudes and widths of the current model
initial_y = p7sim(params, region, fitted_peaks, ind1)
inty = np.sum(region_y[region_y > 0])
intmodel = np.sum(initial_y)
# check the region can be optimised this way
# find peak with max amplitude
maxamp = 0
for peak in fitted_peaks:
amp = params['A' + str(peak)]
if amp > maxamp:
maxamp = copy.copy(amp)
maxintegral = maxamp * len(region)
if maxintegral > inty:
# set initial conditions
while (intmodel / inty < 0.99) or (intmodel / inty > 1.01):
for f in fitted_peaks:
params['std' + str(f)].set(value=params['std' + str(f)] * inty / intmodel)
initial_y = p7sim(params, region, fitted_peaks, ind1)
for f in fitted_peaks:
params['A' + str(f)].set(
value=params['A' + str(f)] * region_y[int(params['mu' + str(f)]) - region[0]] / (
initial_y[f - region[0]]))
initial_y = p7sim(params, region, fitted_peaks, ind1)
intmodel = np.sum(initial_y)
# print('built model region ' + str(ind1))
################################################################################################################
# now relax all params
################################################################################################################
# allow all params to vary
params['vregion' + str(ind1)].set(vary=True)
for peak in fitted_peaks:
params['A' + str(peak)].set(vary=False, min=max(0, params['A' + str(peak)] - 0.01),
max=min(params['A' + str(peak)] + 0.01, 1))
params['mu' + str(peak)].set(vary=False)
params['std' + str(peak)].set(vary=False, min=min(std_lower, params['std' + str(peak)] - av_std),
max=max(params['std' + str(peak)] + av_std, std_upper))
out = Minimizer(p7residual, params,
fcn_args=(region, fitted_peaks, region_y, ind1, False))
results = out.minimize()
params = results.params
# print('relaxed params region ' + str(ind1))
################################################################################################################
# now remove peaks in turn
################################################################################################################
trial_y = p7sim(params, region, fitted_peaks, ind1)
trial_peaks = np.array(fitted_peaks)
amps = []
for peak in trial_peaks:
amps.append(params['A' + str(peak)])
r = trial_y - region_y