示例#1
0
    def _takeImage(self):

        if self._debugging:
            try:
                frame = self._debug_images[self._debug_image]
                self._debug_image += 1

                img = Image.fromFile(frame)
                srv = getImageServer(self.getManager())
                return srv.register(img)
            except IndexError:
                raise ChimeraException("Cannot find debug images")

        self.imageRequest["filename"] = os.path.join(SYSTEM_CONFIG_DIRECTORY,
                                                     self.currentRun,
                                                     "focus-$DATE.fits")

        cam = self.getCam()

        if self.filter:
            filter = self.getFilter()
            filter.setFilter(self.filter)

        frame = cam.expose(self.imageRequest)

        if frame:
            return frame[0]
        else:
            raise Exception("Error taking image.")
示例#2
0
    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)
示例#3
0
    def control(self):

        if self.getMode() == Mode.Stand:
            return True

        if not self.queue.empty():
            self._processQueue()
            return True

        try:
            if not self._tel or self._telChanged:
                self._tel = self.getTelescope()
                self._telChanged = False
                if not self._tel:
                    return True

            if self._tel.isSlewing():
                self.log.debug(
                    "[control] telescope slewing... not checking az.")
                self._waitAfterSlew.set()
                return True

            self._telescopeChanged(self._tel.getAz())
            # flag all waiting threads that the control loop already checked the new telescope position
            # probably adding new azimuth to the queue
            self._waitAfterSlew.clear()

        except ObjectNotFoundException:
            raise ChimeraException("Couldn't found the selected telescope."
                                   " Dome cannnot track.")

        return True
示例#4
0
    def _takeImage(self, position=None):

        if self._debugging:
            try:
                frame = self._debug_images[self._debug_image]
                self._debug_image += 1

                img = Image.fromFile(frame)
                srv = getImageServer(self.getManager())
                return srv.register(img)
            except IndexError:
                raise ChimeraException("Cannot find debug images")

        if position is not None:
            self.imageRequest["filename"] = os.path.basename(ImageUtil.makeFilename("focus-%i-$DATE-$TIME" % position))
        else:
            self.imageRequest["filename"] = os.path.basename(ImageUtil.makeFilename("focus-$DATE-$TIME"))

        cam = self.getCam()

        if self.filter:
            filter = self.getFilter()
            filter.setFilter(self.filter)

        frames = cam.expose(self.imageRequest)

        if frames:
            image = frames[0]
            image_path = image.filename()
            if not os.path.exists(image_path):  # If image is on a remote server, donwload it.

                #  If remote is windows, image_path will be c:\...\image.fits, so use ntpath instead of os.path.
                if ':\\' in image_path:
                    modpath = ntpath
                else:
                    modpath = os.path
                image_path = ImageUtil.makeFilename(os.path.join(getImageServer(self.getManager()).defaultNightDir(),
                                                                 modpath.basename(image_path)))
                t0 = time.time()
                self.log.debug('Downloading image from server to %s' % image_path)
                if not ImageUtil.download(image, image_path):
                    raise ChimeraException('Error downloading image %s from %s' % (image_path, image.http()))
                self.log.debug('Finished download. Took %3.2f seconds' % (time.time() - t0))
            return image_path, image
        else:
            raise Exception("Could not take an image")
示例#5
0
    def __init__ (self, manager):

        SocketServer.UDPServer.allow_reuse_address = True
        SocketServer.ThreadingUDPServer.daemon_threads = False

        try:
            SocketServer.ThreadingUDPServer.__init__(self, ("", MANAGER_BEACON_PORT), _ManagerBeaconHandler)
        except Exception, e:
            raise ChimeraException("Failed to start Manager Beacon.")
示例#6
0
    def _checkQuirk(self):
        # clear uC command buffer sending and \r, this makes the uC happy!
        self._write("")

        ret = self._readline()
        if ret != "INVALIDO":
            raise ChimeraException("Quirk error!!! (%s)" % str(ret))

        return True
示例#7
0
 def open(self):
     '''
     Connects to CCDSoft server
     :return:
     '''
     self.log.debug('Starting CCDSoft camera')
     self._ccdsoft = Dispatch("CCDSoft.Camera")
     try:
         self._ccdsoft.Connect()
         self._ccdsoft.Asynchronous = 1
     except com_error:
         raise ChimeraException("Could not configure camera.")
