pyfar.io#

Functions:

audio_formats()

Return a dictionary of available audio formats.

audio_subtypes([audio_format])

Return a dictionary of available audio subtypes.

convert_sofa(sofa)

Convert SOFA object to pyfar object.

default_audio_subtype(audio_format)

Return the default subtype for a given format.

read(filename)

Read any compatible pyfar object or numpy array (.far file) from disk.

read_audio(filename[, dtype])

Import an audio file as Signal object.

read_comsol(filename[, expressions, parameters])

Read data exported from COMSOL Multiphysics.

read_comsol_header(filename)

Read header information on exported data from COMSOL Multiphysics.

read_sofa(filename[, verify, verbose])

Import a SOFA file as pyfar object.

write(filename[, compress])

Write any compatible pyfar object or numpy array and often used builtin types as .far file to disk.

write_audio(signal, filename[, subtype, ...])

Write a Signal object as an audio file to disk.

pyfar.io.audio_formats()[source]#

Return a dictionary of available audio formats.

Notes

This function is a wrapper of soundfile.available_formats.

Examples

>>> import pyfar as pf
>>> pf.io.audio_formats()
{'FLAC': 'FLAC (FLAC Lossless Audio Codec)',
 'OGG': 'OGG (OGG Container format)',
 'WAV': 'WAV (Microsoft)',
 'AIFF': 'AIFF (Apple/SGI)',
 ...
 'WAVEX': 'WAVEX (Microsoft)',
 'RAW': 'RAW (header-less)',
 'MAT5': 'MAT5 (GNU Octave 2.1 / Matlab 5.0)'}
pyfar.io.audio_subtypes(audio_format=None)[source]#

Return a dictionary of available audio subtypes.

Parameters:

audio_format (str) – If given, only compatible subtypes are returned.

Notes

This function is a wrapper of soundfile.available_subtypes.

Examples

>>> import pyfar as pf
>>> pf.io.audio_subtypes('FLAC')
{'PCM_24': 'Signed 24 bit PCM',
 'PCM_16': 'Signed 16 bit PCM',
 'PCM_S8': 'Signed 8 bit PCM'}
pyfar.io.convert_sofa(sofa)[source]#

Convert SOFA object to pyfar object.

Parameters:

sofa (SOFA object) – A SOFA object read or generated by the sofar package ([1]).

Returns:

  • audio (pyfar audio object) – The audio object that is returned depends on the DataType of the SOFA object:

    • Signal

      A Signal object is returned is the DataType is 'FIR', 'FIR-E', or 'FIRE'. In case of 'FIR-E', the time data is returned with the cshape EMRN (samples are in the last dimension) and not MRNE as in the SOFA standard (emitters are in the last dimension).

    • FrequencyData

      A FrequencyData object is returned is the DataType is 'TF', 'TF-E', or 'TFE'. In case of 'TF-E', the frequency data is returned with the cshape EMRN (frequencies are in the last dimension) and not MRNE as in the SOFA standard (emitters are in the last dimension).

    The cshape of the object is is (M, R) with M being the number of measurements and R being the number of receivers from the SOFA file.

  • source_coordinates (Coordinates) – Coordinates object containing the data stored in SOFA_object.SourcePosition. The domain, convention and unit are automatically matched.

  • receiver_coordinates (Coordinates) – Coordinates object containing the data stored in SOFA_object.RecevierPosition. The domain, convention and unit are automatically matched.

References

pyfar.io.default_audio_subtype(audio_format)[source]#

Return the default subtype for a given format.

Parameters:

audio_format (str) – If given, only compatible subtypes are returned.

Notes

This function is a wrapper of soundfile.default_subtype.

Examples

>>> import pyfar as pf
>>> pf.io.default_audio_subtype('WAV')
'PCM_16'
>>> pf.io.default_audio_subtype('MAT5')
'DOUBLE'
pyfar.io.read(filename)[source]#

Read any compatible pyfar object or numpy array (.far file) from disk.

Parameters:

filename (string, Path) – Input file. If no extension is provided, .far-suffix is added.

Returns:

collection – Contains pyfar objects like { 'name1': 'obj1', 'name2': 'obj2' ... }.

Return type:

dict

Examples

Read signal and orientations objects stored in a .far file.

>>> collection = pyfar.read('my_objs.far')
>>> my_signal = collection['my_signal']
>>> my_orientations = collection['my_orientations']
pyfar.io.read_audio(filename, dtype='float64', **kwargs)[source]#

Import an audio file as Signal object.

Reads ‘wav’, ‘aiff’, ‘ogg’, ‘flac’, and ‘mp3’ files among others. For a complete list see audio_formats.

