Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1import numpy as np 

2from lsst.sims.utils import (_hpid2RaDec, _raDec2Hpid, Site, calcLmstLast, 

3 m5_flat_sed, _approx_RaDec2AltAz, _angularSeparation) 

4import lsst.sims.skybrightness_pre as sb 

5import healpy as hp 

6from datetime import datetime 

7from lsst.sims.downtimeModel import ScheduledDowntimeData, UnscheduledDowntimeData 

8import lsst.sims.downtimeModel as downtimeModel 

9from lsst.sims.seeingModel import SeeingData, SeeingModel 

10from lsst.sims.cloudModel import CloudData 

11from lsst.sims.featureScheduler.features import Conditions 

12from lsst.sims.featureScheduler.utils import set_default_nside, approx_altaz2pa 

13from lsst.ts.observatory.model import ObservatoryModel, Target 

14from astropy.coordinates import EarthLocation 

15from astropy.time import Time 

16from lsst.sims.almanac import Almanac 

17import warnings 

18import matplotlib.pylab as plt 

19from lsst.ts.observatory.model import ObservatoryState 

20from importlib import import_module 

21 

22__all__ = ['Model_observatory'] 

23 

24 

25class ExtendedObservatoryModel(ObservatoryModel): 

26 """Add some functionality to ObservatoryModel 

27 """ 

28 

29 def expose(self, target): 

30 # Break out the exposure command from observe method 

31 visit_time = sum(target.exp_times) + \ 

32 target.num_exp * self.params.shuttertime + \ 

33 max(target.num_exp - 1, 0) * self.params.readouttime 

34 self.update_state(self.current_state.time + visit_time) 

35 

36 def observe_times(self, target): 

37 """observe a target, and return the slewtime and visit time for the action 

38 Note, slew and expose will update the current_state 

39 """ 

40 t1 = self.current_state.time + 0 

41 # Note, this slew assumes there is a readout that needs to be done. 

42 self.slew(target) 

43 t2 = self.current_state.time + 0 

44 self.expose(target) 

45 t3 = self.current_state.time + 0 

46 if not self.current_state.tracking: 

47 ValueError('Telescope model stopped tracking, that seems bad.') 

48 slewtime = t2 - t1 

49 visitime = t3 - t2 

50 return slewtime, visitime 

51 

52 # Adding wrap_padding to make azimuth slews more intelligent 

53 def get_closest_angle_distance(self, target_rad, current_abs_rad, 

54 min_abs_rad=None, max_abs_rad=None, 

55 wrap_padding=0.873): 

56 """Calculate the closest angular distance including handling \ 

57 cable wrap if necessary. 

58 

59 Parameters 

60 ---------- 

61 target_rad : float 

62 The destination angle (radians). 

63 current_abs_rad : float 

64 The current angle (radians). 

65 min_abs_rad : float, optional 

66 The minimum constraint angle (radians). 

67 max_abs_rad : float, optional 

68 The maximum constraint angle (radians). 

69 wrap_padding : float (0.873) 

70 The amount of padding to use to make sure we don't track into limits (radians). 

71 

72 

73 Returns 

74 ------- 

75 tuple(float, float) 

76 (accumulated angle in radians, distance angle in radians) 

77 """ 

78 # if there are wrap limits, normalizes the target angle 

79 TWOPI = 2 * np.pi 

80 if min_abs_rad is not None: 

81 norm_target_rad = divmod(target_rad - min_abs_rad, TWOPI)[1] + min_abs_rad 

82 if max_abs_rad is not None: 

83 # if the target angle is unreachable 

84 # then sets an arbitrary value 

85 if norm_target_rad > max_abs_rad: 

86 norm_target_rad = max(min_abs_rad, norm_target_rad - np.pi) 

87 else: 

88 norm_target_rad = target_rad 

89 

90 # computes the distance clockwise 

91 distance_rad = divmod(norm_target_rad - current_abs_rad, TWOPI)[1] 

92 

93 # take the counter-clockwise distance if shorter 

