Skip to content

Commit

Permalink
Fixs for building docs etc
Browse files Browse the repository at this point in the history
  • Loading branch information
ceb8 committed Oct 25, 2023
1 parent ef736b4 commit 2faac54
Show file tree
Hide file tree
Showing 8 changed files with 134 additions and 91 deletions.
13 changes: 8 additions & 5 deletions astroquery/esa/neocc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,14 @@ class Conf(_config.ConfigNamespace):

BASE_URL = 'https://' + os.getenv('NEOCC_PORTAL_IP', default='neo.ssa.esa.int')

API_URL = _config.ConfigItem(BASE_URL + '/PSDB-portlet/download?file=')
API_URL = _config.ConfigItem(BASE_URL + '/PSDB-portlet/download?file=',
"Main API URL")

EPHEM_URL = _config.ConfigItem(BASE_URL + '/PSDB-portlet/ephemerides?des=')
EPHEM_URL = _config.ConfigItem(BASE_URL + '/PSDB-portlet/ephemerides?des=',
"Ephermerides URL")

SUMMARY_URL = _config.ConfigItem(BASE_URL + '/search-for-asteroids?sum=1&des=')
SUMMARY_URL = _config.ConfigItem(BASE_URL + '/search-for-asteroids?sum=1&des=',
"Object summary URL")

TIMEOUT = 60

Expand All @@ -31,6 +34,6 @@ class Conf(_config.ConfigNamespace):

conf = Conf()

from .core import neocc, ESAneoccClass
from .core import neocc, NEOCCClass

__all__ = ['neocc', 'ESAneoccClass', 'Conf', 'conf']
__all__ = ['neocc', 'NEOCCClass', 'Conf', 'conf']
89 changes: 40 additions & 49 deletions astroquery/esa/neocc/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,11 @@

from astroquery.esa.neocc import lists, tabs

__all__ = ['neocc', 'ESAneoccClass']
__all__ = ['neocc', 'NEOCCClass']


@async_to_sync
class ESAneoccClass(BaseQuery):
class NEOCCClass(BaseQuery):
"""
Class to init ESA NEOCC Python interface library
"""
Expand Down Expand Up @@ -130,7 +130,9 @@ def query_list(list_name):
return neocc_list