Parameters:
  • filename (string, Path) – Input file.

  • dtype ({'float64', 'float32', 'int32', 'int16'}, optional) – Data type to which the data in the wav file is casted, by default 'float64'. Floating point audio data is typically in the range from -1.0 to 1.0. Note that 'int16' and 'int32' should only be used if the data was written in the same format. Integer data is in the range from -2**15 to 2**15-1 for 'int16' and from -2**31 to 2**31-1 for 'int32'. In any case, the data is converted to float.

  • **kwargs – Other keyword arguments to be passed to soundfile.read. This is needed, e.g, to read RAW audio files.

Returns:

signalSignal object containing the audio data.

Return type:

Signal

Notes

  • This function is based on soundfile.read.

  • Reading int values from a float file will not scale the data to [-1.0, 1.0). If the file contains np.array([42.6], dtype='float32'), you will read np.array([43], dtype='int32') for dtype='int32'.

pyfar.io.read_comsol(filename, expressions=None, parameters=None)[source]#

Read data exported from COMSOL Multiphysics.

Note

The data is created by defining at least one Expression within a Data node in Comsol’s Results/Export section. The data format needs to be Spreadsheet. This function supports several Expressions as well as results for Parametric Sweeps. For more information see read_comsol_header.

Parameters:
  • filename (str, Path) – Input file. Excepted input files are .txt, .dat and .csv. .csv- files are strongly recommended, since .txt and .dat-files vary in their format definitions.

  • expressions (list of strings, optional) – This parameter defines which parts of the COMSOL data is returned as a pyfar FrequencyData or TimeData object. By default, all expressions are returned. COMSOL terminology is used, e.g., expressions=['pabe.p_t']. Further information and a list of all expressions can be obtained with read_comsol_header.

  • parameters (dict, optional) – COMSOL supports Parametric Sweeps to vary certain parameters in a sequence of simulations. The parameters dict contains the parameters and the their values that are to be returned. For example, in a study with a varying angle, the dict could be parameters={'theta': [0.0, 0.7854], 'phi': [0., 1.5708]}. A list of all parameters included in a file can be obtained with read_comsol_header. The default is None, which means all parameters are included.

