The Wayback Machine - https://web.archive.org/web/20241119090702/https://www.geeksforgeeks.org/complex-demodulation-phase-and-amplitude-plot/
Open In App

Complex Demodulation Phase and Amplitude Plot

Last Updated : 14 Aug, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Complex Demodulation Phase Plot

In the frequency analysis of time series models, a common model is a sinusoidal wave:

Y_{i} = C + \alpha\sin{(2\pi\omega t_{i} + \phi)} + E_{i}

where, ∝ is the amplitude, phi is the phase shift and omega is the dominant frequency. The goal of the complex demodulation plot is to improve the frequency estimate.


 The complex demodulation plots formed by two components:

  • Vertical axis: Phase
  • Horizontal axis: Time

Importance of a Good Initial Estimate for the Frequency:

The non-linear fitting for the sinusoidal waves

Y_{i} = C + \alpha\sin{(2\pi\omega t_{i} + \phi)} + E_{i}  

The above equation is sensitive to good initial values. The initial value of frequency omega can be obtained by the spectral plot. The complex demodulation phase plot is used to assess whether this estimate is adequate. If the estimate is not adequate then whether it should be increased and decreased.

Complex Demodulation Amplitude Plot:

In the frequency analysis of time series models, a common model is a sinusoidal wave:

Y_{i} = C + \alpha\sin{(2\pi\omega t_{i} + \phi)} + E_{i}  

where, ∝ is the amplitude, phi is the phase shift and omega is the dominant frequency.

If the slope of the complex demodulation amplitude plot is not zero, then the above equation is finally replaced by the model.

Y_{i} = C + \alpha_{i}\sin{(2\pi\omega t_{i} + \phi)} + E_{i}

where, ai is some type of linear model fit with standard least squares. The most common case is linear fit, that is the model becomes as follows:

Y_{i} = C + (B_0 + B_1*t_{i})\sin{(2\pi\omega t_{i} + \phi)} + E_{i}

The complex demodulation amplitude plot is formed by

  • Vertical axis: Amplitude
  • Horizontal axis: Time

 The complex amplitude demodulation plot answers the following questions:

  • Does amplitude change over time?
  • Is there any start-up effect that led to the amplitude being unstable at the start?
  • Is there any outliers in amplitude?

Implementation:
Code: Python code for complex demodulation analysis 

python3

# code
import numpy as np
import matplotlib.pyplot as plt
 
def gen_test_data(periods, noise=0, rotary=False, npts=1000, dt=1.0/24):
    """
    Generate a simple time series for testing complex demodulation.
     
    *periods* is a sequence with the periods of one or more
        harmonics that will be added to make the test signal.
        They can be positive or negative.
    *noise* is the amplitude of independent Gaussian noise.   
    *rotary* is Boolean; if True, the test signal is complex.
    *npts* is the length of the series.
    *dt* is the time interval (default is 1.0/24)
     
    Returns t, x: ndarrays with the test times and test data values..
    """    
         
    t = np.arange(npts, dtype=float) * dt
     
    if rotary:
        x = noise * (np.random.randn(npts) + 1j * np.random.randn(npts))
    else:
        x = noise * np.random.randn(npts)
 
    for p in periods:
        if rotary:
            x += np.exp(2j * np.pi * t / p)
        else:
            x += np.cos(2 * np.pi * t / p)
     
    return t, x
   
