taigatakano commited on
Commit
44aae25
·
1 Parent(s): 314b026
.gitignore CHANGED
@@ -2,3 +2,5 @@
2
  *.csv
3
  *.xls
4
  *.png
 
 
 
2
  *.csv
3
  *.xls
4
  *.png
5
+ __pycache__
6
+ flagged
lab_tool_webui.py CHANGED
@@ -1,98 +1,9 @@
1
- import sys
2
- import numpy as np
3
- import matplotlib.pyplot as plt
4
- import math
5
- import pandas as pd
6
  import gradio as gr
7
- import tempfile
8
-
9
-
10
- # CSVファイルから信号データを読み込む
11
- def load_signal(file_path, column_name):
12
- try:
13
- df = pd.read_csv(file_path)
14
- signal = df[column_name].values
15
- return signal
16
- except FileNotFoundError as e:
17
- print(f"Error: {e}", file=sys.stderr)
18
- return []
19
- except KeyError as e:
20
- print(f"Column '{column_name}' not found in the file. ({e})", file=sys.stderr)
21
- return []
22
-
23
-
24
- # モルレーウェーブレット関数
25
- def morlet(x, f, width):
26
- sf = f / width
27
- st = 1 / (2 * math.pi * sf)
28
- A = 1 / (st * math.sqrt(2 * math.pi))
29
- h = -np.power(x, 2) / (2 * st**2)
30
- co1 = 1j * 2 * math.pi * f * x
31
- return A * np.exp(co1) * np.exp(h)
32
-
33
-
34
- # 連続ウェーブレット変換
35
- def continuous_wavelet_transform(Fs, data, fmax, width=48, wavelet_R=0.5):
36
- Ts = 1 / Fs
37
- wavelet_length = np.arange(-wavelet_R, wavelet_R, Ts)
38
- data_length = len(data)
39
- cwt_result = np.zeros([fmax, data_length])
40
-
41
- for i in range(fmax):
42
- conv_result = np.convolve(data, morlet(wavelet_length, i + 1, width), mode='same')
43
- cwt_result[i, :] = (2 * np.abs(conv_result) / Fs) ** 2
44
-
45
- return cwt_result
46
-
47
-
48
- # 連続ウェーブレット変換結果をカラーマップとしてプロット
49
- def plot_cwt(cwt_result, time_data, fmax):
50
- plt.imshow(cwt_result, cmap='jet', aspect='auto',
51
- extent=[time_data[0], time_data[-1], 0, fmax],
52
- vmax=abs(cwt_result).max(), vmin=-abs(cwt_result).max())
53
- plt.xlabel("Time [sec]")
54
- plt.ylabel("Frequency [Hz]")
55
- plt.colorbar(label="Power")
56
- plt.clim(-5, 5)
57
-
58
-
59
- # グラフ描画とCWTの処理を行う関数
60
- def wavelet_ui(uploaded_file, Fs, fmax, column_name, start_time, end_time):
61
- filepath = uploaded_file.name
62
- signal = load_signal(filepath, column_name)
63
-
64
- if len(signal) == 0:
65
- return None, None
66
-
67
- # 時間データを計算
68
- t_data = np.arange(0, len(signal) / Fs, 1 / Fs)
69
-
70
- # スライダーの範囲に基づいてデータをフィルタリング
71
- start_idx = int(start_time * Fs)
72
- end_idx = int(end_time * Fs)
73
- signal = signal[start_idx:end_idx]
74
- t_data = t_data[start_idx:end_idx]
75
-
76
- signal_filename = tempfile.NamedTemporaryFile(delete=False, suffix='.png').name
77
- plt.figure(dpi=200)
78
- plt.title("Signal")
79
- plt.plot(t_data, signal)
80
- plt.xlim(start_time, end_time)
81
- plt.xlabel("Time [sec]")
82
- plt.ylabel("Voltage [uV]")
83
- plt.savefig(signal_filename)
84
-
85
- cwt_signal_filename = tempfile.NamedTemporaryFile(delete=False, suffix='.png').name
86
- cwt_signal = continuous_wavelet_transform(Fs=Fs, data=signal, fmax=fmax)
87
- plt.figure(dpi=200)
88
- plot_cwt(cwt_signal, t_data, fmax)
89
- plt.savefig(cwt_signal_filename)
90
-
91
- return cwt_signal_filename, signal_filename
92
-
93
 
94
  def update_slider_range(filepath):
95
- timestamp = load_signal(filepath, "Timestamp")
96
  max_value = float(timestamp[len(timestamp) - 1])
