def test_catshtm_redshift(requests_mock):
    alerce = Alerce()
    requests_mock.register_uri(
        "GET",
        alerce.config["CATSHTM_API_URL"] +
        alerce.config["CATSHTM_ROUTES"]["crossmatch_all"],
        json=COSSMATCH_ALL_RESPONSE,
    )
    r = alerce.catshtm_redshift(ra=357.73373, dec=14.20514, radius=10)
    assert r is not None
def test_catshtm_crossmatch_catalog(requests_mock):
    alerce = Alerce()
    requests_mock.register_uri(
        "GET",
        alerce.config["CATSHTM_API_URL"] +
        alerce.config["CATSHTM_ROUTES"]["crossmatch"],
        json=CROSSMATCH_CATALOG_RESPONSE,
    )
    r = alerce.catshtm_crossmatch(ra=357.73373,
                                  dec=14.20514,
                                  radius=10,
                                  format="pandas",
                                  catalog_name="2MASS")
    assert r is not None
def test_catshtm_conesearch_all(requests_mock):
    alerce = Alerce()
    requests_mock.register_uri(
        "GET",
        alerce.config["CATSHTM_API_URL"] +
        alerce.config["CATSHTM_ROUTES"]["conesearch_all"],
        json=CONESEARCH_ALL_RESPONSE,
    )
    r = alerce.catshtm_conesearch(ra=357.73373,
                                  dec=14.20514,
                                  radius=10,
                                  format="pandas",
                                  catalog_name="all")
    assert r is not None
Beispiel #4
0
from unittest.mock import Mock, patch
from requests import Session
from requests import Response
from pandas import DataFrame
from astropy.table import Table
import sys
import pytest

sys.path.append("..")
from alerce.core import Alerce
from alerce.exceptions import ObjectNotFoundError, FormatValidationError, ParseError

alerce = Alerce()


@patch.object(Session, "request")
def test_query_objects(mock_request):
    mock_request.return_value.status_code = 200
    r = alerce.query_objects(classifier="late")
    assert r is not None


@patch.object(Session, "request")
def test_query_objects_not_found(mock_request):
    mock_request.return_value.status_code = 404
    with pytest.raises(ObjectNotFoundError):
        alerce.query_objects(classifier="late")


@patch.object(Session, "request")
def test_query_objects_parser_error(mock_request):
def test_exception_stamp(mock_fits):
    alerce = Alerce()
    with pytest.warns(RuntimeWarning):
        r = alerce.plot_stamps(oid="ZTF18abjpdlh", candid="570448435315010001")
        assert r is None
def test_get_stamp(mock_fits):
    alerce = Alerce()
    r = alerce.get_stamps(oid="ZTF18abjpdlh", candid="570448435315010000")
    assert isinstance(r, HDUList)
def test_plot_stamp():
    alerce = Alerce()
    with pytest.warns(RuntimeWarning):
        r = alerce.plot_stamps(oid="ZTF18abjpdlh", candid="570448435315010000")
        assert r is None
class SNParametricForecast(Resource):
    """
        Supernova Parametric Model.
    """
    client = Alerce()
    extractor = SNParametricModelExtractor(bands=[1, 2])

    def check_object(self, oid):
        try:
            object = self.client.query_object(oid, format="pandas")
            object = object.iloc[0]
            return object
        except ObjectNotFoundError:
            return abort(404,
                         'Not Found',
                         errors='Object ID not found in ALeRCE database')

    def mjd_now(self):
        now_datetime = datetime.datetime.utcnow()
        astro_time = Time(now_datetime)
        return astro_time.mjd

    def shift_mjd(self, mjd, days=0):
        mjd += days
        return mjd

    def fit_parameters(self, oid):
        detections = self.client.query_detections(oid, format="pandas")
        detections["oid"] = oid
        detections.set_index("oid", inplace=True)
        params = self.extractor.compute_features(detections)
        return params

    def clean_response(self, values):
        new_values = []
        for value in values:
            if np.isnan(value):
                new_values.append(value)
            else:
                new_values.append(value)
        return new_values

    def get_parameters(self, oid):
        try:
            features = self.client.query_features(oid, format="pandas")
            if len(features) == 0:
                raise Exception("Features not found, fitting model")
            params = features[features.name.isin(MODEL_PARAMS)]
            return True, params
        except Exception:
            # Fitting model and getting params
            params = self.fit_parameters(oid).iloc[0]

            # Renaming index and getting fid
            fids = [int(i.rsplit("_", 1)[1]) for i in params.index]
            params.index = [i.rsplit("_", 1)[0] for i in params.index]

            # Transforming to dataframe and resetting index
            params = params.to_frame()
            params.reset_index(inplace=True)
            # Setting new column names
            params.columns = ["name", "value"]

            # Adding fid
            params["fid"] = fids
            return False, params

    def infer(self, params, mjd):
        flux_forecast = model_inference(mjd, params.SPM_A, params.SPM_t0,
                                        params.SPM_gamma, params.SPM_beta,
                                        params.SPM_tau_rise,
                                        params.SPM_tau_fall)
        magnitude_forecast = flux_to_mag(flux_forecast)
        return magnitude_forecast

    @api.marshal_with(parametric_response)
    @api.expect(parametric_parser)
    def get(self):
        args = parametric_parser.parse_args()
        object = self.check_object(args.oid)
        min_mjd = object["firstmjd"]
        if not args.mjd:
            forecast_mjd = np.array([self.mjd_now()])
        else:
            forecast_mjd = np.array(args.mjd)
        shifted_mjd = forecast_mjd - min_mjd
        features_on_db, parameters = self.get_parameters(args.oid)
        message = "Forecast based on modified Villar et al. 2019. analytic model"
        message += " (see [https://arxiv.org/abs/1905.07422] and [https://arxiv.org/abs/2008.03311]). "
        if features_on_db:
            message += "Using precomputed ALeRCE [http://alerce.science] parameters."
        else:
            message += "On-demand parameters computed in ALeRCE [http://alerce.science] API."
            message += " Warning: This forecast was made with few points."

        forecasts = []
        for fid in parameters.fid.unique():
            fid_params = parameters[parameters.fid == fid]
            fid_params.set_index("name", inplace=True)
            fid_params = fid_params.value
            magpsf = self.infer(fid_params, shifted_mjd)
            forecasts.append({
                'magpsf': self.clean_response(magpsf),
                'mjd': forecast_mjd,
                'fid': fid,
            })

        return {'oid': args.oid, "forecast": forecasts, "comment": message}
def test_error(requests_mock):
    alerce = Alerce()
    requests_mock.register_uri("GET", "mock://test.com", status_code=500)
    with pytest.raises(APIError):
        alerce._request_catshtm("GET", "mock://test.com")
Beispiel #10
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self._client = Alerce()