Files
ciclovolametrie/cv_current_over_sqrt_scanrate.py
T

87 lines
2.8 KiB
Python
Raw Normal View History

"""Aggiunge ai CSV dell'ultimo ciclo due colonne derivate dalla corrente:
Corrente / sqrt(velocita' di scansione) e (Corrente / sqrt(v)) / v.
La velocita' di scansione (V/s) viene cercata nel nome del file (es. "0.5Vs").
Per ogni file viene chiesto conferma: premere invio per usare il valore
trovato, oppure digitarne uno diverso e premere invio. I file vengono
sovrascritti.
"""
import csv
import math
import re
import sys
from pathlib import Path
INPUT_SUFFIX = "_ultimo_ciclo"
SCAN_RATE_PATTERN = re.compile(r"(\d+(?:\.\d+)?)\s*[Vv][Ss]\b")
def find_scan_rate_in_filename(name: str) -> float | None:
match = SCAN_RATE_PATTERN.search(name)
return float(match.group(1)) if match else None
def ask_scan_rate(filename: str) -> float:
found = find_scan_rate_in_filename(filename)
if found is not None:
prompt = f"Velocita' di scansione trovata nel nome file: {found} V/s. Premi invio per usarla, oppure inserisci un valore: "
else:
prompt = "Velocita' di scansione non trovata nel nome file. Inserisci un valore (V/s): "
while True:
raw = input(prompt).strip()
if raw == "" and found is not None:
return found
try:
return float(raw)
except ValueError:
print("Valore non valido, inserisci un numero (es. 0.5).")
def add_current_over_sqrt_scanrate(path: Path, scan_rate: float) -> None:
with path.open("r", encoding="utf-8", newline="") as f:
reader = csv.reader(f, delimiter=";")
header = next(reader)
rows = [tuple(row) for row in reader]
header = [*header, "Current/sqrt(scan rate)", "Current/sqrt(scan rate)/scan rate"]
sqrt_scan_rate = math.sqrt(scan_rate)
new_rows = []
for row in rows:
current = float(row[1].replace(",", "."))
value_d = current / sqrt_scan_rate
value_e = value_d / scan_rate
new_rows.append((
*row,
f"{value_d:.4e}".replace(".", ","),
f"{value_e:.4e}".replace(".", ","),
))
with path.open("w", encoding="utf-8", newline="") as f:
writer = csv.writer(f, delimiter=";")
writer.writerow(header)
writer.writerows(new_rows)
def main(argv: list[str]) -> None:
folder = Path(argv[1]) if len(argv) > 1 else Path(__file__).parent
csv_files = sorted(
p for p in folder.glob("*.csv") if p.stem.endswith(INPUT_SUFFIX)
)
if not csv_files:
print(f"Nessun file *{INPUT_SUFFIX}.csv trovato in {folder}")
return
for csv_file in csv_files:
scan_rate = ask_scan_rate(csv_file.name)
add_current_over_sqrt_scanrate(csv_file, scan_rate)
print(f"OK {csv_file.name} (colonne Current/sqrt(scan rate) e Current/sqrt(scan rate)/scan rate aggiunte con v={scan_rate} V/s)")
if __name__ == "__main__":
main(sys.argv)