def test_JulianDate_reduce_jd(julian_date, expected):
    jd = JulianDate(julian_date)
    assert jd.jd == julian_date
    assert not jd.reduced
    jd.reduce()
    assert jd.reduced
    assert np.allclose(jd.jd, expected)
def test_JulianDate_reduce_jd(julian_date, expected):
    jd = JulianDate(julian_date)
    assert jd.jd == julian_date
    assert not jd.reduced
    jd.reduce()
    assert jd.reduced
    assert np.allclose(jd.jd, expected)
def test_jd_conversions(jd):
    """Test JulianDate.to_datetime and JulianDate.from_datetime are reversible."""
    assert np.allclose(jd,
                       JulianDate(jd).jd)
    assert np.allclose(JulianDate(jd).jd,
                       JulianDate.from_datetime(JulianDate(jd).to_datetime()).jd)
    assert np.allclose(ephem.julian_date(JulianDate(jd).to_datetime()),
                       JulianDate.from_datetime(JulianDate(jd).to_datetime()).jd)
def test_JulianDate_reduce_datetime(date, expected):
    d = datetime.datetime(*date)
    jd = JulianDate.from_datetime(d, reduced=True)

    assert jd.reduced
    assert np.allclose(jd.jd, expected)
    assert np.allclose(jd.jd, ephem.julian_date(d) - 2400000)
def test_JulianDate_reduce_datetime(date, expected):
    d = datetime.datetime(*date)
    jd = JulianDate.from_datetime(d, reduced=True)

    assert jd.reduced
    assert np.allclose(jd.jd, expected)
    assert np.allclose(jd.jd, ephem.julian_date(d) - 2400000)
def test_jd_conversions(jd):
    """Test JulianDate.to_datetime and JulianDate.from_datetime are reversible."""
    assert np.allclose(jd, JulianDate(jd).jd)
    assert np.allclose(
        JulianDate(jd).jd,
        JulianDate.from_datetime(JulianDate(jd).to_datetime()).jd)
    assert np.allclose(
        ephem.julian_date(JulianDate(jd).to_datetime()),
        JulianDate.from_datetime(JulianDate(jd).to_datetime()).jd)
def test_reduced_JulianDate_to_datetime(jd, expected):
    jd = JulianDate(jd)
    jd.reduce()
    assert abs(jd.to_datetime() -
               datetime.datetime(*expected)) < datetime.timedelta(seconds=1)
    assert isinstance(jd, JulianDate)
    assert isinstance(jd.to_datetime(), datetime.datetime)
