Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main' into 21_login-squash
Browse files Browse the repository at this point in the history
  • Loading branch information
mcauley-penney committed Mar 16, 2023
2 parents 1c02d03 + 77c668c commit acbde2d
Show file tree
Hide file tree
Showing 9 changed files with 258 additions and 206 deletions.
2 changes: 1 addition & 1 deletion api/main/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def get_env_variable(name: str) -> str | None:
async_mode="eventlet",
logger=True,
max_http_buffer_size=10**20,
ping_timeout=60,
ping_timeout=60
)

# Set variables from .env to global scope
Expand Down
101 changes: 56 additions & 45 deletions api/main/file_writing/views.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
"""TODO."""

from datetime import datetime, timedelta, timezone
from datetime import date, datetime, timedelta, timezone
import math
import pickle
import os
from astropy.io import fits

from . import file_writer
from .. import DATA_FILEPATH, db, sio
from ..models.observation import Observation, headers_to_db_cols
Expand All @@ -14,7 +17,7 @@ def index():


@sio.on("save_img")
def submit_data(image_data: dict):
def submit_data(serial_image, exposure_data: dict):
"""
Save observation image data to FITS file format.
Expand All @@ -30,56 +33,56 @@ def submit_data(image_data: dict):
# TODO: return error message
return

timestr_fmt = "%Y-%m-%d %X:%f"
timestr_fmt = "%Y-%m-%dT%X.%f"
file_date_fmt = "%Y%m%d"

image = image_data["image"]
exposure_data = image_data["exposure_data"]
image = pickle.loads(serial_image)

# calculate needed headers
time_difference = timedelta(weeks=26)
cur_date = datetime.now(timezone.utc)
filename_prefix = f"{cur_date}_{exposure_data['OBSID']}.fits"
exposure_data["date_obs"] = cur_date.strftime(timestr_fmt)
exposure_data["date_made_open_source"] = (cur_date + time_difference).strftime(timestr_fmt)
date_obs: datetime = datetime.strptime(exposure_data["DATE-OBS"], timestr_fmt)
exposure_data["date_made_open_source"] = (date_obs + time_difference).strftime(timestr_fmt)

# create specialized FITS file name
date_obs_file_prefix = datetime.strftime(date_obs, file_date_fmt)
padded_id = str(exposure_data['OBSID']).zfill(4)
fits_path_head = f"{date_obs_file_prefix}.{padded_id}"


# ensure path to fits directory exists
fits_dir = os.path.dirname(DATA_FILEPATH)

if not os.path.exists(fits_dir):
os.makedirs(fits_dir)

fits_path = f"{fits_dir}/{filename_prefix}"
fits_path = f"{fits_dir}/{fits_path_head}.fits"


# make fits file - add headers and such
hdu = fits.PrimaryHDU(image)
hdu = fits.PrimaryHDU(image, uint=True)

# airmass: will compute; 1/cos(altitude)
# can use astropy.units, "45*units.deg.to(u.rad)"
# NOTE: make sure that altitude in radians, NOT DEGREES
hdu.header["AIRM"] = 0
hdu = populate_headers(hdu, exposure_data, fits_path_head)

# from camera
hdu.header["CCD-TEMP"] = 0
hdu.header["GAIN"] = 0
hdu.header["GAMMA"] = 0
# write this fits file to disk
hdu.writeto(fits_path, overwrite=True)

# selected at user interface, e.g. dark, flat
hdu.header["IMAGETYP"] = 0
# At this point, there is a row in the database for
# this observation, but it is essentially a receipt
# that indicates an observation is in action. We must
# update that row with the data gained from the finished
# observation.
db_data: dict = headers_to_db_cols(hdu.header, exposure_data)

# Shelyak
hdu.header["INSTRUME"] = 0
cur_observation = Observation.query.filter_by(id=exposure_data["OBSID"]).first()
cur_observation.set_attrs(db_data)

# name of file without fits extension
hdu.header["LOGID"] = 0
db.session.commit()

# DATE-OBS in numerical form: will receive script
hdu.header["MJDOBS"] = 0
# TODO: return success message
return "Success"

# potentially camera
hdu.header["OFFSET"] = 0

# camera
hdu.header["ROWORDER"] = 0

def populate_headers(hdu, exposure_data, filename):

hdu.header["OBSERVER"] = "Joe Llama"
hdu.header["OBSID"] = exposure_data["OBSID"]
Expand All @@ -89,6 +92,8 @@ def submit_data(image_data: dict):
"flat": "Flat",
"thar": "ThAr",
}[exposure_data["observation_type"]]
hdu.header["DATE-OBS"] = exposure_data["DATE-OBS"]
hdu.header["DATE-END"] = exposure_data["DATE-END"]

if hdu.header["OBSTYPE"] == "Object":
hdu.header["OBJECT"] = exposure_data["object"]
Expand All @@ -100,20 +105,26 @@ def submit_data(image_data: dict):
hdu.header["DEC"] = "00:00:00.00"
hdu.header["ALT"] = 0

# write this fits file to disk
hdu.writeto(fits_path)
# airmass
hdu.header["AIRM"] = 1 / math.cos(exposure_data["altitude"])
hdu.header["INSTRUME"] = "Shelyak"

# At this point, there is a row in the database for
# this observation, but it is essentially a receipt
# that indicates an observation is in action. We must
# update that row with the data gained from the finished
# observation.
db_data: dict = headers_to_db_cols(hdu.header)
# TODO: from camera, currently unset
hdu.header["GAMMA"] = 0
hdu.header["ROWORDER"] = 0

cur_observation = Observation.query.filter_by(id=exposure_data["OBSID"]).first()
cur_observation.set_attrs(db_data)
# TODO: confirm that "Temperature" in ZWO ASI is CCD-TEMP
hdu.header["CCD-TEMP"] = exposure_data["CCD-TEMP"]
hdu.header["GAIN"] = exposure_data["GAIN"]
hdu.header["IMAGETYP"] = exposure_data["IMAGETYP"]
hdu.header["OFFSET"] = exposure_data["OFFSET"]

db.session.commit()
# name of file without fits extension
hdu.header["LOGID"] = filename

# TODO: return success message
return {}
# TODO: DATE-OBS in numerical form: will receive script
hdu.header["MJDOBS"] = 0

hdu.header["EXPTIME"] = exposure_data["exposure_duration"]

return hdu
5 changes: 3 additions & 2 deletions api/main/logsheet/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ def handle_chat(data):
dbQuery = Observation.query.all()

for row in dbQuery:
data.append(str(row).split("|"))
emit("retrieveLogsheetData", data)
data.insert(0, list(row))

emit("retrieveLogsheetData", data)
54 changes: 27 additions & 27 deletions api/main/models/observation.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,31 @@
from datetime import datetime, timedelta, timezone
from main import db
from . import logsheet


def headers_to_db_cols(obs_data) -> dict:
def headers_to_db_cols(headers, obs_data) -> dict:
headers = {
"id": obs_data["OBSID"],
"observer": obs_data["OBSERVER"],
"obs_type": obs_data["OBSTYPE"],
}

# owner_id = obs_data[""]
#
# date_made_open_source = obs_data[""]
# exp_time = obs_data[""]
# ccd_temp = obs_data[""]
# image_typ = obs_data[""]
# gain = obs_data[""]
# offset = obs_data[""]
# gamma = obs_data[""]
# date_obs = obs_data[""]
# instrume = obs_data[""]
# roworder = obs_data["ROWORDER"]
# object_name = obs_data[""]
"id": headers["OBSID"],
"observer": headers["OBSERVER"],
"obs_type": headers["OBSTYPE"],
"date_made_open_source": obs_data["date_made_open_source"],
"exp_time": headers["EXPTIME"],
"ccd_temp": headers["CCD-TEMP"],
"image_typ": headers["IMAGETYP"],
"gain": headers["GAIN"],
"offset": headers["OFFSET"],
"date_obs": headers["DATE-OBS"],
"instrume": headers["INSTRUME"],
"roworder": headers["ROWORDER"],
"object_name": headers["OBJECT"],
"airm": headers["AIRM"],
"obs_id": headers["OBSID"],
"log_id": headers["LOGID"],
"mjdobs": headers["MJDOBS"],

# airm = obs_data[""]
# obs_id = obs_data[""]
# log_id = obs_data[""]
# mjdobs = obs_data[""]
# TODO: need to determine if we need these and get them
# "owner_id" = obs_data[""],
# "gamma": headers[""],
}

return headers

Expand All @@ -49,20 +47,22 @@ class Observation(db.Model):
instrume = db.Column(db.String)
log_id = db.Column(db.String)
mjdobs = db.Column(db.Float)
object_name = db.Column("object", db.String)
object = db.Column(db.String)
obs_id = db.Column(db.String)
obs_type = db.Column(db.String)
observer = db.Column(db.String)
offset = db.Column(db.Float)
owner_id = db.Column(db.Integer)
reworder = db.Column(db.String)


def __init__(self, init_dict):
self.set_attrs(init_dict)

def __repr__(self):
return f"{self.object_name} was observed on {self.date_obs} by {self.observer}"
return f"{self.object} was observed on {self.date_obs} by {self.observer}"

def __iter__(self):
return iter([self.id, self.object, "In Progress", str(self.date_obs), "None"])

def set_attrs(self, attrs: dict):
for key, val in attrs.items():
Expand Down
16 changes: 16 additions & 0 deletions api/main/observations/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,19 @@ def post_observation():
# order number should be the last number in the table of
# all past orders.
return {}


@observations.post("/end")
def end_observation():
sio.emit("end_exposure")

last_observation = Observation.query.order_by(-Observation.id).limit(1).first()
db.session.delete(last_observation)
db.session.commit()

return {}


@sio.on("observation_complete")
def update_request_form():
sio.emit("enable_request_form")
5 changes: 3 additions & 2 deletions api/main/resolve/views.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Endpoints related to resolving celestial targets."""

from flask import request
from .. import sio
from . import resolve, utils


Expand All @@ -16,4 +15,6 @@ def resolve_target():
resolution_input: dict = request.get_json()
celestial_body: str = resolution_input["object"]

return utils.query_for_target(celestial_body)
resolution_input.update(utils.query_for_target(celestial_body))

return resolution_input
Loading

0 comments on commit acbde2d

Please sign in to comment.