@staticmethod
def query_object(name, tab, **kwargs):
def query_object(name, tab, *,
orbital_elements=None, orbit_epoch=None,
observatory=None, start=None, stop=None, step=None, step_unit=None):
"""Get requested object data from ESA NEOCC.
Parameters
Expand All @@ -141,22 +143,27 @@ def query_object(name, tab, **kwargs):
Name of the request tab. Valid names are: summary,
orbit_properties, physical_properties, observations,
ephemerides, close_approaches and impacts.
**kwargs : str
Tabs orbit_properties and ephemerides tabs required additional
arguments to work:
* *orbit_properties*: the required additional arguments are:
* *orbital_elements* : str (keplerian or equinoctial)
* *orbit_epoch* : str (present or middle)
* *ephemerides*: the required additional arguments are:
* *observatory* : str (observatory code, e.g. '500', 'J04', etc.)
* *start* : str (start date in YYYY-MM-DD HH:MM)
* *stop* : str (end date in YYYY-MM-DD HH:MM)
* *step* : str (time step, e.g. '2', '15', etc.)
* *step_unit* : str (e.g. 'days', 'minutes', etc.)
orbital_elements : str
Additional required argument for "orbit_properties" table.
Valid arguments are: keplerian, equinoctial
orbit_epoch : str
Additional required argument for "orbit_properties" table.
Valid arguments are: present, middle
observatory : str
Additional required argument for "ephemerides" table.
Observatory code, e.g. '500', 'J04', etc.
start : str
Additional required argument for "ephemerides" table.
Start date in YYYY-MM-DD HH:MM
stop : str
Additional required argument for "ephemerides" table.
End date in YYYY-MM-DD HH:MM
step : str
Additional required argument for "ephemerides" table.
Time step, e.g. '2', '15', etc.
step_unit : str
Additional required argument for "ephemerides" table.
Unit for time step e.g. 'days', 'minutes', etc.
Returns
-------
Expand Down Expand Up @@ -387,22 +394,14 @@ def query_object(name, tab, **kwargs):

# Orbit properties
elif tab == 'orbit_properties':
# Raise error if no elements are provided
if 'orbital_elements' not in kwargs:
raise KeyError('Please specify type of orbital_elements: '
'keplerian or equinoctial '
'(e.g., orbital_elements="keplerian")')

# Raise error if no epoch is provided
if 'orbit_epoch' not in kwargs:
raise KeyError('Please specify type of orbit_epoch: '
'present or middle '
'(e.g., orbit_epoch="middle")')

# Raise error if elements or epoch are not provided
if not all([orbital_elements, orbit_epoch]):
raise KeyError(("orbital_elements and orbit_epoch must be specified"
"for an orbit_properties query."))

# Get URL to obtain the data from NEOCC
url = tabs.get_object_url(name, tab,
orbital_elements=kwargs['orbital_elements'],
orbit_epoch=kwargs['orbit_epoch'])
url = tabs.get_object_url(name, tab, orbital_elements=orbital_elements, orbit_epoch=orbit_epoch)

# Request data two times if the first attempt fails
try:
Expand All @@ -423,21 +422,13 @@ def query_object(name, tab, **kwargs):

# Ephemerides
elif tab == 'ephemerides':
# Create dictionary for kwargs
args_dict = {'observatory': 'observatory (e.g., observatory="500")',
'start': 'start date (e.g., start="2021-05-17 00:00")',
'stop': 'end date (e.g., stop="2021-05-18 00:00")',
'step': 'time step (e.g., step="1")',
'step_unit': 'step unit (e.g., step_unit="days")'}

# Check if any kwargs is missing
for element in args_dict:
if element not in kwargs:
raise KeyError(f'Please specify {args_dict[element]} for ephemerides.')

resp_str = tabs.get_ephemerides_data(name, observatory=kwargs['observatory'],
start=kwargs['start'], stop=kwargs['stop'],
step=kwargs['step'], step_unit=kwargs['step_unit'])

if not all([observatory, start, stop, step, step_unit]):
raise KeyError(("Ephemerides queries require the following arguments:"
"observatory, start, stop, step, and step_unit"))

resp_str = tabs.get_ephemerides_data(name, observatory=observatory, start=start, stop=stop,
step=step, step_unit=step_unit)
neocc_obj = tabs.parse_ephemerides(resp_str)

elif tab == 'summary':
Expand All @@ -450,4 +441,4 @@ def query_object(name, tab, **kwargs):
return neocc_obj


neocc = ESAneoccClass()
neocc = NEOCCClass()
1 change: 0 additions & 1 deletion astroquery/esa/neocc/tabs.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,6 @@ def parse_observations(resp_str, verbose=False):
"""
Parse the close approach response string into the close approach tables.
TODO: document properly.
Parameters
----------
resp_str : str
Expand Down
38 changes: 32 additions & 6 deletions astroquery/esa/neocc/test/test_neocc.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import os
import re
import pytest
import warnings

import numpy as np
import requests
Expand Down Expand Up @@ -54,7 +55,6 @@ def get_mockreturn(name, timeout=TIMEOUT, verify=VERIFICATION):
# Split name (the requested url) to obtain the name of the file location stored in \data

fileloc = name.split(r'=')[1]
print(fileloc)

# Exception for ephemerides
if '&oc' in fileloc:
Expand All @@ -63,6 +63,7 @@ def get_mockreturn(name, timeout=TIMEOUT, verify=VERIFICATION):
filename = data_path(fileloc)
with open(filename, 'rb') as FLE:
content = FLE.read()
content = content.replace(b"\r", b"") # For windows tests

return MockResponse(content)

Expand All @@ -86,7 +87,12 @@ def test_bad_list_names():