94 if distance_rad > np.pi: 

95 distance_rad = distance_rad - TWOPI 

96 

97 # if there are wrap limits 

98 if (min_abs_rad is not None) and (max_abs_rad is not None): 

99 # compute accumulated angle 

100 accum_abs_rad = current_abs_rad + distance_rad 

101 

102 # if limits reached chose the other direction 

103 if accum_abs_rad > max_abs_rad - wrap_padding: 

104 distance_rad = distance_rad - TWOPI 

105 if accum_abs_rad < min_abs_rad + wrap_padding: 

106 distance_rad = distance_rad + TWOPI 

107 

108 # compute final accumulated angle 

109 final_abs_rad = current_abs_rad + distance_rad 

110 

111 return (final_abs_rad, distance_rad) 

112 

113 # Put in wrap padding kwarg so it's not used on camera rotation. 

114 def get_closest_state(self, targetposition, istracking=False): 

115 """Find the closest observatory state for the given target position. 

116 

117 Parameters 

118 ---------- 

119 targetposition : :class:`.ObservatoryPosition` 

120 A target position instance. 

121 istracking : bool, optional 

122 Flag for saying if the observatory is tracking. Default is False. 

123 

124 Returns 

125 ------- 

126 :class:`.ObservatoryState` 

127 The state that is closest to the current observatory state. 

128 

129 Binary schema 

130 ------------- 

131 The binary schema used to determine the state of a proposed target. A 

132 value of 1 indicates that is it failing. A value of 0 indicates that the 

133 state is passing. 

134 ___ ___ ___ ___ ___ ___ 

135 | | | | | | 

136 rot rot az az alt alt 

137 max min max min max min 

138 

139 For example, if a proposed target exceeds the rotators maximum value, 

140 and is below the minimum azimuth we would have a binary value of; 

141 

142 0 1 0 1 0 0 

143 

144 If the target passed, then no limitations would occur; 

145 

146 0 0 0 0 0 0 

147 """ 

148 TWOPI = 2 * np.pi 

149 

150 valid_state = True 

151 fail_record = self.current_state.fail_record 

152 self.current_state.fail_state = 0 

153 

154 if targetposition.alt_rad < self.params.telalt_minpos_rad: 

155 telalt_rad = self.params.telalt_minpos_rad 

156 domalt_rad = self.params.telalt_minpos_rad 

157 valid_state = False 

158 

159 if "telalt_minpos_rad" in fail_record: 

160 fail_record["telalt_minpos_rad"] += 1 

161 else: 

162 fail_record["telalt_minpos_rad"] = 1 

163 

164 self.current_state.fail_state = self.current_state.fail_state | \ 

165 self.current_state.fail_value_table["altEmin"] 

166 

167 elif targetposition.alt_rad > self.params.telalt_maxpos_rad: 

168 telalt_rad = self.params.telalt_maxpos_rad 

169 domalt_rad = self.params.telalt_maxpos_rad 

170 valid_state = False 

171 if "telalt_maxpos_rad" in fail_record: 

172 fail_record["telalt_maxpos_rad"] += 1 

173 else: 

174 fail_record["telalt_maxpos_rad"] = 1 

175 

176 self.current_state.fail_state = self.current_state.fail_state | \ 

177 self.current_state.fail_value_table["altEmax"] 

178 

179 else: 

180 telalt_rad = targetposition.alt_rad 

181 domalt_rad = targetposition.alt_rad 

182 

183 if istracking: 

184 (telaz_rad, delta) = self.get_closest_angle_distance(targetposition.az_rad, 

185 self.current_state.telaz_rad) 

186 if telaz_rad < self.params.telaz_minpos_rad: 

187 telaz_rad = self.params.telaz_minpos_rad 

188 valid_state = False 

189 if "telaz_minpos_rad" in fail_record: 

190 fail_record["telaz_minpos_rad"] += 1 

191 else: 

192 fail_record["telaz_minpos_rad"] = 1 

193 

