1#!/usr/bin/env python
2
3##########################################################################
4# Copyright (c) 2009, ETH Zurich.
5# All rights reserved.
6#
7# This file is distributed under the terms in the attached LICENSE file.
8# If you do not find this file, copies can be found by writing to:
9# ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
10##########################################################################
11
12# this program munges readings to produce a gnuplot file, data in the form:
13#   <index> [<reading> ...]
14# is converted to:
15#   <index> <n_readings> <median> <mean> <std dev.> <min> <max>
16#
17# blank lines, and lines starting with a '#', are ignored
18#
19# -- andrewb@cse.unsw.edu.au, 2003/10/31, updated 2009/09/04
20
21import sys, string, math
22
23class Stats:
24    def __init__(self, data):
25        self.nvalues = len(data)
26        self.minimum = self.maximum = self.median = self.mean = self.stddev = float('nan')
27        if self.nvalues == 0:
28            return
29        data.sort()
30        self.minimum = data[0]
31        self.maximum = data[-1]
32        self.mean = float(sum(data)) / self.nvalues
33        if (self.nvalues % 2 == 0):
34            self.median = (data[self.nvalues / 2]
35                           + data[self.nvalues / 2 - 1]) / 2.0
36        else:
37            self.median = data[self.nvalues / 2]
38
39        diffs = 0.0
40        for datum in data:
41            diffs += (datum - self.mean) ** 2
42        self.stddev = math.sqrt(diffs / self.nvalues)
43
44
45if __name__ == "__main__":
46    if len(sys.argv) > 1:
47        try:
48            infile = open(sys.argv[1])
49        except:
50            sys.stderr.write("Error opening %s\n" % sys.argv[1])
51            sys.exit(1)
52    else:
53        infile = sys.stdin
54
55    for line in infile:
56        stripped = string.lstrip(line)
57        if (stripped == "" or stripped[0] == '#'):
58            sys.stdout.write(line)
59            continue
60
61        words = string.split(line)
62        if (len(words) == 0):
63            sys.stderr.write("Error parsing line: %s" % line)
64            sys.exit(1)
65
66        index = words[0]
67        data = map(float, words[1:])
68        if (len(data) == 0):
69            sys.stderr.write("Error parsing line: %s" % line)
70            sys.exit(1)
71
72        s = Stats(data)
73        sys.stdout.write("%s %s %s %s %s %s %s\n" % (index, s.nvalues,
74                         s.median, s.mean, s.stddev, s.minimum, s.maximum))
75