示例#8
0
    def _expose(self, request):
        """
        .. method:: expose(request=None, **kwargs)

            Start an exposure based upon the specified image request or
            create a new image request from kwargs

            :keyword request: ImageRequest object
            :type request: ImageRequest
        """
        self.exposeBegin(request)

        if request['shutter'] == Shutter.OPEN:
            img_type = 1  # light
        elif request['shutter'] == Shutter.CLOSE:
            img_type = 3  # dark
        elif request['shutter'] == Shutter.LEAVE_AS_IS:
            raise ChimeraException('Not supported to leave as is shutter.')

        # Can only take images of exptime > minexptime.
        if request["exptime"] < self['min_exptime']:
            request["exptime"] = self['min_exptime']

        mode, binning, top, left, width, height = self._getReadoutModeInfo(request["binning"], request["window"])
        # Binning
        vbin, hbin = [int(v) for v in binning.split('x')]
        self._ccdsoft.BinX = vbin
        self._ccdsoft.BinY = hbin

        # TODO: Subframing
        self._ccdsoft.Subframe = False
        # self._ccdsoft.SubframeBottom = top
        # self._ccdsoft.SubframeLeft = left
        # self._ccdsoft.SubframeRight = right
        # self._ccdsoft.SubframeTop = top

        # Start Exposure...
        self._ccdsoft.ImageReduction = 0  # Disable any possible data reduction
        self._ccdsoft.ExposureTime = request["exptime"]
        self._ccdsoft.Frame = img_type
        self._ccdsoft.TakeImage()

        status = CameraStatus.OK

        while not bool(self._ccdsoft.IsExposureComplete):
            # [ABORT POINT]
            if self.abort.isSet():
                self._ccdsoft.Abort()
                status = CameraStatus.ABORTED
                break

        self.exposeComplete(request, status)
示例#9
0
    def __init__(self, host=None, port=None, local=False):
        RemoteObject.__init__(self)

        log.info("Starting manager.")

        self.resources = ResourcesManager()
        self.classLoader = ClassLoader()

        # identity
        self.setGUID(MANAGER_LOCATION)

        # shutdown event
        self.died = threading.Event()

        if not local:
            try:
                ManagerLocator.locate()
                raise ChimeraException("Chimera is already running"
                                       " on this system. Use chimera-admin"
                                       " to manage it.")
            except ManagerNotFoundException:
                # ok, we are alone.
                pass

        # our daemon server
        self.adapter = ManagerAdapter(self, host, port)
        self.adapterThread = threading.Thread(target=self.adapter.requestLoop)
        self.adapterThread.setDaemon(True)
        self.adapterThread.start()

        # finder beacon
        if not local:
            self.beacon = ManagerBeacon(self)
            self.beaconThread = threading.Thread(target=self.beacon.run)
            self.beaconThread.setDaemon(True)
            self.beaconThread.start()
        else:
            self.beacon = None

        # register ourself
        self.resources.add(MANAGER_LOCATION, self,
                           getManagerURI(self.getHostname(), self.getPort()))

        # signals
        signal.signal(signal.SIGTERM, self._sighandler)
        signal.signal(signal.SIGINT, self._sighandler)
        atexit.register(self._sighandler)
示例#10
0
    def _takeImage(self):
        cam = self.getCam()

        if self.filter:
            filter = self.getFilter()
            filter.setFilter(self.filter)

        self.imageRequest["filename"] = os.path.basename(
            ImageUtil.makeFilename("align-$DATE"))

        frames = cam.expose(self.imageRequest)

        if frames:
            image = frames[0]
            image_path = image.filename()
            if not os.path.exists(
                    image_path
            ):  # If image is on a remote server, donwload it.

                #  If remote is windows, image_path will be c:\...\image.fits, so use ntpath instead of os.path.
                if ':\\' in image_path:
                    modpath = ntpath
                else:
                    modpath = os.path
                image_path = ImageUtil.makeFilename(
                    os.path.join(
                        getImageServer(self.getManager()).defaultNightDir(),
                        modpath.basename(image_path)))
                t0 = time.time()
                self.log.debug('Downloading image from server to %s' %
                               image_path)
                if not ImageUtil.download(image, image_path):
                    raise ChimeraException(
                        'Error downloading image %s from %s' %
                        (image_path, image.http()))
                self.log.debug('Finished download. Took %3.2f seconds' %
                               (time.time() - t0))
                image = Image.fromFile(image_path)
            return image  #image_path #, image
        else:
            raise Exception("Could not take an image")
示例#11
0
 def answer(self):
     try:
         raise ChimeraException("I'm an Exception, sorry.")
     except ChimeraException:
         self.log.exception("from except: wow, exception caught.")
         raise ChimeraException("I'm a new Exception, sorry again")
示例#12
0
    def com_wrapper(*args, **kwargs):

        try:
            return func(*args, **kwargs)
        except com_error, e:
            raise ChimeraException(str(e))
