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_modeandinput_padaccept one value (meaning every channel) or a list of lengthchannels, indexed in captured-column order — on a cDAQ chassis that is slot order (seeinput_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'smax_input_channelsatstart_streamtime (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 raisesValueErrorif 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 onpretrig_samples. -
num_chunks(int) –Chunks held in the oscilloscope circular buffer (default
6); recomputed fromviewed_timewhen set. -
viewed_time(float or None) –Oscilloscope display window in seconds (default
0.3). When set, overridesnum_chunksasceil(viewed_time * fs / chunk_size). Set to None to size the oscilloscope buffer directly fromnum_chunksinstead. -
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 exceedchunk_size(the pretrigger buffer holds only one chunk of pre-trigger context), and must be less thanstored_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
VmaxSCis set and full-scale units while it is left at 1.0 (uncalibrated) — the samples are scaled byVmaxSCon 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 givenstored_time + 5seconds 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_datacaptures ABOVEfsand resamples down behind a linear-phase anti-alias FIR (analysis.resample_to_fs— passband tofs/2.56, 96 dB stopband atfs/2).fskeeps its normal meaning (the rate you log at); the toggle changes only HOW that rate is achieved — oversample + noise-reducing decimation instead of sampling atfsdirectly. How far abovefsthe capture runs is set byoversample; on a device with a published rate ladder it is one of that device's real rates, otherwise an integer multiple offsunder the device maximum. The logged settings record the capture rate aslpf_capture_fs. NOTE the capture rate can differ fromfswith this toggle OFF too: a device that cannot run atfsat 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
fsto 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 — seestreams.oversample_strategy. -
capture_fs(float) –Force the rate the hardware runs at, in Hz, overriding the automatic choice (default
None= auto).fsis what you want delivered; this is what the converter actually samples at before pydvma decimates down tofs. Auto picks the lowest rate the device can genuinely run that coversfs, 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 leastfs. -
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;
Nonepicks 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 withdvma.list_available_devices()(its nidaq section is indexed the same waydevice_indexis). -
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 indevice_index,device_nameanddevice_hostapitogether. 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 onfs. The choice and its reason are printed. RaisesValueErrorlisting the candidates if the name matches no device, or more than one. An int is taken as an index. Runstreams.list_available_devicesto see what is present and what pydvma knows about each device's voltage scale. -
device_name(str or None) –Exact enumerated name that
device_indexis expected to refer to (defaultNone). Device indices are positions in an enumeration, not identities, and the enumeration reorders — so when this is set,streams.start_streamverifies 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_streamrecords 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_indexwas chosen on, e.g.'Windows WDM-KS'(defaultNone, 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, sodevice_namealone 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 toadd_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 letsVmaxSCbe 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 explicitVmaxSC. Only applies to interfaces characterised inpydvma._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:VmaxSCis derived automatically when this isNoneandVmaxSCis left at its default. An interface with a preamp per channel (the Audient iD44, four gain knobs) takes a list of lengthchannelsinstead, e.g.[60, 60, None, 0]: each channel'sVmaxSCis derived from its own entry, and aNoneentry leaves that channel'sVmaxSCas 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 (theirVmaxSCis 1.0 unless given per channel), soVmaxSCbecomes 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 withinput_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), orValueErrornames 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'spad_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);Truethere on an interface with no pad raisesValueError. -
VmaxSC(float or sequence) –Soundcard input calibration (default
1.0) — the jack voltage corresponding to a normalised reading of 1.0. Default1.0treats 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 throughinput_vmax/input_vmax_channelsrather 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 lengthchannels. Only NI 9234-class DSA modules support it; the legal discrete values on the 9234 are0.0and0.002(2 mA), validated against the module that actually owns each channel. A channel with current> 0is switched to AC coupling and the recorder blocks ~2 s after start for the sensor bias to settle through the AC-coupling HPF. Requiresdevice_driver='nidaq'(raisesValueErrorotherwise). 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 lengthchannelsand every value must be non-zero.log_datastores the reciprocal asTimeData.channel_cal_factors, which plotting and modal fitting apply automatically, so a100 mV/gaccelerometer (0.1here) gives a cal factor of10and plots read ing. The storedtime_dataarray 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.
Nonefollows the resolveddevice_indexwhen the output driver matches the input driver and the input device can play (forsoundcard, when it reports output channels — a USB audio interface drives its own outputs; a capture on it then runs as ONE full-duplex stream, seepydvma.streams.Recorder.init_stream). Otherwise:soundcardfalls back to the default output device (a microphone-only input cannot play the stimulus), andnidaq/mockto 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 anoutput=array is passed tolog_data. -
output_channels_spec(str or None) –Raw DAQmx physical-channel string for the AO task, e.g.
'cDAQ1Mod2/ao0'; the output analogue ofinput_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
VmaxSCwhen that is one number (every channel equal), as on the Scarlett 2i2 and ESI U24 XL. It defaults to1.0instead, i.e. the generated output is in normalised ±1 units until you set it, with a per-channelVmaxSCand 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
Trueand anoutputarray is passed tolog_data, the generated drive signal is prepended as channel 0 of the recorded data (defaultFalse). 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 ¶
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) whendevice_driver='nidaq'; otherwiseVmaxSC, the sound card's full-scale voltage (1.0 when uncalibrated, so readings are in full-scale units). With a per-channelVmaxSC, thatchannel's entry, or the largest entry whenchannelis 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-channelVmaxSCreads 1.0 (seeinput_vmax_channels).
Raises:
-
IndexError–A negative
channel.
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 ¶
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 ¶
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_VmaxNIwhenoutput_device_driver='nidaq'; otherwiseoutput_VmaxSC.
pretrig_level ¶
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 ¶
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, waitssettings.stored_timeseconds, and returns the most recentstored_time * fssamples. Ifoutputis supplied it is played in parallel (soundcard playback blocks until played; NI and mock playback run alongside the wait). - Pretrigger armed (
pretrig_samplesset): waits up tosettings.pretrig_timeoutseconds for the channelsettings.pretrig_channelto exceedsettings.pretrig_thresholdin magnitude, then up to a furtherstored_time + 5seconds 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 anoutputstimulus is supplied it starts about 1 s after arming, and the timeout clock starts once the stimulus is playing. On trigger, the returned window ofstored_time * fssamples has the first sample above threshold at exactly indexpretrig_samples, so samples[0, pretrig_samples)are pre-trigger context. On timeout with no trigger nothing is raised: the most recentstored_time * fssamples 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 withlpf_onoff, rather than leaving the operating system to resample at unknown quality; lpf_onis set: the capture deliberately runs abovefsfor the anti-alias filter and some noise reduction; how far above is set bysettings.oversample(seestreams.oversample_strategy);capture_fsis 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
TimeDatafor 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 fromsignal_generator. On NI it is sent as it is and must stay within±output_VmaxNI; on a sound card it is divided byoutput_VmaxSCto give the±1normalised 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 andCaptureCancelledis 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
TimeDatain volts (full-scale units on an uncalibrated sound card), withchannel_cal_factorsset to1 / settings.channel_sensitivities. Ifsettings.use_output_as_ch0is True andoutputwas given, the output signal is prepended as extra leading column(s) with a calibration factor of 1.
Raises:
-
CaptureCancelled–cancel_eventwas set before the capture finished. -
ValueError–pretrig_samplesexceedschunk_size, or leaves no post-trigger data (>= stored_time * fs).
Output Signals¶
output_signal ¶
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 fromsignal_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_datalater stops; None (after printing a message) ifsettings.output_device_driveris not'soundcard','nidaq'or'mock'.
signal_generator ¶
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 isamplitude, truncated at the output rail (±settings.output_vmax()); it is not a peak bound. Withfgiven, the noise is band-pass filtered tofand rescaled to an rms ofamplitude.'uniform': uniform white noise between±amplitude. Withfgiven, it is band-pass filtered and rescaled to an rms ofamplitude.'sweep': a linear chirp of peakamplitudefromf[0]tof[1]overTseconds;fdefaults to 0 tooutput_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_channelsand 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 tooutput_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 thesettings.output_channelscolumns.
Returns:
-
t(ndarray) –Sample times in seconds,
arange(N) / output_fswithN = ceil(T * output_fs), so every time is belowT. -
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 ¶
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 againstn_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_periodstransient periods come first, thenp_periodssteady-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 forlog_data(..., output=y).
Raises:
-
ValueError–The bins violate
1 <= k1 <= k2 <= (N-1)//2,n_exc < 1,t_periods + p_periods < 1,eis outside[0, n_exc),n_excexceedssettings.output_channels, or the peak exceedssettings.output_vmax().
Stream Monitoring¶
stream_snapshot ¶
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_factorsare all ones andunitsis 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 ¶
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_scalecounts 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 ¶
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 ¶
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
describerecord. -
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 ¶
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 (seedescribe) sorted best first. Empty when PortAudio (or nidaqmx) is unavailable.
format_inventory ¶
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
Nonefor 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 ¶
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 inpydvma._soundcard_specsand its full scale is known, either because it is fixed-gain (nothing to mis-set) or because a gain was stated.VmaxSCis 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 stateinput_gain_dbbefore volts mean anything.'uncalibrated'— the model is not characterised. Everything the driver reports is still trustworthy; the voltage scale is not known andVmaxSC = 1.0is 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 ¶
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 ¶
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,fsandoutput_fs. Add your ownchannels=,stored_time=and so on when constructing.
Raises:
-
RuntimeError–nidaqmx is not installed, or no NI device is found.
-
ValueError–device_indexis out of range.
get_device_info ¶
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 nidaqmxProductCategorymember),ai_voltage_rangesandao_voltage_rangesas[(min, max), ...]lists,ai_max_single_chan_rate,ai_min_rate,ao_max_rateandao_min_rateas floats (None where the device has no AI or no AO), andai_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 theQUIRKStable 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 ¶
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
typeattribute. -
amp(float, default:0) –Stored as the
ampattribute. -
f1(float, default:0) –Stored as the
f1attribute. -
f2(float, default:0) –Stored as the
f2attribute.
Attributes:
-
type(str) –Waveform name:
'None'(the default),'sweep','gaussian'or'uniform', the values ofsignal_generator'ssig. -
amp(float) –Amplitude in volts (default
0). -
f1(float) –Lower frequency in Hz (default
0). -
f2(float) –Upper frequency in Hz (default
0).