-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathax3_median.py
155 lines (140 loc) · 5.45 KB
/
ax3_median.py
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
#!/usr/bin/env python3
# coding=UTF-8
#
# BSD 2-Clause License
#
# Copyright (c) 2020, Jason Leake
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Median filter for AX3 CSV data
#
# Axes:
# X is the long axis
# Y is the across-the-device axis
# Z is across the thickness of the device axis
from Row import Row
from tkinter import filedialog
import argparse
import csv
import math
import numpy as np
import os
import sys
import tkinter as tk
from medianfilter import medianFilter
class MedianProcessor:
def makeOutFile(self, filename):
""" Make output filename """
path, name = os.path.split(filename)
newName = "median_" + name
fullPath = os.path.join(path, newName)
print("Output file is", fullPath)
return fullPath
def process(self, filename, window):
""" Process the file """
# Count number of lines in file to get array dimension
print(f"Median window size is {window}")
print("Count lines in file")
count = 0
with open(filename, "rt", newline="\n") as fh:
line = fh.readline().strip()
while line:
row = Row(line)
if row.skip:
pass
else:
count += 1
if count % 1000000 == 0:
print(f"{count} lines counted")
line = fh.readline().strip()
# Set initial values of array to match actual field length
timestamp = np.array(["YYYY-MM-DD HH:MM:SS.FFF" for _ in range(count)])
x = np.zeros((count,))
y = np.zeros((count,))
z = np.zeros((count,))
print("Read file")
firstLine = None
with open(filename, "rt", newline="\n") as fh:
line = fh.readline().strip()
index = 0
while line:
row = Row(line)
if row.skip:
pass
else:
if firstLine is None:
firstLine = row.timestamp
timestamp[index] = row.timestamp
x[index] = row.val[0]
y[index] = row.val[1]
z[index] = row.val[2]
index += 1
if index % 1000000 == 0:
print(f"{index} data lines read")
line = fh.readline().strip()
print("Calculate x axis medians")
medx = medianFilter(x, window, len(x)//50)
print("Calculate y axis medians")
medy = medianFilter(y, window, len(y)//50)
print("Calculate z axis medians")
medz = medianFilter(z, window, len(z)//50)
outputFilename = self.makeOutFile(filename)
lineEnd = "\r\n"
with open(outputFilename, "w") as outfile:
outfile.write("datetime, x, y, z{}".format(lineEnd))
for index in range(len(timestamp)):
outfile.write("{},{:.06f},{:.06f},{:.06f}{}".format(
timestamp[index], medx[index],
medy[index], medz[index], lineEnd))
return outputFilename
def main():
if len(sys.argv) < 2:
root = tk.Tk()
root.withdraw()
filePath = filedialog.askopenfilename(
filetypes = [("Comma separated file (CSV) format",".csv")])
window = 7
else:
parser = argparse.ArgumentParser(description=
"Convert accelerometer file to per second values")
parser.add_argument("filename", help="Input filename")
parser.add_argument("--window", help="Window size",
type=int, default="7")
args = parser.parse_args()
filePath = args.filename
name, extension = os.path.splitext(filePath)
window = args.window
if window < 0:
print(f"Bad value for window, {window}, using 25")
window = 7
if window % 2 != 1:
print(f"Window size must be odd, {window}, using 25")
window = 7
if extension == ".CWA":
print("You need the .csv, not the .CWA", file=stderr)
os.exit(0)
processor = MedianProcessor()
processor.process(filePath, window)
if __name__ == "__main__":
main()