Exemple #8
0
def binary_time_curve(host, companion, cycle_fraction=1, ignore_mean=False, t_past=False, t_future=False,
                      start_day=None):
    # type: (RV, RV, float, bool, Any, Any, Any) -> int
    """Plot RV phase curve centered on zero.

    Parameters
    ----------
    host: RV
        RV class for system.
    cycle_fraction: float
        Minimum Fraction of orbit to plot. (Default=1)
    ignore_mean: bool
        Remove the contribution from the systems mean velocity. (Default=False)
    t_past: float, array-like
        Times of past observations in julian days.
    t_future: float, array-like
        Times of future observations  in julian days.
    start_day: str
        Day to being RV curve from in julian days. The Default=None sets the start time to ephem.now().

    Returns
    -------
    exit_status: bool
        Returns 0 if successful.

        Displays matplotlib figure.
    """
    companion_present = companion is not None
    t_start = start_day if start_day is not None else JulianDate.now().jd
    # Make curve from start of t_past
    print("t_past", t_past, "t_future", t_future)
    if isinstance(t_past, float):
        obs_start = t_past
    elif t_past != [] and t_past is not None:
        obs_start = np.min(t_past)
    else:
        obs_start = t_start

    if isinstance(t_future, float):
        obs_end = t_future
    elif t_future != [] and t_future is not None:
        obs_end = np.max(t_future)
    else:
        obs_end = t_start
    # Specify 100 points per period
    num_cycles = ((t_start + host.period * cycle_fraction) - np.min([t_start, obs_start])) / host.period
    num_points = np.ceil(500 * num_cycles)
    if num_points > 10000:
        logging.debug("num points = {}".format(num_points))
        raise ValueError("num_points is to large")

    t_space = np.linspace(min([t_start, obs_start]), np.max([t_start + host.period * cycle_fraction, obs_end]),
                          num_points)

    start_dt = JulianDate(t_start).to_datetime()
    if (start_dt.hour == 0) and (start_dt.minute == 0) and (start_dt.second == 0):
        start_string = datetime.strftime(start_dt, "%Y-%m-%d")
    else:
        start_string = datetime.strftime(start_dt, "%Y-%m-%d %H:%M:%S")  # Issue with 00:00:01 not appearing

    fig = plt.figure(figsize=(10, 7))
    fig.subplots_adjust()
    ax1 = host_subplot(111)

    host.ignore_mean = ignore_mean
    host_rvs = host.rv_at_times(t_space)
    ax1.plot(t_space - t_start, host_rvs, label="Host", lw=2, color="k")
    # Determine rv max amplitudes.
    amp1 = host.max_amp()
    # Adjust axis limits
    ax1.set_ylim(host.gamma - (amp1 * 1.1), host.gamma + (amp1 * 1.1))
    ax1.axhline(host.gamma, color="black", linestyle="-.", alpha=0.5)
    ax1.set_xlabel("Days from {!s}".format(start_string))
    ax1.set_ylabel("Host RV (km/s)")

    if companion_present:
        companion.ignore_mean = ignore_mean
        companion_rvs = companion.rv_at_times(t_space)
        companion_label = generate_companion_label(companion)
        ax2 = ax1.twinx()
        ax2.plot(t_space - t_start, companion_rvs, '--', label=companion_label, lw=2)
        # Adjust axis limits
        amp2 = companion.max_amp()
        # Determine rv max amplitudes.
        ax2.set_ylim(companion.gamma - (amp2 * 1.1), companion.gamma + (amp2 * 1.1))
        ax2.axhline(companion.gamma, color="black", linestyle="-.", alpha=0.5)
        ax2.set_ylabel("Companion RV (km/s)")

    if t_past:
        t_past = np.asarray(t_past)
        rv_star = host.rv_at_times(t_past)
        ax1.plot(t_past - t_start, rv_star, "b.", markersize=10, markeredgewidth=2, label="Host past")
        if companion_present:
            rv_planet = companion.rv_at_times(t_past)
            ax2.plot(t_past - t_start, rv_planet, "r+", markersize=10, markeredgewidth=2, label="Comp past")

    if t_future:
        t_future = np.asarray(t_future)
        rv_star = host.rv_at_times(t_future)
        ax1.plot(t_future - t_start, rv_star, "ko", markersize=10, markeredgewidth=2, label="Host future")
        if companion_present:
            rv_planet = companion.rv_at_times(t_future)
            ax2.plot(t_future - t_start, rv_planet, "g*", markersize=10, markeredgewidth=2, label="Comp future")

    if 'name' in host._params.keys():
        if ("companion" in host._params.keys()) and (companion_present):
            plt.title("Radial Velocity Curve for {} {}".format(host._params['name'].upper(), host._params['companion']))
        else:
            plt.title("Radial Velocity Curve for {}".format(host._params['name'].upper()))
    else:
        plt.title("Radial Velocity Curve")
    plt.legend(loc=0)

    return fig
def test_julian_date_to_and_frm_str_starting_from_str(input, format):
    assert JulianDate.from_str(input, format).to_str(format) == input
def test_JulainDate_now():
    assert np.allclose(JulianDate.now().jd, ephem.julian_date(ephem.now()))
def test_julian_date_to_str(input, expected):
    jd = JulianDate(input)
    format = "%Y-%m-%d"
    assert jd.to_str(format) == expected
def test_julian_date_to_and_frm_str_starting_from_jd(input):
    assert JulianDate.from_str(JulianDate(input).to_str()).jd == input
def test_JulianDate_from_str(date, expected):
    jd = JulianDate.from_str(date)
    assert np.allclose(jd.jd, expected)
    assert np.allclose(jd.jd, ephem.julian_date(date))
def test_JulianDate_from_str_to_datetime(datestr, dtime):
    jd = JulianDate.from_str(datestr)
    assert abs(jd.to_datetime() -
               datetime.datetime(*dtime)) < datetime.timedelta(seconds=1)
def test_julian_date_to_and_frm_str_starting_from_jd(input):
    assert JulianDate.from_str(JulianDate(input).to_str()).jd == input
def test_julian_date_to_str(input, expected):
    jd = JulianDate(input)
    format = "%Y-%m-%d"
    assert jd.to_str(format) == expected