194 self.current_state.fail_state = self.current_state.fail_state | \ 

195 self.current_state.fail_value_table["azEmin"] 

196 

197 elif telaz_rad > self.params.telaz_maxpos_rad: 

198 telaz_rad = self.params.telaz_maxpos_rad 

199 valid_state = False 

200 if "telaz_maxpos_rad" in fail_record: 

201 fail_record["telaz_maxpos_rad"] += 1 

202 else: 

203 fail_record["telaz_maxpos_rad"] = 1 

204 

205 self.current_state.fail_state = self.current_state.fail_state | \ 

206 self.current_state.fail_value_table["azEmax"] 

207 

208 else: 

209 (telaz_rad, delta) = self.get_closest_angle_distance(targetposition.az_rad, 

210 self.current_state.telaz_rad, 

211 self.params.telaz_minpos_rad, 

212 self.params.telaz_maxpos_rad) 

213 

214 (domaz_rad, delta) = self.get_closest_angle_distance(targetposition.az_rad, 

215 self.current_state.domaz_rad) 

216 

217 if istracking: 

218 (telrot_rad, delta) = self.get_closest_angle_distance(targetposition.rot_rad, 

219 self.current_state.telrot_rad, 

220 wrap_padding=0.) 

221 if telrot_rad < self.params.telrot_minpos_rad: 

222 telrot_rad = self.params.telrot_minpos_rad 

223 valid_state = False 

224 if "telrot_minpos_rad" in fail_record: 

225 fail_record["telrot_minpos_rad"] += 1 

226 else: 

227 fail_record["telrot_minpos_rad"] = 1 

228 

229 self.current_state.fail_state = self.current_state.fail_state | \ 

230 self.current_state.fail_value_table["rotEmin"] 

231 

232 elif telrot_rad > self.params.telrot_maxpos_rad: 

233 telrot_rad = self.params.telrot_maxpos_rad 

234 valid_state = False 

235 if "telrot_maxpos_rad" in fail_record: 

236 fail_record["telrot_maxpos_rad"] += 1 

237 else: 

238 fail_record["telrot_maxpos_rad"] = 1 

239 

240 self.current_state.fail_state = self.current_state.fail_state | \ 

241 self.current_state.fail_value_table["rotEmax"] 

242 else: 

243 # if the target rotator angle is unreachable 

244 # then sets an arbitrary value (opposite) 

245 norm_rot_rad = divmod(targetposition.rot_rad - self.params.telrot_minpos_rad, TWOPI)[1] \ 

246 + self.params.telrot_minpos_rad 

247 if norm_rot_rad > self.params.telrot_maxpos_rad: 

248 targetposition.rot_rad = norm_rot_rad - np.pi 

249 (telrot_rad, delta) = self.get_closest_angle_distance(targetposition.rot_rad, 

250 self.current_state.telrot_rad, 

251 self.params.telrot_minpos_rad, 

252 self.params.telrot_maxpos_rad, 

253 wrap_padding=0.) 

254 targetposition.ang_rad = divmod(targetposition.pa_rad - telrot_rad, TWOPI)[1] 

255 

256 targetstate = ObservatoryState() 

257 targetstate.set_position(targetposition) 

258 targetstate.telalt_rad = telalt_rad 

259 targetstate.telaz_rad = telaz_rad 

260 targetstate.telrot_rad = telrot_rad 

261 targetstate.domalt_rad = domalt_rad 

262 targetstate.domaz_rad = domaz_rad 

263 if istracking: 

264 targetstate.tracking = valid_state 

265 

266 self.current_state.fail_record = fail_record 

267 

268 return targetstate 

269 

270 

271class Model_observatory(object): 

272 """A class to generate a realistic telemetry stream for the scheduler 

273 """ 

274 

275 def __init__(self, nside=None, mjd_start=59853.5, seed=42, quickTest=True, 

276 alt_min=5., lax_dome=True, cloud_limit=0.3, sim_ToO=None, 

277 seeing_db=None): 

