How to use the astropy.log function in astropy

To help you get started, weā€™ve selected a few astropy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nanograv / PINT / tests / test_model.py View on Github external
did_tempo1 = False
    try:
        import tempo_utils

        log.info("Running TEMPO1...")
        t1_result = np.genfromtxt(
            t1_parfile + ".tempo_test", names=True, comments="#", dtype=np.longdouble
        )
        t1_resids = t1_result["residuals_phase"] / float(m.F0.value) * 1e6 * u.us
        did_tempo1 = True
        diff_t1 = (resids_us - t1_resids).to(u.ns)
        diff_t1 -= diff_t1.mean()
        log.info(
            "Max resid diff between PINT and T1: %.2f ns" % np.fabs(diff_t1).max().value
        )
        log.info("Std resid diff between PINT and T1: %.2f ns" % diff_t1.std().value)
        diff_t2_t1 = (t2_resids - t1_resids).to(u.ns)
        diff_t2_t1 -= diff_t2_t1.mean()
        log.info(
            "Max resid diff between T1 and T2: %.2f ns"
            % np.fabs(diff_t2_t1).max().value
        )
        log.info("Std resid diff between T1 and T2: %.2f ns" % diff_t2_t1.std().value)
    except:
        pass

    if did_tempo1 and not planets:
        assert np.fabs(diff_t1).max() < 32.0 * u.ns

    def do_plot():
        plt.clf()
        plt.subplot(211)
github cta-observatory / ctapipe / ctapipe / plotting / camera.py View on Github external
"""
        Draw the pixel_ids on top of a camera image

        Parameters
        ----------
        tel : int
            The telescope you want drawn.
        pixels : list
            A list of the pixel IDs you want drawing
        axes : `matplotlib.axes.Axes`
            A matplotlib axes object to plot on, or None to create a new one.
        """

        geom = self.get_geometry(tel)
        axes = axes if axes is not None else plt.gca()
        log.info("Annotating with pixel_ids")
        for pix in pixels:
            x = u.Quantity(geom.pix_x).value[pix]
            y = u.Quantity(geom.pix_y).value[pix]
            axes.text(x, y, pix, fontsize=2, ha='center')
github soar-telescope / goodman_pipeline / src / goodman_ccd / fix_header.py View on Github external
except KeyError:
                pass

        # Removing duplicated keywords
        key_list = []
        for key in hdr.iterkeys():
            if key in key_list:
                hdr.remove(keyword=key)
            key_list.append(key)

        hdr.add_history('Header and Shape fixed.')
        fits.writeto(os.path.join(output_path, '') + prefix + os.path.basename(_file), ccddata, hdr,
                     clobber=overwrite)
        log.info('Keywords header of ' + os.path.basename(_file) + ' have been updated --> ' + prefix
                 + os.path.basename(_file))
    log.info('Done: all keywords header have been updated.')
    print('\n')
    return
github hyperion-rt / hyperion / hyperion / densities / power_law_envelope.py View on Github external
def mass(self, value):
        if value is not None:
            validate_scalar('mass', value, domain='positive')
            if self._rho_0 is not None:
                logger.warning("Overriding value of rho_0 with value derived from mass")
                self._rho_0 = None
        self._mass = value
github NASA-Planetary-Science / sbpy / sbpy / photometry / core.py View on Github external
if valid.any():
            valid = list(valid).index(True)
            for p in cls.param_names:
                par[p] = par[p][valid]
            meta = kwargs.pop('meta', OrderedDict())
            if 'targetname' in phys.field_names:
                meta.update({'targetname': phys['targetname'][valid]})
            kwargs['meta'] = meta
            for p in cls.param_names:
                val = kwargs.pop(p, None)
            try:
                par['radius'] = phys['diameter'][valid]/2
            except KeyError:
                pass
            if 'targetname' in meta.keys():
                log.info("Model initialized for {}.".format(
                    meta['targetname']))
            else:
                log.info("Model initialized.")
            kwargs.update(par)
        else:
            raise ValueError(
                'no valid model parameters found in `data` keyword')
        out = cls(**kwargs)
        return out
github nanograv / PINT / src / pint / observatory / fermi_obs.py View on Github external
CartesianRepresentation(
                    self.X(time.tt.mjd) * u.m,
                    self.Y(time.tt.mjd) * u.m,
                    self.Z(time.tt.mjd) * u.m,
                ),
                obstime=time,
            )

            # Now transform ECI (GCRS) to ECEF (ITRS)
            # By default, this uses the WGS84 ellipsoid
            pos_ITRS = pos_gcrs.transform_to(ITRS(obstime=time))

            # Return geocentric ITRS coordinates as an EarthLocation object
            return pos_ITRS.earth_location
        else:
            log.error("Unknown tt2tdb_mode %s, using None" % self.tt2tdb_mode)
            return None
