summaryrefslogtreecommitdiffstats
path: root/dpd/src/Measure_Shoulders.py
blob: d2b4b5bf8bca9cbfa576167582e76303b41c9562 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# -*- coding: utf-8 -*-
#
# DPD Calculation Engine, calculate peak to shoulder difference
#
# http://www.opendigitalradio.org
# Licence: The MIT License, see notice at the end of this file

import datetime
import os
import logging

logging_path = os.path.dirname(logging.getLoggerClass().root.handlers[0].baseFilename)

import numpy as np
import matplotlib.pyplot as plt

def plt_next_axis(sub_rows, sub_cols, i_sub):
    i_sub += 1
    ax = plt.subplot(sub_rows, sub_cols, i_sub)
    return i_sub, ax

def plt_annotate(ax, x,y,title=None,legend_loc=None):
    ax.set_xlabel(x)
    ax.set_ylabel(y)
    if title is not None: ax.set_title(title)
    if legend_loc is not None: ax.legend(loc=legend_loc)


class Measure_Shoulder:
    """Calculate difference between the DAB signal and the shoulder hight in the
    power spectrum"""

    def __init__(self,
                 c,
                 plot=False):
        self.c = c
        self.plot = plot

    def calc_fft_db(self, signal, offset=0):
        fft = np.fft.fftshift(np.fft.fft(signal[offset:offset + self.c.MS_FFT_size]))
        fft_db = 20 * np.log10(np.abs(fft))
        return fft_db

    def _calc_peak(self, fft):
        assert fft.shape == (self.c.MS_FFT_size,), fft.shape
        idxs = (self.c.MS_peak_start, self.c.MS_peak_end)
        peak = np.mean(fft[idxs[0]:idxs[1]])
        return peak, idxs

    def _calc_shoulder_hight(self, fft_db):
        assert fft_db.shape == (self.c.MS_FFT_size,), fft_db.shape
        idxs_left = (self.c.MS_shoulder_left_start, self.c.MS_shoulder_left_end)
        idxs_right = (self.c.MS_shoulder_right_start, self.c.MS_shoulder_right_end)

        shoulder_left = np.mean(fft_db[idxs_left[0]:idxs_left[1]])
        shoulder_right = np.mean(fft_db[idxs_right[0]:idxs_right[1]])

        shoulder = np.mean((shoulder_left, shoulder_right))
        return shoulder, (idxs_left, idxs_right)

    def calc_shoulder(self, fft):
        peak = self._calc_peak(fft)[0]
        shoulder = self._calc_shoulder_hight(fft)[0]
        assert (peak >= shoulder), (peak, shoulder)
        return peak - shoulder

    def _plot(self, signal):
        fft = self.calc_fft_db(signal, 100)
        peak, idxs_peak = self._calc_peak(fft)
        shoulder, idxs_sh = self._calc_shoulder_hight(fft)

        sub_rows = 1
        sub_cols = 1
        fig = plt.figure(figsize=(sub_cols * 6, sub_rows / 2. * 6))
        i_sub = 0

        i_sub, ax = plt_next_axis(sub_rows, sub_cols, i_sub)
        ax.scatter(np.arange(fft.shape[0]), fft, s=0.1,
                   label="FFT",
                   color="red")
        ax.plot(idxs_peak, (peak, peak))
        ax.plot(idxs_sh[0], (shoulder, shoulder), color='blue')
        ax.plot(idxs_sh[1], (shoulder, shoulder), color='blue')
        plt_annotate(ax, "Frequency", "Magnitude [dB]", None, 4)

        ax.text(100, -17, str(self.calc_shoulder(fft)))

        ax.set_ylim(-20, 30)
        fig.tight_layout()

    def average_shoulders(self, signal, n_avg=None):
        assert signal.shape[0] > 4 * self.c.MS_FFT_size
        if n_avg is None: n_avg = self.c.MS_averaging_size

        off_min = 0
        off_max = signal.shape[0] - self.c.MS_FFT_size
        offsets = np.linspace(off_min, off_max, num=n_avg, dtype=int)

        shoulders = []
        for offset in offsets:
            fft_db = self.calc_fft_db(signal, offset)
            shoulders.append(self.calc_shoulder(fft_db))
        shoulder = np.mean(shoulders)

        if logging.getLogger().getEffectiveLevel() == logging.DEBUG and self.plot:
            self._plot(signal)

        return shoulder


# The MIT License (MIT)
#
# Copyright (c) 2017 Andreas Steger
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.