Python astropy.units.day() Examples

The following are 30 code examples of astropy.units.day(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module astropy.units , or try the search function .
Example #1
Source File: test_OpticalSystem.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def test_calc_dMag_per_intTime(self):
        """
        Check calc_dMag_per_intTime i/o 
        """

        for mod in self.allmods:
            if 'calc_dMag_per_intTime' not in mod.__dict__:
                continue
            obj = mod(**copy.deepcopy(self.spec))
            
            dMag = obj.calc_dMag_per_intTime(np.ones(self.TL.nStars)*u.day,
                    self.TL, np.arange(self.TL.nStars), 
                    np.array([0]*self.TL.nStars)/(u.arcsec**2.),np.array([0]*self.TL.nStars)/(u.arcsec**2.),
                    np.array([obj.WA0.value]*self.TL.nStars)*obj.WA0.unit,obj.observingModes[0])
        
            self.assertEqual(dMag.shape,np.arange(self.TL.nStars).shape) 
Example #2
Source File: test_stellar_estimators.py    From lightkurve with MIT License 6 votes vote down vote up
def test_estimate_mass_basic():
    """Assert the basic functions of estimate_mass
    """
    M = estimate_mass(cnumax, cdeltanu, cteff)
    assert(M.unit == u.solMass)  # Check units
    assert(np.isclose(M.value, cM.n, rtol=cM.s))  # Check right answer

    # Check units on parameters
    M = estimate_mass(u.Quantity(cnumax, u.microhertz), cdeltanu, cteff)
    assert(np.isclose(M.value, cM.n, rtol=cM.s))

    M = estimate_mass(cnumax, u.Quantity(cdeltanu, u.microhertz), cteff)
    assert(np.isclose(M.value, cM.n, rtol=cM.s))

    M = estimate_mass(cnumax, cdeltanu, u.Quantity(cteff, u.Kelvin))
    assert(np.isclose(M.value, cM.n, rtol=cM.s))

    # Check works with a random selection of appropriate units
    M = estimate_mass(u.Quantity(cnumax, u.microhertz).to(1/u.day),
                      u.Quantity(cdeltanu, u.microhertz).to(u.hertz),
                      cteff)
    assert(np.isclose(M.value, cM.n, rtol=cM.s)) 
Example #3
Source File: linearJScheduler_det_only_sotoSS.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def revisitFilter(self, sInds, tmpCurrentTimeNorm):
        """Helper method for Overloading Revisit Filtering

        Args:
            sInds - indices of stars still in observation list
            tmpCurrentTimeNorm (MJD) - the simulation time after overhead was added in MJD form
        Returns:
            sInds - indices of stars still in observation list
        """
        tovisit = np.zeros(self.TargetList.nStars, dtype=bool)#tovisit is a boolean array containing the 
        if len(sInds) > 0:#so long as there is at least 1 star left in sInds
            tovisit[sInds] = ((self.starVisits[sInds] == min(self.starVisits[sInds])) \
                    & (self.starVisits[sInds] < self.nVisitsMax))# Checks that no star has exceeded the number of revisits
            if self.starRevisit.size != 0:#There is at least one revisit planned in starRevisit
                dt_rev = self.starRevisit[:,1]*u.day - tmpCurrentTimeNorm#absolute temporal spacing between revisit and now.

                ind_rev2 = [int(x) for x in self.starRevisit[dt_rev < 0*u.d, 0] if (x in sInds)]
                tovisit[ind_rev2] = (self.starVisits[ind_rev2] < self.nVisitsMax)
            sInds = np.where(tovisit)[0]
        return sInds 
Example #4
Source File: coroOnlyScheduler.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def scheduleRevisit(self, sInd, smin, det, pInds):
        """A Helper Method for scheduling revisits after observation detection
        Args:
            sInd - sInd of the star just detected
            smin - minimum separation of the planet to star of planet just detected
            det - 
            pInds - Indices of planets around target star
        Return:
            updates self.starRevisit attribute
        """

        TK = self.TimeKeeping

        t_rev = TK.currentTimeNorm.copy() + self.revisit_wait[sInd]
        # finally, populate the revisit list (NOTE: sInd becomes a float)
        revisit = np.array([sInd, t_rev.to('day').value])
        if self.starRevisit.size == 0:#If starRevisit has nothing in it
            self.starRevisit = np.array([revisit])#initialize sterRevisit
        else:
            revInd = np.where(self.starRevisit[:,0] == sInd)[0]#indices of the first column of the starRevisit list containing sInd 
            if revInd.size == 0:
                self.starRevisit = np.vstack((self.starRevisit, revisit))
            else:
                self.starRevisit[revInd,1] = revisit[1]#over 
Example #5
Source File: coroOnlyScheduler.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def revisitFilter(self, sInds, tmpCurrentTimeNorm):
        """Helper method for Overloading Revisit Filtering

        Args:
            sInds - indices of stars still in observation list
            tmpCurrentTimeNorm (MJD) - the simulation time after overhead was added in MJD form
        Returns:
            sInds - indices of stars still in observation list
        """
        tovisit = np.zeros(self.TargetList.nStars, dtype=bool)#tovisit is a boolean array containing the 
        if len(sInds) > 0:#so long as there is at least 1 star left in sInds
            tovisit[sInds] = ((self.starVisits[sInds] == min(self.starVisits[sInds])) \
                    & (self.starVisits[sInds] < self.nVisitsMax))# Checks that no star has exceeded the number of revisits
            if self.starRevisit.size != 0:#There is at least one revisit planned in starRevisit
                dt_rev = self.starRevisit[:,1]*u.day - tmpCurrentTimeNorm#absolute temporal spacing between revisit and now.

                #return indices of all revisits within a threshold dt_max of revisit day and indices of all revisits with no detections past the revisit time
                ind_rev2 = [int(x) for x in self.starRevisit[dt_rev < 0*u.d, 0] if (x in sInds)]
                tovisit[ind_rev2] = (self.starVisits[ind_rev2] < self.nVisitsMax)
            sInds = np.where(tovisit)[0]

        return sInds 
Example #6
Source File: linearJScheduler_det_only.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def revisitFilter(self, sInds, tmpCurrentTimeNorm):
        """Helper method for Overloading Revisit Filtering

        Args:
            sInds - indices of stars still in observation list
            tmpCurrentTimeNorm (MJD) - the simulation time after overhead was added in MJD form
        Returns:
            sInds - indices of stars still in observation list
        """
        tovisit = np.zeros(self.TargetList.nStars, dtype=bool)#tovisit is a boolean array containing the 
        if len(sInds) > 0:#so long as there is at least 1 star left in sInds
            tovisit[sInds] = ((self.starVisits[sInds] == min(self.starVisits[sInds])) \
                    & (self.starVisits[sInds] < self.nVisitsMax))# Checks that no star has exceeded the number of revisits
            if self.starRevisit.size != 0:#There is at least one revisit planned in starRevisit
                dt_rev = self.starRevisit[:,1]*u.day - tmpCurrentTimeNorm#absolute temporal spacing between revisit and now.

                ind_rev2 = [int(x) for x in self.starRevisit[dt_rev < 0*u.d, 0] if (x in sInds)]
                tovisit[ind_rev2] = (self.starVisits[ind_rev2] < self.nVisitsMax)
            sInds = np.where(tovisit)[0]
        return sInds 
Example #7
Source File: test_velocity_corrs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_IRAF_input(writefn=None):
    dt = test_input_time.utc.datetime

    coos = _get_test_input_radecs()

    lines = []
    for ra, dec in zip(coos.ra, coos.dec):
        rastr = Angle(ra).to_string(u.hour, sep=':')
        decstr = Angle(dec).to_string(u.deg, sep=':')

        msg = '{yr} {mo} {day} {uth}:{utmin} {ra} {dec}'
        lines.append(msg.format(yr=dt.year, mo=dt.month, day=dt.day,
                                uth=dt.hour, utmin=dt.minute,
                                ra=rastr, dec=decstr))
    if writefn:
        with open(writefn, 'w') as f:
            for l in lines:
                f.write(l)
    else:
        for l in lines:
            print(l)
    print('Run IRAF as:\nastutil\nrvcorrect f=<filename> observatory=Paranal') 
Example #8
Source File: test_intermediate_transformations.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_gcrs_altaz():
    """
    Check GCRS<->AltAz transforms for round-tripping.  Has multiple paths
    """
    from astropy.coordinates import EarthLocation

    ra, dec, _ = randomly_sample_sphere(1)
    gcrs = GCRS(ra=ra[0], dec=dec[0], obstime='J2000')

    # check array times sure N-d arrays work
    times = Time(np.linspace(2456293.25, 2456657.25, 51) * u.day,
                 format='jd')

    loc = EarthLocation(lon=10 * u.deg, lat=80. * u.deg)
    aaframe = AltAz(obstime=times, location=loc)

    aa1 = gcrs.transform_to(aaframe)
    aa2 = gcrs.transform_to(ICRS).transform_to(CIRS).transform_to(aaframe)
    aa3 = gcrs.transform_to(ITRS).transform_to(CIRS).transform_to(aaframe)

    # make sure they're all consistent
    assert_allclose(aa1.alt, aa2.alt)
    assert_allclose(aa1.az, aa2.az)
    assert_allclose(aa1.alt, aa3.alt)
    assert_allclose(aa1.az, aa3.az) 
Example #9
Source File: tieredScheduler_SLSQP.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def revisitFilter(self, sInds, tmpCurrentTimeNorm):
        """Helper method for Overloading Revisit Filtering

        Args:
            sInds - indices of stars still in observation list
            tmpCurrentTimeNorm (MJD) - the simulation time after overhead was added in MJD form
        Returns:
            sInds - indices of stars still in observation list
        """
        tovisit = np.zeros(self.TargetList.nStars, dtype=bool)#tovisit is a boolean array containing the 
        if len(sInds) > 0:#so long as there is at least 1 star left in sInds
            tovisit[sInds] = ((self.starVisits[sInds] == min(self.starVisits[sInds])) \
                    & (self.starVisits[sInds] < self.nVisitsMax))# Checks that no star has exceeded the number of revisits
            if self.starRevisit.size != 0:#There is at least one revisit planned in starRevisit
                dt_rev = self.starRevisit[:,1]*u.day - tmpCurrentTimeNorm#absolute temporal spacing between revisit and now.

                #return indices of all revisits within a threshold dt_max of revisit day and indices of all revisits with no detections past the revisit time
                ind_rev2 = [int(x) for x in self.starRevisit[dt_rev < 0*u.d, 0] if (x in sInds)]
                tovisit[ind_rev2] = (self.starVisits[ind_rev2] < self.nVisitsMax)
            sInds = np.where(tovisit)[0]

        return sInds 
Example #10
Source File: test_OpticalSystem.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ddMag_dt(self):
        """
        Check ddMag_dt i/o 
        """

        for mod in self.allmods:
            if 'ddMag_dt' not in mod.__dict__:
                continue
            obj = mod(**copy.deepcopy(self.spec))

            ddMag = obj.ddMag_dt(np.ones(self.TL.nStars)*u.day,
                    self.TL, np.arange(self.TL.nStars), 
                    np.array([0]*self.TL.nStars)/(u.arcsec**2.),np.array([0]*self.TL.nStars)/(u.arcsec**2.),
                    np.array([obj.WA0.value]*self.TL.nStars)*obj.WA0.unit,obj.observingModes[0])

            self.assertEqual(ddMag.shape,np.arange(self.TL.nStars).shape) 
Example #11
Source File: test_finite_difference_velocities.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_altaz_diffs():
    time = Time('J2015') + np.linspace(-1, 1, 1000)*u.day
    loc = get_builtin_sites()['greenwich']
    aa = AltAz(obstime=time, location=loc)

    icoo = ICRS(np.zeros_like(time)*u.deg, 10*u.deg, 100*u.au,
                pm_ra_cosdec=np.zeros_like(time)*u.marcsec/u.yr,
                pm_dec=0*u.marcsec/u.yr,
                radial_velocity=0*u.km/u.s)

    acoo = icoo.transform_to(aa)

    # Make sure the change in radial velocity over ~2 days isn't too much
    # more than the rotation speed of the Earth - some excess is expected
    # because the orbit also shifts the RV, but it should be pretty small
    # over this short a time.
    assert np.ptp(acoo.radial_velocity)/2 < (2*np.pi*constants.R_earth/u.day)*1.2  # MAGIC NUMBER

    cdiff = acoo.data.differentials['s'].represent_as(CartesianDifferential,
                                                    acoo.data)

    # The "total" velocity should be > c, because the *tangential* velocity
    # isn't a True velocity, but rather an induced velocity due to the Earth's
    # rotation at a distance of 100 AU
    assert np.all(np.sum(cdiff.d_xyz**2, axis=0)**0.5 > constants.c) 
Example #12
Source File: linearJScheduler_orbitChar.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def revisitFilter(self, sInds, tmpCurrentTimeNorm):
        """Helper method for Overloading Revisit Filtering

        Args:
            sInds - indices of stars still in observation list
            tmpCurrentTimeNorm (MJD) - the simulation time after overhead was added in MJD form
        Returns:
            sInds - indices of stars still in observation list
        """
        tovisit = np.zeros(self.TargetList.nStars, dtype=bool)#tovisit is a boolean array containing the 
        if len(sInds) > 0:#so long as there is at least 1 star left in sInds
            tovisit[sInds] = ((self.starVisits[sInds] == min(self.starVisits[sInds])) \
                    & (self.starVisits[sInds] < self.nVisitsMax))# Checks that no star has exceeded the number of revisits
            if self.starRevisit.size != 0:#There is at least one revisit planned in starRevisit
                dt_rev = self.starRevisit[:,1]*u.day - tmpCurrentTimeNorm#absolute temporal spacing between revisit and now.

                #return indices of all revisits within a threshold dt_max of revisit day and indices of all revisits with no detections past the revisit time
                ind_rev2 = [int(x) for x in self.starRevisit[dt_rev < 0*u.d, 0] if (x in sInds)]
                tovisit[ind_rev2] = (self.starVisits[ind_rev2] < self.nVisitsMax)
            sInds = np.where(tovisit)[0]

        return sInds 
Example #13
Source File: tieredScheduler.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def revisitFilter(self, sInds, tmpCurrentTimeNorm):
        """Helper method for Overloading Revisit Filtering

        Args:
            sInds - indices of stars still in observation list
            tmpCurrentTimeNorm (MJD) - the simulation time after overhead was added in MJD form
        Returns:
            sInds - indices of stars still in observation list
        """
        tovisit = np.zeros(self.TargetList.nStars, dtype=bool)#tovisit is a boolean array containing the 
        if len(sInds) > 0:#so long as there is at least 1 star left in sInds
            tovisit[sInds] = ((self.starVisits[sInds] == min(self.starVisits[sInds])) \
                    & (self.starVisits[sInds] < self.nVisitsMax))# Checks that no star has exceeded the number of revisits
            if self.starRevisit.size != 0:#There is at least one revisit planned in starRevisit
                dt_rev = self.starRevisit[:,1]*u.day - tmpCurrentTimeNorm#absolute temporal spacing between revisit and now.

                #return indices of all revisits within a threshold dt_max of revisit day and indices of all revisits with no detections past the revisit time
                ind_rev2 = [int(x) for x in self.starRevisit[dt_rev < 0*u.d, 0] if (x in sInds)]
                tovisit[ind_rev2] = (self.starVisits[ind_rev2] < self.nVisitsMax)
            sInds = np.where(tovisit)[0]

        return sInds 
Example #14
Source File: test_units.py    From starry with MIT License 6 votes vote down vote up
def test_period_semi():
    # Check that an error is raised if neither a nor porb is given
    with pytest.raises(ValueError) as e:
        body = starry.Secondary(starry.Map())
    assert "Must provide a value for either `porb` or `a`" in str(e.value)

    # Check that the semi --> period conversion works
    pri = starry.Primary(starry.Map(), m=1.0, mass_unit=u.Msun)
    sec = starry.Secondary(
        starry.Map(), a=10.0, m=1.0, length_unit=u.AU, mass_unit=u.Mearth
    )
    sys = starry.System(pri, sec)
    period = sys._get_periods()[0]
    true_period = (
        (
            (2 * np.pi)
            * (sec.a * sec.length_unit) ** (3 / 2)
            / (np.sqrt(G * (pri.m * pri.mass_unit + sec.m * sec.mass_unit)))
        )
        .to(u.day)
        .value
    )
    assert np.allclose(period, true_period) 
Example #15
Source File: tieredScheduler_sotoSS.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def revisitFilter(self, sInds, tmpCurrentTimeNorm):
        """Helper method for Overloading Revisit Filtering
        Args:
            sInds - indices of stars still in observation list
            tmpCurrentTimeNorm (MJD) - the simulation time after overhead was added in MJD form
        Returns:
            sInds - indices of stars still in observation list
        """
        tovisit = np.zeros(self.TargetList.nStars, dtype=bool)#tovisit is a boolean array containing the 
        if len(sInds) > 0:#so long as there is at least 1 star left in sInds
            tovisit[sInds] = ((self.starVisits[sInds] == min(self.starVisits[sInds])) \
                    & (self.starVisits[sInds] < self.nVisitsMax))# Checks that no star has exceeded the number of revisits
            if self.starRevisit.size != 0:#There is at least one revisit planned in starRevisit
                dt_rev = self.starRevisit[:,1]*u.day - tmpCurrentTimeNorm#absolute temporal spacing between revisit and now.

                #return indices of all revisits within a threshold dt_max of revisit day and indices of all revisits with no detections past the revisit time
                # ind_rev = [int(x) for x in self.starRevisit[np.abs(dt_rev) < self.dt_max, 0] if (x in sInds and self.no_dets[int(x)] == False)]
                # ind_rev2 = [int(x) for x in self.starRevisit[dt_rev < 0*u.d, 0] if (x in sInds and self.no_dets[int(x)] == True)]
                # tovisit[ind_rev] = (self.starVisits[ind_rev] < self.nVisitsMax)#IF duplicates exist in ind_rev, the second occurence takes priority
                ind_rev2 = [int(x) for x in self.starRevisit[dt_rev < 0*u.d, 0] if (x in sInds)]
                tovisit[ind_rev2] = (self.starVisits[ind_rev2] < self.nVisitsMax)
            sInds = np.where(tovisit)[0]

        return sInds 
Example #16
Source File: test_periodogram.py    From lightkurve with MIT License 6 votes vote down vote up
def test_flatten():
    npts = 10000
    np.random.seed(12069424)
    lc = LightCurve(time=np.arange(npts),
                    flux=np.random.normal(1, 0.1, npts),
                    flux_err=np.zeros(npts)+0.1)
    lc = lc.normalize()
    p = lc.to_periodogram(normalization='psd', freq_unit=1/u.day)

    # Check method returns equal frequency
    assert all(p.flatten(method='logmedian').frequency == p.frequency)
    assert all(p.flatten(method='boxkernel').frequency == p.frequency)

    # Check logmedian flatten of white noise returns mean of ~unity
    assert np.isclose(np.mean(p.flatten(method='logmedian').power.value), 1.0,
                      atol=0.05)

    # Check return trend works
    s, b = p.flatten(return_trend=True)
    assert all(b.power == p.smooth(method='logmedian', filter_width=0.01).power)
    assert all(s.power == p.flatten().power)
    str(s)
    s.plot()
    plt.close() 
Example #17
Source File: TimeKeeping.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def advancetToStartOfNextOB(self):
        """Advances to Start of Next Observation Block
        This method is called in the allocate_time() method of the TimeKeeping 
        class object, when the allocated time requires moving outside of the current OB.
        If no OB duration was specified, a new Observing Block is created for 
        each observation in the SurveySimulation module. Updates attributes OBnumber, 
        currentTimeNorm and currentTimeAbs.

        """
        self.OBnumber += 1#increase the observation block number
        self.currentTimeNorm = self.OBstartTimes[self.OBnumber]#update currentTimeNorm
        self.currentTimeAbs = self.OBstartTimes[self.OBnumber] + self.missionStart#update currentTimeAbs

        # begin Survey, and loop until mission is finished
        log_begin = 'OB%s:'%(self.OBnumber)#prints because this is the beginning of the nesxt observation block
        self.vprint(log_begin)
        self.vprint("Advanced currentTimeNorm to beginning of next OB %.2fd"%(self.currentTimeNorm.to('day').value)) 
Example #18
Source File: test_lightcurve.py    From lightkurve with MIT License 6 votes vote down vote up
def test_fold_v2():
    """The API of LightCurve.fold() changed in Lightkurve v2.x when we adopted
    AstroPy's TimeSeries.fold() method. This test verifies the new API."""
    lc = LightCurve(time=np.linspace(0, 10, 100), flux=np.zeros(100)+1)

    # Can period be passed as a float?
    fld = lc.fold(period=1)
    fld2 = lc.fold(period=1*u.day)
    assert_array_equal(fld.phase, fld2.phase)
    assert isinstance(fld.time, TimeDelta)
    fld.plot_river()
    plt.close()

    # Does phase normalization work?
    fld = lc.fold(period=1, normalize_phase=True)
    assert isinstance(fld.time, u.Quantity)
    fld.plot_river()
    plt.close() 
Example #19
Source File: linearJScheduler_orbitChar.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def scheduleRevisit(self, sInd, smin, det, pInds):
        """A Helper Method for scheduling revisits after observation detection
        Args:
            sInd - sInd of the star just detected
            smin - minimum separation of the planet to star of planet just detected
            det - 
            pInds - Indices of planets around target star
        Return:
            updates self.starRevisit attribute
        """

        TK = self.TimeKeeping

        t_rev = TK.currentTimeNorm.copy() + self.revisit_wait[sInd]
        # finally, populate the revisit list (NOTE: sInd becomes a float)
        revisit = np.array([sInd, t_rev.to('day').value])
        if self.starRevisit.size == 0:#If starRevisit has nothing in it
            self.starRevisit = np.array([revisit])#initialize sterRevisit
        else:
            revInd = np.where(self.starRevisit[:,0] == sInd)[0]#indices of the first column of the starRevisit list containing sInd 
            if revInd.size == 0:
                self.starRevisit = np.vstack((self.starRevisit, revisit))
            else:
                self.starRevisit[revInd,1] = revisit[1]#over 
Example #20
Source File: test_butler.py    From lightkurve with MIT License 6 votes vote down vote up
def test_estimate_deltanu_kwargs():
    """Test if we can estimate a deltanu using its various keyword arguments
    """
    f, p, _, true_deltanu = generate_test_spectrum()
    snr = SNRPeriodogram(f*u.microhertz, u.Quantity(p, None))
    butler = snr.to_seismology()

    # Assert custom numax works
    numax = butler.estimate_numax()
    deltanu = butler.estimate_deltanu(numax=numax)
    assert(np.isclose(deltanu.value, true_deltanu, atol=.25*true_deltanu))

    # Assert you can't pass custom numax outside of appropriate range
    with pytest.raises(ValueError):
        deltanu = butler.estimate_deltanu(numax= -5.)
    with pytest.raises(ValueError):
        deltanu = butler.estimate_deltanu(numax=5000)

    # Assert it doesn't matter what units of frequency numax is passed in as
    daynumax = u.Quantity(numax.value*u.microhertz, 1/u.day)
    deltanu = butler.estimate_deltanu(numax=daynumax)
    assert(np.isclose(deltanu.value, true_deltanu, atol=.25*true_deltanu))
    assert(deltanu.unit == u.microhertz) 
Example #21
Source File: SurveySimulation.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def revisitFilter(self,sInds,tmpCurrentTimeNorm):
        """Helper method for Overloading Revisit Filtering

        Args:
            sInds - indices of stars still in observation list
            tmpCurrentTimeNorm (MJD) - the simulation time after overhead was added in MJD form
        Returns:
            sInds - indices of stars still in observation list
        """

        tovisit = np.zeros(self.TargetList.nStars, dtype=bool)
        if len(sInds) > 0:
            tovisit[sInds] = ((self.starVisits[sInds] == min(self.starVisits[sInds])) \
                    & (self.starVisits[sInds] < self.nVisitsMax))#Checks that no star has exceeded the number of revisits and the indicies of all considered stars have minimum number of observations
            #The above condition should prevent revisits so long as all stars have not been observed
            if self.starRevisit.size != 0:
                dt_rev = np.abs(self.starRevisit[:,1]*u.day - tmpCurrentTimeNorm)
                ind_rev = [int(x) for x in self.starRevisit[dt_rev < self.dt_max,0] 
                        if x in sInds]
                tovisit[ind_rev] = (self.starVisits[ind_rev] < self.nVisitsMax)
            sInds = np.where(tovisit)[0]
        return sInds 
Example #22
Source File: test_butler.py    From lightkurve with MIT License 6 votes vote down vote up
def test_estimate_numax_basics():
    """Test if we can estimate a numax."""
    f, p, true_numax, _ = generate_test_spectrum()
    snr = SNRPeriodogram(f*u.microhertz, u.Quantity(p, None))
    numax = snr.to_seismology().estimate_numax()

    #Assert recovers numax within 10%
    assert(np.isclose(true_numax, numax.value, atol=.1*true_numax))
    #Assert numax has unit equal to input frequency unit
    assert(numax.unit == u.microhertz)

    # Assert you can recover numax with a chopped periodogram
    rsnr = snr[(snr.frequency.value>1600) & (snr.frequency.value<3200)]
    numax = rsnr.to_seismology().estimate_numax()
    assert(np.isclose(true_numax, numax.value, atol=.1*true_numax))

    # Assert numax estimator works when input frequency is not in microhertz
    fday = u.Quantity(f*u.microhertz, 1/u.day)
    snr = SNRPeriodogram(fday, u.Quantity(p, None))
    numax = snr.to_seismology().estimate_numax()
    nmxday = u.Quantity(true_numax*u.microhertz, 1/u.day)
    assert(np.isclose(nmxday, numax, atol=.1*nmxday)) 
Example #23
Source File: test_Observatory.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_log_occulterResults(self):
        """
        Test that log_occulter_results returns proper dictionary with keys
        """

        atts_list = ['slew_time', 'slew_angle', 'slew_dV', 'slew_mass_used', 'scMass']
        for mod in self.allmods:
            if 'log_occulterResults' in mod.__dict__:
                with RedirectStreams(stdout=self.dev_null):
                    if 'SotoStarshade' in mod.__name__:
                        obj = mod(f_nStars=4, **copy.deepcopy(self.spec))
                    else:
                        obj = mod(**copy.deepcopy(self.spec))
                DRM = {}
                slewTimes = np.ones((5,))*u.day
                sInds = np.arange(5)
                sd = np.ones((5,))*u.rad
                dV = np.ones((5,))*u.m/u.s

                DRM = obj.log_occulterResults(DRM, slewTimes, sInds, sd, dV)

                for att in atts_list:
                    self.assertTrue(att in DRM, 'Missing key in log_occulterResults for %s' % mod.__name__) 
Example #24
Source File: test_butler.py    From lightkurve with MIT License 5 votes vote down vote up
def test_estimate_deltanu_basics():
    """Test if we can estimate a deltanu
    """
    f, p, _, true_deltanu = generate_test_spectrum()
    snr = SNRPeriodogram(f*u.microhertz, u.Quantity(p, None))
    butler = snr.to_seismology()
    butler.estimate_numax()
    deltanu = butler.estimate_deltanu()

    # Assert recovers deltanu within 25%
    assert(np.isclose(true_deltanu, deltanu.value, atol=.25*true_deltanu))
    # Assert deltanu has unit equal to input frequency unit
    assert(deltanu.unit == u.microhertz)

    # Assert you can recover numax with a sliced periodogram
    rsnr = snr[(snr.frequency.value>1600) & (snr.frequency.value<3200)]
    butler = rsnr.to_seismology()
    butler.estimate_numax()
    numax = butler.estimate_deltanu()
    assert(np.isclose(true_deltanu, deltanu.value, atol=.25*true_deltanu))

    # Assert deltanu estimator works when input frequency is not in microhertz
    fday = u.Quantity(f*u.microhertz, 1/u.day)
    daysnr = SNRPeriodogram(fday, u.Quantity(p, None))
    butler = daysnr.to_seismology()
    butler.estimate_numax()
    deltanu = butler.estimate_deltanu()
    deltanuday = u.Quantity(true_deltanu*u.microhertz, 1/u.day)
    assert(np.isclose(deltanuday.value, deltanu.value, atol=.25*deltanuday.value)) 
Example #25
Source File: test_stellar_estimators.py    From lightkurve with MIT License 5 votes vote down vote up
def test_estimate_mass_kwargs():
    """Test the kwargs of estimate_mass."""
    M = estimate_mass(cnumax, cdeltanu, cteff, cenumax, cedeltanu, ceteff)

    # Check units
    assert M.unit == u.solMass
    assert M.error.unit == u.solMass

    # Check returns right answer
    assert_correct_answer(M, cM)

    # Check units on parameters
    M = estimate_mass(cnumax, cdeltanu, cteff,
                      u.Quantity(cenumax, u.microhertz), cedeltanu, ceteff)
    assert_correct_answer(M, cM)

    M = estimate_mass(cnumax, cdeltanu, cteff,
                      cenumax, u.Quantity(cedeltanu, u.microhertz), ceteff)
    assert_correct_answer(M, cM)

    M = estimate_mass(cnumax, cdeltanu, cteff,
                      cenumax, cedeltanu, u.Quantity(ceteff, u.Kelvin))
    assert_correct_answer(M, cM)

    #Check works with a random selection of appropriate units
    M = estimate_mass(cnumax, cdeltanu, cteff,
                      u.Quantity(cenumax, u.microhertz).to(1/u.day),
                      u.Quantity(cedeltanu, u.microhertz).to(u.hertz),
                      ceteff)
    assert_correct_answer(M, cM) 
Example #26
Source File: test_KnownRVPlanets.py    From EXOSIMS with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_init_traub_etal(self):
        r"""Test of initialization and __init__ -- compare values to Traub et al., JATIS, Mar. 2016.

        Method: Loop over the values from Traub et al., Table 6, as entered above, and find the
        corresponding planet in the EXOSIMS data.  Compare SMA (semi-major axis) and planetary mass.
        The relative error in SMA is presently allowed to be about 10%, and in mass, about 25%.
        This turned out to be an ineffective test, so it is disabled.
        """
        plan_pop = self.fixture
        # ensure basic module attributes are set up
        self.validate_planet_population(plan_pop)

        for planet_tuple in significant_planets:
            (_,name,name_alt,_,_,_,_,_,v,mass,rad,period,sma) = planet_tuple
            # units
            #  (v is a dimensionless magnitude)
            mass = mass * const.M_jup
            rad = rad * const.R_jup
            period = period * u.day
            sma = sma * u.au
            
            # match planets in EXOSIMS to planet in the Traub et al list
            # 1: match host star name
            index = np.array([name_alt in name1 for name1 in plan_pop.hostname])
            # 2: within this, match particular planet
            index2 = np.argmin(np.abs(plan_pop.sma[index] - sma))

            # compute relative differences
            delta_sma =  ((plan_pop.sma [index][index2] - sma ) / sma ).decompose().value
            delta_mass = ((plan_pop.mass[index][index2] - mass) / mass).decompose().value

            # proportional difference in SMA
            self.assertAlmostEqual(np.abs(delta_sma), 0.0, delta=0.08)
            # proportional difference in mass
            self.assertAlmostEqual(np.abs(delta_mass), 0.0, delta=0.25) 
Example #27
Source File: test_stellar_estimators.py    From lightkurve with MIT License 5 votes vote down vote up
def test_estimate_logg_basic():
    """Assert basic functionality of estimate_logg."""
    logg = estimate_logg(cnumax, cteff)
    # Check units
    assert(logg.unit == u.dex)
    # Check returns right answer
    assert(np.isclose(logg.value, clogg.n, rtol=clogg.s))
    # Check units on parameters
    logg = estimate_logg(u.Quantity(cnumax, u.microhertz), cteff)
    assert(np.isclose(logg.value, clogg.n, rtol=clogg.s))
    logg = estimate_logg(cnumax, u.Quantity(cteff, u.Kelvin))
    assert(np.isclose(logg.value, clogg.n, rtol=clogg.s))
    # Check works with a random selection of appropriate units
    logg = estimate_logg(u.Quantity(cnumax, u.microhertz).to(1/u.day), cteff)
    assert(np.isclose(logg.value, clogg.n, rtol=clogg.s)) 
Example #28
Source File: test_lightcurve.py    From lightkurve with MIT License 5 votes vote down vote up
def test_lightcurve_fold_issue520():
    """Regression test for #520; accept quantities in `fold()`."""
    lc = LightCurve(time=np.linspace(0, 10, 100), flux=np.zeros(100)+1)
    lc.fold(period=1*u.day, epoch_time=5*u.day) 
Example #29
Source File: test_velocity_corrs.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_rvcorr_multiple_obstimes_onskycoord():
    loc = EarthLocation(-2309223 * u.m, -3695529 * u.m, -4641767 * u.m)
    arrtime = Time('2005-03-21 00:00:00') + np.linspace(-1, 1, 10)*u.day

    sc = SkyCoord(1*u.deg, 2*u.deg, 100*u.kpc, obstime=arrtime, location=loc)
    rvcbary_sc2 = sc.radial_velocity_correction(kind='barycentric')
    assert len(rvcbary_sc2) == 10

    # check the multiple-obstime and multi- mode
    sc = SkyCoord(([1]*10)*u.deg, 2*u.deg, 100*u.kpc,
                  obstime=arrtime, location=loc)
    rvcbary_sc3 = sc.radial_velocity_correction(kind='barycentric')
    assert len(rvcbary_sc3) == 10 
Example #30
Source File: test_regression.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_regression_4926():
    times = Time('2010-01-1') + np.arange(20)*u.day
    green = get_builtin_sites()['greenwich']
    # this is the regression test
    moon = get_moon(times, green)

    # this is an additional test to make sure the GCRS->ICRS transform works for complex shapes
    moon.transform_to(ICRS())

    # and some others to increase coverage of transforms
    moon.transform_to(HCRS(obstime="J2000"))
    moon.transform_to(HCRS(obstime=times))