Read pertinent information from the image headers,
         especially location and radius of the Sun to calculate the default thematic map
        :return: setes self.date, self.cy, self.cx, and self.sun_radius_pixel
173751
def interpret_header(self):
        
        # handle special cases since date-obs field changed names
        if 'DATE_OBS' in self.header:
            self.date = self.header['DATE_OBS']
        elif 'DATE-OBS' in self.header:
            self.date = self.header['DATE-OBS']
        else:
            raise Exception("Image does not have a DATE_OBS or DATE-OBS field")

        self.cy, self.cx = self.header['CRPIX1'], self.header['CRPIX2']
        sun_radius_angular = sun.solar_semidiameter_angular_size(t=time.parse_time(self.date)).arcsec
        arcsec_per_pixel = self.header['CDELT1']
        self.sun_radius_pixel = (sun_radius_angular / arcsec_per_pixel)
1235445
def _daily_suns(self, datetimes):
        """"""
        for dt in datetimes:
            # calculate sunrise sunset and noon
            nss = self.calculate_sunrise_sunset(dt.month, dt.day)
            dts = tuple(nss[k] for k in ('sunrise', 'noon', 'sunset'))
            if dts[0] is None:
                # circle
                yield (self.calculate_sun(dt.month, dt.day, h) for h in (0, 12,
                                                                         15)), \
                    False
            else:
                # Arc
                yield (self.calculate_sun_from_date_time(dt) for dt in dts), True
326310
def _get_coordinates_for_dataset_key(self, dsid):
        """"""
        ds_info = self.ids[dsid]
        cids = []

        for cinfo in ds_info.get('coordinates', []):
            if not isinstance(cinfo, dict):
                cinfo = {'name': cinfo}

            cinfo['resolution'] = ds_info['resolution']
            if 'polarization' in ds_info:
                cinfo['polarization'] = ds_info['polarization']
            cid = DatasetID(**cinfo)
            cids.append(self.get_dataset_key(cid))

        return cids
1121223
def _map_from_binaries(self, eopatch, dst_shape, request_data):
        
        if self.feature_name in eopatch[self.feature_type]:
            raster = eopatch[self.feature_type][self.feature_name].squeeze()
        else:
            raster = np.ones(dst_shape, dtype=self.raster_dtype) * self.no_data_val

        new_raster = self._reproject(eopatch, self._to_binary_mask(request_data))

        # update raster
        raster[new_raster != 0] = new_raster[new_raster != 0]

        return raster
798073
def get_ref_dir(region, coordsys):
        
        if region is None:
            if coordsys == "GAL":
                c = SkyCoord(0., 0., frame=Galactic, unit="deg")
            elif coordsys == "CEL":
                c = SkyCoord(0., 0., frame=ICRS, unit="deg")
            return c

        tokens = parse_hpxregion(region)
        if tokens[0] in ['DISK', 'DISK_INC']:
            if coordsys == "GAL":
                c = SkyCoord(float(tokens[1]), float(
                    tokens[2]), frame=Galactic, unit="deg")
            elif coordsys == "CEL":
                c = SkyCoord(float(tokens[1]), float(
                    tokens[2]), frame=ICRS, unit="deg")
            return c
        elif tokens[0] == 'HPX_PIXEL':
            nside_pix = int(tokens[2])
            ipix_pix = int(tokens[3])
            if tokens[1] == 'NESTED':
                nest_pix = True
            elif tokens[1] == 'RING':
                nest_pix = False
            else:
                raise Exception(
                    "Did not recognize ordering scheme %s" % tokens[1])
            theta, phi = hp.pix2ang(nside_pix, ipix_pix, nest_pix)
            lat = np.degrees((np.pi / 2) - theta)
            lon = np.degrees(phi)
            if coordsys == "GAL":
                c = SkyCoord(lon, lat, frame=Galactic, unit="deg")
            elif coordsys == "CEL":
                c = SkyCoord(lon, lat, frame=ICRS, unit="deg")
            return c
        else:
            raise Exception(
                "HPX.get_ref_dir did not recognize region type %s" % tokens[0])
        return None
530007
def sunRelation(self):
        
        sun = self.chart.getObject(const.SUN)
        return sunRelation(self.obj, sun)