def complex_demodulation(t, x, central_period, hwidth = 2):
    """
    Complex demodulation of a real or complex series, *x*
    of samples at times *t*, assumed to be uniformly spaced.
     
    *central_period* is the period of the central frequency
        for the demodulation.  It should be positive for real
        signals. For complex signals, a positive value will
        return the CCW rotary component, and a negative value
        will return the CW component (negative frequency).
        Period is in the same time units as are used for *t*.
 
    *hwidth* is the Blackman filter half-width in units of the
        *central_period*.  For example, the default value of 2
        makes the Blackman half-width equal to twice the
        central period.
     
    Returns a dictionary.
    """    
     
    rotary = x.dtype.kind == 'c'  # complex input
     
    # Make the complex exponential for demodulation:
    c = np.exp(-1j * 2 * np.pi * t / central_period)
     
    product = x * c
     
    # filter half-width number of points
    dt = t[1] - t[0]
    hwpts = int(round(hwidth * abs(central_period) / dt))
    nf = hwpts * 2 + 1
    x1 = np.linspace(-1, 1, nf, endpoint=True)
    x1 = x1[1:-1]   # chop off the useless endpoints with zero weight
    w1 = 0.42 + 0.5 * np.cos(x1 * np.pi) + 0.08 * np.cos(x1 * 2 * np.pi)
    ytop = np.convolve(product, w1, mode='same')
    ybot = np.convolve(np.ones_like(product), w1, mode='same')
    demod = ytop/ybot
    if not rotary:   
        # The factor of 2 below comes from fact that the
        # mean value of a squared unit sinusoid is 0.5.
        demod *= 2
     
    reconstructed = (demod * np.conj(c))
    if not rotary:
        reconstructed = reconstructed.real
         
    if np.sign(central_period) < 0:
        demod = np.conj(demod)
        # This is to make the phase increase in time
        # for both positive and negative demod frequency
        # when the frequency of the signal exceeds the
        # frequency of the demodulation.
     
    d = {'t':t,'signal' : x,'hwpts' : hwpts,'demod': demod,'reconstructed' : reconstructed}
    return d
   
def plot_demodulation(dm):
    fig, axs = plt.subplots(3, sharex=True)
    resid = dm.get('signal') - dm.get('reconstructed')
    if dm.get('signal').dtype.kind == 'c':
        axs[0].plot(dm.get('t'), dm.get('signal').real, label='signal.real')
        axs[0].plot(dm.get('t'), dm.get('signal').imag, label='signal.imag')
        axs[0].plot(dm.get('t'), resid.real, label='difference real')
        axs[0].plot(dm.get('t'), resid.imag, label='difference imag')
    else:   
        axs[0].plot(dm.get('t'), dm.get('signal'), label='signal')
        axs[0].plot(dm.get('t'), dm.get('reconstructed'), label='reconstructed')
        axs[0].plot(dm.get('t'), dm.get('signal') - dm.get('reconstructed'), label='difference')
     
    axs[0].legend(loc='upper right', fontsize='small')
     
    axs[1].plot(dm.get('t'), np.abs(dm.get('demod')), label='amplitude', color='C3')
    axs[1].legend(loc='upper right', fontsize='small')
     
    axs[2].plot(dm.get('t'), np.angle(dm.get('demod'), deg=True), '.', label='phase',
                color='C4')
    axs[2].set_ylim(-180, 180)
    axs[2].legend(loc='upper right', fontsize='small')
     
    for ax in axs:
        ax.locator_params(axis='y', nbins=5)
    return fig, axs
 
def test_demodulation(periods, central_period,
                 noise=0,
                 rotary=False,
                 hwidth = 1,
                 npts=1000,
                 dt=1.0/24):
     
    t, x = gen_test_data(periods, noise=noise, rotary=rotary,
                     npts=npts, dt=dt)
    dm = complex_demodulation(t, x, central_period, hwidth=hwidth)
    fig, axs = plot_demodulation(dm)
    return fig, axs, dm
# Example 1
test_demodulation([12.0/24], 12.0/24);
# Example 2
test_demodulation([11.0/24], 12.0/24)

                    

Example 1: Signal, amplitude demodulation, and phase demodulation

Example 2: Signal, amplitude demodulation, and phase demodulation



Similar Reads

