"""Pulse-based measurement handler for transient surface photovoltage measurements.
The handler runs the acquisition loop in a worker thread and communicates with the main
thread (live view) via queues, modeled after the prsctrl MeasurementHandler.
"""
import logging
import time
import threading as mt
from pathlib import Path
from queue import Queue
from typing import Optional
import numpy as np
import yaml
from devctrl.devices import Oscilloscope, LaserOpo, DummyDevice
from devctrl.utility.sample import Sample
from devctrl.utility.file_io import sanitize_filename, get_date_time_for_filename, get_next_filename
from .settings import TspvSettings, BASE_LASER_REPETITION_RATE_HZ
from ..utility.setup import TspvSetupInfo
from ..data.util import (GZIP_COMPRESSION_LEVEL_AVERAGE, log_downsample_split_indices, raw_to_volts,
save_downsampled_pulse_hdf5, save_pulse_hdf5)
from ..version import version
log = logging.getLogger(__name__)
class _PulseSaveThread:
"""Background writer for the pulse hdf5 files: hdf5 compression is CPU-bound, so saving must not
block the pulse acquisition loop (which mostly waits for the trigger otherwise). Save calls are
executed in submission order. The queue is bounded, so saving slower than the acquisition
throttles the acquisition (backpressure) instead of growing the memory unboundedly.
"""
def __init__(self, queue_size: int = 2):
self._queue: Queue = Queue(maxsize=queue_size)
self._exception: Optional[BaseException] = None
self._thread = mt.Thread(target=self._run, name="pulse-save", daemon=True)
self._thread.start()
def submit(self, fn, *args, **kwargs):
"""Queue a save call for execution, blocking (backpressure) while the queue is full."""
t0 = time.monotonic()
self._queue.put((fn, args, kwargs))
blocked_s = time.monotonic() - t0
if blocked_s > 1.0:
log.warning(f"Saving the pulse data is slower than the acquisition "
f"(blocked {blocked_s:.1f} s waiting for a free queue slot)")
def _run(self):
while True:
item = self._queue.get()
if item is None:
break
fn, args, kwargs = item
try:
fn(*args, **kwargs)
except Exception as e:
log.error(f"Error saving the pulse data: {e!r}")
if self._exception is None:
self._exception = e
# drain the queue, so that submit() does not block forever after an error
def close(self):
"""Wait until all queued files are written. Raises the first error that occurred while saving."""
self._queue.put(None)
self._thread.join()
if self._exception is not None:
raise RuntimeError("Saving the pulse data failed") from self._exception
[docs]
class MeasurementHandler:
"""Pulse-based measurement handler: acquires single-shot captures from the oscilloscope and accumulates their average.
`run()` performs the measurement and may be run in a worker thread.
Communication with the main thread (live view) happens via queues:
- `command_queue`: receives commands, currently only "stop"
- `data_queue`: emits status tuples for the live view:
("status", msg) - human-readable progress message
("pulse", i, n, t_s, U_spv_V, U_diode_V) - after each acquired pulse, i is 1-based; the arrays are the
split-log-downsampled transient of the full pulse record, including pre-trigger samples
("avg", t_s, U_spv_V, U_diode_V) - running average, including pre-trigger samples
("warning", msg) - warning message
("trigger_timeout", msg) - a capture timed out and is retried
("done", t_s, U_spv_V, U_diode_V) - final averaged data
``U_diode_V`` is None in all messages when the diode channel is not recorded (single mode).
"""
[docs]
def __init__(self,
settings: TspvSettings,
osci: Oscilloscope,
laser: Optional[LaserOpo] = None,
data_queue: Optional[Queue] = None,
command_queue: Optional[Queue] = None,
data_dir: Optional[str|Path] = None,
compress_data: bool = True,
laser_wait_s: float = 0.0,
setup_info: Optional[TspvSetupInfo|dict] = None,
sample: Sample|str|None = None,
extra_metadata: Optional[dict] = None,
):
"""Class that performs the actual pulse acquisition.
:param settings: All measurement settings.
:param osci: Oscilloscope device.
:param laser: Laser device, or None to not control the laser.
:param data_queue: Queue where status messages are put in. Useful for live monitoring when `run()` is
run in another thread.
:param command_queue: Queue used to receive a "stop" signal. Useful when `run()` is run in another thread.
:param data_dir: Cache directory where per-pulse and averaged data files are stored, or None to not save.
:param compress_data: Whether to gzip-compress the data files (with the byte-shuffle filter).
:param laser_wait_s: Time in s to wait for the laser (e.g. ramp-up after turning it on, or settle after
a wavelength change) before the first acquisition. Resolve it with :py:func:`laser_wait_time_s`
before applying the laser settings.
:param setup_info: Setup description (e.g. buffer, laser temperatures) recorded in the metadata.yaml,
either as a TspvSetupInfo object or as a preprocessed dict, or None to not record setup info.
:param sample: Sample object (or its name, or None) recorded in the metadata.yaml.
:param extra_metadata: Additional metadata recorded top-level in the metadata.yaml (e.g. the sample
capacitance or global measurement metadata from the GUI). Applied last, so it can override other entries.
"""
self.settings = settings
self.osci = osci
self.laser = laser
self.data_queue: Optional[Queue] = data_queue
self.command_queue: Optional[Queue] = command_queue
self.data_dir = Path(data_dir) if data_dir is not None else None
self.compress_data = compress_data
self.laser_wait_s = laser_wait_s
self.setup_info = setup_info
self.sample = sample
self.extra_metadata: Optional[dict] = dict(extra_metadata) if extra_metadata else None
"""Additional metadata recorded top-level in the metadata.yaml, applied last (see __init__)."""
self.pulse_period_s: Optional[float] = (settings.laser.frequency_divider / BASE_LASER_REPETITION_RATE_HZ
if settings.laser.frequency_divider is not None else None)
"""Actual pulse interval in s, or None if no frequency divider is set"""
self.timeout_s: float = -1
self.n_acquired: int = 0
self.result: Optional[tuple[np.ndarray, np.ndarray, Optional[np.ndarray]]] = None
self.record_diode: bool = self.settings.acquisition.records_diode()
self.osci_raw_config: Optional[dict] = None
"""Raw configuration dump of the oscilloscope (Gage CompuScope only), recorded in the metadata."""
self.conversion_params: Optional[dict] = None
"""ADC-to-volt conversion parameters per channel, recorded in the metadata."""
self._writer: Optional[_PulseSaveThread] = None
self.error: Optional[BaseException] = None
"""Error that stopped the measurement, e.g. an error while saving the data"""
self._warned_no_raw_adc = False
[docs]
def _put(self, msg: tuple):
if self.data_queue is not None:
self.data_queue.put(msg)
[docs]
def _put_status(self, msg: str):
self._put(("status", msg))
[docs]
def _put_avg(self, data_type: str, t: np.ndarray, U_spv: np.ndarray, U_diode: np.ndarray):
self._put((data_type, t, U_spv, U_diode))
[docs]
def _put_warning(self, msg: str):
log.warning(msg)
self._put(("warning", msg))
#
# PREPARATION
#
[docs]
def prepare(self):
"""Compute derived parameters and create the data directory.
Also writes the settings to a ``parameters.yaml`` file in the data directory (if a data
directory is set), so that the parameters of the measurement are recorded in the same place
by the CLI and the GUI.
"""
if not getattr(self.settings, "resolved_acquisition", None):
raise RuntimeError("TspvSettings.prepare(osci) must be called before MeasurementHandler.prepare()")
# after start_capture, the next trigger is at most one pulse period away,
# the capture then completes after the acquisition time
self.timeout_s = ((self.pulse_period_s or 0.0)
+ self.settings.resolved_acquisition["acquisition_time_s"] + 2.0)
if self.data_dir is not None:
self.data_dir.mkdir(parents=True, exist_ok=True)
self.settings.save_yaml(self.data_dir / "parameters.yaml")
self._check_pulse_interval()
[docs]
def _check_pulse_interval(self):
"""Warn when the pulse interval is shorter than the recorded time span per pulse."""
if self.pulse_period_s is None:
return
rc = self.settings.resolved_acquisition
span_s = rc["segment_size"] / rc["sampling_rate_Hz"]
if span_s > self.pulse_period_s:
self._put_warning(
f"The pulse interval ({self.pulse_period_s:g} s) is shorter than the recorded time span per "
f"pulse ({span_s:g} s): pulses may be missed or the next pulse may fall into the recorded "
f"time window")
#
# RUN
#
[docs]
def run(self):
"""Run the measurement. You must call ``prepare()`` first.
``run()`` may be run in a separate thread.
"""
if self.timeout_s < 0:
raise RuntimeError("You must call `prepare()` before `run()`")
try:
self._run()
except KeyboardInterrupt:
log.info("Keyboard interrupt, stopping measurement")
except Exception as e:
self.error = e
log.critical(f"Unexpected error, stopping measurement. Error: {e}")
if self.data_queue is not None:
self.data_queue.put(("exception", e))
raise RuntimeError("Unexpected error, stopping measurement") from e
[docs]
def _run(self):
n_pulses = self.settings.general.n_pulses
n_wait = self.settings.general.wait_n_pulses
# turn the laser on and wait for it to ramp up / settle
# (the wait is resolved by the caller via laser_wait_time_s BEFORE the laser settings are applied)
if self.laser is not None:
self._put_status("Turning laser on")
self.laser.on()
if self.laser_wait_s > 0:
self._put_status(f"Waiting for the laser ({self.laser_wait_s:.0f} s)")
time.sleep(self.laser_wait_s)
# wait n_wait pulses before starting acquisition, to let the laser settle
if n_wait > 0:
if self.pulse_period_s is None:
self._put_warning("The pulse interval is unknown (no frequency divider set), "
"ignoring wait_n_pulses")
else:
self._put_status(f"Waiting {n_wait} pulses before starting acquisition "
f"({n_wait * self.pulse_period_s:.1f} s)")
time.sleep(n_wait * self.pulse_period_s)
if self.data_dir is not None:
self._writer = _PulseSaveThread()
try:
self._apply_rate_config(self.settings.resolved_acquisition)
result = self._measure(n_pulses, self.data_dir)
if result is None:
self._put_warning("No pulses acquired")
return
self.result = result
self._put_status("Measurement done")
finally:
if self._writer is not None:
# flush all queued files before returning, so that the data directory is complete
# when measure_transient writes the metadata
self._writer.close()
[docs]
def _apply_rate_config(self, rate_config: dict):
"""Apply the resolved acquisition configuration to the oscilloscope.
Sets the record length (post-trigger depth), the pre-trigger samples (segment size) and the
sampling rate, and stores the raw oscilloscope configuration for the metadata.
:param rate_config: The resolved acquisition configuration dict from
:py:attr:`TspvSettings.resolved_acquisition`.
"""
# self.osci.set_record_length(rate_config["depth"]) # TODO: , pre_trigger_samples=rate_config["pre_trigger_samples"])
self.osci.set_record_length(rate_config["depth"], n_pre_trigger=rate_config["pre_trigger_samples"])
self.osci.set_sampling_rate_Hz(rate_config["sampling_rate_Hz"])
# self.osci.set_acquisition_time_s(rate_config["depth"] / rate_config["sampling_rate_Hz"])
self._capture_osci_raw_config()
[docs]
def _capture_osci_raw_config(self):
"""Store the raw configuration dump of the oscilloscope for the metadata.
Only done for oscilloscopes that support the raw configuration queries, currently the
Gage CompuScope (acquisition, channels 1 and 2 and trigger engine 1). The dump reflects
the applied acquisition configuration.
"""
if not hasattr(self.osci, "get_acquisition_config"):
return
try:
self.osci_raw_config = {
"acquisition": self.osci.get_acquisition_config(),
"channel_1": self.osci.get_channel_config(1),
"channel_2": self.osci.get_channel_config(2),
"trigger_1": self.osci.get_trigger_config(1),
}
except Exception as e:
log.warning(f"Failed to retrieve the raw oscilloscope configuration for the metadata: {e}")
self.osci_raw_config = None
[docs]
def _get_conversions(self) -> Optional[dict[int, tuple[float, float]]]:
"""ADC-to-volt conversion parameters per channel, or None if the oscilloscope does not support
raw ADC data access (the data is then stored as float64 volts).
The conversion is queried after the acquisition configuration was applied, so it matches the
acquired data.
"""
acq = self.settings.acquisition
try:
channels = (acq.spv_channel, acq.diode_channel) if self.record_diode else (acq.spv_channel,)
return {ch: self.osci.get_waveform_conversion(ch) for ch in channels}
except (AttributeError, NotImplementedError):
if not self._warned_no_raw_adc:
self._warned_no_raw_adc = True
self._put_warning(f"{self.osci.get_device_name()} does not support raw ADC data access, "
f"storing the pulse data as float64 voltages instead")
return None
[docs]
def _measure(self, n_pulses: int, data_dir: Optional[Path]) -> Optional[tuple]:
"""Acquire ``n_pulses`` pulses at the configured sample rate and accumulate their average.
Stores a partial file per pulse and the averaged data in ``data_dir`` (if given): the individual
pulse files are always written, in the format given by
:py:attr:`MeasurementParameters.pulse_storage` (full int16 ADC / float64 volts, or
log-downsampled). The in-memory result and the live view always contain the full averaged
transient, independent of the settings.
:param n_pulses: Number of pulses to acquire.
:param data_dir: Directory to store the data in, or None to not save.
:return: (t_s, U_spv_V, U_diode_V) averaged and stripped of pre-trigger samples, or None if no pulse
was acquired. ``U_diode_V`` is None when the diode channel is not recorded (single mode).
"""
acq = self.settings.acquisition
store_downsampled = self.settings.general.pulse_storage == "downsampled"
conversions = self._get_conversions()
if conversions is not None:
self.conversion_params = {str(ch): {"gain_V_per_count": gain, "offset_V": offset}
for ch, (gain, offset) in conversions.items()}
t_avg: Optional[np.ndarray] = None
U_spv_sum: Optional[np.ndarray] = None
U_diode_sum: Optional[np.ndarray] = None
n_pre_trigger = -1
sample_rate_Hz = -1.0
downsample_indices: Optional[np.ndarray] = None
n = 0
while n < n_pulses:
if self.command_queue is not None and not self.command_queue.empty():
cmd = self.command_queue.get(block=False)
if cmd == "stop":
log.info("Measurement stopped by command")
break
try:
U_spv_raw, U_diode_raw, t, n_pre, rate = self._get_pulse_data(use_raw=conversions is not None)
except RuntimeError as e:
self._put_warning(str(e))
break
if conversions is not None:
# convert the raw ADC counts to volt, replacing the conversion that get_waveform_V
# would have applied internally
U_spv = raw_to_volts(U_spv_raw, *conversions[acq.spv_channel])
U_diode = None if U_diode_raw is None else raw_to_volts(U_diode_raw, *conversions[acq.diode_channel])
else:
U_spv, U_diode = U_spv_raw, U_diode_raw
if t_avg is None:
t_avg, U_spv_sum, U_diode_sum = t, U_spv, U_diode
n_pre_trigger, sample_rate_Hz = n_pre, rate
downsample_indices = log_downsample_split_indices(t.shape[0], n_pre,
self.settings.general.n_log_downsampled)
else:
U_spv_sum += U_spv
if U_diode is not None:
U_diode_sum += U_diode
n += 1
self.n_acquired = n
if data_dir is not None:
timestamp = time.strftime("%H:%M:%S")
if store_downsampled:
# the downsampled data is stored in volt, it is tiny compared to the full transient
idx = downsample_indices
self._writer.submit(save_downsampled_pulse_hdf5, data_dir / f"PART_{n - 1:04d}.h5", t[idx],
U_spv[idx], None if U_diode is None else U_diode[idx], sample_rate_Hz,
n_pre_trigger, pulse_idx=n - 1, compress=self.compress_data,
timestamp=timestamp)
else:
# the full transient is stored as raw ADC counts (or as float64 volts if the
# oscilloscope does not support raw ADC data access)
self._writer.submit(save_pulse_hdf5, data_dir / f"PART_{n - 1:04d}.h5", U_spv_raw, U_diode_raw,
sample_rate_Hz, n_pre_trigger, pulse_idx=n - 1, compress=self.compress_data,
timestamp=timestamp,
conversion_spv=conversions[acq.spv_channel] if conversions else None,
conversion_diode=conversions[acq.diode_channel]
if conversions and U_diode_raw is not None else None)
U_spv_avg = U_spv_sum / n
U_diode_avg = None if U_diode_sum is None else U_diode_sum / n
# per-pulse and running-average data for the live view: log-downsampled with the pre-trigger
# split distribution (see util.log_downsample_split_indices) and NOT stripped of pre-trigger
# samples — the live widgets mask t >= 0 by default. All points if no downsampling is needed.
idx = downsample_indices if downsample_indices is not None else np.arange(t.shape[0])
self._put(("pulse", n, n_pulses, t[idx], U_spv[idx], U_diode[idx] if U_diode is not None else None))
self._put_avg("avg", t[idx], U_spv_avg[idx], None if U_diode_avg is None else U_diode_avg[idx])
if n == 0:
return None
U_spv_avg = U_spv_sum / n
U_diode_avg = None if U_diode_sum is None else U_diode_sum / n
if data_dir is not None:
self._save_average(data_dir, t_avg, U_spv_avg, U_diode_avg, sample_rate_Hz, n_pre_trigger,
downsample_indices)
# the final averaged transient for the live view: downsampled with the same split distribution
idx = downsample_indices if downsample_indices is not None else np.arange(t_avg.shape[0])
self._put_avg("done", t_avg[idx], U_spv_avg[idx], None if U_diode_avg is None else U_diode_avg[idx])
mask = t_avg >= 0
return t_avg[mask], U_spv_avg[mask], None if U_diode_avg is None else U_diode_avg[mask]
[docs]
def _get_pulse_data(self, use_raw: bool = False) \
-> tuple[np.ndarray, Optional[np.ndarray], np.ndarray, int, float]:
"""Acquire a single pulse: start a capture, wait for the trigger and retrieve the data.
On a trigger timeout, re-arm and retry up to `trigger_retries` times, then fail.
:param use_raw: Whether to retrieve raw ADC counts (:py:meth:`Oscilloscope.get_waveform_ADC`) instead
of voltages (:py:meth:`Oscilloscope.get_waveform_V`).
:return: U_spv, U_diode, t_s, n_pre_trigger, sample_rate_Hz (of the full recorded segment, including
pre-trigger samples), where U_spv/U_diode are raw ADC counts if use_raw, voltages otherwise.
``U_diode`` is None when the diode channel is not recorded (single mode).
"""
acq = self.settings.acquisition
n_retries = self.settings.general.trigger_retries
for attempt in range(n_retries + 1):
try:
self.osci.start_capture()
self.osci.wait_for_capture(timeout=self.timeout_s)
break
except TimeoutError:
self.osci.stop_capture() # re-arm
if attempt < n_retries:
msg = f"Trigger timeout, retrying ({attempt + 1}/{n_retries})"
log.warning(msg)
self._put(("trigger_timeout", msg))
else:
raise RuntimeError(f"No trigger after {n_retries + 1} attempts ({self.timeout_s:.1f} s each), "
f"aborting measurement") from None
t = self.osci.get_time_axis_s(acq.spv_channel)
U_diode: Optional[np.ndarray] = None
if use_raw:
U_spv = self.osci.get_waveform_ADC(acq.spv_channel)
if self.record_diode:
U_diode = self.osci.get_waveform_ADC(acq.diode_channel)
else:
U_spv = self.osci.get_waveform_V(acq.spv_channel)
if self.record_diode:
U_diode = self.osci.get_waveform_V(acq.diode_channel)
# pre-trigger samples: everything recorded before the trigger
n_pre_trigger = int(np.sum(t < 0))
if n_pre_trigger == 0 and self.settings.resolved_acquisition["pre_trigger_samples"] > 0:
log.warning(f"The oscilloscope returned a time axis without pre-trigger samples although "
f"{self.settings.resolved_acquisition['pre_trigger_samples']} were configured; "
f"the pre-trigger part of the transient will be missing")
# sample rate from the time axis; use the configured rate if the axis is
# degenerate (e.g. dummy devices)
diffs = np.diff(t)
if diffs.size and np.median(diffs) > 0:
sample_rate_Hz = 1.0 / np.median(diffs)
else:
sample_rate_Hz = self.settings.resolved_acquisition["sampling_rate_Hz"]
return U_spv, U_diode, t, n_pre_trigger, sample_rate_Hz
#
# SAVING
#
[docs]
def _save_average(self, data_dir: Path, t: np.ndarray, U_spv_avg: np.ndarray, U_diode_avg: Optional[np.ndarray],
sample_rate_Hz: float, n_pre_trigger: int, downsample_indices: Optional[np.ndarray]):
"""Save the averaged transient via the background writer thread, full or log-downsampled.
The format follows :py:attr:`MeasurementParameters.pulse_storage`: 'full' stores the average as
float64 volt data (averages are fractional, unlike raw ADC counts), 'downsampled' stores the
log-downsampled average with the non-uniform time axis as a dataset.
"""
if self.settings.general.pulse_storage == "full" or downsample_indices is None:
self._writer.submit(save_pulse_hdf5, data_dir / "data.h5", U_spv_avg, U_diode_avg, sample_rate_Hz,
n_pre_trigger, pulse_idx=-1, compress=self.compress_data,
compression_opts=GZIP_COMPRESSION_LEVEL_AVERAGE)
else:
idx = downsample_indices
self._writer.submit(save_downsampled_pulse_hdf5, data_dir / "data.h5", t[idx], U_spv_avg[idx],
None if U_diode_avg is None else U_diode_avg[idx], sample_rate_Hz, n_pre_trigger,
pulse_idx=-1, compress=self.compress_data)
[docs]
def laser_wait_time_s(settings: TspvSettings, laser: Optional[LaserOpo]) -> float:
"""Determine how long to wait for the laser before the acquisition starts.
When the laser is off, the ramp-up time (`general.laser_ramp_up_time_s`) applies; when it is on and the
wavelength differs from the configured one, the settle time (`general.laser_settle_time_s`) applies.
The function must be called BEFORE the laser settings are applied to the device (otherwise the wavelength
comparison sees the already-applied value).
:param settings: Measurement settings with the target laser configuration.
:param laser: Laser device, or None to not control the laser.
:return: Wait time in seconds; 0 if no wait is needed or the laser is a dummy device.
"""
if laser is None or isinstance(laser, DummyDevice):
return 0.0
if not laser.is_on():
return settings.general.laser_ramp_up_time_s
if laser.get_wavelength_nm() != settings.laser.wavelength_nm:
return settings.general.laser_settle_time_s
return 0.0
[docs]
def measure_transient(settings: TspvSettings, laser: Optional[LaserOpo], osci: Oscilloscope, name: Optional[str] = None,
data_dir: Optional[str|Path] = None, data_dir_cache: str|Path = "~/.cache/spvctrl/data",
live_view: bool = True, compress_data: bool = True,
setup_info: Optional[TspvSetupInfo|dict] = None, sample: Sample|str|None = None) \
-> tuple[np.ndarray, list[str], Path]:
"""Measure a single transient surface photovoltage.
Applies the settings to the devices, runs the pulse acquisition in a worker thread,
shows a live view of the running average and stores the data in the cache directory:
`PART_`-prefixed per-pulse hdf5 files (always written, format per
:py:attr:`MeasurementParameters.pulse_storage`) and the averaged data.
In single acquisition mode, only the SPV channel is recorded and returned.
:param settings: All measurement settings.
:param laser: Laser device, or None to not control the laser.
:param osci: Oscilloscope device.
:param name: Name of the measurement, used for the cache directory name. Defaults to 'transient'.
:param data_dir: Exact measurement directory to store the data in. Defaults to a new directory in `data_dir_cache` named ``<date>_<name>``.
:param data_dir_cache: Cache directory where the measurement directory is created.
:param live_view: Whether to show a live view of the running average.
:param compress_data: Whether to gzip-compress the data files (with the byte-shuffle filter).
:param setup_info: Setup description (e.g. buffer, laser temperatures) recorded in the metadata.yaml,
either as a TspvSetupInfo object or as a preprocessed dict, or None to not record setup info.
:param sample: Sample object, or its name as stored in the sample database, or a name not present in the
database (stored as plain string), or None (stored as null). Recorded in the metadata.yaml.
:return: (data, columns, data_dir) with columns ["t_s", "U_spv_V", "U_diode_V"] in dual mode
("t_s", "U_spv_V" in single mode), where data is the averaged
transient stripped of pre-trigger samples, and data_dir is the measurement directory in the cache.
"""
if osci is None:
raise RuntimeError("No oscilloscope connected, connect the devices first (run init() or connect_device())")
import matplotlib.pyplot as plt
from devctrl.utility.monitor import Monitor
settings.prepare(osci=osci)
log.info(f"Prepared settings are {settings}")
laser_wait_s = laser_wait_time_s(settings, laser)
if laser is not None:
settings.laser.apply(laser)
settings.acquisition.apply(osci, trigger=settings.general.trigger)
# log the raw oscilloscope configuration, if the device supports it (Gage CompuScope only)
if hasattr(osci, "get_acquisition_config"):
log.info(f"Osci cfg: {osci.get_acquisition_config()}")
if hasattr(osci, "get_channel_config"):
log.info(f"Osci ch1: {osci.get_channel_config(1)}")
log.info(f"Osci ch2: {osci.get_channel_config(2)}")
if hasattr(osci, "get_trigger_config"):
log.info(f"Osci trg: {osci.get_trigger_config()}")
columns = ["t_s", "U_spv_V"] + (["U_diode_V"] if settings.acquisition.records_diode() else [])
if data_dir is not None:
data_dir = Path(data_dir).expanduser()
else:
dirname = sanitize_filename(get_date_time_for_filename() + "_" + (name if name else "transient"))
data_dir = get_next_filename(Path(data_dir_cache).expanduser() / dirname)
data_queue = Queue()
command_queue = Queue()
handler = MeasurementHandler(settings=settings, osci=osci, laser=laser, data_queue=data_queue,
command_queue=command_queue, data_dir=data_dir, compress_data=compress_data,
laser_wait_s=laser_wait_s, setup_info=setup_info, sample=sample)
handler.prepare()
monitor = None
if live_view:
plt.ion()
axes = [dict(ax=0, ylabel="U_spv [V]", color="#2f88ff")]
if settings.acquisition.records_diode():
axes.append(dict(ax=1, ylabel="U_diode [V]", color="#ff7f0e"))
monitor = Monitor("t [s]", axes)
monitor.set_fig_title(f"Starting measurement: {data_dir.name}")
print("Starting measurement, use <C-c> to stop.")
t_start = time.strftime("%Y-%m-%d %H:%M:%S")
proc_measure = mt.Thread(target=handler.run)
proc_measure.start()
messages: list[str] = []
timeout_s = ((settings.general.n_pulses + settings.general.wait_n_pulses) * (handler.pulse_period_s or 0.0)
+ laser_wait_s + 60)
try:
while proc_measure.is_alive():
while not data_queue.empty():
msg = data_queue.get(block=False)
kind = msg[0]
if kind in ("avg", "done"):
_, t, U_spv, U_diode = msg
if monitor is not None:
# the averaged data arrives already log-downsampled from the handler
if t.size:
if U_diode is not None:
monitor.replace_data(t, U_spv, U_diode)
else:
monitor.replace_data(t, U_spv)
monitor.set_ax_title(f"n = {handler.n_acquired}")
elif kind == "pulse":
_, i, n = msg[:3]
if monitor is not None:
monitor.set_ax_title(f"Pulse {i}/{n}")
elif kind in ("status", "warning", "trigger_timeout"):
if kind != "status":
messages.append(msg[1])
if monitor is not None:
monitor.set_ax_title(msg[1])
print(msg[1])
elif kind == "exception":
log.critical(f"Measurement thread reported exception: {msg[1]}")
else:
log.error(f"Invalid tuple received from measurement thread: {msg[0]}")
time.sleep(0.01)
if monitor is not None:
monitor.idle()
except KeyboardInterrupt:
log.info(f"KeyboardInterrupt received, measurement will stop after the current pulse. (Timeout is {timeout_s} s)")
command_queue.put("stop")
proc_measure.join(timeout=timeout_s)
if proc_measure.is_alive():
log.critical(f"Timed out waiting for measurement thread to finish ({timeout_s} s)")
if monitor is not None:
monitor.set_fig_title(data_dir.name)
monitor.set_ax_title("")
if settings.general.turn_off_laser_after_measurement and laser is not None:
try:
laser.off()
except Exception as e:
log.error(f"Failed to turn off the laser: {e}")
if handler.error is not None:
raise RuntimeError("Measurement failed") from handler.error
if handler.result is None:
raise RuntimeError("Measurement failed, no data acquired")
handler.save_metadata(handler.n_acquired, messages, t_start, time.strftime("%Y-%m-%d %H:%M:%S"))
t, U_spv, U_diode = handler.result
if U_diode is None:
data = np.vstack((t, U_spv)).T
else:
data = np.vstack((t, U_spv, U_diode)).T
return data, columns, data_dir