Last active 4 days ago

Revision 485cb446571f7c28ced8fcb48542b4e1f0f769f7

This file can't be rendered. View the full file.
SpringCleanAndAnalyze.py Raw
1import pandas as pd
2import glob
3import os
4
5
6# ---------------------------------------------------------
7# STEP 1 - Ask user which spring to process
8# ---------------------------------------------------------
9spring_name = input("Enter spring number (example: 1040_01): ").strip()
10
11threshold = float(
12 input(
13 "Enter peak detection threshold (mm): "
14 )
15)
16
17
18# ---------------------------------------------------------
19# STEP 2 - Find all matching test files
20# ---------------------------------------------------------
21file_pattern = f"Spring_{spring_name}_Test_*.csv"
22
23file_list = glob.glob(file_pattern)
24
25# Make sure files are processed in order
26file_list.sort()
27
28if len(file_list) == 0:
29 print(f"No files found matching: {file_pattern}")
30 exit()
31
32
33# ---------------------------------------------------------
34# STEP 3 - Variables used while combining files
35# ---------------------------------------------------------
36combined_data = []
37
38time_offset = 0
39
40
41# ---------------------------------------------------------
42# STEP 4 - Process each test file
43# ---------------------------------------------------------
44for test_number, file in enumerate(file_list, start=1):
45
46 print(f"Processing: {file}")
47
48 # Read CSV
49 df = pd.read_csv(file)
50
51 # Remove rows containing empty data
52 df = df.dropna()
53
54 # Time column name
55 time_column = "Time (s)"
56
57 # Create Test column
58 df["Test"] = test_number
59
60 # Create continuous time column
61 df["Continuous Time (s)"] = df[time_column] + time_offset
62
63 # Determine ending time for next test
64 last_time = df[time_column].iloc[-1]
65
66 time_offset += last_time
67
68 # Store cleaned data
69 combined_data.append(df)
70
71
72# ---------------------------------------------------------
73# STEP 5 - Combine all tests into one dataframe
74# ---------------------------------------------------------
75final_df = pd.concat(combined_data, ignore_index=True)
76
77
78# ---------------------------------------------------------
79# STEP 6 - Create output filename
80# ---------------------------------------------------------
81output_file = f"Spring_{spring_name}_Cleaned.csv"
82
83
84# ---------------------------------------------------------
85# STEP 7 - Save cleaned data
86# ---------------------------------------------------------
87final_df.to_csv(output_file, index=False)
88
89print()
90print(f"Finished Cleaning!")
91print(f"Output saved as: {output_file}")
92
93
94# ---------------------------------------------------------------------
95# ANALYZING SECTION
96# ---------------------------------------------------------------------
97
98
99# ---------------------------------------------------------
100# STEP 2 - Open cleaned file
101# ---------------------------------------------------------
102
103input_file = f"Spring_{spring_name}_Cleaned.csv"
104
105print(f"\nLoading {input_file}...")
106
107df = pd.read_csv(input_file)
108
109
110# ---------------------------------------------------------
111# STEP 3 - Define important column names
112# ---------------------------------------------------------
113
114extension_column = "Extension (mm)"
115
116
117# ---------------------------------------------------------
118# STEP 4 - Create Above Threshold flag
119#
120# 1 = Extension is above threshold
121# 0 = Extension is below threshold
122# ---------------------------------------------------------
123print("Creating Above Threshold...")
124df["Above Threshold"] = (
125 df[extension_column] >= threshold
126).astype(int)
127
128
129# ---------------------------------------------------------
130# STEP 5 - Create Previous Above Threshold column
131#
132# Shift the Above Threshold column down by one row
133# ---------------------------------------------------------
134print("Creating Previous Above Threshold...")
135df["Previous Above Threshold"] = (
136 df["Above Threshold"]
137 .shift(1)
138 .fillna(0)
139 .astype(int)
140)
141
142
143# ---------------------------------------------------------
144# STEP 6 - Create Rising Edge column
145#
146# Rising Edge occurs when:
147#
148# Previous = 0
149# Current = 1
150# ---------------------------------------------------------
151print("Creating Rising Edge...")
152df["Rising Edge"] = (
153 (df["Above Threshold"] == 1)
154 &
155 (df["Previous Above Threshold"] == 0)
156).astype(int)
157
158
159# ---------------------------------------------------------
160# STEP 7 - Create Falling Edge column
161#
162# Falling Edge occurs when:
163#
164# Previous = 1
165# Current = 0
166# ---------------------------------------------------------
167print("Creating Falling Edge...")
168df["Falling Edge"] = (
169 (df["Above Threshold"] == 0)
170 &
171 (df["Previous Above Threshold"] == 1)
172).astype(int)
173
174
175# ---------------------------------------------------------
176# STEP 8 - Create Cycle Number
177#
178# Every Rising Edge starts a new cycle.
179#
180# Example:
181#
182# Rising Edge:
183# 0 0 1 0 0 1 0
184#
185# Cycle Number:
186# 0 0 1 1 1 2 2
187# ---------------------------------------------------------
188print("Creating Cycle Number...")
189df["Cycle Number"] = (
190 df["Rising Edge"]
191 .cumsum()
192)
193
194
195# ---------------------------------------------------------
196# STEP 9 - Save analyzed file
197# ---------------------------------------------------------
198print("Saving Analyzed File...")
199output_file = f"Spring_{spring_name}_Analyzed.csv"
200
201df.to_csv(output_file, index=False)
202
203
204# ---------------------------------------------------------
205# STEP 11 - Create Peak Summary
206# ---------------------------------------------------------
207
208peak_summary = []
209
210print("Creating Cycle Numbers...")
211# Get all valid cycle numbers
212cycle_numbers = sorted(
213 df[df["Cycle Number"] > 0]["Cycle Number"].unique()
214)
215
216for cycle in cycle_numbers:
217
218 # Get only rows for this cycle that are above threshold
219 cycle_data = df[
220 (df["Cycle Number"] == cycle)
221 &
222 (df["Above Threshold"] == 1)
223 ]
224
225 # Skip empty cycles just in case
226 if len(cycle_data) == 0:
227 continue
228
229 # Find row with maximum load
230 peak_index = cycle_data["Load (N)"].idxmax()
231
232 peak_row = df.loc[peak_index]
233
234 peak_summary.append({
235 "Cycle Number": cycle,
236 "Test": peak_row["Test"],
237 "Peak Load (N)": peak_row["Load (N)"],
238 "Peak Extension (mm)": peak_row[extension_column],
239 "Peak Time (s)": peak_row["Continuous Time (s)"],
240 "Peak Row": peak_index
241 })
242
243# ---------------------------------------------------------
244# STEP 12 - Create dataframe
245# ---------------------------------------------------------
246
247peak_df = pd.DataFrame(peak_summary)
248
249# ---------------------------------------------------------
250# STEP 13 - Save peak summary
251# ---------------------------------------------------------
252print("Saving peak summary...")
253peak_output_file = (
254 f"Spring_{spring_name}_Peaks.csv"
255)
256
257peak_df.to_csv(
258 peak_output_file,
259 index=False
260)
261
262# Cycles per test count
263cycles_per_test = (
264 peak_df.groupby("Test").size()
265)
266
267print("Cycles Per Test:")
268
269for test, count in cycles_per_test.items():
270 print(f"Test {int(test)}: {count}")
271
272# ---------------------------------------------------------
273# STEP 14 - Report results
274# ---------------------------------------------------------
275
276total_cycles = int(
277 df["Cycle Number"].max()
278)
279
280print("\nAnalysis Complete")
281print(
282 f"Total Cycles Found: "
283 f"{total_cycles}"
284)
285
286print(
287 f"Total Peaks Found: "
288 f"{len(peak_summary)}"
289)
290
291print(
292 f"Analyzed File: "
293 f"{output_file}"
294)
295
296print(
297 f"Peak Summary File: "
298 f"{peak_output_file}"
299)
300
301input("\nPress Enter to exit")