1193084
def get_default_values(self):
        
        out = dict(dx=0, dy=0, dz=0, theta=0, phi=0, psi=0)
        dx, dy, dz, _ = np.mean(self.coord1 - self.coord2, axis=1)
        out['dx'] = dx
        out['dy'] = dy
        out['dz'] = dz

        # C->N vector
        vec1 = self.coord1[:-1, 1] - self.coord1[:-1, -1]
        vec2 = self.coord2[:-1, 1] - self.coord2[:-1, -1]
        vec1 /= np.linalg.norm(vec1)
        vec2 /= np.linalg.norm(vec2)

        # Find the rotation matrix that converts vec1 to vec2:
        # http://math.stackexchange.com/questions/180418/#476311
        v = np.cross(vec1, vec2)
        s = np.linalg.norm(v) + np.finfo(DTYPE).eps

        c = vec1.dot(vec2)
        vx = np.array([[0, -v[2], v[1]],
                       [v[2], 0, -v[0]],
                       [-v[1], v[0], 0]], dtype=DTYPE)
        rotation_matrix = np.eye(3) + vx + vx.dot(vx) * (1 - c) / (s * s)

        # Recover the angles from the matrix as seen here:
        # http://nghiaho.com/?page_id=846
        out['theta'] = math.atan2(rotation_matrix[2, 1], rotation_matrix[2, 2])
        out['phi'] = math.atan2(-rotation_matrix[2, 0],
                                math.hypot(rotation_matrix[2, 1],
                                           rotation_matrix[2, 2]))
        out['psi'] = math.atan2(rotation_matrix[1, 0], rotation_matrix[0, 0])

        return out
389087
def _get_reflectance(self, projectables, optional_datasets):
        """"""
        _nir, _tb11 = projectables
        LOG.info('Getting reflective part of %s', _nir.attrs['name'])

        sun_zenith = None
        tb13_4 = None

        for dataset in optional_datasets:
            wavelengths = dataset.attrs.get('wavelength', [100., 0, 0])
            if (dataset.attrs.get('units') == 'K' and
                    wavelengths[0] <= 13.4 <= wavelengths[2]):
                tb13_4 = dataset
            elif ("standard_name" in dataset.attrs and
                  dataset.attrs["standard_name"] == "solar_zenith_angle"):
                sun_zenith = dataset

        # Check if the sun-zenith angle was provided:
        if sun_zenith is None:
            if sun_zenith_angle is None:
                raise ImportError("No module named pyorbital.astronomy")
            lons, lats = _nir.attrs["area"].get_lonlats_dask(CHUNK_SIZE)
            sun_zenith = sun_zenith_angle(_nir.attrs['start_time'], lons, lats)

        return self._refl3x.reflectance_from_tbs(sun_zenith, _nir, _tb11, tb_ir_co2=tb13_4)
317030
def get_default_mapping(self, z, cmapper):
        

        map_annular = dict(x=self.max_radius, y=self.max_radius,
                           inner_radius="inner_radius",
                           outer_radius="outer_radius",
                           start_angle="start_angle",
                           end_angle="end_angle",
                           fill_color={'field': z, 'transform': cmapper})

        map_seg_label = dict(x="x", y="y", text="text",
                             angle="angle", text_align="center")

        map_ann_label = dict(x="x", y="y", text="text",
                             angle="angle", text_align="center",
                             text_baseline="bottom")

        map_xmarks = dict(xs="xs", ys="ys")

        map_ymarks = dict(x= self.max_radius, y=self.max_radius,
                          start_angle=0, end_angle=2*np.pi, radius="radius")

        return {'annular_wedge_1': map_annular,
                'text_1': map_seg_label,
                'text_2': map_ann_label,
                'multi_line_1': map_xmarks,
                'arc_1': map_ymarks}
