File Operations Module¶
Functions for importing, exporting, and saving data in various formats.
Load and Save¶
load_data ¶
Loads a dataset from filename.
The filename can be given positionally, load_data('name.dvma'),
or as filename=, and is required: there is no file dialog.
Detection is by content for .dvma (zip magic bytes) and CSV (the
first line names the format); .mat and legacy .npy fall back
to extension:
.dvmacontainer files (zip magic bytes) — the default format since 1.5.0; safe, pickle-free (seecontainer).- legacy
.npypickle saves from pydvma <= 1.4.0 — supported forever. Trust model: the legacy path usesnp.load(allow_pickle=True), and unpickling can execute arbitrary code, so only open legacy .npy files you or your lab created..dvmafiles do not have this caveat. - pydvma's own CSV and MATLAB exports (
export_to_csv,export_to_matlab, and the web app's Export CSV / Export Matlab): they hold what a .dvma holds and load back exactly. Exports from pydvma 2.6 and earlier could not be read back and raise ValueError. .matfiles from Jim Woodhouse's MATLAB logger, viaimport_from_matlab_jwlogger.- the CSV that the Vibration Apps' Transfer function app saves
(first line names
vibration-apps-tf-csv), viaimport_from_vibration_apps_csv. Any other.csvraises ValueError.
Parameters:
-
parent(optional, default:None) –Deprecated and ignored, and going in pydvma 3.0 (it was the Qt file dialog's parent). A str or path here is taken as the filename.
-
filename(str or PathLike, default:None) –File to load, given positionally or as
filename=.
Returns:
-
dataset(DataSet or None) –The loaded data, or None if the file is none of the above and its extension is not .csv.
Raises:
-
FileNotFoundError–If
filenamedoes not exist. -
ValueError–If a
.dvmafile is not a valid container, a.matfile is neither a pydvma export nor a JW-logger file, a.csvfile is neither a pydvma export nor a Vibration Apps CSV this version reads, or an export was changed after it was written or comes from pydvma 2.6 or earlier. -
TypeError–If no filename is given.
save_data ¶
Saves a DataSet to 'filename.dvma' (the .dvma container format, a zip
of manifest.json + pickle-free .npy arrays; see container).
The filename can be given positionally, save_data(dataset,
'name.dvma'), or as filename=; .dvma is added when it ends
in neither .dvma nor .npy. If that file already exists you
are asked at the terminal whether to overwrite it, unless
overwrite_without_prompt is True. The filename is required: there
is no file dialog.
Legacy escape hatch: an explicit filename ending in .npy
writes the pre-1.5.0 pickle format instead, for workflows that
still need it. New saves should prefer .dvma — it is safe to
share (loading executes no code) and readable outside Python.
Parameters:
-
dataset(DataSet) –An object of the class DataSet
-
parent(optional, default:None) –Deprecated and ignored, and going in pydvma 3.0 (it was the Qt file dialog's parent). A str or path here is taken as the filename.
-
filename(str or PathLike, default:None) –Output filename, given positionally or as
filename=. -
overwrite_without_prompt(bool, default:False) –If True, overwrite an existing file without asking.
-
sets(int or Iterable[int], default:None) –If given, writes
dataset.subset(sets)instead of the whole dataset — the notebook counterpart of the web app's Save "Choose sets…" picker (seedatastructure.DataSet.subsetfor the exact inclusion rule).None(the default) writesdatasetunchanged.
Returns:
-
filename(str or None) –The file written, or None if the overwrite was declined.
Raises:
-
TypeError–If no filename is given.
save_fig ¶
Saves a figure as both 'filename.png' and 'filename.pdf'.
Any extension on the filename is replaced, so both files are always
written. The filename can be given positionally, save_fig(plot,
'name'), or as filename=, and is required: there is no file
dialog.
Parameters:
-
plot(PlotData or Figure) –A PlotData object or matplotlib Figure object
-
parent(optional, default:None) –Deprecated and ignored, and going in pydvma 3.0 (it was the Qt file dialog's parent). A str or path here is taken as the filename.
-
figsize(tuple, default:None) –Size in inches for the saved files; the figure is restored to its own size afterwards.
-
filename(str or PathLike, default:None) –Output filename, given positionally or as
filename=. -
overwrite_without_prompt(bool, default:False) –If True, overwrite without asking
Returns:
-
filename(str or None) –The PDF written (the PNG is beside it), or None if the overwrite was declined.
Raises:
-
TypeError–If no filename is given.
Export Functions¶
The CSV and MATLAB exports write the stored values with no calibration
applied: volts, or full-scale units on an uncalibrated soundcard. They
record the calibration next to the data so that it is not lost. A CSV file starts with a #-commented header
listing cal_factors and units per data column (numpy.loadtxt and
pandas.read_csv(..., comment='#') skip it). A MATLAB file gains
time_cal_factors and time_units, and the freq_ and tf_ pairs
for those data. Multiply each data column by its factor to get
engineering units. The web logger's exports are described in
Saving & Exporting.
export_to_matlab ¶
Exports data to a MATLAB .mat file that load_data reads back.
The file holds exactly what a save_data .dvma holds (format
pydvma-mat 1), laid out for MATLAB:
pydvma_items: a cell array with one struct per item, in order:kind,test_name,units,fs,timestamp(ISO text),channel_cal_factors, and each array under its own name at its exact shape (time_axis,time_data,freq_axis,tf_data,tf_coherence,Pxy,sono_data,M, ...). In MATLAB,d = load('x.mat'); d.pydvma_items{2}.tf_data.pydvma_manifest: every item's metadata and settings as JSON text (jsondecode(d.pydvma_manifest)in MATLAB).pydvma_format:'pydvma-mat 1'.
Values are RAW (volts for a capture): multiply by the item's
channel_cal_factors for engineering units. Each measurement keeps
its own axis; nothing is interpolated. (pydvma 2.6 and earlier wrote
time_data_all / freq_data_all / tf_data_all on one common
grid instead, and could not read the file back.) The filename can be
given positionally, export_to_matlab(dataset, 'name.mat'), or as
filename=; .mat is added if missing. The filename is required:
there is no file dialog.
Parameters:
-
dataset(DataSet or data list) –The data: a whole DataSet, or one data list (
dataset.tf_data_list, ...). -
parent(optional, default:None) –Deprecated and ignored, and going in pydvma 3.0 (it was the Qt file dialog's parent). A str or path here is taken as the filename.
-
filename(str or PathLike, default:None) –Output filename, given positionally or as
filename=. -
overwrite_without_prompt(bool, default:False) –If True, overwrite without asking
Returns:
-
filename(str or None) –The file written, or None if the overwrite was declined.
Raises:
-
TypeError–If no filename is given, or
datasetis neither a DataSet nor a data list. -
ValueError–If there is no data to export.
export_to_matlab_jwlogger ¶
Exports a DataSet to 'filename.mat' in the JW-logger format.
Saved file is compatible with Jim Woodhouse logger file format, and
import_from_matlab_jwlogger reads it back. The filename can be
given positionally, export_to_matlab_jwlogger(dataset, 'name.mat'),
or as filename=; .mat is added if missing. The filename is
required: there is no file dialog.
The file holds up to two blocks, each resampled onto one grid:
- TIME: every channel of every TimeData as a column of
indata, at the highest sample rate, zero-padded after a shorter capture; withbuflen(the row count) andtsmax, the largest absolute value, which the logger uses as its time plot's y-limit. - SPECTRAL: the transfer functions if there are any (
tfun= 1, coherence not exported), otherwise the FFTs (tfun= 0), as the columns ofyspec, withnpts(the FFT length). The logger stores no frequency axis: it isrfftfreq(npts, 1/freq), at the finest spacing of the spectra, padded with 1 above a spectrum's band. Sonograms and cross-spectra are not exported.
freq is the sample rate, and one value serves both blocks, as in
the logger itself. With time data it is the time data's rate and the
spectra are laid on that rate's grid, so spectral data above half the
time data's rate is left out, with a warning. Without time data it is
the spectra's own sample rate. dt2 holds the column counts
[n_time, n_spectral, 0]. Values are the raw stored numbers, and
unlike export_to_matlab no calibration factors are written: the
logger's layout has no variable for them.
Parameters:
-
dataset(DataSet) –An object of the class DataSet
-
parent(optional, default:None) –Deprecated and ignored, and going in pydvma 3.0 (it was the Qt file dialog's parent). A str or path here is taken as the filename.
-
filename(str or PathLike, default:None) –Output filename, given positionally or as
filename=. -
overwrite_without_prompt(bool, default:False) –If True, overwrite without asking
Returns:
-
filename(str or None) –The file written, or None if the overwrite was declined.
Raises:
-
TypeError–If no filename is given.
export_to_csv ¶
Exports data to one CSV file that load_data reads back.
The file holds exactly what a save_data .dvma holds (format
pydvma-csv 1), laid out as tables a spreadsheet or pandas can read:
- a few
#lines saying what the file is, then every item's metadata and settings as JSON on one# manifest:line; - one table per item (and one of its own for an array that cannot
share the item's rows, such as a sonogram's frequency axis): a
# tableheading line (kind, name, units, calibration), a line of column names, then the rows. The rows run along the item's axis, so a TF table readsfreq_axis, tf_data[0].re, tf_data[0].im, tf_coherence[0]; complex values are.re/.imcolumn pairs; each measurement keeps its own length.
Values are RAW (volts for a capture): multiply by the item's
channel_cal_factors for engineering units. Numbers are written as
the shortest text that reads back to the same value, so nothing is
lost. To read one table with pandas, pass it the lines between its
# table line and the next (pd.read_csv(io.StringIO(...))).
(pydvma 2.6 and earlier wrote one kind per file on the first set's
axis, which could not be read back.)
The filename can be given positionally, export_to_csv(dataset,
'name.csv'), or as filename=; .csv is added if missing. The
filename is required: there is no file dialog.
Parameters:
-
data_list(DataSet or data list) –The data: a whole DataSet, or one data list (
dataset.time_data_list, ...). -
parent(optional, default:None) –Deprecated and ignored, and going in pydvma 3.0 (it was the Qt file dialog's parent). A str or path here is taken as the filename.
-
filename(str or PathLike, default:None) –Output filename, given positionally or as
filename=. -
overwrite_without_prompt(bool, default:False) –If True, overwrite without asking
Returns:
-
filename(str or None) –The file written, or None if the overwrite was declined.
Raises:
-
TypeError–If no filename is given, or
data_listis neither a DataSet nor a data list. -
ValueError–If there is no data to export.
format_cal_factor ¶
Render one calibration factor as text, as '%.12g'.
The form pydvma's CSV table headings use for an item's calibration
(the exact factors travel in the file's manifest). %.12g is short
enough to read, round-trips every realistic factor, and its C
semantics (exponential below 1e-4 or at/above 12 significant digits,
trailing zeros stripped) are pinned by the known-answer vectors in
CAL_FACTOR_FORMAT_VECTORS. Public since 2.5.0, when the web app's
CSV writer had a JavaScript twin of it; that writer is gone.
A non-finite factor renders as '1': the identity, matching how every
consumer already treats an unusable factor, rather than writing a nan
into a header a script may parse.
Import Functions¶
import_from_matlab_jwlogger ¶
Imports a JW-logger .mat file (Jim Woodhouse's MATLAB data logger).
Only JW-logger files can be imported here. pydvma's own MATLAB exports
are refused with a ValueError saying to use load_data (which reads
them; those from pydvma 2.6 and earlier cannot be read at all), as is
any other .mat with neither of the logger's indata / yspec
variables. The filename is required: there is no file dialog.
The conventions below were confirmed against the recovered MATLAB source
("Data logger V2.9a": specmenu.m save path, avtflogpars.m
averaged-TF computation, dospec.m):
- SPECTRAL files save
yspec, dt2, npts, freq, tfun.freqis the SAMPLE RATE,nptsthe FFT length, soyspechasnpts/2 + 1rows on the one-sided axisrfftfreq(npts, 1/freq)(df = freq/npts). - TIME files save
indata, buflen, freq, dt2, tsmax— there is NOnptsand notfun(JW's guitar_string captures confirmed this; the old import assumednptsand raised KeyError). The time axis comes fromindata's own length at fs =freq;buflenduplicates that length andtsmaxrecords the capture's scale (the data is already in physical units — do NOT rescale by it). tfunselects spectrum (0) / transfer function (1).dt2is the saveddtypevector[n_time_channels, n_yspec_columns, n_sonogram]— column COUNTS, not column types.- The averaged-TF logger writes
yspecas INTERLEAVED pairs[H1, coh1, H2, coh2, ...]— each output channel's H1-estimator TF followed by its coherence (avtflogpars.m:thing(:,2k-1) = cross/autoin;thing(:,2k) = |cross|^2/(autoin*autoout)). - The save menu also allows ARBITRARY column subsets ("Channels to save": one / all / displayed / custom) and files can be composited by the Add-on-load path — so real archives also contain bare-H files (coherence stripped) and multi-instrument H collections.
- The writer duplicates the first positive bin into the DC row
(
yspec(1,:) = yspec(2,:)), so the DC bin is cosmetic.
Import behaviour for TF files: coherence columns are detected
unambiguously (real-valued AND within [0, 1] — no measured complex FRF
is both). The documented interleaved [H, coh, ...] layout is
recognised and split with positional pairing; an equal split in any
other order pairs by order of appearance; files with no coherence
columns, or an ambiguous mix, import as before (every column a TF
channel — nothing is dropped).
Parameters:
-
filename(str or PathLike, default:None) –File to import, given positionally or as
filename=.
Returns:
-
dataset(DataSet) –The imported data.
Raises:
-
ValueError–If the file is not a JW-logger .mat file, including a .mat written by
export_to_matlab; if it lacksfreq, or hasyspecwithoutnptsortfun; or iftfunis neither 0 nor 1. -
TypeError–If no filename is given.
import_from_vibration_apps_csv ¶
Imports the CSV that the Vibration Apps' Transfer function app saves.
The app (https://torebutlin.github.io/vibration_apps/apps/frf/, used
in 3C6) measures speaker to microphone in a browser and saves every
measurement it holds as one CSV: format vibration-apps-tf-csv 1,
or vibration-apps-tf-csv 2 when its "time data" box is ticked,
which adds each measurement's time series after the transfer
functions. load_data recognises the file by its first line, so
load_data('x.csv') comes here too.
Each measurement gives, in the file's order and all named
m<no> <the app's name> with the app's card number:
- a
TimeData(format 2, when the measurement has time data; never for a stepped sine): channel 0 x, what was played (or the app's reference channel), channel 1 y, the microphone, moved earlier by the app's loop delay to the nearest sample so the two line up as the app analysed them. The time axis is rebuilt exactly from fs. - a
TfData:freq_axisthe measurement's own frequencies (they differ between measurements and need not be a uniform grid: a stepped sine's points);tf_dataH1 = S_xy/S_xx, one column, with the loop delay already out of its phase;tf_coherenceone column, or None for a result of one frame (the app leaves it empty: it is 1 by definition). - a
CrossSpecData, when the file has theGxx/Gyycolumns (not for a stepped sine): the 2x2 cross-spectral matrix from the auto-spectra, H1 and the coherence, in pydvma's convention (Pxya one-sided power spectrum, the app's density timesenbw_hz, the effective noise bandwidth of the app's window and frame length).
The items of one measurement share one id_link: the TimeData's
unique_id when there is time data, otherwise an id of their own,
so the web app shows each measurement as one set.
All are uncalibrated, microphone full scale per speaker full scale
(units '-', channel_cal_factors 1). settings carry
fs and device_name (the microphone, when the browser named
it); the TF's carry channels (outputs + 1) and ch_in.
timestamp is when the measurement was made, a timezone-aware UTC
datetime. The TF's source_settings hold calc
('vibration_apps_' + the kind: noise, sweep, sine,
file), window, N_frames, overlap, nperseg,
ch_in, and vibration_apps, every key=value of the app's as a
string plus its notes (a list), so the test signal, loop delay and
quality figures survive a .dvma round trip. There is no
source_signature: pydvma did not compute these.
An H1 with no phase anywhere (an |H| from the powers alone) is
imported with ' (|H| only, no phase)' added to its name,
source_settings['magnitude_only'] True, no cross-spectrum, and a
UserWarning: its phase and any modal fit to it are not meaningful.
The file's H2 and H_power columns are not imported. A measurement the
app was hiding when it saved is imported all the same. Keys and
columns this version does not know are ignored.
Parameters:
-
filename(str or PathLike, default:None) –File to import, given positionally or as
filename=.
Returns:
-
dataset(DataSet) –The measurements' TimeData, CrossSpecData and TfData.
Raises:
-
ValueError–If the file's first line does not name the format, including pydvma's own
export_to_csvfiles; if it names another version of it; or if columns, rows, time rows or a measurement's header line are missing. -
TypeError–If no filename is given.