Skip to content

Commit e2a8329

Browse files
committed
Merge branch 'feature/90_logging' into develop #92
2 parents 1d5775b + fed703c commit e2a8329

14 files changed

Lines changed: 570 additions & 193 deletions

Metallicity_Stack_Commons/__init__.py

Lines changed: 56 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,29 @@
55
import getpass
66
import numpy as np
77

8+
from .logging import log_stdout, log_verbose
9+
810
version = "1.2.0"
911

1012
lambda0 = [3726.18, 4101.73, 4340.46, 4363.21, 4861.32, 4958.91, 5006.84]
1113
line_type = ['Oxy2', 'Balmer', 'Balmer', 'Single', 'Balmer', 'Single', 'Single']
1214
line_name = ['OII_3727', 'HDELTA', 'HGAMMA', 'OIII_4363', 'HBETA', 'OIII_4958',
1315
'OIII_5007']
1416

15-
line_name_short = {"OII": line_name[0], "4363": line_name[3],
16-
"HB": line_name[4], "OIII": line_name[-1],
17-
"HG": line_name[2], "HD": line_name[1]}
17+
line_name_short = {
18+
"OII": line_name[0],
19+
"4363": line_name[3],
20+
"HB": line_name[4],
21+
"OIII": line_name[-1],
22+
"HG": line_name[2],
23+
"HD": line_name[1]
24+
}
1825

19-
fitting_lines_dict = {"lambda0": lambda0, "line_type": line_type, "line_name": line_name}
26+
fitting_lines_dict = {
27+
"lambda0": lambda0,
28+
"line_type": line_type,
29+
"line_name": line_name
30+
}
2031

2132
all_lambda0 = [lambda0[0]] + [3728.91] + lambda0[1:]
2233
all_line_name = ['OII_3726', 'OII_3729'] + line_name[1:]
@@ -40,70 +51,95 @@
4051
k_dict = dict(zip(line_name, k_values))
4152

4253

43-
def exclude_outliers(objno):
54+
def exclude_outliers(objno, verbose=False, log=None):
4455
"""
4556
Exclude spectra that are identified as outliers.
4657
4758
Generally this is because the spectra have very high S/N on the continuum.
4859
4960
:param objno: list or numpy array of eight-digit identifier
61+
:param verbose: bool to write verbose message to stdout. Default: file only
62+
:param log: LogClass or logging object
5063
51-
:return:
52-
flag: numpy array of zeros and ones
64+
:return flag: numpy array of zeros and ones
5365
"""
5466

67+
if log is None:
68+
log = log_stdout()
69+
70+
log_verbose(log, "starting ...", verbose=verbose)
71+
5572
flag = np.zeros(len(objno), dtype=int)
56-
bad_data = np.array(['32007727', '32101412', '42006031', '32035286', '14023705'])
73+
bad_data = np.array(['32007727', '32101412', '42006031',
74+
'32035286', '14023705'])
5775
for ii in range(len(bad_data)):
58-
idx = [xx for xx in range(len(objno)) if bad_data[ii] in str(objno[xx])]
76+
idx = [xx for xx in range(len(objno)) if
77+
bad_data[ii] in str(objno[xx])]
5978
flag[idx] = 1
6079

80+
log_verbose(log, "finished.", verbose=verbose)
6181
return flag
6282

6383

64-
def dir_date(folder_name, path_init='', year=False):
84+
def dir_date(folder_name, path_init='', year=False, verbose=False, log=None):
6585
"""
6686
Purpose:
6787
This function finds and returns the path to a directory named after the
6888
current date (MMDDYYYY). If the directory doesn't exist yet, it creates
6989
a new directory named after the current date in the provided folder_name
7090
directory.
7191
72-
From https://github.com/rafia37/Evolution-of-Galaxies/blob/master/general.py
92+
From https://github.com/rafia37/Evolution-of-Galaxies/blob/master/general.py
93+
94+
Usage:
95+
fitspath = dir_date(folder_name, path_init='', year=True)
7396
7497
:param folder_name: str containing directory for date subdirectory will be in
7598
:param path_init: root path. Default: empty string
7699
:param year: Indicate whether to include year in date folder. Default: False
100+
:param verbose: bool to write verbose message to stdout. Default: file only
101+
:param log: LogClass or logging object
77102
78-
:return: fitspath: Full path to the date directory
79-
80-
Usage:
81-
fitspath = dir_date(folder_name, path_init='', year=True)
103+
:return fitspath: Full path to the date directory
82104
"""
83105