97
  min_value = float(timestamp[0])
98
 
@@ -121,6 +32,6 @@ with gr.Blocks() as main_ui:
121
  wavelet_image = gr.Image(type="filepath", label="Wavelet")
122
  signal_image = gr.Image(type="filepath", label="Signal")
123
 
124
- submit_button.click(wavelet_ui, inputs=[file_input, fs_slider, fmax_slider, column_dropdown, start_time, end_time], outputs=[wavelet_image, signal_image])
125
  if __name__ == "__main__":
126
  main_ui.queue().launch(server_name="0.0.0.0")
 
 
 
 
 
 
1
  import gradio as gr
2
+ from lab_tools import wavelet
3
+ from lab_tools import labutils
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  def update_slider_range(filepath):
6
+ timestamp = labutils.load_signal(filepath, "Timestamp")
7
  max_value = float(timestamp[len(timestamp) - 1])
8
  min_value = float(timestamp[0])
9
 
 
32
  wavelet_image = gr.Image(type="filepath", label="Wavelet")
33
  signal_image = gr.Image(type="filepath", label="Signal")
34
 
35
+ submit_button.click(wavelet.wavelet_ui, inputs=[file_input, fs_slider, fmax_slider, column_dropdown, start_time, end_time], outputs=[wavelet_image, signal_image])
36
  if __name__ == "__main__":
37
  main_ui.queue().launch(server_name="0.0.0.0")