278 """ 

279 Parameters 

280 ---------- 

281 nside : int (None) 

282 The healpix nside resolution 

283 mjd_start : float (59853.5) 

284 The MJD to start the observatory up at 

285 alt_min : float (5.) 

286 The minimum altitude to compute models at (degrees). 

287 lax_dome : bool (True) 

288 Passed to observatory model. If true, allows dome creep. 

289 cloud_limit : float (0.3) 

290 The limit to stop taking observations if the cloud model returns something equal or higher 

291 sim_ToO : sim_targetoO object (None) 

292 If one would like to inject simulated ToOs into the telemetry stream. 

293 seeing_db : filename of the seeing data database (None) 

294 If one would like to use an alternate seeing database 

295 """ 

296 

297 if nside is None: 

298 nside = set_default_nside() 

299 self.nside = nside 

300 

301 self.cloud_limit = cloud_limit 

302 

303 self.alt_min = np.radians(alt_min) 

304 self.lax_dome = lax_dome 

305 

306 self.mjd_start = mjd_start 

307 

308 # Conditions object to update and return on request 

309 self.conditions = Conditions(nside=self.nside) 

310 

311 self.sim_ToO = sim_ToO 

312 

313 # Create an astropy location 

314 self.site = Site('LSST') 

315 self.location = EarthLocation(lat=self.site.latitude, lon=self.site.longitude, 

316 height=self.site.height) 

317 

318 # Load up all the models we need 

319 

320 mjd_start_time = Time(self.mjd_start, format='mjd') 

321 # Downtime 

322 self.down_nights = [] 

323 self.sched_downtime_data = ScheduledDowntimeData(mjd_start_time) 

324 self.unsched_downtime_data = UnscheduledDowntimeData(mjd_start_time) 

325 

326 sched_downtimes = self.sched_downtime_data() 

327 unsched_downtimes = self.unsched_downtime_data() 

328 

329 down_starts = [] 

330 down_ends = [] 

331 for dt in sched_downtimes: 

332 down_starts.append(dt['start'].mjd) 

333 down_ends.append(dt['end'].mjd) 

334 for dt in unsched_downtimes: 

335 down_starts.append(dt['start'].mjd) 

336 down_ends.append(dt['end'].mjd) 

337 

338 self.downtimes = np.array(list(zip(down_starts, down_ends)), dtype=list(zip(['start', 'end'], [float, float]))) 

339 self.downtimes.sort(order='start') 

340 

341 # Make sure there aren't any overlapping downtimes 

342 diff = self.downtimes['start'][1:] - self.downtimes['end'][0:-1] 

343 while np.min(diff) < 0: 

344 # Should be able to do this wihtout a loop, but this works 

345 for i, dt in enumerate(self.downtimes[0:-1]): 

346 if self.downtimes['start'][i+1] < dt['end']: 

347 new_end = np.max([dt['end'], self.downtimes['end'][i+1]]) 

348 self.downtimes[i]['end'] = new_end 

349 self.downtimes[i+1]['end'] = new_end 

350 

351 good = np.where(self.downtimes['end'] - np.roll(self.downtimes['end'], 1) != 0) 

352 self.downtimes = self.downtimes[good] 

353 diff = self.downtimes['start'][1:] - self.downtimes['end'][0:-1] 

354 

355 self.seeing_data = SeeingData(mjd_start_time, seeing_db=seeing_db) 

356 self.seeing_model = SeeingModel() 

357 self.seeing_indx_dict = {} 

358 for i, filtername in enumerate(self.seeing_model.filter_list): 

359 self.seeing_indx_dict[filtername] = i 

360 

361 self.cloud_data = CloudData(mjd_start_time, offset_year=0) 

362 

363 self.sky_model = sb.SkyModelPre(speedLoad=quickTest) 

364 

365 self.observatory = ExtendedObservatoryModel() 

366 self.observatory.configure_from_module() 

367 # Make it so it respects my requested rotator angles 

368 self.observatory.params.rotator_followsky = True 