945757
def _convert_sky_coords(self):
        
        parsed_angles = [(x, y)
                         for x, y in zip(self.coord[:-1:2], self.coord[1::2])
                         if (isinstance(x, coordinates.Angle) and isinstance(y, coordinates.Angle))
                         ]
        frame = coordinates.frame_transform_graph.lookup_name(self.coordsys)

        lon, lat = zip(*parsed_angles)
        if hasattr(lon, '__len__') and hasattr(lat, '__len__') and len(lon) == 1 and len(lat) == 1:
            # force entries to be scalar if they are length-1
            lon, lat = u.Quantity(lon[0]), u.Quantity(lat[0])
        else:
            # otherwise, they are vector quantities
            lon, lat = u.Quantity(lon), u.Quantity(lat)
        sphcoords = coordinates.UnitSphericalRepresentation(lon, lat)
        coords = [SkyCoord(frame(sphcoords))]

        if self.region_type != 'polygon':
            coords += self.coord[len(coords * 2):]

        return coords
592796
def global_horizontal_irradiance(self):
        """"""
        analysis_period = AnalysisPeriod(timestep=self.timestep,
                                         is_leap_year=self.is_leap_year)
        header_ghr = Header(data_type=GlobalHorizontalIrradiance(),
                            unit='W/m2',
                            analysis_period=analysis_period,
                            metadata=self.metadata)
        glob_horiz = []
        sp = Sunpath.from_location(self.location)
        sp.is_leap_year = self.is_leap_year
        for dt, dnr, dhr in zip(self.datetimes, self.direct_normal_irradiance,
                                self.diffuse_horizontal_irradiance):
            sun = sp.calculate_sun_from_date_time(dt)
            glob_horiz.append(dhr + dnr * math.sin(math.radians(sun.altitude)))
        return HourlyContinuousCollection(header_ghr, glob_horiz)
1293036
def _get_data_collections(dnr_values, dhr_values, metadata, timestep, is_leap_year):
        
        analysis_period = AnalysisPeriod(timestep=timestep, is_leap_year=is_leap_year)
        dnr_header = Header(data_type=DirectNormalIrradiance(),
                            unit='W/m2',
                            analysis_period=analysis_period,
                            metadata=metadata)
        direct_norm_rad = HourlyContinuousCollection(dnr_header, dnr_values)
        dhr_header = Header(data_type=DiffuseHorizontalIrradiance(),
                            unit='W/m2',
                            analysis_period=analysis_period,
                            metadata=metadata)
        diffuse_horiz_rad = HourlyContinuousCollection(dhr_header, dhr_values)

        return direct_norm_rad, diffuse_horiz_rad
451368
def infos(self):
        
        if not hasattr(self, '_infos'):
            self._infos = OrbitInfos(self)
        return self._infos
328605
def default_cy(self):
        
        px_height = self.image.px_height
        horz_dpi = self.image.horz_dpi
        height_in_emu = 914400 * px_height / horz_dpi
        return Emu(height_in_emu)
903802
def get_pixel_indices(self, lats, lons):
        
        theta = np.radians(90. - lats)
        phi = np.radians(lons)
        return hp.ang2pix(self.nside, theta, phi, self.nest)
442673
def get_SZ(self):
        
        if self.psd_integrator is None:
            (self._S, self._Z) = self.get_SZ_orient()
        else:
            scatter_outdated = self._scatter_signature != (self.thet0, 
                self.thet, self.phi0, self.phi, self.alpha, self.beta, 
                self.orient)            
            psd_outdated = self._psd_signature != (self.psd,)
            outdated = scatter_outdated or psd_outdated

            if outdated:
                (self._S, self._Z) = self.psd_integrator(self.psd, 
                    self.get_geometry())
                self._set_scatter_signature()
                self._set_psd_signature()

        return (self._S, self._Z)
