SNABSuite  0.x
Spiking Neural Architecture Benchmark Suite
1dim_plot.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 
4 # SNABSuite -- Spiking Neural Architecture Benchmark Suite
5 # Copyright (C) 2017 Christoph Jenzen
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>
19 
20 """
21 Plots data from one dimensional sweeps
22 """
23 from __future__ import division
24 from builtins import range
25 from past.utils import old_div
26 import argparse
27 
28 parser = argparse.ArgumentParser(description='Plot one-dimensional graphs')
29 
30 # Optional arguments
31 parser.add_argument("-nx", help="normalize x-values", action="store_true")
32 parser.add_argument("-ny", help="normalize y-values", action="store_true")
33 parser.add_argument("--ymin", type=float, help="minimal y-value")
34 parser.add_argument("--ymax", type=float, help="maximal y-value")
35 parser.add_argument(
36  "-ys", type=int, help="Column of std-deviation of y-values")
37 parser.add_argument("-x", type=int, help="Column of x-values", default=0)
38 parser.add_argument("-s", type=str, help="Name of the simulator", default="")
39 parser.add_argument("-o", type=str, help="Output filename", default="")
40 
41 # Required Parameters
42 parser.add_argument("-y", type=int, required=True, help="Column of y-values")
43 parser.add_argument("files", metavar="files", nargs='+', help="files to plot")
44 
45 args = parser.parse_args()
46 
47 
48 import numpy as np
49 import matplotlib.pyplot as plt
50 import matplotlib.colorbar
51 import sys
52 import os
53 
54 from dim_labels import *
55 
56 
57 def cm2inch(value):
58  return value / 2.54
59 
60 
61 def plot_measure(ax, xs, ys, ys_std, color, simulator, xlabel, ylabel,
62  ys_ref=None, first=True, ymin=None, ymax=None):
63 
64  ax.plot(xs, ys, color=color, lw=1.0, zorder=1, label=simulator)
65 
66  if ys_std is not None:
67  ax.plot(xs, ys - ys_std, lw=0.5,
68  linestyle=':', color=color, zorder=0)
69  ax.plot(xs, ys + ys_std, lw=0.5,
70  linestyle=':', color=color, zorder=0)
71 
72  ax.set_xlabel(xlabel)
73  ax.set_ylabel(ylabel)
74  if (ymin is None) and (ymax is None):
75  ax.autoscale_view()
76  elif ymax is None:
77  ax.set_ylim(bottom=ymin)
78  elif ymin is None:
79  ax.set_ylim(top=ymax)
80  else:
81  ax.set_ylim(bottom=ymin, top=ymax)
82 
83 
84 def normalize(data, norm):
85  for i in range(0, len(data)):
86  data[i] = old_div(data[i], norm)
87 
88 
89 def get_max(data):
90  idcs = np.isfinite(data)
91  return np.max(data[np.isfinite(data)])
92 
93 
94 def get_min(data):
95  idcs = np.isfinite(data)
96  return np.min(data[np.isfinite(data)])
97 
98 fig = plt.figure(figsize=(cm2inch(12), cm2inch(6.0)))
99 ax = fig.add_subplot(111)
100 
101 for target_file in args.files:
102  results = np.genfromtxt(target_file, delimiter=',', names=True)
103  keys = results.dtype.names
104  data = np.zeros((results.shape[0], len(keys)))
105  for i in range(0, len(results)):
106  data[i] = np.array(list(results[i]))
107 
108  xs = np.array(data[:, args.x])
109  ys = np.array(data[:, args.y])
110  ys_dev = None
111  if args.ys:
112  ys_dev = np.array(data[:, args.ys])
113 
114  try:
115  xlabel = DIM_LABELS[keys[args.x]]
116  ylabel = DIM_LABELS[keys[args.y]]
117  except:
118  xlabel = ""
119  ylabel = ""
120  if args.nx:
121  normalize(xs, np.abs(get_max(xs)))
122  xlabel = xlabel + " (normalized)"
123 
124  if args.ny:
125  ylabel = ylabel + " (normalized)"
126  max = get_max(np.abs(ys))
127  normalize(ys, max)
128  if args.ys:
129  normalize(ys_dev, max)
130  simulator = target_file.split('_')[-1].split('.csv')[0].split('.')[-1]
131  if args.s != "":
132  simulator = args.s
133  plot_measure(ax, xs, ys, ys_dev, color=SIMULATOR_COLORS[simulator],
134  simulator=SIMULATOR_LABELS[simulator], xlabel=xlabel,
135  ylabel=ylabel, ymin=args.ymin, ymax=args.ymax)
136 
137 if not os.path.exists("images"):
138  os.mkdir("images")
139 ax.legend(loc='lower center', bbox_to_anchor=(0.5, 1.05),
140  ncol=4)
141 
142 if args.o == "":
143  if args.files[-1].split('/')[-2]:
144  if not os.path.exists("images/" + args.files[-1].split('/')[-2]):
145  os.mkdir("images/" + args.files[-1].split('/')[-2])
146  if args.files[-1].split('/')[-1].split('_')[1] != "max":
147  fig.savefig("images/" + args.files[-1].split('/')[-2] + "/" + args.files[-1].split(
148  '/')[-1].split('_')[0] + ".pdf", format='pdf', bbox_inches='tight')
149  else:
150  fig.savefig("images/" + args.files[-1].split('/')[-2] + "/" + args.files[-1].split(
151  '/')[-1].split('_')[0] + "_max.pdf", format='pdf', bbox_inches='tight')
152  else:
153  fig.savefig("images/" + args.files[-1].split('/')[-1].split('_')
154  [0] + ".pdf", format='pdf', bbox_inches='tight')
155 else:
156  fig.savefig(args.o, format='pdf', bbox_inches='tight')
def get_max(data)
Definition: 1dim_plot.py:89
def get_min(data)
Definition: 1dim_plot.py:94
def plot_measure(ax, xs, ys, ys_std, color, simulator, xlabel, ylabel, ys_ref=None, first=True, ymin=None, ymax=None)
Definition: 1dim_plot.py:62
def cm2inch(value)
Definition: 1dim_plot.py:57
def normalize(data, norm)
Definition: 1dim_plot.py:84