示例#13
0
 def __init__(self, code, msg=""):
     ChimeraException.__init__(self, msg)
     self.code = code
示例#14
0
 def __init__(self, code, msg=""):
     ChimeraException.__init__(self, msg)
     self.code = code
示例#15
0
    def run_stats(self, proxy, status):
        if status == CameraStatus.OK and proxy["IMAGETYP"].upper().rstrip() == "OBJECT" and \
                        proxy["SHUTTER"].upper().rstrip() == "OPEN":

            self.log.debug('%s [status:%s]@[%s]' %
                           (proxy.filename(), status, proxy.http()))

            image_path = proxy.filename()
            if not os.path.exists(
                    image_path
            ):  # If image is on a remote server, donwload it.

                #  If remote is windows, image_path will be c:\...\image.fits, so use ntpath instead of os.path.
                if ':\\' in image_path:
                    modpath = ntpath
                else:
                    modpath = os.path
                image_path = ImageUtil.makeFilename(
                    os.path.join(
                        getImageServer(self.getManager()).defaultNightDir(),
                        modpath.basename(image_path)))
                t0 = time.time()
                self.log.debug('Downloading image from server to %s' %
                               image_path)
                if not ImageUtil.download(proxy, image_path):
                    raise ChimeraException(
                        'Error downloading image %s from %s' %
                        (image_path, image.http()))
                self.log.debug('Finished download. Took %3.2f seconds' %
                               (time.time() - t0))
                img = Image.fromFile(image_path)
            else:
                img = Image.fromFile(image_path)

            tmpfile = mktemp()
            p = self._sex_params
            p.update({"CATALOG_NAME": mktemp()})
            extract = img.extract(p)
            # os.unlink(tmpfile)
            # else:
            # extract = proxy.extract(self.sex_params)

            if len(extract
                   ) > 0:  # Only go ahead if at least one object was detected
                # stats = np.array(
                #     [[data["CLASS_STAR"], data["FLAGS"], data["FWHM_IMAGE"], data["BACKGROUND"]] for data in
                #      extract])
                stats = np.array([[
                    data["NUMBER"],
                    data["X_IMAGE"],
                    data["Y_IMAGE"],
                    data["XWIN_IMAGE"],
                    data["YWIN_IMAGE"],
                    data["ALPHA_J2000"],
                    data["DELTA_J2000"],
                    data["MAG_AUTO"],
                    data["FLUX_AUTO"],
                    data["BACKGROUND"],
                    data["FWHM_IMAGE"],
                    data["FLAGS"],
                    data["CLASS_STAR"],
                ] for data in extract])

                mask = np.bitwise_and(stats[:, 12] > 0.8, stats[:, 11] == 0)
                fff = "CLEAR"
                if "FILTER" in proxy.keys():
                    fff = proxy["FILTER"]
                # fff = "R"
                session = Session()
                try:
                    log = ImageStatistics(
                        date_obs=datetime.datetime.strptime(
                            proxy["DATE-OBS"], "%Y-%m-%dT%H:%M:%S.%f"),
                        filename=proxy.filename(),
                        filter=fff,
                        fwhm_avg=np.average(stats[:, 10][mask]),
                        fwhm_std=np.std(stats[:, 10][mask]),
                        background=np.average(stats[:, 9][mask]),
                        npts=mask.sum(),
                        exptime=proxy["EXPTIME"])
                    session.add(log)
                    session.flush()
                    session.refresh(log)
                    # Now add stars to the star catalog
                    # Todo: Solve astrometry
                    cat = []
                    mag_sort = np.argsort(stats[:,
                                                7])[:self['max_stars_catalog']]
                    for data in stats[mag_sort]:
                        cat.append(
                            ImageCatalog(
                                image_statistics_id=log.id,
                                NUMBER=data[0],
                                X_IMAGE=data[1],
                                Y_IMAGE=data[2],
                                XWIN_IMAGE=data[3],
                                YWIN_IMAGE=data[4],
                                ALPHA_J2000=data[5],
                                DELTA_J2000=data[6],
                                MAG_AUTO=data[7],
                                FLUX_AUTO=data[8],
                                BACKGROUND=data[9],
                                FWHM_IMAGE=data[10],
                                FLAGS=data[11],
                                CLASS_STAR=data[12],
                            ))
                    session.add_all(cat)
                finally:
                    session.commit()
                    # self.stats.append(s)
                    # print "fwhm stats:", s  # self.stats[-1]
        else:
            self.log.debug(
                'Image %s not good for statistics. [status:%s]@[%s]' %
                (proxy.filename(), status, proxy.http()))