Skip to content

Commit

Permalink
bug fix
Browse files Browse the repository at this point in the history
  • Loading branch information
hongquanli committed Feb 11, 2025
1 parent 7acebb1 commit a4834a8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 23 deletions.
45 changes: 23 additions & 22 deletions software/control/core/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3874,7 +3874,7 @@ def add_region(self, well_id, center_x, center_y, scan_size_mm, overlap_percent=

half_steps_height = (steps_height - 1) / 2
half_steps_width = (steps_width - 1) / 2

for i in range(steps_height):
row = []
y = center_y + (i - half_steps_height) * step_size_mm
Expand Down Expand Up @@ -4468,6 +4468,7 @@ def __init__(
look_for_cache=True,
):
QObject.__init__(self)
self._log = squid.logging.get_logger(__class__.__name__)
self.microcontroller = microcontroller
self.camera = camera
self.liveController = liveController
Expand Down Expand Up @@ -4573,7 +4574,7 @@ def initialize_auto(self) -> bool:

result = self._get_laser_spot_centroid()
if result is None:
_log.error("Failed to find laser spot during initialization")
self._log.error("Failed to find laser spot during initialization")
self.microcontroller.turn_off_AF_laser()
self.microcontroller.wait_till_operation_is_completed()
return False
Expand All @@ -4585,7 +4586,7 @@ def initialize_auto(self) -> bool:
# Set up ROI around spot
x_offset = x - LASER_AF_CROP_WIDTH / 2
y_offset = y - LASER_AF_CROP_HEIGHT / 2
_log.info(f"Laser spot location on the full sensor is ({int(x)}, {int(y)})")
self._log.info(f"Laser spot location on the full sensor is ({int(x)}, {int(y)})")

self.initialize_manual(x_offset, y_offset, LASER_AF_CROP_WIDTH, LASER_AF_CROP_HEIGHT, 1, x)

Expand All @@ -4600,7 +4601,7 @@ def initialize_auto(self) -> bool:

result = self._get_laser_spot_centroid()
if result is None:
_log.error("Failed to find laser spot during calibration (position 1)")
self._log.error("Failed to find laser spot during calibration (position 1)")
self.microcontroller.turn_off_AF_laser()
self.microcontroller.wait_till_operation_is_completed()
return False
Expand All @@ -4612,7 +4613,7 @@ def initialize_auto(self) -> bool:

result = self._get_laser_spot_centroid()
if result is None:
_log.error("Failed to find laser spot during calibration (position 2)")
self._log.error("Failed to find laser spot during calibration (position 2)")
self.microcontroller.turn_off_AF_laser()
self.microcontroller.wait_till_operation_is_completed()
return False
Expand All @@ -4624,10 +4625,10 @@ def initialize_auto(self) -> bool:
# Calculate conversion factor
if x1 - x0 == 0:
self.pixel_to_um = 0.4 # Simulation value
_log.warning("Using simulation value for pixel_to_um conversion")
self._log.warning("Using simulation value for pixel_to_um conversion")
else:
self.pixel_to_um = 6.0 / (x1 - x0)
_log.info(f"Pixel to um conversion factor is {self.pixel_to_um:.3f} um/pixel")
self._log.info(f"Pixel to um conversion factor is {self.pixel_to_um:.3f} um/pixel")

# Set reference position
self.x_reference = x1
Expand All @@ -4651,7 +4652,7 @@ def measure_displacement(self) -> float:
self.microcontroller.wait_till_operation_is_completed()

if result is None:
_log.error("Failed to detect laser spot during displacement measurement")
self._log.error("Failed to detect laser spot during displacement measurement")
self.signal_displacement_um.emit(float("nan")) # Signal invalid measurement
return float("nan")

Expand All @@ -4671,14 +4672,14 @@ def move_to_target(self, target_um: float) -> bool:
bool: True if move was successful, False if measurement failed or displacement was out of range
"""
current_displacement_um = self.measure_displacement()
_log.info(f"Current laser AF displacement: {current_displacement_um:.1f} μm")
self._log.info(f"Current laser AF displacement: {current_displacement_um:.1f} μm")

if math.isnan(current_displacement_um):
_log.error("Cannot move to target: failed to measure current displacement")
self._log.error("Cannot move to target: failed to measure current displacement")
return False

if abs(current_displacement_um) > LASER_AF_RANGE:
_log.warning(
self._log.warning(
f"Measured displacement ({current_displacement_um:.1f} μm) is unreasonably large, using previous z position"
)
return False
Expand All @@ -4689,10 +4690,10 @@ def move_to_target(self, target_um: float) -> bool:
# Verify we reached the target
final_displacement = self.measure_displacement()
if math.isnan(final_displacement):
_log.error("Failed to verify final position")
self._log.error("Failed to verify final position")
return False

_log.debug(f"Final displacement: {final_displacement:.1f} μm")
self._log.debug(f"Final displacement: {final_displacement:.1f} μm")
return abs(final_displacement - target_um) < 1.0 # Success if within 1 μm

def set_reference(self) -> bool:
Expand All @@ -4713,13 +4714,13 @@ def set_reference(self) -> bool:
self.microcontroller.wait_till_operation_is_completed()

if result is None:
_log.error("Failed to detect laser spot while setting reference")
self._log.error("Failed to detect laser spot while setting reference")
return False

x, y = result
self.x_reference = x
self.signal_displacement_um.emit(0)
_log.info(f"Set reference position to ({x:.1f}, {y:.1f})")
self._log.info(f"Set reference position to ({x:.1f}, {y:.1f})")
return True

def _get_laser_spot_centroid(self) -> Optional[Tuple[float, float]]:
Expand Down Expand Up @@ -4750,7 +4751,7 @@ def _get_laser_spot_centroid(self) -> Optional[Tuple[float, float]]:
# read camera frame
image = self.camera.read_frame()
if image is None:
_log.warning(f"Failed to read frame {i+1}/{LASER_AF_AVERAGING_N}")
self._log.warning(f"Failed to read frame {i+1}/{LASER_AF_AVERAGING_N}")
continue

self.image = image # store for debugging
Expand All @@ -4762,7 +4763,7 @@ def _get_laser_spot_centroid(self) -> Optional[Tuple[float, float]]:
# calculate centroid
result = utils.find_spot_location(image)
if result is None:
_log.warning(f"No spot detected in frame {i+1}/{LASER_AF_AVERAGING_N}")
self._log.warning(f"No spot detected in frame {i+1}/{LASER_AF_AVERAGING_N}")
continue

x, y = result
Expand All @@ -4771,19 +4772,19 @@ def _get_laser_spot_centroid(self) -> Optional[Tuple[float, float]]:
successful_detections += 1

except Exception as e:
_log.error(f"Error processing frame {i+1}/{LASER_AF_AVERAGING_N}: {str(e)}")
self._log.error(f"Error processing frame {i+1}/{LASER_AF_AVERAGING_N}: {str(e)}")
continue

# Check if we got enough successful detections
if successful_detections == 0:
_log.error(f"No successful detections")
self._log.error(f"No successful detections")
return None

# Calculate average position from successful detections
x = tmp_x / successful_detections
y = tmp_y / successful_detections

_log.debug(f"Spot centroid found at ({x:.1f}, {y:.1f}) from {successful_detections} detections")
self._log.debug(f"Spot centroid found at ({x:.1f}, {y:.1f}) from {successful_detections} detections")
return (x, y)

def get_image(self) -> Optional[np.ndarray]:
Expand All @@ -4804,14 +4805,14 @@ def get_image(self) -> Optional[np.ndarray]:
image = self.camera.read_frame()

if image is None:
_log.error("Failed to read frame in get_image")
self._log.error("Failed to read frame in get_image")
return None

self.image_to_display.emit(image)
return image

except Exception as e:
_log.error(f"Error capturing image: {str(e)}")
self._log.error(f"Error capturing image: {str(e)}")
return None

finally:
Expand Down
3 changes: 2 additions & 1 deletion software/control/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from numpy import std, square, mean
import numpy as np
from scipy.ndimage import label
from scipy import signal
import os
from typing import Optional, Tuple
from enum import Enum, auto
Expand Down Expand Up @@ -220,7 +221,7 @@ def find_spot_location(
"x_window": 20, # Half-width of centroid window
"min_peak_width": 10, # Minimum width of peaks
"min_peak_distance": 10, # Minimum distance between peaks
"mim_peak_prominence": 100, # Minimum peak prominence
"min_peak_prominence": 100, # Minimum peak prominence
"intensity_threshold": 0.1, # Threshold for intensity filtering
"spot_spacing": 100, # Expected spacing between spots
}
Expand Down

0 comments on commit a4834a8

Please sign in to comment.