lab_tools/highpass.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy import signal
3
+ from scipy import fftpack
4
+ from typing import List, Tuple
5
+
6
+ def highpass_filter(signal_data: np.ndarray, samplerate: float, fp: float, fs: float, gpass: float, gstop: float) -> np.ndarray:
7
+ fn = samplerate / 2
8
+ wp = fp / fn
9
+ ws = fs / fn
10
+
11
+ N, Wn = signal.buttord(wp, ws, gpass, gstop)
12
+ b, a = signal.butter(N, Wn, "high")
13
+
14
+ filtered_signal = signal.filtfilt(b, a, signal_data)
15
+
16
+ return filtered_signal
17
+
18
+
19
+ def overlap_frames(signal_data: np.ndarray, samplerate: float, frame_size: int, overlap: float) -> Tuple[np.ndarray, int]:
20
+ total_duration = len(signal_data) / samplerate
21
+ frame_duration = frame_size / samplerate
22
+ step_size = frame_size * (1 - overlap / 100)
23
+
24
+ num_frames = int((total_duration - (frame_duration * overlap / 100)) / (frame_duration * (1 - overlap / 100)))
25
+
26
+ frames = []
27
+
28
+ for i in range(num_frames):
29
+ start_idx = int(step_size * i)
30
+ frames.append(signal_data[start_idx:start_idx + frame_size])
31
+
32
+ return np.array(frames), num_frames
33
+
34
+
35
+ def hanning(signal_data: np.ndarray, frame_size: int, num_frames: int) -> Tuple[np.ndarray, float]:
36
+ han = signal.get_window('hann', frame_size)
37
+ acf = 1 / (sum(han) / frame_size)
38
+
39
+ for i in range(num_frames):
40
+ signal_data[i] *= han
41
+
42
+ return signal_data, acf
43
+
44
+
45
+ def fft_ave(signal_data: np.ndarray, samplerate: float, frame_size: int, num_frames: int, acf: float):
46
+ fft_array = []
47
+ for i in range(num_frames):
48
+ fft_result = fftpack.fft(signal_data[i]) / frame_size
49
+ fft_array.append(acf * np.abs(fft_result))
50
+
51
+ fft_axis = np.linspace(0, samplerate / 2, frame_size // 2)
52
+ fft_array = np.array(fft_array)[:, :frame_size // 2]
53
+ fft_mean = np.mean(fft_array, axis=0)
54
+
55
+ return fft_array, fft_mean, fft_axis
56
+
57
+ def linear_to_db(x: float, y: float) -> float:
58
+ if y == 0:
59
+ raise ValueError("y cannot be zero in logarithmic conversion")
60
+ return 20 * np.log10(x / y)
lab_tools/labutils.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import pandas as pd
3
+
4
+ # CSVファイルから信号データを読み込む
5
+ def load_signal(file_path, column_name):
6
+ try:
7
+ with open(file_path, 'r') as file:
8
+ # データ部分が始まる行を見つける
9
+ for i, line in enumerate(file):
10
+ if 'Timestamp' in line:
11
+ header_line = i
12
+ break
13
+
14
+ # 見つけたヘッダー行からデータを読み込む
15
+ df = pd.read_csv(file_path, skiprows=header_line)
16
+ signal = df[column_name].values
17
+ return signal
18
+ except FileNotFoundError as e:
19
+ print(f"Error: {e}", file=sys.stderr)
20
+ return []
21
+ except KeyError as e:
22
+ print(f"Column '{column_name}' not found in the file. ({e})", file=sys.stderr)
23
+ return []
lab_tools/wavelet.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ import math
4
+ import tempfile
5
+
6
+ from lab_tools import labutils
7
+
8
+ # モルレーウェーブレット関数
9
+ def morlet(x, f, width):
10
+ sf = f / width
11
+ st = 1 / (2 * math.pi * sf)
12
+ A = 1 / (st * math.sqrt(2 * math.pi))
13
+ h = -np.power(x, 2) / (2 * st**2)
14
+ co1 = 1j * 2 * math.pi * f * x
15
+ return A * np.exp(co1) * np.exp(h)
16
+
17
+
18
+ # 連続ウェーブレット変換
19
+ def continuous_wavelet_transform(Fs, data, fmax, width=48, wavelet_R=0.5):
20
+ Ts = 1 / Fs
21
+ wavelet_length = np.arange(-wavelet_R, wavelet_R, Ts)
22
+ data_length = len(data)
23
+ cwt_result = np.zeros([fmax, data_length])
24
+
25
+ for i in range(fmax):
26
+ conv_result = np.convolve(data, morlet(wavelet_length, i + 1, width), mode='same')
27
+ cwt_result[i, :] = (2 * np.abs(conv_result) / Fs) ** 2
28
+
29
+ return cwt_result
30
+
31
+
32
+ # 連続ウェーブレット変換結果をカラーマップとしてプロット
33
+ def plot_cwt(cwt_result, time_data, fmax):
34
+ plt.imshow(cwt_result, cmap='jet', aspect='auto',
35
+ extent=[time_data[0], time_data[-1], 0, fmax],
36
+ vmax=abs(cwt_result).max(), vmin=-abs(cwt_result).max())
37
+ plt.xlabel("Time [sec]")
38
+ plt.ylabel("Frequency [Hz]")
39
+ plt.colorbar(label="Power")
40
+ plt.clim(-5, 5)
41
+
42
+
43
+ # グラフ描画とCWTの処理を行う関数
44
+ def wavelet_ui(uploaded_file, Fs, fmax, column_name, start_time, end_time):
45
+ filepath = uploaded_file.name
46
+ signal = labutils.load_signal(filepath, column_name)
47
+
48
+ if len(signal) == 0:
49
+ return None, None
50
+
51
+ # 時間データを計算
52
+ t_data = np.arange(0, len(signal) / Fs, 1 / Fs)
53
+
54
+ # スライダーの範囲に基づいてデータをフィルタリング
55
+ start_idx = int(start_time * Fs)
56
+ end_idx = int(end_time * Fs)
57
+ signal = signal[start_idx:end_idx]
58
+ t_data = t_data[start_idx:end_idx]
59
+
60
+ signal_filename = tempfile.NamedTemporaryFile(delete=False, suffix='.png').name
61
+ plt.figure(dpi=200)
62
+ plt.title("Signal")
63
+ plt.plot(t_data, signal)
64
+ plt.xlim(start_time, end_time)
65
+ plt.xlabel("Time [sec]")
66
+ plt.ylabel("Voltage [uV]")
67
+ plt.savefig(signal_filename)
68
+
69
+ cwt_signal_filename = tempfile.NamedTemporaryFile(delete=False, suffix='.png').name
70
+ cwt_signal = continuous_wavelet_transform(Fs=Fs, data=signal, fmax=fmax)
71
+ plt.figure(dpi=200)
72
+ plot_cwt(cwt_signal, t_data, fmax)
73
+ plt.savefig(cwt_signal_filename)
74
+
75
+ return cwt_signal_filename, signal_filename
test.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import sys
3
+ import numpy as np
4
+ import matplotlib.pyplot as plt
5
+ import sys
6
+
7
+ from lab_tools import highpass
8
+
9
+ def load_signal(file_path, column_name):
10
+ try:
11
+ with open(file_path, 'r') as file:
12
+ # データ部分が始まる行を見つける
13
+ for i, line in enumerate(file):
14
+ if 'Timestamp' in line:
15
+ header_line = i
16
+ break
17
+
18
+ # 見つけたヘッダー行からデータを読み込む
19
+ df = pd.read_csv(file_path, skiprows=header_line)
20
+ signal = df[column_name].values
21
+ return signal
22
+ except FileNotFoundError as e:
23
+ print(f"Error: {e}", file=sys.stderr)
24
+ return []
25
+ except KeyError as e:
26
+ print(f"Column '{column_name}' not found in the file. ({e})", file=sys.stderr)
27
+ return []
28
+
29
+ # print(load_signal("./test1_103313.csv", "Fp2"))
30
+
31
+ samplerate = 1000
32
+ time_data = load_signal("./test2_143809.csv", "Timestamp")
33
+ signal_data = load_signal("./test2_143809.csv", "Fp1")
34
+ fp = 22 # 通過域端周波数[Hz]※ベクトル
35
+ fs = 10 # 阻止域端周波数[Hz]※ベクトル
36
+ gpass = 5 # 通過域端最大損失[dB]
37
+ gstop = 40 # 阻止域端最小損失[dB]
38
+ Fs = 4096 # フレームサイズ
39
+ overlap = 90
40
+
41
+ data_filt = highpass.highpass_filter(signal_data, samplerate, fp, fs, gpass, gstop)
42
+
43
+ t_array_org, N_ave_org = highpass.overlap_frames(signal_data, samplerate, Fs, overlap)
44
+ t_array_filt, N_ave_filt = highpass.overlap_frames(signal_data, samplerate, Fs, overlap)
45
+
46
+ t_array_org, acf_org = highpass.hanning(t_array_org, Fs, N_ave_org)
47
+ t_array_filt, acf_filt = highpass.hanning(t_array_filt, Fs, N_ave_filt)
48
+
49
+ fft_array_org, fft_mean_org, fft_axis_org = highpass.fft_ave(t_array_org, samplerate, Fs, N_ave_org, acf_org)
50
+ fft_array_filt, fft_mean_filt, fft_axis_filt = highpass.fft_ave(t_array_filt, samplerate, Fs, N_ave_filt, acf_filt)
51
+
52
+ fft_mean_org = highpass.linear_to_db(fft_mean_org, 2e-5)
53
+ fft_mean_filt = highpass.linear_to_db(fft_mean_filt, 2e-5)
54
+
55
+ # フォントの種類とサイズを設定する。
56
+ # plt.rcParams['font.size'] = 14
57
+ # plt.rcParams['font.family'] = 'Times New Roman'
58
+
59
+ # 目盛を内側にする。
60
+ plt.rcParams['xtick.direction'] = 'in'
61
+ plt.rcParams['ytick.direction'] = 'in'
62
+
63
+ # グラフの上下左右に目盛線を付ける。
64
+ fig = plt.figure(figsize=(20,10))
65
+ ax1 = fig.add_subplot(211)
66
+ ax1.yaxis.set_ticks_position('both')
67
+ ax1.xaxis.set_ticks_position('both')
68
+ ax2 = fig.add_subplot(212)
69
+ ax2.yaxis.set_ticks_position('both')
70
+ ax2.xaxis.set_ticks_position('both')
71
+
72
+ # 軸のラベルを設定する。
73
+ ax1.set_xlabel('Time [s]')
74
+ ax1.set_ylabel('V[μV]')
75
+ ax2.set_xlabel('Frequency [Hz]')
76
+ ax2.set_ylabel('Amp[dB]')
77
+
78
+ # データプロットの準備とともに、ラベルと線の太さ、凡例の設置を行う。
79
+ ax1.plot(time_data, signal_data, label='original', lw=1)
80
+ ax1.plot(time_data, data_filt, label='filtered', lw=1)
81
+ ax2.plot(fft_axis_org, fft_mean_org, label='original', lw=1)
82
+ ax2.plot(fft_axis_filt, fft_mean_filt, label='filtered', lw=1)
83
+ plt.legend()
84
+
85
+ # 軸のリミットを設定する。
86
+ # ax1.set_xlim(0,1200)
87
+ # ax1.set_xticks(np.arange(0,1201,100))
88
+ # ax2.set_xlim(0, max(fft_axis_org)/2)
89
+ # ax2.set_xticks(np.arange(0,501,10))
90
+ # ax2.set_ylim(-50, 150)
91
+
92
+ # レイアウト設定
93
+ fig.tight_layout()
94
+
95
+ # グラフを表示する。
96
+ plt.savefig("./out.png")