369 

370 self.filterlist = ['u', 'g', 'r', 'i', 'z', 'y'] 

371 self.seeing_FWHMeff = {} 

372 for key in self.filterlist: 

373 self.seeing_FWHMeff[key] = np.zeros(hp.nside2npix(self.nside), dtype=float) 

374 

375 self.almanac = Almanac(mjd_start=mjd_start) 

376 

377 # Let's make sure we're at an openable MJD 

378 good_mjd = False 

379 to_set_mjd = mjd_start 

380 while not good_mjd: 

381 good_mjd, to_set_mjd = self.check_mjd(to_set_mjd) 

382 self.mjd = to_set_mjd 

383 

384 self.obsID_counter = 0 

385 

386 def get_info(self): 

387 """ 

388 Returns 

389 ------- 

390 Array with model versions that were instantiated 

391 """ 

392 

393 # The things we want to get info on 

394 models = {'cloud data': self.cloud_data, 'sky model': self.sky_model, 

395 'seeing data': self.seeing_data, 'seeing model': self.seeing_model, 

396 'observatory model': self.observatory, 

397 'sched downtime data': self.sched_downtime_data, 

398 'unched downtime data': self.unsched_downtime_data} 

399 

400 result = [] 

401 for model_name in models: 

402 try: 

403 module_name = models[model_name].__module__ 

404 module = import_module(module_name) 

405 ver = import_module(module.__package__+'.version') 

406 version = ver.__version__ 

407 fingerprint = ver.__fingerprint__ 

408 except: 

409 version = 'NA' 

410 fingerprint = 'NA' 

411 result.append([model_name+' version', version]) 

412 result.append([model_name+' fingerprint', fingerprint]) 

413 result.append([model_name+' module', models[model_name].__module__]) 

414 try: 

415 info = models[model_name].config_info() 

416 for key in info: 

417 result.append([key, str(info[key])]) 

418 except: 

419 result.append([model_name, 'no config_info']) 

420 

421 return result 

422 

423 def return_conditions(self): 

424 """ 

425 

426 Returns 

427 ------- 

428 lsst.sims.featureScheduler.features.conditions object 

429 """ 

430 

431 self.conditions.mjd = self.mjd 

432 

433 self.conditions.night = self.night 

434 # Current time as astropy time 

435 current_time = Time(self.mjd, format='mjd') 

436 

437 # Clouds. XXX--just the raw value 

438 self.conditions.bulk_cloud = self.cloud_data(current_time) 

439 

440 # use conditions object itself to get aprox altitude of each healpx 

441 alts = self.conditions.alt 

442 azs = self.conditions.az 

443 

444 good = np.where(alts > self.alt_min) 

445 

446 # Compute the airmass at each heapix 

447 airmass = np.zeros(alts.size, dtype=float) 

448 airmass.fill(np.nan) 

449 airmass[good] = 1./np.cos(np.pi/2. - alts[good]) 

450 self.conditions.airmass = airmass 

451 

452 # reset the seeing 

453 for key in self.seeing_FWHMeff: 

454 self.seeing_FWHMeff[key].fill(np.nan) 

455 # Use the model to get the seeing at this time and airmasses. 

456 FWHM_500 = self.seeing_data(current_time) 

457 seeing_dict = self.seeing_model(FWHM_500, airmass[good]) 

458 fwhm_eff = seeing_dict['fwhmEff'] 

459 for i, key in enumerate(self.seeing_model.filter_list): 

460 self.seeing_FWHMeff[key][good] = fwhm_eff[i, :] 

461 self.conditions.FWHMeff = self.seeing_FWHMeff 

462 

463 # sky brightness 

464 self.conditions.skybrightness = self.sky_model.returnMags(self.mjd, airmass_mask=False, 

465 planet_mask=False, 

466 moon_mask=False, zenith_mask=False) 

467 

468 self.conditions.mounted_filters = self.observatory.current_state.mountedfilters 

