forked from Starfish-develop/Starfish
-
Notifications
You must be signed in to change notification settings - Fork 0
/
star.py
executable file
·225 lines (165 loc) · 7.12 KB
/
star.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
#!/usr/bin/env python
# All of the argument parsing is done in the `parallel.py` module.
import numpy as np
import Starfish
from Starfish import parallel
from Starfish.parallel import args
from Starfish.model import ThetaParam, PhiParam
print("THIS IS WORKING")
if args.generate:
model = parallel.OptimizeTheta(debug=True)
# Now that the different processes have been forked, initialize them
pconns, cconns, ps = parallel.initialize(model)
pars = ThetaParam.from_dict(Starfish.config["Theta"])
for ((spectrum_id, order_id), pconn) in pconns.items():
#Parse the parameters into what needs to be sent to each Model here.
pconn.send(("LNPROB", pars))
pconn.recv() # Receive and discard the answer so we can send the save
pconn.send(("SAVE", None))
# Kill all of the orders
for pconn in pconns.values():
pconn.send(("FINISH", None))
pconn.send(("DIE", None))
# Join on everything and terminate
for p in ps.values():
p.join()
p.terminate()
import sys;sys.exit()
if args.optimize == "Theta":
# Check to see if the order JSONs exist, if so, then recreate the noise structure according to these.
# Otherwise assume white noise.
model = parallel.OptimizeTheta(debug=True)
# Now that the different processes have been forked, initialize them
pconns, cconns, ps = parallel.initialize(model)
def fprob(p):
# Assume p is [temp, logg, Z, vz, vsini, logOmega]
pars = ThetaParam(grid=p[0:3], vz=p[3], vsini=p[4], logOmega=p[5])
#Distribute the calculation to each process
for ((spectrum_id, order_id), pconn) in pconns.items():
#Parse the parameters into what needs to be sent to each Model here.
pconn.send(("LNPROB", pars))
#Collect the answer from each process
lnps = np.empty((len(Starfish.data["orders"]),))
for i, pconn in enumerate(pconns.values()):
lnps[i] = pconn.recv()
s = np.sum(lnps)
print(pars, "lnp:", s)
if s == -np.inf:
return 1e99
else:
return -s
start = Starfish.config["Theta"]
p0 = np.array(start["grid"] + [start["vz"], start["vsini"], start["logOmega"]])
from scipy.optimize import fmin
p = fmin(fprob, p0, maxiter=10000, maxfun=10000)
print(p)
pars = ThetaParam(grid=p[0:3], vz=p[3], vsini=p[4], logOmega=p[5])
pars.save()
# Kill all of the orders
for pconn in pconns.values():
pconn.send(("FINISH", None))
pconn.send(("DIE", None))
# Join on everything and terminate
for p in ps.values():
p.join()
p.terminate()
import sys;sys.exit()
if args.initPhi:
# Figure out how many models and orders we have
i_last = len(Starfish.data["orders"]) - 1
for spec_id in range(len(Starfish.data["files"])):
for i, order in enumerate(Starfish.data["orders"]):
fix_c0 = True if i==i_last else False
if fix_c0:
cheb = np.zeros((Starfish.config["cheb_degree"] - 1,))
else:
cheb = np.zeros((Starfish.config["cheb_degree"],))
# For each order, create a Phi with these values
# Automatically reads all of the Phi parameters from config.yaml
phi = PhiParam(spectrum_id=spec_id, order=int(order), fix_c0=fix_c0, cheb=cheb)
# Write to CWD using predetermined format string
phi.save()
if args.optimize == "Cheb":
model = parallel.OptimizeCheb(debug=True)
# Now that the different processes have been forked, initialize them
pconns, cconns, ps = parallel.initialize(model)
# Initialize to the basics
pars = ThetaParam.from_dict(Starfish.config["Theta"])
#Distribute the calculation to each process
for ((spectrum_id, order_id), pconn) in pconns.items():
#Parse the parameters into what needs to be sent to each Model here.
pconn.send(("LNPROB", pars))
pconn.recv() # Receive and discard the answer so we can send the optimize
pconn.send(("OPTIMIZE_CHEB", None))
# Kill all of the orders
for pconn in pconns.values():
pconn.send(("FINISH", None))
pconn.send(("DIE", None))
# Join on everything and terminate
for p in ps.values():
p.join()
p.terminate()
import sys;sys.exit()
if args.sample == "ThetaCheb" or args.sample == "ThetaPhi" or args.sample == "ThetaPhiLines":
if args.sample == "ThetaCheb":
model = parallel.SampleThetaCheb(debug=True)
if args.sample == "ThetaPhi":
model = parallel.SampleThetaPhi(debug=True)
if args.sample == "ThetaPhiLines":
model = parallel.SampleThetaPhiLines(debug=True)
pconns, cconns, ps = parallel.initialize(model)
# These functions store the variables pconns, cconns, ps.
def lnprob(p):
pars = ThetaParam(grid=p[0:3], vz=p[3], vsini=p[4], logOmega=p[5])
#Distribute the calculation to each process
for ((spectrum_id, order_id), pconn) in pconns.items():
pconn.send(("LNPROB", pars))
#Collect the answer from each process
lnps = np.empty((len(Starfish.data["orders"]),))
for i, pconn in enumerate(pconns.values()):
lnps[i] = pconn.recv()
result = np.sum(lnps) # + lnprior
print("proposed:", p, result)
return result
def query_lnprob():
for ((spectrum_id, order_id), pconn) in pconns.items():
pconn.send(("GET_LNPROB", None))
#Collect the answer from each process
lnps = np.empty((len(Starfish.data["orders"]),))
for i, pconn in enumerate(pconns.values()):
lnps[i] = pconn.recv()
result = np.sum(lnps) # + lnprior
print("queried:", result)
return result
def acceptfn():
print("Calling acceptfn")
for ((spectrum_id, order_id), pconn) in pconns.items():
pconn.send(("DECIDE", True))
def rejectfn():
print("Calling rejectfn")
for ((spectrum_id, order_id), pconn) in pconns.items():
pconn.send(("DECIDE", False))
from Starfish.samplers import StateSampler
start = Starfish.config["Theta"]
p0 = np.array(start["grid"] + [start["vz"], start["vsini"], start["logOmega"]])
jump = Starfish.config["Theta_jump"]
cov = np.diag(np.array(jump["grid"] + [jump["vz"], jump["vsini"], jump["logOmega"]])**2)
if args.use_cov:
try:
cov = np.load('opt_jump.npy')
print("Found a local optimal jump matrix.")
except FileNotFoundError:
print("No optimal jump matrix found, using diagonal jump matrix.")
sampler = StateSampler(lnprob, p0, cov, query_lnprob=query_lnprob, acceptfn=acceptfn, rejectfn=rejectfn, debug=True, outdir=Starfish.routdir)
p, lnprob, state = sampler.run_mcmc(p0, N=args.samples, incremental_save=args.incremental_save)
print("Final", p)
sampler.write()
# Kill all of the orders
for pconn in pconns.values():
pconn.send(("FINISH", None))
pconn.send(("DIE", None))
# Join on everything and terminate
for p in ps.values():
p.join()
p.terminate()
import sys;sys.exit()