106+
if log is None:
107+
log = log_stdout()
108+
109+
log_verbose(log, "starting ...", verbose=verbose)
110+
84111
today = date.today()
85112

86-
list_path = [path_init, folder_name, "%02i%02i" % (today.month, today.day), '']
113+
list_path = [path_init, folder_name,
114+
f"{today.month:02d}{today.day:02d}", '']
87115
if year:
88-
list_path[-2] = "%i" % today.year + list_path[-2]
116+
list_path[-2] = f"{today.year:d}" + list_path[-2]
89117

90118
fitspath = os.path.join(*list_path)
91119
try:
92120
os.mkdir(fitspath)
93121
except FileExistsError:
94-
print("Path already exists : ", fitspath)
122+
log.warning(f"Path already exists : {fitspath}")
95123

124+
log_verbose(log, "finished.", verbose=verbose)
96125
return fitspath
97126

98127

99-
def get_user(username=None):
128+
def get_user(username=None, verbose=False, log=None):
129+
130+
if log is None:
131+
log = log_stdout()
132+
133+
log_verbose(log, "starting ...", verbose=verbose)
100134

101-
if isinstance(username, type(None)):
135+
if username is None:
102136
username = getpass.getuser()
103137

104138
if username in fitspath_dict.keys():
105139
fitspath = fitspath_dict[username]
106140
else:
141+
log.warning("Incorrect username input")
107142
raise ValueError("Incorrect username input")
108143

144+
log_verbose(log, "finished.", verbose=verbose)
109145
return fitspath

Metallicity_Stack_Commons/analysis/attenuation.py

Lines changed: 50 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import numpy as np
22

33
from .. import k_dict, line_name_short
4+
from ..logging import log_stdout, log_verbose
45

56
from chun_codes import compute_onesig_pdf
67

@@ -18,27 +19,38 @@
1819
k_HDELTA = k_dict[HD]
1920

2021

21-
def compute_EBV(ratio, source='HgHb', zero_neg=True):
22+
def compute_EBV(ratio, source='HgHb', zero_neg=True, verbose=False, log=None):
2223
"""
2324
Purpose:
2425
Determines E(B-V) from Hg/Hb or Hd/Hb flux ratios using Case B assumptions
2526
2627
:param ratio: float or numpy array containing Hg/Hb or Hd/Hb
2728
:param source: str indicate ratio type. Either 'HgHb' or 'HdHb'. Default: 'HgHb'
2829
:param zero_neg: boolean to indicate whether to zero out negative reddening. Default: True
30+
:param verbose: bool to write verbose message to stdout. Default: file only
31+
:param log: LogClass or logging object
2932
3033
:return EBV: float or numpy array containing E(B-V).
3134
Note: Not correcting for negative reddening
3235
:return EBV_peak: float or numpy array return when it is a 2-D distribution
3336
"""
3437

38+
if log is None:
39+
log = log_stdout()
40+
41+
log_verbose(log, "starting ...", verbose=verbose)
42+
3543
if isinstance(ratio, list):
36-
print("!!! Incorrect type for input [ratio]. Cannot be list !!!")
37-
raise TypeError
44+
log.warning("!!! Incorrect type for input [ratio]. Cannot be list !!!")
45+
raise TypeError("!!! Incorrect type for input [ratio]. Cannot be list !!!")
46+
47+
if source not in ['HgHb', 'HdHb']:
48+
log.warning("!!! Incorrect [source]")
49+
raise KeyError("!!! Incorrect [source]")
3850

39-
if 'HgHb' in source:
40-
ratio0 = HgHb_CaseB
41-
k1 = k_HGAMMA
51+
# For HgHb (default)
52+
ratio0 = HgHb_CaseB
53+
k1 = k_HGAMMA
4254

