Skip to content

Acquisition Module

Data acquisition functions for logging data from soundcards and National Instruments DAQ devices.

Acquisition Settings

MySettings is the object you pass to every acquisition call — it holds the device, channel, sampling, trigger, voltage-range, IEPE excitation and per-channel calibration configuration. Every constructor argument is keyword-only with a default, and the attributes are plain and mutable. The full per-attribute reference is below; for worked end-to-end recipes (IEPE on a cDAQ, calibration at logging time) see the Data Acquisition user guide.

MySettings

MySettings(*, channels=2, fs=44100, nbits=16, chunk_size=100, num_chunks=6, viewed_time=0.3, stored_time=2, pretrig_samples=None, pretrig_threshold=None, pretrig_channel=0, pretrig_timeout=20, lpf_on=False, capture_fs=None, oversample='auto', device_driver='soundcard', device_index=None, device=None, device_name=None, device_hostapi=None, input_channels_spec=None, VmaxNI=5, VmaxSC=1.0, input_gain_db=None, input_mode='line', input_pad=False, iepe_excit_current_A=0.0, channel_sensitivities=1.0, NI_mode='DAQmx_Val_RSE', init_view_time=True, init_view_freq=True, init_view_levels=True, output_device_driver=None, output_device_index=None, output_channels=None, output_channels_spec=None, output_fs=None, output_VmaxNI=None, output_VmaxSC=None, use_output_as_ch0=False)

Bases: object

A container for every acquisition setting used by a recording.

A single MySettings instance configures all acquisition entry points: acquisition.log_data, acquisition.signal_generator, the streams recorders, and the web logger's local bridge (pydvma-serve and pydvma.launch). All constructor arguments are keyword-only and have defaults, so override only the few you need. See the Data Acquisition user guide for worked end-to-end examples.

Pass every setting as a constructor keyword argument. The constructor derives several values from the others, and assigning an attribute afterwards changes only that one attribute: settings.fs = 10000 leaves output_fs and num_chunks at the old rate; settings.channels = 3 leaves the per-channel values (channel_sensitivities, iepe_excit_current_A) sized for the old count, so plotting and transfer functions later fail with an IndexError (only the full-scale accessors, input_vmax, input_vmax_channels and channels_in_volts, truncate or pad to the new count); and changing device_driver leaves the output driver and its voltage rail (output_vmax()) as they were. To change a setting, make a new MySettings.

Conventions used throughout:

  • Everything is in volts. Acquired data and generated output are in volts; engineering-unit scaling is applied at display/fit time from channel_sensitivities, never by rescaling the stored data.
  • Per-channel fields take a scalar or a sequence. iepe_excit_current_A, channel_sensitivities, VmaxSC, input_gain_db, input_mode and input_pad accept one value (meaning every channel) or a list of length channels, indexed in captured-column order — on a cDAQ chassis that is slot order (see input_channels_spec). A scalar keeps exactly its one-value meaning.
  • The output_* fields configure the generation/AO path and, when left unset, are derived from their input counterparts at construction.

