From cd8faf75406ce3116eb9d2fef2bc385ea2cbc1eb Mon Sep 17 00:00:00 2001 From: Braden Date: Thu, 13 Mar 2025 10:09:15 -0600 Subject: [PATCH 01/19] Initial instantiation of SofastInterface --- opencsp/app/sofast/lib/SofastInterface.py | 453 ++++++++++++++++++++++ 1 file changed, 453 insertions(+) create mode 100644 opencsp/app/sofast/lib/SofastInterface.py diff --git a/opencsp/app/sofast/lib/SofastInterface.py b/opencsp/app/sofast/lib/SofastInterface.py new file mode 100644 index 000000000..7b523f5e4 --- /dev/null +++ b/opencsp/app/sofast/lib/SofastInterface.py @@ -0,0 +1,453 @@ +import glob +from os.path import join, dirname, abspath +from dataclasses import dataclass +import matplotlib.pyplot as plt + +from opencsp.app.sofast.lib.DefinitionFacet import DefinitionFacet +from opencsp.app.sofast.lib.DisplayShape import DisplayShape +from opencsp.app.sofast.lib.DotLocationsFixedPattern import DotLocationsFixedPattern +from opencsp.app.sofast.lib.Fringes import Fringes +from opencsp.app.sofast.lib.ImageCalibrationScaling import ImageCalibrationScaling +from opencsp.app.sofast.lib.ProcessSofastFixed import ProcessSofastFixed +from opencsp.app.sofast.lib.ProcessSofastFringe import ProcessSofastFringe +from opencsp.app.sofast.lib.SpatialOrientation import SpatialOrientation +from opencsp.app.sofast.lib.SystemSofastFringe import SystemSofastFringe +from opencsp.app.sofast.lib.SystemSofastFixed import SystemSofastFixed +from opencsp.common.lib.camera.Camera import Camera +from opencsp.common.lib.camera.ImageAcquisition_DCAM_mono import ImageAcquisition +from opencsp.common.lib.camera.image_processing import highlight_saturation +from opencsp.common.lib.camera.LiveView import LiveView +from opencsp.common.lib.deflectometry.ImageProjection import ImageProjection +from opencsp.common.lib.deflectometry.Surface2DParabolic import Surface2DParabolic +from opencsp.common.lib.geometry.Vxy import Vxy +from opencsp.common.lib.geometry.Vxyz import Vxyz +import opencsp.common.lib.render.figure_management as fm +import opencsp.common.lib.render_control.RenderControlAxis as rca +import opencsp.common.lib.render_control.RenderControlFigure as rcfg +import opencsp.common.lib.tool.log_tools as lt +from opencsp.common.lib.tool.time_date_tools import current_date_time_string_forfile as timestamp + + +class SofastInterface: + def __init__(self) -> "SofastInterface": + # Common sofast parameters + self.image_acquisition: ImageAcquisition = None + self.camera: Camera = None + self.facet_definition: DefinitionFacet = None + self.spatial_orientation: SpatialOrientation = None + self.measure_point_optic: Vxyz = None + self.dist_optic_screen: float = None + self.name_optic: str = None + + self.image_projection = ImageProjection.instance() + self.res_plot = 0.002 # meters + """Resolution of slope map image (meters)""" + self.colorbar_limit = 7 # mrad + """Colorbar limits in slope magnitude plot (mrad)""" + + # Sofast fringe specific + self.system_fringe: SystemSofastFringe = None + self.display_shape: DisplayShape = None + self.surface_fringe: Surface2DParabolic = None + self.timestamp_fringe_measurement = None + + # Sofast fixed specific + self.system_fixed: SystemSofastFixed = None + self.process_sofast_fixed: ProcessSofastFixed = None + self.fixed_pattern_dot_locs: DotLocationsFixedPattern = None + self.surface_fixed: Surface2DParabolic = None + self.origin: Vxy = None + self.timestamp_fixed_measurement = None + self.pattern_width = 3 + """Fixed pattern dot width, pixels""" + self.pattern_spacing = 6 + """Fixed pattern dot spacing, pixels""" + + # Save directories + self.dir_save_fringe: str = "" + """Location to save Sofast Fringe measurement data""" + self.dir_save_fixed: str = "" + """Location to save Sofast Fixed measurement data""" + self.dir_save_fringe_calibration: str = "" + """Location to save Sofast Fringe calibration data""" + + def run(self) -> None: + """Runs command line Sofast""" + self.func_user_input() + + def set_common_data( + self, + image_acquisition: ImageAcquisition, + image_projection: ImageProjection, + camera: Camera, + facet_definition: DefinitionFacet, + spatial_orientation: SpatialOrientation, + measure_point_optic: Vxyz, + dist_optic_screen: float, + name_optic: str, + ) -> None: + """Sets common parametes for Sofast Fringe and Fixed + + Parameters + ---------- + image_acquisition : ImageAcquisition + ImageAcquisition object + image_projection : ImageProjection + Image projection object + camera : Camera + Camera calibration object + facet_definition : DefinitionFacet + Facet definition object + spatial_orientation : SpatialOrientation + Calibrated SpatialOrientation object + measure_point_optic : Vxyz + Measure point location on optic + dist_optic_screen : float + Distance from measure point to screen center + name_optic : str + Name of optic + """ + self.image_acquisition = image_acquisition + self.image_projection = image_projection + self.camera = camera + self.facet_definition = facet_definition + self.spatial_orientation = spatial_orientation + self.measure_point_optic = measure_point_optic + self.dist_optic_screen = dist_optic_screen + self.name_optic = name_optic + + def set_sofast_fringe_data( + self, display_shape: DisplayShape, fringes: Fringes, surface_fringe: Surface2DParabolic + ) -> None: + """Loads Sofast Fringe specific objects + + Parameters + ---------- + display_shape : DisplayShape + Calibrated DisplayShape object + fringes : Fringes + Fringe objects to display + surface_fringe : Surface2DParabolic + Surface to use when processing Sofast Fringe data + """ + self.system_fringe = SystemSofastFringe(self.image_acquisition) + self.system_fringe.set_fringes(fringes) + self.display_shape = display_shape + self.surface_fringe = surface_fringe + + def set_sofast_fixed_data( + self, fixed_pattern_dot_locs: DotLocationsFixedPattern, origin: Vxy, surface_fixed: Surface2DParabolic + ) -> None: + """Loads Sofast Fixed specific objects + + Parameters + ---------- + fixed_pattern_dot_locs : DotLocationsFixedPattern + Calibrated dot locations object + origin : Vxy + Origin dot location in image, pixels + surface_fixed : Surface2DParabolic + Surface to use when processing Sofast Fringe data + """ + self.system_fixed = SystemSofastFixed(self.image_acquisition) + self.system_fixed.set_pattern_parameters(self.pattern_width, self.pattern_spacing) + self.fixed_pattern_dot_locs = fixed_pattern_dot_locs + self.origin = origin + self.surface_fixed = surface_fixed + + self.process_sofast_fixed = ProcessSofastFixed(self.spatial_orientation, self.camera, fixed_pattern_dot_locs) + + def func_run_fringe_measurement(self) -> None: + """Runs sofast fringe measurement""" + lt.info(f"{timestamp():s} Starting Sofast Fringe measurement") + self.timestamp_fringe_measurement = timestamp() + + def _on_done(): + lt.info(f"{timestamp():s} Completed Sofast Fringe measurement") + self.system_fringe.run_next_in_queue() + + self.system_fringe.run_measurement(_on_done) + + def func_run_fixed_measurement(self) -> None: + """Runs Sofast Fixed measurement""" + lt.info(f"{timestamp():s} Starting Sofast Fixed measurement") + self.timestamp_fixed_measurement = timestamp() + + def _f1(): + lt.info(f"{timestamp():s} Completed Sofast Fixed measurement") + self.system_fixed.run_next_in_queue() + + self.system_fixed.prepend_to_queue([self.system_fixed.run_measurement, _f1]) + self.system_fixed.run_next_in_queue() + + def func_show_crosshairs_fringe(self): + """Shows crosshairs and run next in Sofast fringe queue after a 0.2s wait""" + self.image_projection.show_crosshairs() + self.system_fringe.root.after(200, self.system_fringe.run_next_in_queue) + + def func_process_sofast_fringe_data(self): + """Processes Sofast Fringe data""" + lt.info(f"{timestamp():s} Starting Sofast Fringe data processing") + + # Get Measurement object + measurement = self.system_fringe.get_measurements( + self.measure_point_optic, self.dist_optic_screen, self.name_optic + )[0] + + # Calibrate fringe images + measurement.calibrate_fringe_images(self.system_fringe.calibration) + + # Instantiate ProcessSofastFringe + sofast = ProcessSofastFringe(measurement, self.spatial_orientation, self.camera, self.display_shape) + + # Process + sofast.process_optic_singlefacet(self.facet_definition, self.surface_fringe) + + lt.info(f"{timestamp():s} Completed Sofast Fringe data processing") + + # Plot optic + mirror = sofast.get_optic().mirror + + lt.debug(f"{timestamp():s} Plotting Sofast Fringe data") + figure_control = rcfg.RenderControlFigure(tile_array=(1, 1), tile_square=True) + axis_control_m = rca.meters() + fig_record = fm.setup_figure(figure_control, axis_control_m, title="") + mirror.plot_orthorectified_slope(self.res_plot, clim=self.colorbar_limit, axis=fig_record.axis) + fig_record.save(self.dir_save_fringe, f"{self.timestamp_fringe_measurement:s}_slope_magnitude_fringe", "png") + fig_record.close() + + # Save processed sofast data + sofast.save_to_hdf(f"{self.dir_save_fringe:s}/{self.timestamp_fringe_measurement:s}_data_sofast_fringe.h5") + lt.debug(f"{timestamp():s} Sofast Fringe data saved to HDF5") + + # Continue + self.system_fringe.run_next_in_queue() + + def func_process_sofast_fixed_data(self): + """Process Sofast Fixed data""" + lt.info(f"{timestamp():s} Starting Sofast Fixed data processing") + # Get Measurement object + measurement = self.system_fixed.get_measurement( + self.measure_point_optic, self.dist_optic_screen, self.origin, name=self.name_optic + ) + self.process_sofast_fixed.load_measurement_data(measurement) + + # Process + xy_known = (0, 0) + self.process_sofast_fixed.process_single_facet_optic( + self.facet_definition, self.surface_fixed, self.origin, xy_known=xy_known + ) + + lt.info(f"{timestamp():s} Completed Sofast Fixed data processing") + + # Plot optic + mirror = self.process_sofast_fixed.get_optic() + + lt.debug(f"{timestamp():s} Plotting Sofast Fixed data") + figure_control = rcfg.RenderControlFigure(tile_array=(1, 1), tile_square=True) + axis_control_m = rca.meters() + fig_record = fm.setup_figure(figure_control, axis_control_m, title="") + mirror.plot_orthorectified_slope(self.res_plot, clim=self.colorbar_limit, axis=fig_record.axis) + fig_record.save(self.dir_save_fixed, f"{self.timestamp_fixed_measurement:s}_slope_magnitude_fixed", "png") + + # Save processed sofast data + self.process_sofast_fixed.save_to_hdf( + f"{self.dir_save_fixed:s}/{self.timestamp_fixed_measurement:s}_data_sofast_fixed.h5" + ) + lt.debug(f"{timestamp():s} Sofast Fixed data saved to HDF5") + + # Continue + self.system_fixed.run_next_in_queue() + + def func_save_measurement_fringe(self): + """Saves measurement to HDF file""" + measurement = self.system_fringe.get_measurements( + self.measure_point_optic, self.dist_optic_screen, self.name_optic + )[0] + file = f"{self.dir_save_fringe:s}/{self.timestamp_fringe_measurement:s}_measurement_fringe.h5" + measurement.save_to_hdf(file) + self.system_fringe.calibration.save_to_hdf(file) + self.system_fringe.run_next_in_queue() + + def func_save_measurement_fixed(self): + """Save fixed measurement files""" + measurement = self.system_fixed.get_measurement( + self.measure_point_optic, self.dist_optic_screen, self.origin, name=self.name_optic + ) + measurement.save_to_hdf(f"{self.dir_save_fixed:s}/{self.timestamp_fixed_measurement:s}_measurement_fixed.h5") + self.system_fixed.run_next_in_queue() + + def func_load_last_sofast_fringe_image_cal(self): + """Loads last ImageCalibration object""" + # Find file + files = glob.glob(join(self.dir_save_fringe_calibration, "image_calibration_scaling*.h5")) + files.sort() + + if len(files) == 0: + lt.error(f"No previous calibration files found in {self.dir_save_fringe_calibration}") + return + + # Get latest file and set + file = files[-1] + image_calibration = ImageCalibrationScaling.load_from_hdf(file) + self.system_fringe.set_calibration(image_calibration) + lt.info(f"{timestamp()} Loaded image calibration file: {file}") + + def func_gray_levels_cal(self): + """Runs gray level calibration sequence""" + file = join(self.dir_save_fringe_calibration, f"image_calibration_scaling_{timestamp():s}.h5") + self.system_fringe.run_gray_levels_cal( + ImageCalibrationScaling, + file, + on_processed=self.func_user_input, + on_processing=self.func_show_crosshairs_fringe, + ) + + def show_cam_image(self): + """Shows a camera image""" + image = self.image_acquisition.get_frame() + image_proc = highlight_saturation(image, self.image_acquisition.max_value) + plt.imshow(image_proc) + plt.show() + + def show_live_view(self): + """Shows live vieew window""" + LiveView(self.image_acquisition) + + def func_user_input(self): + """Waits for user input""" + retval = input("Input: ") + + lt.debug(f"{timestamp():s} user input: {retval:s}") + + try: + self._run_given_input(retval) + except Exception as error: + lt.error(repr(error)) + self.func_user_input() + + def _check_fringe_system_loaded(self) -> bool: + if self.system_fringe is None: + lt.error(f"{timestamp()} No Sofast Fringe system loaded") + return False + return True + + def _check_fixed_system_loaded(self) -> bool: + if self.system_fixed is None: + lt.error(f"{timestamp()} No Sofast Fixed system loaded") + return False + return True + + def _run_given_input(self, retval: str) -> None: + """Runs the given command""" + # Run fringe measurement and process/save + if retval == "help": + print("\n") + print("Value Command") + print("------------------") + print("mrp run Sofast Fringe measurement and process/save") + print("mrs run Sofast Fringe measurement and save only") + print("mip run Sofast Fixed measurement and process/save") + print("mis run Sofast Fixed measurement and save only") + print("ce calibrate camera exposure") + print("cr calibrate camera-projector response") + print("lr load most recent camera-projector response calibration file") + print("q quit and close all") + print("im show image from camera.") + print("lv shows camera live view") + print("cross show crosshairs") + self.func_user_input() + elif retval == "mrp": + lt.info(f"{timestamp()} Running Sofast Fringe measurement and processing/saving data") + if self._check_fringe_system_loaded(): + funcs = [ + self.func_run_fringe_measurement, + self.func_show_crosshairs_fringe, + self.func_process_sofast_fringe_data, + self.func_save_measurement_fringe, + self.func_user_input, + ] + self.system_fringe.set_queue(funcs) + self.system_fringe.run() + else: + self.func_user_input() + # Run fringe measurement and save + elif retval == "mrs": + lt.info(f"{timestamp()} Running Sofast Fringe measurement and saving data") + if self._check_fringe_system_loaded(): + funcs = [ + self.func_run_fringe_measurement, + self.func_show_crosshairs_fringe, + self.func_save_measurement_fringe, + self.func_user_input, + ] + self.system_fringe.set_queue(funcs) + self.system_fringe.run() + else: + self.func_user_input() + # Run fixed measurement and process/save + elif retval == "mip": + lt.info(f"{timestamp()} Running Sofast Fixed measurement and processing/saving data") + if self._check_fixed_system_loaded(): + funcs = [ + self.func_run_fixed_measurement, + self.func_process_sofast_fixed_data, + self.func_save_measurement_fixed, + self.func_user_input, + ] + self.system_fixed.set_queue(funcs) + self.system_fixed.run() + else: + self.func_user_input() + # Run fixed measurement and save + elif retval == "mis": + lt.info(f"{timestamp()} Running Sofast Fixed measurement and saving data") + if self._check_fixed_system_loaded(): + funcs = [self.func_run_fixed_measurement, self.func_save_measurement_fixed, self.func_user_input] + self.system_fixed.set_queue(funcs) + self.system_fixed.run() + else: + self.func_user_input() + # Calibrate exposure time + elif retval == "ce": + lt.info(f"{timestamp()} Calibrating camera exposure") + self.image_acquisition.calibrate_exposure() + self.func_user_input() + # Calibrate response + elif retval == "cr": + lt.info(f"{timestamp()} Calibrating camera-projector response") + if self._check_fringe_system_loaded(): + funcs = [self.func_gray_levels_cal] + self.system_fringe.set_queue(funcs) + self.system_fringe.run() + else: + self.func_user_input() + # Load last fringe calibration file + elif retval == "lr": + lt.info(f"{timestamp()} Loading response calibration") + if self._check_fringe_system_loaded(): + self.func_load_last_sofast_fringe_image_cal() + self.func_user_input() + # Quit + elif retval == "q": + lt.info(f"{timestamp():s} quitting") + if self.system_fringe is not None: + self.system_fringe.close_all() + if self.system_fixed is not None: + self.system_fixed.close_all() + return + # Show single camera image + elif retval == "im": + self.show_cam_image() + self.func_user_input() + # Show camera live view + elif retval == "lv": + self.show_live_view() + self.func_user_input() + # Project crosshairs + elif retval == "cross": + self.image_projection.show_crosshairs() + self.func_user_input() + else: + lt.error(f"{timestamp()} Command, {retval}, not recognized") + self.func_user_input() From be5e95ad68e2c162eb3aaf31764a312b7deab664 Mon Sep 17 00:00:00 2001 From: Braden Date: Thu, 13 Mar 2025 13:52:07 -0600 Subject: [PATCH 02/19] MIS and MRS working. --- opencsp/app/sofast/lib/SofastInterface.py | 298 +++++++++++----------- 1 file changed, 145 insertions(+), 153 deletions(-) diff --git a/opencsp/app/sofast/lib/SofastInterface.py b/opencsp/app/sofast/lib/SofastInterface.py index 7b523f5e4..74c674313 100644 --- a/opencsp/app/sofast/lib/SofastInterface.py +++ b/opencsp/app/sofast/lib/SofastInterface.py @@ -1,6 +1,10 @@ import glob from os.path import join, dirname, abspath from dataclasses import dataclass +import datetime as dt +import time +import threading + import matplotlib.pyplot as plt from opencsp.app.sofast.lib.DefinitionFacet import DefinitionFacet @@ -14,7 +18,7 @@ from opencsp.app.sofast.lib.SystemSofastFringe import SystemSofastFringe from opencsp.app.sofast.lib.SystemSofastFixed import SystemSofastFixed from opencsp.common.lib.camera.Camera import Camera -from opencsp.common.lib.camera.ImageAcquisition_DCAM_mono import ImageAcquisition +from opencsp.common.lib.camera.ImageAcquisitionAbstract import ImageAcquisitionAbstract from opencsp.common.lib.camera.image_processing import highlight_saturation from opencsp.common.lib.camera.LiveView import LiveView from opencsp.common.lib.deflectometry.ImageProjection import ImageProjection @@ -28,139 +32,103 @@ from opencsp.common.lib.tool.time_date_tools import current_date_time_string_forfile as timestamp -class SofastInterface: - def __init__(self) -> "SofastInterface": - # Common sofast parameters - self.image_acquisition: ImageAcquisition = None - self.camera: Camera = None - self.facet_definition: DefinitionFacet = None - self.spatial_orientation: SpatialOrientation = None - self.measure_point_optic: Vxyz = None - self.dist_optic_screen: float = None - self.name_optic: str = None +@dataclass +class SofastProcessingData: + # Common + image_acquisition: ImageAcquisitionAbstract = None + image_projection: ImageProjection = None + camera: Camera = None + facet_definition: DefinitionFacet = None + spatial_orientation: SpatialOrientation = None + # Sofast Fringe + display_shape: DisplayShape = None + surface_fringe: Surface2DParabolic = None + # Sofast Fixed + fixed_pattern_dot_locs: DotLocationsFixedPattern = None + surface_fixed: Surface2DParabolic = None + process_sofast_fixed: ProcessSofastFixed = None + + +@dataclass +class SofastFixedRunData: + origin: Vxy = None + pattern_width = 3 + """Fixed pattern dot width, pixels""" + pattern_spacing = 6 + """Fixed pattern dot spacing, pixels""" + + def is_ready(self) -> bool: + if (self.origin is None) or (self.pattern_width is None) or (self.pattern_spacing is None): + return False + return True + + +@dataclass +class SofastCommonRunData: + measure_point_optic: Vxyz = None + dist_optic_screen: float = None + name_optic: str = None + + def is_ready(self) -> bool: + if (self.measure_point_optic is None) or (self.dist_optic_screen is None) or (self.name_optic is None): + return False + return True + + +@dataclass +class Paths: + dir_save_fringe: str = "" + """Location to save Sofast Fringe measurement data""" + dir_save_fixed: str = "" + """Location to save Sofast Fixed measurement data""" + dir_save_fringe_calibration: str = "" + """Location to save Sofast Fringe calibration data""" + +class SofastInterface: + def __init__(self, image_acquisition: ImageAcquisitionAbstract) -> "SofastInterface": + self.image_acquisition = image_acquisition self.image_projection = ImageProjection.instance() - self.res_plot = 0.002 # meters - """Resolution of slope map image (meters)""" - self.colorbar_limit = 7 # mrad - """Colorbar limits in slope magnitude plot (mrad)""" - # Sofast fringe specific - self.system_fringe: SystemSofastFringe = None - self.display_shape: DisplayShape = None - self.surface_fringe: Surface2DParabolic = None - self.timestamp_fringe_measurement = None + self.data_sofast_processing = SofastProcessingData() + self.data_sofast_common_run = SofastCommonRunData() + self.data_sofast_fixed_run = SofastFixedRunData() + self.paths = Paths + self.timestamp: dt.datetime = None - # Sofast fixed specific self.system_fixed: SystemSofastFixed = None - self.process_sofast_fixed: ProcessSofastFixed = None - self.fixed_pattern_dot_locs: DotLocationsFixedPattern = None - self.surface_fixed: Surface2DParabolic = None - self.origin: Vxy = None - self.timestamp_fixed_measurement = None - self.pattern_width = 3 - """Fixed pattern dot width, pixels""" - self.pattern_spacing = 6 - """Fixed pattern dot spacing, pixels""" - - # Save directories - self.dir_save_fringe: str = "" - """Location to save Sofast Fringe measurement data""" - self.dir_save_fixed: str = "" - """Location to save Sofast Fixed measurement data""" - self.dir_save_fringe_calibration: str = "" - """Location to save Sofast Fringe calibration data""" - - def run(self) -> None: + self.system_fringe: SystemSofastFringe = None + + def run_cli(self) -> None: """Runs command line Sofast""" - self.func_user_input() - - def set_common_data( - self, - image_acquisition: ImageAcquisition, - image_projection: ImageProjection, - camera: Camera, - facet_definition: DefinitionFacet, - spatial_orientation: SpatialOrientation, - measure_point_optic: Vxyz, - dist_optic_screen: float, - name_optic: str, - ) -> None: + self._func_user_input() + + def set_sofast_processing_data(self, data: SofastProcessingData) -> None: """Sets common parametes for Sofast Fringe and Fixed Parameters ---------- - image_acquisition : ImageAcquisition - ImageAcquisition object - image_projection : ImageProjection - Image projection object - camera : Camera - Camera calibration object - facet_definition : DefinitionFacet - Facet definition object - spatial_orientation : SpatialOrientation - Calibrated SpatialOrientation object - measure_point_optic : Vxyz - Measure point location on optic - dist_optic_screen : float - Distance from measure point to screen center - name_optic : str - Name of optic + data : SofastProcessingData + SofastProcessingData object """ - self.image_acquisition = image_acquisition - self.image_projection = image_projection - self.camera = camera - self.facet_definition = facet_definition - self.spatial_orientation = spatial_orientation - self.measure_point_optic = measure_point_optic - self.dist_optic_screen = dist_optic_screen - self.name_optic = name_optic - - def set_sofast_fringe_data( - self, display_shape: DisplayShape, fringes: Fringes, surface_fringe: Surface2DParabolic - ) -> None: - """Loads Sofast Fringe specific objects + self.data_sofast_processing = data - Parameters - ---------- - display_shape : DisplayShape - Calibrated DisplayShape object - fringes : Fringes - Fringe objects to display - surface_fringe : Surface2DParabolic - Surface to use when processing Sofast Fringe data - """ + def initialize_sofast_fringe(self, fringes: Fringes) -> None: + """Initializes sofast fringe system""" self.system_fringe = SystemSofastFringe(self.image_acquisition) self.system_fringe.set_fringes(fringes) - self.display_shape = display_shape - self.surface_fringe = surface_fringe - def set_sofast_fixed_data( - self, fixed_pattern_dot_locs: DotLocationsFixedPattern, origin: Vxy, surface_fixed: Surface2DParabolic - ) -> None: - """Loads Sofast Fixed specific objects - - Parameters - ---------- - fixed_pattern_dot_locs : DotLocationsFixedPattern - Calibrated dot locations object - origin : Vxy - Origin dot location in image, pixels - surface_fixed : Surface2DParabolic - Surface to use when processing Sofast Fringe data - """ - self.system_fixed = SystemSofastFixed(self.image_acquisition) - self.system_fixed.set_pattern_parameters(self.pattern_width, self.pattern_spacing) - self.fixed_pattern_dot_locs = fixed_pattern_dot_locs - self.origin = origin - self.surface_fixed = surface_fixed - - self.process_sofast_fixed = ProcessSofastFixed(self.spatial_orientation, self.camera, fixed_pattern_dot_locs) + def initialize_sofast_fixed(self) -> None: + """Initializes sofast fixed system""" + if self._check_fixed_run_data_loaded(): + self.system_fixed = SystemSofastFixed(self.image_acquisition) + self.system_fixed.set_pattern_parameters( + self.data_sofast_fixed_run.pattern_width, self.data_sofast_fixed_run.pattern_spacing + ) def func_run_fringe_measurement(self) -> None: """Runs sofast fringe measurement""" lt.info(f"{timestamp():s} Starting Sofast Fringe measurement") - self.timestamp_fringe_measurement = timestamp() def _on_done(): lt.info(f"{timestamp():s} Completed Sofast Fringe measurement") @@ -171,7 +139,6 @@ def _on_done(): def func_run_fixed_measurement(self) -> None: """Runs Sofast Fixed measurement""" lt.info(f"{timestamp():s} Starting Sofast Fixed measurement") - self.timestamp_fixed_measurement = timestamp() def _f1(): lt.info(f"{timestamp():s} Completed Sofast Fixed measurement") @@ -262,9 +229,12 @@ def func_process_sofast_fixed_data(self): def func_save_measurement_fringe(self): """Saves measurement to HDF file""" measurement = self.system_fringe.get_measurements( - self.measure_point_optic, self.dist_optic_screen, self.name_optic + self.data_sofast_common_run.measure_point_optic, + self.data_sofast_common_run.dist_optic_screen, + self.data_sofast_common_run.name_optic, )[0] - file = f"{self.dir_save_fringe:s}/{self.timestamp_fringe_measurement:s}_measurement_fringe.h5" + file_timestamp = self.timestamp.strftime(r"%Y-%m-%d_%H_%M_%S.%f") + file = f"{self.paths.dir_save_fringe:s}/{file_timestamp:s}_measurement_fringe.h5" measurement.save_to_hdf(file) self.system_fringe.calibration.save_to_hdf(file) self.system_fringe.run_next_in_queue() @@ -272,19 +242,23 @@ def func_save_measurement_fringe(self): def func_save_measurement_fixed(self): """Save fixed measurement files""" measurement = self.system_fixed.get_measurement( - self.measure_point_optic, self.dist_optic_screen, self.origin, name=self.name_optic + self.data_sofast_common_run.measure_point_optic, + self.data_sofast_common_run.dist_optic_screen, + self.data_sofast_fixed_run.origin, + name=self.data_sofast_common_run.name_optic, ) - measurement.save_to_hdf(f"{self.dir_save_fixed:s}/{self.timestamp_fixed_measurement:s}_measurement_fixed.h5") + file_timestamp = self.timestamp.strftime(r"%Y-%m-%d_%H_%M_%S.%f") + measurement.save_to_hdf(f"{self.paths.dir_save_fixed:s}/{file_timestamp:s}_measurement_fixed.h5") self.system_fixed.run_next_in_queue() def func_load_last_sofast_fringe_image_cal(self): """Loads last ImageCalibration object""" # Find file - files = glob.glob(join(self.dir_save_fringe_calibration, "image_calibration_scaling*.h5")) + files = glob.glob(join(self.paths.dir_save_fringe_calibration, "image_calibration_scaling*.h5")) files.sort() if len(files) == 0: - lt.error(f"No previous calibration files found in {self.dir_save_fringe_calibration}") + lt.error(f"No previous calibration files found in {self.paths.dir_save_fringe_calibration}") return # Get latest file and set @@ -295,11 +269,11 @@ def func_load_last_sofast_fringe_image_cal(self): def func_gray_levels_cal(self): """Runs gray level calibration sequence""" - file = join(self.dir_save_fringe_calibration, f"image_calibration_scaling_{timestamp():s}.h5") + file = join(self.paths.dir_save_fringe_calibration, f"image_calibration_scaling_{timestamp():s}.h5") self.system_fringe.run_gray_levels_cal( ImageCalibrationScaling, file, - on_processed=self.func_user_input, + on_processed=self._func_user_input, on_processing=self.func_show_crosshairs_fringe, ) @@ -311,33 +285,51 @@ def show_cam_image(self): plt.show() def show_live_view(self): - """Shows live vieew window""" + """Shows live view window""" LiveView(self.image_acquisition) - def func_user_input(self): - """Waits for user input""" - retval = input("Input: ") - - lt.debug(f"{timestamp():s} user input: {retval:s}") + def _check_fixed_run_data_loaded(self) -> bool: + if not self.data_sofast_fixed_run.is_ready(): + lt.error(f"{timestamp()} Sofast Fixed processing data not fully loaded") + return False + return True - try: - self._run_given_input(retval) - except Exception as error: - lt.error(repr(error)) - self.func_user_input() + def _check_common_run_data_loaded(self) -> bool: + if not self.data_sofast_common_run.is_ready(): + lt.error(f"{timestamp()} Sofast Fringe processing data not fully loaded") + return False + return True def _check_fringe_system_loaded(self) -> bool: if self.system_fringe is None: - lt.error(f"{timestamp()} No Sofast Fringe system loaded") + lt.error(f"{timestamp()} Sofast Fringe system not initizlized") + return False + if not self._check_common_run_data_loaded(): return False return True def _check_fixed_system_loaded(self) -> bool: if self.system_fixed is None: - lt.error(f"{timestamp()} No Sofast Fixed system loaded") + lt.error(f"{timestamp()} Sofast Fixed system not initialized") + return False + if not self._check_common_run_data_loaded(): + return False + if not self._check_fixed_run_data_loaded(): return False return True + def _func_user_input(self): + """Function that requests and processes user input""" + # Get user input + retval = input("> ") + self.timestamp = dt.datetime.now() + lt.debug(f"{self.timestamp:s} user input: {retval:s}") + + try: + self._run_given_input(retval) + except Exception as error: + lt.error(repr(error)) + def _run_given_input(self, retval: str) -> None: """Runs the given command""" # Run fringe measurement and process/save @@ -356,7 +348,7 @@ def _run_given_input(self, retval: str) -> None: print("im show image from camera.") print("lv shows camera live view") print("cross show crosshairs") - self.func_user_input() + self._func_user_input() elif retval == "mrp": lt.info(f"{timestamp()} Running Sofast Fringe measurement and processing/saving data") if self._check_fringe_system_loaded(): @@ -365,12 +357,12 @@ def _run_given_input(self, retval: str) -> None: self.func_show_crosshairs_fringe, self.func_process_sofast_fringe_data, self.func_save_measurement_fringe, - self.func_user_input, + self._func_user_input, ] self.system_fringe.set_queue(funcs) self.system_fringe.run() else: - self.func_user_input() + self._func_user_input() # Run fringe measurement and save elif retval == "mrs": lt.info(f"{timestamp()} Running Sofast Fringe measurement and saving data") @@ -379,12 +371,12 @@ def _run_given_input(self, retval: str) -> None: self.func_run_fringe_measurement, self.func_show_crosshairs_fringe, self.func_save_measurement_fringe, - self.func_user_input, + self._func_user_input, ] self.system_fringe.set_queue(funcs) self.system_fringe.run() else: - self.func_user_input() + self._func_user_input() # Run fixed measurement and process/save elif retval == "mip": lt.info(f"{timestamp()} Running Sofast Fixed measurement and processing/saving data") @@ -393,26 +385,26 @@ def _run_given_input(self, retval: str) -> None: self.func_run_fixed_measurement, self.func_process_sofast_fixed_data, self.func_save_measurement_fixed, - self.func_user_input, + self._func_user_input, ] self.system_fixed.set_queue(funcs) self.system_fixed.run() else: - self.func_user_input() + self._func_user_input() # Run fixed measurement and save elif retval == "mis": lt.info(f"{timestamp()} Running Sofast Fixed measurement and saving data") if self._check_fixed_system_loaded(): - funcs = [self.func_run_fixed_measurement, self.func_save_measurement_fixed, self.func_user_input] + funcs = [self.func_run_fixed_measurement, self.func_save_measurement_fixed, self._func_user_input] self.system_fixed.set_queue(funcs) self.system_fixed.run() else: - self.func_user_input() + self._func_user_input() # Calibrate exposure time elif retval == "ce": lt.info(f"{timestamp()} Calibrating camera exposure") self.image_acquisition.calibrate_exposure() - self.func_user_input() + self._func_user_input() # Calibrate response elif retval == "cr": lt.info(f"{timestamp()} Calibrating camera-projector response") @@ -421,13 +413,13 @@ def _run_given_input(self, retval: str) -> None: self.system_fringe.set_queue(funcs) self.system_fringe.run() else: - self.func_user_input() + self._func_user_input() # Load last fringe calibration file elif retval == "lr": lt.info(f"{timestamp()} Loading response calibration") if self._check_fringe_system_loaded(): self.func_load_last_sofast_fringe_image_cal() - self.func_user_input() + self._func_user_input() # Quit elif retval == "q": lt.info(f"{timestamp():s} quitting") @@ -439,15 +431,15 @@ def _run_given_input(self, retval: str) -> None: # Show single camera image elif retval == "im": self.show_cam_image() - self.func_user_input() + self._func_user_input() # Show camera live view elif retval == "lv": self.show_live_view() - self.func_user_input() + self._func_user_input() # Project crosshairs elif retval == "cross": self.image_projection.show_crosshairs() - self.func_user_input() + self._func_user_input() else: lt.error(f"{timestamp()} Command, {retval}, not recognized") - self.func_user_input() + self._func_user_input() From 76012b8ec648f0f154e8d9642581977c106a090b Mon Sep 17 00:00:00 2001 From: Braden Date: Thu, 13 Mar 2025 14:46:16 -0600 Subject: [PATCH 03/19] Migrated to dataclasses. No processing yet. --- opencsp/app/sofast/lib/SofastInterface.py | 184 ++++++++++++---------- 1 file changed, 97 insertions(+), 87 deletions(-) diff --git a/opencsp/app/sofast/lib/SofastInterface.py b/opencsp/app/sofast/lib/SofastInterface.py index 74c674313..1550f8203 100644 --- a/opencsp/app/sofast/lib/SofastInterface.py +++ b/opencsp/app/sofast/lib/SofastInterface.py @@ -1,9 +1,7 @@ import glob -from os.path import join, dirname, abspath +from os.path import join from dataclasses import dataclass import datetime as dt -import time -import threading import matplotlib.pyplot as plt @@ -32,51 +30,46 @@ from opencsp.common.lib.tool.time_date_tools import current_date_time_string_forfile as timestamp -@dataclass -class SofastProcessingData: - # Common - image_acquisition: ImageAcquisitionAbstract = None - image_projection: ImageProjection = None - camera: Camera = None - facet_definition: DefinitionFacet = None - spatial_orientation: SpatialOrientation = None - # Sofast Fringe - display_shape: DisplayShape = None - surface_fringe: Surface2DParabolic = None - # Sofast Fixed - fixed_pattern_dot_locs: DotLocationsFixedPattern = None - surface_fixed: Surface2DParabolic = None - process_sofast_fixed: ProcessSofastFixed = None - - @dataclass class SofastFixedRunData: - origin: Vxy = None + origin: Vxy + """The xy pixel location in the camera image of the center of the xy_known dot""" + xy_known: tuple[int, int] = (0, 0) + """The xy index of a known dot location seen by the camera""" pattern_width = 3 """Fixed pattern dot width, pixels""" pattern_spacing = 6 - """Fixed pattern dot spacing, pixels""" - - def is_ready(self) -> bool: - if (self.origin is None) or (self.pattern_width is None) or (self.pattern_spacing is None): - return False - return True + """Fixed pattern dot spacing between edges of neighboring dots, pixels.""" @dataclass class SofastCommonRunData: - measure_point_optic: Vxyz = None - dist_optic_screen: float = None - name_optic: str = None + measure_point_optic: Vxyz + dist_optic_screen: float + name_optic: str - def is_ready(self) -> bool: - if (self.measure_point_optic is None) or (self.dist_optic_screen is None) or (self.name_optic is None): - return False - return True + +@dataclass +class SofastCommonProcessData: + facet_definition: DefinitionFacet + camera: Camera + spatial_orientation: SpatialOrientation @dataclass -class Paths: +class SofastFringeProcessData: + display_shape: DisplayShape + surface_2d: Surface2DParabolic + + +@dataclass +class SofastFixedProcessData: + fixed_pattern_dot_locs: DotLocationsFixedPattern + surface_2d: Surface2DParabolic + + +@dataclass +class _Paths: dir_save_fringe: str = "" """Location to save Sofast Fringe measurement data""" dir_save_fixed: str = "" @@ -87,32 +80,28 @@ class Paths: class SofastInterface: def __init__(self, image_acquisition: ImageAcquisitionAbstract) -> "SofastInterface": + # Common parameters self.image_acquisition = image_acquisition self.image_projection = ImageProjection.instance() - self.data_sofast_processing = SofastProcessingData() - self.data_sofast_common_run = SofastCommonRunData() - self.data_sofast_fixed_run = SofastFixedRunData() - self.paths = Paths - self.timestamp: dt.datetime = None - + # Sofast system objects self.system_fixed: SystemSofastFixed = None self.system_fringe: SystemSofastFringe = None + self.timestamp: dt.datetime = None + self._process_sofast_fixed: ProcessSofastFixed = None + + # User input objects + self.data_sofast_common_run: SofastCommonRunData = None + self.data_sofast_fixed_run: SofastFixedRunData = None + self.data_sofast_common_proccess: SofastCommonProcessData = None + self.data_sofast_fringe_process: SofastFringeProcessData = None + self.data_sofast_fixed_process: SofastFixedProcessData = None + self.paths = _Paths() def run_cli(self) -> None: """Runs command line Sofast""" self._func_user_input() - def set_sofast_processing_data(self, data: SofastProcessingData) -> None: - """Sets common parametes for Sofast Fringe and Fixed - - Parameters - ---------- - data : SofastProcessingData - SofastProcessingData object - """ - self.data_sofast_processing = data - def initialize_sofast_fringe(self, fringes: Fringes) -> None: """Initializes sofast fringe system""" self.system_fringe = SystemSofastFringe(self.image_acquisition) @@ -158,34 +147,43 @@ def func_process_sofast_fringe_data(self): # Get Measurement object measurement = self.system_fringe.get_measurements( - self.measure_point_optic, self.dist_optic_screen, self.name_optic + self.data_sofast_common_run.measure_point_optic, + self.data_sofast_common_run.dist_optic_screen, + self.data_sofast_common_run.name_optic, )[0] # Calibrate fringe images measurement.calibrate_fringe_images(self.system_fringe.calibration) # Instantiate ProcessSofastFringe - sofast = ProcessSofastFringe(measurement, self.spatial_orientation, self.camera, self.display_shape) + sofast = ProcessSofastFringe( + measurement, + self.data_sofast_common_proccess.spatial_orientation, + self.data_sofast_common_proccess.camera, + self.data_sofast_fringe_process.display_shape, + ) # Process - sofast.process_optic_singlefacet(self.facet_definition, self.surface_fringe) + sofast.process_optic_singlefacet( + self.data_sofast_common_proccess.facet_definition, self.data_sofast_fringe_process.surface_2d + ) lt.info(f"{timestamp():s} Completed Sofast Fringe data processing") # Plot optic mirror = sofast.get_optic().mirror - lt.debug(f"{timestamp():s} Plotting Sofast Fringe data") - figure_control = rcfg.RenderControlFigure(tile_array=(1, 1), tile_square=True) - axis_control_m = rca.meters() - fig_record = fm.setup_figure(figure_control, axis_control_m, title="") - mirror.plot_orthorectified_slope(self.res_plot, clim=self.colorbar_limit, axis=fig_record.axis) - fig_record.save(self.dir_save_fringe, f"{self.timestamp_fringe_measurement:s}_slope_magnitude_fringe", "png") - fig_record.close() + # lt.debug(f"{timestamp():s} Plotting Sofast Fringe data") + # figure_control = rcfg.RenderControlFigure(tile_array=(1, 1), tile_square=True) + # axis_control_m = rca.meters() + # fig_record = fm.setup_figure(figure_control, axis_control_m, title="") + # mirror.plot_orthorectified_slope(self.res_plot, clim=self.colorbar_limit, axis=fig_record.axis) + # fig_record.save(self.dir_save_fringe, f"{self.timestamp_fringe_measurement:s}_slope_magnitude_fringe", "png") + # fig_record.close() - # Save processed sofast data - sofast.save_to_hdf(f"{self.dir_save_fringe:s}/{self.timestamp_fringe_measurement:s}_data_sofast_fringe.h5") - lt.debug(f"{timestamp():s} Sofast Fringe data saved to HDF5") + # # Save processed sofast data + # sofast.save_to_hdf(f"{self.dir_save_fringe:s}/{self.timestamp_fringe_measurement:s}_data_sofast_fringe.h5") + # lt.debug(f"{timestamp():s} Sofast Fringe data saved to HDF5") # Continue self.system_fringe.run_next_in_queue() @@ -193,35 +191,47 @@ def func_process_sofast_fringe_data(self): def func_process_sofast_fixed_data(self): """Process Sofast Fixed data""" lt.info(f"{timestamp():s} Starting Sofast Fixed data processing") + # Instantiate sofast processing object + process_sofast_fixed = ProcessSofastFixed( + self.data_sofast_common_proccess.spatial_orientation, + self.data_sofast_common_proccess.camera, + self.data_sofast_fixed_process.fixed_pattern_dot_locs, + ) + # Get Measurement object measurement = self.system_fixed.get_measurement( - self.measure_point_optic, self.dist_optic_screen, self.origin, name=self.name_optic + self.data_sofast_common_run.measure_point_optic, + self.data_sofast_common_run.dist_optic_screen, + self.data_sofast_fixed_run.origin, + name=self.data_sofast_common_run.name_optic, ) - self.process_sofast_fixed.load_measurement_data(measurement) + process_sofast_fixed.load_measurement_data(measurement) # Process - xy_known = (0, 0) - self.process_sofast_fixed.process_single_facet_optic( - self.facet_definition, self.surface_fixed, self.origin, xy_known=xy_known + process_sofast_fixed.process_single_facet_optic( + self.data_sofast_common_proccess.facet_definition, + self.data_sofast_fixed_process.surface_2d, + self.data_sofast_fixed_run.origin, + xy_known=self.data_sofast_fixed_run.xy_known, ) lt.info(f"{timestamp():s} Completed Sofast Fixed data processing") # Plot optic - mirror = self.process_sofast_fixed.get_optic() - - lt.debug(f"{timestamp():s} Plotting Sofast Fixed data") - figure_control = rcfg.RenderControlFigure(tile_array=(1, 1), tile_square=True) - axis_control_m = rca.meters() - fig_record = fm.setup_figure(figure_control, axis_control_m, title="") - mirror.plot_orthorectified_slope(self.res_plot, clim=self.colorbar_limit, axis=fig_record.axis) - fig_record.save(self.dir_save_fixed, f"{self.timestamp_fixed_measurement:s}_slope_magnitude_fixed", "png") - - # Save processed sofast data - self.process_sofast_fixed.save_to_hdf( - f"{self.dir_save_fixed:s}/{self.timestamp_fixed_measurement:s}_data_sofast_fixed.h5" - ) - lt.debug(f"{timestamp():s} Sofast Fixed data saved to HDF5") + mirror = process_sofast_fixed.get_optic() + + # lt.debug(f"{timestamp():s} Plotting Sofast Fixed data") + # figure_control = rcfg.RenderControlFigure(tile_array=(1, 1), tile_square=True) + # axis_control_m = rca.meters() + # fig_record = fm.setup_figure(figure_control, axis_control_m, title="") + # mirror.plot_orthorectified_slope(self.res_plot, clim=self.colorbar_limit, axis=fig_record.axis) + # fig_record.save(self.dir_save_fixed, f"{self.timestamp_fixed_measurement:s}_slope_magnitude_fixed", "png") + + # # Save processed sofast data + # process_sofast_fixed.save_to_hdf( + # f"{self.dir_save_fixed:s}/{self.timestamp_fixed_measurement:s}_data_sofast_fixed.h5" + # ) + # lt.debug(f"{timestamp():s} Sofast Fixed data saved to HDF5") # Continue self.system_fixed.run_next_in_queue() @@ -289,14 +299,14 @@ def show_live_view(self): LiveView(self.image_acquisition) def _check_fixed_run_data_loaded(self) -> bool: - if not self.data_sofast_fixed_run.is_ready(): - lt.error(f"{timestamp()} Sofast Fixed processing data not fully loaded") + if self.data_sofast_fixed_run is None: + lt.error(f"{timestamp()} Sofast Fixed processing data not loaded") return False return True def _check_common_run_data_loaded(self) -> bool: - if not self.data_sofast_common_run.is_ready(): - lt.error(f"{timestamp()} Sofast Fringe processing data not fully loaded") + if self.data_sofast_common_run is None: + lt.error(f"{timestamp()} Sofast Fringe processing data not loaded") return False return True From bf5b6032820541baa530332bf89cb4f3ea981ed4 Mon Sep 17 00:00:00 2001 From: Braden Date: Thu, 13 Mar 2025 14:48:06 -0600 Subject: [PATCH 04/19] Added sofast command line tool to examples --- .../sofast_fringe/sofast_command_line_tool.py | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 example/sofast_fringe/sofast_command_line_tool.py diff --git a/example/sofast_fringe/sofast_command_line_tool.py b/example/sofast_fringe/sofast_command_line_tool.py new file mode 100644 index 000000000..b4ede29f5 --- /dev/null +++ b/example/sofast_fringe/sofast_command_line_tool.py @@ -0,0 +1,87 @@ +from os.path import join +import sys + +from opencsp.app.sofast.lib.DotLocationsFixedPattern import DotLocationsFixedPattern +from opencsp.app.sofast.lib.Fringes import Fringes +from opencsp.common.lib.deflectometry.Surface2DParabolic import Surface2DParabolic +from opencsp.common.lib.camera.ImageAcquisition_MSMF import ImageAcquisition +from opencsp.common.lib.deflectometry.ImageProjection import ImageProjection +from opencsp.app.sofast.lib.SofastInterface import ( + SofastInterface, + SofastCommonRunData, + SofastFixedRunData, + SofastCommonProcessData, + SofastFringeProcessData, + SofastFixedProcessData, +) +import opencsp.common.lib.tool.log_tools as lt +from opencsp.common.lib.geometry.Vxyz import Vxyz +from opencsp.common.lib.geometry.Vxy import Vxy +from opencsp.app.sofast.lib.DefinitionFacet import DefinitionFacet +from opencsp.common.lib.camera.Camera import Camera +from opencsp.app.sofast.lib.SpatialOrientation import SpatialOrientation +from opencsp.app.sofast.lib.DisplayShape import DisplayShape + + +def example_sofast_command_line_tool(dir_cal: str, dir_save: str): + # Set up OpenCSP logger + lt.logger(join(dir_save, "log.txt")) + + # Define image acquisition + image_acquisition_in = ImageAcquisition(instance=0) # First camera instance found + # image_acquisition_in.frame_size = (1626, 1236) # Set frame size + # image_acquisition_in.gain = 230 # Set gain (higher=faster/more noise, lower=slower/less noise) + + # Define image projection + file_image_projection = join(dir_cal, "image_projection_test_small.h5") + image_projection = ImageProjection.load_from_hdf(file_image_projection) + image_projection.display_data.image_delay_ms = 200 # define projector-camera delay + + # Setup and run Sofast Interface + inter = SofastInterface(image_acquisition_in) + + # Initialize Sofast Fringe system + fringes = Fringes.from_num_periods(4, 4) + inter.data_sofast_common_run = SofastCommonRunData( + measure_point_optic=Vxyz((0, 0, 0)), dist_optic_screen=10, name_optic="Some Optic" + ) + inter.initialize_sofast_fringe(fringes) + + # Initialize Sofast Fixed system + inter.data_sofast_fixed_run = SofastFixedRunData(origin=Vxy((100, 200))) + inter.initialize_sofast_fixed() + + # Initialize Sofast processing data + file_facet = join(dir_cal, "facet_NSTTF.json") + file_camera = join(dir_cal, "camera_sofast_optics_lab_landscape_2025_02.h5") + file_ori = join(dir_cal, "spatial_orientation_optics_lab_landscape.h5") + file_display_shape = join(dir_cal, "display_shape_optics_lab_landscape_square_distorted_3d_100x100.h5") + file_dot_locs = join(dir_cal, "dot_locations_optics_lab_landscape_square_width3_space6.h5") + surface_fringe = Surface2DParabolic((100, 100), False, 10) + surface_fixed = Surface2DParabolic((100, 100), False, 1) + + inter.data_sofast_common_proccess = SofastCommonProcessData( + facet_definition=DefinitionFacet.load_from_json(file_facet), + camera=Camera.load_from_hdf(file_camera), + spatial_orientation=SpatialOrientation.load_from_hdf(file_ori), + ) + inter.data_sofast_fringe_process = SofastFringeProcessData( + display_shape=DisplayShape.load_from_hdf(file_display_shape), surface_2d=surface_fringe + ) + inter.data_sofast_fixed_process = SofastFixedProcessData( + fixed_pattern_dot_locs=DotLocationsFixedPattern.load_from_hdf(file_dot_locs), surface_2d=surface_fixed + ) + + # Set up save paths + inter.paths.dir_save_fixed = dir_save + inter.paths.dir_save_fringe = dir_save + inter.paths.dir_save_fringe_calibration = dir_save + + # Run + inter.run_cli() + + +if __name__ == "__main__": + dir_cal_in = sys.argv[1] + dir_save_in = sys.argv[2] + example_sofast_command_line_tool(dir_cal_in, dir_save_in) From 981b0220c329ccddf32d1a9488e125737cf00510 Mon Sep 17 00:00:00 2001 From: Smith Date: Thu, 13 Mar 2025 15:09:43 -0600 Subject: [PATCH 05/19] Processed data is saved, not plotted. --- .../sofast_fringe/sofast_command_line_tool.py | 26 +++++++++---------- opencsp/app/sofast/lib/SofastInterface.py | 25 +++++++++--------- 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/example/sofast_fringe/sofast_command_line_tool.py b/example/sofast_fringe/sofast_command_line_tool.py index b4ede29f5..93d4f5318 100644 --- a/example/sofast_fringe/sofast_command_line_tool.py +++ b/example/sofast_fringe/sofast_command_line_tool.py @@ -1,11 +1,10 @@ from os.path import join import sys +from opencsp.app.sofast.lib.DefinitionFacet import DefinitionFacet from opencsp.app.sofast.lib.DotLocationsFixedPattern import DotLocationsFixedPattern +from opencsp.app.sofast.lib.DisplayShape import DisplayShape from opencsp.app.sofast.lib.Fringes import Fringes -from opencsp.common.lib.deflectometry.Surface2DParabolic import Surface2DParabolic -from opencsp.common.lib.camera.ImageAcquisition_MSMF import ImageAcquisition -from opencsp.common.lib.deflectometry.ImageProjection import ImageProjection from opencsp.app.sofast.lib.SofastInterface import ( SofastInterface, SofastCommonRunData, @@ -14,26 +13,27 @@ SofastFringeProcessData, SofastFixedProcessData, ) -import opencsp.common.lib.tool.log_tools as lt -from opencsp.common.lib.geometry.Vxyz import Vxyz -from opencsp.common.lib.geometry.Vxy import Vxy -from opencsp.app.sofast.lib.DefinitionFacet import DefinitionFacet -from opencsp.common.lib.camera.Camera import Camera from opencsp.app.sofast.lib.SpatialOrientation import SpatialOrientation -from opencsp.app.sofast.lib.DisplayShape import DisplayShape +from opencsp.common.lib.camera.Camera import Camera +from opencsp.common.lib.camera.ImageAcquisition_DCAM_mono import ImageAcquisition +from opencsp.common.lib.deflectometry.ImageProjection import ImageProjection +from opencsp.common.lib.deflectometry.Surface2DParabolic import Surface2DParabolic +from opencsp.common.lib.geometry.Vxy import Vxy +from opencsp.common.lib.geometry.Vxyz import Vxyz +import opencsp.common.lib.tool.log_tools as lt def example_sofast_command_line_tool(dir_cal: str, dir_save: str): # Set up OpenCSP logger - lt.logger(join(dir_save, "log.txt")) + lt.logger(join(dir_save, "log.txt"), lt.log.WARN) # Define image acquisition image_acquisition_in = ImageAcquisition(instance=0) # First camera instance found - # image_acquisition_in.frame_size = (1626, 1236) # Set frame size - # image_acquisition_in.gain = 230 # Set gain (higher=faster/more noise, lower=slower/less noise) + image_acquisition_in.frame_size = (1626, 1236) # Set frame size + image_acquisition_in.gain = 230 # Set gain (higher=faster/more noise, lower=slower/less noise) # Define image projection - file_image_projection = join(dir_cal, "image_projection_test_small.h5") + file_image_projection = join(dir_cal, "image_projection_optics_lab_landscape_square.h5") image_projection = ImageProjection.load_from_hdf(file_image_projection) image_projection.display_data.image_delay_ms = 200 # define projector-camera delay diff --git a/opencsp/app/sofast/lib/SofastInterface.py b/opencsp/app/sofast/lib/SofastInterface.py index 1550f8203..d19017e36 100644 --- a/opencsp/app/sofast/lib/SofastInterface.py +++ b/opencsp/app/sofast/lib/SofastInterface.py @@ -98,6 +98,11 @@ def __init__(self, image_acquisition: ImageAcquisitionAbstract) -> "SofastInterf self.data_sofast_fixed_process: SofastFixedProcessData = None self.paths = _Paths() + @property + def file_timestamp(self) -> str: + """Returns current run timestamp in string format""" + return self.timestamp.strftime(r"%Y-%m-%d_%H_%M_%S.%f") + def run_cli(self) -> None: """Runs command line Sofast""" self._func_user_input() @@ -181,9 +186,9 @@ def func_process_sofast_fringe_data(self): # fig_record.save(self.dir_save_fringe, f"{self.timestamp_fringe_measurement:s}_slope_magnitude_fringe", "png") # fig_record.close() - # # Save processed sofast data - # sofast.save_to_hdf(f"{self.dir_save_fringe:s}/{self.timestamp_fringe_measurement:s}_data_sofast_fringe.h5") - # lt.debug(f"{timestamp():s} Sofast Fringe data saved to HDF5") + # Save processed sofast data + sofast.save_to_hdf(f"{self.paths.dir_save_fringe:s}/{self.file_timestamp:s}_data_sofast_fringe.h5") + lt.debug(f"{timestamp():s} Sofast Fringe data saved to HDF5") # Continue self.system_fringe.run_next_in_queue() @@ -227,11 +232,9 @@ def func_process_sofast_fixed_data(self): # mirror.plot_orthorectified_slope(self.res_plot, clim=self.colorbar_limit, axis=fig_record.axis) # fig_record.save(self.dir_save_fixed, f"{self.timestamp_fixed_measurement:s}_slope_magnitude_fixed", "png") - # # Save processed sofast data - # process_sofast_fixed.save_to_hdf( - # f"{self.dir_save_fixed:s}/{self.timestamp_fixed_measurement:s}_data_sofast_fixed.h5" - # ) - # lt.debug(f"{timestamp():s} Sofast Fixed data saved to HDF5") + # Save processed sofast data + process_sofast_fixed.save_to_hdf(f"{self.paths.dir_save_fixed:s}/{self.file_timestamp:s}_data_sofast_fixed.h5") + lt.debug(f"{timestamp():s} Sofast Fixed data saved to HDF5") # Continue self.system_fixed.run_next_in_queue() @@ -243,8 +246,7 @@ def func_save_measurement_fringe(self): self.data_sofast_common_run.dist_optic_screen, self.data_sofast_common_run.name_optic, )[0] - file_timestamp = self.timestamp.strftime(r"%Y-%m-%d_%H_%M_%S.%f") - file = f"{self.paths.dir_save_fringe:s}/{file_timestamp:s}_measurement_fringe.h5" + file = f"{self.paths.dir_save_fringe:s}/{self.file_timestamp:s}_measurement_fringe.h5" measurement.save_to_hdf(file) self.system_fringe.calibration.save_to_hdf(file) self.system_fringe.run_next_in_queue() @@ -257,8 +259,7 @@ def func_save_measurement_fixed(self): self.data_sofast_fixed_run.origin, name=self.data_sofast_common_run.name_optic, ) - file_timestamp = self.timestamp.strftime(r"%Y-%m-%d_%H_%M_%S.%f") - measurement.save_to_hdf(f"{self.paths.dir_save_fixed:s}/{file_timestamp:s}_measurement_fixed.h5") + measurement.save_to_hdf(f"{self.paths.dir_save_fixed:s}/{self.file_timestamp:s}_measurement_fixed.h5") self.system_fixed.run_next_in_queue() def func_load_last_sofast_fringe_image_cal(self): From c10391e479718fabdd9703a5fa3c3761630e671c Mon Sep 17 00:00:00 2001 From: Smith Date: Thu, 13 Mar 2025 15:50:19 -0600 Subject: [PATCH 06/19] Added standard output plotting. --- .../sofast_fringe/sofast_command_line_tool.py | 10 +++++++ opencsp/app/sofast/lib/SofastInterface.py | 30 ++++++++----------- 2 files changed, 23 insertions(+), 17 deletions(-) diff --git a/example/sofast_fringe/sofast_command_line_tool.py b/example/sofast_fringe/sofast_command_line_tool.py index 93d4f5318..1c9f5c8ba 100644 --- a/example/sofast_fringe/sofast_command_line_tool.py +++ b/example/sofast_fringe/sofast_command_line_tool.py @@ -16,10 +16,12 @@ from opencsp.app.sofast.lib.SpatialOrientation import SpatialOrientation from opencsp.common.lib.camera.Camera import Camera from opencsp.common.lib.camera.ImageAcquisition_DCAM_mono import ImageAcquisition +from opencsp.common.lib.csp.MirrorParametric import MirrorParametric from opencsp.common.lib.deflectometry.ImageProjection import ImageProjection from opencsp.common.lib.deflectometry.Surface2DParabolic import Surface2DParabolic from opencsp.common.lib.geometry.Vxy import Vxy from opencsp.common.lib.geometry.Vxyz import Vxyz +from opencsp.common.lib.geometry.RegionXY import RegionXY import opencsp.common.lib.tool.log_tools as lt @@ -72,6 +74,14 @@ def example_sofast_command_line_tool(dir_cal: str, dir_save: str): fixed_pattern_dot_locs=DotLocationsFixedPattern.load_from_hdf(file_dot_locs), surface_2d=surface_fixed ) + # Set up plotting + shape = RegionXY.rectangle(1.5) + focal_length = 100 + inter.plotting.optic_reference = MirrorParametric.generate_symmetric_paraboloid(focal_length, shape) + inter.plotting.options_ray_trace_vis.to_plot = False + inter.plotting.options_file_output.number_in_name = False + inter.plotting.options_file_output.to_save = True + # Set up save paths inter.paths.dir_save_fixed = dir_save inter.paths.dir_save_fringe = dir_save diff --git a/opencsp/app/sofast/lib/SofastInterface.py b/opencsp/app/sofast/lib/SofastInterface.py index d19017e36..15765c20e 100644 --- a/opencsp/app/sofast/lib/SofastInterface.py +++ b/opencsp/app/sofast/lib/SofastInterface.py @@ -2,6 +2,7 @@ from os.path import join from dataclasses import dataclass import datetime as dt +import sys import matplotlib.pyplot as plt @@ -19,6 +20,7 @@ from opencsp.common.lib.camera.ImageAcquisitionAbstract import ImageAcquisitionAbstract from opencsp.common.lib.camera.image_processing import highlight_saturation from opencsp.common.lib.camera.LiveView import LiveView +from opencsp.common.lib.csp.StandardPlotOutput import StandardPlotOutput from opencsp.common.lib.deflectometry.ImageProjection import ImageProjection from opencsp.common.lib.deflectometry.Surface2DParabolic import Surface2DParabolic from opencsp.common.lib.geometry.Vxy import Vxy @@ -83,6 +85,7 @@ def __init__(self, image_acquisition: ImageAcquisitionAbstract) -> "SofastInterf # Common parameters self.image_acquisition = image_acquisition self.image_projection = ImageProjection.instance() + self.plotting: StandardPlotOutput = StandardPlotOutput() # Sofast system objects self.system_fixed: SystemSofastFixed = None @@ -177,14 +180,10 @@ def func_process_sofast_fringe_data(self): # Plot optic mirror = sofast.get_optic().mirror - - # lt.debug(f"{timestamp():s} Plotting Sofast Fringe data") - # figure_control = rcfg.RenderControlFigure(tile_array=(1, 1), tile_square=True) - # axis_control_m = rca.meters() - # fig_record = fm.setup_figure(figure_control, axis_control_m, title="") - # mirror.plot_orthorectified_slope(self.res_plot, clim=self.colorbar_limit, axis=fig_record.axis) - # fig_record.save(self.dir_save_fringe, f"{self.timestamp_fringe_measurement:s}_slope_magnitude_fringe", "png") - # fig_record.close() + lt.debug(f"{timestamp():s} Plotting Sofast Fringe data") + self.plotting.optic_measured = mirror + self.plotting.options_file_output.output_dir = self.paths.dir_save_fringe + self.plotting.plot() # Save processed sofast data sofast.save_to_hdf(f"{self.paths.dir_save_fringe:s}/{self.file_timestamp:s}_data_sofast_fringe.h5") @@ -224,13 +223,10 @@ def func_process_sofast_fixed_data(self): # Plot optic mirror = process_sofast_fixed.get_optic() - - # lt.debug(f"{timestamp():s} Plotting Sofast Fixed data") - # figure_control = rcfg.RenderControlFigure(tile_array=(1, 1), tile_square=True) - # axis_control_m = rca.meters() - # fig_record = fm.setup_figure(figure_control, axis_control_m, title="") - # mirror.plot_orthorectified_slope(self.res_plot, clim=self.colorbar_limit, axis=fig_record.axis) - # fig_record.save(self.dir_save_fixed, f"{self.timestamp_fixed_measurement:s}_slope_magnitude_fixed", "png") + lt.debug(f"{timestamp():s} Plotting Sofast Fixed data") + self.plotting.optic_measured = mirror + self.plotting.options_file_output.output_dir = self.paths.dir_save_fringe + self.plotting.plot() # Save processed sofast data process_sofast_fixed.save_to_hdf(f"{self.paths.dir_save_fixed:s}/{self.file_timestamp:s}_data_sofast_fixed.h5") @@ -334,7 +330,7 @@ def _func_user_input(self): # Get user input retval = input("> ") self.timestamp = dt.datetime.now() - lt.debug(f"{self.timestamp:s} user input: {retval:s}") + lt.debug(f"{timestamp():s} user input: {retval:s}") try: self._run_given_input(retval) @@ -438,7 +434,7 @@ def _run_given_input(self, retval: str) -> None: self.system_fringe.close_all() if self.system_fixed is not None: self.system_fixed.close_all() - return + sys.exit(0) # Show single camera image elif retval == "im": self.show_cam_image() From 77f0f9b6f2429616aabc845e1334a78eb2db19e2 Mon Sep 17 00:00:00 2001 From: Smith Date: Thu, 13 Mar 2025 15:55:00 -0600 Subject: [PATCH 07/19] Saves images in folder. --- opencsp/app/sofast/lib/SofastInterface.py | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/opencsp/app/sofast/lib/SofastInterface.py b/opencsp/app/sofast/lib/SofastInterface.py index 15765c20e..e749ac08c 100644 --- a/opencsp/app/sofast/lib/SofastInterface.py +++ b/opencsp/app/sofast/lib/SofastInterface.py @@ -1,5 +1,6 @@ import glob from os.path import join +import os from dataclasses import dataclass import datetime as dt import sys @@ -25,9 +26,6 @@ from opencsp.common.lib.deflectometry.Surface2DParabolic import Surface2DParabolic from opencsp.common.lib.geometry.Vxy import Vxy from opencsp.common.lib.geometry.Vxyz import Vxyz -import opencsp.common.lib.render.figure_management as fm -import opencsp.common.lib.render_control.RenderControlAxis as rca -import opencsp.common.lib.render_control.RenderControlFigure as rcfg import opencsp.common.lib.tool.log_tools as lt from opencsp.common.lib.tool.time_date_tools import current_date_time_string_forfile as timestamp @@ -104,7 +102,7 @@ def __init__(self, image_acquisition: ImageAcquisitionAbstract) -> "SofastInterf @property def file_timestamp(self) -> str: """Returns current run timestamp in string format""" - return self.timestamp.strftime(r"%Y-%m-%d_%H_%M_%S.%f") + return self.timestamp.strftime(r"%Y-%m-%d_%H_%M_%S_%f") def run_cli(self) -> None: """Runs command line Sofast""" @@ -178,11 +176,15 @@ def func_process_sofast_fringe_data(self): lt.info(f"{timestamp():s} Completed Sofast Fringe data processing") - # Plot optic + # Get optic mirror = sofast.get_optic().mirror + + # Plot optic lt.debug(f"{timestamp():s} Plotting Sofast Fringe data") + output_dir = join(self.paths.dir_save_fringe, self.file_timestamp) + os.makedirs(output_dir, exist_ok=True) self.plotting.optic_measured = mirror - self.plotting.options_file_output.output_dir = self.paths.dir_save_fringe + self.plotting.options_file_output.output_dir = output_dir self.plotting.plot() # Save processed sofast data @@ -221,11 +223,15 @@ def func_process_sofast_fixed_data(self): lt.info(f"{timestamp():s} Completed Sofast Fixed data processing") - # Plot optic + # Get optic mirror = process_sofast_fixed.get_optic() + + # Plot optic lt.debug(f"{timestamp():s} Plotting Sofast Fixed data") + output_dir = join(self.paths.dir_save_fringe, self.file_timestamp) + os.makedirs(output_dir, exist_ok=True) self.plotting.optic_measured = mirror - self.plotting.options_file_output.output_dir = self.paths.dir_save_fringe + self.plotting.options_file_output.output_dir = output_dir self.plotting.plot() # Save processed sofast data From 4b4d4a43ef12795bf099fc1033c97fc9abcf650f Mon Sep 17 00:00:00 2001 From: Braden Date: Thu, 13 Mar 2025 17:31:57 -0600 Subject: [PATCH 08/19] Added example to docs --- doc/source/example/sofast_fringe/config.rst | 8 +++ .../sofast_fringe/sofast_command_line_tool.py | 61 ++++++++++++++++++- 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/doc/source/example/sofast_fringe/config.rst b/doc/source/example/sofast_fringe/config.rst index bf779b642..242344c5f 100644 --- a/doc/source/example/sofast_fringe/config.rst +++ b/doc/source/example/sofast_fringe/config.rst @@ -46,3 +46,11 @@ Process SOFAST Temperature Experiment Data .. automodule:: example.sofast_fringe.sofast_temperature_analysis :members: :show-inheritance: +Running SOFAST with Command Line Tool +===================================== + +.. currentmodule:: example.sofast_fringe.sofast_command_line_tool + +.. automodule:: example.sofast_fringe.sofast_command_line_tool + :members: + :show-inheritance: diff --git a/example/sofast_fringe/sofast_command_line_tool.py b/example/sofast_fringe/sofast_command_line_tool.py index 1c9f5c8ba..a1f4d7009 100644 --- a/example/sofast_fringe/sofast_command_line_tool.py +++ b/example/sofast_fringe/sofast_command_line_tool.py @@ -1,3 +1,30 @@ +""" +Command-line tool for processing optical measurements using SOFAST. + +This module provides a command-line interface for processing optical measurements +using the SOFAST framework. It sets up the necessary components for image acquisition, +image projection, and SOFAST processing, allowing users to run measurements and +generate results based on the provided calibration and configuration files. + +NOTE: + + - To run this example, you will need a full physical SOFAST setup. This includes + a camera, display (LCD screen or projector), and a mirror to test. + - The calibration files required to run this example are not included in the + OpenCSP repository. You will need to generate your own for your own system. + +Usage: + +To run the command-line tool, provide the paths to the calibration directory and the +directory where results should be saved as command-line arguments. + +For example: + +``` +python sofast_command_line_tool.py path/to/calibration/files path/to/save/outputs +``` +""" + from os.path import join import sys @@ -25,7 +52,39 @@ import opencsp.common.lib.tool.log_tools as lt -def example_sofast_command_line_tool(dir_cal: str, dir_save: str): +def example_sofast_command_line_tool(dir_cal: str, dir_save: str) -> None: + """ + Processes optical measurements using SOFAST via command-line interface. + + This function performs the following steps: + + 1. Sets up logging for the processing session. + 2. Configures image acquisition settings for the camera. + 3. Loads image projection data from an HDF5 file. + 4. Initializes the SOFAST interface and fringe system. + 5. Loads necessary processing data, including facet definitions, camera data, + spatial orientation, display shape, and dot locations. + 6. Configures plotting options and save paths for output files. + 7. Executes the SOFAST processing routine. + + Parameters + ---------- + dir_cal : str + The directory path containing calibration files required for processing, + including image projection, facet definitions, camera data, and spatial + orientation data. + dir_save : str + The directory path where the output results and figures will be saved. + + Example + ------- + To run the SOFAST command-line tool, execute the script with the required + directories as arguments: + + >>> python script_name.py /path/to/calibration /path/to/save/results + + The results will be saved in the specified directory. + """ # Set up OpenCSP logger lt.logger(join(dir_save, "log.txt"), lt.log.WARN) From 99af16cca2726f274f874bacb241c27893a62e25 Mon Sep 17 00:00:00 2001 From: Braden Date: Fri, 14 Mar 2025 11:55:29 -0600 Subject: [PATCH 09/19] dded example sofast command line tool to test_DocString. --- opencsp/test/test_DocStringsExist.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/opencsp/test/test_DocStringsExist.py b/opencsp/test/test_DocStringsExist.py index b2b5ead7b..3cb5148c7 100644 --- a/opencsp/test/test_DocStringsExist.py +++ b/opencsp/test/test_DocStringsExist.py @@ -6,6 +6,7 @@ # Examples import example.sofast_fringe.sofast_temperature_analysis +import example.sofast_fringe.sofast_command_line_tool # TODO: why aren't these imported from import opencsp as opencsp above from opencsp.app.camera_calibration import CameraCalibration @@ -180,7 +181,7 @@ class test_Docstrings(unittest.TestCase): # TODO: example_sofast_calibration_list # TODO: example_sofast_fringe_list # TODO: example_targetcolor_list - example_list = [example.sofast_fringe.sofast_temperature_analysis] + example_list = [example.sofast_fringe.sofast_temperature_analysis, example.sofast_fringe.sofast_command_line_tool] app_class_list = ( camera_calibration_class_list From ff425605acd44d12a0bba750b0c4438ed04e9ff1 Mon Sep 17 00:00:00 2001 From: Braden Date: Fri, 14 Mar 2025 11:56:15 -0600 Subject: [PATCH 10/19] Added SofastInterface to test_DocString --- opencsp/test/test_DocStringsExist.py | 1 + 1 file changed, 1 insertion(+) diff --git a/opencsp/test/test_DocStringsExist.py b/opencsp/test/test_DocStringsExist.py index 3cb5148c7..b1073df3d 100644 --- a/opencsp/test/test_DocStringsExist.py +++ b/opencsp/test/test_DocStringsExist.py @@ -166,6 +166,7 @@ class test_Docstrings(unittest.TestCase): opencsp.app.sofast.lib.process_optics_geometry, opencsp.app.sofast.lib.sofast_common_functions, opencsp.app.sofast.lib.spatial_processing, + opencsp.app.sofast.lib.SofastInterface, ] target_class_list = [opencsp.app.target.target_color.lib.ImageColor] From 0b2e8bcee410b14304fa4248af8b0a5eacebe314 Mon Sep 17 00:00:00 2001 From: Braden Date: Fri, 14 Mar 2025 12:25:42 -0600 Subject: [PATCH 11/19] Added docstrings to sofastInterface --- opencsp/app/sofast/lib/SofastInterface.py | 103 +++++++++++++++++++--- 1 file changed, 92 insertions(+), 11 deletions(-) diff --git a/opencsp/app/sofast/lib/SofastInterface.py b/opencsp/app/sofast/lib/SofastInterface.py index e749ac08c..ef4fd16ef 100644 --- a/opencsp/app/sofast/lib/SofastInterface.py +++ b/opencsp/app/sofast/lib/SofastInterface.py @@ -1,3 +1,43 @@ +""" +Sofast Interface Module for Optical Measurement Processing. + +This module provides the `SofastInterface` class, which facilitates the +configuration and execution of optical measurements using the SOFAST framework. +It includes functionality for initializing measurement systems, processing +fringe and fixed measurements, and handling user interactions. The module +also supports saving and loading calibration data, displaying camera images, +and managing the overall workflow of optical measurements. + +Usage: + +To use this module, create an instance of the `SofastInterface` class +with an image acquisition object, and then call the appropriate methods +to run measurements and process data. See /example/ for more information. + +TODO: + +Refactor so that common code is separate from end-of-file input/execution block, move this to common. + +Make this a "kitchen sink" file, which includes all aspects: + + 1. Data collection: + + - Fringe measurement + - Fixed measurement with projector + - Fixed measurement with printed target in ambient lght + + 2. Data analysis -- finding the best-fit instance of the class of shapes. + + 3. Fitting to a desired reference optical shape. (Make this an enhancement issue added to SOFAST. Then, another file?) + + 4. Plotting/ray tracing + + 5. (Suggest puttting calibration in another file.) + + - This file contains 1 and 2. + +""" + import glob from os.path import join import os @@ -32,6 +72,8 @@ @dataclass class SofastFixedRunData: + """Data class holding data required to run Sofast Fixed""" + origin: Vxy """The xy pixel location in the camera image of the center of the xy_known dot""" xy_known: tuple[int, int] = (0, 0) @@ -44,28 +86,46 @@ class SofastFixedRunData: @dataclass class SofastCommonRunData: + """Data class holding data required to run Sofast Fixed and Fringe""" + measure_point_optic: Vxyz + """The measurement point in 3D space for the optical system.""" dist_optic_screen: float + """The distance from the optic to the screen, in meters.""" name_optic: str + """A descriptive name for the optical system.""" @dataclass class SofastCommonProcessData: + """Data class holding data common to processing captured Sofast Fixed or Fringe measurements""" + facet_definition: DefinitionFacet + """The definition of the optical facet being measured.""" camera: Camera + """The camera calibration parameters for the camera used during measurements.""" spatial_orientation: SpatialOrientation + """The spatial orientation of the measurement setup.""" @dataclass class SofastFringeProcessData: + """Data class holding data required to process captured Sofast Fringe measurements""" + display_shape: DisplayShape + """The display shape used in the fringe measurement.""" surface_2d: Surface2DParabolic + """The 2D surface model used for processing fringe data.""" @dataclass class SofastFixedProcessData: + """Data class holding data required to process captured Sofast Fixed measurements""" + fixed_pattern_dot_locs: DotLocationsFixedPattern + """The locations of fixed pattern dots used in measurements.""" surface_2d: Surface2DParabolic + """The 2D surface model used for processing fixed data.""" @dataclass @@ -79,6 +139,21 @@ class _Paths: class SofastInterface: + """ + Interface for managing SOFAST optical measurement systems. + + The `SofastInterface` class provides methods to initialize and run + measurements using the SOFAST framework. It manages the configuration + of fringe and fixed measurement systems, processes measurement data, + and handles user interactions. The class also supports saving and + loading calibration data and displaying camera images. + + Parameters + ---------- + image_acquisition : ImageAcquisitionAbstract + Object responsible for acquiring images from the camera. + """ + def __init__(self, image_acquisition: ImageAcquisitionAbstract) -> "SofastInterface": # Common parameters self.image_acquisition = image_acquisition @@ -109,7 +184,13 @@ def run_cli(self) -> None: self._func_user_input() def initialize_sofast_fringe(self, fringes: Fringes) -> None: - """Initializes sofast fringe system""" + """Initializes sofast fringe system + + Parameters + ---------- + fringes : Fringes + Input fringe object to initialize Sofast Fringe system + """ self.system_fringe = SystemSofastFringe(self.image_acquisition) self.system_fringe.set_fringes(fringes) @@ -142,12 +223,12 @@ def _f1(): self.system_fixed.prepend_to_queue([self.system_fixed.run_measurement, _f1]) self.system_fixed.run_next_in_queue() - def func_show_crosshairs_fringe(self): + def func_show_crosshairs_fringe(self) -> None: """Shows crosshairs and run next in Sofast fringe queue after a 0.2s wait""" self.image_projection.show_crosshairs() self.system_fringe.root.after(200, self.system_fringe.run_next_in_queue) - def func_process_sofast_fringe_data(self): + def func_process_sofast_fringe_data(self) -> None: """Processes Sofast Fringe data""" lt.info(f"{timestamp():s} Starting Sofast Fringe data processing") @@ -194,7 +275,7 @@ def func_process_sofast_fringe_data(self): # Continue self.system_fringe.run_next_in_queue() - def func_process_sofast_fixed_data(self): + def func_process_sofast_fixed_data(self) -> None: """Process Sofast Fixed data""" lt.info(f"{timestamp():s} Starting Sofast Fixed data processing") # Instantiate sofast processing object @@ -241,7 +322,7 @@ def func_process_sofast_fixed_data(self): # Continue self.system_fixed.run_next_in_queue() - def func_save_measurement_fringe(self): + def func_save_measurement_fringe(self) -> None: """Saves measurement to HDF file""" measurement = self.system_fringe.get_measurements( self.data_sofast_common_run.measure_point_optic, @@ -253,7 +334,7 @@ def func_save_measurement_fringe(self): self.system_fringe.calibration.save_to_hdf(file) self.system_fringe.run_next_in_queue() - def func_save_measurement_fixed(self): + def func_save_measurement_fixed(self) -> None: """Save fixed measurement files""" measurement = self.system_fixed.get_measurement( self.data_sofast_common_run.measure_point_optic, @@ -264,7 +345,7 @@ def func_save_measurement_fixed(self): measurement.save_to_hdf(f"{self.paths.dir_save_fixed:s}/{self.file_timestamp:s}_measurement_fixed.h5") self.system_fixed.run_next_in_queue() - def func_load_last_sofast_fringe_image_cal(self): + def func_load_last_sofast_fringe_image_cal(self) -> None: """Loads last ImageCalibration object""" # Find file files = glob.glob(join(self.paths.dir_save_fringe_calibration, "image_calibration_scaling*.h5")) @@ -280,7 +361,7 @@ def func_load_last_sofast_fringe_image_cal(self): self.system_fringe.set_calibration(image_calibration) lt.info(f"{timestamp()} Loaded image calibration file: {file}") - def func_gray_levels_cal(self): + def func_gray_levels_cal(self) -> None: """Runs gray level calibration sequence""" file = join(self.paths.dir_save_fringe_calibration, f"image_calibration_scaling_{timestamp():s}.h5") self.system_fringe.run_gray_levels_cal( @@ -290,14 +371,14 @@ def func_gray_levels_cal(self): on_processing=self.func_show_crosshairs_fringe, ) - def show_cam_image(self): + def show_cam_image(self) -> None: """Shows a camera image""" image = self.image_acquisition.get_frame() image_proc = highlight_saturation(image, self.image_acquisition.max_value) plt.imshow(image_proc) plt.show() - def show_live_view(self): + def show_live_view(self) -> None: """Shows live view window""" LiveView(self.image_acquisition) @@ -331,7 +412,7 @@ def _check_fixed_system_loaded(self) -> bool: return False return True - def _func_user_input(self): + def _func_user_input(self) -> None: """Function that requests and processes user input""" # Get user input retval = input("> ") From 271793ad46bddd22a29b782a304240e5ea0db9c4 Mon Sep 17 00:00:00 2001 From: Braden Date: Fri, 14 Mar 2025 12:25:56 -0600 Subject: [PATCH 12/19] Remocws Sofast CLI from contrib/ --- .../app/sofast/SofastCommandLineInterface.py | 583 ------------------ 1 file changed, 583 deletions(-) delete mode 100644 contrib/app/sofast/SofastCommandLineInterface.py diff --git a/contrib/app/sofast/SofastCommandLineInterface.py b/contrib/app/sofast/SofastCommandLineInterface.py deleted file mode 100644 index a3300eea1..000000000 --- a/contrib/app/sofast/SofastCommandLineInterface.py +++ /dev/null @@ -1,583 +0,0 @@ -"""A script that runs SOFAST in a command-line manner. We recommend copying this file into -your working directory and modifying it there. To run SOFAST, perform the following steps: - -1. Navigate to the bottom of this file and fill in all user-input data specific to your SOFAST run. -2. Type "help" to display help message -3. Run SOFAST. Collect only measurement data, or (optionally) process data. - -NOTE: To update any of the parameters in the bottom of the file, the CLI must be -restarted for changes to take effect. - -TODO: -Refactor so that common code is separate from end-of-file input/execution block, move this to common. - -Make this a "kitchen sink" file, which includes all aspects: -1. Data collection: - - Fringe measurement - - Fixed measurement with projector - - Fixed measurement with printed target in ambient lght -2. Data analysis -- finding the best-fit instance of the class of shapes. - -3. Fitting to a desired reference optical shape. (Make this an enhancement issue added to SOFAST. Then, another file?) - -4. Plotting/ray tracing - -(Suggest puttting calibration in another file.) - -This file contains 1 and 2. - -In output logs, include user input. -""" - -import glob -from os.path import join, dirname, abspath - -import matplotlib.pyplot as plt - -from opencsp.app.sofast.lib.DefinitionFacet import DefinitionFacet -from opencsp.app.sofast.lib.DisplayShape import DisplayShape -from opencsp.app.sofast.lib.DotLocationsFixedPattern import DotLocationsFixedPattern -from opencsp.app.sofast.lib.Fringes import Fringes -from opencsp.app.sofast.lib.ImageCalibrationScaling import ImageCalibrationScaling -from opencsp.app.sofast.lib.ProcessSofastFixed import ProcessSofastFixed -from opencsp.app.sofast.lib.ProcessSofastFringe import ProcessSofastFringe -from opencsp.app.sofast.lib.SpatialOrientation import SpatialOrientation -from opencsp.app.sofast.lib.SystemSofastFringe import SystemSofastFringe -from opencsp.app.sofast.lib.SystemSofastFixed import SystemSofastFixed -from opencsp.common.lib.camera.Camera import Camera -from opencsp.common.lib.camera.ImageAcquisition_DCAM_mono import ImageAcquisition -from opencsp.common.lib.camera.image_processing import highlight_saturation -from opencsp.common.lib.camera.LiveView import LiveView -from opencsp.common.lib.deflectometry.ImageProjection import ImageProjection -from opencsp.common.lib.deflectometry.Surface2DParabolic import Surface2DParabolic -from opencsp.common.lib.geometry.Vxy import Vxy -from opencsp.common.lib.geometry.Vxyz import Vxyz -import opencsp.common.lib.render.figure_management as fm -import opencsp.common.lib.render_control.RenderControlAxis as rca -import opencsp.common.lib.render_control.RenderControlFigure as rcfg -import opencsp.common.lib.tool.log_tools as lt -from opencsp.common.lib.tool.time_date_tools import current_date_time_string_forfile as timestamp - - -class SofastCommandLineInterface: - """Sofast Command Line Interface class.""" - - def __init__(self) -> "SofastCommandLineInterface": - # Common sofast parameters - self.image_acquisition: ImageAcquisition = None - self.camera: Camera = None - self.facet_definition: DefinitionFacet = None - self.spatial_orientation: SpatialOrientation = None - self.measure_point_optic: Vxyz = None - self.dist_optic_screen: float = None - self.name_optic: str = None - - self.image_projection = ImageProjection.instance() - self.res_plot = 0.002 # meters - """Resolution of slope map image (meters)""" - self.colorbar_limit = 7 # mrad - """Colorbar limits in slope magnitude plot (mrad)""" - - # Sofast fringe specific - self.system_fringe: SystemSofastFringe = None - self.display_shape: DisplayShape = None - self.surface_fringe: Surface2DParabolic = None - self.timestamp_fringe_measurement = None - - # Sofast fixed specific - self.system_fixed: SystemSofastFixed = None - self.process_sofast_fixed: ProcessSofastFixed = None - self.fixed_pattern_dot_locs: DotLocationsFixedPattern = None - self.surface_fixed: Surface2DParabolic = None - self.origin: Vxy = None - self.timestamp_fixed_measurement = None - self.pattern_width = 3 - """Fixed pattern dot width, pixels""" - self.pattern_spacing = 6 - """Fixed pattern dot spacing, pixels""" - - # Save directories - self.dir_save_fringe: str = "" - """Location to save Sofast Fringe measurement data""" - self.dir_save_fixed: str = "" - """Location to save Sofast Fixed measurement data""" - self.dir_save_fringe_calibration: str = "" - """Location to save Sofast Fringe calibration data""" - - def run(self) -> None: - """Runs command line Sofast""" - self.func_user_input() - - def set_common_data( - self, - image_acquisition: ImageAcquisition, - image_projection: ImageProjection, - camera: Camera, - facet_definition: DefinitionFacet, - spatial_orientation: SpatialOrientation, - measure_point_optic: Vxyz, - dist_optic_screen: float, - name_optic: str, - ) -> None: - """Sets common parametes for Sofast Fringe and Fixed - - Parameters - ---------- - image_acquisition : ImageAcquisition - ImageAcquisition object - image_projection : ImageProjection - Image projection object - camera : Camera - Camera calibration object - facet_definition : DefinitionFacet - Facet definition object - spatial_orientation : SpatialOrientation - Calibrated SpatialOrientation object - measure_point_optic : Vxyz - Measure point location on optic - dist_optic_screen : float - Distance from measure point to screen center - name_optic : str - Name of optic - """ - self.image_acquisition = image_acquisition - self.image_projection = image_projection - self.camera = camera - self.facet_definition = facet_definition - self.spatial_orientation = spatial_orientation - self.measure_point_optic = measure_point_optic - self.dist_optic_screen = dist_optic_screen - self.name_optic = name_optic - - def set_sofast_fringe_data( - self, display_shape: DisplayShape, fringes: Fringes, surface_fringe: Surface2DParabolic - ) -> None: - """Loads Sofast Fringe specific objects - - Parameters - ---------- - display_shape : DisplayShape - Calibrated DisplayShape object - fringes : Fringes - Fringe objects to display - surface_fringe : Surface2DParabolic - Surface to use when processing Sofast Fringe data - """ - self.system_fringe = SystemSofastFringe(self.image_acquisition) - self.system_fringe.set_fringes(fringes) - self.display_shape = display_shape - self.surface_fringe = surface_fringe - - def set_sofast_fixed_data( - self, fixed_pattern_dot_locs: DotLocationsFixedPattern, origin: Vxy, surface_fixed: Surface2DParabolic - ) -> None: - """Loads Sofast Fixed specific objects - - Parameters - ---------- - fixed_pattern_dot_locs : DotLocationsFixedPattern - Calibrated dot locations object - origin : Vxy - Origin dot location in image, pixels - surface_fixed : Surface2DParabolic - Surface to use when processing Sofast Fringe data - """ - self.system_fixed = SystemSofastFixed(self.image_acquisition) - self.system_fixed.set_pattern_parameters(self.pattern_width, self.pattern_spacing) - self.fixed_pattern_dot_locs = fixed_pattern_dot_locs - self.origin = origin - self.surface_fixed = surface_fixed - - self.process_sofast_fixed = ProcessSofastFixed(self.spatial_orientation, self.camera, fixed_pattern_dot_locs) - - def func_run_fringe_measurement(self) -> None: - """Runs sofast fringe measurement""" - lt.info(f"{timestamp():s} Starting Sofast Fringe measurement") - self.timestamp_fringe_measurement = timestamp() - - def _on_done(): - lt.info(f"{timestamp():s} Completed Sofast Fringe measurement") - self.system_fringe.run_next_in_queue() - - self.system_fringe.run_measurement(_on_done) - - def func_run_fixed_measurement(self) -> None: - """Runs Sofast Fixed measurement""" - lt.info(f"{timestamp():s} Starting Sofast Fixed measurement") - self.timestamp_fixed_measurement = timestamp() - - def _f1(): - lt.info(f"{timestamp():s} Completed Sofast Fixed measurement") - self.system_fixed.run_next_in_queue() - - self.system_fixed.prepend_to_queue([self.system_fixed.run_measurement, _f1]) - self.system_fixed.run_next_in_queue() - - def func_show_crosshairs_fringe(self): - """Shows crosshairs and run next in Sofast fringe queue after a 0.2s wait""" - self.image_projection.show_crosshairs() - self.system_fringe.root.after(200, self.system_fringe.run_next_in_queue) - - def func_process_sofast_fringe_data(self): - """Processes Sofast Fringe data""" - lt.info(f"{timestamp():s} Starting Sofast Fringe data processing") - - # Get Measurement object - measurement = self.system_fringe.get_measurements( - self.measure_point_optic, self.dist_optic_screen, self.name_optic - )[0] - - # Calibrate fringe images - measurement.calibrate_fringe_images(self.system_fringe.calibration) - - # Instantiate ProcessSofastFringe - sofast = ProcessSofastFringe(measurement, self.spatial_orientation, self.camera, self.display_shape) - - # Process - sofast.process_optic_singlefacet(self.facet_definition, self.surface_fringe) - - lt.info(f"{timestamp():s} Completed Sofast Fringe data processing") - - # Plot optic - mirror = sofast.get_optic().mirror - - lt.debug(f"{timestamp():s} Plotting Sofast Fringe data") - figure_control = rcfg.RenderControlFigure(tile_array=(1, 1), tile_square=True) - axis_control_m = rca.meters() - fig_record = fm.setup_figure(figure_control, axis_control_m, title="") - mirror.plot_orthorectified_slope(self.res_plot, clim=self.colorbar_limit, axis=fig_record.axis) - fig_record.save(self.dir_save_fringe, f"{self.timestamp_fringe_measurement:s}_slope_magnitude_fringe", "png") - fig_record.close() - - # Save processed sofast data - sofast.save_to_hdf(f"{self.dir_save_fringe:s}/{self.timestamp_fringe_measurement:s}_data_sofast_fringe.h5") - lt.debug(f"{timestamp():s} Sofast Fringe data saved to HDF5") - - # Continue - self.system_fringe.run_next_in_queue() - - def func_process_sofast_fixed_data(self): - """Process Sofast Fixed data""" - lt.info(f"{timestamp():s} Starting Sofast Fixed data processing") - # Get Measurement object - measurement = self.system_fixed.get_measurement( - self.measure_point_optic, self.dist_optic_screen, self.origin, name=self.name_optic - ) - self.process_sofast_fixed.load_measurement_data(measurement) - - # Process - xy_known = (0, 0) - self.process_sofast_fixed.process_single_facet_optic( - self.facet_definition, self.surface_fixed, self.origin, xy_known=xy_known - ) - - lt.info(f"{timestamp():s} Completed Sofast Fixed data processing") - - # Plot optic - mirror = self.process_sofast_fixed.get_optic() - - lt.debug(f"{timestamp():s} Plotting Sofast Fixed data") - figure_control = rcfg.RenderControlFigure(tile_array=(1, 1), tile_square=True) - axis_control_m = rca.meters() - fig_record = fm.setup_figure(figure_control, axis_control_m, title="") - mirror.plot_orthorectified_slope(self.res_plot, clim=self.colorbar_limit, axis=fig_record.axis) - fig_record.save(self.dir_save_fixed, f"{self.timestamp_fixed_measurement:s}_slope_magnitude_fixed", "png") - - # Save processed sofast data - self.process_sofast_fixed.save_to_hdf( - f"{self.dir_save_fixed:s}/{self.timestamp_fixed_measurement:s}_data_sofast_fixed.h5" - ) - lt.debug(f"{timestamp():s} Sofast Fixed data saved to HDF5") - - # Continue - self.system_fixed.run_next_in_queue() - - def func_save_measurement_fringe(self): - """Saves measurement to HDF file""" - measurement = self.system_fringe.get_measurements( - self.measure_point_optic, self.dist_optic_screen, self.name_optic - )[0] - file = f"{self.dir_save_fringe:s}/{self.timestamp_fringe_measurement:s}_measurement_fringe.h5" - measurement.save_to_hdf(file) - self.system_fringe.calibration.save_to_hdf(file) - self.system_fringe.run_next_in_queue() - - def func_save_measurement_fixed(self): - """Save fixed measurement files""" - measurement = self.system_fixed.get_measurement( - self.measure_point_optic, self.dist_optic_screen, self.origin, name=self.name_optic - ) - measurement.save_to_hdf(f"{self.dir_save_fixed:s}/{self.timestamp_fixed_measurement:s}_measurement_fixed.h5") - self.system_fixed.run_next_in_queue() - - def func_load_last_sofast_fringe_image_cal(self): - """Loads last ImageCalibration object""" - # Find file - files = glob.glob(join(self.dir_save_fringe_calibration, "image_calibration_scaling*.h5")) - files.sort() - - if len(files) == 0: - lt.error(f"No previous calibration files found in {self.dir_save_fringe_calibration}") - return - - # Get latest file and set - file = files[-1] - image_calibration = ImageCalibrationScaling.load_from_hdf(file) - self.system_fringe.set_calibration(image_calibration) - lt.info(f"{timestamp()} Loaded image calibration file: {file}") - - def func_gray_levels_cal(self): - """Runs gray level calibration sequence""" - file = join(self.dir_save_fringe_calibration, f"image_calibration_scaling_{timestamp():s}.h5") - self.system_fringe.run_gray_levels_cal( - ImageCalibrationScaling, - file, - on_processed=self.func_user_input, - on_processing=self.func_show_crosshairs_fringe, - ) - - def show_cam_image(self): - """Shows a camera image""" - image = self.image_acquisition.get_frame() - image_proc = highlight_saturation(image, self.image_acquisition.max_value) - plt.imshow(image_proc) - plt.show() - - def show_live_view(self): - """Shows live vieew window""" - LiveView(self.image_acquisition) - - def func_user_input(self): - """Waits for user input""" - retval = input("Input: ") - - lt.debug(f"{timestamp():s} user input: {retval:s}") - - try: - self._run_given_input(retval) - except Exception as error: - lt.error(repr(error)) - self.func_user_input() - - def _check_fringe_system_loaded(self) -> bool: - if self.system_fringe is None: - lt.error(f"{timestamp()} No Sofast Fringe system loaded") - return False - return True - - def _check_fixed_system_loaded(self) -> bool: - if self.system_fixed is None: - lt.error(f"{timestamp()} No Sofast Fixed system loaded") - return False - return True - - def _run_given_input(self, retval: str) -> None: - """Runs the given command""" - # Run fringe measurement and process/save - if retval == "help": - print("\n") - print("Value Command") - print("------------------") - print("mrp run Sofast Fringe measurement and process/save") - print("mrs run Sofast Fringe measurement and save only") - print("mip run Sofast Fixed measurement and process/save") - print("mis run Sofast Fixed measurement and save only") - print("ce calibrate camera exposure") - print("cr calibrate camera-projector response") - print("lr load most recent camera-projector response calibration file") - print("q quit and close all") - print("im show image from camera.") - print("lv shows camera live view") - print("cross show crosshairs") - self.func_user_input() - elif retval == "mrp": - lt.info(f"{timestamp()} Running Sofast Fringe measurement and processing/saving data") - if self._check_fringe_system_loaded(): - funcs = [ - self.func_run_fringe_measurement, - self.func_show_crosshairs_fringe, - self.func_process_sofast_fringe_data, - self.func_save_measurement_fringe, - self.func_user_input, - ] - self.system_fringe.set_queue(funcs) - self.system_fringe.run() - else: - self.func_user_input() - # Run fringe measurement and save - elif retval == "mrs": - lt.info(f"{timestamp()} Running Sofast Fringe measurement and saving data") - if self._check_fringe_system_loaded(): - funcs = [ - self.func_run_fringe_measurement, - self.func_show_crosshairs_fringe, - self.func_save_measurement_fringe, - self.func_user_input, - ] - self.system_fringe.set_queue(funcs) - self.system_fringe.run() - else: - self.func_user_input() - # Run fixed measurement and process/save - elif retval == "mip": - lt.info(f"{timestamp()} Running Sofast Fixed measurement and processing/saving data") - if self._check_fixed_system_loaded(): - funcs = [ - self.func_run_fixed_measurement, - self.func_process_sofast_fixed_data, - self.func_save_measurement_fixed, - self.func_user_input, - ] - self.system_fixed.set_queue(funcs) - self.system_fixed.run() - else: - self.func_user_input() - # Run fixed measurement and save - elif retval == "mis": - lt.info(f"{timestamp()} Running Sofast Fixed measurement and saving data") - if self._check_fixed_system_loaded(): - funcs = [self.func_run_fixed_measurement, self.func_save_measurement_fixed, self.func_user_input] - self.system_fixed.set_queue(funcs) - self.system_fixed.run() - else: - self.func_user_input() - # Calibrate exposure time - elif retval == "ce": - lt.info(f"{timestamp()} Calibrating camera exposure") - self.image_acquisition.calibrate_exposure() - self.func_user_input() - # Calibrate response - elif retval == "cr": - lt.info(f"{timestamp()} Calibrating camera-projector response") - if self._check_fringe_system_loaded(): - funcs = [self.func_gray_levels_cal] - self.system_fringe.set_queue(funcs) - self.system_fringe.run() - else: - self.func_user_input() - # Load last fringe calibration file - elif retval == "lr": - lt.info(f"{timestamp()} Loading response calibration") - if self._check_fringe_system_loaded(): - self.func_load_last_sofast_fringe_image_cal() - self.func_user_input() - # Quit - elif retval == "q": - lt.info(f"{timestamp():s} quitting") - if self.system_fringe is not None: - self.system_fringe.close_all() - if self.system_fixed is not None: - self.system_fixed.close_all() - return - # Show single camera image - elif retval == "im": - self.show_cam_image() - self.func_user_input() - # Show camera live view - elif retval == "lv": - self.show_live_view() - self.func_user_input() - # Project crosshairs - elif retval == "cross": - self.image_projection.show_crosshairs() - self.func_user_input() - else: - lt.error(f"{timestamp()} Command, {retval}, not recognized") - self.func_user_input() - - -# Start program -if __name__ == "__main__": - # Define main directory in which to save captured/processed data - # ============================================================== - - # Define upper level save direcory - dir_save = abspath(join(dirname(__file__), "../../../../sofast_cli")) - - # Define logger directory and set up logger - dir_log = join(dir_save, "logs") - lt.logger(join(dir_log, f"log_{timestamp():s}.txt"), lt.log.INFO) - - # Define the file locations of all SOFAST calibration data - # ======================================================== - - # Define directory containing Sofast calibration files - dir_cal = abspath(join(dirname(__file__), "../../../../sofast_calibration_files")) - - # Define data files - file_facet_definition_json = join(dir_cal, "facet_NSTTF.json") - file_spatial_orientation = join(dir_cal, "spatial_orientation_optics_lab_landscape.h5") - file_display = join(dir_cal, "display_shape_optics_lab_landscape_square_distorted_3d_100x100.h5") - file_camera = join(dir_cal, "camera_sofast_optics_lab_landscape.h5") - file_image_projection = join(dir_cal, "image_projection_optics_lab_landscape_square.h5") - file_dot_locs = join(dir_cal, "dot_locations_optics_lab_landscape_square_width3_space6.h5") - - # Instantiate Sofast Command Line Interface - # ========================================= - sofast_cli = SofastCommandLineInterface() - - # Define specific sofast save directories - # ======================================= - sofast_cli.dir_save_fringe = join(dir_save, "sofast_fringe") - sofast_cli.dir_save_fringe_calibration = join(sofast_cli.dir_save_fringe, "calibration") - sofast_cli.dir_save_fixed = join(dir_save, "sofast_fixed") - - # Define camera (ImageAcquisition) parameters - # =========================================== - image_acquisition_in = ImageAcquisition(instance=0) # First camera instance found - image_acquisition_in.frame_size = (1626, 1236) # Set frame size - image_acquisition_in.gain = 230 # Set gain (higher=faster/more noise, lower=slower/less noise) - - # Define projector/display (ImageProjection) parameters - # ===================================================== - image_projection_in = ImageProjection.load_from_hdf(file_image_projection) - image_projection_in.display_data.image_delay_ms = 200 # define projector-camera delay - - # Define measurement-specific inputs - # ================================== - - # NOTE: to update any of these fields, change them here and restart the SOFAST CLI - measure_point_optic_in = Vxyz((0, 0, 0)) # Measure point on optic, meters - dist_optic_screen_in = 10.158 # Measured optic-screen distance, meters - name_optic_in = "Test optic" # Optic name - - # Load all other calibration files - # ================================ - camera_in = Camera.load_from_hdf(file_camera) # SOFAST camera definition - facet_definition_in = DefinitionFacet.load_from_json(file_facet_definition_json) # Facet definition - spatial_orientation_in = SpatialOrientation.load_from_hdf(file_spatial_orientation) # Spatial orientation - - sofast_cli.set_common_data( - image_acquisition_in, - image_projection_in, - camera_in, - facet_definition_in, - spatial_orientation_in, - measure_point_optic_in, - dist_optic_screen_in, - name_optic_in, - ) - - sofast_cli.colorbar_limit = 2 # Update plotting colorbar limit, mrad - - # Set Sofast Fringe parameters - # ============================ - display_shape_in = DisplayShape.load_from_hdf(file_display) - fringes_in = Fringes.from_num_periods(4, 4) - surface_fringe_in = Surface2DParabolic((100.0, 100.0), False, 10) - - sofast_cli.set_sofast_fringe_data(display_shape_in, fringes_in, surface_fringe_in) - - # Set Sofast Fixed parameters - # =========================== - # NOTE: to get the value of "origin_in," the user must first start the CLI, bring up the - # camera live view, then manually find the location of the (0, 0) fixed pattern dot. - fixed_pattern_dot_locs_in = DotLocationsFixedPattern.load_from_hdf(file_dot_locs) - origin_in = Vxy((1100, 560)) # pixels, location of (0, 0) dot in camera image - surface_fixed_in = Surface2DParabolic((100.0, 100.0), False, 1) - - sofast_cli.set_sofast_fixed_data(fixed_pattern_dot_locs_in, origin_in, surface_fixed_in) - - # Run - # === - sofast_cli.run() From 9ef5643c11f7efbe9624526ee54ace1bcbe25e0b Mon Sep 17 00:00:00 2001 From: Braden Date: Fri, 14 Mar 2025 12:28:10 -0600 Subject: [PATCH 13/19] Added SofastInterface to Docs. --- doc/source/library_reference/app/sofast/config.rst | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/doc/source/library_reference/app/sofast/config.rst b/doc/source/library_reference/app/sofast/config.rst index 0ba3fb3c9..f278c8d2b 100644 --- a/doc/source/library_reference/app/sofast/config.rst +++ b/doc/source/library_reference/app/sofast/config.rst @@ -78,6 +78,16 @@ opencsp.app.sofast.lib.ParamsSofastFixed :undoc-members: :show-inheritance: +opencsp.app.sofast.lib.SofastInterface +====================================== + +.. currentmodule:: opencsp.app.sofast.lib.SofastInterface + +.. automodule:: opencsp.app.sofast.lib.SofastInterface + :members: + :undoc-members: + :show-inheritance: + opencsp.app.sofast.lib.SystemSofastFringe ========================================= From 6bd9874fa8f14b620219a22621cb71b6aa475b7f Mon Sep 17 00:00:00 2001 From: Braden Date: Fri, 14 Mar 2025 12:48:39 -0600 Subject: [PATCH 14/19] Added docstring to __init__ in SofastInterface. --- opencsp/app/sofast/lib/SofastInterface.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/opencsp/app/sofast/lib/SofastInterface.py b/opencsp/app/sofast/lib/SofastInterface.py index ef4fd16ef..5a714fe9a 100644 --- a/opencsp/app/sofast/lib/SofastInterface.py +++ b/opencsp/app/sofast/lib/SofastInterface.py @@ -155,6 +155,17 @@ class SofastInterface: """ def __init__(self, image_acquisition: ImageAcquisitionAbstract) -> "SofastInterface": + """Instantiates SofastInterface + + Parameters + ---------- + image_acquisition : ImageAcquisitionAbstract + Image acquisition object connected to camera. + + Returns + ------- + SofastInterface + """ # Common parameters self.image_acquisition = image_acquisition self.image_projection = ImageProjection.instance() From 6ce4331a2c483c26aa179ce5cc3a85531f48f2fa Mon Sep 17 00:00:00 2001 From: Braden Date: Fri, 14 Mar 2025 13:07:03 -0600 Subject: [PATCH 15/19] Added documentation to other classes so that SofastInterface is fully documented. --- opencsp/app/sofast/lib/Fringes.py | 6 ++++++ opencsp/app/sofast/lib/ImageCalibrationScaling.py | 3 +++ opencsp/app/sofast/lib/SofastInterface.py | 2 -- opencsp/common/lib/camera/LiveView.py | 3 +++ 4 files changed, 12 insertions(+), 2 deletions(-) diff --git a/opencsp/app/sofast/lib/Fringes.py b/opencsp/app/sofast/lib/Fringes.py index 35802fa80..8de681bb2 100644 --- a/opencsp/app/sofast/lib/Fringes.py +++ b/opencsp/app/sofast/lib/Fringes.py @@ -1,7 +1,13 @@ +"""Representation sinusoidal pattern (Fringe) used in a Sofast measurement.""" + import numpy as np class Fringes: + """Class that handles calculating the sinusoidal fringes used in a SOFAST + calculation. A fringe is an image whos intensity varies in either x or y + according to a sinusoid.""" + def __init__(self, periods_x: list, periods_y: list): """ Representation of projected fringe images. diff --git a/opencsp/app/sofast/lib/ImageCalibrationScaling.py b/opencsp/app/sofast/lib/ImageCalibrationScaling.py index a85ba2a02..cf3ba10f7 100644 --- a/opencsp/app/sofast/lib/ImageCalibrationScaling.py +++ b/opencsp/app/sofast/lib/ImageCalibrationScaling.py @@ -6,6 +6,9 @@ class ImageCalibrationScaling(ImageCalibrationAbstract): + """Class that handles performing a pixel-wise calibration that 'scales' each pixel + in a Sofast image according to a camera-projector-response calibration curve.""" + @staticmethod def get_calibration_name() -> str: """The name of this calibration class type""" diff --git a/opencsp/app/sofast/lib/SofastInterface.py b/opencsp/app/sofast/lib/SofastInterface.py index 5a714fe9a..5a7637b41 100644 --- a/opencsp/app/sofast/lib/SofastInterface.py +++ b/opencsp/app/sofast/lib/SofastInterface.py @@ -424,7 +424,6 @@ def _check_fixed_system_loaded(self) -> bool: return True def _func_user_input(self) -> None: - """Function that requests and processes user input""" # Get user input retval = input("> ") self.timestamp = dt.datetime.now() @@ -436,7 +435,6 @@ def _func_user_input(self) -> None: lt.error(repr(error)) def _run_given_input(self, retval: str) -> None: - """Runs the given command""" # Run fringe measurement and process/save if retval == "help": print("\n") diff --git a/opencsp/common/lib/camera/LiveView.py b/opencsp/common/lib/camera/LiveView.py index 99da452d0..4132fae60 100644 --- a/opencsp/common/lib/camera/LiveView.py +++ b/opencsp/common/lib/camera/LiveView.py @@ -10,6 +10,9 @@ class LiveView(aph.AbstractPlotHandler): + """Class used to view a live-stream from a connected camera using tkinter and ImageAcquisition + interfaces.""" + def __init__( self, image_acquisition: ImageAcquisitionAbstract = None, update_ms: int = 20, highlight_saturation: bool = True ): From 3dc2325c8bf0d113e9a5da18879da131809438e5 Mon Sep 17 00:00:00 2001 From: Evan Harvey Date: Wed, 16 Apr 2025 07:45:42 -0600 Subject: [PATCH 16/19] fix docs --- doc/source/example/sofast_fringe/config.rst | 2 ++ 1 file changed, 2 insertions(+) diff --git a/doc/source/example/sofast_fringe/config.rst b/doc/source/example/sofast_fringe/config.rst index 242344c5f..3b91ec693 100644 --- a/doc/source/example/sofast_fringe/config.rst +++ b/doc/source/example/sofast_fringe/config.rst @@ -46,6 +46,8 @@ Process SOFAST Temperature Experiment Data .. automodule:: example.sofast_fringe.sofast_temperature_analysis :members: :show-inheritance: + + Running SOFAST with Command Line Tool ===================================== From 6c166001eced224eedc55073e7c599f9c4a98a2b Mon Sep 17 00:00:00 2001 From: Evan Harvey Date: Thu, 17 Apr 2025 12:23:37 -0600 Subject: [PATCH 17/19] Fix ci? --- opencsp/app/sofast/lib/SofastInterface.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/opencsp/app/sofast/lib/SofastInterface.py b/opencsp/app/sofast/lib/SofastInterface.py index 5a7637b41..939d7a065 100644 --- a/opencsp/app/sofast/lib/SofastInterface.py +++ b/opencsp/app/sofast/lib/SofastInterface.py @@ -273,7 +273,7 @@ def func_process_sofast_fringe_data(self) -> None: # Plot optic lt.debug(f"{timestamp():s} Plotting Sofast Fringe data") - output_dir = join(self.paths.dir_save_fringe, self.file_timestamp) + output_dir = os.path.join(self.paths.dir_save_fringe, self.file_timestamp) os.makedirs(output_dir, exist_ok=True) self.plotting.optic_measured = mirror self.plotting.options_file_output.output_dir = output_dir @@ -320,7 +320,7 @@ def func_process_sofast_fixed_data(self) -> None: # Plot optic lt.debug(f"{timestamp():s} Plotting Sofast Fixed data") - output_dir = join(self.paths.dir_save_fringe, self.file_timestamp) + output_dir = os.path.join(self.paths.dir_save_fringe, self.file_timestamp) os.makedirs(output_dir, exist_ok=True) self.plotting.optic_measured = mirror self.plotting.options_file_output.output_dir = output_dir @@ -359,7 +359,7 @@ def func_save_measurement_fixed(self) -> None: def func_load_last_sofast_fringe_image_cal(self) -> None: """Loads last ImageCalibration object""" # Find file - files = glob.glob(join(self.paths.dir_save_fringe_calibration, "image_calibration_scaling*.h5")) + files = glob.glob(os.path.join(self.paths.dir_save_fringe_calibration, "image_calibration_scaling*.h5")) files.sort() if len(files) == 0: @@ -374,7 +374,7 @@ def func_load_last_sofast_fringe_image_cal(self) -> None: def func_gray_levels_cal(self) -> None: """Runs gray level calibration sequence""" - file = join(self.paths.dir_save_fringe_calibration, f"image_calibration_scaling_{timestamp():s}.h5") + file = os.path.join(self.paths.dir_save_fringe_calibration, f"image_calibration_scaling_{timestamp():s}.h5") self.system_fringe.run_gray_levels_cal( ImageCalibrationScaling, file, From a43e8b4771e2c9f983de0b6a3fdbc92d8213ec76 Mon Sep 17 00:00:00 2001 From: Evan Harvey Date: Thu, 24 Apr 2025 07:44:40 -0600 Subject: [PATCH 18/19] Fix typo --- opencsp/test/test_DocStringsExist.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/opencsp/test/test_DocStringsExist.py b/opencsp/test/test_DocStringsExist.py index 1e9399511..8558a0260 100644 --- a/opencsp/test/test_DocStringsExist.py +++ b/opencsp/test/test_DocStringsExist.py @@ -189,7 +189,7 @@ class test_Docstrings(unittest.TestCase): example_list = [ example.sofast_fringe.sofast_temperature_analysis, - example.sofast_fringe.sofast_command_line_tool + example.sofast_fringe.sofast_command_line_tool, example.sofast_fringe.example_process_in_debug_mode, example.sofast_fringe.sofast_temperature_analysis, example.sofast_fringe.example_make_rectangular_screen_definition, From 67ebf296caf2a3e3fc181fb4353b18b6e4a2b665 Mon Sep 17 00:00:00 2001 From: Evan Harvey Date: Tue, 6 May 2025 14:05:54 -0600 Subject: [PATCH 19/19] Change import to workaround windows ci join failure --- opencsp/app/sofast/lib/SofastInterface.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/opencsp/app/sofast/lib/SofastInterface.py b/opencsp/app/sofast/lib/SofastInterface.py index 939d7a065..5d8d04e36 100644 --- a/opencsp/app/sofast/lib/SofastInterface.py +++ b/opencsp/app/sofast/lib/SofastInterface.py @@ -39,7 +39,7 @@ """ import glob -from os.path import join +import os.path import os from dataclasses import dataclass import datetime as dt