4355
if 'HdHb' in source:
4456
ratio0 = HdHb_CaseB
@@ -50,58 +62,76 @@ def compute_EBV(ratio, source='HgHb', zero_neg=True):
5062
if isinstance(EBV, float):
5163
if EBV < 0.0:
5264
EBV = 0.0
53-
print('zero substituted for negative reddening')
65+
log.info('zero substituted for negative reddening')
5466
return EBV
5567
else:
5668
if len(EBV.shape) == 1:
5769
neg_idx = np.where(EBV < 0.0)[0]
5870
if len(neg_idx) > 0:
5971
EBV[neg_idx] = 0.0
60-
print('zero substituted for negative reddening')
72+
log.info('zero substituted for negative reddening')
73+
log_verbose(log, "finished.", verbose=verbose)
6174
return EBV
6275
if len(EBV.shape) == 2:
6376
EBV_avg = np.average(EBV, axis=0) # initial guess
6477
EBV_err, EBV_peak = compute_onesig_pdf(EBV, EBV_avg, usepeak=True)
6578
neg_idx = np.where(EBV_peak < 0.0)[0]
6679
if len(neg_idx) > 0:
67-
print('EBV distribution shifted for peak')
80+
log.info('EBV distribution shifted for peak')
6881
EBV[neg_idx, :] -= EBV_peak[neg_idx].reshape((len(neg_idx), 1))
6982
EBV_peak[neg_idx] = 0.0
83+
log_verbose(log, "finished.", verbose=verbose)
7084
return EBV, EBV_peak
7185
else:
86+
log_verbose(log, "finished.", verbose=verbose)
7287
return EBV
7388

7489

75-
def compute_A(EBV):
90+
def compute_A(EBV, verbose=False, log=None):
7691
"""
7792
Purpose:
7893
Compute A(Lambda) for all possible emission lines
7994
8095
:param EBV: float value of E(B-V)
8196
Has not been configured to handle a large array. Some array handling would be needed
97+
:param verbose: bool to write verbose message to stdout. Default: file only
98+
:param log: LogClass or logging object
8299
83100
:return A_dict: dict containing A(lambda) with keys identical to k_dict
84101
"""
85102

103+
if log is None:
104+
log = log_stdout()
105+
106+
log_verbose(log, "starting ...", verbose=verbose)
107+
86108
k_arr = np.array(list(k_dict.values()))
87109

88110
A_arr = k_arr * EBV
89111
A_dict = dict(zip(list(k_dict.keys()), A_arr))
90112

113+
log_verbose(log, "finished.", verbose=verbose)
91114
return A_dict
92115

93116

94-
def line_ratio_atten(ratio, EBV, wave_top, wave_bottom):
117+
def line_ratio_atten(ratio, EBV, wave_top, wave_bottom, verbose=False,
118+
log=None):
119+
120+
if log is None:
121+
log = log_stdout()
122+
123+
log_verbose(log, "starting ...", verbose=verbose)
95124

96125
k_top = k_dict[wave_top]
97126
k_bottom = k_dict[wave_bottom]
98127

99128
ratio_atten = ratio * 10**(0.4*EBV*(k_top - k_bottom))
100129

130+
log_verbose(log, "finished.", verbose=verbose)
101131
return ratio_atten
102132

103133

104-
def Hb_SFR(log_LHb, EBV):
134+
def Hb_SFR(log_LHb, EBV, verbose=False, log=None):
105135
"""
106136
Purpose:
107137
Determine dust-corrected SFR using the H-beta luminosity and a
@@ -113,11 +143,19 @@ def Hb_SFR(log_LHb, EBV):
113143
:param log_LHb: numpy array or float containing logarithm of H-beta
114144
luminosity in units of erg/s
115145
:param EBV: numpy array or float providing E(B-V)
146+
:param verbose: bool to write verbose message to stdout. Default: file only
147+
:param log: LogClass or logging object
116148
117149
:return logSFR: numpy array or float containing the SFR in
118150
logarithmic units of M_sun/yr
119151
"""
120152

153+
if log is None:
154+
log = log_stdout()
155+
156+
log_verbose(log, "starting ...", verbose=verbose)
157+
121158
logSFR = np.log10(4.4e-42 * HaHb_CaseB) + 0.4*EBV*k_HBETA + log_LHb
122159

160+
log_verbose(log, "finished.", verbose=verbose)
123161
return logSFR

0 commit comments

Comments
 (0)