def test_julian_date_to_and_frm_str_starting_from_str(input, format):
    assert JulianDate.from_str(input, format).to_str(format) == input
def test_JulianDate_from_datetime(date, expected):
    d = datetime.datetime(*date)
    jd = JulianDate.from_datetime(d)
    assert np.allclose(jd.jd, expected)
    assert np.allclose(jd.jd, ephem.julian_date(d))
    assert isinstance(jd.to_datetime(), datetime.datetime)
def test_JulianDate_to_datetime(jd, expected):
    jd = JulianDate(jd)
    assert abs(jd.to_datetime() - datetime.datetime(*expected)) < datetime.timedelta(seconds=1)
    assert isinstance(jd, JulianDate)
    assert isinstance(jd.to_datetime(), datetime.datetime)
def test_prereduced_JulianDate_to_datetime(jd, expected):
    jd = JulianDate(jd, reduced=True)
    jd.reduce()
    assert abs(jd.to_datetime() - datetime.datetime(*expected)) < datetime.timedelta(seconds=1)
    assert isinstance(jd, JulianDate)
def test_JulainDate_now():
    assert np.allclose(JulianDate.now().jd, ephem.julian_date(ephem.now()))
def test_JulianDate_from_datetime(date, expected):
    d = datetime.datetime(*date)
    jd = JulianDate.from_datetime(d)
    assert np.allclose(jd.jd, expected)
    assert np.allclose(jd.jd, ephem.julian_date(d))
    assert isinstance(jd.to_datetime(), datetime.datetime)
Exemple #23
0
def binary_time_curve(host,
                      companion,
                      cycle_fraction=1,
                      ignore_mean=False,
                      t_past=False,
                      t_future=False,
                      start_day=None):
    # type: (RV, RV, float, bool, Any, Any, Any) -> int
    """Plot RV phase curve centered on zero.

    Parameters
    ----------
    host: RV
        RV class for system.
    cycle_fraction: float
        Minimum Fraction of orbit to plot. (Default=1)
    ignore_mean: bool
        Remove the contribution from the systems mean velocity. (Default=False)
    t_past: float, array-like
        Times of past observations in julian days.
    t_future: float, array-like
        Times of future observations  in julian days.
    start_day: str
        Day to being RV curve from in julian days. The Default=None sets the start time to ephem.now().

    Returns
    -------
    exit_status: bool
        Returns 0 if successful.

        Displays matplotlib figure.
    """
    companion_present = companion is not None
    t_start = start_day if start_day is not None else JulianDate.now().jd
    # Make curve from start of t_past
    print("t_past", t_past, "t_future", t_future)
    if isinstance(t_past, float):
        obs_start = t_past
    elif t_past != [] and t_past is not None:
        obs_start = np.min(t_past)
    else:
        obs_start = t_start

    if isinstance(t_future, float):
        obs_end = t_future
    elif t_future != [] and t_future is not None:
        obs_end = np.max(t_future)
    else:
        obs_end = t_start
    # Specify 100 points per period
    num_cycles = ((t_start + host.period * cycle_fraction) -
                  np.min([t_start, obs_start])) / host.period
    num_points = np.ceil(500 * num_cycles)
    if num_points > 10000:
        logging.debug("num points = {}".format(num_points))
        raise ValueError("num_points is to large")

    t_space = np.linspace(
        min([t_start, obs_start]),
        np.max([t_start + host.period * cycle_fraction, obs_end]), num_points)

    start_dt = JulianDate(t_start).to_datetime()
    if (start_dt.hour == 0) and (start_dt.minute == 0) and (start_dt.second
                                                            == 0):
        start_string = datetime.strftime(start_dt, "%Y-%m-%d")
    else:
        start_string = datetime.strftime(
            start_dt, "%Y-%m-%d %H:%M:%S")  # Issue with 00:00:01 not appearing

    fig = plt.figure(figsize=(10, 7))
    fig.subplots_adjust()
    ax1 = host_subplot(111)

    host.ignore_mean = ignore_mean
    host_rvs = host.rv_at_times(t_space)
    ax1.plot(t_space - t_start, host_rvs, label="Host", lw=2, color="k")
    # Determine rv max amplitudes.
    amp1 = host.max_amp()
    # Adjust axis limits
    ax1.set_ylim(host.gamma - (amp1 * 1.1), host.gamma + (amp1 * 1.1))
    ax1.axhline(host.gamma, color="black", linestyle="-.", alpha=0.5)
    ax1.set_xlabel("Days from {!s}".format(start_string))
    ax1.set_ylabel("Host RV (km/s)")

    if companion_present:
        companion.ignore_mean = ignore_mean
        companion_rvs = companion.rv_at_times(t_space)
        companion_label = generate_companion_label(companion)
        ax2 = ax1.twinx()
        ax2.plot(t_space - t_start,
                 companion_rvs,
                 '--',
                 label=companion_label,
                 lw=2)
        # Adjust axis limits
        amp2 = companion.max_amp()
        # Determine rv max amplitudes.
        ax2.set_ylim(companion.gamma - (amp2 * 1.1),
                     companion.gamma + (amp2 * 1.1))
        ax2.axhline(companion.gamma, color="black", linestyle="-.", alpha=0.5)
        ax2.set_ylabel("Companion RV (km/s)")

    if t_past:
        t_past = np.asarray(t_past)
        rv_star = host.rv_at_times(t_past)
        ax1.plot(t_past - t_start,
                 rv_star,
                 "b.",
                 markersize=10,
                 markeredgewidth=2,
                 label="Host past")
        if companion_present:
            rv_planet = companion.rv_at_times(t_past)
            ax2.plot(t_past - t_start,
                     rv_planet,
                     "r+",
                     markersize=10,
                     markeredgewidth=2,
                     label="Comp past")

    if t_future:
        t_future = np.asarray(t_future)
        rv_star = host.rv_at_times(t_future)
        ax1.plot(t_future - t_start,
                 rv_star,
                 "ko",
                 markersize=10,
                 markeredgewidth=2,
                 label="Host future")
        if companion_present:
            rv_planet = companion.rv_at_times(t_future)
            ax2.plot(t_future - t_start,
                     rv_planet,
                     "g*",
                     markersize=10,
                     markeredgewidth=2,
                     label="Comp future")

    if 'name' in host._params.keys():
        if ("companion" in host._params.keys()) and (companion_present):
            plt.title("Radial Velocity Curve for {} {}".format(
                host._params['name'].upper(), host._params['companion']))
        else:
            plt.title("Radial Velocity Curve for {}".format(
                host._params['name'].upper()))
    else:
        plt.title("Radial Velocity Curve")
    plt.legend(loc=0)

    return fig
