1. ホーム
  2. スクリプト・コラム
  3. パイソン

任意波形を生成してtxtで保存するためのPython実装

2022-01-02 23:02:49

I. スクリプト機能

  • サンプル数、サンプリング周期数、波形の数式などのパラメータをもとに任意の波形を生成する
  • 波形データを指定ビット幅の2進数の補数に変換してtxtで保存
  • 元の波形と変換後の2進数の補数波形をプロットし、変換が正しいことを確認する。

II. 効果を利用する

III. コードの共有

'''
Author : Xu Dakang
Email : [email protected]
Date : 2021-11-19 19:12:31
LastEditors : Xu Dakang
LastEditTime : 2021-11-21 21:36:19
Filename :
Description :
'''

'''
Module functions.
1. Generate arbitrary waveforms based on the number of samples, the number of sampling periods and other parameters, as well as the mathematical expressions of the waveform
2. Convert waveform data to binary complement of specified bit width and then save it as txt
3. Draw the original waveform and the waveform after conversion to binary complement to verify whether the conversion is correct.
'''

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pylab import mpl

mpl.rcParams['font.sans-serif'] = ['SimHei'] # show Chinese
mpl.rcParams['axes.unicode_minus'] = False # show negative signs
import mplcursors
import time

now_time = time.strftime("%Y%m%d-%H%M%S", time.localtime(time.time()))

# My self-coded module
import myBin2dec2hex

#! Parameters to change
file_name = 'waveform-' + now_time

N = 250 # number of samples in a cycle, sampling frequency Fs = signal frequency f * number of samples N
TNUM = 10 # number of sampling periods
BIT_WIDTH = 24 # number of binary complement bits
f = 0.5 # frequency of the sine signal, can be arbitrary value

t0 = np.linspace(0, 1 / f, N) # np.linspace(start, end, number), note that the start point will be included and the end point may be included (if it is divisible)
pi = np.pi

#! Change the expression for y0 to obtain an arbitrary waveform
#! Sine function equation y = sin(wt) = sin(2πft)
y0 = np.sin(2 * pi * f * t0) + np.sin(2 * pi * f * 2 * t0)
# y0 = np.sin(2 * pi * f * t0)

#! Delay the original waveform period and plot the delayed waveform
x0_tnum = []
y0_tnum = []
y0_bit_tnum = []
for i in range(TNUM):
    for j in t0:
        x0_tnum.append(j + i * 1 / f)
    for k in y0:
        y0_tnum.append(k)
plt.figure(1)
plt.subplot(2, 1, 1)
plt.plot(x0_tnum, y0_tnum)
plt.grid()
plt.title('Original waveform, minimum frequency = ' + str(f) + 'Corresponding period is ' + str(1/f)
          + ', number of cycles = ' + str(TNUM) + ', sampling frequency = ' + str(f * N))
mplcursors.cursor() # make it possible to take points on the image

#! Original waveform decimal multiplied by binary magnification and rounded
y0_bit = np.int0((2**(BIT_WIDTH - 1) - 1) * y0 / max(abs(y0)))
y0_bit_tnum = []
for i in range(TNUM):
    for j in y0_bit:
        y0_bit_tnum.append(j)

#! Convert decimal to binary complement and store in txt file
fotxt = ''
fo = open(file_name + '.txt', 'w', encoding='utf8')
for dec_num in y0_bit_tnum: # Excluding the last number
    fotxt += myBin2dec2hex.signed_dec2bin(dec_num, BIT_WIDTH)[2:] + '\n'
fo.write(fotxt[:-1])
print('Generated ' + file_name + '.txt file successfully!')
fo.close()

#! Read the written txt file, convert it to decimal and draw a waveform to verify that the write is correct
fi = open(file_name + '.txt', 'r', encoding='utf8')

y_out = []
for line in fi.readlines():
    y_out.append(myBin2dec2hex.signed_bin2dec(line))
fi.close()

x_out = list(range(len(x0_tnum)))

plt.figure(1)
plt.subplot(2, 1, 2)
plt.plot(x_out, y_out)
plt.grid()
plt.title('convert binary complement and then decimal waveform, equivalent to multiplying decimal value by 2^' + str(BIT_WIDTH - 1) + ' - 1 that is'
            + str('{:e}'.format(2**(BIT_WIDTH - 1) - 1)))
mplcursors.cursor()
plt.show()


<スパン



Pythonで任意波形を生成し、txtで保存する方法は以上となります。Pythonで任意波形を生成する方法については、Script Houseの過去の記事を検索していただくか、引き続き以下の関連記事をご覧ください。