Returns:

  • data (FrequencyData, TimeData) – Returns a TimeData or FrequencyData object depending the domain of the input data. The output has the cshape (#points, #expressions, #parameter1, #parameter2, …). In case of missing parameter value combinations in the input, the missing data is filled with nans. If the input does not include parameters, the cshape is just (#points, #expressions).

  • coordinates (Coordinates) – Evaluation points extracted from the input file as Coordinates object. The coordinate system is always cartesian. If the input dimension is lower than three, missing dimensions are filled with zeros. If the input file does not include evaluation points (e.g., in case of non-local datasets such as averages or integrals) no coordinates are returned.

Examples

Assume a Pressure Acoustics BEM Simulation (named “pabe” in COMSOL) for two frequencies including a Parametric Sweep with All Combinations of certain incident angles theta and phi for the incident sound wave. The sound pressure (“p_t”) is exported to a file comsol_sample.csv.

Obtain information on the input file with read_comsol_header.

>>> expressions, units, parameters, domain, domain_data = \
>>>     pf.io.read_comsol_header('comsol_sample.csv')
>>> expressions
['pabe.p_t']
>>> units
['Pa']
>>> parameters
{'theta': [0.0, 0.7854, 1.5708, 2.3562, 3.1416],
 'phi': [0.0, 1.5708, 3.1416, 4.7124]}
>>> domain
'freq'
>>> domain_data
[100.0, 500.0]

Read the data including all parameter combinations.

>>> data, coordinates = pf.io.read_comsol('comsol_sample.csv')
>>> data
FrequencyData:
(8, 1, 5, 4) channels with 2 frequencies
>>> coordinates
1D Coordinates object with 8 points of cshape (8,)
domain: cart, convention: right, unit: met
coordinates: x in meters, y in meters, z in meters
Does not contain sampling weights

Read the data with a subset of the parameters.

>>> parameter_subset = {
        'theta': [1.5708, 2.3562, 3.1416],
        'phi': [0.0, 1.5708, 3.1416, 4.7124]}
>>> data, coordinates = pf.io.read_comsol(
>>>     'comsol_sample.csv', parameters=parameter_subset)
>>> data
FrequencyData:
(8, 1, 3, 4) channels with 2 frequencies
pyfar.io.read_comsol_header(filename)[source]#

Read header information on exported data from COMSOL Multiphysics.

Note

The data is created by defining at least one Expression within a Data node in Comsol’s Results/Export section. The data format needs to be Spreadsheet. This function supports several Expressions as well as results for Parametric Sweeps. For more information see below.

Parameters:

filename (str, Path) – Input file. Excepted input files are .txt, .dat and .csv. .csv- files are strongly recommended, since .txt and .dat-files vary in their format definitions.

Returns:

  • expressions (list of strings) – When exporting data in COMSOL, certain Expressions need to be specified that define the physical quantities to be exported. This function returns the expressions as a list, e.g., expressions=['pabe.p_t'].

  • units (list of strings) – List of the units corresponding to expressions, e.g., units=['Pa'].

  • parameters (dict) – COMSOL supports Parametric Sweeps to vary certain parameters in a sequence of simulations. This function returns the parameters and the parameter values as a dict. For example, in a study with a varying angle, the dict could be parameters={'theta': [0.0, 0.7854], 'phi': [0., 1.5708]}. If the input does not include parameters, an emtpy dict is returnd. Note that the dict is same for All Combinations and Specific Combinations of parameters as a distinction is not possible due to the data format.

  • domain (string) – Domain of the input data. Only time domain ('time') or frequency domain ('freq') simulations are supported.

  • domain_data (list) – List containing the sampling times or frequency bins depending on the domain of the data in the input file.

Examples

Assume a Pressure Acoustics BEM Simulation (named “pabe” in COMSOL) for two frequencies 100 Hz and 500 Hz including a Parametric Sweep of certain incident angles theta and phi for the incident sound wave. The sound pressure (“p_t”) is exported to a file comsol_sample.csv.

Obtain information on the input file.

>>> expressions, units, parameters, domain, domain_data = \
>>>     pf.io.read_comsol_header('comsol_sample.csv')
>>> expressions
['pabe.p_t']
>>> units
['Pa']
>>> parameters
{'theta': [0.0, 0.7854, 1.5708, 2.3562, 3.1416],
 'phi': [0.0, 1.5708, 3.1416, 4.7124]}
>>> domain
'freq'
>>> domain_data
[100.0, 500.0]
pyfar.io.read_sofa(filename, verify=True, verbose=True)[source]#

Import a SOFA file as pyfar object.

Parameters:
  • filename (string, Path) – Input SOFA file (cf. [2], [3]).

  • verify (bool, optional) – Verify if the data contained in the SOFA file agrees with the AES69 standard (see references). If the verification fails, the SOFA file can be loaded by setting verify=False. The default is True

  • verbose (bool, optional) – Print the names of detected custom variables and attributes. The default is True.

Returns:

  • audio (pyfar audio object) – The audio object that is returned depends on the DataType of the SOFA object:

    • Signal

      A Signal object is returned is the DataType is 'FIR', 'FIR-E', or 'FIRE'.

    • FrequencyData

      A FrequencyData object is returned is the DataType is 'TF', 'TF-E', or 'TFE'.

    The cshape of the object is is (M, R) with M being the number of measurements and R being the number of receivers from the SOFA file.

  • source_coordinates (Coordinates) – Coordinates object containing the data stored in SOFA_object.SourcePosition. The domain, convention and unit are automatically matched.

  • receiver_coordinates (Coordinates) – Coordinates object containing the data stored in SOFA_object.ReceiverPosition. The domain, convention and unit are automatically matched.

Notes

  • This function uses the sofar package to read SOFA files [4].

References

pyfar.io.write(filename, compress=False, **objs)[source]#

Write any compatible pyfar object or numpy array and often used builtin types as .far file to disk.

Parameters:
  • filename (string) – Full path or filename. If now extension is provided, .far-suffix will be add to filename.

  • compress (bool) – Default is False (uncompressed). Compressed files take less disk space but need more time for writing and reading.

  • **objs – Objects to be saved as key-value arguments, e.g., name1=object1, name2=object2.

Examples

Save Signal object, Orientations objects and numpy array to disk.

>>> s = pyfar.Signal([1, 2, 3], 44100)
>>> o = pyfar.Orientations.from_view_up([1, 0, 0], [0, 1, 0])
>>> a = np.array([1,2,3])
>>> pyfar.io.write('my_objs.far', signal=s, orientations=o, array=a)

Notes

  • Supported builtin types are: bool, bytes, complex, float, frozenset, int, list, set, str and tuple

pyfar.io.write_audio(signal, filename, subtype=None, overwrite=True, **kwargs)[source]#

Write a Signal object as an audio file to disk.

Writes ‘wav’, ‘aiff’, ‘ogg’, ‘flac’ and ‘mp3’ files among others. For a complete list see audio_formats.

Parameters:
  • signal (Signal) – Object to be written.

  • filename (string, Path) – Output file. The format is determined from the file extension. See audio_formats for all possible formats.

  • subtype (str, optional) – The subtype of the sound file, the default value depends on the selected format (see default_audio_subtype). See audio_subtypes for all possible subtypes for a given format.

  • overwrite (bool) – Select wether to overwrite the audio file, if it already exists. The default is True.

  • **kwargs – Other keyword arguments to be passed to soundfile.write.

Notes

  • Signals are flattened before writing to disk (e.g. a signal with cshape = (3, 2) will be written to disk as a six channel audio file).

  • This function is based on soundfile.write.

  • Except for the subtypes 'FLOAT', 'DOUBLE' and 'VORBIS' ´ amplitudes larger than +/- 1 are clipped.

  • Only integer values are allowed for signal.sampling_rate.