def test_JulianDate_reduce_jd_to_datetime(expected, julian_date):
    jd = JulianDate(julian_date)
    jd.reduce()
    assert abs(jd.to_datetime() -
               datetime.datetime(*expected)) < datetime.timedelta(seconds=1)
def test_JulianDate_from_str_to_datetime(datestr, dtime):
    jd = JulianDate.from_str(datestr)
    assert abs(jd.to_datetime() - datetime.datetime(*dtime)) < datetime.timedelta(seconds=1)
Exemple #26
0
def main(params, mode="phase", obs_times=None, obs_list=None, date=None,
         cycle_fraction=1, phase_center=0, save_only=False):  # obs_times=None, mode='phase', rv_diff=None
    # type: (Dict[str, Union[str, float]], str, List[str], str, str, bool) -> None
    r"""Radial velocity displays.

    Parameters
    ----------
    params: str
        Filename for text file containing the rv parameters. Format of 'param = value\n'.
    mode: str
        Mode for script to use. Phase, time, future.
    obs_times: list of str
        Dates of observations added manually at command line of format YYYY-MM-DD.
    obs_list: str
        Filename for list which contains obs_times (YYY-MM-DD HH:MM:SS).
    date: str
        Reference date for some modes. Defaults=None)
    """

    # Load in params and store as a dictionary
    parameters = parse_paramfile(params)

    parameters = prepare_mass_params(parameters, only_msini=True)

    parameters = check_core_parameters(parameters)

    # combine obs_times and obs_list and turn into jd.
    if obs_times:
        if (".txt" in obs_times) or (".dat" in obs_times):
            raise ValueError("Filename given instead of dates for obs_times.")

    obs_times = join_times(obs_times, obs_list)
    obs_jd = strtimes2jd(obs_times)

    test_jd = obs_jd[0] if isinstance(obs_jd, (list, tuple)) else obs_jd

    if ((str(parameters["tau"]).startswith("24") and not str(test_jd).startswith("24")) or
        (not(str(parameters["tau"]).startswith("24")) and str(test_jd).startswith("24"))):
        raise ValueError("Mismatch between Tau parameter '{0}' and times used '{1}'.".format(parameters["tau"], obs_jd))

    date_split = JulianDate.now().jd if date is None else JulianDate.from_str(date).jd
    # Slit past and future obs
    future_obs = [obs for obs in obs_jd if obs > date_split]
    past_obs = [obs for obs in obs_jd if obs <= date_split]

    host_orbit = RV.from_dict(parameters)
    companion_orbit = host_orbit.create_companion()

    if mode == "phase":
        fig = binary_phase_curve(host_orbit, companion_orbit, t_past=past_obs,
                                 t_future=future_obs,
                                 cycle_fraction=cycle_fraction,
                                 phase_center=phase_center)
    elif mode == "time":
        fig = binary_time_curve(host_orbit, companion_orbit, t_past=past_obs,
                                start_day=date_split, t_future=future_obs,
                                cycle_fraction=cycle_fraction)
    else:
        raise NotImplementedError("Other modes are not Implemented yet.")
    if not save_only:
        fig.show()

    return fig
