Debian Codegraph @

src/battery-stats-graph

raw ◀ ▶
2 Debian patches touch this file
•1 #!/usr/bin/python3
2 # -*- coding: utf-8 -*-
3 #
4 # This file is part of the battery-stats package.
5 # Copyright (C) 2015 Antoine Beaupré <[email protected]>
6 # 2016 Petter Reinholdtsen <[email protected]>
7 #
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20
21 import argparse
22 import datetime
23 import fileinput
24 import glob
25 import logging
26 import os
27 import sys
28 import time
29
30 from matplotlib.ticker import FuncFormatter
31 import matplotlib
32 import matplotlib.pyplot as plt
33 import numpy as np
34
35 parser = argparse.ArgumentParser()
36 parser.add_argument('logfile', nargs='*',
37 default='/var/log/battery-stats.csv*',
38 help='logfile to read (default: %(default)s)')
39 parser.add_argument('--output', type=argparse.FileType('w'),
40 default=sys.stdout,
41 help='image to write (default to terminal if available, otherwise stdout)')
42 parser.add_argument('--death', type=int, default=5,
43 help='percentage of battery when it is considered dead (default: %(default)s)')
44 args = parser.parse_args()
45 if type(args.logfile) is str:
46 args.logfile = glob.glob(args.logfile)
47 logfiles = fileinput.input(args.logfile, openhook=fileinput.hook_compressed)
48
49 now = 'energy_now'
50 full = 'energy_full'
51 full_design = 'energy_full_design'
52
53 def parse_csv_np():
54 logging.debug('loading CSV file %s with NumPy', args.logfile)
55 data = np.genfromtxt(logfiles,
56 delimiter=',', names=True,
57 filling_values = 0.0)
58 # convert timestamp to datetime, but also select only relevant
59 # fields to avoid having to specify all
60 # XXX: it seems that datetime is not what plot expects, so stick
61 # with float and we convert later
62 #return data.astype([('timestamp', 'datetime64[s]'),
63 # ('energy_full', 'f'),
64 # ('energy_full_design', 'f'),
65 # ('energy_now', 'f')])
66 return data
67
68 def parse_csv_builtin(fields =
69 ['timestamp',
70 'energy_full', 'energy_full_design', 'energy_now',
71 'charge_now', 'charge_full', 'charge_full_design'
72 ]):
73 import csv
74 logging.debug('loading CSV file %s with builtin CSV module', args.logfile)
75 log = csv.DictReader(logfiles)
76 data = []
77 try:
78 for row in log:
79 v = []
80 for f in fields:
81 if f not in row or '' == row[f]:
82 v.append(None)
83 else:
84 v.append(row[f])
85 l = tuple(v)
86 data.append(l)
87 except csv.Error as e:
88 logging.warning('CSV file is corrupt, skipping remaining entries: %s', e)
89 logging.debug('building data array')
•90 return np.array(data, dtype=list(zip(fields, 'i'+'f'*(len(fields)-1))))
91
92 # the builtin CSV parser above is faster, we went from 8 to 2 seconds
93 # on our test data here there are probably other ways of making this
94 # even faster, see:
95 #
96 # http://stackoverflow.com/a/25508739/1174784
97 # http://softwarerecs.stackexchange.com/a/7510/506
98 #
99 # TL;DR: performance is currently fine, it could be improved with
100 # Numpy.fromfile(), Numpy.load() or pandas.read_csv() which should
101 # apparently all outperform the above code by an order of magnitude
102 parse_csv = parse_csv_builtin
103
104 def to_percent(y, position):
105 # Ignore the passed in position. This has the effect of scaling
106 # the default tick locations.
107 s = str(100 * y)
108
109 # The percent symbol needs escaping in latex
110 if matplotlib.rcParams['text.usetex']:
111 return s + r'$\%$'
112 else:
113 return s + '%'
114
115 def build_graph(data):
116 logging.debug('building graph')
117 # create vectorized converter (can take list-like objects as
118 # arguments)
119 dateconv = np.vectorize(datetime.datetime.fromtimestamp)
120 dates = dateconv(data['timestamp'])
121
122 fig, ax = plt.subplots()
123
124 # XXX: can't seem to plot all at once...
125 #plt.plot(dates, data[now], '-b', data[full], '-r')
126 # ... but once at a time seems to do the result i am looking for
127 ax.plot(dates, data[full_design] / data[full_design],
128 linestyle = '-',
129 color = 'black',
130 label='design')
131 ax.plot(dates, data[now] / data[full_design],
132 linestyle = '-',
133 linewidth = 0.1,
134 color='grey',
135 label='current')
136 ax.plot(dates, data[full] / data[full_design],
137 linestyle = '-',
138 color = 'red',
139 label='effective')
140
141 # legend and labels
142 ax.legend(loc='upper right')
143 ax.set_xlabel('time')
144 ax.set_ylabel('percent')
145 ax.set_title('Battery capacity statistics')
146
147 # Tell matplotlib to interpret the x-axis values as dates
148 ax.xaxis_date()
149 # Make space for and rotate the x-axis tick labels
150 fig.autofmt_xdate()
151
152 # Create the formatter using the function to_percent. This
153 # multiplies all the dfault labels by 100, making them all
154 # percentages
155 formatter = FuncFormatter(to_percent)
156
157 # Set the formatter
158 ax.yaxis.set_major_formatter(formatter)
159
160 def render_graph():
161 if args.output == sys.stdout and \
162 ('DISPLAY' in os.environ or sys.stdout.isatty()):
163 logging.info("drawing on tty")
164 plt.show()
165 else:
166 logging.info('drawing to file %s', args.output)
167 plt.savefig(args.output, bbox_inches='tight')
168
169 def guess_expiry(x, y, zero = 0):
170 fit = np.polyfit(data[full], data['timestamp'], 1)
171 #print "fit: %s" % fit
172
173 fit_fn = np.poly1d(fit)
174 #print "fit_fn: %s" % fit_fn
175 return datetime.datetime.fromtimestamp(fit_fn(zero))
176
177 if __name__ == "__main__":
178 logging.basicConfig(format='%(message)s', level=logging.DEBUG)
179 data = parse_csv()
180
181 if str(data[full_design][1]) in ['', 'nan']:
182 logging.warning('switching to charge_* prefix')
183 now = 'charge_now'
184 full = 'charge_full'
185 full_design = 'charge_full_design'
186
187
188 # XXX: this doesn't work because it counts all charge/discharge
189 # cycles, we'd need to reprocess the CSV to keep only the last
190 # continuous states
191 #death = guess_expiry(data[now], data['timestamp'])
192 #logging.info("this battery will be depleted in %s, on %s",
193 # death - datetime.datetime.now(), death)
194
195 # actual energy at which the battery is considered dead
196 # we compute the mean design capacity, then take the given percentage out of that
197 logging.debug('guessing expiry')
198 zero = args.death * np.mean(data[full_design]) / 100
199 death = guess_expiry(data[full], data['timestamp'], zero)
200 logging.info("this battery will reach end of life (%s%%) in %s, on %s",
201 args.death, death - datetime.datetime.now(), death)
202
203 build_graph(data)
204 render_graph()