From af8ce2b332a7ea689982c3b002984e5d537ccff5 Mon Sep 17 00:00:00 2001 From: Nathan Campos Date: Sun, 8 Mar 2015 09:32:44 -0300 Subject: [PATCH] The Python script is back! --- battery_capacity.py | 88 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 battery_capacity.py diff --git a/battery_capacity.py b/battery_capacity.py new file mode 100644 index 0000000..3e8fadf --- /dev/null +++ b/battery_capacity.py @@ -0,0 +1,88 @@ +#!/usr/bin/env python + +import sys +import csv +import matplotlib.pyplot +from pprint import pprint + +# Constants +DATADIR = "data/" + +def parse_index(btype): + index = [] + bdir = DATADIR + btype + "/" + + with open(bdir + "index.csv", "rb") as f: + reader = csv.reader(f) + try: + for i, row in enumerate(reader): + if i > 0: + expcap = 0 + if row[4] != "": + expcap = int(row[4]) + + index.append({ + "show": bool(int(row[0])), + "brand": row[1], + "model": row[2], + "voltage": float(row[3]), + "exp_capacity": expcap, + "current": int(row[5]), + "type": row[6], + "cutoff": float(row[7]), + "file": row[8], + "comment": row[9] + }) + except csv.Error as err: + sys.exit("File %s, line %d: %s" % (filename, reader.line_num, err)) + + return index + +def parse_battery(filename, current, cutoff = 0.8): + mah = [] + volts = [] + + with open(filename, "rb") as f: + reader = csv.reader(f) + try: + for i, row in enumerate(reader): + voltage = float(row[2]) + mah.append(current * (float(i) / 3600)) + volts.append(voltage) + + if (voltage < cutoff): + break + except csv.Error as err: + sys.exit("File %s, line %d: %s" % (filename, reader.line_num, err)) + + return { "mah": mah, "volts": volts } + +def get_batteries(btype): + index = parse_index(btype) + bdir = DATADIR + btype + "/" + batteries = [] + + for battery in index: + if battery["show"]: + batteries.append({ "name": battery["brand"] + " " + battery["model"], + "data": parse_battery(bdir + battery["file"], battery["current"], battery["cutoff"]) }) + + return batteries + +if __name__ == "__main__": + batteries = get_batteries("9V") + + # Prepare the plot. + matplotlib.pyplot.style.use("ggplot") + + for batt in batteries: + matplotlib.pyplot.plot(batt["data"]["mah"], batt["data"]["volts"], label = batt["name"]) + + # Setup the plot. + matplotlib.pyplot.title("Battery Discharge") + matplotlib.pyplot.legend(loc = "upper right") + matplotlib.pyplot.xlabel("Capacity (mAh)") + matplotlib.pyplot.ylabel("Voltage (V)") + matplotlib.pyplot.grid(True) + matplotlib.pyplot.show() +