Added loads of comments and readability improvements.

This commit is contained in:
Anne de Jong 2018-12-29 15:34:24 +01:00
parent 21d9efc139
commit 505add6ae1
15 changed files with 55 additions and 58 deletions

1
.gitignore vendored
View File

@ -23,3 +23,4 @@ lasp_octave_fir.*
lasp/ui_* lasp/ui_*
resources_rc.py resources_rc.py
lasp/device/lasp_daqdevice.c lasp/device/lasp_daqdevice.c
.ropeproject

View File

@ -30,7 +30,8 @@ endif(LASP_FLOAT STREQUAL "double")
if(NOT DEFINED LASP_DEBUG) if(NOT DEFINED LASP_DEBUG)
message(FATAL_ERROR "LASP_DEBUG flag not defined. Please set -DLASP_DEBUG=TRUE or -DLASP_DEBUG=FALSE") message(FATAL_ERROR "LASP_DEBUG flag not defined. Please set -DLASP_DEBUG=TRUE
or -DLASP_DEBUG=FALSE")
endif(NOT DEFINED LASP_DEBUG) endif(NOT DEFINED LASP_DEBUG)
# ##################### END Cmake variables converted to a macro # ##################### END Cmake variables converted to a macro
@ -46,14 +47,14 @@ if(LASP_DEBUG)
add_definitions(-DTRACERNAME=${TRACERNAME}) add_definitions(-DTRACERNAME=${TRACERNAME})
add_definitions(-DDEBUG) add_definitions(-DDEBUG)
add_definitions(-DTRACER=1) add_definitions(-DTRACER=1)
set(CYTHON_VARIABLES "#cython: boundscheck=True") set(CYTHON_VARIABLES "#cython: boundscheck=True")
# This will produce html files # This will produce html files
set(CYTHON_ANNOTATE ON) set(CYTHON_ANNOTATE ON)
# Add the __FILENAME__ macro # Add the __FILENAME__ macro
# set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__FILENAME__='\"$(subst ${CMAKE_SOURCE_DIR}/,,$(abspath $<))\"'") # set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__FILENAME__='\"$(subst ${CMAKE_SOURCE_DIR}/,,$(abspath $<))\"'")
else() else()
message("Building release code") message("Building LASP for release")
set(CMAKE_BUILD_TYPE Release) set(CMAKE_BUILD_TYPE Release)
set(CYTHON_ANNOTATE OFF) set(CYTHON_ANNOTATE OFF)
set(CYTHON_NO_DOCSTRINGS ON) set(CYTHON_NO_DOCSTRINGS ON)
@ -61,7 +62,7 @@ else()
# Strip unnecessary symbols # Strip unnecessary symbols
# set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--gc-sections") # set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--gc-sections")
# set(CMAKE_MODULE_LINKER_FLAGS "-Wl,--gc-sections") # set(CMAKE_MODULE_LINKER_FLAGS "-Wl,--gc-sections")
add_definitions(-DTRACER=0 -DNDEBUG) add_definitions(-DTRACER=0 -DNDEBUG)
endif(LASP_DEBUG) endif(LASP_DEBUG)
@ -85,9 +86,9 @@ set(CMAKE_C_FLAGS_RELEASE "-O2 -mfpmath=sse -march=x86-64 -mtune=native \
# set(CMAKE_C_FLAGS_RELEASE "-O2 -march=native -mtune=native -fomit-frame-pointer") # set(CMAKE_C_FLAGS_RELEASE "-O2 -march=native -mtune=native -fomit-frame-pointer")
if(LASP_USE_BLAS) if(LASP_USE_BLAS)
add_definitions(-DLASP_USE_BLAS=1) add_definitions(-DLASP_USE_BLAS=1)
else() else()
add_definitions(-DLASP_USE_BLAS=0) add_definitions(-DLASP_USE_BLAS=0)
endif(LASP_USE_BLAS) endif(LASP_USE_BLAS)
# ############################# End compilation flags # ############################# End compilation flags

View File

@ -2,13 +2,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" """
Provides a simple atomic variable: Provides a simple atomic variable:
>>> a = Atomic(0) >>> a = Atomic(0)
Retrieve the value Retrieve the value
>>> b = a() >>> b = a()
Set a new value: Set a new value:
>>> a <<= b >>> a <<= b
Get conversion to boolean: Get conversion to boolean:
>>> if a: >>> if a:
do something do something
@ -20,11 +20,12 @@ Atomic increment:
""" """
from threading import Lock from threading import Lock
class Atomic: class Atomic:
def __init__(self, val): def __init__(self, val):
self._val = val self._val = val
self._lock = Lock() self._lock = Lock()
def __iadd__(self, toadd): def __iadd__(self, toadd):
with self._lock: with self._lock:
self._val += toadd self._val += toadd
@ -34,18 +35,16 @@ class Atomic:
with self._lock: with self._lock:
self._val -= toadd self._val -= toadd
return self return self
def __bool__(self): def __bool__(self):
with self._lock: with self._lock:
return self._val return self._val
def __ilshift__(self, other): def __ilshift__(self, other):
with self._lock: with self._lock:
self._val = other self._val = other
return self return self
def __call__(self): def __call__(self):
with self._lock: with self._lock:
return self._val return self._val

View File

@ -29,7 +29,8 @@ class AvStream:
self.nchannels = len(daq.channels_en) self.nchannels = len(daq.channels_en)
self.samplerate = daq.input_rate self.samplerate = daq.input_rate
self.blocksize = daq.blocksize self.blocksize = daq.blocksize
self.sensitivity = np.asarray(daqconfig.input_sensitivity)[daq.channels_en] self.sensitivity = np.asarray(daqconfig.input_sensitivity)[
daq.channels_en]
except Exception as e: except Exception as e:
raise RuntimeError(f'Could not initialize DAQ device: {str(e)}') raise RuntimeError(f'Could not initialize DAQ device: {str(e)}')

View File

@ -7,28 +7,18 @@ Common definitions used throughout the code.
""" """
__all__ = ['P_REF', 'FreqWeighting', 'TimeWeighting', 'getTime', 'calfile', __all__ = ['P_REF', 'FreqWeighting', 'TimeWeighting', 'getTime', 'calfile',
'W_REF', 'U_REF', 'I_REF', 'DEFAULT_FIGSIZE_H', 'DEFAULT_FIGSIZE_W', 'W_REF', 'U_REF', 'I_REF']
'GOLDEN', 'PLOT_COLORS_LIST', 'PLOT_NOCOLORS_LIST']
PLOT_COLORS_LIST = ['b', 'g', 'r', 'c', 'm', 'y', 'k', '#BE6500']
PLOT_NOCOLORS_LIST = ['k', '0.5', 'k', '0.5', '0.5', '0.5', '0.5', 'k']
DEFAULT_FIGSIZE_W = 8
GOLDEN = (np.sqrt(5.)+1)/2
DEFAULT_FIGSIZE_H = DEFAULT_FIGSIZE_W/GOLDEN
# Reference sound pressure level # Reference sound pressure level
P_REF = 2e-5 P_REF = 2e-5
W_REF = 1e-12 # 1 picoWatt W_REF = 1e-12 # 1 picoWatt
I_REF = 1e-12 # 1 picoWatt/ m^2 I_REF = 1e-12 # 1 picoWatt/ m^2
# Reference velocity for sound velocity level # Reference velocity for sound velocity level
U_REF = 5e-8 U_REF = 5e-8
# Todo: fix This # Todo: fix This
# calfile = '/home/anne/wip/UMIK-1/cal/7027430_90deg.txt'
calfile = None calfile = None

View File

@ -9,16 +9,14 @@ import numpy as np
LASP_NUMPY_FLOAT_TYPE = np.float64 LASP_NUMPY_FLOAT_TYPE = np.float64
def zeros(shape): def zeros(shape):
return np.zeros(shape, dtype=LASP_NUMPY_FLOAT_TYPE) return np.zeros(shape, dtype=LASP_NUMPY_FLOAT_TYPE)
def ones(shape): def ones(shape):
return np.ones(shape, dtype=LASP_NUMPY_FLOAT_TYPE) return np.ones(shape, dtype=LASP_NUMPY_FLOAT_TYPE)
def empty(shape): def empty(shape):
return np.empty(shape, dtype=LASP_NUMPY_FLOAT_TYPE) return np.empty(shape, dtype=LASP_NUMPY_FLOAT_TYPE)
class config:
default_figsize = (12,7)
default_comment_lenght_measoverview = 50
default_xlim_freq_plot = (50, 10000)
default_ylim_freq_plot = (20, 100)
versiontxt = '0.1'

View File

@ -12,7 +12,7 @@ The ASCEE hdf5 measurement file format contains the following fields:
'samplerate': The audio data sample rate in Hz. 'samplerate': The audio data sample rate in Hz.
'nchannels': The number of audio channels in the file 'nchannels': The number of audio channels in the file
'sensitivity': (Optionally) the stored sensitivity of the record channels. 'sensitivity': (Optionally) the stored sensitivity of the record channels.
This can be a single value, or an array of sensitivities for This can be a single value, or a list of sensitivities for
each channel. Both representations are allowed. each channel. Both representations are allowed.
- Datasets: - Datasets:
@ -32,9 +32,8 @@ that can be stored for the integer bit depth to get a number between -1.0 and
The video dataset can possibly be not present in the data. The video dataset can possibly be not present in the data.
""" """
__all__ = ['Measurement', 'scaleBlockSens'] __all__ = ['Measurement', 'scaleBlockSens']
from contextlib import contextmanager from contextlib import contextmanager
import h5py as h5 import h5py as h5
@ -42,7 +41,6 @@ import numpy as np
from .lasp_config import LASP_NUMPY_FLOAT_TYPE from .lasp_config import LASP_NUMPY_FLOAT_TYPE
import wave import wave
import os import os
import numbers
class BlockIter: class BlockIter:
@ -177,7 +175,9 @@ class Measurement:
# Sensitivity # Sensitivity
try: try:
sens = f.attrs['sensitivity'] sens = f.attrs['sensitivity']
self._sens = sens*np.ones(self.nchannels) if isinstance(sens, float) else sens self._sens = sens * \
np.ones(self.nchannels) if isinstance(
sens, float) else sens
except KeyError: except KeyError:
self._sens = np.ones(self.nchannels) self._sens = np.ones(self.nchannels)
@ -198,7 +198,7 @@ class Measurement:
Args: Args:
mode: Opening mode for the file. Should either be 'r', or 'r+' mode: Opening mode for the file. Should either be 'r', or 'r+'
""" """
if mode not in ('r','r+'): if mode not in ('r', 'r+'):
raise ValueError('Invalid file opening mode.') raise ValueError('Invalid file opening mode.')
with h5.File(self.fn, mode) as f: with h5.File(self.fn, mode) as f:
yield f yield f

View File

@ -6,7 +6,8 @@ Author: J.A. de Jong - ASCEE
Provides the FIR implementation of the octave filter bank Provides the FIR implementation of the octave filter bank
""" """
__all__ = ['OctaveFilterBank'] __all__ = ['OctaveFilterBank', 'ThirdOctaveFilterBank']
from .filter.bandpass_fir import OctaveBankDesigner, ThirdOctaveBankDesigner from .filter.bandpass_fir import OctaveBankDesigner, ThirdOctaveBankDesigner
from .wrappers import Decimator, FilterBank as pyxFilterBank from .wrappers import Decimator, FilterBank as pyxFilterBank
import numpy as np import numpy as np
@ -28,7 +29,6 @@ class FilterBank:
assert np.isclose(fs, 48000), "Only sampling frequency" \ assert np.isclose(fs, 48000), "Only sampling frequency" \
" available is 48 kHz" " available is 48 kHz"
maxdecimation = self.decimation(self.xs[0]) maxdecimation = self.decimation(self.xs[0])
self.decimators = [] self.decimators = []
for dec in maxdecimation: for dec in maxdecimation:

View File

@ -23,10 +23,17 @@ class Playback:
def __init__(self, fn1, channel=0, video=True, verbose=True): def __init__(self, fn1, channel=0, video=True, verbose=True):
""" """
Initialize a Playback class for playing back audio
Args:
fn1: Filename of the measurement file
channel: channel index to play back
video: if True and video is available in the measurement file,
video will also be shown
verbose: print out status messages to stdout
""" """
ext = '.h5' ext = '.h5'
if not ext in fn1: if fn1[-3:] != ext:
fn = fn1 + ext fn = fn1 + ext
else: else:
fn = fn1 fn = fn1

View File

@ -25,7 +25,7 @@ class ReverbTime:
""" """
assert level.ndim == 2, 'Invalid number of dimensions in level' assert level.ndim == 2, 'Invalid number of dimensions in level'
assert level.shape[1] == 1,'Invalid number of channels, should be 1' assert level.shape[1] == 1, 'Invalid number of channels, should be 1'
self._level = level self._level = level
# Number of time samples # Number of time samples
self._N = self._level.shape[0] self._N = self._level.shape[0]

View File

@ -22,7 +22,7 @@ class Dummy:
class SLM: class SLM:
""" """
Multi-channel sound Level Meter. Input data: time data with a certain Multi-channel Sound Level Meter. Input data: time data with a certain
sampling frequency. Output: time-weighted (fast/slow) sound pressure sampling frequency. Output: time-weighted (fast/slow) sound pressure
levels in dB(A/C/Z). levels in dB(A/C/Z).
@ -39,6 +39,8 @@ class SLM:
""" """
if tw[0] is not TimeWeighting.none[0]: if tw[0] is not TimeWeighting.none[0]:
# Initialize the single-pole low-pass filter for given time-
# weighting value.
self._lp = SPLowpass(fs, tw[0]) self._lp = SPLowpass(fs, tw[0])
else: else:
self._lp = Dummy() self._lp = Dummy()
@ -69,6 +71,8 @@ class SLM:
Args: Args:
data: data:
returns:
level values as a function of time
""" """
assert data.ndim == 2 assert data.ndim == 2
assert data.shape[1] == 1 assert data.shape[1] == 1

View File

@ -19,7 +19,7 @@ class WeighCal:
""" """
Frequency weighting and calibration FIR filter Frequency weighting and calibration FIR filter
""" """
def __init__(self, fw=FreqWeighting.default, def __init__(self, fw=FreqWeighting.default,
nchannels=1, nchannels=1,
fs=48000., fs=48000.,

View File

@ -15,7 +15,6 @@ from lasp.lasp_common import (PLOT_COLORS_LIST, PLOT_NOCOLORS_LIST,
DEFAULT_FIGSIZE_H, DEFAULT_FIGSIZE_W) DEFAULT_FIGSIZE_H, DEFAULT_FIGSIZE_W)
class Figure: class Figure:
def __init__(self, **kwargs): def __init__(self, **kwargs):
ncols = kwargs.pop('ncols', 1) ncols = kwargs.pop('ncols', 1)

View File

@ -1,3 +1,6 @@
"""
This file contains the Cython wrapper functions to
"""
include "config.pxi" include "config.pxi"
setTracerLevel(15) setTracerLevel(15)
@ -208,14 +211,14 @@ cdef class AvPowerSpectra:
us window=Window.hann, us window=Window.hann,
d[:] weighting = np.array([])): d[:] weighting = np.array([])):
cdef vd weighting_vd cdef vd weighting_vd
cdef vd* weighting_ptr = NULL cdef vd* weighting_ptr = NULL
if(weighting.size != 0): if(weighting.size != 0):
weighting_vd = dmat_foreign_data(weighting.size,1, weighting_vd = dmat_foreign_data(weighting.size,1,
&weighting[0],False) &weighting[0],False)
weighting_ptr = &weighting_vd weighting_ptr = &weighting_vd
self.aps = AvPowerSpectra_alloc(nfft, self.aps = AvPowerSpectra_alloc(nfft,
nchannels, nchannels,
overlap_percentage, overlap_percentage,
@ -323,11 +326,11 @@ cdef extern from "lasp_decimation.h":
ctypedef struct c_Decimator "Decimator" ctypedef struct c_Decimator "Decimator"
ctypedef enum DEC_FAC: ctypedef enum DEC_FAC:
DEC_FAC_4 DEC_FAC_4
c_Decimator* Decimator_create(us nchannels,DEC_FAC d) nogil c_Decimator* Decimator_create(us nchannels,DEC_FAC d) nogil
dmat Decimator_decimate(c_Decimator* dec,const dmat* samples) nogil dmat Decimator_decimate(c_Decimator* dec,const dmat* samples) nogil
void Decimator_free(c_Decimator* dec) nogil void Decimator_free(c_Decimator* dec) nogil
cdef class Decimator: cdef class Decimator:
cdef: cdef:
c_Decimator* dec c_Decimator* dec

View File

@ -1,6 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from .config import report_quality
from .report_tools import *
__all__ = ['report_quality']