Skip to content

Commit 2a9e2d6

Browse files
authored
Helper functions to check and get things from lookup tables (#152)
* get_db_publication and test * get_db_regime and tests * get_db_instrument and tests * ingest_instrument improvements
1 parent 321da96 commit 2a9e2d6

File tree

9 files changed

+452
-198
lines changed

9 files changed

+452
-198
lines changed

astrodb_utils/__init__.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
from .utils import ( # noqa: F401
66
AstroDBError,
77
exit_function,
8-
ingest_instrument,
98
internet_connection,
109
load_astrodb,
1110
)
@@ -15,7 +14,7 @@
1514

1615

1716

18-
logger = logging.getLogger("astrodb_utils")
17+
logger = logging.getLogger(__name__) # Sets up the parent "astrodb_utils" logger
1918

2019
LOGFORMAT = logging.Formatter(
2120
"%(levelname)-8s - %(name)-15s - %(message)s")
@@ -30,7 +29,7 @@
3029
handler.setFormatter(LOGFORMAT)
3130
logger.addHandler(handler)
3231

33-
logger.info(f"Logger initialized: {logger.name}")
34-
logger.info(f"Logger level: {logging.getLevelName(logger.getEffectiveLevel()) }")
32+
logger.setLevel(logging.INFO) # Set the default logging level to INFO
33+
logger.debug(f"Logger level: {logging.getLevelName(logger.getEffectiveLevel()) }")
3534

3635
warnings.filterwarnings("ignore", module="astroquery.simbad")

astrodb_utils/instruments.py

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
import logging
2+
3+
import sqlalchemy.exc
4+
from sqlalchemy import and_
5+
6+
from astrodb_utils import AstroDBError, exit_function
7+
8+
__all__ = [
9+
"ingest_instrument",
10+
"get_db_instrument"
11+
]
12+
13+
logger = logging.getLogger(__name__)
14+
15+
16+
def ingest_instrument(db, *, telescope=None, instrument=None, mode=None, raise_error=True):
17+
"""
18+
Script to ingest instrumentation
19+
TODO: Add option to ingest references for the telescope and instruments
20+
21+
Parameters
22+
----------
23+
db: astrodbkit.astrodb.Database
24+
Database object created by astrodbkit
25+
telescope: str
26+
instrument: str
27+
mode: str
28+
29+
Returns
30+
-------
31+
32+
None
33+
34+
"""
35+
36+
# Make sure enough inputs are provided
37+
if telescope is None and (instrument is None or mode is None):
38+
msg = "Telescope, Instrument, and Mode must be provided"
39+
logger.error(msg)
40+
raise AstroDBError(msg)
41+
42+
msg_search = f"Searching for {telescope}, {instrument}, {mode} in database"
43+
logger.debug(msg_search)
44+
45+
# Search for the inputs in the database
46+
telescope_db = (
47+
db.query(db.Telescopes).filter(db.Telescopes.c.telescope == telescope).table()
48+
)
49+
mode_db = (
50+
db.query(db.Instruments)
51+
.filter(
52+
and_(
53+
db.Instruments.c.mode == mode,
54+
db.Instruments.c.instrument == instrument,
55+
db.Instruments.c.telescope == telescope,
56+
)
57+
)
58+
.table()
59+
)
60+
61+
if len(telescope_db) == 1 and len(mode_db) == 1:
62+
msg_found = (
63+
f"{telescope}-{instrument}-{mode} is already in the database. Nothing added."
64+
)
65+
logger.info(msg_found)
66+
return
67+
68+
# Ingest telescope entry if not already present
69+
if telescope is not None and len(telescope_db) == 0:
70+
telescope_add = [{"telescope": telescope}]
71+
try:
72+
with db.engine.connect() as conn:
73+
conn.execute(db.Telescopes.insert().values(telescope_add))
74+
conn.commit()
75+
msg_telescope = f"{telescope} was successfully ingested in the database"
76+
logger.info(msg_telescope)
77+
except sqlalchemy.exc.IntegrityError as e: # pylint: disable=invalid-name
78+
msg =f"Telescope could not be ingested: {telescope}"
79+
logger.error(msg)
80+
raise AstroDBError(msg) from e
81+
82+
# Ingest instrument+mode (requires telescope) if not already present
83+
if (
84+
telescope is not None
85+
and instrument is not None
86+
and mode is not None
87+
and len(mode_db) == 0
88+
):
89+
instrument_add = [
90+
{"instrument": instrument, "mode": mode, "telescope": telescope}
91+
]
92+
try:
93+
with db.engine.connect() as conn:
94+
conn.execute(db.Instruments.insert().values(instrument_add))
95+
conn.commit()
96+
msg_instrument = f"{telescope}-{instrument}-{mode} was successfully ingested in the database."
97+
logger.info(msg_instrument)
98+
except sqlalchemy.exc.IntegrityError as e: # pylint: disable=invalid-name
99+
msg = "Instrument/Mode could not be ingested: {telescope}-{instrument}-{mode} "
100+
logger.error(msg)
101+
raise AstroDBError(msg) from e
102+
103+
return
104+
105+
106+
def get_db_instrument(db, instrument=None, mode=None, telescope=None):
107+
instrument_table = (
108+
db.query(db.Instruments)
109+
.filter(
110+
and_(
111+
db.Instruments.c.instrument.contains(instrument),
112+
db.Instruments.c.telescope.contains(telescope),
113+
)
114+
)
115+
.table()
116+
)
117+
118+
if len(instrument_table) > 1: # constrain query with instrument mode
119+
instrument_table = (
120+
db.query(db.Instruments)
121+
.filter(
122+
and_(
123+
db.Instruments.c.instrument.contains(instrument),
124+
db.Instruments.c.mode.ilike(mode),
125+
db.Instruments.c.telescope.contains(telescope),
126+
)
127+
)
128+
.table()
129+
)
130+
131+
if len(instrument_table) == 1:
132+
if (
133+
instrument_table["instrument"][0] != instrument
134+
or instrument_table["mode"][0] != mode
135+
or instrument_table["telescope"][0] != telescope
136+
):
137+
msg = (
138+
f"Instrument {instrument} with mode {mode} and telescope {telescope} "
139+
f"matched to {instrument_table['instrument'][0]}-{instrument_table['mode'][0]}-{instrument_table['telescope'][0]}. "
140+
)
141+
logger.warning(msg)
142+
143+
return (
144+
instrument_table["instrument"][0],
145+
instrument_table["mode"][0],
146+
instrument_table["telescope"][0],
147+
)
148+
149+
if len(instrument_table) == 0:
150+
msg = f"{telescope}-{instrument}-{mode}, not found in database. Please add it to the Instruments table."
151+
else:
152+
msg = f"Multiple matches found for {telescope}-{instrument}-{mode}. Please check the Instruments table."
153+
154+
exit_function(msg, raise_error=True, return_value=None)

astrodb_utils/photometry.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@
1212

1313
from astrodb_utils import (
1414
AstroDBError,
15-
ingest_instrument,
1615
internet_connection,
1716
)
17+
from astrodb_utils.instruments import ingest_instrument
1818
from astrodb_utils.publications import find_publication
1919
from astrodb_utils.sources import find_source_in_db
2020

0 commit comments

Comments
 (0)