469 self.conditions.current_filter = self.observatory.current_state.filter[0] 

470 

471 # Compute the slewtimes 

472 slewtimes = np.empty(alts.size, dtype=float) 

473 slewtimes.fill(np.nan) 

474 slewtimes[good] = self.observatory.get_approximate_slew_delay(alts[good], azs[good], 

475 self.observatory.current_state.filter, 

476 lax_dome=self.lax_dome) 

477 # Mask out anything the slewtime says is out of bounds 

478 slewtimes[np.where(slewtimes < 0)] = np.nan 

479 self.conditions.slewtime = slewtimes 

480 

481 # Let's get the sun and moon 

482 sun_moon_info = self.almanac.get_sun_moon_positions(self.mjd) 

483 # convert these to scalars 

484 for key in sun_moon_info: 

485 sun_moon_info[key] = sun_moon_info[key].max() 

486 self.conditions.moonPhase = sun_moon_info['moon_phase'] 

487 

488 self.conditions.moonAlt = sun_moon_info['moon_alt'] 

489 self.conditions.moonAz = sun_moon_info['moon_az'] 

490 self.conditions.moonRA = sun_moon_info['moon_RA'] 

491 self.conditions.moonDec = sun_moon_info['moon_dec'] 

492 self.conditions.sunAlt = sun_moon_info['sun_alt'] 

493 self.conditions.sunRA = sun_moon_info['sun_RA'] 

494 self.conditions.sunDec = sun_moon_info['sun_dec'] 

495 

496 self.conditions.lmst, last = calcLmstLast(self.mjd, self.site.longitude_rad) 

497 

498 self.conditions.telRA = self.observatory.current_state.ra_rad 

499 self.conditions.telDec = self.observatory.current_state.dec_rad 

500 self.conditions.telAlt = self.observatory.current_state.alt_rad 

501 self.conditions.telAz = self.observatory.current_state.az_rad 

502 

503 self.conditions.rotTelPos = self.observatory.current_state.rot_rad 

504 

505 # Add in the almanac information 

506 self.conditions.night = self.night 

507 self.conditions.sunset = self.almanac.sunsets['sunset'][self.almanac_indx] 

508 self.conditions.sun_n12_setting = self.almanac.sunsets['sun_n12_setting'][self.almanac_indx] 

509 self.conditions.sun_n18_setting = self.almanac.sunsets['sun_n18_setting'][self.almanac_indx] 

510 self.conditions.sun_n18_rising = self.almanac.sunsets['sun_n18_rising'][self.almanac_indx] 

511 self.conditions.sun_n12_rising = self.almanac.sunsets['sun_n12_rising'][self.almanac_indx] 

512 self.conditions.sunrise = self.almanac.sunsets['sunrise'][self.almanac_indx] 

513 self.conditions.moonrise = self.almanac.sunsets['moonrise'][self.almanac_indx] 

514 self.conditions.moonset = self.almanac.sunsets['moonset'][self.almanac_indx] 

515 

516 # Planet positions from almanac 

517 self.conditions.planet_positions = self.almanac.get_planet_positions(self.mjd) 

518 

519 # See if there are any ToOs to include 

520 if self.sim_ToO is not None: 

521 toos = self.sim_ToO(self.mjd) 

522 if toos is not None: 

523 self.conditions.targets_of_opportunity = toos 

524 

525 return self.conditions 

526 

527 @property 

528 def mjd(self): 

529 return self._mjd 

530 

531 @mjd.setter 

532 def mjd(self, value): 

533 self._mjd = value 

534 self.almanac_indx = self.almanac.mjd_indx(value) 

535 self.night = self.almanac.sunsets['night'][self.almanac_indx] 

536 

537 def observation_add_data(self, observation): 

538 """ 

539 Fill in the metadata for a completed observation 

540 """ 

541 current_time = Time(self.mjd, format='mjd') 

542 

543 observation['clouds'] = self.cloud_data(current_time) 

544 observation['airmass'] = 1./np.cos(np.pi/2. - observation['alt']) 