1070465
def update(self):
        
        g = get_root(self).globals

        if g.astro is None or g.fpslide is None:
            self.after(100, self.update)
            return

        try:
            if g.cpars['tcs_on']:

                try:
                    # Poll TCS for ra,dec etc.
                    ra, dec, pa, focus = self.tcs_data_queue.get(block=False)

                    # format ra, dec as HMS
                    coo = coord.SkyCoord(ra, dec, unit=(u.deg, u.deg))
                    ratxt = coo.ra.to_string(sep=':', unit=u.hour, precision=0)
                    dectxt = coo.dec.to_string(sep=':', unit=u.deg,
                                               alwayssign=True,
                                               precision=0)
                    self.ra.configure(text=ratxt)
                    self.dec.configure(text=dectxt)

                    # wrap pa from 0 to 360
                    pa = coord.Longitude(pa*u.deg)
                    self.pa.configure(text='{0:6.2f}'.format(pa.value))

                    # set focus
                    self.focus.configure(text='{0:+5.2f}'.format(focus))

                    # Calculate most of the
                    # stuff that we don't get from the telescope
                    now = Time.now()
                    with warnings.catch_warnings():
                        warnings.simplefilter('ignore')
                        # ignore astropy deprecation warnings
                        lon = g.astro.obs.longitude
                    lst = now.sidereal_time(kind='mean',
                                            longitude=lon)
                    ha = coo.ra.hourangle*u.hourangle - lst
                    hatxt = ha.wrap_at(12*u.hourangle).to_string(sep=':', precision=0)
                    self.ha.configure(text=hatxt)

                    altaz_frame = coord.AltAz(obstime=now, location=g.astro.obs)
                    altaz = coo.transform_to(altaz_frame)
                    self.alt.configure(text='{0:<4.1f}'.format(altaz.alt.value))
                    self.az.configure(text='{0:<5.1f}'.format(altaz.az.value))
                    # set airmass
                    self.airmass.configure(text='{0:<4.2f}'.format(altaz.secz))

                    # distance to the moon. Warn if too close
                    # (configurable) to it.
                    md = coord.get_moon(now, g.astro.obs).separation(coo)
                    self.mdist.configure(text='{0:<7.2f}'.format(md.value))
                    if md < g.cpars['mdist_warn']*u.deg:
                        self.mdist.configure(bg=g.COL['warn'])
                    else:
                        self.mdist.configure(bg=g.COL['main'])
                except Empty:
                    # silently do nothing if queue is empty
                    pass
                except Exception as err:
                    self.ra.configure(text='UNDEF')
                    self.dec.configure(text='UNDEF')
                    self.pa.configure(text='UNDEF')
                    self.ha.configure(text='UNDEF')
                    self.alt.configure(text='UNDEF')
                    self.az.configure(text='UNDEF')
                    self.airmass.configure(text='UNDEF')
                    self.mdist.configure(text='UNDEF')
                    g.clog.warn('TCS error: ' + str(err))

            if g.cpars['hcam_server_on'] and \
               g.cpars['eso_server_online']:

                # get run number (set by the 'Start' button')
                try:
                    # get run number from hipercam server
                    run = getRunNumber(g)
                    self.run.configure(text='{0:03d}'.format(run))

                    # Find the number of frames in this run
                    try:
                        frame_no = getFrameNumber(g)
                        self.frame.configure(text='{0:04d}'.format(frame_no))
                    except Exception as err:
                        if err.code == 404:
                            self.frame.configure(text='0')
                        else:
                            g.clog.debug('Error occurred trying to set frame')
                            self.frame.configure(text='UNDEF')

                except Exception as err:
                    g.clog.debug('Error trying to set run: ' + str(err))

            # get the slide position
            # poll at 5x slower rate than the frame
            if self.count % 5 == 0 and g.cpars['focal_plane_slide_on']:
                try:
                    pos_ms, pos_mm, pos_px = self.slide_pos_queue.get(block=False)
                    self.fpslide.configure(text='{0:d}'.format(
                        int(round(pos_px))))
                    if pos_px < 1050.:
                        self.fpslide.configure(bg=g.COL['warn'])
                    else:
                        self.fpslide.configure(bg=g.COL['main'])
                except Exception as err:
                    pass

            # get the CCD temperature poll at 5x slower rate than the frame
            if self.count % 5 == 0:
                try:
                    if g.ccd_hw is not None and g.ccd_hw.ok:
                        self.ccd_temps.configure(text='OK')
                        self.ccd_temps.configure(bg=g.COL['main'])
                    else:
                        self.ccd_temps.configure(text='ERR')
                        self.ccd_temps.configure(bg=g.COL['warn'])
                except Exception as err:
                    g.clog.warn(str(err))
                    self.ccd_temps.configure(text='UNDEF')
                    self.ccd_temps.configure(bg=g.COL['warn'])

        except Exception as err:
            # this is a safety catchall trap as it is important
            # that this routine keeps going
            g.clog.warn('Unexpected error: ' + str(err))

        # run every 2 seconds
        self.count += 1
        self.after(2000, self.update)