-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathShowTrace.py
More file actions
1859 lines (1443 loc) · 72.1 KB
/
Copy pathShowTrace.py
File metadata and controls
1859 lines (1443 loc) · 72.1 KB
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author : MikeChan
# Email : m7807031@gmail.com
import time, sys, os, threading
import pandas as pd
import numpy as np
from scipy import signal, optimize, stats, integrate
from sklearn.metrics import r2_score
import matplotlib as mpl
from matplotlib import cm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class IMU_trace(QWidget):
# self.raw_data is all raw data!
def __init__(self, parent = None):
super(IMU_trace, self).__init__(parent)
#self.setGeometry(200,50,350,150)
self.move(10,10)
self.setWindowTitle(u"產出軌跡程式")
# create Layout and connection
self.createLayout()
self.createConnection()
#bias dict
self.bias_dict ={ 'ax': 0.639909, 'ay': 142.6601, 'az': -824.501,
'gx': 35.61079, 'gy': 53.51407, 'gz': -135.055,
'mx':0 ,'my':0 ,'mz':0 }
# set global varibles
self.raw_data = np.array(0)
def createLayout(self):
self.fileLineEdit=QLineEdit()
self.openfile_Button=QPushButton(u"選擇檔案")
h0 = QHBoxLayout()
h0.addWidget(self.fileLineEdit)
h0.addWidget(self.openfile_Button)
self.record_sec_le = QLineEdit()
self.sec_label = QLabel(u'秒')
self.set_record_sec_btn = QPushButton(u"輸入靜置秒數(預設=10s)")
ht =QHBoxLayout()
ht.addWidget(self.record_sec_le)
ht.addWidget(self.sec_label)
ht.addWidget(self.set_record_sec_btn)
self.record_sec_le.setText(str(10))
self.axis_choose_label = QLabel(u"軸向選取:ax")
self.axis_choose_label.setAlignment(Qt.AlignCenter)
self.axis_combobox = QComboBox()
self.axis_combobox.addItems(['ax', 'ay', 'az', 'gx', 'gy', 'gz', 'mx', 'my', 'mz'])
h6=QHBoxLayout()
h6.addWidget(self.axis_choose_label)
h6.addWidget(self.axis_combobox)
self.magic_label = QLabel(u"@===== 魔法按鈕 =====@")
self.magic_label.setAlignment(Qt.AlignCenter)
h00 = QHBoxLayout()
h00.addWidget(self.magic_label)
self.magic_2_button = QPushButton('magic! 2')
self.magic_3_button = QPushButton('magic! 3')
h000 = QHBoxLayout()
h000.addWidget(self.magic_2_button)
h000.addWidget(self.magic_3_button)
self.trendLine_label = QLabel(u"@===== 1D資訊 =====@")
self.trendLine_label.setAlignment(Qt.AlignCenter)
h1 = QHBoxLayout()
h1.addWidget(self.trendLine_label)
self.show_raw_mean_le = QLineEdit()
self.show_raw_mean_button = QPushButton(u'原始資料各軸平均')
h1_0=QHBoxLayout()
h1_0.addWidget(self.show_raw_mean_le)
h1_0.addWidget(self.show_raw_mean_button)
self.trendLine_content1_label = QLabel("Trendline: Y = AX + B")
self.trendLine_content2_label = QLabel("R: NaN")
self.trendLine_button = QPushButton(u"計算趨勢線")
self.show_detrend_button = QPushButton(u"產出Detrend圖表")
h1_1 = QHBoxLayout()
h1_1.addWidget(self.trendLine_content1_label)
h1_1.addWidget(self.trendLine_content2_label)
h1_1.addWidget(self.trendLine_button)
h1_1.addWidget(self.show_detrend_button)
self.acc_label = QLabel(u"@===== 原始2D資訊 =====@")
self.acc_label.setAlignment(Qt.AlignCenter)
h2 = QHBoxLayout()
h2.addWidget(self.acc_label)
self.show_raw_2d_acc_Button = QPushButton(u"三軸加速度與積分")
self.show_raw_2d_gyro_Button = QPushButton(u"三軸角速度與積分")
self.show_raw_2d_mag_Button = QPushButton(u'三軸磁力值')
h2_1 = QHBoxLayout()
h2_1.addWidget(self.show_raw_2d_acc_Button)
h2_1.addWidget(self.show_raw_2d_gyro_Button)
h2_1.addWidget(self.show_raw_2d_mag_Button)
self.gyro_label = QLabel(u"@===== 原始資料3D資訊 =====@")
self.gyro_label.setAlignment(Qt.AlignCenter)
h3 = QHBoxLayout()
h3.addWidget(self.gyro_label)
self.show_raw_3d_acctrace_Button = QPushButton(u"加速度軌跡")
self.show_raw_3d_gyrotrace_Button = QPushButton(u"角速度軌跡")
h3_1 = QHBoxLayout()
h3_1.addWidget(self.show_raw_3d_acctrace_Button)
h3_1.addWidget(self.show_raw_3d_gyrotrace_Button)
self.horizontal_line = QLabel("+"*30 + "+++++++++" + "+"*30)
self.horizontal_line.setAlignment(Qt.AlignCenter)
h5_up=QHBoxLayout()
h5_up.addWidget(self.horizontal_line)
self.horizontal_line = QLabel("="*30 + " Analyst " + "="*30)
self.horizontal_line.setAlignment(Qt.AlignCenter)
h5=QHBoxLayout()
h5.addWidget(self.horizontal_line)
self.horizontal_line = QLabel("+"*30 + "+++++++++" + "+"*30)
self.horizontal_line.setAlignment(Qt.AlignCenter)
h5_d=QHBoxLayout()
h5_d.addWidget(self.horizontal_line)
self.godmode_label = QLabel(u"@===== 頻譜分析 =====@")
self.godmode_label.setAlignment(Qt.AlignCenter)
h9 = QHBoxLayout()
h9.addWidget(self.godmode_label)
self.godmode_Button1 = QPushButton(u"頻譜分析")
self.godmode_Button2 = QPushButton(u"頻譜分析2")
h9_1 = QHBoxLayout()
h9_1.addWidget(self.godmode_Button1)
h9_1.addWidget(self.godmode_Button2)
self.filter_label = QLabel(u"@===== 濾波分析 =====@")
self.filter_label.setAlignment(Qt.AlignCenter)
h10 = QHBoxLayout()
h10.addWidget(self.filter_label)
self.filtbutter_lp_slider_label = QLabel("Cutoff: NaNHz; Wn:Nan")
self.filtbutter_lp_slider = QSlider(Qt.Horizontal)
self.filtbutter_lp_slider.setMinimum(1)
self.filtbutter_lp_slider.setMaximum(1420)
self.filtbutter_lp_slider.setValue(200)
self.filtbutter_lp_slider.setTickInterval(1)
self.filtbutter_lp_slider.setSingleStep(1)
h10_1 = QHBoxLayout()
h10_1.addWidget(self.filtbutter_lp_slider)
h10_1.addWidget(self.filtbutter_lp_slider_label)
self.filtfilt_Button = QPushButton(u"Lowpass")
self.butterHP_Button = QPushButton(u"Highpass")
h10_2 = QHBoxLayout()
h10_2.addWidget(self.filtfilt_Button)
h10_2.addWidget(self.butterHP_Button)
self.butterBP_Button = QPushButton('BandPass')
h10_3 = QHBoxLayout()
h10_3.addWidget(self.butterBP_Button)
self.lp_filt_3D_trace_Button = QPushButton('Lowpass Trace')
h10_4 = QHBoxLayout()
h10_4.addWidget(self.lp_filt_3D_trace_Button)
self.fusion_label = QLabel(u"@===== 磁力測試 =====@")
self.fusion_label.setAlignment(Qt.AlignCenter)
h11 = QHBoxLayout()
h11.addWidget(self.fusion_label)
self.threshold_test_label = QLabel("Data not decide yet")
self.threshold_test_button = QPushButton(u"門檻過濾測試用")
h11_XX = QHBoxLayout()
h11_XX.addWidget(self.threshold_test_label)
h11_XX.addWidget(self.threshold_test_button)
self.mag_scatter_label = QLabel("Data not decide yet")
self.mag_scatter_button = QPushButton(u"原始磁力平面散佈圖")
h11_00 = QHBoxLayout()
h11_00.addWidget(self.mag_scatter_label)
h11_00.addWidget(self.mag_scatter_button)
self.mag_scatter_adj_label = QLabel("Data not decide yet")
self.mag_scatter_adj_button = QPushButton(u"修正後磁力平面散佈圖")
h11_000 = QHBoxLayout()
h11_000.addWidget(self.mag_scatter_adj_label)
h11_000.addWidget(self.mag_scatter_adj_button)
self.mag_heading_label = QLabel("Mean Heading")
self.raw_mag_heading_button = QPushButton(u"計算原始磁力角(無修正)")
self.mag_heading_button = QPushButton(u"計算磁力角(無傾斜修正)")
h11_0 = QHBoxLayout()
h11_0.addWidget(self.mag_heading_label)
h11_0.addWidget(self.raw_mag_heading_button)
h11_0.addWidget(self.mag_heading_button)
self.fusion_label = QLabel(u"@===== 9軸Fusion =====@")
self.fusion_label.setAlignment(Qt.AlignCenter)
h12 = QHBoxLayout()
h12.addWidget(self.fusion_label)
self.gravity_calibration_label = QLabel("roll:NaN; pitch:NaN")
self.gravity_calibration_button = QPushButton(u"計算整體的RPH")
h12_1 = QHBoxLayout()
h12_1.addWidget(self.gravity_calibration_label)
h12_1.addWidget(self.gravity_calibration_button)
self.gravity_compensate_label =QLabel(u"消除重力影響")
self.gravity_compensate_button = QPushButton(u'消除重力軌跡')
h12_2=QHBoxLayout()
h12_2.addWidget(self.gravity_compensate_label)
h12_2.addWidget(self.gravity_compensate_button)
self.acc_with_gyro_fusion_label =QLabel(u"以角速度修正 Body to NEH acc")
self.acc_with_gyro_fusion_button = QPushButton(u"6軸Fusion產出軌跡")
h12_3=QHBoxLayout()
h12_3.addWidget(self.acc_with_gyro_fusion_label)
h12_3.addWidget(self.acc_with_gyro_fusion_button)
self.answer_trace_button = QPushButton(u'產出軌跡')
h12_4 = QHBoxLayout()
h12_4.addWidget(self.answer_trace_button)
self.for_hofong_label = QLabel(u"@===== 后豐用? =====@")
h13_0=QHBoxLayout()
h13_0.addWidget(self.for_hofong_label)
self.acc_integral_per_sec_label =QLabel(u"每秒加速度")
self.generate_dist_per_sec_button = QPushButton(u"產出每秒移動距離")
h13_1a = QHBoxLayout()
h13_1a.addWidget(self.acc_integral_per_sec_label)
h13_1a.addWidget(self.generate_dist_per_sec_button)
self.gyro_integral_per_sec_label =QLabel(u"每秒旋轉角度")
self.generate_degree_per_sec_button = QPushButton(u"產出內差一秒旋轉角度")
h13_1b = QHBoxLayout()
h13_1b.addWidget(self.gyro_integral_per_sec_label)
h13_1b.addWidget(self.generate_degree_per_sec_button)
self.interp_different_hz_label =QLabel(u"內差不同頻率旋轉角度")
self.interp_different_hz_button = QPushButton(u"產出內差不同頻率旋轉角度")
h13_2 = QHBoxLayout()
h13_2.addWidget(self.interp_different_hz_label)
h13_2.addWidget(self.interp_different_hz_button)
self.trace_by_238mmpersec_with_degrees_label =QLabel(u"以秒速23.83cm產出軌跡")
self.trace_by_238mmpersec_with_degrees_button = QPushButton(u"以秒速23.83cm+指定旋轉量產出軌跡")
h13_3 = QHBoxLayout()
h13_3.addWidget(self.trace_by_238mmpersec_with_degrees_label)
h13_3.addWidget(self.trace_by_238mmpersec_with_degrees_button)
layout = QVBoxLayout()
layout.addLayout(h0)
layout.addLayout(ht)
layout.addLayout(h6)
layout.addLayout(h00)
layout.addLayout(h000)
layout.addLayout(h1)
layout.addLayout(h1_0)
layout.addLayout(h1_1)
layout.addLayout(h2)
layout.addLayout(h2_1)
layout.addLayout(h3)
layout.addLayout(h3_1)
layout.addLayout(h5_up)
layout.addLayout(h5)
layout.addLayout(h5_d)
layout.addLayout(h9)
layout.addLayout(h9_1)
layout.addLayout(h10)
layout.addLayout(h10_1)
layout.addLayout(h10_2)
layout.addLayout(h10_3)
layout.addLayout(h10_4)
layout.addLayout(h11)
layout.addLayout(h11_XX)
layout.addLayout(h11_00)
layout.addLayout(h11_000)
layout.addLayout(h11_0)
layout.addLayout(h12)
layout.addLayout(h12_1)
layout.addLayout(h12_2)
layout.addLayout(h12_3)
layout.addLayout(h12_4)
layout.addLayout(h13_0)
layout.addLayout(h13_1a)
layout.addLayout(h13_1b)
layout.addLayout(h13_2)
layout.addLayout(h13_3)
'''
# plot area!! =====================
# a figure instance to plot on
self.figure = plt.figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
#self.canvas = FigureCanvas(self.figure)
#self.canvas.setMinimumSize(1200,800)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
self.plot_button = QPushButton('Plot')
plot_area = QVBoxLayout()
plot_area.addWidget(self.toolbar)
plot_area.addWidget(self.canvas)
plot_area.addWidget(self.plot_button)
'''
layout_all = QGridLayout()
layout_all.addLayout(layout,0,0)
#layout_all.addLayout(plot_area,0,1)
self.setLayout(layout_all)
def createConnection(self):
self.openfile_Button.clicked.connect(self.file_open)
self.trendLine_button.clicked.connect(self.trendLine)
self.show_detrend_button.clicked.connect(self.show_detrend)
self.set_record_sec_btn.clicked.connect(self.set_record_sec)
self.show_raw_mean_button.clicked.connect(self.show_raw_mean)
self.magic_2_button.clicked.connect(self.magic2)
self.magic_3_button.clicked.connect(self.magic3)
self.show_raw_2d_acc_Button.clicked.connect(self.show_raw_2d_acc_data)
self.show_raw_2d_gyro_Button.clicked.connect(self.show_raw_2d_gyro_data)
self.show_raw_2d_mag_Button.clicked.connect(self.show_raw_2d_mag_data)
self.show_raw_3d_acctrace_Button.clicked.connect(self.show_raw_3d_acctrace)
self.show_raw_3d_gyrotrace_Button.clicked.connect(self.show_raw_3d_gyrotrace)
self.axis_combobox.currentIndexChanged.connect(self.axis_choose)
self.godmode_Button1.clicked.connect(self.fft_test)
self.godmode_Button2.clicked.connect(self.fft_test2)
self.filtbutter_lp_slider.valueChanged.connect(self.change_filtfilt_Wn)
self.filtfilt_Button.clicked.connect(self.butterLP)
self.butterHP_Button.clicked.connect(self.butterHP)
self.butterBP_Button.clicked.connect(self.butterBP)
self.lp_filt_3D_trace_Button.clicked.connect(self.lp_filt_3D_trace)
self.threshold_test_button.clicked.connect(self.threshold_test)
self.mag_scatter_button.clicked.connect(self.mag_scatter)
self.mag_scatter_adj_button.clicked.connect(self.mag_scatter_adj)
self.raw_mag_heading_button.clicked.connect(self.raw_mag_heading)
self.mag_heading_button.clicked.connect(self.mag_heading_without_cali_tile)
self.gravity_calibration_button.clicked.connect(self.gravity_calibration)
self.gravity_compensate_button.clicked.connect(self.show_gravity_compensate)
self.acc_with_gyro_fusion_button.clicked.connect(self.acc_with_gyro_fusion_output_new_acc)
self.answer_trace_button.clicked.connect(self.answer_trace)
self.generate_dist_per_sec_button.clicked.connect(self.generate_dist_per_sec)
self.generate_degree_per_sec_button.clicked.connect(self.generate_degree_per_sec)
self.interp_different_hz_button.clicked.connect(self.interp_different_hz)
self.trace_by_238mmpersec_with_degrees_button.clicked.connect(self.trace_by_238mmpersec_with_degrees)
'''#===== File reading section =====#'''
def check_file_available(self, file):
first_line = self.raw_file.readline()
check_line = first_line.rstrip().split("\t")
if len(check_line) == 10: return True
else: return False
def read_file_to_np(self, file_name):
datatype = [('time',np.float32), ('ax',np.int16), ('ay',np.int16), ('az',np.int16),
('gx',np.int16), ('gy',np.int16), ('gz',np.int16),
('mx',np.int16), ('my',np.int16), ('mz',np.int16),
('time_diff', np.float32)]
data = np.genfromtxt(file_name, dtype=datatype, delimiter="\t")
data['time'] = data['time']-data['time'][0]
a = np.diff(data['time'])
time_diff_array = np.insert(a, 0, 0)
data['time_diff'] = time_diff_array
# 磁力值校正
data['mx'] = data['mx'] * 1.18359375
data['my'] = data['my'] * 1.19140625
data['mz'] = data['mz'] * 1.14453125
return data
def show_error_message(self, index):
if index == 0:
error_file_popup = QMessageBox.warning(self, u'檔案錯誤!', u"請重新選擇檔案", QMessageBox.Cancel)
self.fileLineEdit.setText("")
elif index == 1:
error_file_popup = QMessageBox.warning(self, u'定軸錯誤!', u"請重新輸入定軸", QMessageBox.Cancel)
elif index == 2:
error_file_popup = QMessageBox.information(self, u'讀取完成', u"檔案讀取完成!", QMessageBox.Ok)
def file_open(self):
fn = QFileDialog.getOpenFileName(self, 'Open File')
self.fileLineEdit.setText(fn)
self.raw_file = open(u'%s' %fn, 'r')
if self.check_file_available(self.raw_file):
self.raw_data = self.read_file_to_np(self.raw_file)
self.show_error_message(2)
self.show_raw_2d_acc_Button.setEnabled(True)
self.show_raw_2d_gyro_Button.setEnabled(True)
self.show_raw_3d_acctrace_Button.setEnabled(True)
self.show_raw_3d_gyrotrace_Button.setEnabled(True)
else:
self.show_error_message(0)
'''#===== Qitem Support =====#'''
def axis_choose(self):
self.axis_choose_label.setText(u"軸向選取: " + self.axis_combobox.currentText())
def change_filtfilt_Wn(self):
self.filtbutter_lp_slider_label.setText("Cutoff: " + str(self.filtbutter_lp_slider.value()/10.0)+ "Hz" +
"; Wn: %.3f " %(self.filtbutter_lp_slider.value()/1430.0) )
def set_record_sec(self):
num,ok = QInputDialog.getInt(self,u"IMU靜置時間",u"輸入此筆資料靜置秒數")
if ok:
self.record_sec_le.setText(str(num))
'''#===== magic button =====#'''
def magic2(self):
ax = self.acc_normalize(self.raw_data['ax'])
ay = self.acc_normalize(self.raw_data['ay'])
az = self.acc_normalize(self.raw_data['az'])
gx, dx, nx = self.another_integral(self.gyro_normalize(self.raw_data['gx']))
gy, dy, ny = self.another_integral(self.gyro_normalize(self.raw_data['gy']))
gz, dz, nz = self.another_integral(self.gyro_normalize(self.raw_data['gz']))
f,ax = plt.subplots(2, sharex=True)
ax[0].set_title("gyro data drift")
ax[0].plot(self.raw_data['gx'], label='gx')
ax[0].plot(self.raw_data['gy'], label='gy')
ax[0].plot(self.raw_data['gz'], label='gz')
ax[1].plot(dx, label='dx')
ax[1].plot(dy, label='dy')
ax[1].plot(dz, label='dz')
plt.show()
def magic3(self):
time_end = 5123
real_hofong_fix_pts = pd.read_csv('20161012_HoFong/control_points_coodination.csv').sort(ascending=False)
real_hofong_fix_pts['N'] = real_hofong_fix_pts['N'] - real_hofong_fix_pts['N'][129]
real_hofong_fix_pts['E'] = real_hofong_fix_pts['E'] - real_hofong_fix_pts['E'][129] # last data name=2717, index=129
N_diff = np.diff(real_hofong_fix_pts['N'])
E_diff = np.diff(real_hofong_fix_pts['E'])
hofong_deg = np.rad2deg(np.arctan2(N_diff, E_diff))
hofong_deg = hofong_deg - hofong_deg[0]
hofong_deg_diff = np.cumsum(np.diff(hofong_deg))
interp_hofong = np.interp(np.arange(100), np.arange(hofong_deg_diff.size), hofong_deg_diff)
#plt.plot(hofong_deg, label='hahaxd')
#plt.plot(hofong_deg_diff, label='hehexd')
plt.plot(interp_hofong)
plt.legend()
plt.show()
'''#===== data normalizer =====#'''
def acc_normalize(self, lst):
#change gyro data from lSB to g then m/s^2
#offset will be remove !
stable_sec= int(self.record_sec_le.text())
stable_count = int(stable_sec * (1/0.007))
offset = np.average(lst[1:stable_count])
#offset = 0
np_acc_lst = np.array(lst)
np_acc_normalized_list = (np_acc_lst - offset)* 9.80665 / 16384.0
return np_acc_normalized_list
def gyro_normalize(self, lst):
#change gyro data from lSB to deg/s
#offset will be remove !
stable_sec= int(self.record_sec_le.text())
stable_count = int(stable_sec * (1/0.007))
offset = np.average(lst[1:stable_count])
np_gyro_lst = np.array(lst)
np_gyro_normalized_list = (np_gyro_lst - offset)/131.0
#print np_gyro_normalized_list[5:15]
return np_gyro_normalized_list
def mag_adj(self):
#打開磁力校正用檔案
mag_cali_file = self.read_file_to_np("CALIBRATION_DATA/hofong_mag_cali_RESULT.txt")
raw_data_size = self.raw_data['mx'].size
#mx = self.raw_data['mx'].astype(np.float32) * 1.15625
#my = self.raw_data['my'].astype(np.float32) * 1.1640625
#mz = self.raw_data['mz'].astype(np.float32) * 1.11328125
mx = np.append(self.raw_data['mx'].astype(np.float32), mag_cali_file['mx'].astype(np.float32))
my = np.append(self.raw_data['my'].astype(np.float32), mag_cali_file['my'].astype(np.float32))
mz = np.append(self.raw_data['mz'].astype(np.float32), mag_cali_file['mz'].astype(np.float32))
m_normal = np.sqrt(np.square(mx)+np.square(my)+np.square(mz))
mx_bias = (np.amax(mx) + np.amin(mx)) /2.
my_bias = (np.amax(my) + np.amin(my)) /2.
mz_bias = (np.amax(mz) + np.amin(mz)) /2.
mx_scale = (np.amax(mx) - np.amin(mx)) /2.
my_scale = (np.amax(my) - np.amin(my)) /2.
mz_scale = (np.amax(mz) - np.amin(mz)) /2.
avg_radius = (mx_scale + my_scale + mz_scale)/3.
#avg_radius = 255
#print avg_radius
mx_rad_enlarge_times = avg_radius/mx_scale
my_rad_enlarge_times = avg_radius/my_scale
mz_rad_enlarge_times = avg_radius/mz_scale
mx_adj = (mx-mx_bias)*mx_rad_enlarge_times
my_adj = (my-my_bias)*my_rad_enlarge_times
mz_adj = (mz-mz_bias)*mz_rad_enlarge_times
mx_adj = mx_adj[:raw_data_size]
my_adj = my_adj[:raw_data_size]
mz_adj = mz_adj[:raw_data_size]
return mx_adj, my_adj, mz_adj
'''#===== 1D information =====#'''
def trendLine(self, axis_choose=None):
stable_sec= int(self.record_sec_le.text())
stable_count = int(stable_sec * (1/0.007))
if axis_choose:
axis = axis_choose
else:
axis = str(self.axis_combobox.currentText())
x = self.raw_data['time'][:stable_count]
y = self.raw_data[axis][:stable_count]
coefficients = np.polyfit(x,y,1)
p = np.poly1d(coefficients)
coefficient_of_dermination = r2_score(y, p(x))
self.trendLine_content1_label.setText("Trendline: " + str(p))
self.trendLine_content2_label.setText("R: " + str(coefficient_of_dermination))
return coefficients
def detrend(self, signal, coefficients):
detrend_signal = []
for i in range(signal.size):
detrend_signal.append(signal[i] - (
(self.raw_data['time'][i]-self.raw_data['time'][0]) * coefficients[0] + coefficients[1]) )
return detrend_signal
def detrend_1d(self, signal, time_lst):
stable_sec= int(self.record_sec_le.text())
stable_count = int(stable_sec * (1/0.007))
x = self.raw_data['time'][:stable_count]
y = signal[:stable_count]
coefficients = np.polyfit(x,y,1)
detrend_signal = []
for i in range(signal.size):
detrend_signal.append(
signal[i] - ((time_lst[i]-time_lst[0]) * coefficients[0] + coefficients[1])
)
return detrend_signal
def show_detrend(self):
if self.fileLineEdit.text().isEmpty(): self.show_error_message(index=0)
gx_notrend,dx_notrend, nx_notrend = self.another_integral(self.gyro_normalize(self.detrend(self.raw_data['gx'], self.trendLine('gx'))))
gy_notrend,dy_notrend, ny_notrend = self.another_integral(self.gyro_normalize(self.detrend(self.raw_data['gy'], self.trendLine('gy'))))
gz_notrend,dz_notrend, nz_notrend = self.another_integral(self.gyro_normalize(self.detrend(self.raw_data['gz'], self.trendLine('gz'))))
gx_g_array,gx_r_array, gx_no_array = self.another_integral(self.gyro_normalize(self.raw_data['gx']))
gy_g_array,gy_r_array, gy_no_array = self.another_integral(self.gyro_normalize(self.raw_data['gy']))
gz_g_array,gz_r_array, gz_no_array = self.another_integral(self.gyro_normalize(self.raw_data['gz']))
#===== gx =====
plt.subplot(231)
plt.plot(gx_g_array, "blue", label="gx")
plt.plot(gx_notrend, "r", label = "gx_notrend", alpha=0.7)
plt.legend(loc='best')
plt.subplot(234)
plt.plot(gx_r_array, "blue", label="dx")
plt.plot(dx_notrend, "r", label = "dx_notrend", alpha=0.7)
plt.legend(loc='best')
#===== gy =====
plt.subplot(232)
plt.plot(gy_g_array, "blue", label="gy")
plt.plot(gy_notrend, "r", label = "gy_notrend", alpha=0.7)
plt.legend(loc='best')
plt.subplot(235)
plt.plot(gy_r_array, "blue", label="dy")
plt.plot(dy_notrend, "r", label = "dy_notrend", alpha=0.7)
plt.legend(loc='best')
#===== gz =====
plt.subplot(233)
plt.plot(gz_g_array, "blue", label="gz")
plt.plot(gz_notrend, "r", label = "gz_notrend", alpha=0.7)
plt.legend(loc='best')
plt.subplot(236)
plt.plot(gz_r_array, "blue", label="dz")
plt.plot(dz_notrend, "r", label = "dz_notrend", alpha=0.7)
plt.legend(loc='best')
#===== show plot =====
plt.show()
'''#===== Show Raw Data's integral ====='''
def show_raw_mean(self):
if self.fileLineEdit.text().isEmpty(): self.show_error_message(index=0)
ax_mean = np.mean(self.raw_data['ax'])
ay_mean = np.mean(self.raw_data['ay'])
az_mean = np.mean(self.raw_data['az'])
gx_mean = np.mean(self.raw_data['gx'])
gy_mean = np.mean(self.raw_data['gy'])
gz_mean = np.mean(self.raw_data['gz'])
mx_mean = np.mean(self.raw_data['mx'])
my_mean = np.mean(self.raw_data['my'])
mz_mean = np.mean(self.raw_data['mz'])
show_text = u"mean_a_g_m:\t%.6f\t%.6f\t%.6f\t%.6f\t%.6f\t%.6f\t%.6f\t%.6f\t%.6f" \
%(ax_mean, ay_mean, az_mean, gx_mean, gy_mean, gz_mean, mx_mean, my_mean, mz_mean)
self.show_raw_mean_le.setText(show_text)
def show_raw_2d_acc_data(self):
if self.fileLineEdit.text().isEmpty(): self.show_error_message(index=0)
ax_a_array,ax_v_array,ax_s_array = self.another_integral(self.acc_normalize(self.raw_data['ax']))
ay_a_array,ay_v_array,ay_s_array = self.another_integral(self.acc_normalize(self.raw_data['ay']))
az_a_array,az_v_array,az_s_array = self.another_integral(self.acc_normalize(self.raw_data['az']))
#plt.plot(np.insert(np.diff(ax_a_array),0,0) +500, "r", label="ax")
#plt.plot(np.insert(np.diff(ay_a_array),0,0) +0, "g", label="ay")
#plt.plot(np.insert(np.diff(az_a_array),0,0) -500, "b", label="az")
'''
s = ""
w = open('acc_integrate_data.txt', 'w')
print >> w, "ax\tay\taz"
for i in range(ax_s_array.size):
s = str(ax_s_array[i]) + "\t" + str(ay_s_array[i]) + "\t" +str(az_s_array[i])
print >> w, s
s=""
w.close()
'''
#===== ax =====
plt.subplot(331)
plt.plot(ax_a_array, "blue", label="ax_a")
plt.legend(loc='upper right')
plt.subplot(334)
plt.plot(ax_v_array, "blue", label="ax_v")
plt.legend(loc='upper right')
plt.subplot(337)
plt.plot(ax_s_array, "blue", label="ax_s")
plt.legend(loc='upper right')
#===== ay =====
plt.subplot(332)
plt.plot(ay_a_array, "green", label="ay_a")
plt.legend(loc='upper right')
plt.subplot(335)
plt.plot(ay_v_array, "green", label="ay_v")
plt.legend(loc='upper right')
plt.subplot(338)
plt.plot(ay_s_array, "green", label="ay_s")
plt.legend(loc='upper right')
#===== az =====
plt.subplot(333)
plt.plot(az_a_array, "red", label="az_a")
plt.legend(loc='upper right')
plt.subplot(336)
plt.plot(az_v_array, "red", label="az_v")
plt.legend(loc='upper right')
plt.subplot(339)
plt.plot(az_s_array, "red", label="az_s")
plt.legend(loc='upper right')
plt.show()
def show_raw_3d_acctrace(self):
if len(self.raw_data) < 1:
self.show_error_message(0)
else:
ax_array,vx_array,sx_array = self.another_integral(self.acc_normalize(self.raw_data['ax']))
ay_array,vy_array,sy_array = self.another_integral(self.acc_normalize(self.raw_data['ay']))
az_array,vz_array,sz_array = self.another_integral(self.acc_normalize(self.raw_data['az']))
mpl.rcParams['legend.fontsize'] = 24
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect('equal')
x = sx_array
y = sy_array
z = sz_array
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
max_axis_value = max(np.amax(x), np.amax(y), np.amax(z))
min_axis_value = min(np.amin(x), np.amin(y), np.amin(z))
ax.set_xlim(min_axis_value,max_axis_value)
ax.set_ylim(min_axis_value,max_axis_value)
ax.set_zlim(min_axis_value,max_axis_value)
ax.plot(x, y, z, 'b-', linewidth=2.0, label='tracker')
ax.plot(x, y, zs=min_axis_value, c='k' , zdir='z') # shadow on XY plane
ax.plot(y, z, min_axis_value, c='k' , zdir='x') #
#ax.annotate("start point", xyz=(x[0],y[0],z[0]), xyztext=(x[0]+1, y[0]+1, z[0]+1), arrowprops=dict(facecolor='black', shrink=0.05) )
'''
ax.annotate( "Value",
xy = (x[0], y[0]), xytext = (x[0]-20, y[0]-20), textcoords = 'offset points', ha = 'right', va = 'bottom',
bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
'''
ax.legend()
plt.show()
def show_raw_2d_gyro_data(self):
if self.fileLineEdit.text().isEmpty(): self.show_error_message(index=0)
gx_g_array,gx_r_array, gx_no_array = self.another_integral(self.gyro_normalize(self.raw_data['gx']))
gy_g_array,gy_r_array, gy_no_array = self.another_integral(self.gyro_normalize(self.raw_data['gy']))
gz_g_array,gz_r_array, gz_no_array = self.another_integral(self.gyro_normalize(self.raw_data['gz']))
#===== gx =====
plt.subplot(231)
plt.plot(gx_g_array, "blue", label="gx_g")
plt.legend(loc='best')
plt.subplot(234)
plt.plot(gx_r_array, "blue", label="gx_r")
plt.legend(loc='best')
#===== gy =====
plt.subplot(232)
plt.plot(gy_g_array, "green", label="gy_g")
plt.legend(loc='best')
plt.subplot(235)
plt.plot(gy_r_array, "green", label="gy_r")
plt.legend(loc='best')
#===== gz =====
plt.subplot(233)
#plt.plot(gz_array,"b", label="no diff bias")
plt.plot(gz_g_array, "red", label="gz_g")
plt.legend(loc='best')
plt.subplot(236)
#plt.plot(np.rad2deg(dz_array),"b", label="no diff bias")
plt.plot(gz_r_array, "red", label="gz_r")
plt.legend(loc='best')
plt.show()
def show_raw_3d_gyrotrace(self):
if len(self.raw_data) < 1:
self.show_error_message(0)
else:
gx_g_array,gx_r_array, gx_no_array = self.another_integral(self.gyro_normalize(self.raw_data['gx']))
gy_g_array,gy_r_array, gy_no_array = self.another_integral(self.gyro_normalize(self.raw_data['gy']))
gz_g_array,gz_r_array, gz_no_array = self.another_integral(self.gyro_normalize(self.raw_data['gz']))
mpl.rcParams['legend.fontsize'] = 18
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect('equal')
x = gx_r_array
y = gy_r_array
z = gz_r_array
ax.set_xlabel('rx axis')
ax.set_ylabel('ry axis')
ax.set_zlabel('rz axis')
ax.set_xlim(np.amin(x),np.amax(x))
ax.set_ylim(np.amin(y),np.amax(y))
ax.set_zlim(np.amin(z),np.amax(z))
ax.plot(x, y, z, 'r-', label='tracker')
ax.legend()
plt.grid()
plt.show()
def show_raw_2d_mag_data(self):
mx = self.raw_data['mx']
my = self.raw_data['my']
mz = self.raw_data['mz']
mx_adj, my_adj, mz_adj = self.mag_adj()
plt.subplot(211)
plt.plot(mx, 'blue', label='mx')
plt.plot(my, 'green', label='my')
plt.plot(mz, 'red', label='mz')
plt.subplot(212)
plt.plot(mx_adj, 'blue', label='mx_adj')
plt.plot(my_adj, 'green', label='my_adj')
plt.plot(mz_adj, 'red', label='mz_adj')
plt.legend(loc='upper right', fontsize=16)
plt.show()
'''#===== algorithm =====#'''
def moving_average(self, a, n=101) :
ret = np.cumsum(a, dtype=float)
ret[n:] = ret[n:] - ret[:-n]
return ret[n - 1:] / n
def another_integral(self,lst, time_lst=None):
acc = np.array(lst, dtype=np.float32)
if time_lst != None:
time = time_lst
else:
time = self.raw_data['time']
vel = integrate.cumtrapz(acc, time, initial=0)
dist = integrate.cumtrapz(vel, time, initial=0)
return acc, vel, dist
def basic_basic_integral(self, target_list, time_diff_list=None):
a_array = target_list
if time_diff_list:
time_diff_array = time_diff_list
else:
time_diff_array = self.raw_data['time_diff'].copy()
#time_diff_array= np.ones(self.raw_data['time'].size)
v_array = [0]
s_array = [0]
for i in range(time_diff_array.size):
s_data = s_array[-1] + v_array[-1] * time_diff_array[i] + 0.5 * a_array[i] * (time_diff_array[i]**2 )
s_array.append(s_data)
v_data= v_array[-1] + a_array[i] * time_diff_array[i]
v_array.append(v_data)
v_array = np.array(v_array, np.float32)
s_array = np.array(s_array, np.float32)
return a_array, v_array, s_array
#r=roll, p=pitch, h= heading
def rotate_array(self, roll, pitch, heading):
r= roll
p= pitch
h= heading
C_a2b = np.array([
[np.cos(p)*np.cos(h), np.cos(p)*np.sin(h), -1*np.sin(p)],
[np.sin(r)*np.sin(p)*np.cos(h)-np.cos(r)*np.sin(h), np.sin(r)*np.sin(p)*np.sin(h)+np.cos(r)*np.cos(h), np.sin(r)*np.cos(p)],
[np.cos(r)*np.sin(p)*np.cos(h)+np.sin(r)*np.sin(h), np.cos(r)*np.sin(p)*np.sin(h)-np.sin(r)*np.cos(h), np.cos(r)*np.cos(p)]
])
return C_a2b
def threshold_test(self):
mx_adj, my_adj, mz_adj = self.mag_adj()
m_normal = np.sqrt(np.square(mx_adj)+np.square(my_adj)+np.square(mz_adj))
heading = np.degrees(np.arctan2(mx_adj/m_normal, my_adj/m_normal))
heading_diff = np.diff(heading)
rotate_index = np.insert(np.where(np.absolute(heading_diff)>20.0), 0, 0)
plt.plot(heading_diff)
plt.show()
angle_lst = []
for i in range(rotate_index.size):
try:
angle_onestep = np.mean(heading[rotate_index[i]: rotate_index[i+1]])
angle_lst.append(angle_onestep)
except:
pass
print angle_lst
def std_threshold(self, lst): #將指定門檻職以外的砍除
lst = np.array(lst)
index_array = []
threshold = 10
a = np.insert(np.where(np.diff(lst)>threshold),0,0)
a = np.append(a, lst.size)
lst_2 = lst.copy()
for i in range(a.size-1):
lst_2[a[i]:a[i+1]+1] = np.mean(lst[a[i]:a[i+1]+1])
return lst_2
'''#===== Filter Area =====#'''
def fft_test(self):
#t = np.arange(0, 1.0, 1.0/8000)
#signal = np.sin(2*np.pi*156.25*t) + 2*np.sin(2*np.pi*234.375*t)
axis = str(self.axis_combobox.currentText())
signal = self.raw_data[axis] - self.bias_dict[axis]
n = signal.size
time_step = 0.007
fftResult = (np.abs(np.fft.fft(signal)/n))**2
freq = np.fft.fftfreq(n, d=time_step)
plt.plot(1/freq, fftResult, 'g')
plt.xlim(0)
plt.grid('on')
plt.title('Power Spectrum')
plt.show()
def fft_test2(self):
axis = str(self.axis_combobox.currentText())
if axis.startswith('a'):
normal_para = 16384.0
elif axis.startswith('g'):