545 # Seeing 

546 fwhm_500 = self.seeing_data(current_time) 

547 seeing_dict = self.seeing_model(fwhm_500, observation['airmass']) 

548 observation['FWHMeff'] = seeing_dict['fwhmEff'][self.seeing_indx_dict[observation['filter'][0]]] 

549 observation['FWHM_geometric'] = seeing_dict['fwhmGeom'][self.seeing_indx_dict[observation['filter'][0]]] 

550 observation['FWHM_500'] = fwhm_500 

551 

552 observation['night'] = self.night 

553 observation['mjd'] = self.mjd 

554 

555 hpid = _raDec2Hpid(self.sky_model.nside, observation['RA'], observation['dec']) 

556 observation['skybrightness'] = self.sky_model.returnMags(self.mjd, 

557 indx=[hpid], 

558 extrapolate=True)[observation['filter'][0]] 

559 

560 observation['fivesigmadepth'] = m5_flat_sed(observation['filter'][0], observation['skybrightness'], 

561 observation['FWHMeff'], observation['exptime'], 

562 observation['airmass']) 

563 

564 lmst, last = calcLmstLast(self.mjd, self.site.longitude_rad) 

565 observation['lmst'] = lmst 

566 

567 sun_moon_info = self.almanac.get_sun_moon_positions(self.mjd) 

568 observation['sunAlt'] = sun_moon_info['sun_alt'] 

569 observation['sunAz'] = sun_moon_info['sun_az'] 

570 observation['sunRA'] = sun_moon_info['sun_RA'] 

571 observation['sunDec'] = sun_moon_info['sun_dec'] 

572 observation['moonAlt'] = sun_moon_info['moon_alt'] 

573 observation['moonAz'] = sun_moon_info['moon_az'] 

574 observation['moonRA'] = sun_moon_info['moon_RA'] 

575 observation['moonDec'] = sun_moon_info['moon_dec'] 

576 observation['moonDist'] = _angularSeparation(observation['RA'], observation['dec'], 

577 observation['moonRA'], observation['moonDec']) 

578 observation['solarElong'] = _angularSeparation(observation['RA'], observation['dec'], 

579 observation['sunRA'], observation['sunDec']) 

580 observation['moonPhase'] = sun_moon_info['moon_phase'] 

581 

582 observation['ID'] = self.obsID_counter 

583 self.obsID_counter += 1 

584 

585 return observation 

586 

587 def check_up(self, mjd): 

588 """See if we are in downtime 

589 

590 True if telescope is up 

591 False if in downtime 

592 """ 

593 

594 result = True 

595 indx = np.searchsorted(self.downtimes['start'], mjd, side='right')-1 

596 if mjd < self.downtimes['end'][indx]: 

597 result = False 

598 return result 

599 

600 def check_mjd(self, mjd, cloud_skip=20.): 

601 """See if an mjd is ok to observe 

602 Parameters 

603 ---------- 

604 cloud_skip : float (20) 

605 How much time to skip ahead if it's cloudy (minutes) 

606 

607 

608 Returns 

609 ------- 

610 bool 

611 

612 mdj : float 

613 If True, the input mjd. If false, a good mjd to skip forward to. 

614 """ 

615 passed = True 

616 new_mjd = mjd + 0 

617 

618 # Maybe set this to a while loop to make sure we don't land on another cloudy time? 

619 # or just make this an entire recursive call? 

620 clouds = self.cloud_data(Time(mjd, format='mjd')) 

621 if clouds > self.cloud_limit: 

622 passed = False 

623 while clouds > self.cloud_limit: 

624 new_mjd = new_mjd + cloud_skip/60./24. 

625 clouds = self.cloud_data(Time(new_mjd, format='mjd')) 

626 alm_indx = np.searchsorted(self.almanac.sunsets['sunset'], mjd) - 1 

627 # at the end of the night, advance to the next setting twilight 

628 if mjd > self.almanac.sunsets['sun_n12_rising'][alm_indx]: 

