summaryrefslogtreecommitdiffstats
path: root/dpd/src/phase_align.py
blob: f8e38c42d68e1ebfbee394199729e025a975b602 (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
# -*- coding: utf-8 -*-
#
# DPD Calculation Engine, phase-align a signal against a reference.
#
# 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
from scipy import signal, optimize
import sys
import matplotlib.pyplot as plt


def phase_align(sig, ref_sig, plot=False):
    """Do phase alignment for sig relative to the reference signal
    ref_sig.

    Returns the aligned signal"""

    angle_diff = (np.angle(sig) - np.angle(ref_sig)) % (2. * np.pi)

    real_diffs = np.cos(angle_diff)
    imag_diffs = np.sin(angle_diff)

    if logging.getLogger().getEffectiveLevel() == logging.DEBUG and plot:
        dt = datetime.datetime.now().isoformat()
        fig_path = logging_path + "/" + dt + "_phase_align.pdf"

        plt.subplot(511)
        plt.hist(angle_diff, bins=60, label="Angle Diff")
        plt.xlabel("Angle")
        plt.ylabel("Count")
        plt.legend(loc=4)

        plt.subplot(512)
        plt.hist(real_diffs, bins=60, label="Real Diff")
        plt.xlabel("Real Part")
        plt.ylabel("Count")
        plt.legend(loc=4)

        plt.subplot(513)
        plt.hist(imag_diffs, bins=60, label="Imaginary Diff")
        plt.xlabel("Imaginary Part")
        plt.ylabel("Count")
        plt.legend(loc=4)

        plt.subplot(514)
        plt.plot(np.angle(ref_sig[:128]), label="ref_sig")
        plt.plot(np.angle(sig[:128]), label="sig")
        plt.xlabel("Angle")
        plt.ylabel("Sample")
        plt.legend(loc=4)

    real_diff = np.median(real_diffs)
    imag_diff = np.median(imag_diffs)

    angle = np.angle(real_diff + 1j * imag_diff)

    logging.debug(
        "Compensating phase by {} rad, {} degree. real median {}, imag median {}".format(
        angle, angle*180./np.pi, real_diff, imag_diff
    ))
    sig = sig * np.exp(1j * -angle)

    if logging.getLogger().getEffectiveLevel() == logging.DEBUG and plot:
        plt.subplot(515)
        plt.plot(np.angle(ref_sig[:128]), label="ref_sig")
        plt.plot(np.angle(sig[:128]), label="sig")
        plt.xlabel("Angle")
        plt.ylabel("Sample")
        plt.legend(loc=4)
        plt.tight_layout()
        plt.savefig(fig_path)
        plt.clf()

    return sig

# 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.