-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmwydyn.py
1813 lines (1562 loc) · 69.5 KB
/
mwydyn.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 concurrent.futures
import configparser
import copy
import json
import multiprocessing as mp
import os
import sys
import time
import warnings
from packaging import version
from platform import python_version
import astropy
import lmfit
import matplotlib
import astropy.constants as const
import astropy.units as u
import matplotlib.axes as maxes
import matplotlib.pyplot as plt
import numpy as np
from astropy.coordinates import SkyCoord
from astropy.io import fits
from astropy.table import Table
from astropy.utils.exceptions import AstropyWarning
from astropy.wcs import WCS
from lmfit import Model
from matplotlib.ticker import MaxNLocator
from mpl_toolkits.axes_grid1 import make_axes_locatable
from tqdm import tqdm
plt.rcParams['font.size'] = 9.0
# ==============================================================================
def parse_config(config):
"""
Reads input configuration file name (e.g. 'config.ini'), extracts
parameter options and returns lists of parameter values for each section.
Configuration file sections:
- [paths]: Main directory and subdirectory management
- [input]: Input data filename and subcube selection
- [processing]: Parallel processing options
- [fitting]: Fitting procedure options
- [output]: Set various output options
"""
# Initialise ConfigParser
cfg = configparser.ConfigParser(inline_comment_prefixes='#')
# Read configuration file
cfg.read(config)
# Get items from each section
# [paths]:
path = cfg.get('paths', 'path')
if path == 'default':
path = os.getcwd() + '/' # Path to repositor
inp_dir = path + cfg.get('paths', 'input_dir')
pro_dir = path + cfg.get('paths', 'prod_dir')
mod_dir = path + cfg.get('paths', 'model_dir')
# [input]:
inp_fn = cfg.get('input', 'input_fn')
s_cube = cfg.getboolean('input', 'subcube')
if s_cube: # Format bounds into list if subcube: True
s_bounds = [int(sb) for sb in cfg.get(
'input', 'subcube_bounds').strip('[]').split(",")]
else:
s_bounds = None
# [processing]:
para = cfg.getboolean('processing', 'parallel')
nprc = cfg.get('processing', 'nproc')
if (nprc == 'auto') & (mp.cpu_count() > 2):
nprc = mp.cpu_count() - 1
elif (mp.cpu_count() > 2):
nprc = int(nprc)
else:
para = False
nprc = 1
# [fitting]:
rmschan = cfg.getint('fitting', 'rmschan')
snrlim = cfg.getfloat('fitting', 'snrlim')
n_max = cfg.getint('fitting', 'n_max')
delbic = cfg.getfloat('fitting', 'delbic')
fwhm_guess = cfg.getfloat('fitting', 'fwhm_guess')
tau_guess = cfg.getfloat('fitting', 'tau_guess')
fwhm_limits = tuple([float(t) for t in cfg.get(
'fitting', 'fwhm_limits').strip('[]').split(',')])
tau_limits = tuple([float(t) for t in cfg.get(
'fitting', 'tau_limits').strip('[]').split(',')])
v_guess_tolerance = cfg.getfloat('fitting', 'v_guess_tolerance')
line_model = cfg.get('fitting', 'line_model')
min_dv = cfg.getfloat('fitting', 'min_dv')
constrain_fits = cfg.getboolean('fitting', 'constrain_fits')
method = cfg.get('fitting', 'method')
verbose = cfg.getboolean('fitting', 'verbose')
cleaniter = cfg.getint('fitting', 'cleaniter')
refrad = cfg.getint('fitting', 'refrad')
use_integ_res = cfg.getboolean('fitting', 'use_integ_res')
# [output]:
save_products = cfg.getboolean('output', 'save_products')
do_summary_figures = cfg.getboolean('output', 'do_summary_figures')
do_plots = cfg.getboolean('output', 'do_plots')
save_figures = cfg.getboolean('output', 'save_figures')
save_table = cfg.getboolean('output', 'save_table')
# Create lists of options for each section of the config file
cfg_paths = [path, inp_dir, pro_dir, mod_dir]
cfg_input = [inp_fn, s_cube, s_bounds]
cfg_processing = [para, nprc]
cfg_fitting = [rmschan, snrlim, n_max, delbic,
fwhm_guess, tau_guess, fwhm_limits, tau_limits,
v_guess_tolerance, line_model, min_dv, constrain_fits,
method, verbose, cleaniter, refrad,
use_integ_res]
cfg_output = [save_products, do_summary_figures, do_plots, save_figures,
save_table]
"""
These chould be dictionaries instead, but at least this is compact.
"""
return cfg_paths, cfg_input, cfg_processing, cfg_fitting, cfg_output
# ==============================================================================
# Initialise code timing and set some plotting settings
start_time = time.time()
plt.ion()
plt.rcParams['image.origin'] = 'lower'
# Get input data and config file from command line arguments
if len(sys.argv) == 1:
print(' No config file or input data specified. \n Quitting.')
sys.exit()
else:
arg_list = sys.argv[1:] # Get command line arguments
# arg_list = ['/opt/homebrew/bin/ipython', 'config.ini', 'filename.fits']
# Determine which arguments are present
dat_name = [dn for dn in arg_list if '.fits' in dn]
cfg_name = [cn for cn in arg_list if '.ini' in cn]
# Parse config file
if len(cfg_name) == 1:
# print('\nUsing configuration file: {}'.format(cfg_name[0]))
cfg_lists = parse_config(config=cfg_name[0])
else:
print('\n No configuration file specified. ' +
'\n Using default: config.ini')
cfg_lists = parse_config(config='config.ini')
# Get section options from parsed config fi le and set appropriate variables
cfg_paths, cfg_input, cfg_processing, cfg_fitting, cfg_output = cfg_lists
# Path options
path = cfg_paths[0]
inpt_dir = cfg_paths[1]
prod_dir = cfg_paths[2]
if not os.path.exists(prod_dir):
os.makedirs(prod_dir) # Make product directory if it doesn't exist
model_dir = cfg_paths[3]
# Input data options
if (cfg_input[0] == 'user') & (len(dat_name) == 0): # Check iput filename
print('\n No input data specified in command line or configuration file.' +
'\n Quitting.')
sys.exit()
elif len(dat_name) == 1:
print('\n Input data specified in command line, overriding configuration ' +
'file entry.') # Using input data: {}'.format(dat_name[0]))
inpt_fn = dat_name[0]
else:
print('\n Input data not specified in command line, using configuration ' +
'file entry.') # Using input data: {}'.format(cfg_input[0]))
inpt_fn = cfg_input[0]
if cfg_input[1]: # Check if only a subcube should be fit
ymin, ymax, xmin, xmax = cfg_input[2]
# Parallel processing options
parallel = cfg_processing[0]
nproc = cfg_processing[1]
# Fitting options
rmschan = cfg_fitting[0]
snrlim = cfg_fitting[1]
N_max = cfg_fitting[2]
delbic = cfg_fitting[3]
fwhm_guess= cfg_fitting[4]
tau_guess = cfg_fitting[5]
fwhm_limits = cfg_fitting[6]
tau_limits = cfg_fitting[7]
v_guess_tolerance = cfg_fitting[8]
line_model = cfg_fitting[9]
min_dv = cfg_fitting[10]
constrain_fits = cfg_fitting[11]
method = cfg_fitting[12]
verbose = cfg_fitting[13]
cleaniter = cfg_fitting[14]
refrad = cfg_fitting[15]
use_integ_residuals = cfg_fitting[16]
# Output options
save_products = cfg_output[0]
do_summary_figures = cfg_output[1]
do_plots = cfg_output[2]
save_figures = cfg_output[3]
save_table = cfg_output[4]
# Unless verbose mode is enabled, turn off annoying astropy warnings:
if not verbose:
warnings.simplefilter('ignore', category=AstropyWarning)
# ==============================================================================
def RMS(x, **kwargs):
"""
Calculate the root mean square (RMS) of an input array x.
"""
rms = np.sqrt(np.nanmean(np.square(x), **kwargs))
return rms
def RMS_map(data, method='ends', auto_Plim=0.005, ends_chans=rmschan,
frac_chans=0.125):
"""
Returns a masked spectrum containing only noise channels
Arguments:
spectrum - an astropy Quantity object containing a spectrum
method - 'auto', 'ends', or 'frac' ['ends']:
* auto - automatically identifies noise-only regions by assuming
that series of consecutive channels that have either all
positive or negative are unlikely to be attributable to random
noise. Assumes that spectra are well baselined. (EXPERIMENTAL)
* ends - assumes that the first and last channels in a spectrum are
emission free.
* frac - takes the RMS from a fraction of the start and end of the
spectrum, as defined by rmsfrac.
Plim - in conescutive mode, this gives the minimum likelihood that an
series of consecutive positive or negative pixels can be
expected from random noise. Smaller values leave more spectrum
unmasked [0.005].
endchan - number of channels at the beginning and end of the spectrum
assumed to be emission free [rmschan].
Returns:
The input spectrum with channels assumed to contain signal as NaNs
Notes:
The 'consecutive' method is similar to that described in Riener et al.
(2019) Sect 3.1.1.
"""
if data.ndim == 1:
data = data[:, np.newaxis, np.newaxis]
if type(data) == u.Quantity:
dataunit = data.unit
dataval = data.value
else:
dataunit = 1
dataval = data
if method == 'ends':
return RMS(np.concatenate([dataval[:ends_chans, :, :],
dataval[-ends_chans:, :, :]]),
axis=0) * dataunit
elif method == 'frac':
nchans = int(frac_chans * data.shape[0])
return RMS(np.concatenate([dataval[:nchans, :, :],
dataval[-nchans:, :, :]]),
axis=0) * dataunit
elif method == 'auto':
auto_map = np.zeros_like(data[0]) * np.nan
for i in tqdm(range(data.shape[2])):
for j in range(data.shape[1]):
spec = dataval[:, j, i]
masked_spec = spec.copy()
# Identify series of consecutive positive and negative values
positive = np.where(spec > 0)[0]
negative = np.where(spec < 0)[0]
posseries = np.split(positive,
np.where(np.diff(positive) != 1)[0] + 1)
negseries = np.split(negative,
np.where(np.diff(negative) != 1)[0] + 1)
poslist = [list(p) for p in posseries]
neglist = [list(p) for p in negseries]
lists = poslist + neglist
# Estimate probability of their random occurrence
prob = 0.5**np.array([len(lis) for lis in lists])
# Mask out windows whose occurence is inconsistent with noise
for window in np.where(prob < Plim)[0]:
masked_spec[lists[window]] = np.nan
auto_map[j, i] = RMS(masked_spec)
return auto_map * dataunit
else:
print('RMS method not recognised')
def mask_spectrum(spectrum, method='ends', Plim=0.005, endchan=rmschan):
"""
Returns a masked spectrum containing only noise channels
Arguments:
spectrum - an astropy Quantity object containing a spectrum
method - 'consecutive' or 'ends' ['consecutive']:
* consecutive - assumes that series of consecutive channels that
have either all positive or negative are unlikely to be
attributable to random noise, and masks those.
* ends - assumes that the first and last channels in a spectrum are
emission free.
Plim - in conescutive mode, this gives the minimum likelihood that an
series of consecutive positive or negative pixels can be
expected from random noise. Smaller values leave more spectrum
unmasked [0.005].
endchan - number of channels at the beginning and end of the spectrum
assumed to be emission free [rmschan].
Returns:
The input spectrum with channels assumed to contain signal as nans
Notes:
The 'consecutive' method is similar to that described in Riener et al.
(2019) Sect 3.1.1.
"""
masked_spectrum = spectrum.copy()
if method == 'consecutive':
# Identify series of consecutive positive and negative values
positive = np.where(spectrum.value > 0)[0]
negative = np.where(spectrum.value < 0)[0]
posseries = np.split(positive, np.where(np.diff(positive) != 1)[0] + 1)
negseries = np.split(negative, np.where(np.diff(negative) != 1)[0] + 1)
lists = np.concatenate([posseries, negseries])
# Estimate probability of their random occurrence
prob = 0.5**np.array([len(lis) for lis in lists])
# Mask out windows whose occurence is inconsistent with noise
for window in np.where(prob < Plim)[0]:
masked_spectrum[lists[window]] = np.nan
elif method == 'ends':
masked_spectrum[rmschan:-rmschan] = np.nan
return masked_spectrum
def tau(vels, p2, p3, p4):
"""
Purpose:
Eq. 2.2 from CLASS hyperfine fitting guide. See:
https://www.iram.fr/IRAMFR/GILDAS/doc/html/class-html/node11.html
Arguments:
vels = velocities of channels for produced spectrum
p2 = centroid velocity
p3 = velocity FWHM
p4 = Tau main
Returns:
Model tau "spectrum".
"""
nu_i, r_i = model['nu_0i'], model['r_i'] # Hyperfine components
nu_rest = model['nu_rest'] # Rest frequency
# Velocity shifts of hyperfine components
v_i = nu_i.to(u.km / u.s, equivalencies=u.doppler_radio(nu_rest)).value
# Calculate tau for each component
t_i = [r_i[i] * np.exp(-4 * np.log(2) * ((vels - v_i[i] - p2) / p3)**2) for
i in range(len(v_i))]
# Calculate tau(nu)
tau_nu = p4 * np.nansum(t_i, axis=0)
return tau_nu
def Tant(vels, p1, p2, p3, p4):
"""
Purpose:
Equation 2.3 from CLASS hyperfine fitting guide - 1 component. See:
https://www.iram.fr/IRAMFR/GILDAS/doc/html/class-html/node11.html
Arguments:
vels = velocities of channels for produced spectrum
p1 = Tant * Tau
p2 = centroid velocity
p3 = velocity FWHM
p4 = Tau main
Returns:
Model intensity/antenna temperature spectrum.
"""
T_ant = (p1 / p4) * (1 - np.exp(-tau(vels, p2, p3, p4)))
return T_ant
def set_pars(p, p_guess, p_bound, prefix=''):
"""
Sets initial guess (p_guess) paramters and their bounds (p_bound) for an
input LMFIT parameter object p. A parameter name prefix can be specified if
fitting model is composed of a series of sub-models. p_guess is a list of
values, p_bound is a list of tuples with format: (lower, upper).
"""
# Extract p_guess values
p1_g, p2_g, p3_g, p4_g = p_guess
# Extract p_bound tuples
p1_b, p2_b, p3_b, p4_b = p_bound
# Set guess parameters
p[prefix + 'p1'].value = p1_g
p[prefix + 'p2'].value = p2_g
p[prefix + 'p3'].value = p3_g
p[prefix + 'p4'].value = p4_g
# Set bounds of fit parameters
p[prefix + 'p1'].min, p[prefix + 'p1'].max = p1_b
p[prefix + 'p2'].min, p[prefix + 'p2'].max = p2_b
p[prefix + 'p3'].min, p[prefix + 'p3'].max = p3_b
p[prefix + 'p4'].min, p[prefix + 'p4'].max = p4_b
return p
def fitcomp(spec, vaxis, ncomp=N_max, guesses=None, bounds=None, min_dv=min_dv,
rmschan=rmschan, method=method, verbose=False):
"""
The main fitting code.
Purpose:
Produce a best-fit model of n components in a spectrum
Arguments:
spec - the spectrum to fit
vaxis - the accompanying velocity axis.
ncomp - number of components to fit
guesses - List of the 4 guess parameters: T*tau, vlsr, fwhm, tau
bounds - List of tuples of the lower and upper bounds of each parameter
min_dv - Minimum separation between velocity componenets. If set to
'linewidth' then separation is set to linewidth/2, though this
is not yet tested/fully functional.
rmschan - Number of channels from ends of spectrum used to calculate
rms [25].
method - ['leastsq'] the lmfit 'method'
Returns:
The lmfit mod.fit() object
"""
if verbose:
print(f'\n ----- Fitting spectrum at {spec.yx} -----')
if not isinstance(ncomp, int):
raise ValueError('ncomp must be an integer')
if ncomp == 1:
if verbose:
print(f'\n Fitting {ncomp} component')
elif ncomp > 1:
if verbose:
print(f'\n Fitting {ncomp} components')
if ncomp > N_max:
raise ValueError('The number of componenets (ncomp) must be between'
+ ' 1 and {}'.format(N_max))
rms = RMS(mask_spectrum(spec)).value
w = 1 / rms
if guesses is None:
# T*tau, vlsr, fwhm, tau
guesses = [np.nanmax(spec).value,
vaxis[np.argmax(spec)].value,
fwhm_guess,
tau_guess]
if bounds is None:
'''
Notes on bounds [Ttau, vlsr, fwhm, tau]:
-Ttau should be constrained by [N*rms, peak] * tau_main bounds.
-vlsr should be probably constrained by the dispersion of the cloud.
-fwhm should be probably constrained by the dispersion of the cloud.
-tau (main) could be the same way as GILDAS, or be more generous.
'''
fwhm_min, fwhm_max = fwhm_limits
tau_min, tau_max = tau_limits
v_gt = v_guess_tolerance
vlsr_min, vlsr_max = (np.max((guesses[1] - v_gt, vaxis.min().value)),
np.min((guesses[1] + v_gt, vaxis.max().value)))
bounds = [(tau_min * 3 * rms, tau_max * 1.5 * guesses[0]),
(vlsr_min, vlsr_max),
(fwhm_min, fwhm_max),
(tau_min, tau_max)]
fitlist = []
for i in range(ncomp):
comp = i + 1
pfix = '_' + str(comp) + '_' # Model parameter prefix
if i == 0:
mod = Model(Tant, prefix=pfix)
pars = mod.make_params()
else:
# if verbose: print('\n * Fitting {} components'.format(ncomp))
# Add extra line model (component) to total model (series)
mod += Model(Tant, prefix=pfix)
# Extend pars to include new model parameters
pn = mod.param_names[-4:] # Get 4 newest parameter names
pars.add_many((pn[0],), (pn[1],), (pn[2],), (pn[3],))
pars = set_pars(p=pars,
p_guess=guesses,
p_bound=bounds,
prefix=pfix)
if constrain_fits:
# Add minimum component peak strength (strongest hyperfine, r=7/27)
pars.add('min_peak', value=2 * snrlim * rms, min=snrlim * rms,
vary=True)
pars[pfix + 'p1'].expr = ('min_peak * ' + pfix +
'p4 / (1 - exp(-' + pfix +
'p4 * (7/27)))')
'''
WARNING: This is expression currently hard-coded for N2H+(1-0)
This is currently set as snrilim, with the inital guess at 2*snrlim,
but could be lowered.
We could consider having this only activate when line_model='n2h+_1-0',
ideally though there should be a way for the user to edit this condition
depending on the molecule (might be a lot of work)
'''
if (i > 0):
'''
If the initial fit wasn't an obvious success, try guessing the
velocity from the velocity range of detected components. Previously
from the velocity of the residual maximmum.
'''
previous_vlsr = fitlist[0].best_values['_1_p2']
# Establish range of detected emission
'''Set the minimum SNR for this method of guess the second vlsr_max
to give an insignificant probability of mis-interpretating a random
noise feature as emission. There is a 1 in 2000 chance of
encountering a spurious SNR = 3.5 noise feature, so this limit
should work so long as the user has significantly fewer than 2000
channels per spectrum. At a snr_vguess of 8.2, the isolated
component in the CLASS 7-component N2H+ model will just be
detected, and so values lower than this risk this method not
working properly. The spatial refitting procedure should, however,
fix most issues arising from this.'''
snr_vguess = max([snrlim / 2, 3.5])
detected_v_ax = v_ax[np.where(spec.value > (snr_vguess * rms))]
vrange = [detected_v_ax.min().value, detected_v_ax.max().value]
# Given 1st comp fit, calculate expected range of hyperfine comps
previous_hf_v = previous_vlsr + model_dv.value
# Determine offset between vrange and expected range from 1st comp
diff = [vrange[0] - previous_hf_v.min(),
vrange[1] - previous_hf_v.max()]
vsep_guess = diff[np.argmax(np.abs(diff))]
guesses[1] = previous_vlsr + vsep_guess
vlsr_min, vlsr_max = (np.max((guesses[1] - v_gt,
vaxis.min().value)),
np.min((guesses[1] + v_gt,
vaxis.max().value)))
# Update the bounds for the new velocity guess
bounds = [(tau_min * 3 * rms, tau_max * 1.5 * guesses[0]),
(vlsr_min, vlsr_max),
(fwhm_min, fwhm_max),
(tau_min, tau_max)]
if min_dv == 'linewidth':
min_dv_expr = ('(((_1_p3/2) + _1_p2) or ' +
'(-(_1_p3/2) + _1_p2))')
if i > 1:
min_dv_expr = (min_dv_expr + ' and ' +
'(((_2_p3/2) + _1_p2) or ' +
' (-(_2_p3/2) + _2_p2))')
else:
if vsep_guess < 0:
pars.add('min_dv', value=vsep_guess - min_dv,
max=-min_dv, vary=True)
elif vsep_guess > 0:
pars.add('min_dv', value=vsep_guess + min_dv,
min=min_dv, vary=True)
min_dv_expr = '(min_dv + _1_p2)'
if i > 1:
if vsep_guess < 0:
pars.add('min_dv', value=vsep_guess - min_dv,
max=-min_dv, vary=True)
elif vsep_guess > 0:
pars.add('min_dv', value=vsep_guess + min_dv,
min=min_dv, vary=True)
min_dv_expr = (min_dv_expr + ' and ' +
'(min_dv + _2_p2)')
pars[pfix + 'p2'].expr = min_dv_expr
pars = set_pars(p=pars,
p_guess=guesses,
p_bound=bounds,
prefix=pfix)
fit = mod.fit(spec.value, pars, vels=vaxis.value, weights=w,
method=method, scale_covar=False,
nan_policy='propagate')
residuals = fit.data - fit.best_fit
# Add additional data to fit object
fit.rms = rms
fit.ncomp = comp
fit.residuals = residuals
fit.rms_residuals = RMS(residuals)
fitlist.append(fit)
return fitlist
def bestcomps(fitlist, verbose=False, delbic0=delbic, redchimax=25):
"""
Determine which number of components is optimal
Arguments:
fits - list of model fits. The result of fitcomp.
verbose - more print statements
sigrac - [0.2] fractional improvement in redchi/bic to be
significant
delbic0 - [10] minimum decrease in BIC considered significant
Wikipedia suggests a value of 10, but might overfit for us.
redchimax - [25] Limit at which one component will be returned with a
bad quality flag.
Returns:
nbest - the optimal number of components
"""
ncomps = len(fitlist)
converged = [fit.success for fit in fitlist]
if verbose:
print(f'\n Determing the best of {ncomps} components')
rchs = [fit.redchi for fit in fitlist]
bics = [fit.bic for fit in fitlist]
del_bics = [bics[i - 1] - bics[i] for i in range(ncomps)[1:]]
nbest = 0
for i in range(ncomps):
# Check if fit converged
if fitlist[i].success:
if verbose:
print(f'\nComponent {i + 1} fit converged')
quality = 1
else:
if verbose:
print(f'\nComponent {i + 1} fit not converged')
quality = 0
if i == 0:
nbest = 1
# Check for improvement in BIC
if i > 0:
if verbose:
print(f'-> Comparing fits with {i} and {i + 1} components...')
if del_bics[i - 1] > delbic0:
if verbose:
print(' + Significant improvement in BIC')
nbest = i + 1
elif verbose:
print(' - No significant improvement in BIC')
if (nbest == 0):
nbest = 1 + np.nanargmin(bics)
quality = 0
if verbose:
print('No fantastic fit found, returning BIC minimum.')
if verbose:
if nbest == 1:
print('1 component is the best fit.\n')
else:
print(f'{nbest} components is the best fit.\n')
return nbest, quality
def plot_fits(fitlist, precision=2, title=None, components=True):
"""
Plots the data, fit, and residuals on an axis object
Arguments:
fitlist - list of lmfit objects to plot
precision - number of decimal places on the printed fit parameters
title - title for the figure
"""
fig = plt.figure(figsize=(8, 2.5 * len(fitlist)))
plt.subplots_adjust(hspace=0)
if title is not None:
fig.suptitle(title)
for f, fit in enumerate(fitlist):
ncomps = f + 1
if ncomps == 1:
compstring = 'component'
else:
compstring = 'components'
if ncomps == bestcomps(fitlist)[0]:
fc = 'k'
alpha = 1
else:
fc = 'grey'
alpha = 0.5
if fit.success:
fitstring = 'converged'
else:
fitstring = 'not converged'
ax = fig.add_subplot(len(fitlist), 1, ncomps)
ax.plot(fit.userkws['vels'], fit.residuals,
c='k', alpha=alpha, label='residuals', lw=1)
ax.step(fit.userkws['vels'], fit.data,
c='k', alpha=alpha, label='data')
if components:
# print(fit.best_values)
for i in range(ncomps):
if i == 0:
clabel = 'components'
else:
clabel = None
Ttau = fit.best_values[f'_{i + 1}_p1']
vcen = fit.best_values[f'_{i + 1}_p2']
fwhm = fit.best_values[f'_{i + 1}_p3']
taum = fit.best_values[f'_{i + 1}_p4']
ax.plot(v_ax, Tant(v_ax.value, Ttau, vcen, fwhm, taum),
c='salmon', lw=1, alpha=alpha, label=clabel)
ax.plot(fit.userkws['vels'], fit.best_fit,
c='r', alpha=alpha, label='model')
if f == 0:
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.2), ncol=4)
ax.set_xlabel('Velocity [km s$^{-1}$]')
ax.axhline(5 * fit.rms, color='k', ls='--', lw=0.8, alpha=alpha)
ax.text(0.05, 0.9,
'{} {}: {}'.format(ncomps, compstring, fitstring)
+ '\nTant * tau = {}'.format(
np.round([fit.best_values['_{}_p1'.format(i)] for i in
1 + np.arange(ncomps)], precision))
+ '\nvlsr = {}'.format(
np.round([fit.best_values['_{}_p2'.format(i)] for i in
1 + np.arange(ncomps)], precision))
+ '\nFWHM = {}'.format(
np.round([fit.best_values['_{}_p3'.format(i)] for i in
1 + np.arange(ncomps)], precision))
+ '\ntau = {}'.format(
np.round([fit.best_values['_{}_p4'.format(i)] for i in
1 + np.arange(ncomps)], precision))
+ '\nrms_res = {:.4f}'.format(fit.rms_residuals)
+ '\nrchisq = {:.2f}'.format(fit.redchi)
+ '\nBIC = {:.1f}'.format(fit.bic),
va='top', ha='left', transform=ax.transAxes, c=fc)
xmin = np.min([ax.get_position().xmin for ax in fig.axes])
xmax = np.max([ax.get_position().xmax for ax in fig.axes])
ymin = np.min([ax.get_position().ymin for ax in fig.axes])
ymax = np.max([ax.get_position().ymax for ax in fig.axes])
fig.text(xmin * 0.4, (ymin + ymax) * 0.5,
'Brightness [{}]'.format(u.Unit(head['BUNIT']).to_string()),
rotation='vertical', va='center')
def plot_fits_yx(iy, ix):
""""
A thin wrapper for plot_fits which takes the y and x indices as opposed to
the flattend j index.
"""
jind = np.where(np.sum((yxindices.T == [iy, ix]), axis=1) == 2)[0][0]
plot_fits(fitcomp(spec[:, jind], v_ax), title=(iy, ix))
def plot_fit(y, x, components=True):
"""
Plots the best fit for a pixel based on what is saved in the data products
Arguments:
iy, ix - pixel coordinates of the spectrum
"""
fig = plt.figure(figsize=(8, 2.5))
fig.suptitle(f'(x, y) = ({x}, {y})')
ncomps = products[-1]['ncomp'][y, x]
compstring = 'component'
if ncomps > 1:
compstring += 's'
precision = 2 # Number of decimal places to quote fit parameters to
indices = np.where(~np.isnan(products[-1]['p2_vcen'][:, y, x]))[0]
Ttau_values = products[-1]['p1_Ttau'][:, y, x][indices]
vcen_values = products[-1]['p2_vcen'][:, y, x][indices]
fwhm_values = products[-1]['p3_fwhm'][:, y, x][indices]
taum_values = products[-1]['p4_taum'][:, y, x][indices]
success = products[-1]['quality'][y, x]
thismodel = products[-1]['model'][:, y, x]
if success == 1:
fitstring = 'converged'
else:
fistring = 'not converged'
ax = fig.add_subplot(111)
ax.plot(v_ax, data[:, y, x] - thismodel, label='residuals', c='k', lw=1)
ax.step(v_ax, data[:, y, x], label='data', c='k')
if components:
for i in range(ncomps):
if i == 0:
clabel = 'components'
else:
clabel = None
ax.plot(v_ax, Tant(v_ax.value, Ttau_values[i], vcen_values[i],
fwhm_values[i], taum_values[i]),
c='salmon', lw=1, label=clabel)
ax.plot(v_ax, thismodel, label='model', c='r')
ax.legend()
ax.set_xlabel('Velocity [km s$^{-1}$]')
ax.set_ylabel('Brightness [{}]'.format(u.Unit(head['BUNIT']).to_string()))
ax.axhline(snrlim * rms_map[y, x].value, color='k', ls='--', lw=0.5)
ax.text(0.05, 0.9,
'{} {}: {}'.format(ncomps, compstring, fitstring)
+ '\nTant * tau = {}'.format(
np.round([Ttau_values[i] for i in range(ncomps)], precision))
+ '\nvlsr = {}'.format(
np.round([vcen_values[i] for i in range(ncomps)], precision))
+ '\nFWHM = {}'.format(
np.round([fwhm_values[i] for i in range(ncomps)], precision))
+ '\ntau = {}'.format(
np.round([taum_values[i] for i in range(ncomps)], precision))
+ '\nrms_res = {:.4f}'.format(RMS((data[:, y, x] - thismodel)))
+ '\nrchisq = {:.2f}'.format(products[-1]['rchi'][y, x])
+ '\nBIC = {:.1f}'.format(products[-1]['bic'][y, x]),
va='top', ha='left', transform=ax.transAxes, c='k')
xmin = np.min([ax.get_position().xmin for ax in fig.axes])
xmax = np.max([ax.get_position().xmax for ax in fig.axes])
ymin = np.min([ax.get_position().ymin for ax in fig.axes])
ymax = np.max([ax.get_position().ymax for ax in fig.axes])
def clickspec(event, refit=False):
"""
Produces the set of spectra when clicking on any pixel in the summary
figure
"""
global ix, iy
ix, iy = int(np.round(event.xdata, 0)), int(np.round(event.ydata, 0))
jind = np.where(np.sum((yxindices.T == [iy, ix]), axis=1) == 2)[0][0]
print('Producing spectrum for (x, y) = ({}, {})'.format(ix, iy))
ax = event.inaxes
for ax in [event.canvas.figure.axes[i] for i in
[0, 2, 4, 6, 8, 10, 12, 14]]:
if len(ax.collections) > 0:
ax.collections[0].remove()
ax.scatter(ix, iy, marker='+', c='r', s=81)
plt.draw()
if refit:
plot_fits(fitcomp(spec[:, jind], v_ax), title=(iy, ix))
else:
plot_fit(iy, ix)
def summary_figure(numbers=False, crop_back=True, back_pad=10):
"""
Produces the summary figure
Arguments:
number - if True, plot numbers in the pixels of the integer maps
crop_back - if True, crop the axes to remove large areas of no data
Assumes background values will be 0s or NaNs
back_pad - minimum number of pixels padding between data and axes
"""
intmodel = np.nansum(products[-1]['model'], axis=0)
vmin, vmax = np.nanpercentile(intdata.value, [0, 99])
if crop_back:
nzeros = len(np.where(intdata.value == 0)[0])
n_nans = len(np.where(np.isnan(intdata.value))[0])
if nzeros > n_nans:
datapixels = np.where(intdata.value != 0)
elif n_nans > nzeros:
datapixels = np.where(~np.isnan(intdata.value))
else:
# print('Background values neither 0 or nan. Do not crop.')
crop_back = False
fig = plt.figure(figsize=(12, 7))
plt.subplots_adjust(left=0.03, right=0.96, top=0.93, bottom=0.02,
hspace=0.02, wspace=0.50)
fig.suptitle(f'{inpt_fn}\n snrlim={snrlim} delbic={delbic}')
ax1 = fig.add_subplot(241)
ax1.set_title('Integrated intensity')
im = ax1.imshow(intdata.value, vmin=vmin, vmax=vmax)
if crop_back:
ymax, xmax = np.max(datapixels, axis=1)
ymin, xmin = np.min(datapixels, axis=1)
ax1.set_xlim(xmin - back_pad, xmax + back_pad)
ax1.set_ylim(ymin - back_pad, ymax + back_pad)
divider = make_axes_locatable(ax1)
cax = divider.append_axes('right', size="5%", pad=0, axes_class=maxes.Axes)
cbar = fig.colorbar(im, cax=cax, pad=0)
cbar.set_label('[' + (u.Unit(head['BUNIT']) * v_ax.unit).to_string() + ']')
ax = fig.add_subplot(242, sharex=ax1, sharey=ax1)
ax.set_title('Integrated model')
im = ax.imshow((intmodel * chanwidth).value, vmin=vmin, vmax=vmax)
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size="5%", pad=0, axes_class=maxes.Axes)
cbar = fig.colorbar(im, cax=cax, pad=0)
cbar.set_label('[' + (u.Unit(head['BUNIT']) * v_ax.unit).to_string() + ']')
ax = fig.add_subplot(243, sharex=ax1, sharey=ax1)
ax.set_title('Residuals')
im = ax.imshow((np.nansum(data, axis=0) -
np.nansum(products[-1]['model'], axis=0))
* np.abs(v_ax[1] - v_ax[0]).value)
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size="5%", pad=0, axes_class=maxes.Axes)
cbar = fig.colorbar(im, cax=cax, pad=0)
cbar.set_label('[' + (u.Unit(head['BUNIT']) * v_ax.unit).to_string() + ']')
ax = fig.add_subplot(244, sharex=ax1, sharey=ax1)
ax.set_title('No. components')
im = ax.imshow(products[-1]['ncomp'], vmin=0, vmax=N_max)
if numbers:
for (j, i), label in np.ndenumerate(products[-1]['comp']):
ax.text(i, j, label, ha='center', va='center')
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size="5%", pad=0, axes_class=maxes.Axes)
cbar = fig.colorbar(im, cax=cax, pad=0, format="%.0f",
ticks=range(N_max + 1))
ax = fig.add_subplot(245, sharex=ax1, sharey=ax1)
ax.set_title('rms')
im = ax.imshow(rms_map.value)
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size="5%", pad=0, axes_class=maxes.Axes)
cbar = fig.colorbar(im, cax=cax, pad=0)
cbar.set_label('[' + (u.Unit(head['BUNIT'])).to_string() + ']')
ax = fig.add_subplot(246, sharex=ax1, sharey=ax1)
ax.set_title('Reduced chi-squared')
im = ax.imshow(products[-1]['rchi'])
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size="5%", pad=0, axes_class=maxes.Axes)
cbar = fig.colorbar(im, cax=cax, pad=0)
ax = fig.add_subplot(247, sharex=ax1, sharey=ax1)
ax.set_title('BIC')
im = ax.imshow(products[-1]['bic'])
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size="5%", pad=0, axes_class=maxes.Axes)
cbar = fig.colorbar(im, cax=cax, pad=0)
ax = fig.add_subplot(248, sharex=ax1, sharey=ax1)
ax.set_title('Quality')
im = ax.imshow(products[-1]['quality'], vmin=-1, vmax=1)
if numbers:
for (j, i), label in np.ndenumerate(prod_qual):
ax.text(i, j, label, ha='center', va='center', c='w')
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size="5%", pad=0, axes_class=maxes.Axes)
cbar = fig.colorbar(im, cax=cax, pad=0, ticks=[-1, 0, 1])
for ax in [fig.axes[i] for i in [0, 2, 4, 6, 8, 10]]:
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
# Add map-clicking feature
click = fig.canvas.mpl_connect('button_press_event', clickspec)
print('\n * Click on a pixel to inspect the spectrum and fit')
return fig
# ======================== Define the model ====================================
def get_model(model_name):
"""
Imports model from JSON file, reformats, adds units, normalises.
"""
# Load model dictionary (Probably should have to check for valid model)
with open(model_dir + model_name + '.json', 'r') as file:
model = json.load(file)
# Pull items from dictionary, reformat
f_unit = u.Unit(model['freq_unit'])
f_0i = model['nu_0i'] * f_unit
f_rest = model['nu_rest'] * f_unit
r_i = model['r_i'] / np.sum(model['r_i'])
# Create new model dictionary, populate with reformated items
model_dict = {}
model_dict['nu_0i'] = f_0i
model_dict['nu_rest'] = f_rest
model_dict['r_i'] = r_i
return model_dict