Demo entry 6784692

harmonics

   

Submitted by anonymous on Mar 07, 2019 at 16:04
Language: Python. Code size: 2.0 kB.

##############################################################################
#
# Copyright (c) 2019 Mind Chasers Inc.
# All Rights Reserved.
#
#    file: harmonics.py
#
#    create and visualize harmonic waveforms
#
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################

import matplotlib.pylab as plt
import numpy as np
import argparse

VERSION = '0.1'

def factor(shape, h, i):
    if shape == "triangle":
        return (1/(h*h) * (-1)**i)
    else:
        return (1/h)
    

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='plot harmonics',
                                 epilog='Version: ' + VERSION)
    parser.add_argument('-f','--frequency',default=4,help='specify the frequency',action='store')
    parser.add_argument('-n','--harmonics',default=0,help='specify the number of harmonics',action='store')
    parser.add_argument('-t','--type',default='odd',help='specify the type of harmonics (even, odd, or all)',action='store')
    parser.add_argument('-s','--shape',default='square',help='specify the shaping factor (square, triangle)',action='store')
    

    args = parser.parse_args()
    
    f = args.frequency
    
    if args.type == 'even':
        odd = 0
        mult = 2
    elif args.type == 'odd':
        odd = 1
        mult = 2
    else:   # all
        odd = 0
        mult = 1
    
    t = np.linspace(0, 1, num=8000)
    y = np.zeros(8000)
    
    # compute fundamental and each harmonic
    for i in range(int(args.harmonics)+1):
        h = i * mult + odd
        yh = factor(args.shape,h,i) * np.sin(h * 2 * np.pi * f * t)
        y = y + yh
    
    plt.plot(t, y)
    plt.xlabel('time')
    plt.ylabel('harmonics {0}'.format(args.harmonics))
    plt.axis('tight')
    plt.show()

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).