Source code

Download source archive ↓

upstream-extended/community/tools/rpy_statistics_collection/histogram.py

1#!/usr/bin/env python
2# Greg Von Kuster
3
4import sys
5
6# from rpy import *
7import rpy2.robjects as robjects
8from rpy2.robjects.packages import importr
9
10r = robjects.r
11grdevices = importr("grDevices")
12
13
14assert sys.version_info[:2] >= (2, 4)
15
16
17def stop_err(msg):
18    sys.stderr.write(msg)
19    sys.exit()
20
21
22def main():
23
24    # Handle input params
25    in_fname = sys.argv[1]
26    out_fname = sys.argv[2]
27    try:
28        column = int(sys.argv[3]) - 1
29    except Exception:
30        stop_err(
31            "Column not specified, your query does not contain a column of numerical data."
32        )
33    title = sys.argv[4]
34    xlab = sys.argv[5]
35    breaks = int(sys.argv[6])
36    if breaks == 0:
37        breaks = "Sturges"
38    if sys.argv[7] == "true":
39        density = True
40    else:
41        density = False
42    if len(sys.argv) >= 9 and sys.argv[8] == "true":
43        frequency = True
44    else:
45        frequency = False
46
47    matrix = []
48    skipped_lines = 0
49    first_invalid_line = 0
50    invalid_value = ""
51    i = 0
52    for i, line in enumerate(file(in_fname)):  # noqa F821
53        valid = True
54        line = line.rstrip("\r\n")
55        # Skip comments
56        if line and not line.startswith("#"):
57            # Extract values and convert to floats
58            row = []
59            try:
60                fields = line.split("\t")
61                val = fields[column]
62                if val.lower() == "na":
63                    row.append(float("nan"))
64            except Exception:
65                valid = False
66                skipped_lines += 1
67                if not first_invalid_line:
68                    first_invalid_line = i + 1
69            else:
70                try:
71                    row.append(float(val))
72                except ValueError:
73                    valid = False
74                    skipped_lines += 1
75                    if not first_invalid_line:
76                        first_invalid_line = i + 1
77                        invalid_value = fields[column]
78        else:
79            valid = False
80            skipped_lines += 1
81            if not first_invalid_line:
82                first_invalid_line = i + 1
83
84        if valid:
85            matrix += row
86
87    if skipped_lines < i:
88        try:
89            # a = r.array( matrix )
90            fv = robjects.FloatVector(matrix)
91            a = r["matrix"](fv, ncol=1, byrow=True)
92            # r.pdf( out_fname, 8, 8 )
93            r.pdf(out_fname, 8, 8)
94            histogram = r.hist(
95                a, probability=not frequency, main=title, xlab=xlab, breaks=breaks
96            )
97            if density:
98                density = r.density(a)
99                if frequency:
100                    scale_factor = len(matrix) * (
101                        histogram["mids"][1] - histogram["mids"][0]
102                    )  # uniform bandwidth taken from first 2 midpoints
103                    density["y"] = map(lambda x: x * scale_factor, density["y"])
104                r.lines(density)
105            # r.dev_off()
106            grdevices.dev_off()
107        except Exception as exc:
108            stop_err("%s" % str(exc))
109    else:
110        if i == 0:
111            stop_err("Input dataset is empty.")
112        else:
113            stop_err("All values in column %s are non-numeric." % sys.argv[3])
114
115    print("Histogram of column %s. " % sys.argv[3])
116    if skipped_lines > 0:
117        print(
118            "Skipped %d invalid lines starting with line #%d, '%s'."
119            % (
120                skipped_lines,
121                first_invalid_line,
122                invalid_value,
123            )
124        )
125
126    # r.quit( save="no" )
127
128
129if __name__ == "__main__":
130    main()