-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
220 lines (181 loc) · 6.28 KB
/
main.py
File metadata and controls
220 lines (181 loc) · 6.28 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
import tkinter as tk
from tkinter import ttk, messagebox
from datetime import datetime, date
import statistics
import csv
import os
# ================== Paths ==================
EXPORT_DIR = "data/exports"
os.makedirs(EXPORT_DIR, exist_ok=True)
# ================== Batch Data ==================
batch_data = {}
sample_counter = 1
current_sample_id = None
measurements = []
# ================== Sample Management ==================
def new_sample():
global sample_counter, current_sample_id, measurements
current_sample_id = f"SAMPLE_{sample_counter:03d}"
sample_counter += 1
measurements = []
reset_table_only()
summary_var.set(f"Current Sample: {current_sample_id}")
def reset_table_only():
for row in tree.get_children():
tree.delete(row)
# ================== Core Calculation ==================
def calculate_caffeine():
try:
max_rep = int(entry_reps.get())
if len(measurements) >= max_rep:
messagebox.showwarning("Limit Reached", "Maximum number of replicates reached.")
return
Asamp = float(entry_Asamp.get())
slope = float(entry_slope.get())
mass = float(entry_mass.get())
volume_ml = float(entry_volume.get())
dilution = float(entry_dilution.get())
wdm = float(entry_wdm.get())
if slope == 0 or mass == 0 or wdm == 0:
raise ValueError
# ---- Calculations ----
C = Asamp / slope
amount_mg = C * (volume_ml / 1000) * dilution
mg_per_g = amount_mg / mass
percent = mg_per_g / 10 * (100 / wdm)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
record = {
"Asamp": Asamp,
"C": C,
"total": amount_mg,
"mg_g": mg_per_g,
"percent": percent,
"time": timestamp
}
measurements.append(record)
tree.insert(
"",
"end",
values=(
len(measurements),
timestamp,
f"{Asamp:.2f}",
f"{C:.2f}",
f"{amount_mg:.2f}",
f"{mg_per_g:.2f}",
f"{percent:.2f}"
)
)
update_summary()
except ValueError:
messagebox.showerror("Input Error", "Please enter valid numeric values.")
# ================== Summary ==================
def update_summary():
if not measurements:
return
percents = [m["percent"] for m in measurements]
mean_val = statistics.mean(percents)
sd_val = statistics.stdev(percents) if len(percents) > 1 else 0
rsd_val = (sd_val / mean_val) * 100 if mean_val != 0 else 0
summary_var.set(
f"Current Sample: {current_sample_id}\n"
f"Replicates: {len(percents)}\n"
f"Mean (% w/w): {mean_val:.2f}\n"
f"SD: {sd_val:.2f}\n"
f"RSD (%): {rsd_val:.2f}"
)
batch_data[current_sample_id] = {
"measurements": measurements.copy(),
"summary": {
"mean": mean_val,
"sd": sd_val,
"rsd": rsd_val
}
}
# ================== Export CSV ==================
def export_csv():
if not batch_data:
messagebox.showwarning("No Data", "No batch data to export.")
return
filename = f"TCC_Export_{date.today().strftime('%Y%m%d')}.csv"
filepath = os.path.join(EXPORT_DIR, filename)
with open(filepath, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow([
"SampleID", "Replicate", "DateTime",
"Asamp", "C_mg_L", "Total_mg", "mg_g", "Percent_w_w",
"Mean", "SD", "RSD"
])
for sample_id, data in batch_data.items():
summary = data["summary"]
for i, m in enumerate(data["measurements"], start=1):
writer.writerow([
sample_id,
i,
m["time"],
f"{m['Asamp']:.2f}",
f"{m['C']:.2f}",
f"{m['total']:.2f}",
f"{m['mg_g']:.2f}",
f"{m['percent']:.2f}",
f"{summary['mean']:.2f}",
f"{summary['sd']:.2f}",
f"{summary['rsd']:.2f}"
])
messagebox.showinfo("Export Complete", f"CSV exported:\n{filepath}")
# ================== GUI ==================
root = tk.Tk()
root.title("TCC – Tea Caffeine Calculator")
root.geometry("950x700")
frame = ttk.Frame(root, padding=15)
frame.pack(fill="both", expand=True)
# ---- Inputs ----
inputs = [
("Sample Area (Asamp)", "Asamp"),
("Calibration Slope", "slope"),
("Sample Mass (g)", "mass"),
("Extraction Volume (mL)", "volume"),
("Dilution Factor", "dilution"),
("Dry Matter (%)", "wdm")
]
entries = {}
for i, (label, key) in enumerate(inputs):
ttk.Label(frame, text=label).grid(row=i, column=0, sticky="w", pady=4)
e = ttk.Entry(frame)
e.grid(row=i, column=1, pady=4)
entries[key] = e
entry_Asamp = entries["Asamp"]
entry_slope = entries["slope"]
entry_mass = entries["mass"]
entry_volume = entries["volume"]
entry_dilution = entries["dilution"]
entry_wdm = entries["wdm"]
# Defaults
entry_mass.insert(0, "1")
entry_volume.insert(0, "300")
entry_dilution.insert(0, "10")
entry_wdm.insert(0, "100")
# ---- Replicates ----
ttk.Label(frame, text="Max Replicates").grid(row=0, column=2, padx=20)
entry_reps = ttk.Spinbox(frame, from_=1, to=20, width=5)
entry_reps.set(6)
entry_reps.grid(row=0, column=3)
# ---- Buttons ----
ttk.Button(frame, text="Calculate", command=calculate_caffeine).grid(row=7, column=0, pady=10)
ttk.Button(frame, text="New Sample", command=new_sample).grid(row=7, column=1, pady=10)
ttk.Button(frame, text="Export CSV (Batch)", command=export_csv).grid(row=7, column=2, pady=10)
# ---- Table ----
columns = ("#", "DateTime", "Asamp", "C (mg/L)", "Total (mg)", "mg/g", "% w/w")
tree = ttk.Treeview(frame, columns=columns, show="headings", height=10)
for col in columns:
tree.heading(col, text=col)
tree.column(col, anchor="center")
tree.grid(row=8, column=0, columnspan=4, pady=15, sticky="nsew")
# ---- Summary ----
summary_var = tk.StringVar()
ttk.Label(frame, textvariable=summary_var, foreground="blue").grid(
row=9, column=0, columnspan=4, pady=10
)
# ---- Init ----
new_sample()
root.mainloop()