github nanograv / PINT / pint / observatory / fermi_obs.py View on Github external
def __init__(self, name, ft2name, tt2tdb_mode = 'pint'):
        self.FT2 = load_FT2(ft2name)
        # Now build the interpolator here:
        self.X = InterpolatedUnivariateSpline(self.FT2['MJD_TT'],self.FT2['X'])
        self.Y = InterpolatedUnivariateSpline(self.FT2['MJD_TT'],self.FT2['Y'])
        self.Z = InterpolatedUnivariateSpline(self.FT2['MJD_TT'],self.FT2['Z'])
        self.Vx = InterpolatedUnivariateSpline(self.FT2['MJD_TT'],self.FT2['Vx'])
        self.Vy = InterpolatedUnivariateSpline(self.FT2['MJD_TT'],self.FT2['Vy'])
        self.Vz = InterpolatedUnivariateSpline(self.FT2['MJD_TT'],self.FT2['Vz'])
        super(FermiObs, self).__init__(name=name)
        # Print this warning once, mainly for @paulray
        if self.tt2tdb_mode.lower().startswith('pint'):
            log.warning('Using location=None for TT to TDB conversion (pint mode)')
        elif self.tt2tdb_mode.lower().startswith('geo'):
            log.warning('Using location geocenter for TT to TDB conversion')
github hyperion-rt / hyperion / hyperion / densities / alpha_disk.py View on Github external
def mass(self, value):
        if value is not None:
            validate_scalar('mass', value, domain='positive')
            if self._rho_0 is not None:
                logger.warning("Overriding value of rho_0 with value derived from mass")
                self._rho_0 = None
        self._mass = value
github pyspeckit / pyspeckit / pyspeckit / spectrum / fitters.py View on Github external
if len(guesses) != len(pinf_for_scaling):
                    raise ValueError("Length of parinfo doens't match length of guesses")

                # zip guesses with parinfo: truncates parinfo if len(parinfo) > len(guesses)
                # actually not sure how/when/if this should happen; this might be a bad hack
                # revisit with tests!!
                for jj,(guess,par) in enumerate(zip(guesses,pinf_for_scaling)):
                    if par.scaleable:
                        guesses[jj] /= scalefactor
                        # if parinfo was passed in, this will change it
                        # if it was not, it will change only the placeholder
                        # (becuase we are passing by reference above)
                        par.value /= scalefactor
                        par.limits = [lim / scalefactor for lim in par.limits]

                log.debug("Rescaled guesses to {0}".format(guesses))

        # all fit data must be float64, otherwise the optimizers may take steps
        # less than the precision of the data and get stuck
        xtofit = self.Spectrum.xarr[self.xmin:self.xmax][~self.mask_sliced].astype('float64')
        spectofit = self.spectofit[self.xmin:self.xmax][~self.mask_sliced].astype('float64')
        err = self.errspec[self.xmin:self.xmax][~self.mask_sliced].astype('float64')

        if np.all(err == 0):
            raise ValueError("Errors are all zero.  This should not occur and "
                             "is a bug. (if you set the errors to all zero, "
                             "they should be overridden and set to 1)")

        if parinfo is not None:
            self._validate_parinfo(parinfo, mode='fix')
        else:
            pinf, _ = self.fitter._make_parinfo(parvalues=guesses,
github nanograv / PINT / pint / observatory / special_locations.py View on Github external
def clock_corrections(self, t):
        corr = numpy.zeros(t.shape)*u.s
        if self.include_gps:
            log.info('Applying GPS to UTC clock correction (~few nanoseconds)')
            if self._gps_clock is None:
                log.info('Observatory {0}, loading GPS clock file {1}'.format(self.name, self.gps_fullpath))
                self._gps_clock = ClockFile.read(self.gps_fullpath,
                        format='tempo2')
            corr += self._gps_clock.evaluate(t)
        if self.include_bipm:
            log.info('Applying TT(TAI) to TT(BIPM) clock correction (~27 us)')
            tt2tai = 32.184 * 1e6 * u.us
            if self._bipm_clock is None:
                try:
                    log.info('Observatory {0}, loading BIPM clock file {1}'.format(self.name, self.bipm_fullpath))
                    self._bipm_clock = ClockFile.read(self.bipm_fullpath,
                                                      format='tempo2')
                except:
                    raise ValueError("Can not find TT BIPM file '%s'. " % self.bipm_version)
            corr += self._bipm_clock.evaluate(t) - tt2tai
        return corr