SNABSuite  0.x
Spiking Neural Architecture Benchmark Suite
2dim_plot.py
Go to the documentation of this file.
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 
4 # SNABSuite -- Spiking Neural Architecture Benchmark Suite
5 # Copyright (C) 2017 Andreas Stöckel, 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 for two dimensional sweeps
22 """
23 from __future__ import division
24 
25 from builtins import range
26 from past.utils import old_div
27 import argparse
28 
29 parser = argparse.ArgumentParser(description='Plot two-dimensional images')
30 
31 # Optional arguments
32 parser.add_argument("--zmin", type=float, help="minimal z-value")
33 parser.add_argument("--zmax", type=float, help="maximal z-value")
34 parser.add_argument(
35  "-nl", type=int, help="Number of levels/ticks in z", default=11)
36 parser.add_argument("-q", help="qualitative Colormap", action="store_true")
37 parser.add_argument("-c", help="draw contour lines", action="store_true")
38 
39 
40 # Required Parameters
41 parser.add_argument("-z", type=int, required=True, help="Column of z-values")
42 parser.add_argument("files", metavar="Files", nargs='+', help="files to plot")
43 
44 args = parser.parse_args()
45 
46 import numpy as np
47 import matplotlib.pyplot as plt
48 import matplotlib.colorbar
49 import sys
50 import os
51 from dim_labels import *
52 
53 
54 def cm2inch(value):
55  return value / 2.54
56 
57 
58 def round_to_divisable(value, divisable):
59  if value == 0:
60  return 0
61  temp = np.abs(value)
62  a = 0
63  while temp < divisable:
64  temp *= 10.0
65  a += 1
66  if temp % divisable == 0:
67  return value
68  res = old_div((temp - (temp % divisable) + divisable), (10.0**a))
69  if value < 0:
70  return -res
71  return res
72 
73 
74 def plot_measure2d(xs, ys, zs, xlabel, ylabel, zlabel="", zmin=None,
75  zmax=None, qualitative=False, contour=True, title=None):
76  fig = plt.figure(figsize=(cm2inch(5.5), cm2inch(5.5)))
77 
78  ax1 = fig.add_axes([0.0, 0.25, 1.0, 0.85])
79  if title is not None:
80  plt.title(title)
81  ax2 = fig.add_axes([0.0, 0.0, 1.0, 0.05])
82 
83 
84  _, steps_x = np.unique(xs, return_counts=True)
85  _, steps_y = np.unique(ys, return_counts=True)
86  steps_x = np.max(steps_x)
87  steps_y = np.max(steps_y)
88  xs = xs.reshape((steps_y, steps_x))
89  ys = ys.reshape((steps_y, steps_x))
90  zs = zs.reshape((steps_y, steps_x))
91  zs = zs.transpose()
92 
93  # Auto-scale
94  idcs = np.isfinite(zs)
95  if np.sum(idcs) == 0:
96  return
97  if zmin is None:
98  zmin = np.min(zs[idcs])
99  if 0 < zmin < 1:
100  zmin = 0
101  else:
102  zmin = int(zmin)
103  if zmax is None:
104  zmax = round_to_divisable(np.max(zs[idcs]), args.nl - 1)
105  if zmin > 0:
106  zmax = zmax + zmin
107  if 0 < zmax < 1:
108  zmax = 1
109 
110  # Select the colormap
111  if qualitative:
112  cmap = plt.cm.rainbow
113  else:
114  #cmap = plt.cm.Purples
115  # if zmin < 0.0:
116  cmap = plt.cm.PuOr
117  cmap.set_bad('black', 1.)
118 
119  extent = (np.min(xs), np.max(xs), np.min(ys), np.max(ys))
120  ax1.imshow(zs, aspect='auto', origin='lower', extent=extent, cmap=cmap,
121  vmin=zmin, vmax=zmax, interpolation="none")
122 
123  levels = np.linspace(zmin, zmax, args.nl)
124  zs = zs.transpose()
125  if contour:
126  CS2 = ax1.contour(xs, ys, zs, levels, linewidths=0.25,
127  colors='k', vmin=zmin, vmax=zmax)
128  ax1.grid(color='black', linestyle=':', linewidth=0.25)
129  ax1.set_xlabel(xlabel)
130  ax1.set_ylabel(ylabel)
131  cbar = matplotlib.colorbar.ColorbarBase(ax2, cmap=cmap,
132  orientation='horizontal', ticks=levels,
133  norm=matplotlib.colors.Normalize(zmin, zmax))
134  cbar.set_label(zlabel)
135  return fig
136 
137 
138 if not os.path.exists("images"):
139  os.mkdir("images")
140 
141 for target_file in args.files:
142  simulator = target_file.split('_')[-1].split('.csv')[0]
143  experiment = target_file.split('/')[-1].split(simulator)[0]
144 
145  #import data
146  results = np.genfromtxt(target_file, delimiter=',', names=True)
147  keys = results.dtype.names
148  data = np.zeros((results.shape[0], len(keys)))
149  for i in range(0, len(results)):
150  data[i] = np.array(list(results[i]))
151 
152  fig = plot_measure2d(data[:, 0], data[:, 1], data[:, args.z],
153  xlabel=get_label(keys[0]), ylabel=get_label(keys[1]),
154  zlabel=get_label(keys[args.z]), zmin=args.zmin,
155  zmax=args.zmax, qualitative=args.q, contour=args.c,
156  title=SIMULATOR_LABELS[simulator])
157 
158  if target_file.split('/')[-2]:
159  if not os.path.exists("images/" + target_file.split('/')[-2]):
160  os.mkdir("images/" + target_file.split('/')[-2])
161  fig.savefig("images/" + target_file.split('/')[-2] + "/" +
162  experiment + simulator + ".pdf", format='pdf',
163  bbox_inches='tight')
164  else:
165  fig.savefig("images/" + experiment + simulator + ".pdf", format='pdf',
166  bbox_inches='tight')
def get_label(key)
Definition: dim_labels.py:82
def plot_measure2d(xs, ys, zs, xlabel, ylabel, zlabel="", zmin=None, zmax=None, qualitative=False, contour=True, title=None)
Definition: 2dim_plot.py:75
def cm2inch(value)
Definition: 2dim_plot.py:54
def round_to_divisable(value, divisable)
Definition: 2dim_plot.py:58