629 passed = False 

630 new_mjd = self.almanac.sunsets['sun_n12_setting'][alm_indx+1] 

631 if mjd < self.almanac.sunsets['sun_n12_setting'][alm_indx]: 

632 passed = False 

633 new_mjd = self.almanac.sunsets['sun_n12_setting'][alm_indx+1] 

634 # We're in a down night, advance to next night 

635 if not self.check_up(mjd): 

636 passed = False 

637 new_mjd = self.almanac.sunsets['sun_n12_setting'][alm_indx+1] 

638 # recursive call to make sure we skip far enough ahead 

639 if not passed: 

640 while not passed: 

641 passed, new_mjd = self.check_mjd(new_mjd) 

642 return False, new_mjd 

643 else: 

644 return True, mjd 

645 

646 def _update_rotSkyPos(self, observation): 

647 """If we have an undefined rotSkyPos, try to fill it out. 

648 """ 

649 alt, az = _approx_RaDec2AltAz(observation['RA'], observation['dec'], self.site.latitude_rad, 

650 self.site.longitude_rad, self.mjd) 

651 obs_pa = approx_altaz2pa(alt, az, self.site.latitude_rad) 

652 observation['rotSkyPos'] = (obs_pa + observation['rotTelPos']) % (2*np.pi) 

653 observation['rotTelPos'] = 0. 

654 

655 return observation 

656 

657 def observe(self, observation): 

658 """Try to make an observation 

659 

660 Returns 

661 ------- 

662 observation : observation object 

663 None if there was no observation taken. Completed observation with meta data filled in. 

664 new_night : bool 

665 Have we started a new night. 

666 """ 

667 

668 start_night = self.night.copy() 

669 

670 # Make sure the kinematic model is set to the correct mjd 

671 t = Time(self.mjd, format='mjd') 

672 self.observatory.update_state(t.unix) 

673 

674 if np.isnan(observation['rotSkyPos']): 

675 observation = self._update_rotSkyPos(observation) 

676 

677 target = Target(band_filter=observation['filter'], ra_rad=observation['RA'], 

678 dec_rad=observation['dec'], ang_rad=observation['rotSkyPos'], 

679 num_exp=observation['nexp'], exp_times=[observation['exptime']]) 

680 start_ra = self.observatory.current_state.ra_rad 

681 start_dec = self.observatory.current_state.dec_rad 

682 slewtime, visittime = self.observatory.observe_times(target) 

683 

684 # Check if the mjd after slewtime and visitime is fine: 

685 observation_worked, new_mjd = self.check_mjd(self.mjd + (slewtime + visittime)/24./3600.) 

686 if observation_worked: 

687 observation['visittime'] = visittime 

688 observation['slewtime'] = slewtime 

689 observation['slewdist'] = _angularSeparation(start_ra, start_dec, 

690 self.observatory.current_state.ra_rad, 

691 self.observatory.current_state.dec_rad) 

692 self.mjd = self.mjd + slewtime/24./3600. 

693 # Reach into the observatory model to pull out the relevant data it has calculated 

694 # Note, this might be after the observation has been completed. 

695 observation['alt'] = self.observatory.current_state.alt_rad 

696 observation['az'] = self.observatory.current_state.az_rad 

697 observation['pa'] = self.observatory.current_state.pa_rad 

698 observation['rotTelPos'] = self.observatory.current_state.rot_rad 

699 observation['rotSkyPos'] = self.observatory.current_state.ang_rad 

700 

701 # Metadata on observation is after slew and settle, so at start of exposure. 

702 result = self.observation_add_data(observation) 

703 self.mjd = self.mjd + visittime/24./3600. 

704 new_night = False 

705 else: 

706 result = None 

707 self.observatory.park() 

708 # Skip to next legitimate mjd 

709 self.mjd = new_mjd 

710 now_night = self.night 

711 if now_night == start_night: 

712 new_night = False 

713 else: 

714 new_night = True 

715 

716 return result, new_night