def test_JulianDate_from_str(date, expected):
    jd = JulianDate.from_str(date)
    assert np.allclose(jd.jd, expected)
    assert np.allclose(jd.jd, ephem.julian_date(date))
Exemple #28
0
def main(params,
         mode="phase",
         obs_times=None,
         obs_list=None,
         date=None,
         cycle_fraction=1,
         phase_center=0,
         save_only=False):  # obs_times=None, mode='phase', rv_diff=None
    # type: (Dict[str, Union[str, float]], str, List[str], str, str, bool) -> None
    r"""Radial velocity displays.

    Parameters
    ----------
    params: str
        Filename for text file containing the rv parameters. Format of 'param = value\n'.
    mode: str
        Mode for script to use. Phase, time, future.
    obs_times: list of str
        Dates of observations added manually at command line of format YYYY-MM-DD.
    obs_list: str
        Filename for list which contains obs_times (YYY-MM-DD HH:MM:SS).
    date: str
        Reference date for some modes. Defaults=None)
    """

    # Load in params and store as a dictionary
    parameters = parse_paramfile(params)

    parameters = prepare_mass_params(parameters, only_msini=True)

    parameters = check_core_parameters(parameters)

    # combine obs_times and obs_list and turn into jd.
    if obs_times:
        if (".txt" in obs_times) or (".dat" in obs_times):
            raise ValueError("Filename given instead of dates for obs_times.")

    obs_times = join_times(obs_times, obs_list)
    obs_jd = strtimes2jd(obs_times)

    test_jd = obs_jd[0] if isinstance(obs_jd, (list, tuple)) else obs_jd

    if ((str(parameters["tau"]).startswith("24")
         and not str(test_jd).startswith("24"))
            or (not (str(parameters["tau"]).startswith("24"))
                and str(test_jd).startswith("24"))):
        raise ValueError(
            "Mismatch between Tau parameter '{0}' and times used '{1}'.".
            format(parameters["tau"], obs_jd))

    date_split = JulianDate.now().jd if date is None else JulianDate.from_str(
        date).jd
    # Slit past and future obs
    future_obs = [obs for obs in obs_jd if obs > date_split]
    past_obs = [obs for obs in obs_jd if obs <= date_split]

    host_orbit = RV.from_dict(parameters)
    companion_orbit = host_orbit.create_companion()

    if mode == "phase":
        fig = binary_phase_curve(host_orbit,
                                 companion_orbit,
                                 t_past=past_obs,
                                 t_future=future_obs,
                                 cycle_fraction=cycle_fraction,
                                 phase_center=phase_center)
    elif mode == "time":
        fig = binary_time_curve(host_orbit,
                                companion_orbit,
                                t_past=past_obs,
                                start_day=date_split,
                                t_future=future_obs,
                                cycle_fraction=cycle_fraction)
    else:
        raise NotImplementedError("Other modes are not Implemented yet.")
    if not save_only:
        fig.show()

    return fig
def test_JulianDate_reduce_jd_to_datetime(expected, julian_date):
    jd = JulianDate(julian_date)
    jd.reduce()
    assert abs(jd.to_datetime() - datetime.datetime(*expected)) < datetime.timedelta(seconds=1)