def check_table_structure(data_table, table_len, table_cols, float_cols=[], int_cols=[], str_cols=[], time_cols=[]):
"""
TODO
Given a data table, checks:
- Table length matches given table_len
- Table column names match the given table_cols list
- All the columns with indices given in float_cols are of float type
- Equivalent checks for int_cols, and string_cols
- Checks that columns with indices given in time_cols are `~astropy.time.Time` objects
"""

table_cols = np.array(table_cols)
Expand All @@ -96,15 +102,20 @@ def check_table_structure(data_table, table_len, table_cols, float_cols=[], int_

assert all([x == y for x, y in zip(data_table.colnames, table_cols)])

assert all([data_table[x].dtype == np.dtype('float64') for x in table_cols[float_cols]])
assert all([data_table[x].dtype == np.dtype('int64') for x in table_cols[int_cols]])
assert all([data_table[x].dtype.type == np.str_ for x in table_cols[str_cols]])
# Ignore the FutureWarning that only comes up with the oldest dependencies
warnings.filterwarnings("ignore", category=FutureWarning,
message="Conversion of the second argument of issubdtype*")
assert all([np.issubdtype(data_table[x].dtype, float) for x in table_cols[float_cols]])
assert all([np.issubdtype(data_table[x].dtype, int) for x in table_cols[int_cols]])
assert all([np.issubdtype(data_table[x].dtype, str) for x in table_cols[str_cols]])

assert all([isinstance(data_table[x], Time) for x in table_cols[time_cols]])


def check_table_values(data_table, true_value_dict):
"""
TODO
Checks data_table rows against true values given in true_value_dict.
The format of true_value_dict is {<row number>: [true row data], ...}
"""

for row, values in true_value_dict.items():
Expand Down Expand Up @@ -178,8 +189,11 @@ def test_parse_nea(patch_get):
assert re.match(r'\w{3} \w{3} \d{2} \d{2}:\d{2}:\d{2} \w{3} \d{4}', monthly_update["NEA"][0])


@pytest.mark.filterwarnings('ignore:ERFA function *:erfa.core.ErfaWarning')
def test_parse_risk(patch_get):
"""Check data: risk_list, risk_list_special
Ignore ERFA 'dubious year' warnings because they are expected.
"""
# Risk and risk special lists
risk_list = neocc.neocc.query_list("risk_list")
Expand Down Expand Up @@ -293,8 +307,11 @@ def test_parse_pri(patch_get):
check_table_values(faint_list, faint_dict)


@pytest.mark.filterwarnings('ignore:ERFA function *:erfa.core.ErfaWarning')
def test_parse_encounter(patch_get):
"""Check data: encounter_list
Ignore ERFA 'dubious year' warnings because they are expected.
"""

encounter_list = neocc.neocc.query_list("close_encounter")
Expand Down Expand Up @@ -377,8 +394,11 @@ def check_tab_result_basic(results, num_tabs):
assert len(results) == num_tabs


@pytest.mark.filterwarnings('ignore:ERFA function *:erfa.core.ErfaWarning')
def test_tabs_impacts(patch_get):
"""Check data: asteroid impacts tab
Ignore ERFA 'dubious year' warnings because they are expected.
"""

# 433 Eros has no tab "impacts"
Expand Down Expand Up @@ -418,8 +438,11 @@ def test_tabs_impacts(patch_get):
check_table_values(impact_table, impact_dict)


@pytest.mark.filterwarnings('ignore:ERFA function *:erfa.core.ErfaWarning')
def test_tabs_close_approach(patch_get):
"""Check data: asteroid close approaches tab
Ignore ERFA 'dubious year' warnings because they are expected.
"""

# Check opbject with no close approaches
Expand Down Expand Up @@ -503,8 +526,11 @@ def test_tabs_physical_properties(patch_get):
check_table_values(phys_props, phys_dict)


@pytest.mark.filterwarnings('ignore:ERFA function *:erfa.core.ErfaWarning')
def test_tabs_observations(patch_get):
"""Check data: asteroid observations tab
Ignore ERFA 'dubious year' warnings because they are expected.
"""

with pytest.raises(ValueError):
Expand Down
Loading

0 comments on commit 2faac54

Please sign in to comment.