astra.observatory#
Observatory Control System for Autonomous Astronomical Operations.
This module provides the core Observatory class for managing and controlling astronomical observatories. It handles device coordination, safety monitoring, automated observations, and data acquisition for professional astronomical facilities.
- The module integrates multiple subsystems including:
Alpaca-compatible device drivers for telescopes, cameras, and accessories
Real-time safety and weather monitoring systems
Automated observation schedule execution
Database logging and FITS header management
Thread-safe multiprocessing architecture
- Key Components:
Observatory: Main control class for observatory operations
Device Management: Alpaca protocol device coordination
Safety Systems: Weather monitoring and error handling
Scheduling: Automated observation execution
Calibration: Automated flat, dark, and bias frame acquisition
Pointing & Guiding: Telescope pointing correction and guiding
- Usage:
This module is typically used as part of the ASTRA observatory automation framework. The Observatory class is instantiated with a configuration file and then manages all aspects of observatory operation.
Note
This software is designed for professional astronomical observatories. Proper configuration of safety systems is essential to prevent equipment damage and ensure personnel safety.
Classes
|
Autonomous astronomical observatory control system. |
- class astra.observatory.Observatory(config_filename: Path | str, truncate_factor: float | None = None, logging_level: int = logging.INFO)[source]#
Bases:
objectAutonomous astronomical observatory control system.
The Observatory class provides comprehensive control and automation for astronomical observatories, managing telescopes, cameras, filter wheels, focusers, domes, and other equipment. It coordinates complex observation sequences, safety monitoring, device management, and data acquisition for autonomous or semi-autonomous operation.
- Key Features:
Multi-device coordination and control via Alpaca protocol
Autonomous observation scheduling and execution
Real-time safety monitoring and weather assessment
Automated calibration sequences (flats, darks, bias frames)
Autoguiding and pointing correction capabilities
Comprehensive error handling and recovery
Database logging of all operations and device states
FITS header management and metadata completion
Thread-safe multiprocessing architecture
- Observatory Operations:
Schedule-driven autonomous observations
Real-time device monitoring and polling
Safety watchdog with weather integration
Automatic dome and telescope control
Image acquisition and processing pipelines
Pointing model generation and refinement
Focus maintenance and autofocus routines
Calibration frame acquisition
- Safety Systems:
Continuous weather monitoring integration
Device health checking and error detection
Automatic observatory closure on unsafe conditions
- Architecture:
Thread-based concurrent operations
Database-backed logging and state persistence
Queue-based multiprocessing communication
Configuration-driven device management
Modular sequence and action execution
- Usage:
Typically instantiated with a configuration file that defines the observatory layout, device connections, safety parameters, and operational settings. The observatory can then be operated manually or through automated scheduling.
Note
This class is designed for professional astronomical observatories and requires proper configuration of safety systems and device drivers. Improper use could result in equipment damage or safety hazards.
Initialize the Observatory object.
Sets up the observatory configuration, database, logging, device management, and scheduling systems. Creates a queue for multiprocessing and initializes all necessary attributes for observatory operations.
- Parameters:
config_filename (str) – Path to the configuration file for the observatory. The filename is used to derive the observatory name.
truncate_factor (float | None, optional) – If specified, the schedule is truncated by a factor and moved to the current time. Defaults to None.
- database_manager#
Manages the observatory database.
- Type:
- logger#
Logger instance for the observatory.
- Type:
- _config#
Observatory configuration object.
- Type:
- fits_config#
FITS header configuration.
- Type:
pd.DataFrame
- thread_manager#
Manages threads for observatory operations.
- Type:
- queue#
Multiprocessing queue for communication.
- Type:
Queue
- property config: ObservatoryConfig#
Get the observatory configuration, reloading if the file has been modified.
This property provides access to the observatory configuration and automatically reloads it if the underlying configuration file has been modified since the last access.
- Returns:
ObservatoryConfig – The current observatory configuration object.
Note
If the configuration is reloaded, devices may need to be restarted
- get_observatory_location(telescope_name: str | None = None) EarthLocation | None[source]#
Get observatory location for a telescope, using cache when available.
This method caches the EarthLocation object to avoid repeated ASCOM calls. If telescope_name is not provided, uses the first available telescope.
- Parameters:
telescope_name – Name of the telescope to get location for. If None, uses first telescope.
- Returns:
EarthLocation object or None if no telescope available or location cannot be retrieved.
- property image_handler: ImageHandler#
Get the ImageHandler instance for image processing and FITS header management.
DEPRECATED for multi-camera observatories. Use get_image_handler(camera_name) instead.
This property provides backward compatibility but will raise an error if multiple ImageHandlers are active (indicating multi-camera use). For new code, use get_image_handler(camera_name) to explicitly specify which camera’s ImageHandler to retrieve.
- Returns:
ImageHandler – The current ImageHandler instance.
- Raises:
ValueError – If multiple ImageHandlers are active or if no ImageHandler is initialized.
- get_image_handler(camera_name: str) ImageHandler[source]#
Get the ImageHandler for a specific camera.
- Parameters:
camera_name (str) – The name of the camera device.
- Returns:
ImageHandler – The ImageHandler instance for the specified camera.
- Raises:
ValueError – If ImageHandler for the specified camera is not initialized.
- connect_all_devices()[source]#
Connect to all loaded devices and start polling for FITS header data.
Establishes connections to all initialized devices and begins regular polling of device properties needed for FITS headers. Different polling intervals are used based on device criticality: - Most devices: 5-second intervals - SafetyMonitor: 1-second intervals for safety-critical data
The method: 1. Connects to all devices in the devices dictionary 2. Starts polling threads for non-fixed FITS header properties 3. Sets up special high-frequency polling for safety monitors 4. Starts the watchdog process after all connections are established
- Raises:
Exception – Device connection errors are logged and added to error_source, but do not prevent other devices from being connected.
Note
SPECULOOS observatories skip focuser connection due to compatibility issues
A 1-second delay is added after connections before starting the watchdog to ensure devices are ready
- start_watchdog() None[source]#
Start the observatory watchdog monitoring thread.
Initializes and starts a daemon thread that runs the watchdog() method to continuously monitor observatory safety, weather conditions, device health, and system status. The watchdog is essential for autonomous operation and safety.
The method: 1. Checks if watchdog is already running to prevent duplicates 2. Creates a new daemon thread running the watchdog() method 3. Adds the thread to the threads list for tracking
Note
If watchdog is already running, logs a warning and returns
The watchdog thread is marked as a daemon thread
The thread is automatically tracked in the observatory’s thread list
- watchdog() None[source]#
Main observatory monitoring loop for safety and operational status.
Continuously monitors critical observatory systems and takes appropriate actions to ensure safe and efficient operation. The watchdog is the central control system that coordinates all observatory activities.
See class docstring for full behavior.
- update_heartbeat() None[source]#
Update the observatory heartbeat with current system status information.
Creates a comprehensive status snapshot of the observatory including system health, device status, resource usage, and operational state. This heartbeat information is used for monitoring and debugging observatory operations.
The heartbeat includes: - Current timestamp with millisecond precision - Error status and error source details - Weather safety status - Schedule execution status - System resource usage (CPU, memory, disk) - Active thread information - Device polling status for all connected devices - Monitor action queue status
This information is typically used by: - External monitoring systems - Web interfaces for observatory status - Debugging and troubleshooting - Health check systems
Note
Called regularly by the watchdog to maintain current status
Provides real-time snapshot of observatory state
Essential for remote monitoring of autonomous operations
- open_observatory(paired_devices: dict | None = None) None[source]#
Open the observatory for observations in a safe, controlled sequence.
Performs the complete observatory opening sequence, ensuring safety at each step: 1. Opens dome shutter (if present and weather is safe) 2. Unparks telescope (if present and weather is safe) 3. Handles SPECULOOS-specific error acknowledgment and polling management
The sequence only proceeds if weather conditions are safe and no errors are present. For SPECULOOS observatories, special error handling and polling management is performed.
- Parameters:
paired_devices (dict, optional) – Dictionary specifying which specific devices to use for the opening sequence. If None, uses all available devices of each type. Defaults to None.
- Safety Checks:
Weather safety verification before each major operation
Error-free status confirmation
SPECULOOS-specific error acknowledgment and recovery
Note
SPECULOOS observatories pause polling during critical operations
Opening sequence is aborted if unsafe conditions develop
Telescope readiness is verified after unparking for SPECULOOS systems
- _wait_for_telescopes_ready()[source]#
Poll Astelco TELESCOPE.READY_STATE until ready or timeout per telescope.
- close_observatory(paired_devices: PairedDevices | None = None, error_sensitive: bool = True) bool[source]#
Close the observatory in a safe, controlled sequence.
Performs the complete observatory shutdown sequence to ensure equipment safety and protection from weather. The sequence follows this order: 1. Stop any active guiding operations 2. Stop telescope slewing and tracking 3. Park the telescope to safe position 4. Park the dome and close shutter (if dome present)
For SPECULOOS observatories, includes special error handling and polling management during the closure sequence.
- Parameters:
paired_devices (dict, optional) – Dictionary specifying which specific devices to use for the closing sequence. Format: {‘Telescope’: ‘TelescopeName’, ‘Dome’: ‘DomeName’} If None, uses all available devices. Defaults to None.
error_sensitive (bool, optional) – If True, the closure process is sensitive to system errors. If False, attempts closure even with errors present. Defaults to True.
- Returns:
bool – True if the closure sequence completed successfully.
Note
SPECULOOS observatories pause polling during critical operations
Dome errors are acknowledged before attempting closure
Critical for protecting equipment during unsafe weather conditions
- toggle_robotic_switch() None[source]#
Toggle the observatory’s robotic operation mode on or off.
Controls the robotic switch that enables or disables autonomous observatory operations. When enabled, the observatory can execute schedules automatically. When disabled, manual control is required for all operations.
Behavior: - If robotic switch is currently ON: Turns it OFF and stops any running schedule - If robotic switch is currently OFF: Turns it ON and starts the schedule
(if watchdog is running)
Safety Features: - Requires watchdog to be running before enabling robotic mode - Automatically stops schedule execution when disabling robotic mode - Logs all state changes for monitoring and debugging
Note
Essential safety feature for autonomous operations
Provides manual override capability for emergency situations
Schedule execution is dependent on robotic switch being enabled
- start_schedule() None[source]#
Start the observatory schedule execution in a new thread.
Initializes and starts a dedicated daemon thread for executing the loaded schedule. Performs various safety and readiness checks before starting schedule execution to ensure safe autonomous operation.
Pre-execution Checks: - Schedule must be loaded - Schedule must not already be running - Watchdog must be running for safety monitoring - Schedule end time must be in the future - No duplicate schedule threads allowed
Thread Management: - Creates a daemon thread running run_schedule() - Resets the ‘completed’ flag on all schedule items - Adds thread to the observatory’s thread tracking list - Thread ID ‘schedule’ for easy identification
Safety Features: - Multiple validation checks prevent unsafe execution - Automatic thread cleanup if conditions not met - Logging of all start attempts and failures
Note
Schedule execution continues until completion or safety conditions fail
Essential component of autonomous observatory operations
Coordinates with watchdog for continuous safety monitoring
- run_schedule() None[source]#
Execute the observatory schedule while monitoring safety and operational conditions.
Manages the execution of scheduled observatory activities in a continuous loop, ensuring safety conditions are met before starting each action. The scheduler coordinates multiple concurrent operations while maintaining system safety.
Key features: - Waits for weather safety confirmation before starting - Iterates through schedule rows checking timing and conditions - Starts actions in separate threads for concurrent execution - Handles both weather-dependent and weather-independent operations - Manages thread lifecycle and cleanup - Performs final header completion after schedule ends
Safety Management: - Monitors weather_safe, error_free, and watchdog_running status - Aborts operations if unsafe conditions develop - Times out if weather safety check takes longer than 2 minutes
Thread Management: - Removes completed threads from tracking list - Prevents duplicate actions from starting - Ensures proper cleanup on schedule completion
Note
Schedule must be loaded before calling this method
Method runs until schedule completion or safety conditions fail
Automatically starts final header completion thread on exit
- run_action(action: Action) None[source]#
Execute the action specified in the schedule (Action object).
- Parameters:
action (Action) – The action object to execute.
- Raises:
Exception – Any unexpected error that occurs during execution.
Notes
For ‘object’, ‘calibration’, or ‘flats’ action types, specialized sequences are executed based on the action_type.
For ‘open’ action type, the function may turn on camera cooler, set temperature, and open the observatory dome.
For ‘close’ action type, the function may close the observatory dome.
For other action types, the function assumes it’s an ASCOM command and attempts to execute it on the specified device.
- cool_camera(device_name: str, set_temperature: float, temperature_tolerance: float = 1, cooling_timeout: int = 30) None[source]#
Cool a camera to the specified temperature.
Activates the camera cooler and sets the target temperature with specified tolerance. This is typically done before imaging sequences to reduce thermal noise and ensure consistent camera performance.
- Parameters:
device_name (str) – Name of the camera device to be cooled.
set_temperature (float) – Target temperature in degrees Celsius for the camera CCD.
temperature_tolerance (float, optional) – Acceptable temperature deviation from target in degrees Celsius. Defaults to 1.
cooling_timeout (int, optional) – Time in minutes to wait for cooling before raising error. Defaults to 30.
Process: 1. Turns on the camera cooler 2. Sets the target CCD temperature with specified tolerance 3. Waits up to cooling_timeout for temperature stabilization
Safety Features: - Not weather sensitive (can operate in unsafe weather) - Continuous monitoring until target temperature reached - Configurable timeout for temperature stabilization
Note
Essential for scientific imaging to reduce thermal noise
Temperature stabilization can take significant time
Used in camera cooling sequences and before observations
- pre_sequence(action: Action, paired_devices: dict | PairedDevices) None[source]#
Prepare the observatory and metadata for a sequence.
This method is responsible for preparing the observatory and gathering necessary information before running a sequence. Depending on the parameters in the action value in the inputted row, it can move the telescope to specificed (ra, dec) coordinates, and the filter wheel to the specified filter. It also creates a directory for the sequence images and writes a header with relevant information.
- Parameters:
action (Action) – An Action object containing information about the action to be performed.
paired_devices (dict) – A list of paired devices required for the sequence.
- setup_observatory(paired_devices: PairedDevices | dict, action_value: BaseActionConfig, filter_list_index: int = 0) None[source]#
Prepares the observatory for a sequence by performing necessary setup actions.
- Parameters:
paired_devices (dict) – A dictionary specifying paired devices for the sequence.
action_value (dict) – A dictionary containing information about the action to be performed.
filter_list_index (int, optional) – The index of the filter in the filter list (default is 0).
This method prepares the observatory for a sequence by performing the following steps:
- If the action value contains ‘ra’ and ‘dec’ keys, it will:
open_observatory(paired_devices)
Set telescope tracking to true
Slew telescope to the specified target coordinates.
- If the action value contains ‘filter’ key, it will:
Setting the filter wheel to the specified filter position.
Notes
This method relies on certain conditions like weather safety, error-free operation, and no interruptions.
The ‘paired_devices’ dictionary should specify devices required for the sequence.
- _setup_camera_subframe(camera, action_value: BaseActionConfig, paired_devices: PairedDevices) None[source]#
Configure camera subframe (Region of Interest) settings.
This method calculates and sets the ASCOM camera subframe parameters (StartX, StartY, NumX, NumY) based on the action_value configuration.
- Parameters:
camera – Camera device object with ASCOM properties
action_value – Action configuration containing subframe parameters
paired_devices – PairedDevices object for logging
- Subframe Parameters from action_value:
subframe_width: Width in binned pixels
subframe_height: Height in binned pixels
subframe_center_x: Horizontal center position (0.0-1.0, 0.5=center)
subframe_center_y: Vertical center position (0.0-1.0, 0.5=center)
- ASCOM Camera Properties Set:
StartX: Left edge in unbinned pixels (from sensor origin)
StartY: Top edge in unbinned pixels (from sensor origin)
NumX: Width in binned pixels
NumY: Height in binned pixels
- Raises:
ValueError – If subframe dimensions exceed sensor size
Exception – If camera doesn’t support subframing or properties can’t be set
Note
StartX/StartY are in unbinned pixels
NumX/NumY are in binned pixels
Coordinates use sensor origin (typically top-left corner)
Bounds checking ensures subframe fits within sensor after binning
- wait_for_slew(paired_devices: PairedDevices) None[source]#
Wait for telescope slewing operation to complete.
Monitors the telescope’s slewing status and blocks until the slew operation is finished. Includes safety condition checking and timeout protection to prevent infinite waiting.
- Parameters:
paired_devices (PairedDevices) – Object containing the telescope device to monitor for slewing completion.
Safety Features: - Continuous condition checking during wait (weather, errors, schedule) - Automatic timeout protection (prevents infinite loops) - 1-second settle time after slew completion
Process: 1. Checks initial slewing status 2. Logs slewing start if telescope is moving 3. Polls slewing status with safety condition checks 4. Waits for slewing to complete 5. Adds settle time for mechanical stabilization
Note
Critical for ensuring telescope positioning accuracy
Safety conditions are checked continuously during wait
Settle time allows for mechanical vibrations to dampen
- check_conditions(action: Action | None = None) bool[source]#
Check if current conditions allow safe execution of observatory operations.
Evaluates multiple safety and operational conditions to determine if an action or sequence can proceed safely. Different action types have different condition requirements based on their weather sensitivity.
- Parameters:
action (Action, optional) – The action object containing action_type, start_time, and end_time. If None, only base conditions are checked. Defaults to None.
- Returns:
bool –
- True if all required conditions are met for the operation,
False if any condition fails.
Base Conditions (always checked): - error_free: No system errors present - schedule_running: Schedule execution is active - watchdog_running: Safety monitoring is active
Action-Specific Conditions: - Weather-sensitive actions (open, object, flats, autofocus, calibrate_guiding,
pointing_model): Also require weather_safe
Weather-independent actions (calibration, close, cool_camera, complete_headers): Only require base conditions
Time-sensitive actions: Must be within scheduled start/end time window
Note
Used throughout the system for safety checks
Different actions have different safety requirements
Critical for preventing unsafe operations during bad weather
- perform_exposure(camera: AlpacaDevice, exptime, maxadu, action: Action, use_light=True, log_option=None, maximal_sleep_time=0.1, sequence_counter: int = 0, wcs=None) tuple[bool, Path | None][source]#
Execute a camera exposure and handle image acquisition.
Performs a complete camera exposure sequence including exposure start, monitoring, and image saving. Handles both light and dark frames with appropriate header information and file management.
- Parameters:
camera (AlpacaDevice) – The camera device to use for exposure.
exptime (float) – Exposure time in seconds.
maxadu (int) – Maximum ADU value for the camera.
action (Action) – The action object containing action_type and device_name.
use_light (bool, optional) – Whether to use light during exposure. False for dark frames. Defaults to True.
log_option (str, optional) – Additional text for logging messages. Defaults to None.
maximal_sleep_time (float, optional) – Maximum sleep interval during image ready polling. Defaults to 0.1 seconds.
sequence_counter (int, optional) – Sequence number for the image in a series. Defaults to 0.
wcs (WCS, optional) – World Coordinate System solution for the image. Defaults to None.
- Returns:
tuple –
- A tuple containing:
bool: True if exposure was successful, False otherwise
Path or None: Path to saved image file, None if failed
Note
Monitors conditions continuously during exposure
Handles exposure timing and image readiness polling
Automatically saves image with appropriate filename and headers
Sets proper IMAGETYP header based on action type and use_light
- image_sequence(action: Action, paired_devices: PairedDevices) None[source]#
Execute a sequence of astronomical images with a camera.
Runs a complete imaging sequence including observatory setup, multiple exposures with various exposure times, pointing correction, and optional guiding. Handles both object imaging and calibration sequences.
- Parameters:
row (dict) – Schedule row containing sequence information including: - device_name: Camera device to use - action_type: Type of sequence (‘object’ or ‘calibration’) - start_time/end_time: Sequence timing constraints - action_value: Sequence parameters (exposure times, filters, etc.)
paired_devices (PairedDevices) – Object containing all devices needed for the sequence (camera, telescope, filter wheel, etc.)
Sequence Features: - Pre-sequence setup (telescope pointing, filter selection) - Multiple exposure time support - Automatic pointing correction for object sequences - Optional autoguiding activation and management - Continuous condition monitoring throughout sequence
Process Flow: 1. Pre-sequence setup (telescope pointing, filters, headers) 2. Iterate through exposure time list 3. Perform pointing correction (object sequences only) 4. Start guiding if configured 5. Execute exposures with safety monitoring 6. Stop guiding and telescope tracking at completion
Note
Supports both single and multiple exposure times
Automatically handles different sequence types
Coordinates telescope, camera, and filter wheel operations
Essential for all astronomical imaging operations
- pointing_model_sequence(action: Action, paired_devices: PairedDevices) None[source]#
Execute a pointing model sequence to improve telescope pointing accuracy.
Generates a systematic series of sky positions and captures images at each location to build or refine a telescope pointing model. The sequence creates a spiral pattern of points from zenith down to a specified altitude, avoiding positions too close to the Moon.
- Parameters:
action (Action) – Schedule action containing sequence information.
paired_devices (dict) – Dictionary of paired devices for the sequence, including telescope and camera.
- Action Value Parameters (from row[‘action_value’]):
‘n’ (int, optional): Number of pointing positions. Defaults to 20.
‘exptime’ (float, optional): Exposure time in seconds. Defaults to 1.
Additional standard action parameters (ra, dec, etc.)
Process: 1. Creates pointing_model directory for image storage 2. Generates spiral pattern of sky coordinates from zenith 3. For each position (if not too close to Moon):
Slews telescope to target coordinates
Takes exposure with specified parameters
Performs pointing correction to measure error
Updates FITS header with correction information
Continues until all positions are captured or conditions change
Safety Features: - Continuous condition checking during sequence - Moon avoidance for accurate measurements - Error handling for individual pointing failures
Note
Critical for maintaining high telescope pointing accuracy
Results improve automated observation precision
Typically run during commissioning or maintenance periods
- pointing_correction(action: Action, filepath: str | Path | None, paired_devices: PairedDevices, dark_frame: str | Path | None = None, sync: bool = False, slew: bool = True) tuple[bool, WCS | None][source]#
Perform telescope pointing correction based on an acquired image.
Uses plate solving to determine the actual pointing position from a captured image and corrects the telescope pointing if the error exceeds the configured threshold. Supports both sync-only and slew corrections.
- Parameters:
action (Action) – The action object containing action_type, start_time, end_time, and action_value with target coordinates.
filepath (str | Path) – Path to the FITS image file for plate solving.
paired_devices (PairedDevices) – Object containing telescope and other devices for the correction.
dark_frame (str | Path | None, optional) – Path to a dark frame for calibration. Defaults to None (no dark subtraction).
sync (bool, optional) – If True, only sync the telescope without slewing. Defaults to False.
slew (bool, optional) – If True, allows slewing to correct large errors. If False, sets pointing threshold to 0. Defaults to True.
- Returns:
tuple –
- A tuple containing:
bool: True if pointing correction completed successfully
WCS or None: World Coordinate System object if plate solve succeeded, None if failed
Process: 1. Performs plate solving on the provided image 2. Calculates pointing error relative to target coordinates 3. Compares error to configured pointing threshold 4. Executes sync or slew correction based on error magnitude 5. Logs correction details and results
Note
Uses PointingCorrectionHandler for plate solving and correction calculations
Pointing threshold is configurable per telescope in the configuration
Falls back gracefully if plate solving fails
- guiding_calibration_sequence(action: Action, paired_devices: PairedDevices) bool[source]#
Perform autoguiding calibration to establish guide star movements.
Executes a calibration sequence that maps the relationship between guide commands and resulting star movements on the guide camera. This calibration is essential for accurate autoguiding performance.
- Parameters:
action (Action) – Schedule action containing guiding calibration information.
paired_devices (PairedDevices) – Object containing telescope, guide camera, and other devices required for calibration.
- Returns:
bool –
- True if calibration completed successfully, False if failed
or conditions became unsafe.
Process: 1. Prepares observatory and creates calibration metadata 2. Checks safety conditions before starting 3. Executes guiding calibration using GuidingCalibrator 4. Measures guide star response to directional commands 5. Calculates calibration parameters for future guiding 6. Returns success status
Safety Features: - Continuous condition checking during calibration - Graceful handling of calibration failures - Proper error logging and reporting
Note
Required before autoguiding can be used effectively
Calibration parameters are device and mount specific
Should be performed when guiding setup changes
- autofocus_sequence(action: Action, paired_devices: PairedDevices) bool[source]#
Perform autofocus sequence to achieve optimal telescope focus.
Executes an automated focusing routine that systematically tests different focus positions to find the optimal focus setting. Uses star analysis to measure focus quality and determine the best focus position.
- Parameters:
action (Action) – Schedule action containing autofocus sequence information.
paired_devices (PairedDevices) – Object containing telescope, camera, focuser, and other devices required for autofocus.
- Returns:
bool –
- True if autofocus completed successfully and achieved good focus,
False if failed or conditions became unsafe.
Process: 1. Prepares observatory and creates autofocus metadata 2. Checks safety conditions before starting 3. Executes autofocus routine using appropriate algorithm 4. Takes test exposures at different focus positions 5. Analyzes star quality metrics (FWHM, HFD, etc.) 6. Determines and sets optimal focus position 7. Returns success status
Focus Methods: - Uses Autofocuser or Defocuser classes for focus optimization - Supports different focus algorithms (curve fitting, star analysis) - Handles both coarse and fine focus adjustments
Safety Features: - Continuous condition checking during focus sequence - Graceful handling of focus failures - Proper error logging and reporting
Note
Critical for achieving optimal image quality
Should be performed regularly or when focus changes
Temperature changes often require refocusing
- flats_sequence(action: Action, paired_devices: PairedDevices) None[source]#
Execute a flat field calibration sequence during twilight.
Captures flat field images during astronomical twilight when the sky provides near-uniform illumination. Automatically manages telescope positioning, exposure timing, and filter changes to create comprehensive flat field libraries for image calibration.
- Parameters:
action (Action) – Schedule action containing flats sequence information.
paired_devices (PairedDevices) – Object containing all devices needed for the sequence (camera, telescope, filter wheel, etc.)
Process: 1. Monitors sun altitude for optimal flat field conditions 2. Positions telescope for uniform sky illumination 3. Calculates optimal exposure times for target ADU levels 4. Captures flat frames with consistent brightness 5. Iterates through multiple filters if specified 6. Handles exposure time adjustments as sky brightness changes
Timing Considerations: - Only operates during narrow twilight windows - Monitors sun elevation for optimal conditions - Automatically adjusts for changing sky brightness - Stops when conditions become unsuitable
Safety Features: - Continuous sky brightness monitoring - Automatic exposure time calculation - Weather and condition checking - Graceful handling of changing conditions
Note
Critical for high-quality photometric calibration
Timing is crucial - operates only during twilight
Results improve scientific data quality significantly
- flats_position(obs_location: EarthLocation, paired_devices: dict, action: Action) None[source]#
Position telescope to optimal sky location for flat field imaging.
Calculates and moves the telescope to an optimal sky position for capturing uniform flat field images. The position is determined based on sun location, telescope constraints, and sky brightness uniformity requirements.
- Parameters:
obs_location (EarthLocation) – Observatory geographical location for astronomical calculations.
paired_devices (dict) – Dictionary of paired devices including telescope and dome for positioning operations.
action (Action) – The action object containing action_type, start_time, end_time, and action_value with target coordinates.
Process: 1. Calculates optimal sky position based on current conditions 2. Considers sun position and twilight geometry 3. Ensures position provides uniform illumination 4. Commands telescope to slew to calculated position 5. Updates action_value with target coordinates
Positioning Strategy: - Avoids regions near sun or moon for uniform illumination - Selects high altitude positions when possible - Considers dome constraints and telescope limits - Optimizes for sky brightness uniformity
Note
Critical for obtaining high-quality flat field calibrations
Position affects uniformity and quality of flat frames
Coordinates with flats_exptime for complete flat acquisition
- flats_exptime(obs_location: EarthLocation, paired_devices: dict, action: Action, target_adu: list, offset: float, lower_exptime_limit: float, upper_exptime_limit: float, exptime: float | None = None) float[source]#
Set the exposure time for flat field calibration images.
This function adjusts the exposure time for flat field calibration images captured with a camera device to achieve a specific target median ADU (Analog-to-Digital Units) level, considering user-defined limits. It uses 64x64 pixel subframes to speed up the process.
- Parameters:
obs_location (EarthLocation) – The location of the observatory.
paired_devices (dict) – A dictionary specifying paired devices, including ‘Camera’ for the camera device.
action (Action) – The action object containing action_type, start_time, end_time, and action_value.
numx (int) – The original number of pixels in the X-axis of the camera sensor. # TODO delete?
numy (int) – The original number of pixels in the Y-axis of the camera sensor.
startx (int) – The original starting pixel position in the X-axis for the camera sensor.
starty (int) – The original starting pixel position in the Y-axis for the camera sensor.
target_adu (list) – A list containing the target ADU level and tolerance as [target_level, tolerance].
offset (float) – The offset ADU level to be considered when adjusting the exposure time.
lower_exptime_limit (float) – The lower limit for the exposure time in seconds.
upper_exptime_limit (float) – The upper limit for the exposure time in seconds.
exptime (float, optional) – The initial exposure time guess. If not provided, it is calculated as the midpoint between lower_exptime_limit and upper_exptime_limit.
- Returns:
exptime (float) – The adjusted exposure time in seconds that meets the target ADU level within the specified limits.
- execute_and_monitor_device_task(device_type: str, monitor_command: str, desired_condition: Any, run_command: str, device_name: str, run_command_type: str = '', abs_tol: float = 0, log_message: str = '', timeout: float = 120, error_sensitive: bool = True, weather_sensitive: bool = True) None[source]#
Monitor a device property and execute commands to achieve desired conditions.
Continuously monitors a device property and executes a command if the current value doesn’t match the desired condition. Provides robust error handling, timeout management, and safety checks during execution.
This is a fundamental method for observatory automation, handling everything from telescope movements to camera settings with appropriate safety checks.
- Parameters:
device_type (str) – Type of device to monitor (e.g., ‘Telescope’, ‘Camera’).
monitor_command (str) – Property to monitor on the device.
desired_condition (any) – Target value or condition to achieve.
run_command (str) – Command to execute if condition not met.
device_name (str) – Specific device name to operate on.
run_command_type (str, optional) – Command type (‘set’ or ‘get’). Defaults to empty string for simple commands.
abs_tol (float, optional) – Absolute tolerance for numerical comparisons. Defaults to 0 for exact matches.
log_message (str, optional) – Custom message logged when action starts. Defaults to empty string.
timeout (float, optional) – Maximum time to wait in seconds. Defaults to 120 seconds.
error_sensitive (bool, optional) – Whether to abort on system errors. Defaults to True.
weather_sensitive (bool, optional) – Whether to abort on unsafe weather. Defaults to True.
Safety Features: - Continuous monitoring of weather and error conditions - Timeout protection prevents infinite loops - Queue management prevents conflicting operations - Detailed error logging and reporting
Note
Uses queue system to prevent overlapping operations on same device
Automatically handles different data types and comparison methods
Critical for all automated observatory operations