def worldAt(self, *pixel): if not self._findWCS(): return Position.fromRaDec(0, 0) world = self._valueAt(self._wcs.wcs_pix2world, *pixel) return Position.fromRaDec(Coord.fromD(world[0]), Coord.fromD(world[1]))
def getOffset(self, position): ret = {"X": 0.0, "Y": 0.0, "N": 0.0, "E": 0.0, "Status": self.state()} try: frame = self._takeImage() fname = "/tmp/autoguider.fits" if os.path.exists(fname): os.remove(fname) frame.save(fname) img = fits.getdata(fname) # Extract some backgroud img -= np.mean(img) * 0.9 img[img < 0] = 0.0 pY, pX = centroid(img) ret["X"] = pX - position["XWIN_IMAGE"] ret["Y"] = pY - position["YWIN_IMAGE"] centerPos = frame.worldAt([position["XWIN_IMAGE"], position["YWIN_IMAGE"]]) currPos = frame.worldAt([pX, pY]) # offset = centerPos.angsep(currPos) ret["E"] = Coord.fromAS((centerPos.ra.AS - currPos.ra.AS) * np.cos(currPos.dec.R)) ret["N"] = Coord.fromAS(centerPos.dec.AS - currPos.dec.AS) except: if self.abort.isSet(): ret["Status"] = GuiderStatus.ABORTED return ret else: raise self.plot(frame, position, ret) return ret
def syncWithTel(self): self.syncBegin() self.log.debug('[sync] Check if dome is in sync with telescope') if self.getMode() == Mode.Track: self.log.warning('Dome is in track mode... Slew is completely controled by AsTelOS...' 'Waiting for dome to reach expected position') start_time = time.time() tpl = self.getTPL() ref_altitude = Coord.fromD(0.) target_az = Coord.fromD(tpl.getobject('POSITION.INSTRUMENTAL.DOME[0].TARGETPOS')) target_position = Position.fromAltAz(ref_altitude, target_az) while True: current_az = self.getAz() current_position = Position.fromAltAz(ref_altitude, current_az) self.log.debug('Current az: %s | Target az: %s' % (current_az.toDMS(), target_az.toDMS())) if time.time() > (start_time + self._maxSlewTime): if abs(target_position.angsep(current_position).D) < tpl.getobject( 'POINTING.SETUP.DOME.MAX_DEVIATION') * 4.0: self.log.warning("[sync] Dome too far from target position!") break else: self.syncComplete() raise AstelcoDomeException("Dome synchronization timed-out") elif abs(target_position.angsep(current_position).D) < tpl.getobject( 'POINTING.SETUP.DOME.MAX_DEVIATION') * 2.0: break self.syncComplete() self.log.debug('[sync] Dome in sync')
def find (self, near=None, limit=9999, **conditions): self.useCat("II/183A/") if conditions.get("closest", False): limit = 1 self.useColumns("*POS_EQ_RA_MAIN,*POS_EQ_DEC_MAIN,*ID_MAIN,Vmag,_r", sortBy="_r") else: self.useColumns("*POS_EQ_RA_MAIN,*POS_EQ_DEC_MAIN,*ID_MAIN,Vmag,_r", sortBy="*POS_EQ_RA_MAIN") if near: self.useTarget(near, radius=conditions.get("radius", 45)) x = super(Landolt,self).find(limit) for i in x: RA = i.pop("*POS_EQ_RA_MAIN") i["RA"] = Coord.fromHMS(str(RA)) DEC = i.pop("*POS_EQ_DEC_MAIN") i["DEC"] = Coord.fromDMS(str(DEC)) ID = i.pop("*ID_MAIN") i["ID"] = str(ID) V = i.pop("Vmag") i["V"] = str(V) i.pop("_r") return x
def __init__(self): TelescopeBase.__init__(self) self.__slewing = False self._az = Coord.fromDMS(0) self._alt = Coord.fromDMS(70) self._slewing = False self._tracking = True self._parked = False self._abort = threading.Event() self._epoch = Epoch.J2000 self._cover = False self._pierside = TelescopePierSide.UNKNOWN try: self._site = self.getManager().getProxy("/Site/0") self._gotSite = True except: self._site = Site() self._gotSite = False self._setRaDecFromAltAz()
def _valueAt(self, fn, *coords): """ Accepts a function callback and variable coords. If len(coords) == 1 convert (from tuple or Position) to decimal degress. If len(coords) == 2, convert (from number or Coord) to decimal degress """ assert len(coords) >= 1 assert self._wcs is not None if len(coords) == 2: c1 = Coord.fromH(coords[0]).D c2 = Coord.fromD(coords[1]).D else: if isinstance(coords[0], Position): c1, c2 = coords[0].dd() else: # assumes as tuple c1, c2 = coords[0] value = fn(N.array([[c1, c2]]), 1) if len(value) >= 1: return tuple(value[0]) else: raise WCSNotFoundException("Couldn't convert coordinates.")
def _moveScope(self, tracking=False, pierSide=None): """ Moves the scope, usually to zenith """ tel = self._getTel() site = self._getSite() self.log.debug('Moving scope to alt %s az %s.' % (self["flat_alt"], self["flat_az"])) if tel.getPositionAltAz().angsep( Position.fromAltAz(Coord.fromD(self["flat_alt"]), Coord.fromD(self["flat_az"]))).D < self[ "flat_position_max"]: self.log.debug( 'Telescope is less than {} degrees from flat position. Not moving!'.format(self["flat_position_max"])) if tracking and not tel.isTracking(): tel.startTracking() elif not tracking and tel.isTracking(): tel.stopTracking() if pierSide is not None and tel.features(TelescopePier): self.log.debug("Setting telescope pier side to %s." % tel.getPierSide().__str__().lower()) tel.setSideOfPier(self['pier_side']) return try: self.log.debug("Skyflat Slewing scope to alt {} az {}".format(self["flat_alt"], self["flat_az"])) tel.slewToRaDec(Position.altAzToRaDec(Position.fromAltAz(Coord.fromD(self["flat_alt"]), Coord.fromD(self["flat_az"])), site['latitude'], site.LST())) if tracking: self._startTracking() else: self._stopTracking() except: self.log.debug("Error moving the telescope")
def test_distances(self): p1 = Position.fromRaDec("10:00:00", "0:0:0") p2 = Position.fromRaDec("12:00:00", "0:0:0") d = p1.angsep(p2) assert p1.within(p2, Coord.fromD(29.99)) == False assert p1.within(p2, Coord.fromD(30.01)) == True
def raDecToAltAz(raDec, latitude, lst): decR = CoordUtil.coordToR(raDec.dec) latR = CoordUtil.coordToR(latitude) ha = CoordUtil.raToHa(raDec.ra, lst) haR = CoordUtil.coordToR(ha) altR,azR = CoordUtil.coordRotate(decR, latR, haR) return Position.fromAltAz(Coord.fromR(CoordUtil.makeValid180to180(altR)), Coord.fromR(CoordUtil.makeValid0to360(azR)))
def __init__(self, buffer): # discard time buffer.recv(8) self.ra = struct.unpack("<1I", buffer.recv(4))[0] self.ra *= (math.pi / 0x80000000) self.ra = Coord.fromR(self.ra).toHMS() self.dec = struct.unpack("<1i", buffer.recv(4))[0] self.dec *= (math.pi / 0x80000000) self.dec = Coord.fromR(self.dec).toDMS() self.position = Position.fromRaDec(self.ra, self.dec)
def precess(self, epoch=Epoch.NOW): if str(epoch).lower() == str(Epoch.J2000).lower(): epoch = ephem.J2000 elif str(epoch).lower() == str(Epoch.B1950).lower(): epoch = ephem.B1950 elif str(epoch).lower() == str(Epoch.NOW).lower(): epoch = ephem.now() j2000 = self.toEphem() now = ephem.Equatorial(j2000, epoch=epoch) return Position.fromRaDec(Coord.fromR(now.ra), Coord.fromR(now.dec), epoch=Epoch.NOW)
def moveNorth(self, offset, rate=SlewRate.MAX): self._slewing = True pos = self.getPositionRaDec() pos = Position.fromRaDec(pos.ra, pos.dec + Coord.fromAS(offset)) self.slewBegin(pos) self._dec += Coord.fromAS(offset) self._setAltAzFromRaDec() self._slewing = False self.slewComplete(self.getPositionRaDec(), TelescopeStatus.OK)
def moveSouth(self, offset, rate=SlewRate.MAX): self._slewing = True pos = self.getPositionRaDec() pos = Position.fromRaDec(pos.ra, pos.dec + Coord.fromAS(-offset)) self.slewBegin(pos) self._dec += Coord.fromAS(-offset) self._setAltAzFromRaDec() self._slewing = False self.slewComplete(self.getPositionRaDec(), TelescopeStatus.OK)
def test_parsing_conversion_hipparcos(self): """Parsing and comparing a subset of the Hipparcos and Tycho Catalog""" hipp = ascii.read(os.path.abspath( os.path.join(os.path.dirname(__file__), 'hipparcos-tycho.dat')), format="tab") expected_ra = [] expected_ra_str = [] expected_dec = [] expected_dec_str = [] ra = [] ra_hms = [] dec = [] dec_dms = [] for row in hipp: expected_ra_str.append(row[0].strip()) expected_dec_str.append(row[1].strip()) expected_ra.append(float(row[2])) expected_dec.append(float(row[3])) ra.append(Coord.fromD(str(row[2]))) dec.append(Coord.fromD(str(row[3]))) ra_hms.append(Coord.fromHMS(str(row[0]))) dec_dms.append(Coord.fromDMS(str(row[1]))) for i in range(len(hipp)): assert expected_ra_str[i] == ra_hms[i].strfcoord("%(h)02d %(m)02d %(s)05.2f"), \ "ra: %s != coord ra: %s" % (expected_ra_str[i], ra_hms[i].strfcoord("%(h)02d %(m)02d %(s)05.2f")) assert expected_dec_str[i] == dec_dms[i].strfcoord("%(d)02d %(m)02d %(s)04.1f"), \ "dec: %s != coord dec: %s" % (expected_dec_str[i], dec_dms[i].strfcoord("%(d)02d %(m)02d %(s)04.1f")) # test conversion from D to D assert TestCoord.equal(ra[i].D, expected_ra[i], e=1e-8), \ "ra: %.6f != coord ra: %.6f (%.6f)" % (expected_ra[i], ra[i].D, expected_ra[i]-ra[i].D) assert TestCoord.equal(dec[i].D, expected_dec[i], e=1e-8), \ "dec: %.6f != coord dec: %.64f (%.6f)" % (expected_dec[i], dec[i].D, expected_dec[i]-dec[i].D) # test conversion from DMS HMS to D assert TestCoord.equal(ra_hms[i].D, expected_ra[i], e=1e-4), \ "ra: %.6f != coord ra: %.6f (%.6f)" % (expected_ra[i], ra_hms[i].D, expected_ra[i]-ra_hms[i].D) assert TestCoord.equal(dec_dms[i].D, expected_dec[i], e=1e-4), \ "dec: %.6f != coord dec: %.64f (%.6f)" % (expected_dec[i], dec_dms[i].D, expected_dec[i]-dec_dms[i].D)
def chimera_handler(self, payload, root): t0 = time.time() # Check if it is a real GRB ra, dec = float( root.find( "./WhereWhen/ObsDataLocation/ObservationLocation/AstroCoords/Position2D/Value2/C1" ).text ), float( root.find( "./WhereWhen/ObsDataLocation/ObservationLocation/AstroCoords/Position2D/Value2/C2" ).text) packet_type = int( root.find("./What/Param[@name='Packet_Type']").attrib['value']) site = self.getSite() ephem_site = site.getEphemSite(site.ut()) grb = ephem.FixedBody() grb._ra, grb._dec = ra, dec grb.compute(ephem_site) # Conditions to pull the observation trigger # TODO: implement min_moon_distance -> Position(coord.fromD(grb.alt), coord.fromD(grb.az)) - site.moonpos() # In[8]: a = Position.fromAltAz(Coord.fromD(10), Coord.fromD(10)) # # In[9]: b = Position.fromAltAz(Coord.fromD(10), Coord.fromD(20)) # # In[11]: a.angsep(b).D # Out[11]: 10.0 moondist = Position.fromAltAz(Coord.fromD(float(grb.alt)), Coord.fromD(float(grb.az))).angsep( site.moonpos()) if moondist > self['obs-min_moondist']: self.log.debug("Moon is OK! Moon distance = %.2f deg" % moondist) else: self.log.debug("Moon is NOT OK! Moon distance = %.2f deg" % moondist) # TODO: check if Test_Notice != True (for INTEGRAL) if grb.alt >= self['obs-min_alt'] and packet_type in range( 1000): # self['obs-packets']: gal_coord = ephem.Galactic(grb) ebv = get_SFD_dust([gal_coord.long], [gal_coord.lat], dustmap=self.dust_file, interpolate=False) if ebv < self['obs-ebv_max']: self.log.debug('Total analysis time: %6.3f secs' % (time.time() - t0)) self.trigger_observation(ra, dec) else: self.log.debug( "Reject alert type %i. ALT = %.2f, RA = %.2f DEC = %.2f. Config: %d, %s" % (packet_type, grb.alt, ra, dec, self['obs-min_alt'], str(self['obs-packets'])))
def test_coord(self): c = Config({"DMS": Coord.fromDMS(10), "HMS": Coord.fromHMS(10)}) assert c["DMS"].state == State.DMS assert c["HMS"].state == State.HMS c["DMS"] = 20 assert c["DMS"] == Coord.fromDMS(20) c["HMS"] = 20 assert c["HMS"] == Coord.fromHMS(20) assert c["HMS"] == Coord.fromDMS(20 * 15)
def test_parsing_conversion_hipparcos (self): """Parsing and comparing a subset of the Hipparcos and Tycho Catalog""" hipp = ascii.read(os.path.abspath(os.path.join(os.path.dirname(__file__), 'hipparcos-tycho.dat')), format="tab") expected_ra = [] expected_ra_str = [] expected_dec = [] expected_dec_str = [] ra = [] ra_hms = [] dec = [] dec_dms = [] for row in hipp: expected_ra_str.append(row[0].strip()) expected_dec_str.append(row[1].strip()) expected_ra.append(float(row[2])) expected_dec.append(float(row[3])) ra.append(Coord.fromD(str(row[2]))) dec.append(Coord.fromD(str(row[3]))) ra_hms.append(Coord.fromHMS(str(row[0]))) dec_dms.append(Coord.fromDMS(str(row[1]))) for i in range(len(hipp)): assert expected_ra_str[i] == ra_hms[i].strfcoord("%(h)02d %(m)02d %(s)05.2f"), \ "ra: %s != coord ra: %s" % (expected_ra_str[i], ra_hms[i].strfcoord("%(h)02d %(m)02d %(s)05.2f")) assert expected_dec_str[i] == dec_dms[i].strfcoord("%(d)02d %(m)02d %(s)04.1f"), \ "dec: %s != coord dec: %s" % (expected_dec_str[i], dec_dms[i].strfcoord("%(d)02d %(m)02d %(s)04.1f")) # test conversion from D to D assert TestCoord.equal(ra[i].D, expected_ra[i], e=1e-8), \ "ra: %.6f != coord ra: %.6f (%.6f)" % (expected_ra[i], ra[i].D, expected_ra[i]-ra[i].D) assert TestCoord.equal(dec[i].D, expected_dec[i], e=1e-8), \ "dec: %.6f != coord dec: %.64f (%.6f)" % (expected_dec[i], dec[i].D, expected_dec[i]-dec[i].D) # test conversion from DMS HMS to D assert TestCoord.equal(ra_hms[i].D, expected_ra[i], e=1e-4), \ "ra: %.6f != coord ra: %.6f (%.6f)" % (expected_ra[i], ra_hms[i].D, expected_ra[i]-ra_hms[i].D) assert TestCoord.equal(dec_dms[i].D, expected_dec[i], e=1e-4), \ "dec: %.6f != coord dec: %.64f (%.6f)" % (expected_dec[i], dec_dms[i].D, expected_dec[i]-dec_dms[i].D)
def test_parsing_conversion_bsc(self): """Parsing and comparing to Vizier calculated values the entire 5th Bright Star Catalogue""" bsc = asciidata.open(os.path.abspath( os.path.join(os.path.dirname(__file__), 'bsc.dat')), comment_char='#', delimiter='\t') expected_ra = [] expected_ra_str = [] expected_dec = [] expected_dec_str = [] ra = [] dec = [] for i in range(bsc.nrows): expected_ra.append(bsc[0][i]) expected_dec.append(bsc[1][i]) expected_ra_str.append(bsc[2][i].strip()) expected_dec_str.append(bsc[3][i].strip()) ra.append(Coord.fromHMS(bsc[2][i])) dec.append(Coord.fromDMS(bsc[3][i])) for i in range(bsc.nrows): # use e=0.0001 'cause its the maximum we can get with Vizier data (4 decimal places only) # test conversion from HMS DMS to decimal assert TestCoord.equal( ra[i].D, expected_ra[i], e=1e-4), "ra: %.6f != coord ra: %.6f (%.6f)" % ( expected_ra[i], ra[i].D, expected_ra[i] - ra[i].D) assert TestCoord.equal( dec[i].D, expected_dec[i], e=1e-4), "dec: %.6f != coord dec: %.64f (%.6f)" % ( expected_dec[i], dec[i].D, expected_dec[i] - dec[i].D) # test strfcoord implementation assert expected_ra_str[i] == ra[i].strfcoord( "%(h)02d %(m)02d %(s)04.1f"), "ra: %s != coord ra: %s" % ( expected_ra_str[i], ra[i].strfcoord("%(h)02d %(m)02d %(s)04.1f")) assert expected_dec_str[i] == dec[i].strfcoord( "%(d)02d %(m)02d %(s)02.0f"), "dec: %s != coord dec: %s" % ( expected_dec_str[i], dec[i].strfcoord("%(d)02d %(m)02d %(s)02.0f"))
def getAz(self): self._write(":GZ#") ret = self._readline() ret = ret.replace('\xdf', ':') c = Coord.fromDMS(ret[:-1]) if self['azimuth180Correct']: if c.toD() >= 180: c = c - Coord.fromD(180) else: c = c + Coord.fromD(180) return c
def test_coord (self): c = Config({"DMS": Coord.fromDMS(10), "HMS": Coord.fromHMS(10)}) assert c["DMS"].state == State.DMS assert c["HMS"].state == State.HMS c["DMS"] = 20 assert c["DMS"] == Coord.fromDMS(20) c["HMS"] = 20 assert c["HMS"] == Coord.fromHMS(20) assert c["HMS"] == Coord.fromDMS(20*15)
def fromRaDec(ra, dec, epoch=Epoch.J2000): try: if type(ra) is str: ra = Coord.fromHMS(ra) elif isinstance(ra, Coord): ra = ra.toHMS() else: try: ra = Coord.fromH(float(ra)) ra = ra.toHMS() except ValueError: raise ValueError( "Invalid RA coordinate type %s. Expected numbers, strings or Coords." % str(type(ra))) Position._checkRange(float(ra), 0, 360) except ValueError as e: raise ValueError("Invalid RA coordinate %s" % str(ra)) except PositionOutsideLimitsError: raise ValueError( "Invalid RA range %s. Must be between 0-24 hours or 0-360 deg." % str(ra)) try: if type(dec) is str: dec = Coord.fromDMS(dec) elif isinstance(dec, Coord): dec = dec.toDMS() else: try: dec = Coord.fromD(float(dec)) dec = dec.toDMS() except ValueError: raise ValueError( "Invalid DEC coordinate type %s. Expected numbers, strings or Coords." % str(type(dec))) Position._checkRange(float(dec), -90, 360) except ValueError as e: raise ValueError("Invalid DEC coordinate %s" % str(dec)) except PositionOutsideLimitsError: raise ValueError( "Invalid DEC range %s. Must be between 0-360 deg or -90 - +90 deg." % str(dec)) return Position((ra, dec), system=System.CELESTIAL, epoch=epoch)
def getAz(self): # converted to Astelco ret = self._tpl.getobject('POSITION.HORIZONTAL.AZ') if ret: self._az = Coord.fromD(ret) self.log.debug('Az: %9.5f'%float(ret)) c = self._az #Coord.fromD(ret) if self['azimuth180Correct']: if c.toD() >= 180: c = c - Coord.fromD(180) else: c = c + Coord.fromD(180) return c
def test_park(self): # FIXME: make a real test. raise SkipTest() def printPosition(): print self.tel.getPositionRaDec(), self.tel.getPositionAltAz() sys.stdout.flush() print ra = self.tel.getRa() dec = self.tel.getDec() print "current position:", self.tel.getPositionRaDec() print "moving to:", (ra - "01 00 00"), (dec - "01 00 00") self.tel.slewToRaDec( Position.fromRaDec(ra - Coord.fromH(1), dec - Coord.fromD(1))) for i in range(10): printPosition() time.sleep(0.5) print "parking..." sys.stdout.flush() self.tel.park() t0 = time.time() wait = 30 for i in range(10): printPosition() time.sleep(0.5) while time.time() < t0 + wait: print "\rwaiting ... ", sys.stdout.flush() time.sleep(1) print "unparking..." sys.stdout.flush() self.tel.unpark() for i in range(10): printPosition() time.sleep(0.5)
def getTargetDec(self): self._write(":Gd#") ret = self._readline() ret = ret.replace('\xdf', ':') return Coord.fromDMS(ret[:-1])
class Dome(Interface): """ A Roll-off or classic dome. """ __config__ = { "device": None, "telescope": "/Telescope/0", "mode": Mode.Stand, "model": "Fake Domes Inc.", "style": Style.Classic, 'park_position': Coord.fromD(155), 'park_on_shutdown': False, 'close_on_shutdown': False, "az_resolution": 2, # dome position resolution in degrees "slew_timeout": 120, "abort_timeout": 60, "init_timeout": 5, "open_timeout": 20, "close_timeout": 20, "fans": [], # list of fans of the dome, i.e.: fans: ['/FakeFan/fake1', '/FakeFan/fake2'] "lamps": [], # list of lamps of the dome, i.e.: lamps: ['/FakeLamp/fake1'] }
def test_parse_dms (self): coords = [] t_parse = 0 t_check = 0 for dd in range(-23, 24): for mm in range(0, 60): for ss in range(0, 60): s = '%+03d:%02d:%06.3f' % (dd,mm,ss) t = time.clock() c = Coord.fromDMS(s) t_parse += time.clock()-t coords.append((s,c)) for coord in coords: t = time.clock() assert coord[0] == str(coord[1]), (coord[0], "!=", str(coord[1])) t_check += time.clock()-t print "#%d coords parsed in %.3fs (%.3f/s) and checked in %.3fs (%.3f/s) ..." % (len(coords), t_parse, len(coords)/t_parse, t_check, len(coords)/t_check)
def _waitSlew (self, start_time, target, local=False): self.slewBegin(target) while True: # check slew abort event if self._abort.isSet (): self._slewing = False return TelescopeStatus.ABORTED # check timeout if time.time () >= (start_time + self["max_slew_time"]): self.abortSlew () self._slewing = False raise MeadeException("Slew aborted. Max slew time reached.") if local: position = self.getPositionAltAz() else: position = self.getPositionRaDec() if target.within (position, eps=Coord.fromAS(60)): time.sleep (self["stabilization_time"]) self._slewing = False return TelescopeStatus.OK time.sleep (self["slew_idle_time"]) return TelescoopeStatus.ERROR
def GST(self): """ Mean Greenwhich Sidereal Time """ lst = self.LST() gst = (lst - self["longitude"].toH()) % Coord.fromH(24) return gst
def getAlt(self): # converted to Astelco ret = self._tpl.getobject('POSITION.HORIZONTAL.ALT') if ret: self._alt = Coord.fromD(ret) self.log.debug('Alt: %9.5f'%float(ret)) return self._alt
def getAz(self): self._checkQuirk() self.tty.setTimeout(10) cmd = "POSICAO?" self._write(cmd) ack = self._readline() # check timeout if not ack: raise IOError("Couldn't get azimuth after %d seconds." % 10) # uC is going crazy if ack == "INVALIDO": raise IOError("Error getting dome azimuth (ack=INVALIDO).") # get ack return if ack.startswith("CUPULA="): ack = ack[ack.find("=") + 1:] if ack == "ERRO": # FIXME: restart and try again raise ChimeraException( "Dome is in invalid state. Hard restart needed.") # correct dome/telescope phase difference az = int(math.ceil(int(ack) * self["az_resolution"])) az -= self._az_shift az = az % 360 return Coord.fromDMS(az)
def getRa(self): # converted to Astelco ret = self._tpl.getobject('POSITION.EQUATORIAL.RA_J2000') if ret: self._ra = Coord.fromH(ret) self.log.debug('Ra: %9.5f'%float(ret)) return self._ra
def _waitSlew(self, start_time, target, local=False): self.slewBegin(target) while True: # check slew abort event if self._abort.isSet(): self._slewing = False return TelescopeStatus.ABORTED # check timeout if time.time() >= (start_time + self["max_slew_time"]): self.abortSlew() self._slewing = False raise MeadeException("Slew aborted. Max slew time reached.") if local: position = self.getPositionAltAz() else: position = self.getPositionRaDec() if target.within(position, eps=Coord.fromAS(60)): time.sleep(self["stabilization_time"]) self._slewing = False return TelescopeStatus.OK time.sleep(self["slew_idle_time"]) return TelescoopeStatus.ERROR
def test_parse_dms(self): coords = [] t_parse = 0 t_check = 0 for dd in range(-23, 24): for mm in range(0, 60): for ss in range(0, 60): s = '%+03d:%02d:%06.3f' % (dd, mm, ss) t = time.clock() c = Coord.fromDMS(s) t_parse += time.clock() - t coords.append((s, c)) for coord in coords: t = time.clock() assert coord[0] == str(coord[1]), (coord[0], "!=", str(coord[1])) t_check += time.clock() - t print "#%d coords parsed in %.3fs (%.3f/s) and checked in %.3fs (%.3f/s) ..." % ( len(coords), t_parse, len(coords) / t_parse, t_check, len(coords) / t_check)
def test_park (self): # FIXME: make a real test. raise SkipTest() def printPosition(): print self.tel.getPositionRaDec(), self.tel.getPositionAltAz() sys.stdout.flush() print ra = self.tel.getRa() dec = self.tel.getDec() print "current position:", self.tel.getPositionRaDec() print "moving to:", (ra-"01 00 00"), (dec-"01 00 00") self.tel.slewToRaDec(Position.fromRaDec(ra-Coord.fromH(1), dec-Coord.fromD(1))) for i in range(10): printPosition() time.sleep(0.5) print "parking..." sys.stdout.flush() self.tel.park() t0 = time.time() wait = 30 for i in range(10): printPosition() time.sleep(0.5) while time.time() < t0+wait: print "\rwaiting ... ", sys.stdout.flush() time.sleep(1) print "unparking..." sys.stdout.flush() self.tel.unpark() for i in range(10): printPosition() time.sleep(0.5)
def test_slew_abort(self): site = self.manager.getProxy("/Site/0") # go to know position self.tel.slewToRaDec(Position.fromRaDec(site.LST(), site["latitude"])) last = self.tel.getPositionRaDec() # clear event checkings FiredEvents = {} # drift it dest = Position.fromRaDec(last.ra + Coord.fromH(1), last.dec + Coord.fromD(10)) real_dest = None @callback(self.manager) def slewBeginClbk(target): global real_dest real_dest = target @callback(self.manager) def slewCompleteClbk(position, status): assert last.ra < position.ra < real_dest.ra assert last.dec < position.dec < real_dest.dec self.tel.slewBegin += slewBeginClbk self.tel.slewComplete += slewCompleteClbk # async slew def slew(): tel = self.manager.getProxy(self.TELESCOPE) tel.slewToRaDec(dest) pool = ThreadPool() pool.queueTask(slew) # wait thread to be scheduled time.sleep(2) # abort and test self.tel.abortSlew() pool.joinAll() # event checkings self.assertEvents(TelescopeStatus.ABORTED)
def test_slew_abort (self): site = self.manager.getProxy("/Site/0") # go to know position self.tel.slewToRaDec(Position.fromRaDec(site.LST(), site["latitude"])) last = self.tel.getPositionRaDec() # clear event checkings FiredEvents = {} # drift it dest = Position.fromRaDec(last.ra+Coord.fromH(1), last.dec+Coord.fromD(10)) real_dest = None @callback(self.manager) def slewBeginClbk(target): global real_dest real_dest = target @callback(self.manager) def slewCompleteClbk(position, status): assert last.ra < position.ra < real_dest.ra assert last.dec < position.dec < real_dest.dec self.tel.slewBegin += slewBeginClbk self.tel.slewComplete += slewCompleteClbk # async slew def slew(): tel = self.manager.getProxy(self.TELESCOPE) tel.slewToRaDec(dest) pool = ThreadPool() pool.queueTask(slew) # wait thread to be scheduled time.sleep(2) # abort and test self.tel.abortSlew() pool.joinAll() # event checkings self.assertEvents(TelescopeStatus.ABORTED)
def LST (self): """ Mean Local Sidereal Time """ #lst = self._getEphem(self.ut()).sidereal_time() #required since a Coord cannot be constructed from an Ephem.Angle lst_c = Coord.fromR(self.LST_inRads()) return lst_c.toHMS()
def _watchTrackingStopped(self, position, status): self.setFlag("telescope",InstrumentOperationFlag.READY) self.broadCast('Telescope tracking stopped with status %s.' % status) if status == TelescopeStatus.OBJECT_TOO_LOW: # Todo: Make this an action on the checklist database, so user can configure what to do robobs = self.getRobObs() sched = self.getSched() robobs.stop() sched.stop() tel = self.getTel() from chimera.util.position import Position from chimera.util.coord import Coord park_position = Position.fromAltAz(Coord.fromD(80),Coord.fromD(89)) tel.slewToAltAz(park_position) robobs.reset_scheduler() robobs.start() robobs.wake()
def LST(self): """ Mean Local Sidereal Time """ #lst = self._getEphem(self.ut()).sidereal_time() #required since a Coord cannot be constructed from an Ephem.Angle lst_c = Coord.fromR(self.LST_inRads()) return lst_c.toHMS()
def getAz(self): self._write(":GZ#") ret = self._readline() ret = ret.replace('\xdf', ':') c = Coord.fromDMS(ret[:-1]) if self['azimuth180Correct']: self.log.debug('Initial azimuth: %s' % str(c.toDMS())) if c.toD() > 180: c = c - Coord.fromD(180) else: c = c + Coord.fromD(180) self.log.debug('Final azimuth: %s' % str(c.toDMS())) return c
def setLong(self, coord): # converted to Astelco if not isinstance(coord, Coord): coord = Coord.fromDMS(coord) cmdid = self._tpl.set( 'POINTING.SETUP.LOCAL.LONGITUDE', coord.D, wait=True) ret = self._tpl.succeeded(cmdid) if not ret: raise AstelcoException("Invalid Longitude '%s'" % coord.D) return True
def test_set_info (self): m = self.m try: m.setLat("-22 32 03") m.setLong("-45 34 57") m.setDate(time.time()) m.setLocalTime(time.time()) m.setUTCOffset(3) m.setLat(Coord.fromDMS("-22 32 03")) m.setLong(Coord.fromDMS("-45 34 57")) m.setDate(dt.date.today()) m.setLocalTime(dt.datetime.now().time()) m.setUTCOffset(3) except Exception: log.exception("error")
def fromRaDec (ra, dec, epoch=Epoch.J2000): try: if type(ra) == StringType: ra = Coord.fromHMS(ra) elif isinstance(ra, Coord): ra = ra.toHMS() else: try: ra = Coord.fromH(float(ra)) ra = ra.toHMS() except ValueError: raise ValueError("Invalid RA coordinate type %s. Expected numbers, strings or Coords." % str(type(ra))) Position._checkRange(float(ra), 0, 360) except ValueError, e: raise ValueError("Invalid RA coordinate %s" % str(ra))
def _moveDome(self): dome = self._getDome() # from chimera.util.coord import Coord target = Coord.fromD(self["dome_az"]) dome.stand() dome.slewToAz(target)
def check(self, value, state=None): if not isinstance(value, Coord): try: return Coord.fromState(value, state) except ValueError: pass # any other type is ignored raise OptionConversionException('invalid coord value %s.' % value)
def getAz(self): tpl = self.getTPL() ret = tpl.getobject('POSITION.INSTRUMENTAL.DOME[0].CURRPOS') if ret: self._position = ret elif not self._position: self._position = 0. return Coord.fromD(self._position)
def check (self, value, state=None): if not isinstance(value, Coord): try: return Coord.fromState(value, state) except ValueError: pass # any other type is ignored raise OptionConversionException ('invalid coord value %s.' % value)
def slewToAz(self, az): if not isinstance(az, Coord): az = Coord.fromDMS(az) if int(az) >= 360: az = az % 360 drv = self.getDriver() drv.slewToAz(az)
def angsep(self, other): """ Calculate the Great Circle Distance from other. @param other: position to calculate distance from. @type other: L{Position} @returns: The distance from this point to L{other}. @rtype: L{Coord} in degress (convertable, as this is a Coord). """ return Coord.fromR(CoordUtil.gcdist(self.R, other.R)).toD()
def _genericLongLat(long, lat): try: if not isinstance(long, Coord): long = Coord.fromDMS(long) else: long = long.toDMS() Position._checkRange(float(long), -180, 360) except ValueError, e: raise ValueError("Invalid LONGITUDE coordinate %s" % str(long))
def fromAltAz(alt, az): try: if not isinstance(az, Coord): az = Coord.fromDMS(az) else: az = az.toDMS() Position._checkRange(float(az), -180, 360) except ValueError, e: raise ValueError("Invalid AZ coordinate %s" % str(az))
def getRa(self): self._write(":GR#") ret = self._readline() # meade bugs: sometimes, after use Move commands, getRa # returns a 1 before the RA, so we just check this and discard # it here if len(ret) > 9: ret = ret[1:] return Coord.fromHMS(ret[:-1])
def getDec(self): self._write(":GD#") ret = self._readline() # meade bugs: same as getRa if len(ret) > 10: ret = ret[1:] ret = ret.replace('\xdf', ':') return Coord.fromDMS(ret[:-1])
def test_sync (self): # get current position, drift the scope, and sync on the first # position (like done when aligning the telescope). real = self.tel.getPositionRaDec() @callback(self.manager) def syncCompleteClbk(position): assert position.ra == real.ra assert position.dec == real.dec self.tel.syncComplete += syncCompleteClbk # drift to "real" object coordinate drift = Position.fromRaDec(real.ra+Coord.fromH(1), real.dec+Coord.fromD(1)) self.tel.slewToRaDec(drift) self.tel.syncRaDec(real) time.sleep(2)
def __init__(self): ChimeraObject.__init__(self) self.__slewing = False self._az = Coord.fromDMS(0) self._alt = Coord.fromDMS(70) self._slewing = False self._tracking = True self._parked = False self._abort = threading.Event() try: self._site = self.getManager().getProxy(self['site']) self._gotSite = True except: self._site = Site() self._gotSite = False self._setRaDecFromAltAz()
def _telescopeChanged(self, az): if not isinstance(az, Coord): az = Coord.fromDMS(az) if self._needToMove(az): self.log.debug("[control] adding %s to the queue." % az) self.queue.put(az) else: self.log.debug("[control] telescope still in the slit, standing" " (dome az=%.2f, tel az=%.2f, delta=%.2f.)" % (self.getAz(), az, abs(self.getAz() - az)))