From 0d177805ebedbd701d5e0e569cd7f5fac4344a8a Mon Sep 17 00:00:00 2001 From: Kristian Date: Tue, 10 Nov 2026 01:01:04 +0100 Subject: [PATCH 1/2] start the light paths of a camera behind a window pane at the pane A camera that looks into the smoke through a window pane sees the LEDs along lines of sight whose part between the camera and the pane is free of smoke. Counted from the camera, the light paths were too long and the extinction coefficients too low, by half where the pane lies halfway. The pane is the plane through pane_point with the normal pane_normal. Both are optional options of [experiment_geometry] in config_analysis.ini and of every [simulation_N] in config_stacked.ini. With a pane, the light path of an LED starts where its line of sight crosses the pane, and the camera may stand outside domain_bounds as long as the light paths behind the pane lie inside. A pane that does not separate the camera from an LED is reported with the LED. The result headers name the pane. Without the options, or with None, the light paths and the result files stay as they were. Co-Authored-By: Claude Opus 5.5 --- README.md | 23 ++ ledsa/analysis/ConfigDataAnalysis.py | 35 ++- ledsa/analysis/ConfigDataStacked.py | 17 + ledsa/analysis/Experiment.py | 237 +++++++++++--- ledsa/analysis/ExperimentData.py | 2 +- .../analysis/StackedExtinctionCoefficients.py | 18 +- .../AcceptanceTests/12_test_camera_pane.robot | 56 ++++ .../AcceptanceTests/LedsaATestLibrary.py | 39 ++- ledsa/tests/AcceptanceTests/TestExperiment.py | 37 ++- ledsa/tests/UnitTests/test_camera_pane.py | 292 ++++++++++++++++++ 10 files changed, 711 insertions(+), 45 deletions(-) create mode 100644 ledsa/tests/AcceptanceTests/12_test_camera_pane.robot create mode 100644 ledsa/tests/UnitTests/test_camera_pane.py diff --git a/README.md b/README.md index 6e94ab4..b40866c 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,29 @@ individual runs. Since image IDs are counted per run, `num_ref_images` and `ref_ be set per `[simulation_N]` section; pick the reference images of all cameras from the same time window before the fire. +### Camera behind a window pane (optional) + +A camera that looks into the smoke through a window pane, for example from outside the test +room, sees the LEDs along lines of sight whose part between the camera and the pane is free of +smoke. Only the part behind the pane belongs in the layers; counted from the camera, the light +paths are too long and the extinction coefficients come out too low. The pane is the plane +through `pane_point` with the normal `pane_normal`, in the global coordinates of +`camera_position`: + +```ini +[experiment_geometry] + camera_position = 0 -0.5 1.5 + pane_point = 0 0 0 + pane_normal = 0 1 0 +``` + +The normal may point to either side, and the pane has to separate the camera from every LED. In +`config_stacked.ini`, every `[simulation_N]` section takes a pane of its own. Without the two +options, or with `None`, the light paths reach the camera as before. The camera may then stand +outside `domain_bounds`, as long as the layers hold the light paths behind the pane. Only the +geometry is corrected: a pane whose transmission changes during the test, for example by soot or +condensate, dims the LEDs like smoke. The header of each result file names the pane. + ### Temperature correction (optional) LEDs lose radiant power as they heat up, which would otherwise be read as extinction. Reduction diff --git a/ledsa/analysis/ConfigDataAnalysis.py b/ledsa/analysis/ConfigDataAnalysis.py index 5087c7b..e2cfd2d 100644 --- a/ledsa/analysis/ConfigDataAnalysis.py +++ b/ledsa/analysis/ConfigDataAnalysis.py @@ -1,6 +1,7 @@ import configparser as cp from typing import Iterable, List, Optional, Union +from ledsa.analysis.Experiment import Pane, read_pane from ledsa.analysis.temperature_correction import TEMPERATURE_CORRECTION_CHANNELS from ledsa.core.config_file import report_removed_options, save_config @@ -62,6 +63,13 @@ def format_reference_properties(reference_property: Union[str, Iterable[str]]) - return ' '.join(str(name) for name in reference_property) +def _format_coordinates(coordinates) -> str: + """Write coordinates given as a sequence of numbers, a string or None as the value of an option.""" + if coordinates is None or isinstance(coordinates, str): + return str(coordinates) + return ' '.join(str(value) for value in coordinates) + + class ConfigDataAnalysis(cp.ConfigParser): """ Class responsible for handling the configuration data related to LEDSA's data analysis. @@ -72,7 +80,8 @@ def __init__(self, load_config_file=True, camera_position=None, num_layers=20, d reference_property='sum_col_val', average_images=False, n_summarize=2, solver='linear', weighting_preference=-6e-3, weighting_curvature=1e-2, - num_iterations=1000, lambda_reg=1e-3, reduction_files=None): + num_iterations=1000, lambda_reg=1e-3, reduction_files=None, pane_point=None, + pane_normal=None): """ :param load_config_file: Determines whether to load the config file on initialization. Defaults to True. :type load_config_file: bool @@ -115,6 +124,11 @@ def __init__(self, load_config_file=True, camera_position=None, num_layers=20, d camera channel. Channels without an entry are analysed without the correction, which is the default for every channel. :type reduction_files: dict[int, str] or None + :param pane_point: Global X, Y, Z coordinates [m] of a point on the window pane the camera + looks through into the smoke. Defaults to None, for a camera without a pane. + :type pane_point: list[float] or None + :param pane_normal: Normal vector X, Y, Z of the window pane. Defaults to None. + :type pane_normal: list[float] or None """ cp.ConfigParser.__init__(self, allow_no_value=True) if load_config_file: @@ -149,6 +163,13 @@ def __init__(self, load_config_file=True, camera_position=None, num_layers=20, d self['experiment_geometry'] = {} self.set('experiment_geometry', '# Global X Y Z position of the camera ') self['experiment_geometry'][' camera_position'] = str(camera_position) + self.set('experiment_geometry', ' # Window pane the camera looks through into the smoke, None without a pane:') + self.set('experiment_geometry', ' # the plane through the global X Y Z point pane_point [m] with the normal') + self.set('experiment_geometry', ' # X Y Z pane_normal, pointing to either side. The line of sight between the') + self.set('experiment_geometry', ' # camera and the pane is free of smoke, so only its part behind the pane is') + self.set('experiment_geometry', ' # distributed over the layers.') + self['experiment_geometry'][' pane_point'] = _format_coordinates(pane_point) + self['experiment_geometry'][' pane_normal'] = _format_coordinates(pane_normal) self['model_parameters'] = {} self.set('model_parameters', '# Parameters regarding the discretization of the spatial domain ') @@ -272,6 +293,18 @@ def get_reduction_file(self, channel: int) -> Optional[str]: return None return raw + def get_pane(self) -> Optional[Pane]: + """ + Return the window pane the camera looks through into the smoke. + + :return: The pane, None if the smoke reaches the camera, which is also the case for a config + file written before the options of the pane. + :rtype: Optional[Pane] + :raises ValueError: If only one of pane_point and pane_normal is set, or one of them is not + three numbers, or the normal is the zero vector. + """ + return read_pane(self, 'experiment_geometry', 'config_analysis.ini') + def in_camera_channels(self) -> None: """ Prompts the user to input the camera channels to analyse and updates the configuration. diff --git a/ledsa/analysis/ConfigDataStacked.py b/ledsa/analysis/ConfigDataStacked.py index 16ce23e..16285ca 100644 --- a/ledsa/analysis/ConfigDataStacked.py +++ b/ledsa/analysis/ConfigDataStacked.py @@ -3,6 +3,7 @@ from typing import Dict, List, Optional from ledsa.analysis.ConfigDataAnalysis import DEFAULT_REFERENCE_PROPERTY, parse_reference_properties +from ledsa.analysis.Experiment import Pane, read_pane from ledsa.analysis.temperature_correction import TEMPERATURE_CORRECTION_CHANNELS from ledsa.core.config_file import save_config @@ -38,6 +39,9 @@ class ConfigDataStacked(cp.ConfigParser): [simulation_0] path = /data/exp01/cam0 camera_position = 1.0 0.0 1.5 + # window pane this camera looks through into the smoke, optional + pane_point = 0.5 0.0 0.0 + pane_normal = 1.0 0.0 0.0 [simulation_1] path = /data/exp01/cam1 @@ -144,6 +148,14 @@ def get_camera_position(self, sim_idx: int) -> List[float]: """Camera position ``[x, y, z]`` for simulation *sim_idx*.""" return self.get_list_of_values(f'simulation_{sim_idx}', 'camera_position', dtype=float) + def get_pane(self, sim_idx: int) -> Optional[Pane]: + """Window pane camera *sim_idx* looks through into the smoke, ``None`` if + the smoke reaches the camera. + + :raises ValueError: if the options of the pane are set inconsistently. + """ + return read_pane(self, f'simulation_{sim_idx}', self._filename) + def get_ref_img_indices(self, sim_idx: int) -> Optional[List[int]]: """Reference image IDs of simulation *sim_idx*; ``None`` means use :meth:`get_num_ref_images`. @@ -364,6 +376,11 @@ def create_template(cls, filename: str = DEFAULT_FILENAME, num_simulations: int cfg[section]['path'] = f'/path/to/sim{i}' cfg.set(section, '# Global X Y Z position [m] of camera') cfg[section]['camera_position'] = '0.0 0.0 1.5' + cfg.set(section, '# Window pane the camera looks through into the smoke (optional): the plane') + cfg.set(section, '# through the global X Y Z point pane_point [m] with the normal X Y Z') + cfg.set(section, '# pane_normal. Only the line of sight behind the pane is in the smoke.') + cfg.set(section, '# pane_point = 0.0 0.5 0.0') + cfg.set(section, '# pane_normal = 0.0 1.0 0.0') cfg.set(section, '# Reference images of this camera; both options override the ones above') cfg.set(section, '# Image IDs are counted per camera, so choose images from the same time') cfg.set(section, '# window before the fire in every camera') diff --git a/ledsa/analysis/Experiment.py b/ledsa/analysis/Experiment.py index 9d1f1d6..920bb12 100644 --- a/ledsa/analysis/Experiment.py +++ b/ledsa/analysis/Experiment.py @@ -1,10 +1,14 @@ +import configparser as cp import os from dataclasses import dataclass, field from pathlib import Path -from typing import List +from typing import List, Optional, Tuple import numpy as np +# options of a camera section that describe the window pane in front of the camera +PANE_OPTIONS = ('pane_point', 'pane_normal') + class InconsistentDistanceError(ValueError): """The light path of an LED does not add up to its distance from the camera. @@ -15,6 +19,14 @@ class InconsistentDistanceError(ValueError): """ +class PaneGeometryError(ValueError): + """The window pane in front of the camera does not lie between the camera and an LED. + + The light path of an LED through the smoke starts where its line of sight crosses the pane. + An LED on the camera's side of the pane, or on the pane itself, has no such crossing. + """ + + @dataclass class Layer: """ @@ -76,6 +88,42 @@ def __repr__(self): return f'Layers(amount={self.amount}, bottom_border={self.bottom_border}, top_border={self.top_border})' +@dataclass(frozen=True) +class Pane: + """ + Window pane the camera looks through into the smoke. + + The pane is the plane through ``point`` with the normal ``normal``; which of the two directions + the normal points to does not matter. The part of a line of sight between the camera and the + pane is free of smoke, so the light path of an LED through the smoke starts where its line of + sight crosses the pane. The transmission of the pane itself is the same in the reference images + and cancels in I/I0, and the refraction in a pane with parallel faces shifts the line of sight by + less than the thickness of the pane, so neither is taken into account. + + :ivar point: Global X, Y, Z coordinates [m] of a point on the pane + :vartype point: Tuple[float, float, float] + :ivar normal: Normal vector of the pane, of any length but zero + :vartype normal: Tuple[float, float, float] + """ + point: Tuple[float, float, float] + normal: Tuple[float, float, float] + + def __post_init__(self): + for name in ('point', 'normal'): + given = getattr(self, name) + coordinates = tuple(float(value) for value in given) + if len(coordinates) != 3 or not np.isfinite(coordinates).all(): + raise ValueError(f'The {name} of the pane needs three finite coordinates X Y Z, got {given}.') + object.__setattr__(self, name, coordinates) + if not any(self.normal): + raise ValueError('The normal of the pane must not be the zero vector.') + + def __str__(self): + point = ', '.join(f'{value:g}' for value in self.point) + normal = ', '.join(f'{value:g}' for value in self.normal) + return f'pane through ({point}) with the normal ({normal})' + + @dataclass class Camera: """ @@ -87,16 +135,23 @@ class Camera: :vartype pos_y: float :ivar pos_z: The z-coordinate of the camera :vartype pos_z: float + :ivar pane: Window pane the camera looks through into the smoke, None if the smoke reaches the + camera + :vartype pane: Pane or None """ pos_x: float pos_y: float pos_z: float + pane: Optional[Pane] = None def __str__(self): - return f'Camera: ({self.pos_x}, {self.pos_y}, {self.pos_z})\n' + if self.pane is None: + return f'Camera: ({self.pos_x}, {self.pos_y}, {self.pos_z})\n' + return f'Camera: ({self.pos_x}, {self.pos_y}, {self.pos_z}), behind the {self.pane}\n' def __repr__(self): - return f'Camera(pos_x={self.pos_x}, pos_y={self.pos_y}, pos_z={self.pos_z})' + pane = '' if self.pane is None else f', pane={self.pane!r}' + return f'Camera(pos_x={self.pos_x}, pos_y={self.pos_y}, pos_z={self.pos_z}{pane})' @dataclass @@ -176,57 +231,108 @@ def __str__(self): str(self.camera) return out + def calc_smoke_path_start(self, led: LED) -> Tuple[float, float, float]: + """ + Find the point where the light path between an LED and the camera enters the smoke. + + Without a pane, the smoke reaches the camera and the light path starts there. Behind a pane, + it starts where the line of sight of the LED crosses the pane, because the part between the + pane and the camera is free of smoke. + + :param led: The LED light source + :type led: LED + :return: Global X, Y, Z coordinates of the start of the light path through the smoke + :rtype: Tuple[float, float, float] + :raises PaneGeometryError: If the pane does not lie between the camera and the LED. + """ + camera = (self.camera.pos_x, self.camera.pos_y, self.camera.pos_z) + pane = self.camera.pane + if pane is None: + return camera + camera_pos = np.array(camera, dtype=float) + led_pos = np.array([led.pos_x, led.pos_y, led.pos_z], dtype=float) + # distances from the pane, signed by the side and in units of the length of the normal + camera_side = np.dot(camera_pos - pane.point, pane.normal) + led_side = np.dot(led_pos - pane.point, pane.normal) + if led_side == 0 or camera_side * led_side > 0: + raise PaneGeometryError( + f'LED {led.id} of LED array {self.led_array} at ({led.pos_x}, {led.pos_y}, {led.pos_z}) ' + f'is not behind the {pane} as seen from the camera at {camera}, so its line of sight ' + f'does not cross the pane into the smoke. Check pane_point and pane_normal in the ' + f'analysis configuration: the pane has to separate the camera from every LED.') + fraction = camera_side / (camera_side - led_side) + return tuple(camera_pos + fraction * (led_pos - camera_pos)) + def calc_traversed_dist_per_layer(self, led: LED) -> np.ndarray: """ Calculate the distance traversed by light from an LED through each layer to the camera. + Behind a pane, only the part of the light path between the pane and the LED is traversed in + the smoke, see calc_smoke_path_start. + :param led: The LED light source :type led: LED :return: Array of distances traversed in each layer :rtype: np.ndarray - :raises InconsistentDistanceError: If the distances do not add up to the distance between - the LED and the camera. + :raises InconsistentDistanceError: If the distances do not add up to the length of the light + path through the smoke. + :raises PaneGeometryError: If the pane does not lie between the camera and the LED. """ - horizontal_dist = np.sqrt((self.camera.pos_x - led.pos_x) ** 2 + (self.camera.pos_y - led.pos_y) ** 2) - alpha = np.arctan((led.pos_z - self.camera.pos_z) / horizontal_dist) + start = self.calc_smoke_path_start(led) + start_x, start_y, start_z = start + horizontal_dist = np.sqrt((start_x - led.pos_x) ** 2 + (start_y - led.pos_y) ** 2) + alpha = np.arctan((led.pos_z - start_z) / horizontal_dist) if alpha == 0: - distance_per_layer = self.calc_traversed_dist_in_plane(led) + distance_per_layer = self.calc_traversed_dist_in_plane(led, start) else: - distance_per_layer = self.calc_traversed_dist_per_layer_with_nonzero_alpha(alpha, led) - - if not self.distance_calculation_is_consistent(distance_per_layer, led): - euclidean_dist = np.sqrt((self.camera.pos_x - led.pos_x) ** 2 + - (self.camera.pos_y - led.pos_y) ** 2 + - (self.camera.pos_z - led.pos_z) ** 2) + distance_per_layer = self.calc_traversed_dist_per_layer_with_nonzero_alpha(alpha, led, start) + + if not self.distance_calculation_is_consistent(distance_per_layer, led, start=start): + path_length = np.sqrt((start_x - led.pos_x) ** 2 + + (start_y - led.pos_y) ** 2 + + (start_z - led.pos_z) ** 2) + if self.camera.pane is None: + path_end = f'while the LED is {path_length:.6g} away from the camera' + range_end = 'the camera' + else: + path_end = (f'while the LED is {path_length:.6g} away from the point ({start_x:.6g}, ' + f'{start_y:.6g}, {start_z:.6g}) where its line of sight crosses the ' + f'{self.camera.pane}') + range_end = 'the points where the lines of sight cross the pane' raise InconsistentDistanceError( f'The light path of LED {led.id} of LED array {self.led_array} traverses the layers ' - f'over {np.sum(distance_per_layer):.6g}, while the LED is {euclidean_dist:.6g} away ' - f'from the camera. LED position: ({led.pos_x}, {led.pos_y}, {led.pos_z}), camera ' - f'position: ({self.camera.pos_x}, {self.camera.pos_y}, {self.camera.pos_z}), layers: ' - f'{self.layers.bottom_border} to {self.layers.top_border}. The part of the light path ' - f'outside the layers belongs to no layer, so set domain_bounds in the analysis ' - f'configuration to a range that holds the camera and every LED of the array.') + f'over {np.sum(distance_per_layer):.6g}, {path_end}. LED position: ({led.pos_x}, ' + f'{led.pos_y}, {led.pos_z}), camera position: ({self.camera.pos_x}, {self.camera.pos_y}, ' + f'{self.camera.pos_z}), layers: {self.layers.bottom_border} to {self.layers.top_border}. ' + f'The part of the light path outside the layers belongs to no layer, so set domain_bounds ' + f'in the analysis configuration to a range that holds {range_end} and every LED of the ' + f'array.') return distance_per_layer - def calc_traversed_dist_in_plane(self, led: LED) -> np.ndarray: + def calc_traversed_dist_in_plane(self, led: LED, + start: Optional[Tuple[float, float, float]] = None) -> np.ndarray: """ Calculate the distance traversed by light from an LED in a plane to the camera. :param led: The LED light source :type led: LED + :param start: Start of the light path through the smoke, the camera position if None + :type start: Tuple[float, float, float] or None :return: Array of distances traversed in each layer within the plane :rtype: np.ndarray """ + start_x, start_y, start_z = self._camera_position_if_none(start) distance_per_layer = np.zeros(self.layers.amount) - horizontal_dist = np.sqrt((self.camera.pos_x - led.pos_x) ** 2 + (self.camera.pos_y - led.pos_y) ** 2) + horizontal_dist = np.sqrt((start_x - led.pos_x) ** 2 + (start_y - led.pos_y) ** 2) for layer in range(self.layers.amount): layer_bottom = self.layers.borders[layer] layer_top = self.layers.borders[layer + 1] - if layer_bottom <= self.camera.pos_z < layer_top: + if layer_bottom <= start_z < layer_top: distance_per_layer[layer] = horizontal_dist return distance_per_layer - def calc_traversed_dist_per_layer_with_nonzero_alpha(self, alpha: float, led: LED) -> np.ndarray: + def calc_traversed_dist_per_layer_with_nonzero_alpha( + self, alpha: float, led: LED, start: Optional[Tuple[float, float, float]] = None) -> np.ndarray: """ Calculate the distance traversed by light from an LED through each layer to the camera, taking into account a non-zero angle of incidence. @@ -235,18 +341,22 @@ def calc_traversed_dist_per_layer_with_nonzero_alpha(self, alpha: float, led: LE :type alpha: float :param led: The LED light source :type led: LED + :param start: Start of the light path through the smoke, the camera position if None + :type start: Tuple[float, float, float] or None :return: Array of distances traversed in each layer considering the angle :rtype: np.ndarray """ + start_z = self._camera_position_if_none(start)[2] distance_per_layer = np.zeros(self.layers.amount) for layer in range(self.layers.amount): layer_bottom = self.layers.borders[layer] layer_top = self.layers.borders[layer + 1] - th = self.calc_traversed_height_in_layer(led.pos_z, layer_bottom, layer_top) + th = self.calc_traversed_height_in_layer(led.pos_z, layer_bottom, layer_top, start_z) distance_per_layer[layer] = np.abs(th / np.sin(alpha)) return distance_per_layer - def calc_traversed_height_in_layer(self, led_height: float, layer_bot: float, layer_top: float) -> float: + def calc_traversed_height_in_layer(self, led_height: float, layer_bot: float, layer_top: float, + start_height: Optional[float] = None) -> float: """ Calculate the vertical distance (height) traversed by light from an LED within a layer. @@ -256,11 +366,16 @@ def calc_traversed_height_in_layer(self, led_height: float, layer_bot: float, la :type layer_bot: float :param layer_top: The z-coordinate of the top of the layer :type layer_top: float + :param start_height: The z-coordinate of the start of the light path through the smoke, that + of the camera if None + :type start_height: float or None :return: The vertical distance traversed within the layer :rtype: float """ - top_end = max(self.camera.pos_z, led_height) - bot_end = min(self.camera.pos_z, led_height) + if start_height is None: + start_height = self.camera.pos_z + top_end = max(start_height, led_height) + bot_end = min(start_height, led_height) bot = max(bot_end, layer_bot) top = min(top_end, layer_top) h = top - bot @@ -268,7 +383,8 @@ def calc_traversed_height_in_layer(self, led_height: float, layer_bot: float, la h = 0 return h - def distance_calculation_is_consistent(self, distance_per_layer: np.ndarray, led: LED, silent=True) -> bool: + def distance_calculation_is_consistent(self, distance_per_layer: np.ndarray, led: LED, silent=True, + start: Optional[Tuple[float, float, float]] = None) -> bool: """ Check if the computed distance values for each layer are consistent with the Euclidean distance. @@ -278,19 +394,27 @@ def distance_calculation_is_consistent(self, distance_per_layer: np.ndarray, led :type led: LED :param silent: If set to False, prints out debugging information, defaults to True :type silent: bool, optional + :param start: Start of the light path through the smoke, the camera position if None + :type start: Tuple[float, float, float] or None :return: True if computations are consistent, False otherwise :rtype: bool """ - if np.abs(np.sum(distance_per_layer) - np.sqrt((self.camera.pos_x - led.pos_x) ** 2 + - (self.camera.pos_y - led.pos_y) ** 2 + - (self.camera.pos_z - led.pos_z) ** 2)) > 1e-6: + start_x, start_y, start_z = self._camera_position_if_none(start) + if np.abs(np.sum(distance_per_layer) - np.sqrt((start_x - led.pos_x) ** 2 + + (start_y - led.pos_y) ** 2 + + (start_z - led.pos_z) ** 2)) > 1e-6: if not silent: - print("error in distance computation, camera_x: {}, camera_y: {} camera_z: {}, led_x: {}, led_y: {}, " - "led_z: {}".format( - self.camera.pos_x, self.camera.pos_y, self.camera.pos_z, led.pos_x, led.pos_y, led.pos_z)) + print("error in distance computation, start_x: {}, start_y: {} start_z: {}, led_x: {}, led_y: {}, " + "led_z: {}".format(start_x, start_y, start_z, led.pos_x, led.pos_y, led.pos_z)) return False return True + def _camera_position_if_none(self, start: Optional[Tuple[float, float, float]]) -> Tuple[float, float, float]: + """Return start, or the position of the camera if start is None.""" + if start is None: + return self.camera.pos_x, self.camera.pos_y, self.camera.pos_z + return start + def set_leds(self) -> None: """ Initialize the LED instances involved in the experiment based on loaded data. @@ -332,3 +456,46 @@ def get_led_positions(self, ids: np.ndarray) -> List[np.ndarray]: search_areas_led_array.append(search_areas_all[led_id]) search_areas_led_array = np.array(search_areas_led_array) return [search_areas_led_array[:, 3], search_areas_led_array[:, 4], search_areas_led_array[:, 5]] + + +def read_pane(config: cp.ConfigParser, section: str, file_name: str) -> Optional[Pane]: + """ + Read the window pane in front of a camera from the options pane_point and pane_normal. + + Both options are optional, so a config file written before them, or one that sets them to + None, keeps the light paths reaching the camera through the smoke. + + :param config: The loaded config file + :type config: configparser.ConfigParser + :param section: Section holding the options of the camera + :type section: str + :param file_name: Name of the config file, for the error messages + :type file_name: str + :return: The pane, None if neither option is set + :rtype: Optional[Pane] + :raises ValueError: If only one of the options is set, if one of them is not three numbers or if + the normal is the zero vector. + """ + values = {} + for option in PANE_OPTIONS: + raw = config.get(section, option, fallback=None) + raw = '' if raw is None else raw.strip() + values[option] = None if raw.lower() in ('', 'none') else raw + if all(value is None for value in values.values()): + return None + if any(value is None for value in values.values()): + set_option, unset_option = PANE_OPTIONS if values[PANE_OPTIONS[0]] is not None else PANE_OPTIONS[::-1] + raise ValueError(f'[{section}] of {file_name} sets {set_option} but not {unset_option}. A pane needs ' + f'both, a point on the pane and its normal.') + coordinates = {} + for option, raw in values.items(): + try: + coordinates[option] = [float(item) for item in raw.split()] + except ValueError: + coordinates[option] = [] + if len(coordinates[option]) != 3: + raise ValueError(f'{option} = {raw} in [{section}] of {file_name} is not three numbers X Y Z.') + try: + return Pane(*(coordinates[option] for option in PANE_OPTIONS)) + except ValueError as err: + raise ValueError(f'[{section}] of {file_name}: {err}') from None diff --git a/ledsa/analysis/ExperimentData.py b/ledsa/analysis/ExperimentData.py index 7a47836..16fc218 100644 --- a/ledsa/analysis/ExperimentData.py +++ b/ledsa/analysis/ExperimentData.py @@ -136,7 +136,7 @@ def load_config_parameters(self) -> None: camera_position = config_analysis.get_list_of_values('experiment_geometry', 'camera_position', dtype=float) self.layers = Layers(num_layers, *domain_bounds) - self.camera = Camera(*camera_position) + self.camera = Camera(*camera_position, pane=config_analysis.get_pane()) self.n_cpus = int(config_analysis['DEFAULT']['num_cores']) self.merge_led_arrays = str(self.config['analyse_positions']['merge_led_array_indices']) diff --git a/ledsa/analysis/StackedExtinctionCoefficients.py b/ledsa/analysis/StackedExtinctionCoefficients.py index 5c2daee..f6f6d24 100644 --- a/ledsa/analysis/StackedExtinctionCoefficients.py +++ b/ledsa/analysis/StackedExtinctionCoefficients.py @@ -110,7 +110,7 @@ def __init__(self, config: ConfigDataStacked, led_array_id: int, channel: int, exp = Experiment( layers=self.layers, led_array=arr_id, - camera=Camera(*cam_pos), + camera=Camera(*cam_pos, pane=config.get_pane(sim_idx)), path=config.get_simulation_path(sim_idx), channel=channel, merge_led_arrays='None', @@ -493,7 +493,7 @@ def save(self) -> None: f'sim{idx}:arr{arr}' for idx, arr in sorted(self.led_array_mapping.items()) ) header = ( - f'Stacked inversion | {sim_info} | solver: {self.solver} | ' + f'Stacked inversion | {sim_info} | {self._pane_info()}solver: {self.solver} | ' f'ref_prop: {self.reference_property} | ' f'ref_imgs: {self._ref_img_info()} | ' f'temperature_correction: {self._sub_solvers[0].temperature_correction_info()} | ' @@ -539,6 +539,20 @@ def __str__(self) -> str: # Internal helpers # ------------------------------------------------------------------ + def _pane_info(self) -> str: + """Header entries of the cameras behind a window pane. + + Only a camera behind a pane is named, so the header of a run without panes stays as it was. + + :return: One entry per camera behind a pane, each ending in a separator, or an empty string. + :rtype: str + """ + return ''.join( + f'sim{idx} behind the {exp.camera.pane} | ' + for idx, exp in zip(sorted(self.led_array_mapping), self.sub_experiments) + if exp.camera.pane is not None + ) + def _ref_img_info(self) -> str: """Describe the reference images of every simulation, e.g. ``sim0 first 10, sim1 [385, 386]``. diff --git a/ledsa/tests/AcceptanceTests/12_test_camera_pane.robot b/ledsa/tests/AcceptanceTests/12_test_camera_pane.robot new file mode 100644 index 0000000..d042eaa --- /dev/null +++ b/ledsa/tests/AcceptanceTests/12_test_camera_pane.robot @@ -0,0 +1,56 @@ +*** Settings *** +Resource global_keywords.resource + +Suite Setup Prepare Images Of A Camera Behind A Pane +Suite Teardown Change Directory ${WORKDIR} + +Force Tags camera_pane + + +*** Variables *** +${PANE_DIR} ${WORKDIR}${/}camera_behind_a_pane +# The camera stands at y = 0 and the LEDs at y = 4, so a pane at y = 2 leaves half of every line +# of sight in the smoke. +${PANE_POINT} 0 2 0 +${PANE_NORMAL} 0 1 0 + + +*** Test Cases *** +The Light Paths Of A Camera Behind A Pane Start At The Pane + [Documentation] The camera looks through a window pane into the smoke, so the part of every line of + ... sight between the camera and the pane is free of smoke. The test images have smoke + ... behind the pane only. With the pane in config_analysis.ini, the extinction coefficients + ... match the input. + Create And Fill Config Analysis linear pane_point=${PANE_POINT} pane_normal=${PANE_NORMAL} + Execute Ledsa --analysis + Extinction Coefficients Should Match The Input 2 + Extinction Coefficients Should Match The Input 3 + Extinction Coefficients Should Match The Input 4 + +Without The Pane The Smoke Is Spread Over The Whole Line Of Sight + [Documentation] Analysed as if the smoke reached the camera, which stays the default without pane_point + ... and pane_normal, the same images give coefficients half as large for the constant + ... extinction of image 2, because every light path is taken twice as long as its part in + ... the smoke. This is what the pane corrects. + Create And Fill Config Analysis linear + Execute Ledsa --analysis + ${ratio} = Mean Ratio Of Computed To Input Extinction Coefficients 2 linear + Should Be True 0.4 < ${ratio} < 0.6 + + +*** Keywords *** +Prepare Images Of A Camera Behind A Pane + Create Directory ${PANE_DIR} + Change Directory ${PANE_DIR} + Create Test Data pane_point=${PANE_POINT} pane_normal=${PANE_NORMAL} + Create Config + ${leds} = Execute Ledsa S1 ${TRUE} + Should Be Equal ${leds} 100 + Execute Ledsa -s2 + Execute Ledsa --coordinates + Execute Ledsa -s3_fast + +Extinction Coefficients Should Match The Input + [Arguments] ${image_id} + ${rmse} = Check Input Vs Computed Extinction Coefficients ${image_id} linear + Should Be True ${rmse} < 0.05 diff --git a/ledsa/tests/AcceptanceTests/LedsaATestLibrary.py b/ledsa/tests/AcceptanceTests/LedsaATestLibrary.py index 962d9e0..20d9a36 100644 --- a/ledsa/tests/AcceptanceTests/LedsaATestLibrary.py +++ b/ledsa/tests/AcceptanceTests/LedsaATestLibrary.py @@ -14,7 +14,7 @@ from robot.libraries.BuiltIn import BuiltIn from scipy.stats import norm -from TestExperiment import TestExperiment, Layers, Camera +from TestExperiment import TestExperiment, Layers, Camera, Pane from ledsa.analysis.ConfigDataAnalysis import ConfigDataAnalysis from ledsa.analysis.ConfigDataStacked import ConfigDataStacked from ledsa.core.ConfigData import ConfigData @@ -39,12 +39,22 @@ def change_dir(self, new_dir): os.chdir(new_dir) @keyword - def create_test_data(self, num_of_leds=100, num_of_layers=20, bottom_border=0, top_border=3): + def create_test_data(self, num_of_leds=100, num_of_layers=20, bottom_border=0, top_border=3, + pane_point=None, pane_normal=None): + """Create the test images of four extinction profiles, seen by a camera at (0, 0, 2). + + :param pane_point: Point X Y Z of a window pane the camera looks through into the smoke, so + that the smoke dims the LEDs only behind the pane. None for smoke up to the camera. + :param pane_normal: Normal X Y Z of that pane. + """ # Create test_data directory if it doesn't exist if not os.path.exists('test_data'): os.makedirs('test_data') camera = Camera(0, 0, 2) + pane = None + if pane_point is not None: + pane = Pane(_coordinates(pane_point), _coordinates(pane_normal)) layers = Layers(num_of_layers, bottom_border, top_border) extinction_coefficients_set = [] @@ -76,7 +86,7 @@ def extco_quad(z): extinction_coefficients_set.append(extco_quad(z_range)) for image_id, extinction_coefficients in enumerate(extinction_coefficients_set): - ex = TestExperiment(camera=camera, layers=layers) + ex = TestExperiment(camera=camera, layers=layers, pane=pane) np.savetxt(os.path.join('test_data', f'test_extinction_coefficients_input_{image_id + 1}.csv'), extinction_coefficients) for z in np.linspace(bottom_border + 0.05, top_border - 0.05, num_of_leds): ex.add_led(0, 4, z) @@ -397,6 +407,15 @@ def check_input_vs_computed_extinction_coefficients(self, image_id, solver, led_ np.mean((extinction_coefficients_input - extinction_coefficients_computed[int(image_id) - 1, :]) ** 2)) return rmse + @keyword + def mean_ratio_of_computed_to_input_extinction_coefficients(self, image_id, solver, led_array=0, channel=0): + """Return the mean computed extinction coefficient of an image over the mean of its input.""" + _, extinction_coefficients_computed = load_extinction_coefficients_computed(solver, channel, led_array) + extinction_coefficients_input = np.loadtxt( + os.path.join('test_data', f'test_extinction_coefficients_input_{image_id}.csv'), delimiter=',') + return float(np.mean(extinction_coefficients_computed[int(image_id) - 1, :]) / + np.mean(extinction_coefficients_input)) + @keyword def create_and_fill_config(self, first=1, last=4): # Create test_data directory if it doesn't exist @@ -418,11 +437,13 @@ def create_and_fill_config(self, first=1, last=4): @keyword def create_and_fill_config_analysis(self, solver, reference_property='sum_col_val', num_ref_images=1, - average_images=False, n_summarize=2): + average_images=False, n_summarize=2, pane_point=None, pane_normal=None): """Write config_analysis.ini. num_ref_images lets a test take the reference from another image than the first. :param average_images: Summarize the images after the reference images. :param n_summarize: Number of consecutive images summarized into one. + :param pane_point: Point X Y Z of the window pane in front of the camera, None without a pane. + :param pane_normal: Normal X Y Z of the window pane. """ average_images = str(average_images).lower() == 'true' conf = ConfigDataAnalysis(load_config_file=False, camera_position=None, num_layers=20, domain_bounds=None, @@ -431,7 +452,8 @@ def create_and_fill_config_analysis(self, solver, reference_property='sum_col_va average_images=average_images, n_summarize=int(n_summarize), solver=solver, weighting_preference=-6e-3, weighting_curvature=1e-2, - num_iterations=1000, lambda_reg=1e-3) + num_iterations=1000, lambda_reg=1e-3, pane_point=pane_point, + pane_normal=pane_normal) conf.set('experiment_geometry', ' camera_position', '0 0 2') conf.set('model_parameters', ' domain_bounds', '0 3') conf.save() @@ -731,6 +753,13 @@ def read_experiment_times_of_images(infos_path): times_of_img[name] = float(experiment_time) return times_of_img +def _coordinates(value): + """Coordinates X Y Z given as a string of a Robot Framework test, or as numbers.""" + if isinstance(value, str): + return tuple(float(item) for item in value.split()) + return tuple(float(item) for item in value) + + def extinction_coefficients_path(solver, channel, led_array, reference_property='sum_col_val'): """Path of an extinction coefficient file, which lies in a directory of its solver and quantity. diff --git a/ledsa/tests/AcceptanceTests/TestExperiment.py b/ledsa/tests/AcceptanceTests/TestExperiment.py index 71b924c..06cbd8b 100644 --- a/ledsa/tests/AcceptanceTests/TestExperiment.py +++ b/ledsa/tests/AcceptanceTests/TestExperiment.py @@ -51,6 +51,13 @@ def __repr__(self): return f'Camera(pos_x={self.pos_x}, pos_y={self.pos_y}, pos_z={self.pos_z})' +@dataclass +class Pane: + """Window pane between the camera and the smoke: the plane through point with the normal normal.""" + point: tuple + normal: tuple + + @dataclass class LED: id: int @@ -60,9 +67,10 @@ class LED: class TestExperiment: - def __init__(self, layers: Layers, camera: Camera): + def __init__(self, layers: Layers, camera: Camera, pane: Pane = None): self.layers = layers self.camera = camera + self.pane = pane self.leds = [] self.extinction_coefficients = np.zeros(layers.amount) @@ -74,6 +82,8 @@ def set_extinction_coefficients(self, extinction_coefficients_array): self.extinction_coefficients = extinction_coefficients_array def calc_traversed_dist_per_layer(self, led: LED) -> np.ndarray: + if self.pane is not None: + return self.calc_traversed_dist_per_layer_behind_pane(led) horizontal_dist = np.sqrt((self.camera.pos_x - led.pos_x) ** 2 + (self.camera.pos_y - led.pos_y) ** 2) alpha = np.arctan((led.pos_z - self.camera.pos_z) / horizontal_dist) if alpha == 0: @@ -85,6 +95,31 @@ def calc_traversed_dist_per_layer(self, led: LED) -> np.ndarray: distance_per_layer = None return distance_per_layer + def calc_traversed_dist_per_layer_behind_pane(self, led: LED) -> np.ndarray: + """Distances in the layers of the part of the line of sight between the pane and the LED. + + Only that part runs through the smoke. It is cut at the layer borders by the share of its + height each layer holds, so that this does not repeat how LEDSA computes the light paths. + """ + camera = np.array([self.camera.pos_x, self.camera.pos_y, self.camera.pos_z], dtype=float) + led_pos = np.array([led.pos_x, led.pos_y, led.pos_z], dtype=float) + point = np.array(self.pane.point, dtype=float) + normal = np.array(self.pane.normal, dtype=float) + crossing = np.dot(point - camera, normal) / np.dot(led_pos - camera, normal) + start = camera + crossing * (led_pos - camera) + length = np.linalg.norm(led_pos - start) + z_low, z_high = sorted((start[2], led_pos[2])) + distance_per_layer = np.zeros(self.layers.amount) + for layer in range(self.layers.amount): + bottom, top = self.layers.borders[layer], self.layers.borders[layer + 1] + if z_high == z_low: + if bottom <= z_low < top: + distance_per_layer[layer] = length + else: + overlap = max(0.0, min(top, z_high) - max(bottom, z_low)) + distance_per_layer[layer] = length * overlap / (z_high - z_low) + return distance_per_layer + def calc_traversed_dist_in_plane(self, led: LED) -> np.ndarray: distance_per_layer = np.zeros(self.layers.amount) horizontal_dist = np.sqrt((self.camera.pos_x - led.pos_x) ** 2 + (self.camera.pos_y - led.pos_y) ** 2) diff --git a/ledsa/tests/UnitTests/test_camera_pane.py b/ledsa/tests/UnitTests/test_camera_pane.py new file mode 100644 index 0000000..7578576 --- /dev/null +++ b/ledsa/tests/UnitTests/test_camera_pane.py @@ -0,0 +1,292 @@ +"""Unit tests for a camera that looks through a window pane into the smoke. + +The part of a line of sight between the camera and the pane is free of smoke, so only its part +behind the pane is distributed over the layers. Without a pane, the light paths reach the camera +as before. +""" +import configparser + +import numpy as np +import pytest + +import ledsa.analysis.StackedExtinctionCoefficients as stacked_module +from ledsa.analysis.ConfigDataAnalysis import ConfigDataAnalysis +from ledsa.analysis.ConfigDataStacked import ConfigDataStacked +from ledsa.analysis.Experiment import (Camera, Experiment, InconsistentDistanceError, LED, Layers, Pane, + PaneGeometryError, read_pane) +from ledsa.analysis.ExtinctionCoefficientsNonLinear import ExtinctionCoefficientsNonLinear +from ledsa.analysis.StackedExtinctionCoefficients import StackedExtinctionCoefficients + +NUM_LAYERS = 30 +BOTTOM_BORDER = 0.0 +TOP_BORDER = 3.0 +CAMERA_POSITION = (0.0, 0.0, 2.0) +LED_DISTANCE = 4.0 # the LEDs stand at y = 4, in front of the camera at y = 0 +HEIGHTS = [0.5, 1.5, 2.5] +# the pane at y = 2 lies halfway between the camera and the LEDs +HALFWAY_PANE = Pane((0.0, 2.0, 0.0), (0.0, 1.0, 0.0)) + + +class ExperimentStub(Experiment): + """Experiment whose LEDs are given by their heights instead of read from the analysis files.""" + + def __init__(self, heights, pane=None, camera_position=CAMERA_POSITION): + self.heights = heights + super().__init__(layers=Layers(NUM_LAYERS, BOTTOM_BORDER, TOP_BORDER), led_array=0, + camera=Camera(*camera_position, pane=pane)) + + def set_leds(self) -> None: + self.leds = [LED(led_id, 0.0, LED_DISTANCE, height) for led_id, height in enumerate(self.heights)] + self.num_leds = len(self.leds) + + +def distances(heights, pane=None, camera_position=CAMERA_POSITION): + """Distances traversed in the layers, one row per LED in the order of the heights.""" + experiment = ExperimentStub(heights, pane, camera_position) + return np.array([experiment.calc_traversed_dist_per_layer(led) for led in experiment.leds]) + + +def distance_to_camera(height, camera_position=CAMERA_POSITION): + return np.hypot(LED_DISTANCE - camera_position[1], height - camera_position[2]) + + +class TestLightPathsBehindAPane: + def test_without_a_pane_the_light_paths_reach_the_camera(self): + np.testing.assert_allclose(distances(HEIGHTS).sum(axis=1), + [distance_to_camera(height) for height in HEIGHTS]) + + def test_the_light_path_starts_where_the_line_of_sight_crosses_the_pane(self): + experiment = ExperimentStub([1.0], HALFWAY_PANE) + + start = experiment.calc_smoke_path_start(experiment.leds[0]) + + np.testing.assert_allclose(start, (0.0, 2.0, 1.5)) + + def test_a_pane_halfway_halves_the_light_paths(self): + np.testing.assert_allclose(distances(HEIGHTS, HALFWAY_PANE).sum(axis=1), + [distance_to_camera(height) / 2 for height in HEIGHTS]) + + def test_only_the_layers_between_the_pane_and_the_led_hold_the_light_path(self): + # the line of sight of the LED at 0.5 m crosses the pane at 1.25 m + full, = distances([0.5]) + behind, = distances([0.5], HALFWAY_PANE) + borders = np.linspace(BOTTOM_BORDER, TOP_BORDER, NUM_LAYERS + 1) + below_the_crossing = borders[1:] <= 1.25 + above_the_crossing = borders[:-1] >= 1.25 + + np.testing.assert_allclose(behind[below_the_crossing], full[below_the_crossing]) + assert not behind[above_the_crossing].any() + + def test_the_direction_and_length_of_the_normal_do_not_matter(self): + flipped = Pane((0.0, 2.0, 0.0), (0.0, -3.0, 0.0)) + + np.testing.assert_allclose(distances(HEIGHTS, flipped), distances(HEIGHTS, HALFWAY_PANE)) + + def test_an_oblique_pane(self): + # the plane y + z / 2 = 2 crosses the line of sight to the LED at 1 m at 2/7 of its length + oblique = Pane((0.0, 2.0, 0.0), (0.0, 1.0, 0.5)) + + np.testing.assert_allclose(distances([1.0], oblique).sum(), 5 / 7 * distance_to_camera(1.0)) + + def test_a_level_line_of_sight_lies_in_the_layer_of_the_camera(self): + behind, = distances([CAMERA_POSITION[2]], HALFWAY_PANE) + + assert behind.sum() == pytest.approx(LED_DISTANCE / 2) + assert np.count_nonzero(behind) == 1 + + def test_a_camera_on_the_pane_sees_the_smoke_from_the_camera_on(self): + pane = Pane(CAMERA_POSITION, (0.0, 1.0, 0.0)) + + np.testing.assert_allclose(distances(HEIGHTS, pane), distances(HEIGHTS)) + + def test_an_led_on_the_camera_side_of_the_pane_is_reported(self): + behind_the_leds = Pane((0.0, LED_DISTANCE + 1, 0.0), (0.0, 1.0, 0.0)) + + with pytest.raises(PaneGeometryError, match='LED 0 '): + distances([1.0], behind_the_leds) + + def test_an_led_on_the_pane_is_reported(self): + through_the_leds = Pane((0.0, LED_DISTANCE, 0.0), (0.0, 1.0, 0.0)) + + with pytest.raises(PaneGeometryError, match='pane_normal'): + distances([1.0], through_the_leds) + + def test_a_camera_above_the_layers_is_accepted_if_the_light_paths_behind_the_pane_lie_inside(self): + # the lines of sight cross the pane at 2.0 m and 2.5 m, inside the layers + camera_position = (0.0, 0.0, TOP_BORDER + 0.5) + heights = [0.5, 1.5] + + np.testing.assert_allclose(distances(heights, HALFWAY_PANE, camera_position).sum(axis=1), + [distance_to_camera(height, camera_position) / 2 for height in heights]) + with pytest.raises(InconsistentDistanceError, match='domain_bounds'): + distances(heights, None, camera_position) + + def test_a_crossing_above_the_layers_is_reported(self): + # the line of sight crosses the pane at 4.25 m, above the layers + with pytest.raises(InconsistentDistanceError, match='cross the pane'): + distances([2.5], HALFWAY_PANE, (0.0, 0.0, 6.0)) + + def test_the_distance_array_holds_the_light_paths_behind_the_pane(self): + solver = ExtinctionCoefficientsNonLinear(ExperimentStub(HEIGHTS, HALFWAY_PANE)) + + distance_array = solver.calc_distance_array() + + # the distance array is built from the top LED down, the reverse of the LED order + np.testing.assert_allclose(distance_array.sum(axis=1), + [distance_to_camera(height) / 2 for height in reversed(HEIGHTS)]) + + +class TestPane: + def test_a_zero_normal_is_refused(self): + with pytest.raises(ValueError, match='zero vector'): + Pane((0.0, 2.0, 0.0), (0.0, 0.0, 0.0)) + + def test_two_coordinates_are_refused(self): + with pytest.raises(ValueError, match='three finite coordinates'): + Pane((0.0, 2.0), (0.0, 1.0, 0.0)) + + def test_a_coordinate_that_is_not_finite_is_refused(self): + with pytest.raises(ValueError, match='three finite coordinates'): + Pane((0.0, np.nan, 0.0), (0.0, 1.0, 0.0)) + + def test_the_camera_of_the_result_header_names_its_pane(self): + assert str(Camera(0, 0, 2)) == 'Camera: (0, 0, 2)\n' + assert str(Camera(0, 0, 2, pane=HALFWAY_PANE)) == \ + 'Camera: (0, 0, 2), behind the pane through (0, 2, 0) with the normal (0, 1, 0)\n' + + +def config_with(**options): + config = configparser.ConfigParser() + config['experiment_geometry'] = {'camera_position': '0 0 2', **options} + return config + + +class TestReadPane: + def test_a_config_without_the_options_has_no_pane(self): + assert read_pane(config_with(), 'experiment_geometry', 'config_analysis.ini') is None + + def test_none_means_no_pane(self): + config = config_with(pane_point='None', pane_normal='None') + + assert read_pane(config, 'experiment_geometry', 'config_analysis.ini') is None + + def test_a_section_that_is_missing_has_no_pane(self): + assert read_pane(config_with(), 'simulation_3', 'config_stacked.ini') is None + + def test_both_options_give_the_pane(self): + config = config_with(pane_point='0 2 0', pane_normal='0 1 0') + + assert read_pane(config, 'experiment_geometry', 'config_analysis.ini') == HALFWAY_PANE + + def test_a_point_without_a_normal_is_reported(self): + config = config_with(pane_point='0 2 0') + + with pytest.raises(ValueError, match='sets pane_point but not pane_normal'): + read_pane(config, 'experiment_geometry', 'config_analysis.ini') + + def test_a_normal_without_a_point_is_reported(self): + config = config_with(pane_normal='0 1 0', pane_point='None') + + with pytest.raises(ValueError, match='sets pane_normal but not pane_point'): + read_pane(config, 'experiment_geometry', 'config_analysis.ini') + + @pytest.mark.parametrize('value', ['0 2', '0 2 0 1', 'x 2 0']) + def test_a_value_that_is_not_three_numbers_is_reported(self, value): + config = config_with(pane_point=value, pane_normal='0 1 0') + + with pytest.raises(ValueError, match='pane_point = .* is not three numbers'): + read_pane(config, 'experiment_geometry', 'config_analysis.ini') + + def test_a_zero_normal_is_reported_with_its_section(self): + config = config_with(pane_point='0 2 0', pane_normal='0 0 0') + + with pytest.raises(ValueError, match=r'\[experiment_geometry\] of config_analysis.ini: .*zero'): + read_pane(config, 'experiment_geometry', 'config_analysis.ini') + + +class TestAnalysisConfig: + def test_the_template_writes_no_pane(self, tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + ConfigDataAnalysis(load_config_file=False) + + config = ConfigDataAnalysis() + + assert config['experiment_geometry']['pane_point'] == 'None' + assert config['experiment_geometry']['pane_normal'] == 'None' + assert config.get_pane() is None + + def test_the_template_writes_a_given_pane(self, tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + ConfigDataAnalysis(load_config_file=False, pane_point=[0, 2, 0], pane_normal='0 1 0') + + assert ConfigDataAnalysis().get_pane() == HALFWAY_PANE + + def test_a_config_written_before_the_options_has_no_pane(self, tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + (tmp_path / 'config_analysis.ini').write_text( + '[experiment_geometry]\ncamera_position = 0 0 2\n', encoding='utf-8') + + assert ConfigDataAnalysis().get_pane() is None + + +STACKED_CONFIG = """ +[DEFAULT] +solver = linear +num_layers = 10 +domain_bounds = 0 3 +reference_property = sum_col_val + +[simulation_0] +path = {tmp_path}/cam0 +camera_position = 0 0 2 +pane_point = 0 2 0 +pane_normal = 0 1 0 + +[simulation_1] +path = {tmp_path}/cam1 +camera_position = 0 0 0.5 + +[led_arrays] +0 = 0:0 1:0 +""" + + +def load_stacked_config(tmp_path): + path = tmp_path / ConfigDataStacked.DEFAULT_FILENAME + path.write_text(STACKED_CONFIG.format(tmp_path=tmp_path.as_posix()), encoding='utf-8') + return ConfigDataStacked(filename=str(path)) + + +class ExperimentSpy: + """Stands in for the Experiment of a camera, which would read the LEDs of its run.""" + + def __init__(self, layers, led_array, camera, path, channel, merge_led_arrays): + self.camera = camera + + +class TestStackedAnalysis: + def test_every_camera_has_its_own_pane(self, tmp_path): + config = load_stacked_config(tmp_path) + + assert config.get_pane(0) == HALFWAY_PANE + assert config.get_pane(1) is None + + def test_the_template_leaves_the_pane_commented_out(self, tmp_path): + path = tmp_path / ConfigDataStacked.DEFAULT_FILENAME + ConfigDataStacked.create_template(filename=str(path), num_simulations=2) + + config = ConfigDataStacked(filename=str(path)) + + assert [config.get_pane(sim_idx) for sim_idx in range(2)] == [None, None] + + @pytest.fixture + def stacked_solver(self, tmp_path, monkeypatch): + monkeypatch.setattr(stacked_module, 'Experiment', ExperimentSpy) + monkeypatch.setattr(StackedExtinctionCoefficients, '_build_sub_solver', lambda self, exp, sim_idx: None) + return StackedExtinctionCoefficients(load_stacked_config(tmp_path), led_array_id=0, channel=0) + + def test_the_analysis_puts_every_camera_behind_its_own_pane(self, stacked_solver): + assert [experiment.camera.pane for experiment in stacked_solver.sub_experiments] == [HALFWAY_PANE, None] + + def test_the_header_names_only_the_cameras_behind_a_pane(self, stacked_solver): + assert stacked_solver._pane_info() == 'sim0 behind the pane through (0, 2, 0) with the normal (0, 1, 0) | ' From 6930d9dca0e39d26180a52eb2ce1c8cbccf780d4 Mon Sep 17 00:00:00 2001 From: Kristian Date: Tue, 10 Nov 2026 11:26:08 +0100 Subject: [PATCH 2/2] describe the window pane by its distance from the camera pane_point and pane_normal give way to a single option, pane_distance: the distance in m between the camera and the pane, in [experiment_geometry] of config_analysis.ini and in every [simulation_N] of config_stacked.ini. The pane is taken as normal to the line of sight, so the light path of every LED starts pane_distance away from the camera. A flat pane normal to the optical axis is crossed by a line of sight at 15 degrees to the axis 3.5 % farther away, which is negligible as long as the pane is close to the camera compared to the LEDs. An LED that is not farther away from the camera than the pane is reported, and the result headers name the distance. Without the option, or with None, the light paths and the result files stay as they were. The unit test that writes a config file names the encoding on the line of write_text, where the encoding check of the CI looks for it. Co-Authored-By: Claude Opus 5.5 --- README.md | 19 +- ledsa/analysis/ConfigDataAnalysis.py | 47 ++-- ledsa/analysis/ConfigDataStacked.py | 25 +- ledsa/analysis/Experiment.py | 153 +++++------- ledsa/analysis/ExperimentData.py | 2 +- .../analysis/StackedExtinctionCoefficients.py | 15 +- .../AcceptanceTests/12_test_camera_pane.robot | 21 +- .../AcceptanceTests/LedsaATestLibrary.py | 32 +-- ledsa/tests/AcceptanceTests/TestExperiment.py | 26 +- ledsa/tests/UnitTests/test_camera_pane.py | 227 ++++++++---------- 10 files changed, 236 insertions(+), 331 deletions(-) diff --git a/README.md b/README.md index b40866c..b108ede 100644 --- a/README.md +++ b/README.md @@ -140,23 +140,24 @@ window before the fire. A camera that looks into the smoke through a window pane, for example from outside the test room, sees the LEDs along lines of sight whose part between the camera and the pane is free of smoke. Only the part behind the pane belongs in the layers; counted from the camera, the light -paths are too long and the extinction coefficients come out too low. The pane is the plane -through `pane_point` with the normal `pane_normal`, in the global coordinates of -`camera_position`: +paths are too long and the extinction coefficients come out too low. `pane_distance` is the +distance in m between the camera and the pane: ```ini [experiment_geometry] camera_position = 0 -0.5 1.5 - pane_point = 0 0 0 - pane_normal = 0 1 0 + pane_distance = 0.5 ``` -The normal may point to either side, and the pane has to separate the camera from every LED. In -`config_stacked.ini`, every `[simulation_N]` section takes a pane of its own. Without the two -options, or with `None`, the light paths reach the camera as before. The camera may then stand +The pane is taken as normal to the line of sight, so the light path of every LED starts +`pane_distance` away from the camera. A flat pane normal to the optical axis is crossed by a line +of sight at an angle θ to the axis `pane_distance / cos θ` away from the camera, at 15° 3.5 % +farther, which is negligible as long as the pane is close to the camera compared to the LEDs. In +`config_stacked.ini`, every `[simulation_N]` section takes a `pane_distance` of its own. Without +the option, or with `None`, the light paths reach the camera as before. The camera may then stand outside `domain_bounds`, as long as the layers hold the light paths behind the pane. Only the geometry is corrected: a pane whose transmission changes during the test, for example by soot or -condensate, dims the LEDs like smoke. The header of each result file names the pane. +condensate, dims the LEDs like smoke. The header of each result file names the distance. ### Temperature correction (optional) diff --git a/ledsa/analysis/ConfigDataAnalysis.py b/ledsa/analysis/ConfigDataAnalysis.py index e2cfd2d..fdb2d03 100644 --- a/ledsa/analysis/ConfigDataAnalysis.py +++ b/ledsa/analysis/ConfigDataAnalysis.py @@ -1,7 +1,7 @@ import configparser as cp from typing import Iterable, List, Optional, Union -from ledsa.analysis.Experiment import Pane, read_pane +from ledsa.analysis.Experiment import read_pane_distance from ledsa.analysis.temperature_correction import TEMPERATURE_CORRECTION_CHANNELS from ledsa.core.config_file import report_removed_options, save_config @@ -63,13 +63,6 @@ def format_reference_properties(reference_property: Union[str, Iterable[str]]) - return ' '.join(str(name) for name in reference_property) -def _format_coordinates(coordinates) -> str: - """Write coordinates given as a sequence of numbers, a string or None as the value of an option.""" - if coordinates is None or isinstance(coordinates, str): - return str(coordinates) - return ' '.join(str(value) for value in coordinates) - - class ConfigDataAnalysis(cp.ConfigParser): """ Class responsible for handling the configuration data related to LEDSA's data analysis. @@ -80,8 +73,7 @@ def __init__(self, load_config_file=True, camera_position=None, num_layers=20, d reference_property='sum_col_val', average_images=False, n_summarize=2, solver='linear', weighting_preference=-6e-3, weighting_curvature=1e-2, - num_iterations=1000, lambda_reg=1e-3, reduction_files=None, pane_point=None, - pane_normal=None): + num_iterations=1000, lambda_reg=1e-3, reduction_files=None, pane_distance=None): """ :param load_config_file: Determines whether to load the config file on initialization. Defaults to True. :type load_config_file: bool @@ -124,11 +116,9 @@ def __init__(self, load_config_file=True, camera_position=None, num_layers=20, d camera channel. Channels without an entry are analysed without the correction, which is the default for every channel. :type reduction_files: dict[int, str] or None - :param pane_point: Global X, Y, Z coordinates [m] of a point on the window pane the camera - looks through into the smoke. Defaults to None, for a camera without a pane. - :type pane_point: list[float] or None - :param pane_normal: Normal vector X, Y, Z of the window pane. Defaults to None. - :type pane_normal: list[float] or None + :param pane_distance: Distance [m] between the camera and the window pane it looks through + into the smoke. Defaults to None, for a camera without a pane. + :type pane_distance: float or None """ cp.ConfigParser.__init__(self, allow_no_value=True) if load_config_file: @@ -163,13 +153,11 @@ def __init__(self, load_config_file=True, camera_position=None, num_layers=20, d self['experiment_geometry'] = {} self.set('experiment_geometry', '# Global X Y Z position of the camera ') self['experiment_geometry'][' camera_position'] = str(camera_position) - self.set('experiment_geometry', ' # Window pane the camera looks through into the smoke, None without a pane:') - self.set('experiment_geometry', ' # the plane through the global X Y Z point pane_point [m] with the normal') - self.set('experiment_geometry', ' # X Y Z pane_normal, pointing to either side. The line of sight between the') - self.set('experiment_geometry', ' # camera and the pane is free of smoke, so only its part behind the pane is') - self.set('experiment_geometry', ' # distributed over the layers.') - self['experiment_geometry'][' pane_point'] = _format_coordinates(pane_point) - self['experiment_geometry'][' pane_normal'] = _format_coordinates(pane_normal) + self.set('experiment_geometry', ' # Distance [m] between the camera and the window pane it looks through into the') + self.set('experiment_geometry', ' # smoke, None without a pane. The pane is taken as normal to the line of sight:') + self.set('experiment_geometry', ' # the first pane_distance of every line of sight is free of smoke, so only the') + self.set('experiment_geometry', ' # part behind the pane is distributed over the layers.') + self['experiment_geometry'][' pane_distance'] = str(pane_distance) self['model_parameters'] = {} self.set('model_parameters', '# Parameters regarding the discretization of the spatial domain ') @@ -293,17 +281,16 @@ def get_reduction_file(self, channel: int) -> Optional[str]: return None return raw - def get_pane(self) -> Optional[Pane]: + def get_pane_distance(self) -> Optional[float]: """ - Return the window pane the camera looks through into the smoke. + Return the distance between the camera and the window pane it looks through into the smoke. - :return: The pane, None if the smoke reaches the camera, which is also the case for a config - file written before the options of the pane. - :rtype: Optional[Pane] - :raises ValueError: If only one of pane_point and pane_normal is set, or one of them is not - three numbers, or the normal is the zero vector. + :return: The distance [m], None if the smoke reaches the camera, which is also the case for a + config file written before the option. + :rtype: Optional[float] + :raises ValueError: If pane_distance is not a finite number of at least 0. """ - return read_pane(self, 'experiment_geometry', 'config_analysis.ini') + return read_pane_distance(self, 'experiment_geometry', 'config_analysis.ini') def in_camera_channels(self) -> None: """ diff --git a/ledsa/analysis/ConfigDataStacked.py b/ledsa/analysis/ConfigDataStacked.py index 16285ca..f7caca1 100644 --- a/ledsa/analysis/ConfigDataStacked.py +++ b/ledsa/analysis/ConfigDataStacked.py @@ -3,7 +3,7 @@ from typing import Dict, List, Optional from ledsa.analysis.ConfigDataAnalysis import DEFAULT_REFERENCE_PROPERTY, parse_reference_properties -from ledsa.analysis.Experiment import Pane, read_pane +from ledsa.analysis.Experiment import read_pane_distance from ledsa.analysis.temperature_correction import TEMPERATURE_CORRECTION_CHANNELS from ledsa.core.config_file import save_config @@ -39,9 +39,8 @@ class ConfigDataStacked(cp.ConfigParser): [simulation_0] path = /data/exp01/cam0 camera_position = 1.0 0.0 1.5 - # window pane this camera looks through into the smoke, optional - pane_point = 0.5 0.0 0.0 - pane_normal = 1.0 0.0 0.0 + # distance to the window pane this camera looks through into the smoke, optional + pane_distance = 0.5 [simulation_1] path = /data/exp01/cam1 @@ -148,13 +147,13 @@ def get_camera_position(self, sim_idx: int) -> List[float]: """Camera position ``[x, y, z]`` for simulation *sim_idx*.""" return self.get_list_of_values(f'simulation_{sim_idx}', 'camera_position', dtype=float) - def get_pane(self, sim_idx: int) -> Optional[Pane]: - """Window pane camera *sim_idx* looks through into the smoke, ``None`` if - the smoke reaches the camera. + def get_pane_distance(self, sim_idx: int) -> Optional[float]: + """Distance [m] between camera *sim_idx* and the window pane it looks + through into the smoke, ``None`` if the smoke reaches the camera. - :raises ValueError: if the options of the pane are set inconsistently. + :raises ValueError: if ``pane_distance`` is not a finite number of at least 0. """ - return read_pane(self, f'simulation_{sim_idx}', self._filename) + return read_pane_distance(self, f'simulation_{sim_idx}', self._filename) def get_ref_img_indices(self, sim_idx: int) -> Optional[List[int]]: """Reference image IDs of simulation *sim_idx*; ``None`` means use @@ -376,11 +375,9 @@ def create_template(cls, filename: str = DEFAULT_FILENAME, num_simulations: int cfg[section]['path'] = f'/path/to/sim{i}' cfg.set(section, '# Global X Y Z position [m] of camera') cfg[section]['camera_position'] = '0.0 0.0 1.5' - cfg.set(section, '# Window pane the camera looks through into the smoke (optional): the plane') - cfg.set(section, '# through the global X Y Z point pane_point [m] with the normal X Y Z') - cfg.set(section, '# pane_normal. Only the line of sight behind the pane is in the smoke.') - cfg.set(section, '# pane_point = 0.0 0.5 0.0') - cfg.set(section, '# pane_normal = 0.0 1.0 0.0') + cfg.set(section, '# Distance [m] between the camera and the window pane it looks through into') + cfg.set(section, '# the smoke (optional). Only the lines of sight behind the pane are in the smoke.') + cfg.set(section, '# pane_distance = 0.5') cfg.set(section, '# Reference images of this camera; both options override the ones above') cfg.set(section, '# Image IDs are counted per camera, so choose images from the same time') cfg.set(section, '# window before the fire in every camera') diff --git a/ledsa/analysis/Experiment.py b/ledsa/analysis/Experiment.py index 920bb12..5c76042 100644 --- a/ledsa/analysis/Experiment.py +++ b/ledsa/analysis/Experiment.py @@ -6,9 +6,6 @@ import numpy as np -# options of a camera section that describe the window pane in front of the camera -PANE_OPTIONS = ('pane_point', 'pane_normal') - class InconsistentDistanceError(ValueError): """The light path of an LED does not add up to its distance from the camera. @@ -22,8 +19,9 @@ class InconsistentDistanceError(ValueError): class PaneGeometryError(ValueError): """The window pane in front of the camera does not lie between the camera and an LED. - The light path of an LED through the smoke starts where its line of sight crosses the pane. - An LED on the camera's side of the pane, or on the pane itself, has no such crossing. + The light path of an LED through the smoke starts where its line of sight crosses the pane, + pane_distance away from the camera. An LED that is not farther away from the camera than the + pane has no such crossing. """ @@ -88,42 +86,6 @@ def __repr__(self): return f'Layers(amount={self.amount}, bottom_border={self.bottom_border}, top_border={self.top_border})' -@dataclass(frozen=True) -class Pane: - """ - Window pane the camera looks through into the smoke. - - The pane is the plane through ``point`` with the normal ``normal``; which of the two directions - the normal points to does not matter. The part of a line of sight between the camera and the - pane is free of smoke, so the light path of an LED through the smoke starts where its line of - sight crosses the pane. The transmission of the pane itself is the same in the reference images - and cancels in I/I0, and the refraction in a pane with parallel faces shifts the line of sight by - less than the thickness of the pane, so neither is taken into account. - - :ivar point: Global X, Y, Z coordinates [m] of a point on the pane - :vartype point: Tuple[float, float, float] - :ivar normal: Normal vector of the pane, of any length but zero - :vartype normal: Tuple[float, float, float] - """ - point: Tuple[float, float, float] - normal: Tuple[float, float, float] - - def __post_init__(self): - for name in ('point', 'normal'): - given = getattr(self, name) - coordinates = tuple(float(value) for value in given) - if len(coordinates) != 3 or not np.isfinite(coordinates).all(): - raise ValueError(f'The {name} of the pane needs three finite coordinates X Y Z, got {given}.') - object.__setattr__(self, name, coordinates) - if not any(self.normal): - raise ValueError('The normal of the pane must not be the zero vector.') - - def __str__(self): - point = ', '.join(f'{value:g}' for value in self.point) - normal = ', '.join(f'{value:g}' for value in self.normal) - return f'pane through ({point}) with the normal ({normal})' - - @dataclass class Camera: """ @@ -135,22 +97,34 @@ class Camera: :vartype pos_y: float :ivar pos_z: The z-coordinate of the camera :vartype pos_z: float - :ivar pane: Window pane the camera looks through into the smoke, None if the smoke reaches the - camera - :vartype pane: Pane or None + :ivar pane_distance: Distance [m] between the camera and the window pane it looks through into + the smoke, None if the smoke reaches the camera. The pane is taken as normal to the line of + sight, so the first pane_distance of every line of sight is free of smoke. The transmission + of the pane itself is the same in the reference images and cancels in I/I0, and the + refraction in a pane with parallel faces shifts the line of sight by less than the thickness + of the pane, so neither is taken into account. + :vartype pane_distance: float or None """ pos_x: float pos_y: float pos_z: float - pane: Optional[Pane] = None + pane_distance: Optional[float] = None + + def __post_init__(self): + if self.pane_distance is not None: + distance = float(self.pane_distance) + if not np.isfinite(distance) or distance < 0: + raise ValueError(f'The distance between the camera and the pane has to be a finite number of ' + f'at least 0, got {self.pane_distance}.') + self.pane_distance = distance def __str__(self): - if self.pane is None: + if self.pane_distance is None: return f'Camera: ({self.pos_x}, {self.pos_y}, {self.pos_z})\n' - return f'Camera: ({self.pos_x}, {self.pos_y}, {self.pos_z}), behind the {self.pane}\n' + return f'Camera: ({self.pos_x}, {self.pos_y}, {self.pos_z}), pane_distance: {self.pane_distance}\n' def __repr__(self): - pane = '' if self.pane is None else f', pane={self.pane!r}' + pane = '' if self.pane_distance is None else f', pane_distance={self.pane_distance}' return f'Camera(pos_x={self.pos_x}, pos_y={self.pos_y}, pos_z={self.pos_z}{pane})' @@ -236,32 +210,34 @@ def calc_smoke_path_start(self, led: LED) -> Tuple[float, float, float]: Find the point where the light path between an LED and the camera enters the smoke. Without a pane, the smoke reaches the camera and the light path starts there. Behind a pane, - it starts where the line of sight of the LED crosses the pane, because the part between the - pane and the camera is free of smoke. + it starts where the line of sight of the LED crosses the pane, pane_distance away from the + camera, because the part between the camera and the pane is free of smoke. The pane is taken + as normal to the line of sight. A flat pane normal to the optical axis of the camera is + crossed by a line of sight at an angle theta to the axis pane_distance / cos(theta) away + from the camera, at 15 degrees 3.5 % farther; this is negligible as long as the pane is + close to the camera compared to the LEDs. :param led: The LED light source :type led: LED :return: Global X, Y, Z coordinates of the start of the light path through the smoke :rtype: Tuple[float, float, float] - :raises PaneGeometryError: If the pane does not lie between the camera and the LED. + :raises PaneGeometryError: If the LED is not farther away from the camera than the pane. """ camera = (self.camera.pos_x, self.camera.pos_y, self.camera.pos_z) - pane = self.camera.pane - if pane is None: + pane_distance = self.camera.pane_distance + if pane_distance is None: return camera camera_pos = np.array(camera, dtype=float) led_pos = np.array([led.pos_x, led.pos_y, led.pos_z], dtype=float) - # distances from the pane, signed by the side and in units of the length of the normal - camera_side = np.dot(camera_pos - pane.point, pane.normal) - led_side = np.dot(led_pos - pane.point, pane.normal) - if led_side == 0 or camera_side * led_side > 0: + led_distance = np.linalg.norm(led_pos - camera_pos) + if pane_distance >= led_distance: raise PaneGeometryError( f'LED {led.id} of LED array {self.led_array} at ({led.pos_x}, {led.pos_y}, {led.pos_z}) ' - f'is not behind the {pane} as seen from the camera at {camera}, so its line of sight ' - f'does not cross the pane into the smoke. Check pane_point and pane_normal in the ' - f'analysis configuration: the pane has to separate the camera from every LED.') - fraction = camera_side / (camera_side - led_side) - return tuple(camera_pos + fraction * (led_pos - camera_pos)) + f'is {led_distance:.6g} away from the camera at {camera}, so it is not behind the pane ' + f'{pane_distance:g} away from the camera and its line of sight does not pass the pane ' + f'into the smoke. Check pane_distance and camera_position in the analysis ' + f'configuration: the pane has to lie between the camera and every LED.') + return tuple(camera_pos + pane_distance / led_distance * (led_pos - camera_pos)) def calc_traversed_dist_per_layer(self, led: LED) -> np.ndarray: """ @@ -276,7 +252,7 @@ def calc_traversed_dist_per_layer(self, led: LED) -> np.ndarray: :rtype: np.ndarray :raises InconsistentDistanceError: If the distances do not add up to the length of the light path through the smoke. - :raises PaneGeometryError: If the pane does not lie between the camera and the LED. + :raises PaneGeometryError: If the LED is not farther away from the camera than the pane. """ start = self.calc_smoke_path_start(led) start_x, start_y, start_z = start @@ -291,13 +267,13 @@ def calc_traversed_dist_per_layer(self, led: LED) -> np.ndarray: path_length = np.sqrt((start_x - led.pos_x) ** 2 + (start_y - led.pos_y) ** 2 + (start_z - led.pos_z) ** 2) - if self.camera.pane is None: + if self.camera.pane_distance is None: path_end = f'while the LED is {path_length:.6g} away from the camera' range_end = 'the camera' else: path_end = (f'while the LED is {path_length:.6g} away from the point ({start_x:.6g}, ' - f'{start_y:.6g}, {start_z:.6g}) where its line of sight crosses the ' - f'{self.camera.pane}') + f'{start_y:.6g}, {start_z:.6g}) where its line of sight crosses the pane, ' + f'{self.camera.pane_distance:g} away from the camera') range_end = 'the points where the lines of sight cross the pane' raise InconsistentDistanceError( f'The light path of LED {led.id} of LED array {self.led_array} traverses the layers ' @@ -458,11 +434,11 @@ def get_led_positions(self, ids: np.ndarray) -> List[np.ndarray]: return [search_areas_led_array[:, 3], search_areas_led_array[:, 4], search_areas_led_array[:, 5]] -def read_pane(config: cp.ConfigParser, section: str, file_name: str) -> Optional[Pane]: +def read_pane_distance(config: cp.ConfigParser, section: str, file_name: str) -> Optional[float]: """ - Read the window pane in front of a camera from the options pane_point and pane_normal. + Read the distance between a camera and the window pane it looks through into the smoke. - Both options are optional, so a config file written before them, or one that sets them to + The option pane_distance is optional, so a config file written before it, or one that sets it to None, keeps the light paths reaching the camera through the smoke. :param config: The loaded config file @@ -471,31 +447,20 @@ def read_pane(config: cp.ConfigParser, section: str, file_name: str) -> Optional :type section: str :param file_name: Name of the config file, for the error messages :type file_name: str - :return: The pane, None if neither option is set - :rtype: Optional[Pane] - :raises ValueError: If only one of the options is set, if one of them is not three numbers or if - the normal is the zero vector. + :return: The distance [m], None if the option is not set + :rtype: Optional[float] + :raises ValueError: If the value is not a finite number of at least 0. """ - values = {} - for option in PANE_OPTIONS: - raw = config.get(section, option, fallback=None) - raw = '' if raw is None else raw.strip() - values[option] = None if raw.lower() in ('', 'none') else raw - if all(value is None for value in values.values()): + raw = config.get(section, 'pane_distance', fallback=None) + raw = '' if raw is None else raw.strip() + if raw.lower() in ('', 'none'): return None - if any(value is None for value in values.values()): - set_option, unset_option = PANE_OPTIONS if values[PANE_OPTIONS[0]] is not None else PANE_OPTIONS[::-1] - raise ValueError(f'[{section}] of {file_name} sets {set_option} but not {unset_option}. A pane needs ' - f'both, a point on the pane and its normal.') - coordinates = {} - for option, raw in values.items(): - try: - coordinates[option] = [float(item) for item in raw.split()] - except ValueError: - coordinates[option] = [] - if len(coordinates[option]) != 3: - raise ValueError(f'{option} = {raw} in [{section}] of {file_name} is not three numbers X Y Z.') try: - return Pane(*(coordinates[option] for option in PANE_OPTIONS)) - except ValueError as err: - raise ValueError(f'[{section}] of {file_name}: {err}') from None + distance = float(raw) + except ValueError: + distance = np.nan + if not np.isfinite(distance) or distance < 0: + raise ValueError(f'pane_distance = {raw} in [{section}] of {file_name} is not a distance: give the ' + f'distance [m] between the camera and the window pane as a number of at least 0, or ' + f'None for a camera without a pane.') + return distance diff --git a/ledsa/analysis/ExperimentData.py b/ledsa/analysis/ExperimentData.py index 16fc218..0214bf6 100644 --- a/ledsa/analysis/ExperimentData.py +++ b/ledsa/analysis/ExperimentData.py @@ -136,7 +136,7 @@ def load_config_parameters(self) -> None: camera_position = config_analysis.get_list_of_values('experiment_geometry', 'camera_position', dtype=float) self.layers = Layers(num_layers, *domain_bounds) - self.camera = Camera(*camera_position, pane=config_analysis.get_pane()) + self.camera = Camera(*camera_position, pane_distance=config_analysis.get_pane_distance()) self.n_cpus = int(config_analysis['DEFAULT']['num_cores']) self.merge_led_arrays = str(self.config['analyse_positions']['merge_led_array_indices']) diff --git a/ledsa/analysis/StackedExtinctionCoefficients.py b/ledsa/analysis/StackedExtinctionCoefficients.py index f6f6d24..8c4de73 100644 --- a/ledsa/analysis/StackedExtinctionCoefficients.py +++ b/ledsa/analysis/StackedExtinctionCoefficients.py @@ -110,7 +110,7 @@ def __init__(self, config: ConfigDataStacked, led_array_id: int, channel: int, exp = Experiment( layers=self.layers, led_array=arr_id, - camera=Camera(*cam_pos, pane=config.get_pane(sim_idx)), + camera=Camera(*cam_pos, pane_distance=config.get_pane_distance(sim_idx)), path=config.get_simulation_path(sim_idx), channel=channel, merge_led_arrays='None', @@ -540,18 +540,19 @@ def __str__(self) -> str: # ------------------------------------------------------------------ def _pane_info(self) -> str: - """Header entries of the cameras behind a window pane. + """Header entry of the cameras behind a window pane, e.g. ``pane_distance: sim0 0.5 | ``. Only a camera behind a pane is named, so the header of a run without panes stays as it was. - :return: One entry per camera behind a pane, each ending in a separator, or an empty string. + :return: The entry, ending in a separator, or an empty string if no camera is behind a pane. :rtype: str """ - return ''.join( - f'sim{idx} behind the {exp.camera.pane} | ' + distances = [ + f'sim{idx} {exp.camera.pane_distance}' for idx, exp in zip(sorted(self.led_array_mapping), self.sub_experiments) - if exp.camera.pane is not None - ) + if exp.camera.pane_distance is not None + ] + return f'pane_distance: {", ".join(distances)} | ' if distances else '' def _ref_img_info(self) -> str: """Describe the reference images of every simulation, e.g. ``sim0 first 10, sim1 [385, 386]``. diff --git a/ledsa/tests/AcceptanceTests/12_test_camera_pane.robot b/ledsa/tests/AcceptanceTests/12_test_camera_pane.robot index d042eaa..faee9e2 100644 --- a/ledsa/tests/AcceptanceTests/12_test_camera_pane.robot +++ b/ledsa/tests/AcceptanceTests/12_test_camera_pane.robot @@ -8,11 +8,10 @@ Force Tags camera_pane *** Variables *** -${PANE_DIR} ${WORKDIR}${/}camera_behind_a_pane -# The camera stands at y = 0 and the LEDs at y = 4, so a pane at y = 2 leaves half of every line -# of sight in the smoke. -${PANE_POINT} 0 2 0 -${PANE_NORMAL} 0 1 0 +${PANE_DIR} ${WORKDIR}${/}camera_behind_a_pane +# The camera stands at y = 0 and the LEDs at y = 4, so a pane 2 m in front of the camera leaves +# about half of every line of sight in the smoke. +${PANE_DISTANCE} 2 *** Test Cases *** @@ -21,17 +20,17 @@ The Light Paths Of A Camera Behind A Pane Start At The Pane ... sight between the camera and the pane is free of smoke. The test images have smoke ... behind the pane only. With the pane in config_analysis.ini, the extinction coefficients ... match the input. - Create And Fill Config Analysis linear pane_point=${PANE_POINT} pane_normal=${PANE_NORMAL} + Create And Fill Config Analysis linear pane_distance=${PANE_DISTANCE} Execute Ledsa --analysis Extinction Coefficients Should Match The Input 2 Extinction Coefficients Should Match The Input 3 Extinction Coefficients Should Match The Input 4 Without The Pane The Smoke Is Spread Over The Whole Line Of Sight - [Documentation] Analysed as if the smoke reached the camera, which stays the default without pane_point - ... and pane_normal, the same images give coefficients half as large for the constant - ... extinction of image 2, because every light path is taken twice as long as its part in - ... the smoke. This is what the pane corrects. + [Documentation] Analysed as if the smoke reached the camera, which stays the default without + ... pane_distance, the same images give coefficients about half as large for the constant + ... extinction of image 2, because every light path is taken about twice as long as its + ... part in the smoke. This is what the pane corrects. Create And Fill Config Analysis linear Execute Ledsa --analysis ${ratio} = Mean Ratio Of Computed To Input Extinction Coefficients 2 linear @@ -42,7 +41,7 @@ Without The Pane The Smoke Is Spread Over The Whole Line Of Sight Prepare Images Of A Camera Behind A Pane Create Directory ${PANE_DIR} Change Directory ${PANE_DIR} - Create Test Data pane_point=${PANE_POINT} pane_normal=${PANE_NORMAL} + Create Test Data pane_distance=${PANE_DISTANCE} Create Config ${leds} = Execute Ledsa S1 ${TRUE} Should Be Equal ${leds} 100 diff --git a/ledsa/tests/AcceptanceTests/LedsaATestLibrary.py b/ledsa/tests/AcceptanceTests/LedsaATestLibrary.py index 20d9a36..5408ff8 100644 --- a/ledsa/tests/AcceptanceTests/LedsaATestLibrary.py +++ b/ledsa/tests/AcceptanceTests/LedsaATestLibrary.py @@ -14,7 +14,7 @@ from robot.libraries.BuiltIn import BuiltIn from scipy.stats import norm -from TestExperiment import TestExperiment, Layers, Camera, Pane +from TestExperiment import TestExperiment, Layers, Camera from ledsa.analysis.ConfigDataAnalysis import ConfigDataAnalysis from ledsa.analysis.ConfigDataStacked import ConfigDataStacked from ledsa.core.ConfigData import ConfigData @@ -40,21 +40,19 @@ def change_dir(self, new_dir): @keyword def create_test_data(self, num_of_leds=100, num_of_layers=20, bottom_border=0, top_border=3, - pane_point=None, pane_normal=None): + pane_distance=None): """Create the test images of four extinction profiles, seen by a camera at (0, 0, 2). - :param pane_point: Point X Y Z of a window pane the camera looks through into the smoke, so - that the smoke dims the LEDs only behind the pane. None for smoke up to the camera. - :param pane_normal: Normal X Y Z of that pane. + :param pane_distance: Distance [m] between the camera and a window pane it looks through into + the smoke, so that the smoke dims the LEDs only behind the pane. None for smoke up to the + camera. """ # Create test_data directory if it doesn't exist if not os.path.exists('test_data'): os.makedirs('test_data') camera = Camera(0, 0, 2) - pane = None - if pane_point is not None: - pane = Pane(_coordinates(pane_point), _coordinates(pane_normal)) + pane_distance = None if pane_distance is None else float(pane_distance) layers = Layers(num_of_layers, bottom_border, top_border) extinction_coefficients_set = [] @@ -86,7 +84,7 @@ def extco_quad(z): extinction_coefficients_set.append(extco_quad(z_range)) for image_id, extinction_coefficients in enumerate(extinction_coefficients_set): - ex = TestExperiment(camera=camera, layers=layers, pane=pane) + ex = TestExperiment(camera=camera, layers=layers, pane_distance=pane_distance) np.savetxt(os.path.join('test_data', f'test_extinction_coefficients_input_{image_id + 1}.csv'), extinction_coefficients) for z in np.linspace(bottom_border + 0.05, top_border - 0.05, num_of_leds): ex.add_led(0, 4, z) @@ -437,13 +435,13 @@ def create_and_fill_config(self, first=1, last=4): @keyword def create_and_fill_config_analysis(self, solver, reference_property='sum_col_val', num_ref_images=1, - average_images=False, n_summarize=2, pane_point=None, pane_normal=None): + average_images=False, n_summarize=2, pane_distance=None): """Write config_analysis.ini. num_ref_images lets a test take the reference from another image than the first. :param average_images: Summarize the images after the reference images. :param n_summarize: Number of consecutive images summarized into one. - :param pane_point: Point X Y Z of the window pane in front of the camera, None without a pane. - :param pane_normal: Normal X Y Z of the window pane. + :param pane_distance: Distance [m] between the camera and the window pane in front of it, None + without a pane. """ average_images = str(average_images).lower() == 'true' conf = ConfigDataAnalysis(load_config_file=False, camera_position=None, num_layers=20, domain_bounds=None, @@ -452,8 +450,7 @@ def create_and_fill_config_analysis(self, solver, reference_property='sum_col_va average_images=average_images, n_summarize=int(n_summarize), solver=solver, weighting_preference=-6e-3, weighting_curvature=1e-2, - num_iterations=1000, lambda_reg=1e-3, pane_point=pane_point, - pane_normal=pane_normal) + num_iterations=1000, lambda_reg=1e-3, pane_distance=pane_distance) conf.set('experiment_geometry', ' camera_position', '0 0 2') conf.set('model_parameters', ' domain_bounds', '0 3') conf.save() @@ -753,13 +750,6 @@ def read_experiment_times_of_images(infos_path): times_of_img[name] = float(experiment_time) return times_of_img -def _coordinates(value): - """Coordinates X Y Z given as a string of a Robot Framework test, or as numbers.""" - if isinstance(value, str): - return tuple(float(item) for item in value.split()) - return tuple(float(item) for item in value) - - def extinction_coefficients_path(solver, channel, led_array, reference_property='sum_col_val'): """Path of an extinction coefficient file, which lies in a directory of its solver and quantity. diff --git a/ledsa/tests/AcceptanceTests/TestExperiment.py b/ledsa/tests/AcceptanceTests/TestExperiment.py index 06cbd8b..ed72c52 100644 --- a/ledsa/tests/AcceptanceTests/TestExperiment.py +++ b/ledsa/tests/AcceptanceTests/TestExperiment.py @@ -51,13 +51,6 @@ def __repr__(self): return f'Camera(pos_x={self.pos_x}, pos_y={self.pos_y}, pos_z={self.pos_z})' -@dataclass -class Pane: - """Window pane between the camera and the smoke: the plane through point with the normal normal.""" - point: tuple - normal: tuple - - @dataclass class LED: id: int @@ -67,10 +60,10 @@ class LED: class TestExperiment: - def __init__(self, layers: Layers, camera: Camera, pane: Pane = None): + def __init__(self, layers: Layers, camera: Camera, pane_distance: float = None): self.layers = layers self.camera = camera - self.pane = pane + self.pane_distance = pane_distance self.leds = [] self.extinction_coefficients = np.zeros(layers.amount) @@ -82,7 +75,7 @@ def set_extinction_coefficients(self, extinction_coefficients_array): self.extinction_coefficients = extinction_coefficients_array def calc_traversed_dist_per_layer(self, led: LED) -> np.ndarray: - if self.pane is not None: + if self.pane_distance is not None: return self.calc_traversed_dist_per_layer_behind_pane(led) horizontal_dist = np.sqrt((self.camera.pos_x - led.pos_x) ** 2 + (self.camera.pos_y - led.pos_y) ** 2) alpha = np.arctan((led.pos_z - self.camera.pos_z) / horizontal_dist) @@ -98,16 +91,15 @@ def calc_traversed_dist_per_layer(self, led: LED) -> np.ndarray: def calc_traversed_dist_per_layer_behind_pane(self, led: LED) -> np.ndarray: """Distances in the layers of the part of the line of sight between the pane and the LED. - Only that part runs through the smoke. It is cut at the layer borders by the share of its - height each layer holds, so that this does not repeat how LEDSA computes the light paths. + The first pane_distance of the line of sight is free of smoke, so only the rest runs through + the smoke. It is cut at the layer borders by the share of its height each layer holds, so + that this does not repeat how LEDSA computes the light paths. """ camera = np.array([self.camera.pos_x, self.camera.pos_y, self.camera.pos_z], dtype=float) led_pos = np.array([led.pos_x, led.pos_y, led.pos_z], dtype=float) - point = np.array(self.pane.point, dtype=float) - normal = np.array(self.pane.normal, dtype=float) - crossing = np.dot(point - camera, normal) / np.dot(led_pos - camera, normal) - start = camera + crossing * (led_pos - camera) - length = np.linalg.norm(led_pos - start) + led_distance = np.linalg.norm(led_pos - camera) + start = camera + self.pane_distance / led_distance * (led_pos - camera) + length = led_distance - self.pane_distance z_low, z_high = sorted((start[2], led_pos[2])) distance_per_layer = np.zeros(self.layers.amount) for layer in range(self.layers.amount): diff --git a/ledsa/tests/UnitTests/test_camera_pane.py b/ledsa/tests/UnitTests/test_camera_pane.py index 7578576..0d7e124 100644 --- a/ledsa/tests/UnitTests/test_camera_pane.py +++ b/ledsa/tests/UnitTests/test_camera_pane.py @@ -1,8 +1,8 @@ """Unit tests for a camera that looks through a window pane into the smoke. -The part of a line of sight between the camera and the pane is free of smoke, so only its part -behind the pane is distributed over the layers. Without a pane, the light paths reach the camera -as before. +The pane is pane_distance away from the camera and taken as normal to the line of sight, so the +first pane_distance of every line of sight is free of smoke and only the part behind the pane is +distributed over the layers. Without a pane, the light paths reach the camera as before. """ import configparser @@ -12,8 +12,8 @@ import ledsa.analysis.StackedExtinctionCoefficients as stacked_module from ledsa.analysis.ConfigDataAnalysis import ConfigDataAnalysis from ledsa.analysis.ConfigDataStacked import ConfigDataStacked -from ledsa.analysis.Experiment import (Camera, Experiment, InconsistentDistanceError, LED, Layers, Pane, - PaneGeometryError, read_pane) +from ledsa.analysis.Experiment import (Camera, Experiment, InconsistentDistanceError, LED, Layers, + PaneGeometryError, read_pane_distance) from ledsa.analysis.ExtinctionCoefficientsNonLinear import ExtinctionCoefficientsNonLinear from ledsa.analysis.StackedExtinctionCoefficients import StackedExtinctionCoefficients @@ -23,26 +23,24 @@ CAMERA_POSITION = (0.0, 0.0, 2.0) LED_DISTANCE = 4.0 # the LEDs stand at y = 4, in front of the camera at y = 0 HEIGHTS = [0.5, 1.5, 2.5] -# the pane at y = 2 lies halfway between the camera and the LEDs -HALFWAY_PANE = Pane((0.0, 2.0, 0.0), (0.0, 1.0, 0.0)) class ExperimentStub(Experiment): """Experiment whose LEDs are given by their heights instead of read from the analysis files.""" - def __init__(self, heights, pane=None, camera_position=CAMERA_POSITION): + def __init__(self, heights, pane_distance=None, camera_position=CAMERA_POSITION): self.heights = heights super().__init__(layers=Layers(NUM_LAYERS, BOTTOM_BORDER, TOP_BORDER), led_array=0, - camera=Camera(*camera_position, pane=pane)) + camera=Camera(*camera_position, pane_distance=pane_distance)) def set_leds(self) -> None: self.leds = [LED(led_id, 0.0, LED_DISTANCE, height) for led_id, height in enumerate(self.heights)] self.num_leds = len(self.leds) -def distances(heights, pane=None, camera_position=CAMERA_POSITION): +def distances(heights, pane_distance=None, camera_position=CAMERA_POSITION): """Distances traversed in the layers, one row per LED in the order of the heights.""" - experiment = ExperimentStub(heights, pane, camera_position) + experiment = ExperimentStub(heights, pane_distance, camera_position) return np.array([experiment.calc_traversed_dist_per_layer(led) for led in experiment.leds]) @@ -55,21 +53,23 @@ def test_without_a_pane_the_light_paths_reach_the_camera(self): np.testing.assert_allclose(distances(HEIGHTS).sum(axis=1), [distance_to_camera(height) for height in HEIGHTS]) - def test_the_light_path_starts_where_the_line_of_sight_crosses_the_pane(self): - experiment = ExperimentStub([1.0], HALFWAY_PANE) + def test_the_light_path_starts_pane_distance_away_from_the_camera(self): + # the line of sight from the camera at 3.5 m to the LED at 0.5 m is 5 m long + experiment = ExperimentStub([0.5], 2.5, camera_position=(0.0, 0.0, 3.5)) start = experiment.calc_smoke_path_start(experiment.leds[0]) - np.testing.assert_allclose(start, (0.0, 2.0, 1.5)) + np.testing.assert_allclose(start, (0.0, 2.0, 2.0)) - def test_a_pane_halfway_halves_the_light_paths(self): - np.testing.assert_allclose(distances(HEIGHTS, HALFWAY_PANE).sum(axis=1), - [distance_to_camera(height) / 2 for height in HEIGHTS]) + def test_the_pane_shortens_every_light_path_by_its_distance(self): + np.testing.assert_allclose(distances(HEIGHTS, 1.0).sum(axis=1), + [distance_to_camera(height) - 1.0 for height in HEIGHTS]) def test_only_the_layers_between_the_pane_and_the_led_hold_the_light_path(self): - # the line of sight of the LED at 0.5 m crosses the pane at 1.25 m + # a pane halfway along the line of sight of the LED at 0.5 m is crossed at 1.25 m + halfway = distance_to_camera(0.5) / 2 full, = distances([0.5]) - behind, = distances([0.5], HALFWAY_PANE) + behind, = distances([0.5], halfway) borders = np.linspace(BOTTOM_BORDER, TOP_BORDER, NUM_LAYERS + 1) below_the_crossing = borders[1:] <= 1.25 above_the_crossing = borders[:-1] >= 1.25 @@ -77,82 +77,63 @@ def test_only_the_layers_between_the_pane_and_the_led_hold_the_light_path(self): np.testing.assert_allclose(behind[below_the_crossing], full[below_the_crossing]) assert not behind[above_the_crossing].any() - def test_the_direction_and_length_of_the_normal_do_not_matter(self): - flipped = Pane((0.0, 2.0, 0.0), (0.0, -3.0, 0.0)) - - np.testing.assert_allclose(distances(HEIGHTS, flipped), distances(HEIGHTS, HALFWAY_PANE)) - - def test_an_oblique_pane(self): - # the plane y + z / 2 = 2 crosses the line of sight to the LED at 1 m at 2/7 of its length - oblique = Pane((0.0, 2.0, 0.0), (0.0, 1.0, 0.5)) - - np.testing.assert_allclose(distances([1.0], oblique).sum(), 5 / 7 * distance_to_camera(1.0)) - def test_a_level_line_of_sight_lies_in_the_layer_of_the_camera(self): - behind, = distances([CAMERA_POSITION[2]], HALFWAY_PANE) + behind, = distances([CAMERA_POSITION[2]], 1.5) - assert behind.sum() == pytest.approx(LED_DISTANCE / 2) + assert behind.sum() == pytest.approx(LED_DISTANCE - 1.5) assert np.count_nonzero(behind) == 1 - def test_a_camera_on_the_pane_sees_the_smoke_from_the_camera_on(self): - pane = Pane(CAMERA_POSITION, (0.0, 1.0, 0.0)) - - np.testing.assert_allclose(distances(HEIGHTS, pane), distances(HEIGHTS)) - - def test_an_led_on_the_camera_side_of_the_pane_is_reported(self): - behind_the_leds = Pane((0.0, LED_DISTANCE + 1, 0.0), (0.0, 1.0, 0.0)) + def test_a_pane_at_the_camera_changes_nothing(self): + np.testing.assert_array_equal(distances(HEIGHTS, 0.0), distances(HEIGHTS)) + def test_an_led_nearer_than_the_pane_is_reported(self): with pytest.raises(PaneGeometryError, match='LED 0 '): - distances([1.0], behind_the_leds) + distances([1.0], LED_DISTANCE + 1) def test_an_led_on_the_pane_is_reported(self): - through_the_leds = Pane((0.0, LED_DISTANCE, 0.0), (0.0, 1.0, 0.0)) - - with pytest.raises(PaneGeometryError, match='pane_normal'): - distances([1.0], through_the_leds) + with pytest.raises(PaneGeometryError, match='pane_distance'): + distances([CAMERA_POSITION[2]], LED_DISTANCE) def test_a_camera_above_the_layers_is_accepted_if_the_light_paths_behind_the_pane_lie_inside(self): - # the lines of sight cross the pane at 2.0 m and 2.5 m, inside the layers + # the lines of sight cross the pane at 2.0 m and 2.38 m, inside the layers camera_position = (0.0, 0.0, TOP_BORDER + 0.5) heights = [0.5, 1.5] - np.testing.assert_allclose(distances(heights, HALFWAY_PANE, camera_position).sum(axis=1), - [distance_to_camera(height, camera_position) / 2 for height in heights]) + np.testing.assert_allclose(distances(heights, 2.5, camera_position).sum(axis=1), + [distance_to_camera(height, camera_position) - 2.5 for height in heights]) with pytest.raises(InconsistentDistanceError, match='domain_bounds'): distances(heights, None, camera_position) def test_a_crossing_above_the_layers_is_reported(self): - # the line of sight crosses the pane at 4.25 m, above the layers - with pytest.raises(InconsistentDistanceError, match='cross the pane'): - distances([2.5], HALFWAY_PANE, (0.0, 0.0, 6.0)) + # the 5 m long line of sight from the camera at 5.5 m to the LED at 2.5 m crosses the pane at + # 4 m, above the layers + with pytest.raises(InconsistentDistanceError, + match=r'point \(0, 2, 4\) where its line of sight crosses the pane'): + distances([2.5], 2.5, (0.0, 0.0, 5.5)) def test_the_distance_array_holds_the_light_paths_behind_the_pane(self): - solver = ExtinctionCoefficientsNonLinear(ExperimentStub(HEIGHTS, HALFWAY_PANE)) + solver = ExtinctionCoefficientsNonLinear(ExperimentStub(HEIGHTS, 1.0)) distance_array = solver.calc_distance_array() # the distance array is built from the top LED down, the reverse of the LED order np.testing.assert_allclose(distance_array.sum(axis=1), - [distance_to_camera(height) / 2 for height in reversed(HEIGHTS)]) - + [distance_to_camera(height) - 1.0 for height in reversed(HEIGHTS)]) -class TestPane: - def test_a_zero_normal_is_refused(self): - with pytest.raises(ValueError, match='zero vector'): - Pane((0.0, 2.0, 0.0), (0.0, 0.0, 0.0)) - def test_two_coordinates_are_refused(self): - with pytest.raises(ValueError, match='three finite coordinates'): - Pane((0.0, 2.0), (0.0, 1.0, 0.0)) +class TestCamera: + def test_a_negative_distance_is_refused(self): + with pytest.raises(ValueError, match='at least 0'): + Camera(0.0, 0.0, 2.0, pane_distance=-0.5) - def test_a_coordinate_that_is_not_finite_is_refused(self): - with pytest.raises(ValueError, match='three finite coordinates'): - Pane((0.0, np.nan, 0.0), (0.0, 1.0, 0.0)) + @pytest.mark.parametrize('distance', [np.nan, np.inf]) + def test_a_distance_that_is_not_finite_is_refused(self, distance): + with pytest.raises(ValueError, match='finite'): + Camera(0.0, 0.0, 2.0, pane_distance=distance) - def test_the_camera_of_the_result_header_names_its_pane(self): + def test_the_camera_of_the_result_header_names_the_pane_distance(self): assert str(Camera(0, 0, 2)) == 'Camera: (0, 0, 2)\n' - assert str(Camera(0, 0, 2, pane=HALFWAY_PANE)) == \ - 'Camera: (0, 0, 2), behind the pane through (0, 2, 0) with the normal (0, 1, 0)\n' + assert str(Camera(0, 0, 2, pane_distance=0.5)) == 'Camera: (0, 0, 2), pane_distance: 0.5\n' def config_with(**options): @@ -161,47 +142,31 @@ def config_with(**options): return config -class TestReadPane: - def test_a_config_without_the_options_has_no_pane(self): - assert read_pane(config_with(), 'experiment_geometry', 'config_analysis.ini') is None +class TestReadPaneDistance: + def test_a_config_without_the_option_has_no_pane(self): + assert read_pane_distance(config_with(), 'experiment_geometry', 'config_analysis.ini') is None - def test_none_means_no_pane(self): - config = config_with(pane_point='None', pane_normal='None') + @pytest.mark.parametrize('value', ['None', 'none', '']) + def test_none_or_no_value_means_no_pane(self, value): + config = config_with(pane_distance=value) - assert read_pane(config, 'experiment_geometry', 'config_analysis.ini') is None + assert read_pane_distance(config, 'experiment_geometry', 'config_analysis.ini') is None def test_a_section_that_is_missing_has_no_pane(self): - assert read_pane(config_with(), 'simulation_3', 'config_stacked.ini') is None - - def test_both_options_give_the_pane(self): - config = config_with(pane_point='0 2 0', pane_normal='0 1 0') - - assert read_pane(config, 'experiment_geometry', 'config_analysis.ini') == HALFWAY_PANE + assert read_pane_distance(config_with(), 'simulation_3', 'config_stacked.ini') is None - def test_a_point_without_a_normal_is_reported(self): - config = config_with(pane_point='0 2 0') + def test_the_option_gives_the_distance(self): + config = config_with(pane_distance='0.5') - with pytest.raises(ValueError, match='sets pane_point but not pane_normal'): - read_pane(config, 'experiment_geometry', 'config_analysis.ini') + assert read_pane_distance(config, 'experiment_geometry', 'config_analysis.ini') == 0.5 - def test_a_normal_without_a_point_is_reported(self): - config = config_with(pane_normal='0 1 0', pane_point='None') + @pytest.mark.parametrize('value', ['x', '0 2 0', '-1', 'nan', 'inf']) + def test_a_value_that_is_not_a_distance_is_reported_with_its_section(self, value): + config = config_with(pane_distance=value) - with pytest.raises(ValueError, match='sets pane_normal but not pane_point'): - read_pane(config, 'experiment_geometry', 'config_analysis.ini') - - @pytest.mark.parametrize('value', ['0 2', '0 2 0 1', 'x 2 0']) - def test_a_value_that_is_not_three_numbers_is_reported(self, value): - config = config_with(pane_point=value, pane_normal='0 1 0') - - with pytest.raises(ValueError, match='pane_point = .* is not three numbers'): - read_pane(config, 'experiment_geometry', 'config_analysis.ini') - - def test_a_zero_normal_is_reported_with_its_section(self): - config = config_with(pane_point='0 2 0', pane_normal='0 0 0') - - with pytest.raises(ValueError, match=r'\[experiment_geometry\] of config_analysis.ini: .*zero'): - read_pane(config, 'experiment_geometry', 'config_analysis.ini') + with pytest.raises(ValueError, match=r'pane_distance = .* in \[experiment_geometry\] of ' + r'config_analysis.ini is not a distance'): + read_pane_distance(config, 'experiment_geometry', 'config_analysis.ini') class TestAnalysisConfig: @@ -211,22 +176,21 @@ def test_the_template_writes_no_pane(self, tmp_path, monkeypatch): config = ConfigDataAnalysis() - assert config['experiment_geometry']['pane_point'] == 'None' - assert config['experiment_geometry']['pane_normal'] == 'None' - assert config.get_pane() is None + assert config['experiment_geometry']['pane_distance'] == 'None' + assert config.get_pane_distance() is None - def test_the_template_writes_a_given_pane(self, tmp_path, monkeypatch): + def test_the_template_writes_a_given_pane_distance(self, tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) - ConfigDataAnalysis(load_config_file=False, pane_point=[0, 2, 0], pane_normal='0 1 0') + ConfigDataAnalysis(load_config_file=False, pane_distance=0.5) - assert ConfigDataAnalysis().get_pane() == HALFWAY_PANE + assert ConfigDataAnalysis().get_pane_distance() == 0.5 - def test_a_config_written_before_the_options_has_no_pane(self, tmp_path, monkeypatch): + def test_a_config_written_before_the_option_has_no_pane(self, tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) - (tmp_path / 'config_analysis.ini').write_text( - '[experiment_geometry]\ncamera_position = 0 0 2\n', encoding='utf-8') + config_text = '[experiment_geometry]\ncamera_position = 0 0 2\n' + (tmp_path / 'config_analysis.ini').write_text(config_text, encoding='utf-8') - assert ConfigDataAnalysis().get_pane() is None + assert ConfigDataAnalysis().get_pane_distance() is None STACKED_CONFIG = """ @@ -239,8 +203,7 @@ def test_a_config_written_before_the_options_has_no_pane(self, tmp_path, monkeyp [simulation_0] path = {tmp_path}/cam0 camera_position = 0 0 2 -pane_point = 0 2 0 -pane_normal = 0 1 0 +pane_distance = 2.0 [simulation_1] path = {tmp_path}/cam1 @@ -249,11 +212,12 @@ def test_a_config_written_before_the_options_has_no_pane(self, tmp_path, monkeyp [led_arrays] 0 = 0:0 1:0 """ +STACKED_CONFIG_WITHOUT_PANES = STACKED_CONFIG.replace('pane_distance = 2.0\n', '') -def load_stacked_config(tmp_path): +def load_stacked_config(tmp_path, config_text=STACKED_CONFIG): path = tmp_path / ConfigDataStacked.DEFAULT_FILENAME - path.write_text(STACKED_CONFIG.format(tmp_path=tmp_path.as_posix()), encoding='utf-8') + path.write_text(config_text.format(tmp_path=tmp_path.as_posix()), encoding='utf-8') return ConfigDataStacked(filename=str(path)) @@ -264,29 +228,38 @@ def __init__(self, layers, led_array, camera, path, channel, merge_led_arrays): self.camera = camera +def build_stacked_solver(tmp_path, monkeypatch, config_text=STACKED_CONFIG): + monkeypatch.setattr(stacked_module, 'Experiment', ExperimentSpy) + monkeypatch.setattr(StackedExtinctionCoefficients, '_build_sub_solver', lambda self, exp, sim_idx: None) + return StackedExtinctionCoefficients(load_stacked_config(tmp_path, config_text), led_array_id=0, channel=0) + + class TestStackedAnalysis: - def test_every_camera_has_its_own_pane(self, tmp_path): + def test_every_camera_has_its_own_pane_distance(self, tmp_path): config = load_stacked_config(tmp_path) - assert config.get_pane(0) == HALFWAY_PANE - assert config.get_pane(1) is None + assert config.get_pane_distance(0) == 2.0 + assert config.get_pane_distance(1) is None - def test_the_template_leaves_the_pane_commented_out(self, tmp_path): + def test_the_template_leaves_the_pane_distance_commented_out(self, tmp_path): path = tmp_path / ConfigDataStacked.DEFAULT_FILENAME ConfigDataStacked.create_template(filename=str(path), num_simulations=2) config = ConfigDataStacked(filename=str(path)) - assert [config.get_pane(sim_idx) for sim_idx in range(2)] == [None, None] + assert [config.get_pane_distance(sim_idx) for sim_idx in range(2)] == [None, None] + + def test_the_analysis_puts_every_camera_behind_its_own_pane(self, tmp_path, monkeypatch): + solver = build_stacked_solver(tmp_path, monkeypatch) + + assert [experiment.camera.pane_distance for experiment in solver.sub_experiments] == [2.0, None] + + def test_the_header_names_only_the_cameras_behind_a_pane(self, tmp_path, monkeypatch): + solver = build_stacked_solver(tmp_path, monkeypatch) - @pytest.fixture - def stacked_solver(self, tmp_path, monkeypatch): - monkeypatch.setattr(stacked_module, 'Experiment', ExperimentSpy) - monkeypatch.setattr(StackedExtinctionCoefficients, '_build_sub_solver', lambda self, exp, sim_idx: None) - return StackedExtinctionCoefficients(load_stacked_config(tmp_path), led_array_id=0, channel=0) + assert solver._pane_info() == 'pane_distance: sim0 2.0 | ' - def test_the_analysis_puts_every_camera_behind_its_own_pane(self, stacked_solver): - assert [experiment.camera.pane for experiment in stacked_solver.sub_experiments] == [HALFWAY_PANE, None] + def test_without_a_pane_the_header_stays_as_it_was(self, tmp_path, monkeypatch): + solver = build_stacked_solver(tmp_path, monkeypatch, STACKED_CONFIG_WITHOUT_PANES) - def test_the_header_names_only_the_cameras_behind_a_pane(self, stacked_solver): - assert stacked_solver._pane_info() == 'sim0 behind the pane through (0, 2, 0) with the normal (0, 1, 0) | ' + assert solver._pane_info() == ''