Attributes:

  • channels (int) –

    Number of input channels (default 2). On the soundcard backend this is clamped to the device's max_input_channels at start_stream time (with a printed warning) — so the default of 2 becomes 1 on a mono mic rather than failing with PortAudio -9998. The NI backend instead raises ValueError if the count exceeds the device's available AI channels.

  • fs (int) –

    Input sampling frequency in Hz (default 44100). On a DSA module (NI 9234) the driver coerces this to the nearest rate on its discrete divider ladder.

  • nbits (int) –

    Sample bit depth — 8, 16, 24 or 32 (default 16).

  • chunk_size (int) –

    Samples acquired per channel per callback (default 100; values below 10 are raised to 10). Also the upper bound on pretrig_samples.

  • num_chunks (int) –

    Chunks held in the oscilloscope circular buffer (default 6); recomputed from viewed_time when set.

  • viewed_time (float or None) –

    Oscilloscope display window in seconds (default 0.3). When set, overrides num_chunks as ceil(viewed_time * fs / chunk_size). Set to None to size the oscilloscope buffer directly from num_chunks instead.

  • stored_time (float) –

    Duration of the recorded capture in seconds (default 2).

  • pretrig_samples (int or None) –

    Samples retained before the trigger, or None (default) for untriggered recording. Must not exceed chunk_size (the pretrigger buffer holds only one chunk of pre-trigger context), and must be less than stored_time * fs — otherwise there would be no post-trigger data left to record.

  • pretrig_threshold (float or None) –

    Trigger level, as a magnitude, in the units the recorder stores. On NI that is volts. On a soundcard it is volts once VmaxSC is set and full-scale units while it is left at 1.0 (uncalibrated) — the samples are scaled by VmaxSC on the way in, and the threshold is compared after that scaling. None (default) means 5 % of the trigger channel's full scale (input_vmax(pretrig_channel)), rounded to two significant figures: 0.25 V on a ±5 V NI range, 0.05 on an uncalibrated soundcard. That is the web app's default too, and it is resolved when the capture runs (pretrig_level), so it follows a range the hardware coerced. Raise it to a sensible fraction of the expected signal when 5 % sits near the noise floor.

  • pretrig_channel (int) –

    Channel index monitored for the trigger (default 0).

  • pretrig_timeout (float) –

    Seconds to wait for the trigger event before recording anyway (default 20). It bounds only the wait for the threshold crossing: once the crossing happens, the post-trigger data is given stored_time + 5 seconds of its own to arrive, so a capture longer than the timeout is not cut short.

  • lpf_on (bool) –

    Digital low-pass toggle (default False). When on, log_data captures ABOVE fs and resamples down behind a linear-phase anti-alias FIR (analysis.resample_to_fs — passband to fs/2.56, 96 dB stopband at fs/2). fs keeps its normal meaning (the rate you log at); the toggle changes only HOW that rate is achieved — oversample + noise-reducing decimation instead of sampling at fs directly. How far above fs the capture runs is set by oversample; on a device with a published rate ladder it is one of that device's real rates, otherwise an integer multiple of fs under the device maximum. The logged settings record the capture rate as lpf_capture_fs. NOTE the capture rate can differ from fs with this toggle OFF too: a device that cannot run at fs at all (any sound card asked for 3 kHz) is captured at a rate it can run and resampled down regardless, because the alternative is letting the OS resample silently.

  • oversample (str) –

    How far above fs to capture when oversampling — 'auto' (default), 'lowest' or 'highest'. 'auto' is device-specific: a sound card (delta-sigma, already anti-aliased at its own rate) takes the lowest rate with headroom, while NI takes the highest, which is mandatory on the filterless multiplexed USB-6003/6212 and buys noise process gain on DSA modules. Override when you know better than the default — see streams.oversample_strategy.

  • capture_fs (float) –

    Force the rate the hardware runs at, in Hz, overriding the automatic choice (default None = auto). fs is what you want delivered; this is what the converter actually samples at before pydvma decimates down to fs. Auto picks the lowest rate the device can genuinely run that covers fs, which is right for a sound card (delta-sigma, already anti-aliased at its own rate). Set it explicitly to capture faster — worth doing on hardware with no anti-alias filter, where a high capture rate is the only protection. Must be at least fs.

  • device_driver (str) –

    Input backend — 'soundcard' (default), 'nidaq' or 'mock' (the hardware-free test backend).

  • device_index (int or None) –

    Index into the enumerated device list for the chosen driver; None picks a default (the system default input soundcard, or NI device 0). For a cDAQ chassis this indexes the chassis as a whole, not a module — list candidates with dvma.list_available_devices() (its nidaq section is indexed the same way device_index is).

  • device (str or int or None) –

    Name the hardware instead of numbering it (default None). A case-insensitive substring of the device name — device='U24XL' — is resolved to whichever index that interface currently occupies, choosing the best backend available for it and filling in device_index, device_name and device_hostapi together. On Windows that choice is material: one interface is listed once per host API and they differ in word length and in whether they will silently resample, so the resolved backend also depends on fs. The choice and its reason are printed. Raises ValueError listing the candidates if the name matches no device, or more than one. An int is taken as an index. Run streams.list_available_devices to see what is present and what pydvma knows about each device's voltage scale.

  • device_name (str or None) –

    Exact enumerated name that device_index is expected to refer to (default None). Device indices are positions in an enumeration, not identities, and the enumeration reorders — so when this is set, streams.start_stream verifies the two still agree before opening, follows the name to its new index if it moved, and refuses rather than record the wrong instrument if it has gone. Left unset, streams.Recorder.init_stream records the resolved name after the first capture, which arms the same check for every capture after that.

  • device_hostapi (str or None) –

    Host-API name that device_index was chosen on, e.g. 'Windows WDM-KS' (default None, also filled in after the first capture). The other half of the identity, and the half that matters on Windows: PortAudio lists one interface once per host API with the SAME name each time, so device_name alone cannot tell four candidates apart and the check would give up. Ignored on platforms that list each device once.

  • input_channels_spec (str or None) –

    Optional raw DAQmx physical-channel string for the AI task, e.g. 'cDAQ1Mod1/ai0:3,cDAQ1Mod3/ai0'. Overrides the auto-built '<dev>/ai0:N-1' string when set — use it for gappy or mixed-module layouts the count-based builder cannot express. nidaqmx backend only.

  • VmaxNI (float) –

    Full-scale input voltage for the NI AI task (default 5); ±VmaxNI is passed as min/max to add_ai_voltage_chan. Pick the smallest range covering the signal for best resolution. Fixed at ±5 V on the 9234 (other values are accepted but ignored by the hardware).

  • input_gain_db (float or None or sequence) –

    Preamp gain currently set on the audio interface, in dB (default None). pydvma cannot read this — it is a front-panel control no audio API exposes — so stating it here lets VmaxSC be derived from the device's published maximum input level, and records in the saved dataset what the front panel was set to. Takes precedence over an explicit VmaxSC. Only applies to interfaces characterised in pydvma._soundcard_specs; ignored otherwise. Changing the gain on the hardware invalidates the calibration, so re-state it. A characterised FIXED-GAIN interface (e.g. the ESI U24 XL) needs no stated gain: VmaxSC is derived automatically when this is None and VmaxSC is left at its default. An interface with a preamp per channel (the Audient iD44, four gain knobs) takes a list of length channels instead, e.g. [60, 60, None, 0]: each channel's VmaxSC is derived from its own entry, and a None entry leaves that channel's VmaxSC as it is (1.0, full-scale units, unless given). A scalar is the same gain on every channel, as before. Stays a scalar when given as one, else is stored as a list. On a device whose profile has a gain per channel (the iD44) even a scalar gain is applied channel by channel: its 'optical' (ADAT) and 'loopback' channels take no rail from it (their VmaxSC is 1.0 unless given per channel), so VmaxSC becomes an array once such channels are recorded. The 2i2 and U24 XL keep one rail for every channel, loopback included.

  • input_mode (str or sequence) –

    Which input the signal is on — 'line' (default), 'inst' or 'mic', or a list with one per channel. Sets the maximum input level used with input_gain_db; on a Scarlett 2i2 these are 22, 12 and 16 dBu at minimum gain respectively. Where a gain is derived on a device with per-channel inputs, the mode must be one that input offers (pydvma._soundcard_specs.channel_input_modes: the iD44's 'inst' is on inputs 1-2 only), or ValueError names the channel.

  • input_pad (bool or sequence) –

    Whether the interface's input pad is engaged (default False), or a list with one per channel. A pad lowers the signal before the preamp, so it RAISES full scale by the profile's pad_db (10 dB on the Audient iD44). Used only where full scale is derived from a characterised interface's profile (a stated gain, or a fixed-gain interface); True there on an interface with no pad raises ValueError.

  • VmaxSC (float or sequence) –

    Soundcard input calibration (default 1.0) — the jack voltage corresponding to a normalised reading of 1.0. Default 1.0 treats normalised samples as volts at unit scale (no calibration); set it to your measured input sensitivity to calibrate captures in volts. Takes a list with one per channel for an interface whose channels differ. Stored as a float when every channel's value is equal (whatever was passed), otherwise as a float ndarray of shape (channels,); either way the recorder multiplies each channel by its own value, so stored data are volts per channel. Read it through input_vmax / input_vmax_channels rather than directly.

  • NI_mode (str) –

    NI terminal configuration — 'DAQmx_Val_RSE' (default), 'DAQmx_Val_NRSE', 'DAQmx_Val_Diff' or 'DAQmx_Val_PseudoDiff'. DSA modules (9234) are pseudo-differential only.

  • iepe_excit_current_A (float or sequence of float) –

    Per-channel IEPE / ICP excitation current in amps (default 0.0 = off on every channel). Scalar broadcasts; a sequence must be length channels. Only NI 9234-class DSA modules support it; the legal discrete values on the 9234 are 0.0 and 0.002 (2 mA), validated against the module that actually owns each channel. A channel with current > 0 is switched to AC coupling and the recorder blocks ~2 s after start for the sensor bias to settle through the AC-coupling HPF. Requires device_driver='nidaq' (raises ValueError otherwise). Never enable it on a channel wired to an AO output (e.g. a loopback) — the current drives back into the AO terminal.

  • channel_sensitivities (float or sequence of float) –

    Per-channel sensitivity in volts per engineering unit — V/g for an accelerometer, V/N for a force transducer, V/Pa for a microphone, etc. (default 1.0 = no calibration applied). Scalar broadcasts; a sequence must be length channels and every value must be non-zero. log_data stores the reciprocal as TimeData.channel_cal_factors, which plotting and modal fitting apply automatically, so a 100 mV/g accelerometer (0.1 here) gives a cal factor of 10 and plots read in g. The stored time_data array itself stays in volts.

  • output_device_driver (str) –

    Backend for the output/AO path; defaults to device_driver (same device as the input).

  • output_device_index (int or None) –

    Device index for the output path. None follows the resolved device_index when the output driver matches the input driver and the input device can play (for soundcard, when it reports output channels — a USB audio interface drives its own outputs; a capture on it then runs as ONE full-duplex stream, see pydvma.streams.Recorder.init_stream). Otherwise: soundcard falls back to the default output device (a microphone-only input cannot play the stimulus), and nidaq/mock to device 0 for cross-driver output.

  • output_channels (int) –

    Number of output (AO) channels; None (the default) means 1. Setting it does not generate anything: an output is played only when an output= array is passed to log_data.

  • output_channels_spec (str or None) –

    Raw DAQmx physical-channel string for the AO task, e.g. 'cDAQ1Mod2/ao0'; the output analogue of input_channels_spec. nidaqmx backend only.

  • output_fs (int) –

    Output sample rate in Hz; defaults to fs.

  • output_VmaxNI (float or None) –

    Full-scale output voltage for the NI AO task; defaults to VmaxNI. (The NI 9260 is limited to ±4.24 V.)

  • output_VmaxSC (float or None) –

    Full-scale output voltage for the soundcard AO path — the jack voltage corresponding to a ±1 sounddevice sample. Always one number. Defaults to VmaxSC when that is one number (every channel equal), as on the Scarlett 2i2 and ESI U24 XL. It defaults to 1.0 instead, i.e. the generated output is in normalised ±1 units until you set it, with a per-channel VmaxSC and on any device whose profile has a gain per channel (the Audient iD44), whatever its input gains: there the input rail is a mic preamp's millivolts, and an output scaled to it would play a stimulus some 40 dB too hot. An explicit value is always kept.

  • use_output_as_ch0 (bool) –

    When True and an output array is passed to log_data, the generated drive signal is prepended as channel 0 of the recorded data (default False). Useful for transfer-function tests where the excitation should be the reference channel; the prepended column passes through with a cal factor of 1.

  • init_view_time (bool) –

    Accepted for compatibility with code written for the removed desktop logger, and ignored.

  • init_view_freq (bool) –

    Accepted for compatibility and ignored.

  • init_view_levels (bool) –

    Accepted for compatibility and ignored.

Examples:

IEPE accelerometers on a cDAQ with per-channel calibration — 100 mV/g ICP accelerometers on the 9234's ai0/ai1 and a 2.3 mV/N force probe on ai2 (channel index 3 unused):

>>> settings = dvma.MySettings(
...     device_driver='nidaq',
...     device_index=0,                  # the cDAQ chassis
...     channels=3,
...     NI_mode='DAQmx_Val_PseudoDiff',  # required by the 9234
...     VmaxNI=5,                        # 9234 fixed at ±5 V
...     fs=12800,
...     iepe_excit_current_A=[0.002, 0.002, 0.0],  # 2 mA accels only
...     channel_sensitivities=[0.1, 0.1, 0.0023],  # V/g, V/g, V/N
... )
>>> dataset = dvma.log_data(settings)

Scalars broadcast to every channel — four identical IEPE-powered 100 mV/g accelerometers:

>>> settings = dvma.MySettings(
...     device_driver='nidaq', channels=4,
...     iepe_excit_current_A=0.002, channel_sensitivities=0.1,
... )
See Also

acquisition.log_data: Run a capture using these settings. list_available_devices: Print soundcard + nidaq devices by index. suggest_ni_settings: Safe NI ranges/rate/mode for a device.

input_vmax

input_vmax(channel=None)

Effective full-scale input value for the current driver.

Parameters:

  • channel (int or None, default: None ) –

    Zero-based input channel, or None (the default) for the largest over all channels.

Returns:

  • vmax ( float ) –

    VmaxNI (the configured AI range) when device_driver='nidaq'; otherwise VmaxSC, the sound card's full-scale voltage (1.0 when uncalibrated, so readings are in full-scale units). With a per-channel VmaxSC, that channel's entry, or the largest entry when channel is None: the value no sample of the capture can exceed, which is what a single-number consumer (a level meter scale, the dropout check's silence test) needs. A channel beyond a per-channel VmaxSC reads 1.0 (see input_vmax_channels).

Raises:

  • IndexError –

    A negative channel.

input_vmax_channels

input_vmax_channels()

Full-scale input value of each channel, in stored units.

VmaxNI repeated on device_driver='nidaq'; otherwise VmaxSC broadcast when it is one number, or its per-channel entries. The array always has channels entries: when channels was changed after the settings were built, a per-channel VmaxSC is truncated, or padded with 1.0 (the full-scale units of a channel nothing is known about). This is the rail the recorder scales by and the clip check judges each channel against.

Returns:

  • rails ( ndarray ) –

    Float array of shape (channels,).

channels_in_volts

channels_in_volts()

Whether each channel's full scale is a real voltage.

True on every channel on NI, where the AI task returns volts. On a soundcard, True where the channel's VmaxSC has been moved off its uncalibrated default of 1.0, which is what a stated gain on a characterised device, a fixed-gain device's automatic derivation, or an explicit VmaxSC all do; False where the channel's data are full-scale units (no gain stated on a variable-gain device, an uncharacterised device, the device could not be identified, or an optical or loopback input of a device with a gain per channel, which a stated gain does not calibrate). The same rule as the web app's volts test and pydvma.serve's inputVmaxIsVolts, applied per channel.

Returns:

  • in_volts ( ndarray ) –

    Bool array of shape (channels,).

output_vmax

output_vmax()

Effective full-scale output voltage for the current driver.

Mirror of input_vmax for the AO path, based on output_device_driver.

Returns:

  • vmax ( float ) –

    output_VmaxNI when output_device_driver='nidaq'; otherwise output_VmaxSC.

pretrig_level

pretrig_level(settings)

The trigger level a capture compares against, in stored units.

settings.pretrig_threshold when one is set; otherwise PRETRIG_THRESHOLD_FS_FRACTION of the TRIGGER channel's full scale (VmaxNI on NI; on a soundcard VmaxSC, or its entry for pretrig_channel when it is per-channel), rounded to two significant figures exactly as the web app rounds its default, so the two agree to the digit (0.25 V on a ±5 V NI range, 0.05 on an uncalibrated soundcard). Resolved at capture time, so an NI range the hardware coerced upward moves the default with it.

Reads attributes with getattr rather than calling MySettings.input_vmax, so it also accepts the light stand-in settings objects the recorders are sometimes driven with, and settings restored from an old file. A rail that is missing, beyond a per-channel list, or not a finite positive number counts as 1.0.

Parameters:

  • settings (MySettings) –

    the capture's settings.

Returns:

  • level ( float ) –

    the threshold magnitude.

Main Acquisition Function

log_data

log_data(settings, test_name=None, rec=None, output=None, cancel_event=None)

Acquire one block of time-domain data and return it as a DataSet.

Two call modes depending on settings.pretrig_samples:

  • No pretrigger (pretrig_samples is None): starts or reuses a stream, waits settings.stored_time seconds, and returns the most recent stored_time * fs samples. If output is supplied it is played in parallel (soundcard playback blocks until played; NI and mock playback run alongside the wait).
  • Pretrigger armed (pretrig_samples set): waits up to settings.pretrig_timeout seconds for the channel settings.pretrig_channel to exceed settings.pretrig_threshold in magnitude, then up to a further stored_time + 5 seconds for the post-trigger part of the window to fill. The timeout therefore bounds the wait for the EVENT only; a long capture cannot expire it. When an output stimulus is supplied it starts about 1 s after arming, and the timeout clock starts once the stimulus is playing. On trigger, the returned window of stored_time * fs samples has the first sample above threshold at exactly index pretrig_samples, so samples [0, pretrig_samples) are pre-trigger context. On timeout with no trigger nothing is raised: the most recent stored_time * fs samples are returned, as in the no-pretrigger mode, and a "not detected" message is printed.

A stream that is already running with matching settings is reused (soundcard and NI alike), so back-to-back captures are cheap and the buffer already holds real history. A freshly opened stream is given time to deliver a full window of real samples before the data is read, so a capture does not start with the stream's startup zeros.

Pretrigger limits. pretrig_samples must not exceed chunk_size (the recorder keeps only one chunk of pre-trigger context; use a larger chunk_size for a longer pre-trigger window) and must be less than stored_time * fs. The threshold is compared in the units the recorder stores: volts on NI, and on a sound card volts once VmaxSC is set but full-scale units while it is 1.0 (uncalibrated). Calibrating a sound card therefore changes what a given threshold number means.

Capture rate and delivered rate. fs is the rate of the returned data. The converter may run at a different rate, chosen by streams.select_capture_fs:

  • the device cannot run at fs (for example any sound card asked for 3 kHz): the capture runs at the lowest rate the device can and is resampled down, even with lpf_on off, rather than leaving the operating system to resample at unknown quality;
  • lpf_on is set: the capture deliberately runs above fs for the anti-alias filter and some noise reduction; how far above is set by settings.oversample (see streams.oversample_strategy);
  • capture_fs is set: that capture rate is used outright.

In every case the data (pretrigger alignment included) is resampled to fs with a linear-phase anti-alias filter (analysis.resample_to_fs: passband to fs/2.56, 96 dB stopband at fs/2, zero-phase), and the returned settings record the real capture rate as lpf_capture_fs. chunk_size and pretrig_samples keep their meaning at fs. The capture falls back to unfiltered logging at fs (with a printed note) when there is no headroom to oversample into, or when the device refuses to open a stream at the oversampled rate. On a sound card, playback shares the capture clock, so when input and output are the same device (streams.output_shares_input_clock) an output stimulus is resampled onto the capture rate.

Warnings. Progress and warnings are printed and the last one is kept in acquisition.MESSAGE. A clipping warning is printed when any raw sample (before resampling) of an input channel exceeds 95 % of that channel's full scale (settings.input_vmax_channels(): VmaxNI on NI, the channel's VmaxSC otherwise), naming the channels; a drive column prepended by use_output_as_ch0 is not checked. Input the host reported as dropped is counted into acquisition.LAST_CAPTURE_OVERFLOWS, and stretches of exact all-channel zeros inside the capture into acquisition.LAST_CAPTURE_DROPOUTS (see exact_zero_dropouts); either prints a warning, because the data then has gaps that corrupt TF and coherence results.

Parameters:

  • settings (MySettings) –

    Acquisition configuration. See pydvma.options.MySettings.

  • test_name (str, default: None ) –

    Stored on the returned TimeData for labelling.

  • rec (object, default: None ) –

    Ignored. Accepted so that older code which passes a cached recorder still runs; the stream is always started (or reused) from settings.

  • output (ndarray, default: None ) –

    Signal to play during the capture, in volts, shape (N_samples, output_channels), for example from signal_generator. On NI it is sent as it is and must stay within ±output_VmaxNI; on a sound card it is divided by output_VmaxSC to give the ±1 normalised samples the device expects.

  • cancel_event (Event, default: None ) –

    Cooperative stop. Every wait in the capture checks it every CANCEL_POLL_INTERVAL (0.05 s); once it is set, any playing stimulus is stopped and CaptureCancelled is raised instead of returning data. The one wait that cannot be interrupted is playback on a separate soundcard output device. None (the default) is plain blocking behaviour.

Returns:

  • dataset ( DataSet ) –

    One TimeData in volts (full-scale units on an uncalibrated sound card), with channel_cal_factors set to 1 / settings.channel_sensitivities. If settings.use_output_as_ch0 is True and output was given, the output signal is prepended as extra leading column(s) with a calibration factor of 1.

Raises:

  • CaptureCancelled –

    cancel_event was set before the capture finished.

  • ValueError –

    pretrig_samples exceeds chunk_size, or leaves no post-trigger data (>= stored_time * fs).

Output Signals

output_signal

output_signal(settings, output, cancel_event=None)

Start playing output (in volts) on the configured output device.

Usually called for you by log_data (pass it output=); call it directly only to play a signal without capturing.

On a sound card the signal is divided by output_VmaxSC to give the ±1 normalised float32 samples sounddevice expects, then written through streams.setup_output_soundcard. When input and output are the same device it plays through the running capture stream itself (one full-duplex stream; a second stream on the same device silences the capture on macOS), otherwise through a separate sd.OutputStream. Either way the write blocks until the stimulus has been handed to the stream. On NI the voltage array is passed straight to streams.setup_output_NI, whose AO task runs with ±output_VmaxNI rails, and the task is started without waiting.

Parameters:

  • settings (MySettings) –

    Selects the output device (output_device_driver, output_device_index) and its full-scale voltage (output_VmaxSC / output_VmaxNI).

  • output (ndarray) –

    Signal in volts, shape (N_samples, output_channels), for example from signal_generator.

  • cancel_event (Event, default: None ) –

    Makes same-device soundcard playback cancellable: the playback wait checks it and stops the stimulus as soon as it is set. Playback on a separate soundcard output device, and NI output, ignore it.

Returns:

  • stream ( object ) –

    The started output stream or task, which log_data later stops; None (after printing a message) if settings.output_device_driver is not 'soundcard', 'nidaq' or 'mock'.

signal_generator

signal_generator(settings, sig='gaussian', T=1, amplitude=0.1, f=None, selected_channels='all')

Create an output waveform in volts, ready to pass to log_data.

The waveform is T seconds long at settings.output_fs, with a raised-cosine fade-in and fade-out of min(T/10, 0.1) seconds at each end. What amplitude means depends on sig:

  • 'gaussian' (the default): Gaussian white noise whose STANDARD DEVIATION is amplitude, truncated at the output rail (±settings.output_vmax()); it is not a peak bound. With f given, the noise is band-pass filtered to f and rescaled to an rms of amplitude.
  • 'uniform': uniform white noise between ±amplitude. With f given, it is band-pass filtered and rescaled to an rms of amplitude.
  • 'sweep': a linear chirp of peak amplitude from f[0] to f[1] over T seconds; f defaults to 0 to output_fs/2.

Any other sig prints a message and returns zeros. The band-pass filter is a 3rd-order Butterworth, applied forwards and backwards.

If the finished waveform's peak exceeds the output rail settings.output_vmax() (output_VmaxNI when output_device_driver='nidaq', output_VmaxSC otherwise), the WHOLE waveform is scaled down so its peak equals the rail, and an OutputRescaledWarning says so (the new rms is also stored in acquisition.MESSAGE). Plain Gaussian noise never triggers this: it is a truncated normal, so it already stays inside the rail.

Parameters:

  • settings (MySettings) –

    Supplies output_fs, output_channels and the output rail.

  • sig (str, default: 'gaussian' ) –

    'gaussian', 'uniform' or 'sweep'.

  • T (float, default: 1 ) –

    Duration in seconds (default 1).

  • amplitude (float, default: 0.1 ) –

    Level in volts (default 0.1); see above for what it means for each sig.

  • f (list[float], default: None ) –

    [f_low, f_high] in Hz: the sweep range, or the noise pass band. None gives unfiltered noise, or a sweep from 0 to output_fs/2.

  • selected_channels (str or list[int], default: 'all' ) –

    Output columns to fill; the others stay zero. 'all' (the default) fills every one of the settings.output_channels columns.

Returns:

  • t ( ndarray ) –

    Sample times in seconds, arange(N) / output_fs with N = ceil(T * output_fs), so every time is below T.

  • y ( ndarray ) –

    The waveform in volts, shape (len(t), output_channels).

Warns:

  • OutputRescaledWarning –

    If the waveform was scaled down to fit the output rail, so it plays at less than the requested level.

OutputRescaledWarning

Bases: UserWarning

Warned when signal_generator scales a waveform down to the output rail.

A class of its own so a script can filter it, and so pydvma-serve can pass it on to the browser app as a toast.

multisine_generator

multisine_generator(settings, spec)

Create a periodic random-phase multisine buffer for a BLA capture.

One period is N = spec['n_samples'] samples exciting integer DFT bins k1..k2 (inclusive, satisfying 1 <= k1 <= k2 <= (N-1)//2 -- violating this raises ValueError naming k1, k2 and N) with equal amplitudes and uniform random phases drawn from numpy.random.default_rng([seed, m]) — so a saved spec reproduces the waveform exactly. Both the excitation index q (0..n_exc-1) and the experiment index e (0..n_exc-1) are zero-based; experiment e applies the orthogonal DFT-matrix rotation (phase shift -2*pi*q*e/n_exc on excitation q), which keeps every channel's amplitude spectrum identical across the n_exc experiments of a realisation.

Unlike signal_generator this applies NO fade window and NO peak rescale — both would break exact periodicity. amp_rms sets the per-channel RMS (identical across realisations, keeping the excitation class constant); if the resulting peak exceeds settings.output_vmax() a ValueError is raised — lower the level.

Parameters:

  • settings (MySettings) –

    output_fs (the time axis), output_channels (checked against n_exc) and the output voltage rail are consulted.

  • spec (dict) –

    MultisineSpec dict with keys n_samples, k1, k2, p_periods, t_periods, seed, m, e, n_exc, amp_rms. t_periods transient periods come first, then p_periods steady-state periods. See the web logger's Nonlin-stage guide for the design vocabulary (M realisations, P periods, excited bins k1/k2): https://torebutlin.github.io/pydvma/web-logger/nonlin/.

Returns:

  • t ( ndarray ) –

    Sample times in seconds at settings.output_fs.

  • y ( ndarray ) –

    The waveform in volts, C-contiguous, shape ((t_periods + p_periods) * n_samples, n_exc), ready for log_data(..., output=y).

Raises:

  • ValueError –

    The bins violate 1 <= k1 <= k2 <= (N-1)//2, n_exc < 1, t_periods + p_periods < 1, e is outside [0, n_exc), n_exc exceeds settings.output_channels, or the peak exceeds settings.output_vmax().

Stream Monitoring

stream_snapshot

stream_snapshot(rec)

Capture the live oscilloscope buffer as a TimeData.

Unlike log_data, which blocks for stored_time seconds and returns a fresh capture, this is a non-blocking copy of the oscilloscope buffer of the running stream: the most recent num_chunks * chunk_size samples already in memory. Useful for checking what a running stream is doing from a notebook.

Requires a live stream: call streams.start_stream(settings) first, or run log_data, which starts one. On a sound card the samples are scaled by settings.VmaxSC (volts once it is set, full-scale units while it is 1.0); on NI they are volts.

Parameters:

  • rec (object) –

    Ignored; accepted for compatibility with older code. The snapshot is always taken from the module-level streams.REC (the stream most recently started).

Returns:

  • time_data ( TimeData ) –

    The oscilloscope time axis and buffer, with test_name='stream_snapshot' and the stream's settings. No calibration is applied: channel_cal_factors are all ones and units is None.

Cancelled Captures and Dropouts

CaptureCancelled

Bases: Exception

Raised by log_data when its cancel_event is set mid-capture.

Signals that no data was returned on purpose — the caller asked the capture to stop — as opposed to a hardware failure. Any stimulus playing at the time is stopped before this propagates. The pydvma serve bridge turns it into a status/cancelled frame, sent instead of the usual log_result.

exact_zero_dropouts

exact_zero_dropouts(data, fs, full_scale=1.0, min_run=None, silent_fraction=0.001)

Count stretches of exact digital silence inside a live capture.

Counts the runs of at least min_run (default DROPOUT_MIN_RUN) consecutive frames in which EVERY channel of data is exactly zero, and the time they add up to at fs Hz.

Two exclusions keep this honest. A run touching the first sample is not counted — leading zeros are the fresh-stream startup shortfall that _wait_for_buffer_fill already handles, not a mid-capture gap. And a record whose peak is below silent_fraction of full_scale returns (0, 0.0) outright: with nothing plugged in, a 16-bit host (MME) legitimately delivers long exact-zero runs, and there is no coherence in a silent record to protect anyway. With a per-channel full_scale the record is silent only when every channel's peak is below that fraction of its OWN full scale, so a high-gain channel (a few millivolts full scale) is not judged against a line-level neighbour's rail.

Why exact zeros are a fault signature at all: a connected analogue input never produces eight consecutive all-channel zeros — dither and the noise floor keep the converter busy (2e-6 FS on a Scarlett 2i2 is ~34 LSB at 24 bits). A run of them is data the host substituted: the USB audio driver zero-filling lost packets (measured 2026-09-04, runs from 8 frames to 188 ms on a 2i2 4th Gen, PortAudio's input_overflow flag never set). Such a gap time-warps the record at each edge, which destroys TF coherence the same way a counted overflow does — so log_data reports them alongside LAST_CAPTURE_OVERFLOWS.

Parameters:

  • data (ndarray) –

    The capture, shape (samples, channels) or 1-D.

  • fs (float) –

    Sample rate in Hz.

  • full_scale (float or sequence, default: 1.0 ) –

    The input's full-scale value, in the units of data (default 1.0), or one per channel (truncated or padded with 1.0 to the number of columns).

  • min_run (int, default: None ) –

    Shortest run counted, in frames; None (the default) uses DROPOUT_MIN_RUN (8).

  • silent_fraction (float, default: 0.001 ) –

    A record whose peak is below this fraction of full_scale counts as silent and returns (0, 0.0) (default 1e-3).

Returns:

  • n_runs ( int ) –

    The number of all-zero runs found.

  • total_seconds ( float ) –

    Their combined duration in seconds.

Devices

Run list_available_devices() before writing a MySettings to see what is plugged in, which backend to drive each device through, and whether its readings will be in volts or only in full-scale units. Pass MySettings(device='name') to select a device by name rather than by index; resolve, also exported as dvma.resolve_device_spec, does the matching.

list_available_devices

list_available_devices(io='', kind='input', rates=True, raw=False)

Print what is plugged in, and what pydvma knows about it.

The pre-choice step: run this before writing a MySettings, and it tells you which devices are present, which backend to drive each one through, and — the part no raw enumeration can tell you — whether a device's readings will be in VOLTS or merely in full-scale units.

Grouped by physical device rather than by enumeration slot, because on Windows one interface is listed once per host API (an ESI U24 XL fills seven of the 38 rows here) and those entries differ in word length and in whether they will resample silently. See pydvma.devices.format_inventory.

Parameters:

  • io (str, default: '' ) –

    Legacy substring filter on device names, kept so existing calls behave as before. Empty shows everything.

  • kind (str, default: 'input' ) –

    'input' (default), 'output' or 'all'.

  • rates (bool, default: True ) –

    Probe each device's genuine sample-rate ladder. A few driver round-trips per device; pass False to skip.

  • raw (bool, default: False ) –

    Print the old flat index-ordered enumeration instead of the grouped report — useful when you need to see exactly what PortAudio returned.

Returns:

  • report ( str ) –

    The report that was printed.

resolve

resolve(spec, driver='soundcard', kind='input', fs=None)

Find the device index a human-written name refers to.

Parameters:

  • spec (str or int) –

    A device index (returned unchanged), or a case-insensitive substring of the device name, e.g. 'U24XL'.

  • driver (str, default: 'soundcard' ) –

    'soundcard' or 'nidaq'.

  • kind (str, default: 'input' ) –

    'input' or 'output'.

  • fs (float or None, default: None ) –

    Intended sample rate. When given, a backend that cannot genuinely clock it is passed over in favour of one that can, rather than being chosen and silently resampling.

Returns:

  • index ( int ) –

    The chosen device index.

  • entry ( dict ) –

    Its describe record.

  • note ( str ) –

    A sentence explaining the choice (which backend and why), suitable for printing.

Raises:

  • ValueError –

    The spec matches no device, or more than one physical device; the message names every candidate, since guessing between two interfaces is exactly the mistake this function exists to prevent.

inventory

inventory(driver='soundcard', kind='input', rates=True, channels=2)

Physical devices present, each with its available backends.

Groups the per-host-API entries of one piece of hardware into a single record, which is the unit an operator actually thinks in. Grouping is by normalised name, tolerating the 31-character truncation MME applies. It is deliberately conservative: where a host API renames a device beyond recognition (PortAudio's WDM-KS builds its own name from the kernel-streaming filter, which on a Scarlett 2i2 embeds the USB product id and looks nothing like the endpoint name) the entries stay separate. Two rows for one box is a smaller error than merging two different boxes into one row.

Parameters:

  • driver (str, default: 'soundcard' ) –

    'soundcard' or 'nidaq'.

  • kind (str, default: 'input' ) –

    'input', 'output' or 'all'.

  • rates (bool, default: True ) –

    Probe genuine rate ladders.

  • channels (int, default: 2 ) –

    Channel count to probe rates with.

Returns:

  • devices ( list[dict] ) –

    One dict per physical device, with keys 'name', 'profile', 'status', 'full_scale_volts', 'advice', 'channel_roles' and 'entries', the last being that device's per-backend records (see describe) sorted best first. Empty when PortAudio (or nidaqmx) is unavailable.

format_inventory

format_inventory(driver=None, kind='input', rates=True, legend=True)

Render the device inventory as a printable report.

One block per physical device: what it is, whether its voltage scale is KNOWN or merely assumed, and every backend it can be driven through with the recommended one marked. Backs streams.list_available_devices and pydvma-serve --list-devices.

Output is deliberately ASCII: this prints to a Windows console, where the default code page mangles the en/em dashes used elsewhere in the codebase.

Parameters:

  • driver (str or None, default: None ) –

    Restrict to one driver, or None for every driver available.

  • kind (str, default: 'input' ) –

    'input', 'output' or 'all'.

  • rates (bool, default: True ) –

    Probe genuine rate ladders (a few driver round-trips per device).

  • legend (bool, default: True ) –

    Append the explanation of the calibration statuses and the >> marker.

Returns:

  • report ( str ) –

    The report text (it is not printed here).

calibration_status

calibration_status(name, neighbours=None, input_gain_db=None, input_mode='line')

How much pydvma really knows about this device's volts.

The distinction that keeps an assumption from passing for a fact. Sample rates and channel counts come from the driver and are equally knowable for any interface; the volts-per-full-scale does not, and without it a "voltage" reading is a normalised number wearing a unit.

Parameters:

  • name (str or None) –

    PortAudio device name.

  • neighbours (list or None, default: None ) –

    Every device name currently present, for the indirect Windows profile match — see _soundcard_specs.device_profile.

  • input_gain_db (float or None, default: None ) –

    Preamp gain the operator has stated, if any.

  • input_mode (str, default: 'line' ) –

    Input mode for the full-scale lookup.

The status is one of:

  • 'characterised' — the device is in pydvma._soundcard_specs and its full scale is known, either because it is fixed-gain (nothing to mis-set) or because a gain was stated. VmaxSC is a real voltage.
  • 'needs_gain' — the model is recognised and its maximum input level is tabulated, but it has an analogue gain control that no audio API can read, so the operator must state input_gain_db before volts mean anything.
  • 'uncalibrated' — the model is not characterised. Everything the driver reports is still trustworthy; the voltage scale is not known and VmaxSC = 1.0 is a placeholder, so readings are effectively in full-scale units.

Returns:

  • status ( str ) –

    'characterised', 'needs_gain' or 'uncalibrated', as above.

  • full_scale_volts ( float or None ) –

    The input voltage at digital full scale, when known.

  • advice ( str ) –

    One sentence on what the status means for the readings and how to improve it.

preferred_backend

preferred_backend(group)

The entry of a device group that should be driven, or None.

Best-ranked host API first (see HOSTAPI_RANK). This encodes a measurement, not a preference: on Windows the shared-mode APIs both truncate the word and accept sample rates the hardware cannot clock, so choosing MME — which is what sd.default.device points at on this bench — silently costs 8 bits and can hand back a "96 kHz" capture containing nothing above 22 kHz.

Parameters:

  • group (dict) –

    One device record from inventory, whose 'entries' are already sorted best backend first.

Returns:

  • entry ( dict or None ) –

    The first (best-ranked) entry, as described by describe, or None when the group has no entries.

National Instruments devices

suggest_ni_settings

suggest_ni_settings(device_index)

Return MySettings keyword arguments with safe defaults for an NI device.

Picks conservative values that will not trigger DAQmx range or rate errors out of the box: the largest symmetric voltage range the device reports (10 V for AI and 5 V for AO if it reports none), a terminal configuration the module accepts (pseudo-differential on the NI 9234, RSE otherwise), and a sample rate of a quarter of the lower of the AI and AO maximum rates, capped at 12.5 kHz, raised to the devices' minimum rates if needed and rounded to 100 Hz. On a cDAQ chassis the first module with AI and the first with AO are used.

Parameters:

  • device_index (int) –

    Index into the NI device list, in which a cDAQ chassis and its modules count as one device (the order shown by list_available_devices).

Returns:

  • kwargs ( dict ) –

    Keyword arguments for MySettings(...): device_driver, device_index, output_device_driver, output_device_index, NI_mode, VmaxNI, output_VmaxNI, fs and output_fs. Add your own channels=, stored_time= and so on when constructing.

Raises:

  • RuntimeError –

    nidaqmx is not installed, or no NI device is found.

  • ValueError –

    device_index is out of range.

get_device_info

get_device_info(device_name)

Query a live NI device's capabilities via nidaqmx.

Parameters:

  • device_name (str) –

    DAQmx device name, e.g. 'Dev1' or 'cDAQ1Mod1' (a module, not the chassis, for a cDAQ).

Returns:

  • info ( dict ) –

    Keys name, product_type, product_category (the nidaqmx ProductCategory member), ai_voltage_ranges and ao_voltage_ranges as [(min, max), ...] lists, ai_max_single_chan_rate, ai_min_rate, ao_max_rate and ao_min_rate as floats (None where the device has no AI or no AO), and ai_current_int_excit_discrete_vals, the legal IEPE excitation currents in amps (empty when IEPE is not supported; [0.0, 0.002] on an NI 9234). Entries from the QUIRKS table for this product type (terminal configurations, sampling type, notes) are merged in.

Raises:

  • RuntimeError –

    nidaqmx is not installed.

Unused Settings Class

Output_Signal_Settings is not used by pydvma. It is kept so that old code which constructs it still imports. To define a stimulus, use signal_generator with log_data(output=...), or the output group in the web logger's Acquire stage.

Output_Signal_Settings

Output_Signal_Settings(type='None', amp=0, f1=0, f2=0)

Bases: object

Four output-signal fields kept so that existing code still imports.

Nothing in pydvma reads this class any more: it pre-filled the output panel of the desktop logger, which was removed in 2.0.0. It is kept so that scripts which create one keep working. To generate an output, call acquisition.signal_generator and pass the result to log_data(output=...) (see the Data Acquisition user guide).

Parameters:

  • type (str, default: 'None' ) –

    Stored as the type attribute.

  • amp (float, default: 0 ) –

    Stored as the amp attribute.

  • f1 (float, default: 0 ) –

    Stored as the f1 attribute.

  • f2 (float, default: 0 ) –

    Stored as the f2 attribute.

Attributes:

  • type (str) –

    Waveform name: 'None' (the default), 'sweep', 'gaussian' or 'uniform', the values of signal_generator's sig.

  • amp (float) –

    Amplitude in volts (default 0).

  • f1 (float) –

    Lower frequency in Hz (default 0).

  • f2 (float) –

    Upper frequency in Hz (default 0).