Plot Multiple Histograms On Same Plot With Seaborn
Histograms are a powerful tool for visualizing the distribution of data in a dataset. When working with multiple datasets or variables, it can be insightful to compare their distributions side by side. Seaborn, a python data visualization package offers powerful tools for making visually appealing maps and efficient way to plot multiple histograms
3 min read
How To Align Kde Plot With Strip Plot In Seaborn?
A high-level interface for creating attractive and informative statistical graphics is offered by a powerful python library Seaborn. One of the most common tasks in data visualization is aligning different types of plots in one graph to gain insights into the data. In this article, we will understand and implement how to align a KDE (Kernel Density
4 min read
Plot Logistic Regression Line Over Heat Plot in R
Plotting a logistic regression line over a heat plot can be a powerful way to visualize the relationship between predictor variables and a binary outcome. This article will guide you through the steps to create such a visualization in R. What is a Logistic Regression Line?In logistic regression, the logistic regression line is the decision boundary
4 min read
How to Plot a Vertical Line on a Time Series Plot in Pandas
When working with time series data in Pandas, it is often necessary to highlight specific points or events in the data. One effective way to do this is by plotting vertical lines on the time series plot. In this article, we will explore how to plot a vertical line on a time series plot in Pandas, covering the necessary steps, functions, and paramet
3 min read
Add Moving Average Plot to Time Series Plot in R
In time series analysis, a moving average is a widely used technique to smooth out short-term fluctuations and highlight longer-term trends or cycles. R provides several ways to compute and visualize moving averages alongside time series data. This article will guide you through the process of adding a moving average plot to a time series plot in R
3 min read
Overlaying Box Plot on Swarm Plot in Seaborn
Seaborn is a powerful Python library built on top of Matplotlib, designed for creating attractive and informative statistical graphics. It provides a high-level interface for drawing attractive and informative statistical graphics, making it easier to create complex visualizations with less code. One of the key features of Seaborn is its ability to
4 min read
Integrating Game Theory and Artificial Intelligence: Strategies for Complex Decision-Making
In real-world scenarios like financial markets, autonomous vehicles, and multi-agent systems, decision-making occurs in complex, dynamic environments with multiple interacting agents. Effective decision-making requires understanding and anticipating other agents' actions, optimizing strategies, and managing uncertainties. Integrating game theory an
9 min read
Box plot visualization with Pandas and Seaborn
Box Plot is the visual representation of the depicting groups of numerical data through their quartiles. Boxplot is also used for detect the outlier in data set. It captures the summary of the data efficiently with a simple box and whiskers and allows us to compare easily across groups. Boxplot summarizes a sample data using 25th, 50th and 75th per
2 min read
What is Box plot and the condition of outliers?
Box plot is a data visualization plotting function. It shows the min, max, median, first quartile, and third quartile. All of the things will be explained briefly. All of the property of box plot can be accessed by dataframe.column_name.describe() function. Aspects of a box plot Here is a well distributed data-set. data = [0, 1, 2, 3, 4, 5, 6] df =
3 min read
Plot Live Graphs using Python Dash and Plotly
Dash is a Python framework built on top of ReactJS, Plotly and Flask. It is used to create interactive web dashboards using just python. Live graphs are particularly necessary for certain applications such as medical tests, stock data, or basically for any kind of data that changes in a very short amount of time where it is not viable to reload eac
4 min read
How to Plot Mean and Standard Deviation in Pandas?
Errorbar is the plotted chart that refers to the errors contained in the data frame, which shows the confidence & precision in a set of measurements or calculated values. Error bars help in showing the actual and exact missing parts as well as visually display the errors in different areas in the data frame. Error bars are the descriptive behav
3 min read
Create a Scatter Plot using Sepal length and Petal_width to Separate the Species Classes Using scikit-learn
In this article, we are going to see how to create Scatter Plot using Sepal length and Petal_width to Separate the Species classes using scikit-learn in Python. The Iris Dataset contains 50 samples of three Iris species with four characteristics (length and width of sepals and petals). Iris setosa, Iris virginica, and Iris versicolor are the three
2 min read
How to Create and Visualise Volcano Plot in R
In R, a volcano plot is commonly used in bioinformatics and genomics to visualize differential expression analysis results. It displays fold change on the x-axis and statistical significance on the y-axis, typically represented as -log10(p-value). Volcano plots provide a concise way to identify significantly different features between two condition
6 min read
Movie recommender based on plot summary using TF-IDF Vectorization and Cosine similarity
Recommending movies to users can be done in multiple ways using content-based filtering and collaborative filtering approaches. Content-based filtering approach primarily focuses on the item similarity i.e., the similarity in movies, whereas collaborative filtering focuses on drawing a relation between different users of similar choices in watching
6 min read
Box plot and Histogram exploration on Iris data
Attribute Information about data set: Attribute Information: -> sepal length in cm -> sepal width in cm -> petal length in cm -> petal width in cm -> class: Iris Setosa Iris Versicolour Iris VirginicaNumber of Instances: 150 Summary Statistics: Min Max Mean SD Class Correlation sepal length: 4.3 7.9 5.84 0.83 0.7826 sepal width: 2.0
2 min read
Predict and Plot After Fitting arima() Model in R
Autoregressive Integrated Moving Average (ARIMA) models are a powerful class of models for forecasting time series data. This article will cover the theoretical foundation of ARIMA models, their components, and a step-by-step guide to fitting, predicting, and plotting results using ARIMA models in R. Components of ARIMAAn ARIMA model is characteriz
3 min read
KDE Plot Visualization with Pandas and Seaborn
Kernel Density Estimate (KDE) plot, a visualization technique that offers a detailed view of the probability density of continuous variables. In this article, we will be using Iris Dataset and KDE Plot to visualize the insights of the dataset. What is KDE Plot?KDE Plot described as Kernel Density Estimate is used for visualizing the Probability Den
4 min read
Interactively Displaying and Hiding Lines in a Bokeh Plot
Bokeh is a powerful Python library for creating interactive and visually appealing data visualizations. One of its standout features is the ability to interactively display and hide lines in a plot, which can be particularly useful when dealing with complex datasets. This article will guide you through the process of setting up interactive line vis
4 min read
Drawing a Violin Plot and Setting Quartiles as Horizontal Lines
Violin plots are an excellent way to visualize the distribution of numerical data across different categories. They combine the benefits of a boxplot and a KDE (Kernel Density Estimate) plot, displaying not only the summary statistics but also the underlying distribution of the data. By adding quartiles as horizontal lines, you can further highligh
5 min read
Plot Single 3D Point on Top of plot_surface in Python - Matplotlib
Matplotlib is a widely-used plotting library in Python that offers various tools and functionalities for creating 2D and 3D visualizations. In this article, we will explore how to use Matplotlib to plot a single 3D point on top of a 3d surface plot. Plot Single 3D Point on Top of SurfaceLet us understand the Plotting single 3D point on top of the p
5 min read
Introduction to Bootstrap plot
Before getting into Bootstrap plot, let us first understand what Bootstrapping (or Bootstrap sampling) is all about. Bootstrap Sampling: It is a method in which we take a sample data repeatedly with replacement from a data set to estimate a population parameter. It is used to determine various parameters of a population. A bootstrap plot is a graph
5 min read
Understanding different Box Plot with visualization
Let's see how can boxplot be useful in different ways. Loading Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt Preparing Data spread = np.random.rand(50) * 100 center = np.ones(25) * 50 flier_high = np.random.rand(10) * 100 + 100 flier_low = np.random.rand(10) * -100 data = np.concatenate((spread, center, flier_high
2 min read
qqplot (Quantile-Quantile Plot) in Python
When the quantiles of two variables are plotted against each other, then the plot obtained is known as quantile - quantile plot or qqplot. This plot provides a summary of whether the distributions of two variables are similar or not with respect to the locations. Interpretations All point of quantiles lie on or close to straight line at an angle of
2 min read
Grid Plot in Python using Seaborn
Grids are general types of plots that allow you to map plot types to grid rows and columns, which helps you to create similar character-separated plots. In this article, we will be using two different data sets (Iris and Tips) for demonstrating grid plots Using Iris Dataset We are going to use the Iris dataset which is a very famous dataset availab
4 min read
Make an area plot in Python using Bokeh
Bokeh is a Python interactive data visualization. Unlike Matplotlib and Seaborn, Bokeh renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Plotting the Area Plots Area plots are defined as the filled regions betwee
2 min read
Python Bokeh - Plotting a Scatter Plot on a Graph
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh can be used to plot a scatter plot on a graph. Plotting squares on a graph can be done using the scatte
2 min read
Plot Candlestick Chart using mplfinance module in Python
Candlestick chart are also known as a Japanese chart. These are widely used for technical analysis in trading as they visualize the price size within a period. They have four points Open, High, Low, Close (OHLC). Candlestick charts can be created in python using a matplotlib module called mplfinance. Installation:pip install mplfinancemplfinance.ca
2 min read
Sunburst Plot using graph_objects class in plotly
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Sunburst Plot using graph_objects class If Plotl
3 min read
Probability plot correlation coefficient
The probability plot correlation coefficient (PPCC) is a graphical technique for identifying the shape parameter that best describes the dataset. Most of the statistical analysis has been done assuming the shape of the distribution in mind. However, these assumptions may be challenged because sometimes the distributions can have very different shap
4 min read
How to plot data from a text file using Matplotlib?
Perquisites: Matplotlib, NumPy In this article, we will see how to load data files for Matplotlib. Matplotlib is a 2D Python library used for Date Visualization. We can plot different types of graphs using the same data like: Bar GraphLine GraphScatter GraphHistogram Graph and many. In this article, we will learn how we can load data from a file to
3 min read
three90RightbarBannerImg