Skip to content

Commit d5aca95

Browse files
author
Tomas Stolker
committedMar 7, 2019
calibration spectra
1 parent 3b7a8d5 commit d5aca95

29 files changed

+833
-504
lines changed
 

‎species/__init__.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
from species.analysis.fit import FitSpectrum
1+
from species.analysis.fit_model import FitModel
2+
3+
from species.analysis.fit_spectrum import FitSpectrum
24

35
from species.analysis.photometry import SyntheticPhotometry, \
46
apparent_to_absolute
57

8+
from species.read.read_calibration import ReadCalibration
9+
610
from species.read.read_filter import ReadFilter
711

812
from species.read.read_model import ReadModel, \

‎species/analysis/fit.py ‎species/analysis/fit_model.py

+24-94
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
1-
"""
1+
'''
22
Text
3-
"""
3+
'''
44

5-
import os
65
import sys
76
import math
8-
import configparser
97

10-
import h5py
118
import emcee
129
import progress.bar
1310
import numpy as np
@@ -25,7 +22,7 @@ def lnprior(param,
2522
bounds,
2623
modelpar,
2724
prior):
28-
"""
25+
'''
2926
:param param: Parameter values.
3027
:type param: numpy.ndarray
3128
:param bounds: Parameter boundaries.
@@ -39,7 +36,7 @@ def lnprior(param,
3936
4037
:return: Log prior probability.
4138
:rtype: float
42-
"""
39+
'''
4340

4441
if prior:
4542

@@ -72,7 +69,7 @@ def lnlike(param,
7269
synphot,
7370
sampling,
7471
distance):
75-
"""
72+
'''
7673
:param param:
7774
:type param:
7875
:param modelpar:
@@ -90,7 +87,7 @@ def lnlike(param,
9087
9188
:return: Log likelihood probability.
9289
:rtype: float
93-
"""
90+
'''
9491

9592
global MIN_CHISQ
9693
global MIN_PARAM
@@ -123,7 +120,7 @@ def lnprob(param,
123120
sampling,
124121
distance,
125122
prior):
126-
"""
123+
'''
127124
:param param:
128125
:type param:
129126
:param bounds:
@@ -145,7 +142,7 @@ def lnprob(param,
145142
146143
:return:
147144
:rtype:
148-
"""
145+
'''
149146

150147
ln_prior = lnprior(param, bounds, modelpar, prior)
151148

@@ -164,18 +161,18 @@ def lnprob(param,
164161
return ln_prob
165162

166163

167-
class FitSpectrum:
168-
"""
164+
class FitModel:
165+
'''
169166
Text
170-
"""
167+
'''
171168

172169
def __init__(self,
173170
objname,
174171
filters,
175172
model,
176173
sampling,
177174
bounds):
178-
"""
175+
'''
179176
:param objname: Object name in the database.
180177
:type objname: str
181178
:param filters: Filter IDs for which the photometry is selected. All available
@@ -184,17 +181,14 @@ def __init__(self,
184181
:name model: Atmospheric model.
185182
:type model: str
186183
:name sampling: Wavelength sampling for the computation of synthetic photometry
187-
("specres" or "gaussian").
184+
('specres' or 'gaussian').
188185
:type sampling: tuple
189186
:name bounds: Parameter boundaries. Full parameter range is used if None or not specified.
190187
The radius parameter range is set to 0-5 Rjup if not specified.
191188
:type bounds: dict
192189
193190
:return: None
194-
"""
195-
196-
self.parsec = 3.08567758147e16 # [m]
197-
self.r_jup = 71492000. # [m]
191+
'''
198192

199193
self.object = read_object.ReadObject(objname)
200194
self.distance = self.object.get_distance()
@@ -252,10 +246,10 @@ def run_mcmc(self,
252246
guess,
253247
tag,
254248
prior=None,
255-
ncpu=1,):
256-
"""
249+
ncpu=1):
250+
'''
257251
:return: None
258-
"""
252+
'''
259253

260254
global MIN_CHISQ
261255
global MIN_PARAM
@@ -300,75 +294,11 @@ def run_mcmc(self,
300294

301295
progbar.finish()
302296

303-
self.store_samples(sampler, self.model, tag, (MIN_CHISQ, MIN_PARAM))
304-
305-
def store_samples(self,
306-
sampler,
307-
model,
308-
tag,
309-
chisquare):
310-
"""
311-
:param sampler: Ensemble sampler.
312-
:type sampler: emcee.ensemble.EnsembleSampler
313-
:param model: Atmospheric model.
314-
:type model: str
315-
:param tag: Database tag.
316-
:type tag: str
317-
:param chisquare: Maximum likelihood solution. Tuple with the chi-square value and related
318-
parameter values.
319-
:type chisquare: tuple(float, float)
320-
321-
:return: None
322-
"""
323-
324-
config_file = os.path.join(os.getcwd(), 'species_config.ini')
325-
326-
config = configparser.ConfigParser()
327-
config.read_file(open(config_file))
328-
329-
species_db = config['species']['database']
330-
331-
h5_file = h5py.File(species_db, 'a')
332-
333-
if 'results' not in h5_file:
334-
h5_file.create_group('results')
335-
336-
if 'results/mcmc' not in h5_file:
337-
h5_file.create_group('results/mcmc')
338-
339-
if 'results/mcmc/'+tag in h5_file:
340-
del h5_file['results/mcmc/'+tag]
341-
342-
samples = sampler.chain
343-
344-
dset = h5_file.create_dataset('results/mcmc/'+tag,
345-
data=samples,
346-
dtype='f')
347-
348-
dset.attrs['model'] = str(model)
349-
dset.attrs['distance'] = float(self.distance)
350-
dset.attrs['nparam'] = int(len(self.modelpar))
351-
352-
for i, item in enumerate(self.modelpar):
353-
dset.attrs['parameter'+str(i)] = str(item)
354-
355-
dset.attrs['min_chi'] = float(chisquare[0])
356-
for i, item in enumerate(self.modelpar):
357-
dset.attrs['chisquare'+str(i)] = float(chisquare[1][item])
358-
359-
mean_accep = np.mean(sampler.acceptance_fraction)
360-
dset.attrs['acceptance'] = float(mean_accep)
361-
print('Mean acceptance fraction: {0:.3f}'.format(mean_accep))
362-
363-
try:
364-
int_auto = emcee.autocorr.integrated_time(sampler.flatchain)
365-
print('Integrated autocorrelation time =', int_auto)
366-
367-
except emcee.autocorr.AutocorrError:
368-
int_auto = None
369-
370-
if int_auto is not None:
371-
for i, item in enumerate(int_auto):
372-
dset.attrs['autocorrelation'+str(i)] = float(item)
297+
species_db = database.Database()
373298

374-
h5_file.close()
299+
species_db.add_samples(sampler=sampler,
300+
spectrum=('model', self.model),
301+
tag=tag,
302+
chisquare=(MIN_CHISQ, MIN_PARAM),
303+
modelpar=self.modelpar,
304+
distance=self.distance)

‎species/analysis/fit_spectrum.py

+171
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
'''
2+
Text
3+
'''
4+
5+
import os
6+
import sys
7+
import math
8+
import configparser
9+
10+
import h5py
11+
import emcee
12+
import progress.bar
13+
import numpy as np
14+
15+
from species.analysis import photometry
16+
from species.data import database
17+
from species.read import read_model, read_object, read_calibration
18+
19+
20+
MIN_CHISQ = np.inf
21+
MIN_PARAM = None
22+
23+
24+
def lnprob(param,
25+
bounds,
26+
objphot,
27+
specphot):
28+
'''
29+
:param param: Parameter values.
30+
:type param: numpy.ndarray
31+
:param bounds: Parameter boundaries.
32+
:type bounds: tuple(float, float)
33+
:param objphot:
34+
:type objphot:
35+
:param specphot:
36+
:type specphot:
37+
38+
:return:
39+
:rtype:
40+
'''
41+
42+
global MIN_CHISQ
43+
global MIN_PARAM
44+
45+
if bounds[0] <= param <= bounds[1]:
46+
ln_prior = 0.
47+
48+
else:
49+
ln_prior = -np.inf
50+
51+
if math.isinf(ln_prior):
52+
ln_prob = -np.inf
53+
54+
else:
55+
chisq = 0.
56+
for i, item in enumerate(objphot):
57+
chisq += (objphot[i][0]-param*specphot[0])**2 / objphot[i][1]**2
58+
59+
if chisq < MIN_CHISQ:
60+
MIN_CHISQ = chisq
61+
MIN_PARAM = {'scaling':param}
62+
63+
ln_prob = ln_prior - 0.5*chisq
64+
65+
return ln_prob
66+
67+
68+
class FitSpectrum:
69+
'''
70+
Text
71+
'''
72+
73+
def __init__(self,
74+
objname,
75+
filters,
76+
spectrum,
77+
bounds):
78+
'''
79+
:param objname: Object name in the database.
80+
:type objname: str
81+
:param filters: Filter IDs for which the photometry is selected. All available
82+
photometry of the object is selected if set to None.
83+
:type filters: tuple(str, )
84+
:param spectrum: Calibration spectrum.
85+
:type spectrum: str
86+
:param bounds: Range of the scaling parameter (min, max).
87+
:type bounds: tuple(float, float)
88+
89+
:return: None
90+
'''
91+
92+
self.object = read_object.ReadObject(objname)
93+
94+
self.spectrum = spectrum
95+
self.bounds = bounds
96+
97+
self.objphot = []
98+
self.specphot = []
99+
100+
if filters is None:
101+
species_db = database.Database()
102+
objectbox = species_db.get_object(objname, None)
103+
filters = objectbox.filter
104+
105+
for item in filters:
106+
readcalib = read_calibration.ReadCalibration(self.spectrum, item)
107+
calibspec = readcalib.get_spectrum()
108+
109+
synphot = photometry.SyntheticPhotometry(item)
110+
spec_phot = synphot.spectrum_to_photometry(calibspec.wavelength, calibspec.flux)
111+
self.specphot.append(spec_phot)
112+
113+
obj_phot = self.object.get_photometry(item)
114+
self.objphot.append((obj_phot[2], obj_phot[3]))
115+
116+
self.modelpar = ['scaling']
117+
118+
def run_mcmc(self,
119+
nwalkers,
120+
nsteps,
121+
guess,
122+
tag):
123+
'''
124+
:param nwalkers: Number of walkers.
125+
:type nwalkers: int
126+
:param nsteps: Number of steps for each walker.
127+
:type nsteps: int
128+
:param guess: Guess of the scaling factor.
129+
:type guess: float
130+
:param tag: Database tag for the results.
131+
:type tag: int
132+
133+
:return: None
134+
'''
135+
136+
global MIN_CHISQ
137+
global MIN_PARAM
138+
139+
sys.stdout.write('Running MCMC...')
140+
sys.stdout.flush()
141+
142+
ndim = 1
143+
144+
initial = np.zeros((nwalkers, ndim))
145+
initial[:, 0] = guess + np.random.normal(0, 1e-3*guess, nwalkers)
146+
147+
sampler = emcee.EnsembleSampler(nwalkers=nwalkers,
148+
dim=ndim,
149+
lnpostfn=lnprob,
150+
a=2.,
151+
args=([self.bounds,
152+
self.objphot,
153+
self.specphot]))
154+
155+
progbar = progress.bar.Bar('\rRunning MCMC...',
156+
max=nsteps,
157+
suffix='%(percent)d%%')
158+
159+
for i, _ in enumerate(sampler.sample(initial, iterations=nsteps)):
160+
progbar.next()
161+
162+
progbar.finish()
163+
164+
species_db = database.Database()
165+
166+
species_db.add_samples(sampler=sampler,
167+
spectrum=('calibration', self.spectrum),
168+
tag=tag,
169+
chisquare=(MIN_CHISQ, MIN_PARAM),
170+
modelpar=self.modelpar,
171+
distance=None)

0 commit comments

Comments
 (0)
Please sign in to comment.