Data_objects
ASTRAtypes
Define basic types for ASTRA type hinting.
RV_measurement = Quantity
module-attribute
data_vector = Iterable[Quantity]
module-attribute
unitless_data_vector = Union[List[float], np.ndarray]
module-attribute
unitless_data_matrix = np.ndarray
module-attribute
UI_PATH = Union[str, Path]
module-attribute
UI_DICT = Dict[str, Any]
module-attribute
BASE
Base class for ASTRA objects.
Presents a common set of routines for all objects, mainly controlling:
1) internal link to disk paths 2) general options, such as the SAVE_DISK_SPACE and WORKING_MODE
Raises: custom_exceptions.InvalidConfiguration: description custom_exceptions.InvalidConfiguration: description
BASE
Base class, for almost all of SBART objects.
Inheriting from this class brings a common interface for SBART's User parameters and handling of disk paths.
Source code in src/ASTRA/utils/BASE.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
disk_save_level: DISK_SAVE_MODE
property
Return the current disk save level for this object.
work_mode: WORKING_MODE
property
Return the current working mode for this object.
is_valid: bool
property
Check if object only has 'good' flags.
name: str
property
Representation name.
storage_name: str
property
Storage name of object.
disk_save_enabled: bool
property
True if there is any sort of disk savings active.
update_user_configs(new_configs: dict[str, Any]) -> None
update_work_mode_level(level: WORKING_MODE) -> None
update_disk_saving_level(level: DISK_SAVE_MODE) -> None
Update the work level of the current object.
trigger_data_storage(*args: Any, **kwargs: Any) -> None
json_ready() -> Dict[str, Any]
Convert current class into a json entry.
Returns: Dict[str, Any]: json-compatible dictionary
generate_root_path(storage_path: Path, no_logs: bool = True) -> None
Generate root storage folder in memory.
Source code in src/ASTRA/utils/BASE.py
add_relative_path(path_name: str, relative_structure: str) -> None
Add a new relative path to internal structure.
Args: path_name (str): Keyword that will be used to specify the new path relative_structure (str): relative path in relation to the root one
Source code in src/ASTRA/utils/BASE.py
add_to_status(new_flag: Flag) -> None
Add a new flag to the status of this object.
Args: new_flag (Flag): New flag to be added into the status
load_from_file(root_path: Path, loading_path: str) -> None
is_object_type(type_to_check: str) -> bool
config_help() -> None
classmethod
Cubic_spline
Custom cubic spline, as defined in Silva et al, 2022.
CYTHON_UNAVAILABLE = False
module-attribute
CustomCubicSpline
Source code in src/ASTRA/utils/Cubic_spline.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
old_wavelengths = old_wavelengths
instance-attribute
original_data = original_data
instance-attribute
original_errors = original_errors
instance-attribute
data_size = original_data.size
instance-attribute
ignore_covariances = ignore_covariances
instance-attribute
cov_matrix = original_errors ** 2
instance-attribute
n_threads = n_threads
instance-attribute
inv_delta_wave = 1 / np.diff(old_wavelengths)
instance-attribute
cached_ones = np.ones((self.data_size - 2, self.data_size - 2), dtype=np.float64, order='C')
instance-attribute
compute_h_matrix()
Create the H matrix.
Source code in src/ASTRA/utils/Cubic_spline.py
compute_partial(index_i)
Source code in src/ASTRA/utils/Cubic_spline.py
build_U_matrix(index_i_0, index_j_0)
Create the "U" matrix for the covariance estimation; Only computes the relevant quadrant.
Source code in src/ASTRA/utils/Cubic_spline.py
compute_second_derivative()
Source code in src/ASTRA/utils/Cubic_spline.py
interpolate(new_wavelengths)
Interpolate the data to the new wavelengths
Source code in src/ASTRA/utils/Cubic_spline.py
UserConfigs
ASTRA configurations.
This defines the main configuration scheme of ASTRA:
1) Userparam, which defines the individual configurations 2) InternalParameters, which are used by ASTRA objects 3) DefaultValues, which agregates all possible configurations that are available to the users
UserParam
Define an individual configuration that the user can specify.
Source code in src/ASTRA/utils/UserConfigs.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
quiet = quiet
instance-attribute
description = description
instance-attribute
existing_constraints: Constraint
property
Retrieve existing constraints of parameter.
is_mandatory: bool
property
True if the parameter is mandatory.
quiet_output: bool
property
True if the parameter should not log to terminal.
default_value: Any
property
Return the default value of the parameter.
Raises:
| Type | Description |
|---|---|
InvalidConfiguration: if the parameter is mandatory, there is no default
|
|
apply_constraints_to_value(param_name: str, value: Any) -> None
Apply the constraints of this parameter to a given value.
Args: param_name (str): Name of the parameter, used in the logs value (Any): Value that the user provided
Source code in src/ASTRA/utils/UserConfigs.py
get_terminal_output(indent_level: int = 1) -> str
Generate terminal-formatted text from this UserParam.
Args: indent_level (int, optional): How many tabs to add at the start of each line. Defaults to 1.
Returns: str: Formatted message with the Description, mandatory status, default value and constraints
Source code in src/ASTRA/utils/UserConfigs.py
InternalParameters
Contain all configurations from a given ASTRA object.
This class will store all configurations (UserParam) from a given ASTRA object, as well as their current value. When updating a given parameter, the QC checks that are imposed by the UserParam object.
Source code in src/ASTRA/utils/UserConfigs.py
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | |
no_logs = no_logs
instance-attribute
update_configs_with_values(user_configs: dict[str, Any]) -> None
Update the parameters with a configuration dictionary.
Args: user_configs (dict[str, Any]): Dictionary with user parameters.
Raises: InternalError: If the provided value does not meet the imposed restrictions.
Source code in src/ASTRA/utils/UserConfigs.py
receive_user_inputs(user_configs: dict[str, Any] = None) -> None
Parse the config dictionary from the user.
Args: user_configs (Optional[Dict[str, Any]], optional): Dictionary where the keys are the parameter names, and the values are the new values of that parameter. The values will be checked by the validation layer defined in the corresponding UserParam. Defaults to None.
Raises: InvalidConfiguration: If a given parameter is mandatory and it was not provided by the user InternalError: If the validation layer does not agree with the provided value.
Source code in src/ASTRA/utils/UserConfigs.py
text_pretty_description(indent_level: int) -> str
Generate textual description of internal parameters.
Source code in src/ASTRA/utils/UserConfigs.py
get_user_configs() -> Dict[str, Any]
DefaultValues
Defines all of the user parameters that SBART has available for any given object.
We can sum two DefaultValues objects to expand the possible configurable parameters of the ASTRA object.
Source code in src/ASTRA/utils/UserConfigs.py
default_mapping: dict[str, UserParam] = kwargs
instance-attribute
update(item: str, new_value: UserParam) -> None
Update the default value of a stored parameter, if it exists.
Args: item (str): Param name new_value (UserParam): New configuration
Raises: Exception: If the parameter that we want to update does not exist
Source code in src/ASTRA/utils/UserConfigs.py
items()
keys() -> Iterable[str]
air_to_vac
airtovac(wave_air)
Adapted from idl astrolib (https://idlastro.gsfc.nasa.gov/ftp/pro/astro/airtovac.pro).
;+ ; NAME: ; AIRTOVAC ; PURPOSE: ; Convert air wavelengths to vacuum wavelengths ; EXPLANATION: ; Wavelengths are corrected for the index of refraction of air under ; standard conditions. Wavelength values below 2000 A will not be ; altered. Uses relation of Ciddor (1996). ; ; CALLING SEQUENCE: ; AIRTOVAC, WAVE_AIR, [ WAVE_VAC] ; ; INPUT/OUTPUT: ; WAVE_AIR - Wavelength in Angstroms, scalar or vector ; If this is the only parameter supplied, it will be updated on ; output to contain double precision vacuum wavelength(s). ; OPTIONAL OUTPUT: ; WAVE_VAC - Vacuum wavelength in Angstroms, same number of elements as ; WAVE_AIR, double precision ; ; EXAMPLE: ; If the air wavelength is W = 6056.125 (a Krypton line), then ; AIRTOVAC, W yields an vacuum wavelength of W = 6057.8019 ; ; METHOD: ; Formula from Ciddor 1996, Applied Optics 62, 958 ; ; NOTES: ; Take care within 1 A of 2000 A. Wavelengths below 2000 A in air are ; not altered. ; REVISION HISTORY ; Written W. Landsman November 1991 ; Use Ciddor (1996) formula for better accuracy in the infrared ; Added optional output vector, W Landsman Mar 2011 ; Iterate for better precision W.L./D. Schlegel Mar 2011 ;-
Source code in src/ASTRA/utils/air_to_vac.py
choices
Defines that availabe choices of ASTRA.
WORKING_MODE
Bases: Enum
Enumerator to represent the working mode of the ASRA object.
ONE_SHOT - All observations are processed at the same time
Source code in src/ASTRA/utils/choices.py
ONE_SHOT = 'ONE_SHOT'
class-attribute
instance-attribute
DISK_SAVE_MODE
Bases: Enum
Enumerator to represent the DISK save mode of a given ASTRA object.
Source code in src/ASTRA/utils/choices.py
DISABLED = 1
class-attribute
instance-attribute
BASIC = 2
class-attribute
instance-attribute
EXTREME = 3
class-attribute
instance-attribute
TELLURIC_EXTENSION
Bases: Enum
Method for the extension of telluric template.
Source code in src/ASTRA/utils/choices.py
LINES = 'LINES'
class-attribute
instance-attribute
WINDOW = 'WINDOW'
class-attribute
instance-attribute
TELLURIC_CREATION_MODE
Bases: Enum
Method for the construction of telluric template.
Source code in src/ASTRA/utils/choices.py
tapas = 'tapas'
class-attribute
instance-attribute
telfit = 'telfit'
class-attribute
instance-attribute
OHemission = 'OHemission'
class-attribute
instance-attribute
STELLAR_CREATION_MODE
Bases: Enum
Method for the construction of stellar template.
Source code in src/ASTRA/utils/choices.py
Sum = 'Sum'
class-attribute
instance-attribute
OBSERVATION = 'OBSERVATION'
class-attribute
instance-attribute
Median = 'Median'
class-attribute
instance-attribute
PHOENIX = 'PHOENIX'
class-attribute
instance-attribute
TELLURIC_APPLICATION_MODE
Bases: Enum
Approach to handle telluric features.
Source code in src/ASTRA/utils/choices.py
removal = 'removal'
class-attribute
instance-attribute
correction = 'correction'
class-attribute
instance-attribute
SPECTRA_INTERPOL_MODE
Bases: Enum
Enumerator to represent the DISK save mode of a given ASTRA object.
Source code in src/ASTRA/utils/choices.py
SPLINES = 1
class-attribute
instance-attribute
GP = 2
class-attribute
instance-attribute
SPLINE_INTERPOL_MODE
Bases: Enum
Enumerator to represent the interpolation mode of a given ASTRA object.
Possible values: CUBIC_SPLINE QUADRATIC_SPLINE PCHIP NEAREST RBF SMOOTH_CUBIC_SPLINE AKIMA BARYCENTRIC_INTERPOL
Source code in src/ASTRA/utils/choices.py
CUBIC_SPLINE = 1
class-attribute
instance-attribute
QUADRATIC_SPLINE = 2
class-attribute
instance-attribute
PCHIP = 3
class-attribute
instance-attribute
NEAREST = 4
class-attribute
instance-attribute
RBF = 5
class-attribute
instance-attribute
SMOOTH_CUBIC_SPLINE = 6
class-attribute
instance-attribute
AKIMA = 7
class-attribute
instance-attribute
BARYCENTRIC_INTERPOL = 8
class-attribute
instance-attribute
FLUX_SMOOTH_CONFIGS
Bases: Enum
Enumerator to flux smoothing applied at template construction.
Source code in src/ASTRA/utils/choices.py
NONE = 1
class-attribute
instance-attribute
SAVGOL = 2
class-attribute
instance-attribute
FLUX_SMOOTH_ORDER
Bases: Enum
The order in which the smooth is applied.
Source code in src/ASTRA/utils/choices.py
BEFORE = 1
class-attribute
instance-attribute
AFTER = 2
class-attribute
instance-attribute
BOTH = 3
class-attribute
instance-attribute
INTERPOLATION_ERR_PROP
Bases: Enum
how should we propagate uncertainties.
Source code in src/ASTRA/utils/choices.py
interpolation = 1
class-attribute
instance-attribute
propagation = 2
class-attribute
instance-attribute
none = 3
class-attribute
instance-attribute
NORMALIZATION_SOURCES
Bases: Enum
how should we propagate uncertainties.
Source code in src/ASTRA/utils/choices.py
RASSINE = 'RASSINE'
class-attribute
instance-attribute
SNT = 'SNT'
class-attribute
instance-attribute
POLY_FIT = 'POLY_FIT'
class-attribute
instance-attribute
compute_berv_and_herv_poet
Compute BERV (Barycentric-Earth RV) and HERV (HEliocentric RV) correction.
BARYCORR_AVAILABLE = True
module-attribute
compute_berv_and_herv_POET(header) -> tuple[RV_measurement, RV_measurement]
Compute barycentric and heliocentric correction for Paranal Observatory
Source code in src/ASTRA/utils/compute_berv_and_herv_poet.py
concurrent_tools
close_interfaces
close_buffers(shared_buffers)
kill_workers(shared_buffers, in_queue, number_workers)
Source code in src/ASTRA/utils/concurrent_tools/close_interfaces.py
create_shared_arr
evaluate_worker_shutdown
evaluate_shutdown(queue: Queue) -> Tuple[int, int]
Evaluate the shutdown messages sent by the workers, counting the number of good and bad shutdowns
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queue
|
Queue
|
Queue in which the workers place their |
required |
Returns:
| Type | Description |
|---|---|
Tuple[int, int]
|
Goog, bad shutdowns |
Source code in src/ASTRA/utils/concurrent_tools/evaluate_worker_shutdown.py
open_buffers
open_buffer(buffer_info: dict, open_type: str, buffers: list)
Source code in src/ASTRA/utils/concurrent_tools/open_buffers.py
proxyObjects
DataClassManager
Bases: BaseManager
This will be the server that manages the shared objects
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
BaseManager
|
[type]
|
[description] |
required |
proxy_object
DataClassManager
Bases: BaseManager
This will be the server that manages the shared objects
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
BaseManager
|
[type]
|
[description] |
required |
create_logger
Setup the logger, handling terminal and disk output.
astra_logger = logger.bind(module='ASTRA')
module-attribute
setup_ASTRA_logger(storage_path=None, level='INFO', log_to_terminal=True, write_to_file=True, append_to_file=True)
Configure ASTRA's logger dynamically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_path
|
str or Path or None
|
Path to the log file. If None, file logging is skipped. |
required |
level
|
str
|
Minimum level to log ("DEBUG", "INFO", "WARNING", etc.) |
'INFO'
|
console
|
bool
|
Whether to also log to stdout. |
required |
Source code in src/ASTRA/utils/create_logger.py
create_spectral_blocks
Compute start and end of all continuous regions.
build_blocks(indexes)
Evaluate the output of a np.where to find the continuous regions in it.
This returns a numpy array, where each entry is a list of a 'set' of ones.
E.g.
arr = np.array([0,0,1,1,1,1,1,1,0,1,0]) print(build_blocks(arr)) [[2, 3, 4, 5, 6, 7], [9]]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indexes
|
[type]
|
[description] |
required |
Returns:
| Type | Description |
|---|---|
[type]cd
|
[description] |
Source code in src/ASTRA/utils/create_spectral_blocks.py
custom_exceptions
Defines the exceptions that ASTRA will raise.
Error
Bases: Exception
Base class for exceptions in this module.
FrameError
AlreadyLoaded
BadOrderError
NoConvergenceError
NoComputedRVsError
DeadWorkerError
NoDataError
InvalidConfiguration
TemplateNotExistsError
BadTemplateError
FailedStorage
InternalError
MissingRootPath
StopComputationError
ensure_invalid_template(func)
Mark template as invalid if Exception is raised.
Source code in src/ASTRA/utils/custom_exceptions.py
cython_codes
setup
targets = {'inverter': 'inverter.pyx', 'partial_derivative': 'partial_derivative.pyx', 'second_derivative': 'second_derivative.pyx'}
module-attribute
ext_modules = [Extension(key, [value], extra_compile_args=['-fopenmp'], extra_link_args=['-fopenmp'], include_dirs=[np.get_include()]) for key, value in targets.items()]
module-attribute
definitions
Enums that are used to define different properties.
DETECTOR_DEFINITION
Bases: Enum
Represent the cromatic intervals (full spectra, red and blue det.).
Source code in src/ASTRA/utils/definitions.py
WHITE_LIGHT = auto()
class-attribute
instance-attribute
RED_DET = auto()
class-attribute
instance-attribute
BLUE_DET = auto()
class-attribute
instance-attribute
handle_SDO_image
SUNPY_available = True
module-attribute
configs = {'SDO_DOWNLOAD_REPEAT_INTEVAL': 5, 'SDO_FITS_NAME': 'hmi.ic_nolimbdark_720s_nrt.{}_TAI.3.continuum.fits', 'SDO_FITS_QUERY': 'hmi.ic_nolimbdark_720s_nrt[{}_TAI/{}]{{continuum}}', 'SDO_SERVER_NAME': 'JSOC', 'JSOC_EMAIL_ADDRESS': 'Andre.Silva@astro.up.pt', 'SDO_NUMBER_DOWNLOAD_REPEATS': 50}
module-attribute
single_column_width = 85 / 25.4
module-attribute
double_column_width = 175 / 25.4
module-attribute
height = single_column_width * 0.8
module-attribute
download_from_SDO(export_request: drms.ExportRequest, image_name: str, storage_location: Path) -> bool
Base interface to download an image from SDO.
Creates an export request on JSOC servers, and downloads the latest image that was returned. If the image already exists on disk, the download does not proceed
Args: export_request (drms.ExportRequest): export request to use for the download image_index (int): index of the desired file in the request configs (ConfigHolder): description storage_location (Path): Disk location of the stored images
Returns: bool: returns true if it succeeds or false otherwise
Notes/References: - Documentation for the drms download can be found in here
- Description of the SDO data products: http://jsoc.stanford.edu/HMI/Continuum.html
- The email must be registered in [JSOC](http://jsoc.stanford.edu/ajax/register_email.html)
- This functions will retrieve the information from the SDO_SERVER_NAME that
is specified in the configs.
Source code in src/ASTRA/utils/handle_SDO_image.py
construct_JSOC_SDO_query_string(date: Time, time_range: timedelta) -> str
Construct the SDO query for a given date, image identifier and time range
Args: date (Time): Date at which we want to start our "search" image_identifier (str): SDO image idenfitifer. time_range (timedelta): Time range for the search (will search all available fits between date and date + time_range)
Returns: str: Query string to pass into SDO functions
Source code in src/ASTRA/utils/handle_SDO_image.py
plot_sdo_with_multiple_crosses(fits_file: str | Path, tx_arcsec_list: list[float], ty_arcsec_list: list[float], zoom_center_tx: float, zoom_center_ty: float, plot_options: dict[str, str], zoom_width: u.Quantity = 300 * u.arcsec, zoom_height: u.Quantity = 300 * u.arcsec, zoom_map=None, fig=None, ax=None)
Source code in src/ASTRA/utils/handle_SDO_image.py
json_ready_converter
Utility function to convert any dictionary into one that can be saved to disk with json.
json_ready_converter(value: Any) -> Any
Convert a given value to a json-serializable format.
TODO: also prepare SBART objects that have the to_json attribute!
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
[type]
|
[description] |
required |
Returns:
| Type | Description |
|---|---|
[type]
|
[description] |
Source code in src/ASTRA/utils/json_ready_converter.py
parameter_validators
Validators for the configuration options.
We can combine multiple validation conditions by summing them, thus creating a AND condition
Raises: InvalidConfiguration: If passed value does not meet its imposed conditions InternalError: Passing unknown configuration of the methods
constraint_map = {'ValueInInterval': ValueInInterval, 'ValueFromDtype': ValueFromDtype, 'IterableMustHave': IterableMustHave, 'ValueFromList': ValueFromIterable}
module-attribute
Positive_Value_Constraint = ValueInInterval((0, np.inf), include_edges=True)
module-attribute
StringValue = ValueFromDtype((str,))
module-attribute
PathValue = ValueFromDtype((str, Path)) + PathExists()
module-attribute
NumericValue = ValueFromDtype((int, float))
module-attribute
IntegerValue = ValueFromDtype((int,))
module-attribute
BooleanValue = ValueFromDtype((bool,))
module-attribute
predefined_constraints = {'Positive_Value_Constraint': Positive_Value_Constraint, 'StringValue': StringValue, 'PathValue': PathValue, 'NumericValue': NumericValue, 'IntegerValue': IntegerValue, 'BooleanValue': BooleanValue}
module-attribute
Constraint
Base class to define a constraint on possible values that a parameter can take.
Serves as parent class, allows the "sum" of two constraints to make "AND" operations
Attributes: constraint_text: String that describes the constraint
Raises: InvalidConfiguration: If the constraint on the parameter value is not met
Source code in src/ASTRA/utils/parameter_validators.py
constraint_text = const_text
instance-attribute
check_if_value_meets_constraint(value: Any) -> None
Compare the provided value against all constraint.
Args: value (Any): Value to be compared
Raises: InvalidConfiguration: If the value is not met
Source code in src/ASTRA/utils/parameter_validators.py
ValueInInterval
Bases: Constraint
Constraint that imposes the provided value to be inside a given interval.
Source code in src/ASTRA/utils/parameter_validators.py
ValueFromDtype
Bases: Constraint
Constraint that limits the datatype of the input.
Source code in src/ASTRA/utils/parameter_validators.py
valid_dtypes = dtype_list
instance-attribute
ValueFromIterable
Bases: Constraint
Limits the possible values to be inside a list.
Source code in src/ASTRA/utils/parameter_validators.py
available_options = available_options
instance-attribute
IterableMustHave
Bases: Constraint
Imposes that certain values must be inside a given iterable.
Source code in src/ASTRA/utils/parameter_validators.py
available_options = available_options
instance-attribute
mode = mode
instance-attribute
PathExists
Bases: Constraint
Imposes that a given path must exist.
Source code in src/ASTRA/utils/parameter_validators.py
paths_tools
PathsHandler
Handle the interface with disk paths.
Store and generate paths from relative locations, after a given root path is set. It allows to define tags to relative path on disk, ensuring that ASTRA objects are agnostic to the storage path.
Raises: custom_exceptions.MissingRootPath: If accessing disk paths without setting the root one.
Paths
ASTRA internal class to store disk paths for storage.
Source code in src/ASTRA/utils/paths_tools/PathsHandler.py
root_storage_path: Path
property
Retrieve the root storage path.
add_relative_path(folder_KW: str, rel_path: str) -> None
Add relative (to self._root_path) folder, associated with a given Keyword.
Args: folder_KW (str): keyword that will be associated with the relative path rel_path (str): relative (to root path) path
Source code in src/ASTRA/utils/paths_tools/PathsHandler.py
get_path_to(folder_tag: str, absolute: bool = True, as_posix: bool = True) -> Union[str, Path]
Get the path from a relative "tag".
Args: folder_tag (str): Internal path name absolute (bool, optional): returns absolute path. Defaults to True. as_posix (bool, optional): return string if True. Defaults to True.
Raises: custom_exceptions.MissingRootPath: If the root path was not previously set
Returns: Union[str, Path]: Path
Source code in src/ASTRA/utils/paths_tools/PathsHandler.py
add_root_path(path: Union[str, Path], current_folder_name: Optional[str] = None) -> None
Set the current root path.
Source code in src/ASTRA/utils/paths_tools/PathsHandler.py
build_filename
Path creation.
build_filename(og_path: Path, filename: str, fmt: str, ASTRA_version: Optional[str] = None, skip_version: bool = False) -> str
Standardize the filenames of ASTRA outputs.
Args: og_path (Path): Folder in which the file will be stored filename (str): stem of the filename fmt (str): format of the file ASTRA_version (Optional[str], optional): version of ASTRA. Defaults to None.
Returns: str: Posix version of the file that want to store
Source code in src/ASTRA/utils/paths_tools/build_filename.py
ensure_path
Ensure that a given input path is a pathlib.Path object.
ensure_path_from_input(input_path: Union[str, pathlib.Path], ensure_existence: bool = False) -> pathlib.Path
Ensure that a given path is a pathlib.Path object and (optionally) if it exists.
Args: input_path (Union[str, pathlib.Path]): User-provided path ensure_existence (bool): If True, raises an Exception if the input_path does not exists. By default False
Raises: InvalidConfiguration: If the path is neither a string nor a pathlib.Path object NoDataError: If the ensure_existence flag is set to True and input_path does not exist
Source code in src/ASTRA/utils/paths_tools/ensure_path.py
file_older_than
file_older_than(file: str, days: int) -> bool
Check if file has been modified more than days days ago
Source code in src/ASTRA/utils/paths_tools/file_older_than.py
find_latest_version
Search for latest version in file products.
find_latest_version(path: Path, enable_logs: bool = True) -> str
Search, inside a directory, for all files with SBART versions. Returns the latest version found on disk.
Source code in src/ASTRA/utils/paths_tools/find_latest_version.py
poet_SDO_plotter
SUNPY_available = True
module-attribute
plot_SDO_image(d: DataClass, include_fine_point_offset: bool, storage_location: Path, JSOC_EMAIL_ADDRESS: str, zoom_in=False, label_map: dict[str, str] | None = None, legend_options: dict[str, Any] | None = None)
Make plot of the pointing positions on SDO image
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
DataClass
|
DataClass object |
required |
include_fine_point_offset
|
bool
|
Include into the final coordinates the fine-pointing offsets (from the MCS) |
required |
storage_location
|
Path
|
Folder to store the image (pointing_locations.png) |
required |
zoom_in
|
bool
|
If True, zooms the plot to a region close to the pointing position, by default False |
False
|
label_map
|
dict[str, str] | None
|
If not None, dictionary to connect PoET OB names to a legend label |
None
|
Raises:
| Type | Description |
|---|---|
InternalError
|
If Sunpy is not installed |
Source code in src/ASTRA/utils/poet_SDO_plotter.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | |
ranges
ranges(a)
Source code in src/ASTRA/utils/ranges.py
secular_acceleration
Compute secular acceleration.
as_yr = u.arcsec / u.year
module-attribute
mas_yr = u.milliarcsecond / u.year
module-attribute
mas = u.milliarcsecond
module-attribute
handler(signum, frame)
build_query(star: str)
Source code in src/ASTRA/utils/secular_acceleration.py
run_job(query, timeout=5)
mu(pmra, pmdec)
secular_acceleration(star)
Source code in src/ASTRA/utils/secular_acceleration.py
shift_spectra
Functions to shift spectra.
Implements utility functions to correct for stellar RV and BERV
SPEED_OF_LIGHT = 299792.458
module-attribute
apply_RVshift(wave: np.ndarray, stellar_RV: float) -> np.ndarray
Apply RV shift to spectra.
Args: wave (np.ndarray): Wavelength array stellar_RV (float): RV shift to apply, in km/s
Returns: np.ndarray: New wavelength array, after RV shift
Source code in src/ASTRA/utils/shift_spectra.py
remove_RVshift(wave: np.ndarray, stellar_RV: float) -> np.ndarray
Remove RV shift from wavelength vector.
Args: wave (np.ndarray): Wavelength vector stellar_RV (float): stellar RV, in km/s
Returns: np.ndarray: New wavelength array
Source code in src/ASTRA/utils/shift_spectra.py
apply_approximated_BERV_correction(wave: np.ndarray, BERV: float) -> np.ndarray
Apply the approximated BERV correction that is implemented in ESO DRS 3.2.
Args: wave (np.ndarray): wavelength array BERV (float): BERV value, with the 1.55 * 10**-8 approximation
Returns: np.ndarray: BERV-corrected wavelength array
Source code in src/ASTRA/utils/shift_spectra.py
remove_approximated_BERV_correction(wave: np.ndarray, BERV: float) -> np.ndarray
Remove the approximated BERV correction implemented in ESO DRS 3.2.
Args: wave (np.ndarray): wavelength array BERV (float): BERV value, with the 1.55 * 10**-8 approximation
Returns: np.ndarray: BERV-corrected wavelength array
Source code in src/ASTRA/utils/shift_spectra.py
apply_BERV_correction(wave: np.ndarray, BERV: float, BERV_factor: float | None = None) -> np.ndarray
Apply BERV correction to data.
Args: wave (np.ndarray): wavelength array BERV (float): BERV value BERV_factor (float | None): If not None, it will be taken as the value of (1 + BERV/C)
Returns: np.ndarray: BERV-corrected wavelength array
Source code in src/ASTRA/utils/shift_spectra.py
remove_BERV_correction(wave: np.ndarray, BERV: float, BERV_factor: float | None = None) -> np.ndarray
Remove BERV correction to data.
Args: wave (np.ndarray): wavelength array BERV (float): BERV value BERV_factor (float | None): If not None, it will be taken as the value of (1 + BERV/C)
Returns: np.ndarray: BERV-corrected wavelength array
Source code in src/ASTRA/utils/shift_spectra.py
spectral_conditions
Selection of observations based on conditions.
When using ASTRA we can reject observations in two different ways:
- globally - they are effectivelly discarded for all SBART operations
- temporarily -Only disable them for the creation of the Stellar Templates
Even though the two rejection types have completely different effects, we always use the same format,
as defined in :py:class:~SBART.utils.spectral_conditions.
Based on Header values
- Allows to define bounds for the "valid" values that a given header value can take.
- The bounds argument takes a list of list, with each entry defining a "region" that the value can take.
- If we want to place no upper/lower limits, we can place a None
.. code-block:: python
# Only use observations that can have AIRMASS smaller than 1.5 or larger than 1.6
valid_AIRM_condition = KEYWORD_condition(KW = "airmass",
bounds=[[None, 1.5], [1.6, None]]
)
# Only select observations that have a previous RV error (the one from the CCF) smaller than 50 meter_second
# Note1: conditions for 'RV related' values (previousRV, drift, BERV) must be in meter_second OR kilometer_second
# Note2: units will be converted later on, so either "unit" can be chosen
valid_error_condition = KEYWORD_condition(KW="previousRV_ERR",
bounds = [0, 50*meter_second])
-
It is possible to match the Keyword values to a specific one: .. code-block:: python
valid_error_condition = KEYWORD_value(KW="OBS NAME", value = "OB NAME as defined in the header" )
Rejection based on filenames
Provide a list of bad filenames that will be rejected.
Note: Filename only, do NOT pass a path
.. code-block:: python
bad_filename_condition = FNAME_condition(filename_list=["filename.fits"])
Rejecting based on the "subInstrument"
Reject all observations from ESPRESSO21
.. code-block:: python
bad_subInst_condition = SubInstrument_condition("ESPRESSO21")
Rejecting based on Warning Flags when loading the Frames
Reject observation if a given warning flag was set when loading the spectra
.. code-block:: python
bad_subInst_condition = WarningFlag_Notset("HIERARCH ESO QC SCIRED DRIFT CHECK")
Combining conditions
To combine multiple conditions, sum them together. The observations will be rejected if any Condition decides to reject it
.. code-block:: python
full_conditions = valid_AIRM_condition + valid_error_condition + bad_filename_condition + bad_subInst_condition
Applying the conditions
For a :py:class:~SBART.data_objects.DataClass.DataClass object, we can use its
:obj:~SBART.data_objects.DataClass.DataClass.reject_observations method
.. code-block:: python
data.reject_observations(full_conditions)
ConditionModel
Defines the Base Condition Class, from which we can generate new conditions.
The conditions represent a boolean check that is applied to a given spectra, which is then rejected or kept, depending on the result from the check.
The ConditionModel is implemented in such a way that summing two conditions together creates a new, independent, condition that combines them all. This new, merged, conditions works as a sequential application of all conditions.
Source code in src/ASTRA/utils/spectral_conditions.py
set_conditions: list[str]
property
cond_info: str
property
evaluate(frame: Frame) -> Tuple[bool, List[Flag]]
Apply all boolean checks to a given frame, returning a boolean value and a list of Flags with the results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame
|
Frame
|
frame to be validated against the conditions |
required |
Returns:
| Name | Type | Description |
|---|---|---|
valid_OBS |
bool
|
Boolean result of the comparison |
flags |
List[Flag]
|
List of flags, one for each condition that was applied |
Source code in src/ASTRA/utils/spectral_conditions.py
select_spectra(frame: Frame) -> Flag
write_to_disk(file: UI_PATH) -> None
Write constraint to file.
KEYWORD_in_iterable
Bases: ConditionModel
Limit the kW to be a specific value.
Source code in src/ASTRA/utils/spectral_conditions.py
KW = KW
instance-attribute
possible_value = possible_value
instance-attribute
cond_info: str
property
select_spectra(frame) -> Flag
Reject if from a given sub-instrument.
Source code in src/ASTRA/utils/spectral_conditions.py
KEYWORD_value
Bases: ConditionModel
Limit the kW to be a specific value.
Source code in src/ASTRA/utils/spectral_conditions.py
KW = KW
instance-attribute
value = value
instance-attribute
cond_info: str
property
select_spectra(frame) -> Flag
Reject if from a given sub-instrument.
Source code in src/ASTRA/utils/spectral_conditions.py
KEYWORD_condition
Bases: ConditionModel
Limit the KW to be inside the defined interval (edges included).
Source code in src/ASTRA/utils/spectral_conditions.py
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | |
KW = KW
instance-attribute
bounds = bounds
instance-attribute
cond_info: str
property
select_spectra(frame: Frame) -> Flag
Apply conditions to spectra.
Source code in src/ASTRA/utils/spectral_conditions.py
SubInstrument_condition
Bases: ConditionModel
Flag the observations that are from the defined subInstrument.
Source code in src/ASTRA/utils/spectral_conditions.py
cond_info: str
property
select_spectra(frame) -> Flag
Reject if from a given sub-instrument.
Source code in src/ASTRA/utils/spectral_conditions.py
Empty_condition
WarningFlag_Notset
Bases: ConditionModel
Reject the observation if the given warning flag is True, as set through the KW_WARNING flag of QC routines.
Source code in src/ASTRA/utils/spectral_conditions.py
flag_name = flag_name
instance-attribute
full_flag = full_flag
instance-attribute
cond_info: str
property
select_spectra(frame: Frame) -> Flag
Keep observations that don't have a given warning.
Source code in src/ASTRA/utils/spectral_conditions.py
FNAME_condition
Bases: ConditionModel
Flag the observations that have filename inside the filename_list list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename_list
|
list
|
List of files to either be outright used or list of paths to .txt files from which we can select observations |
required |
only_keep_filenames
|
Only keep the filenames that were selected. Default: False |
False
|
|
load_from_file
|
bool
|
If True (default False), use the filename_list parameter to provide a list of files that will be selected |
False
|
Source code in src/ASTRA/utils/spectral_conditions.py
cond_info: str
property
select_spectra(frame) -> Flag
Source code in src/ASTRA/utils/spectral_conditions.py
SNR_condition
Bases: ConditionModel
Reject observations based on the order-wise SNR.
Compares the SNR of the valid orders against the minimum SNR that is provided to this object.
Mostly useful for the creation of the stellar template
Source code in src/ASTRA/utils/spectral_conditions.py
minimum_SNR = minimum_SNR
instance-attribute
cond_info
property
select_spectra(frame)
Source code in src/ASTRA/utils/spectral_conditions.py
telluric_utilities
binary_mask_from_template
create_binary_template(transmittance, continuum_level, percentage_drop) -> None
Transform the transmittance spectra into a binary template.
This is based on percentage deviations from the continuum level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
continuum_level
|
ndarray()
|
Continuum level that is estimated by the children classes |
required |
Source code in src/ASTRA/utils/telluric_utilities/binary_mask_from_template.py
calculate_telluric_indexes
Compute telluric indexes.
calculate_telluric_mask(data_class: DataClass, telluric_temp: TelluricTemplate) -> np.ndarray
Construct the telluric mask.
Source code in src/ASTRA/utils/telluric_utilities/calculate_telluric_indexes.py
clean_wings
clean_wings_order(current_order_wavelengths, telluric_bin_temp, template_base_berv, BERV_window)
Around each telluric feature, remove a window that spans the entire BERV motion over the year.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
current_order_wavelengths
|
ndarray
|
Wavelengths associated with the template |
required |
telluric_bin_temp
|
ndarray
|
Telluric (binary) template |
required |
template_base_berv
|
float
|
BERV value from the template |
required |
BERV_window
|
tuple / list
|
Minimum and Maximum BERV |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Binary template with the increased span |
Source code in src/ASTRA/utils/telluric_utilities/clean_wings.py
compute_common_blocks
Compute overlap between multiple elements.
others = [[[1, 6.1], [7, 10]], [[0, 4], [6, 8], [9, 11]], [[1, 12.2]]]
module-attribute
out = compute_common(others)
module-attribute
off = 0.1 * obs_index
module-attribute
check_if_overlap(block_A, block_B)
compute_common(values)
Source code in src/ASTRA/utils/telluric_utilities/compute_common_blocks.py
compute_overlaps_blocks
Compute overlaps between multiple lists.
check_if_overlap(block_A, block_B) -> bool
Check if there is an overlap between two blocks.
find_overlaps(input_blocks: List[List[float]]) -> List[List[float]]
Loop over a list with 1D regions and find intersections among them.
Used to decrease the number of "standalone" blocks in the telluric template
E.g:
This:
|----| |----| |----| Will be merged into a single "block", as they are all intersected
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_blocks
|
List[List[float]]
|
[description] |
required |
Returns:
| Type | Description |
|---|---|
List[List[float]]
|
[description] |
TODO
- [ ] See if there is a need of porting this function to cython
Source code in src/ASTRA/utils/telluric_utilities/compute_overlaps_blocks.py
units
Collection of utilities to handle units throughout the code base.
Aside from the data conversion function, it also provides three RV "measurements", which are astropy Quantities:
- meter_second
- kilometer_second
- centimeter_second
meter_second = 1 * units.m / units.second
module-attribute
kilometer_second = 1 * units.km / units.second
module-attribute
centimeter_second = 1 * units.cm / units.second
module-attribute
test_list = [meter_second, centimeter_second]
module-attribute
convert_data(data: Union[data_vector, RV_measurement], new_units: Optional[RV_measurement] = None, as_value: bool = False) -> data_vector | RV_measurement
Accept input data that are astropy.units and converts it to a new unit and/or to a numerical value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[data_vector, RV_measurement]
|
Input data |
required |
new_units
|
Optional[RV_measurement]
|
Units to which each element will be converted to |
None
|
as_value
|
bool
|
Switch the list entries to numerical values |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
converted_list |
list
|
Data in the specified format |