-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathradexfit.py
1552 lines (1436 loc) · 61.7 KB
/
radexfit.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RADEX Line Fitter
-----------------
Version 1.4
Copyright (C) 2022 Andrés Megías Toledano
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
radex_path = '/Users/andresmegias/Documents/RADEX/bin/radex'
config_file = 'examples/L1517B-HC3N.yaml'
import os
import re
import io
import sys
import copy
import time
import pickle
import platform
import subprocess
import yaml
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib as mpl
from io import StringIO
from scipy.optimize import minimize
import richvalues as rv
if len(sys.argv) != 1:
radex_path = 'radex'
def combine_rms(v):
"""
Return the final rms of the sum of signals with the given rms noises.
Parameters
----------
v : list / array (float)
Individual rms noises of each signal.
Returns
-------
y : float
Resulting rms noise.
"""
y = np.sqrt(1 / np.sum(1/np.array(v)**2))
return y
def remove_extra_spaces(input_text):
"""
Remove extra spaces from a text string.
Parameters
----------
input_text : str
Input text string.
Returns
-------
text : str
Resulting text.
"""
text = input_text
for i in range(15):
if ' ' in text:
text = text.replace(' ', ' ')
if text.startswith(' '):
text = text[1:]
return text
def format_species_name(input_name, simplify_numbers=True):
"""
Format text as a molecule name, with subscripts and upperscripts.
Parameters
----------
input_name : str
Input text.
simplify_numbers : bool, optional
Remove the brackets between single numbers.
Returns
-------
output_name : str
Formatted molecule name.
"""
original_name = copy.copy(input_name)
# upperscripts
possible_upperscript, in_upperscript = False, False
output_name = ''
upperscript = ''
inds = []
for i, char in enumerate(original_name):
if (char.isupper() and not possible_upperscript
and '-' in original_name[i:]):
inds += [i]
possible_upperscript = True
elif char.isupper():
inds += [i]
if char == '-' and not in_upperscript:
inds += [i]
in_upperscript = True
if not possible_upperscript:
output_name += char
if in_upperscript and i != inds[-1]:
if char.isdigit():
upperscript += char
if char == '-' or i+1 == len(original_name):
if len(inds) > 2:
output_name += original_name[inds[0]:inds[-2]]
output_name += ('$^{' + upperscript + '}$'
+ original_name[inds[-2]:inds[-1]])
upperscript = ''
in_upperscript, possible_upperscript = False, False
inds = []
if output_name.endswith('+') or output_name.endswith('-'):
symbol = output_name[-1]
output_name = output_name.replace(symbol, '$^{'+symbol+'}$')
original_name = copy.copy(output_name)
# subscripts
output_name, subscript, prev_char = '', '', ''
in_bracket = False
for i,char in enumerate(original_name):
if char == '{':
in_bracket = True
elif char == '}':
in_bracket = False
if (char.isdigit() and not in_bracket
and prev_char not in ['=', '-', '{', ',']):
subscript += char
else:
if len(subscript) > 0:
output_name += '$_{' + subscript + '}$'
subscript = ''
output_name += char
if i+1 == len(original_name) and len(subscript) > 0:
output_name += '$_{' + subscript + '}$'
prev_char = char
output_name = output_name.replace('^$_', '$^').replace('$$', '')
# vibrational numbers
output_name = output_name.replace(',vt', ', vt')
output_name = output_name.replace(', vt=', '$, v_t=$')
output_name = output_name.replace(',v=', '$, v=$')
for i,char in enumerate(output_name):
if output_name[i:].startswith('$v_t=$'):
output_name = output_name[:i+5] + \
output_name[i+5:].replace('$_','').replace('_$','')
# some formatting
output_name = output_name.replace('$$', '').replace('__', '')
# remove brackets from single numbers
if simplify_numbers:
single_numbers = re.findall('{(.?)}', output_name)
for number in set(single_numbers):
output_name = output_name.replace('{'+number+'}', number)
return output_name
def radex(molecule, min_freq, max_freq, kin_temp, backgr_temp, h2_num_dens,
col_dens, line_width):
"""
Perform the RADEX calculation with the given parameters.
Parameters
----------
molecule : str
RADEX name of the molecule.
min_freq : TYPE
Minimum frequency (GHz).
max_freq : str
Maximum frequency (GHz).
kin_temp : str / array
Kinetic temperature (K).
backgr_temp : str
Background temperature (K).
h2_num_dens : str / array
H2 number density (/cm3).
col_dens : str / array
Column density of the molecule (/cm2).
line_width : str
Line width of the lines of the molecule.
Returns
-------
transitions_df : dataframe
List of calculated transitions by RADEX on-line
"""
radex_name = species_abreviations[molecule]
def create_radex_input(molecule, min_freq, max_freq, kin_temp, backgr_temp,
h2_num_dens, col_dens, line_width):
"""
Create the RADEX input file with the given parameters.
"""
text = []
radex_name = species_abreviations[molecule]
if type(col_dens) is str or not hasattr(col_dens, '__iter__'):
col_dens = [col_dens]
if type(h2_num_dens) is str or not hasattr(h2_num_dens, '__iter__'):
h2_num_dens = [h2_num_dens]
if type(kin_temp) is str or not hasattr(kin_temp, '__iter__'):
kin_temp = [kin_temp]
num_calcs = 0
for col_dens_i in col_dens:
for h2_num_dens_i in h2_num_dens:
for kin_temp_i in kin_temp:
text += ['{}.dat'.format(radex_name)]
text += ['{}.out'.format(radex_name)]
text += ['{} {}'.format(min_freq, max_freq)]
text += ['{}'.format(kin_temp_i)]
text += ['1', 'H2', '{:e}'.format(float(h2_num_dens_i))]
text += ['{}'.format(backgr_temp)]
text += ['{:e}'.format(float(col_dens_i))]
text += ['{}'.format(line_width)]
text += ['1']
num_calcs += 1
text[-1] = text[-1].replace('1', '0')
for i in range(len(text) - 1):
text[i] += '\n'
with open('{}.inp'.format(radex_name), 'w') as file:
file.writelines(text)
return num_calcs
num_calcs = create_radex_input(molecule, min_freq, max_freq, kin_temp,
backgr_temp, h2_num_dens, col_dens,
line_width)
subprocess.run('{} < {}.inp > radex_log.txt'
.format(radex_path, radex_name), shell=True)
with open('{}.out'.format(radex_name), 'r') as file:
output_text = file.readlines()
i = -1
write_line = False
tables = [[] for j in range(num_calcs)]
for line in output_text:
if line.startswith('* Radex version'):
write_line = False
if i >= 0:
del tables[i][1]
i += 1
if write_line:
tables[i] += [line]
if line.startswith('Calculation finished'):
write_line = True
del tables[num_calcs-1][1]
transitions_df = [[] for j in range(num_calcs)]
for i in range(num_calcs):
tables[i] = ''.join(tables[i])
result_df = pd.read_csv(StringIO(tables[i]), delimiter='\s+')
transitions_dict = {'transition': result_df['LINE'].values,
'frequency (GHz)': result_df['FREQ'].values,
'temperature (K)': result_df['T_EX'].values,
'depth': result_df['TAU'].values,
'intensity (K)': result_df['T_R'].values}
transitions_df[i] = pd.DataFrame(transitions_dict)
return transitions_df
def get_madcuba_transitions(madcuba_csv, radex_table, molecule,
lines_margin=0.2):
"""
Extract the information from the MADCUBA table for comparing it with RADEX.
Parameters
----------
madcuba_csv : dataframe
MADCUBA table.
radex_table : dataframe
RADEX table with the desired transitions.
molecule : str
Molecule name in RADEX.
lines_margin : float, optional
Margin for identifying the lines in MADCUBA, in MHz. The default is 0.2.
Returns
-------
madcuba_table : dataframe
Desired dataframe, analogous to the given RADEX table.
"""
madcuba_table = copy.copy(radex_table)
madcuba_transitions = madcuba_csv[madcuba_csv['Formula']==molecule]
for i,line in radex_table.iterrows():
frequency = float(line['frequency (GHz)']) * 1e3
difference = abs(madcuba_transitions['Frequency'] - frequency)
cond = difference < lines_margin
rows = madcuba_transitions[cond]
intensity = 0
if len(rows) == 0:
madcuba_table.at[i,'intensity (K)'] = 0
madcuba_table.at[i,'transition'] = np.nan
madcuba_table.at[i,'frequency (GHz)'] = frequency
madcuba_table.at[i,'temperature (K)'] = np.nan
madcuba_table.at[i,'depth'] = np.nan
else:
for j,row in rows.iterrows():
intensity += float(row['Intensity'])
madcuba_table.at[i,'intensity (K)'] = intensity
madcuba_table.at[i,'transition'] = row['Transition']
madcuba_table.at[i,'frequency (GHz)'] = row['Frequency'] / 1e3
madcuba_table.at[i,'temperature (K)'] = row['Tex/Te']
madcuba_table.at[i,'depth'] = row['tau/taul']
return madcuba_table
def loss_function(observed_lines, observed_uncs, reference_lines):
"""
Compute the difference between the observed lines and the reference ones.
Parameters
----------
observed_lines : array
Observed intensities of the lines.
observed_uncs : array
Observed uncertainties for the line intensities.
reference_lines : array
Reference intensities of the lines.
Returns
-------
difference : float
Value of the difference between both input tables.
"""
loss = 0
for obs_intensity, obs_intensity_unc, ref_intensity in \
zip(observed_lines, observed_uncs, reference_lines):
obs_intensity = float(obs_intensity)
obs_intensity_unc = float(obs_intensity_unc)
ref_intensity = float(ref_intensity)
loss += ((obs_intensity - ref_intensity) / obs_intensity_unc)**2
return loss
def loss_distribution(observed_lines, observed_uncs, reference_lines,
len_sample=int(1e5)):
"""
Compute the loss distribution between the observed and reference lines.
Parameters
----------
observed_lines : list (float)
Intensities of the observed transitions.
observed_uncs : list (float)
Intensity uncertainties of the observed transitions.
reference_lines : list (float)
Intensities of the theoretical transitions.
len_sample : int
Number of points to create the distribution of intensities from the
uncertainties. The default is int(1e5).
Returns
-------
losses : array (float)
Values of the resulting losses between the observed and reference lines.
"""
observed_lines = np.array(observed_lines)
observed_uncs = np.array(observed_uncs)
reference_lines = np.array(reference_lines)
observed_lines_sample = np.repeat(observed_lines.reshape(-1,1).transpose(),
len_sample, axis=0)
for i, unc in enumerate(observed_uncs):
observed_lines_sample[:,i] += np.random.normal(0., unc, len_sample)
# observed_lines_sample = np.maximum(0., observed_lines_sample)
losses = [loss_function(observed_lines_i, observed_uncs, reference_lines)
for observed_lines_i in observed_lines_sample]
losses = np.array(losses)
return losses
def get_loss_from_radex(name, min_freq, max_freq, kin_temp, backgr_temp,
h2_num_dens, col_dens, line_width,
observed_lines, observed_uncs, inds):
"""
Compute the loss from a RADEX calculation with the given parameters.
Parameters
----------
molecule : str
RADEX name of the molecule.
min_freq : TYPE
Minimum frequency (GHz).
max_freq : str
Maximum frequency (GHz).
kin_temp : str
Kinetic temperature (K).
backgr_temp : str
Background temperature (K).
h2_num_dens : str
H2 number density (/cm3).
col_dens : str
Column density of the molecule (/cm2).
line_width : str
Line width of the lines of the molecule.
observed_lines : list (float)
Intensities of the observed transitions.
observed_uncs : list (float)
Intensity uncertainties of the observed transitions.
inds : list (int)
List of the indices of the desired transitions from RADEX output.
Returns
-------
losses : array
Array of the losses of the input parameters.
"""
radex_results = radex(name, min_freq, max_freq, kin_temp, backgr_temp,
h2_num_dens, col_dens, line_width)
losses = []
for radex_transitions in radex_results:
radex_lines = radex_transitions.iloc[inds]['intensity (K)'].values
loss = loss_function(observed_lines, observed_uncs, radex_lines)
losses += [loss]
if len(losses) == 1:
losses = loss
return losses
def radex_uncertainty_grid(observed_transitions, molecule, min_freq, max_freq,
kin_temp, backgr_temp, h2_num_dens, col_dens,
line_width, lim, fit_params, grid_points=15,
max_enlargings=10, inds=None):
"""
Calculate the uncertainty for a given column density with RADEX online.
Parameters
----------
molecule : str
RADEX name of the molecule.
min_freq : TYPE
Minimum frequency (GHz).
max_freq : str
Maximum frequency (GHz).
kin_temp : str
Kinetic temperature (K).
backgr_temp : str
Background temperature (K).
h2_num_dens : str
H2 number density (/cm3).
col_dens : str
Column density of the molecule (/cm2).
line_width : str
Line width of the lines of the molecule.
lim : float
Reference loss value for calculating the uncertainty.
fit_params: str
Parameters whose uncertainties will be calculated. Possible values are:
- column density
- column density, H2 number density
- column density, temperature
grid_points : int, optional
Number of values of column density for evaluating the loss.
The default is 15.
max_enlargings : int, optional
Number of times that the possible uncertainty range will be enlarged
from the initial ranges obtained fixing the other variable.
The default is 10.
inds : list (int), optional
List of the indices of the desired transitions from RADEX output.
The default is None (all transitions).
Returns
-------
col_dens : float
Final value of the column density.
col_dens_uncs : list
Uncertainties (lower and upper) for the columns density.
(col_dens_values, losses) : tuple(array)
Column density values and corresponding losses.
"""
params = (molecule, min_freq, max_freq, kin_temp, backgr_temp, h2_num_dens,
col_dens, line_width)
observed_lines = observed_transitions['intensity (K)'].values
observed_uncs = observed_transitions['intensity unc. (K)'].values
if type(inds) == type(None):
inds = np.arange(len(observed_lines))
def calculate_range(params, param_name):
"""
Obtain the right range to calculate the losses for the uncertainties.
Parameters
----------
params : float
Values of the RADEX parameters.
param_name : str
Name of the variable. Possibles values are: 'column density',
'H2 number density', and 'temperature'.
Returns
-------
x1 : float
Inferior limit.
x2 : float
Superior limit.
"""
(name, min_freq, max_freq, kin_temp, backgr_temp, h2_num_dens,
col_dens, line_width) = params
names = np.array(['column density', 'H2 number density', 'temperature'])
idx = np.array([6, 5, 3])[names == param_name][0]
x = params[idx]
min_x = 0.001*x
frac = 1
min_frac = 1e-5
good_range = False
all_fracs = []
while not good_range and frac > min_frac:
x1 = x - frac*x/2
x2 = x + frac*x/2
x1 = max(min_x, x1)
losses = []
x_values = [x1, x, x2]
for x_i in x_values:
if param_name == 'column density':
col_dens = x_i
elif param_name == 'H2 number density':
h2_num_dens = x_i
elif param_name == 'temperature':
kin_temp = x_i
loss = get_loss_from_radex(name, min_freq, max_freq, kin_temp,
backgr_temp, h2_num_dens, col_dens,
line_width, observed_lines,
observed_uncs, inds)
losses += [loss]
ind_min = np.argmin(losses)
x = x_values[ind_min]
if ind_min != 1:
raise Exception('Variable was not really minimized.')
small_range, large_range = False, False
if min(losses[0], losses[-1]) < lim:
small_range = True
threshold = losses[1] + 2 * (lim - losses[1])
if ((np.mean([losses[0], losses[1]]) > threshold)
and (np.mean([losses[1], losses[-1]]) > threshold)):
large_range = True
if large_range == small_range or x1 == min_x:
good_range = True
if not good_range:
if large_range and frac/2 not in all_fracs:
frac /= 2
print('Reduced relative range to {}.'.format(frac))
elif small_range and frac*2 not in all_fracs:
frac *= 2
print('Increased relative range to {}.'.format(frac))
else:
good_range = True
all_fracs += [frac]
return x1, x2
def get_uncertainty(x_values, params, param_name):
"""
Obtain the uncertainties given an input array of values of a variable.
Parameters
----------
x_values : array (float)
Input values in which range the uncertainties will be calculated.
params : tuple
Values of the RADEX parameters.
param_name : str
Name of the variable. Possibles values are: 'column density',
'H2 number density', and 'temperature'.
Returns
-------
x : float
Central value.
unc1 : float
Inferior uncertainty.
unc2 : float
Superior uncertainty.
losses : array (float)
Array of the loss values for the input values.
"""
(name, min_freq, max_freq, kin_temp, backgr_temp, h2_num_dens,
col_dens, line_width) = params
num_points = len(x_values)
names = np.array(['column density', 'H2 number density', 'temperature'])
idx = np.array([6, 5, 3])[names == param_name][0]
x = params[idx]
if param_name == 'column density':
col_dens = x_values
elif param_name == 'H2 number density':
h2_num_dens = x_values
elif param_name == 'temperature':
kin_temp = x_values
print('Calculating...')
losses = get_loss_from_radex(molecule, min_freq, max_freq, kin_temp,
backgr_temp, h2_num_dens, col_dens,
line_width, observed_lines,
observed_uncs, inds)
ic = np.argmin(losses)
if ic != (num_points-1) // 2:
x = x_values[ic]
print('Updated minimum value to {:4e}.'.format(x))
x1_old, x2_old = x_values[0], x_values[-1]
frac = 2 * (x2_old - x1_old) / x
x1 = x - frac*x/2
x2 = x + frac*x/2
X = np.linspace(x1, x2, int(10*num_points))
Y = np.interp(X, x_values, losses)
cond1 = (X >= x1_old) & (X < x) & (Y < lim)
cond2 = (X <= x2_old) & (X > x) & (Y < lim)
if cond1.sum() > 0:
unc_1 = x - min(X[cond1])
else:
unc_1 = x_values[max(0, ic-1)]
if cond2.sum() > 0:
unc_2 = max(X[cond2]) - x
else:
unc_2 = x_values[min(ic+1, len(x_values)-1)]
return x, unc_1, unc_2, losses
def enlarge_uncs_2d(xa0, xb0, xa_values, xb_values, xa_losses, xb_losses,
name_a, name_b, params, lim=lim, grid_points=grid_points,
max_enlargings=max_enlargings):
"""
Explore the bidimensional space parameter to calculate uncertainties.
Parameters
----------
xa0 : float
Optimized value for the first variable.
xb0 : float
Optimized value for the second variable.
xa_values : array (float)
Input values for the first variable.
xb_values : array (float)
Input values for the second variable.
xa_losses : array (float)
Losses for the values of the first variable when the second one
has its optimized value.
xb_losses : array (float)
Losses for the values of the second variable when the first one
has its optimzed value.
name_a : str
Name of the first variable. Possibles values are: 'column density',
'H2 number density', and 'temperature'.
name_b : str
Name of the second variable. Possibles values are: 'column density',
'H2 number density', and 'temperature'.
params : tuple
Values of the RADEX parameters.
Returns
-------
xa_uncs : list (float)
New uncertainties for the first variable.
xb_uncs : list (float)
New uncertainties for the second variabl.
xa_new : array (float)
All values of the first variable where the loss is calculated.
xb_new : array (float)
All values of the second variables where the loss is calculated.
losses : array (float)
Loss value for each of the values of the input variables.
"""
print('Exploring the parameter space to improve the values of the '
+ 'uncertainties.')
(molecule, min_freq, max_freq, kin_temp, backgr_temp,
h2_num_dens, col_dens, line_width) = params
num_points_a = copy.copy(grid_points)
num_points_b = copy.copy(grid_points)
xa_new = copy.copy(xa_values)
xb_new = xb0 * np.ones(len(xa_values))
losses = copy.copy(xa_losses)
xa_new = np.append(xa_new, xa0 * np.ones(len(xb_values)))
xb_new = np.append(xb_new, xb_values)
losses = np.append(losses, xb_losses)
xa1, xa2 = min(xa_values), max(xa_values)
xb1, xb2 = min(xb_values), max(xb_values)
xa_range = xa2 - xa1
xb_range = xb2 - xb1
xa_m = (xa1 + xa2) / 2
xb_m = (xb1 + xb2) / 2
factor = 2
xa1n, xa2n = xa_m - factor*xa_range/2, xa_m + factor*xa_range/2
xb1n, xb2n = xb_m - factor*xb_range/2, xb_m + factor*xb_range/2
xa1n = max(0.01*xa_m, xa1n)
xb1n = max(0.01*xb_m, xb1n)
xa_range = xa2n - xa1n
xb_range = xb2n - xb1n
resolution_a = xa_range / num_points_a
resolution_b = xb_range / num_points_b
xa_arr = np.linspace(xa1n, xa2n, grid_points)
xb_arrs = [np.linspace(xb1n, xb2n, grid_points) for xai in xa_arr]
explore = True
num_enlargings = 0
while explore and num_enlargings <= max_enlargings:
xa1o, xa2o = copy.copy(xa1n), copy.copy(xa2n)
xb1o, xb2o = copy.copy(xb1n), copy.copy(xb2n)
for i, xai in enumerate(xa_arr):
print('Iteration {}/{}...'.format(i+1, len(xa_arr)))
xb_arr = xb_arrs[i]
if name_a == 'column density':
col_dens = xai
elif name_a == 'H2 number density':
h2_num_dens = xai
elif name_a == 'temperature':
kin_temp = xai
if name_b == 'column density':
col_dens = xb_arr
elif name_b == 'H2 number density':
h2_num_dens = xb_arr
elif name_b == 'temperature':
kin_temp = xb_arr
losses_i = \
get_loss_from_radex(molecule, min_freq, max_freq,
kin_temp, backgr_temp, h2_num_dens,
col_dens, line_width,
observed_lines, observed_uncs, inds)
xa_new = np.append(xa_new, xai*np.ones(len(xb_arr)))
xb_new = np.append(xb_new, xb_arr)
losses = np.append(losses, losses_i)
cond = losses < lim
xa_cond = xa_new[cond]
xb_cond = xb_new[cond]
xa_interv = [xa_cond.min(), xa_cond.max()]
xb_interv = [xb_cond.min(), xb_cond.max()]
xa_range = xa2o - xa1o
xb_range = xb2o - xb1o
margin_a = 6 * resolution_a
margin_b = 6 * resolution_b
enlarge_xa_p = ((xa2n - xa_interv[1]) < margin_a)
enlarge_xa_m = ((xa_interv[0] - xa1n) < margin_a)
enlarge_xb_p = ((xb2n - xb_interv[1]) < margin_b)
enlarge_xb_m = ((xb_interv[0] - xb1n) < margin_b)
if enlarge_xa_m and (xa1n - (xa2 - xa1)*factor/2) < 0.1*xa_m:
enlarge_xa_m = False
if enlarge_xb_m and (xb1n - (xb2 - xb1)*factor/2) < 0.1*xb_m:
enlarge_xb_m = False
if enlarge_xa_p or enlarge_xa_m or enlarge_xb_p or enlarge_xb_m:
print('Enlarging region.')
num_enlargings += 1
explore = True
if enlarge_xa_p:
xa2n += (xa2 - xa1) * factor/2
if enlarge_xa_m:
xa1n -= (xa2 - xa1) * factor/2
if enlarge_xb_p:
xb2n += (xb2 - xb1) * factor/2
if enlarge_xb_m:
xb1n -= (xb2 - xb1) * factor/2
num_points_a = int(round((xa2n - xa1n) / resolution_a))
num_points_b = int(round((xb2n - xb1n) / resolution_b))
xa_arr, xb_arrs = np.array([]), []
xa_all = np.linspace(xa1n, xa2n, num_points_a)
xb_all = np.linspace(xb1n, xb2n, num_points_b)
for i, xai in enumerate(xa_all):
xb_arr = np.array([])
for xbi in xb_all:
inside = ((xa1o <= xai <= xa2o) & (xb1o <= xbi <= xb2o))
if not inside:
xa_arr = np.append(xa_arr, xai)
xb_arr = np.append(xb_arr, xbi)
if len(xb_arr) > 0:
xb_arrs += [xb_arr]
xa_arr = np.unique(xa_arr)
else:
explore = False
return xa_interv, xb_interv, xa_new, xb_new, losses
if grid_points%2 == 0:
print('The number of points (N) must be odd, so we add 1 to N.')
grid_points += 1
if fit_params == 'column density':
print('Variable: column density')
x1, x2 = calculate_range(params, 'column density')
x_values = np.linspace(x1, x2, grid_points)
x, unc1, unc2, losses = get_uncertainty(x_values, params,
'column density')
results = (rv.RichValue(x, [unc1, unc2]), (x_values, losses))
elif fit_params == 'column density, H2 number density':
num_points_ind = max(15, grid_points//3)
if num_points_ind % 2 == 0:
num_points_ind += 1
print('Variable: column density')
x1, x2 = calculate_range(params, 'column density')
x_values = np.linspace(x1, x2, num_points_ind)
x, unc1, unc2, losses = get_uncertainty(x_values, params,
'column density')
xa0 = copy.copy(x)
xa_values = copy.copy(x_values)
xa_losses = copy.copy(losses)
print('Variable: H2 number density')
x1, x2 = calculate_range(params, 'H2 number density')
x_values = np.linspace(x1, x2, num_points_ind)
x, unc1, unc2, losses = get_uncertainty(x_values, params,
'H2 number density')
xb0 = copy.copy(x)
xb_values = copy.copy(x_values)
xb_losses = copy.copy(losses)
xa_interv, xb_interv, xa_new, xb_new, losses = \
enlarge_uncs_2d(xa0, xb0, xa_values, xb_values, xa_losses,
xb_losses, 'column density', 'H2 number density',
params, lim, grid_points=grid_points)
xa_uncs = [xa0 - xa_interv[0], xa_interv[1] - xa0]
xb_uncs = [xb0 - xb_interv[0], xb_interv[1] - xb0]
results = (rv.RichValue(xa0, xa_uncs), rv.RichValue(xb0, xb_uncs),
(xa_new, xb_new, losses))
elif fit_params == 'column density, temperature':
num_points_ind = max(15, grid_points//3)
if num_points_ind % 2 == 0:
num_points_ind += 1
print('Variable: column density (/cm2)')
x1, x2 = calculate_range(params, 'column density')
x_values = np.linspace(x1, x2, num_points_ind)
x, unc1, unc2, losses = get_uncertainty(x_values, params,
'column density')
xa0 = copy.copy(x)
xa_values = copy.copy(x_values)
xa_losses = copy.copy(losses)
print('Variable: temperature (K)')
x1, x2 = calculate_range(params, 'temperature')
x_values = np.linspace(x1, x2, num_points_ind)
x, unc1, unc2, losses = get_uncertainty(x_values, params,
'temperature')
xb0 = copy.copy(x)
xb_values = copy.copy(x_values)
xb_losses = copy.copy(losses)
xa_interv, xb_interv, xa_new, xb_new, losses = \
enlarge_uncs_2d(xa0, xb0, xa_values, xb_values, xa_losses,
xb_losses, 'column density', 'temperature', params,
lim, grid_points=grid_points)
xa_uncs = [xa0 - xa_interv[0], xa_interv[1] - xa0]
xb_uncs = [xb0 - xb_interv[0], xb_interv[1] - xb0]
results = (rv.RichValue(xa0, xa_uncs), rv.RichValue(xb0, xb_uncs),
(xa_new, xb_new, losses))
else:
raise Exception('Error: incorrect fit parameters.')
return results
def ticks_format(value, index):
"""
Format the input value.
Francesco Montesano
Get the value and returns the value formatted.
To have all the number of the same size they are all returned as LaTeX
strings
"""
if value == 0:
return '0'
else:
exp = np.floor(np.log10(value))
base = value/10**exp
if 0 <= exp <= 2:
return '${0:d}$'.format(int(value))
elif exp == -1:
return '${0:.1f}$'.format(value)
elif exp == -2:
return '${0:.2f}$'.format(value)
else:
return '${0:d}\\times10^{{{1:d}}}$'.format(int(base), int(exp))
def save_subplots(fig, size='auto', name='plot', form='pdf'):
"""
Save each of the subplots of the input figure as a individual plots.
Parameters
----------
fig : matplotlib figure
Figure object from Matplotlib.
size : tuple (float), optional.
Size of the individual figures for the subplots, in inches.
If 'auto', it automatically calculate the appropiate size, although
it will not work with subplots which have a colorbar.
name : str, optional
Main name of the files to be created. A number will be added to
indicate the subplot of the original figure. The default is 'plot'.
form : str, optional
Format of the output files.
Returns
-------
None.
"""
c = 0
suptitle = fig._suptitle.get_text()
for i, oax in enumerate(fig.axes):
if oax.get_label() == '<colorbar>':
c += 1
continue
buf = io.BytesIO()
pickle.dump(fig, buf)
buf.seek(0)
new_fig = pickle.load(buf)
new_fig.suptitle('')
new_ax = []
colorbar = False
for j, ax in enumerate(new_fig.axes):
colorbar = ((j == i+1)
and (j < len(fig.axes)
and fig.axes[j].get_label() == '<colorbar>'))
if j == i or colorbar:
new_ax.extend([ax])
else:
new_fig.delaxes(ax)
new_ax[0].set_subplotspec(plt.GridSpec(1,1)[0])
title = new_ax[0].get_title()
new_ax[0].set_title(suptitle + '\n' + title, fontweight='bold')
new_size = size
if type(size) is str and size == 'auto':
old_geometry = np.array(oax.get_subplotspec().get_geometry()[:2])[::-1]
new_size = fig.get_size_inches() / old_geometry
if len(new_ax) == 2:
new_ax[0].set_subplotspec(plt.GridSpec(1,2)[0])
new_ax[1].set_subplotspec(plt.GridSpec(1,2)[0])
new_size[0] = new_size[0] * 1.5
new_fig.set_size_inches(new_size, forward=True)
new_fig.set_dpi(fig.dpi)
plt.tight_layout()
plt.savefig('{}-{}.{}'.format(name, i+1-c, form), bbox_inches='tight')
plt.close()
species_abreviations = {
'CO': 'co',
'13CO': '13co',
'C18O': 'c18o',
'C17O': 'c17o',
'CS': 'cs',
'p-H2S': 'ph2s',
'o-H2S': 'oh2s',
'HCO+': 'hco+',
'DCO+': 'dco+',
'H13CO+': 'h13co+',
'HC18O+': 'hc18o+',
'HC17O+': 'hc17o+',
'Oatom': 'oatom',
'Catom': 'catom',
'C+ion': 'c+',
'N2H+': 'n2h+',
'HCN': 'hcn@hfs',
'H13CN': 'h13cn',
'HC15N': 'hc15n',
'HC3N': 'hc3n',
'HNC': 'hnc',
'SiO': 'sio',
'29SiO': '29sio',
'SiS': 'sis',
'O2': 'o2',
'CN': 'cn',
'SO': 'so',
'SO2': 'so2',
'o-SiC2': 'o-sic2',
'OCS': 'ocs',
'HCS+': 'hcs+',
'o-H2CO': 'o-h2co',
'p-H2CO': 'p-h2co',
'o-H2CS': 'oh2cs',
'p-H2CS': 'ph2cs',
'CH3OH-E': 'e-ch3oh',
'CH3OH-A': 'a-ch3oh',
'CH3CN': 'ch3cn',
'o-C3H2': 'o-c3h2',
'p-C3H2': 'p-c3h2',
'OH': 'oh',
'o-H2O': 'o-h2o',
'p-H2O': 'p-h2o',
'HDO': 'hdo',
'HCl': 'hcl@hfs',
'o-NH3': 'o-nh3',
'p-NH3': 'p-nh3',
'o-H3O+': 'o-h3o+',
'p-H3O+': 'p-h3o+',
'HNCO': 'hnco',
'NO': 'no',
'HF': 'hf'
}
#%%
plt.close('all')
t1 = time.time()
print()
print('RADEX Line Fitter')
print('-----------------')
# Default options.
default_config = {
'input files': [],
'output files': {'RADEX results': 'radex-output.yaml'},
'RADEX path': '',
'lines margin (MHz)': 0.2,
'RADEX parameters': [],
'RADEX fit parameters': 'column density',
'load previous RADEX results': False,
'maximum iterations for optimization': 1000,
'grid points': 15,
'show RADEX plots': True,