-
Notifications
You must be signed in to change notification settings - Fork 35
/
abssystem.py
555 lines (477 loc) · 17.1 KB
/
abssystem.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
""" Class for absorption systems
"""
from __future__ import print_function, absolute_import, division, unicode_literals
# Python 2 & 3 compatibility
try:
basestring
except NameError:
basestring = str
import numpy as np
import pdb
import warnings
from abc import ABCMeta
from astropy import units as u
from astropy.units import Quantity
from astropy.table import QTable
from astropy import constants as const
from astropy.coordinates import SkyCoord
from linetools.isgm.abscomponent import AbsComponent
from linetools.isgm import utils as ltiu
from linetools import utils as ltu
from linetools import line_utils as ltlu
from linetools.spectralline import AbsLine
from linetools.abund import ions
# Globals to speed things up
c_mks = const.c.to('km/s').value
class AbsSystem(object):
"""
Class for an absorption line system
Parameters
----------
abs_type : str or unicode
Type of absorption system, e.g. MgII, DLA, LLS
radec : tuple or coordinate
RA/Dec of the sightline or astropy.coordinate
zabs : float
Absorption redshift
vlim : Quantity array (2)
Velocity limits of the system
zem : float, optional
Emission redshift of background source
NHI : float, optional
Log10 of the HI column density
sig_NHI : np.array(2), optional
Log10 error of the HI column density (-/+)
name : str, optional
Name for the system
Attributes
----------
abs_type : str
coord : SkyCoord
RA/Dec of the sightline
zabs : float
Absorption redshift
zem : float
Emission redshift of background source
vlim : Quantity array (2)
Velocity limits of the system
NHI : float
Log10 of the HI column density
sig_NHI : np.array(2)
Log10 error of the HI column density (-/+)
MH : float
Metallicity (log10)
name : str
Name of the system
"""
__metaclass__ = ABCMeta
@classmethod
def from_abslines(cls, abslines, vlim=None, **kwargs):
"""Instantiate from a list of AbsLines
Parameters
----------
components : list
List of AbsComponent objects
"""
# Generate components
components = ltiu.build_components_from_abslines(abslines, **kwargs)
# Instantiate
slf = cls.from_components(components, vlim=vlim)
# Return
return slf
@classmethod
def from_components(cls, components, vlim=None, NHI=None):
"""Instantiate from a list of AbsComponent objects
Parameters
----------
components : list
List of AbsComponent objects
vlim : list, optional
Velocity limits for the system
If not set, the first components sets vlim
NHI : float, optional
Set the NHI value of the system. If not set,
the method sums the NHI values of all the HI
components input (if any)
"""
# Check
assert ltiu.chk_components(components)
# Instantiate with the first component
init_comp = components[0]
if vlim is None:
vlim = init_comp.vlim
# Attempt to set NHI
HI_comps = [comp for comp in components if comp.Zion == (1,1)]
if NHI is None:
NHI = 0.
for HI_comp in HI_comps: # Takes only the first line in each list
NHI += HI_comp._abslines[0].attrib['N'].value
if NHI > 0.:
NHI = np.log10(NHI)
#
slf = cls(init_comp.coord, init_comp.zcomp, vlim, NHI=NHI)
if slf.chk_component(init_comp):
slf._components.append(init_comp)
else:
raise IOError("Bad component input")
# Append with component checking
if len(components) > 1:
for component in components[1:]:
slf.add_component(component)
# Return
return slf
@classmethod
def from_json(cls, json_file, **kwargs):
""" Load from a JSON file (via from_dict)
Parameters
----------
json_file
kwargs
Returns
-------
AbsSystem
"""
idict = ltu.loadjson(json_file)
slf = cls.from_dict(idict, **kwargs)
return slf
@classmethod
def from_dict(cls, idict, skip_components=False, use_coord=False, **kwargs):
""" Instantiate from a dict. Usually read from the hard-drive
Parameters
----------
idict : dict
skip_components : bool, optional
If True, absorption components (if any exist) are not loaded from the input dict.
Use when you are only interested in the global properties of an AbsSystem
use_coord : bool, optinal
Use coordinates from the AbsSystem to build the components (and lines)
Speeds up performance, but you should know things are OK before using this
Returns
-------
AbsSystem
"""
if 'NHI' in idict.keys():
ckwargs = dict(NHI=idict['NHI'], sig_NHI=idict['sig_NHI'], flag_NHI=idict['flag_NHI'])
slf = cls(SkyCoord(ra=idict['RA']*u.deg, dec=idict['DEC']*u.deg),
idict['zabs'], idict['vlim']*u.km/u.s, zem=idict['zem'],
name=idict['Name'], **ckwargs)
# Other
if 'kin' in idict.keys():
slf.kin = ltu.convert_quantity_in_dict(idict['kin'])
if 'Refs' in idict.keys():
slf.Refs = idict['Refs']
# Components
if not skip_components:
# Components
if use_coord: # Speed up performance
coord = slf.coord
else:
coord = None
components = ltiu.build_components_from_dict(idict, coord=coord, **kwargs)
for component in components:
# This is to insure the components follow the rules
slf.add_component(component, **kwargs)
# Return
return slf
def __init__(self, radec, zabs, vlim, zem=0., abs_type=None,
NHI=0., sig_NHI=np.zeros(2), flag_NHI=0, name=None):
self.zabs = zabs
self.zem = zem
self.vlim = vlim
self.NHI = NHI
self.sig_NHI = sig_NHI
self.flag_NHI = flag_NHI
self.coord = ltu.radec_to_coord(radec)
if name is None:
self.name = 'J{:s}{:s}_z{:.3f}'.format(
self.coord.ra.to_string(unit=u.hour,sep='',pad=True),
self.coord.dec.to_string(sep='',pad=True,alwayssign=True),
self.zabs)
else:
self.name = name
# Abs type
if abs_type is None:
self.abs_type = 'NONE'
else:
self.abs_type = abs_type
# Components
self._components = [] # List of AbsComponent objects
# Kinematics
self.kin = {}
# Abundances and Tables
self._EW = QTable()
self._ionN = QTable()
self._trans = QTable()
self._ionstate = {}
self._abund = QTable()
# Refs (list of references)
self.Refs = []
def add_component(self, abscomp, tol=0.2*u.arcsec,
chk_sep=True, chk_z=True, overlap_only=False,
vtoler=1., debug=False, **kwargs):
"""Add an AbsComponent object if it satisfies all of the rules.
For velocities, we demand that the new component has a velocity
range that is fully encompassed by the AbsSystem.
We allow a small tolerance for round-off error
Should check for duplicates..
Parameters
----------
comp : AbsComponent
tol : Angle, optional
Tolerance on matching coordinates
Only used if chk_sep=True
chk_sep : bool, optional
Perform coordinate check (expensive)
chk_z : bool, optional
Perform standard velocity range test
overlap_only : bool, optional
Only require that the components overlap in redshift
vtoler : float, optional
Tolerance for velocity in km/s
Returns
-------
test : bool
True if successful
"""
# Coordinates
if chk_sep:
testcoord = bool(self.coord.separation(abscomp.coord) < tol)
else:
testcoord = True
# Now redshift/velocity
if chk_z:
# Will avoid Quantity for speed
comp_vlim_mks = abscomp.vlim.to('km/s').value
sys_vlim_mks = self.vlim.to('km/s').value
dz_toler = (1 + self.zabs) * vtoler / c_mks
zlim_comp = abscomp.zcomp + (1 + abscomp.zcomp) * (comp_vlim_mks / c_mks)
zlim_sys = self.zabs + (1 + self.zabs) * (sys_vlim_mks / c_mks)
if overlap_only:
testz = True
if debug:
pdb.set_trace()
if np.all(zlim_comp > np.max(zlim_sys + dz_toler)) or np.all(
zlim_comp < np.min(zlim_sys-dz_toler)):
testz = False
else:
testz = (zlim_comp[0] >= (zlim_sys[0]-dz_toler)) & (
zlim_comp[1] <= (zlim_sys[1]+dz_toler))
# Additional checks (specific to AbsSystem type)
testcomp = self.chk_component(abscomp)
test = testcoord & testcomp & testz
# Append?
if test:
self._components.append(abscomp)
else:
warnings.warn('Input AbsComponent with Zion={} does not match AbsSystem rules. Not appending'.format(abscomp.Zion))
#
return test
def chk_component(self, component):
"""Additional checks on the component
Parameters
----------
component : AbsComponent
"""
return True
def fill_ionN(self, **kwargs):
""" Fills the ionN Table from the list of components
"""
self._ionN = ltiu.iontable_from_components(self._components, **kwargs)
def fill_trans(self, **kwargs):
""" Fills the ionN Table from the list of components
"""
self._trans = ltlu.transtable_from_speclines(self.list_of_abslines())
def get_absline(self, inp):
""" Returns an AbsLine from the AbsSystem
Parameters
----------
inp : str or Quantity
str -- Name of the transition, e.g. 'CII 1334'
Quantity -- Rest wavelength of the transition, e.g. 1334.53*u.AA
to 0.01 precision
Returns
-------
absline -- AbsLine object or list of Abslines
More than one will be returned if this line exists in
multiple components. The returned quantity will then
be a list instead of a single object
"""
# Generate the lines
abslines = self.list_of_abslines()
if isinstance(inp,basestring):
names = np.array([absline.name for absline in abslines])
mt = np.where(names == inp)[0]
elif isinstance(inp,Quantity):
wrest = Quantity([absline.wrest for absline in abslines])
mt = np.where(np.abs(wrest-inp) < 0.01*u.AA)[0]
else:
raise IOError("Bad input to absline")
# Finish
if len(mt) == 0:
warnings.warn("No absline with input={}".format(inp))
return None
elif len(mt) == 1:
return abslines[mt]
else:
return [abslines[ii] for ii in mt]
def get_comp_from_absline(self, aline):
""" Returns the component that holds the input AbsLine
Parameters
----------
aline : AbsLine
Returns
-------
comp -- AbsComponent object that holds this AbsLine
"""
# Loop on components
for comp in self._components:
# Is the line present?
try:
idx = comp._abslines.index(aline)
except ValueError:
pass
else:
return comp
# Raise error?
warnings.warn("Input absorption line is not in any component")
return None
def list_of_abslines(self):
""" Generate a list of the absorption lines in this system
Drawn from the components
Returns
-------
abslist : list of AbsLines
"""
# Return
return [iline for component in self._components
for iline in component._abslines]
def measure_restew(self, spec=None, **kwargs):
""" Measure rest-frame EWs for lines in the AbsSystem
Parameters
----------
spec : XSpectrum1D, optional
kwargs
Returns
-------
"""
# Grab Lines
abs_lines = self.list_of_abslines()
# Loop
for iline in abs_lines:
# Fill in spec?
if spec is not None:
iline.analy['spec'] = spec
# Measure
iline.measure_restew(**kwargs)
def measure_aodm(self, spec=None, **kwargs):
""" Measure ADOM columns for the list of lines
Note: Components are *not* updated by default
Parameters
----------
spec : XSpectrum1D, optional
kwargs
Returns
-------
"""
# Grab Lines
abs_lines = self.list_of_abslines()
# Loop
for iline in abs_lines:
# Fill in spec?
if spec is not None:
iline.analy['spec'] = spec
# Measure
iline.measure_aodm(**kwargs)
#
print("You may now wish to update the component column densities with update_component_colm()")
def update_component_colm(self, **kwargs):
""" Synthesize/update column density measurements for components
Parameters
----------
kwargs
Returns
-------
"""
for comp in self._components:
comp.synthesize_colm(**kwargs)
def stack_plot(self, **kwargs):
"""Show a stack plot of the system, if spec are loaded
Assumes the data are normalized.
Parameters
----------
"""
from linetools.analysis import plots as ltap
ltap.stack_plot(self.list_of_abslines(), vlim=self.vlim, **kwargs)
def to_dict(self):
""" Write AbsSystem data to a dict that can be written with JSON
"""
import datetime
import getpass
date = str(datetime.date.today().strftime('%Y-%b-%d'))
user = getpass.getuser()
# Generate the dict
outdict = dict(Name=self.name, abs_type=self.abs_type, zabs=self.zabs,
vlim=self.vlim.to('km/s').value, zem=self.zem,
NHI=self.NHI, sig_NHI=self.sig_NHI, flag_NHI=self.flag_NHI,
RA=self.coord.ra.value, DEC=self.coord.dec.value,
kin=self.kin, Refs=self.Refs, CreationDate=date,
user=user
)
# Components
outdict['components'] = {}
for component in self._components:
outdict['components'][component.name] = ltu.jsonify(component.to_dict())
# Polish
outdict = ltu.jsonify(outdict)
# Return
return outdict
def write_json(self, outfil=None):
""" Generate a JSON file from the system
Returns
-------
"""
import io, json
# Generate the dict
odict = self.to_dict()
# Write
if outfil is None:
outfil = self.name+'.json'
with io.open(outfil, 'w', encoding='utf-8') as f:
f.write(json.dumps(odict, sort_keys=True, indent=4,
separators=(',', ': ')))
# Finish
print("Wrote {:s} system to {:s} file".format(self.name, outfil))
def __repr__(self):
txt = '<{:s}: name={:s} type={:s}, {:s} {:s}, z={:g}, NHI={:g}'.format(
self.__class__.__name__, self.name, self.abs_type,
self.coord.ra.to_string(unit=u.hour,sep=':',pad=True),
self.coord.dec.to_string(sep=':',pad=True,alwayssign=True),
self.zabs, self.NHI)
# Finish
txt = txt + '>'
return (txt)
class GenericAbsSystem(AbsSystem):
"""Class for Generic Absorption Line System
"""
def __init__(self, radec, zabs, vlim, **kwargs):
AbsSystem.__init__(self, radec, zabs, vlim, abs_type='Generic', **kwargs)
self.name = 'Foo'
def print_abs_type(self):
""""Return a string representing the type of vehicle this is."""
return 'Generic'
class LymanAbsSystem(AbsSystem):
"""Class for HI Lyman Absorption Line System
"""
def __init__(self, radec, zabs, vlim, **kwargs):
AbsSystem.__init__(self, radec, zabs, vlim, abs_type='HILyman', **kwargs)
def chk_component(self,component):
"""Require components are only of HI
"""
# Require HI
test = (component.Zion[0] == 1) & (component.Zion[1] == 1)
if not test:
warnings.warn('Input component must be HI')
return test
def print_abs_type(self):
""""Return a string representing the type of vehicle this is."""
return 'HILyman'