Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tickets/DM-47601: Add sync dof script #251

Open
wants to merge 9 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/news/DM-47601.perf.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
In set_dof.py script add ability to synchronize dof with state of a specific dayobs and sequence number.
160 changes: 159 additions & 1 deletion python/lsst/ts/standardscripts/maintel/set_dof.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,23 @@

__all__ = ["SetDOF"]

import os

import numpy as np
import yaml
from astropy.time import Time, TimeDelta
from lsst_efd_client import EfdClient

from .apply_dof import ApplyDOF

STD_TIMEOUT = 30

EFD_SERVER_URL = dict(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

these are not URLs, so please, rename this something else. Maybe EFD_NAMES?

tucson="tucson_teststand_efd",
base="base_efd",
summit="summit_efd",
)


class SetDOF(ApplyDOF):
"""Set absolute positions DOF to the main telescope, either bending
Expand All @@ -42,11 +55,156 @@ class SetDOF(ApplyDOF):

"""

@classmethod
def get_schema(cls):
schema_yaml = """
$schema: http://json-schema.org/draft-07/schema#
$id: https://github.com/lsst-ts/ts_standardscripts/maintel/SetDOF.yaml
title: SetDOF v1
description: Configuration for SetDOF.
type: object
properties:
day:
description: Day obs to be used for synchronizing the state.
type: number
default: null
seq:
description: Sequence number to be used for synchronizing the state.
type: number
default: null
anyOf:
- required:
- day
- seq
- required:
- dofs
additionalProperties: false
"""
schema_dict = yaml.safe_load(schema_yaml)

base_schema_dict = super(ApplyDOF, cls).get_schema()

for prop in base_schema_dict["properties"]:
schema_dict["properties"][prop] = base_schema_dict["properties"][prop]

return schema_dict

async def configure(self, config) -> None:
"""Configure script.

Parameters
----------
config : `types.SimpleNamespace`
Script configuration, as defined by `schema`.
"""
super(ApplyDOF, self).configure(config)

if hasattr(config, "day") and hasattr(config, "seq"):
self.day = config.day
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so, self.day and self.seq are only created here and later you try to access them. consider doing:

self.day = getattr(config, "day", None)
self.seq = getattr(config, "seq", None)

self.seq = config.seq

async def get_image_time(self, client, day, seq):
"""Get the image time from the given day and sequence number.

Parameters
----------
day : `int`
Day obs to be used for synchronizing the state.
seq : `int`
Sequence number to be used for synchronizing the state.

Returns
-------
end_time : `astropy.time.Time`
End time of the image.

Raises
------
RuntimeError
Error querying time for image {day}:{seq}.
"""
try:
query = f"""
SELECT "imageDate", "imageNumber"
FROM "efd"."autogen"."lsst.sal.CCCamera.logevent_endReadout"
WHERE imageDate =~ /{day}/ AND imageNumber = {seq}
"""
end_time = await client.influx_client.query(query)
return Time(end_time.iloc[0].name)
except Exception:
raise RuntimeError(f"Error querying time for image {day}:{seq}.")

async def get_last_issued_state(self, client, end_time):
"""Get the state from the given day and sequence number.

Parameters
----------
time : `datetime.datetime`
Initial time to query.

Returns
-------
state : `dict`
State of the system.
"""

topics = [f"aggregatedDoF{i}" for i in range(50)]
lookback_interval = TimeDelta(1, format="jd")
state = await client.select_time_series(
"lsst.sal.MTAOS.logevent_degreeOfFreedom",
topics,
end_time - lookback_interval,
end_time,
)

if not state.empty:
state = state.iloc[[-1]]
return state.values.squeeze()
else:
self.log.warning("No state found.")
return np.zeros(50)

async def get_efd_name(self) -> str:
"""Get the EFD name.

Returns
-------
efd_name : `str`
EFD name.

Raises
------
RuntimeError
Wrong EFd name
"""
site = os.environ.get("LSST_SITE")
if site is None or site not in EFD_SERVER_URL:
message = (
"LSST_SITE environment variable not defined"
if site is None
else (f"No image server url for {site=}.")
)
raise RuntimeError("Wrong EFD name: " + message)
else:
return EFD_SERVER_URL[site]

async def run(self) -> None:
"""Run script."""
"""Run script.

Raises
------
RuntimeError
Unable to connect to EFD.
"""
# Assert feasibility
await self.assert_feasibility()

if self.day is not None and self.seq is not None:
efd_name = await self.get_efd_name()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why don't you move all this to a method and here you just do:

if self.day is not None and self.seq is not None:
    self.dofs = await self.get_last_issued_state()

?

client = EfdClient(efd_name)
image_end_time = self.get_image_time(client, self.day, self.seq)
self.dofs = self.get_last_issued_state(client, image_end_time)

await self.checkpoint("Setting DOF...")
current_dof = await self.mtcs.rem.mtaos.evt_degreeOfFreedom.aget(
timeout=STD_TIMEOUT
Expand Down
Loading