1#!/usr/bin/env python2.7
2
3# Copyright (c) 2014 ARM Limited
4# All rights reserved
5#
6# The license below extends only to copyright in the software and shall
7# not be construed as granting a license to any other intellectual
8# property including but not limited to intellectual property relating
9# to a hardware implementation of the functionality of the software
10# licensed hereunder.  You may use the software subject to the license
11# terms below provided that you ensure that this notice is replicated
12# unmodified and in its entirety in all distributions of the software,
13# modified or unmodified, in source code or in binary form.
14#
15# Redistribution and use in source and binary forms, with or without
16# modification, are permitted provided that the following conditions are
17# met: redistributions of source code must retain the above copyright
18# notice, this list of conditions and the following disclaimer;
19# redistributions in binary form must reproduce the above copyright
20# notice, this list of conditions and the following disclaimer in the
21# documentation and/or other materials provided with the distribution;
22# neither the name of the copyright holders nor the names of its
23# contributors may be used to endorse or promote products derived from
24# this software without specific prior written permission.
25#
26# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
29# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
30# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
31# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
32# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
36# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37#
38# Authors: Andreas Hansson
39
40try:
41    from mpl_toolkits.mplot3d import Axes3D
42    from matplotlib import cm
43    import matplotlib.pyplot as plt
44    import numpy as np
45except ImportError:
46    print "Failed to import matplotlib and numpy"
47    exit(-1)
48
49import sys
50import re
51
52# Determine the parameters of the sweep from the simout output, and
53# then parse the stats and plot the 3D surface corresponding to the
54# different combinations of parallel banks, and stride size, as
55# generated by the config/dram/sweep.py script
56def main():
57
58    if len(sys.argv) != 3:
59        print "Usage: ", sys.argv[0], "-u|p|e <simout directory>"
60        exit(-1)
61
62    if len(sys.argv[1]) != 2 or sys.argv[1][0] != '-' or \
63            not sys.argv[1][1] in "upe":
64        print "Choose -u (utilisation), -p (total power), or -e " \
65            "(power efficiency)"
66        exit(-1)
67
68    # Choose the appropriate mode, either utilisation, total power, or
69    # efficiency
70    mode = sys.argv[1][1]
71
72    try:
73        stats = open(sys.argv[2] + '/stats.txt', 'r')
74    except IOError:
75        print "Failed to open ", sys.argv[2] + '/stats.txt', " for reading"
76        exit(-1)
77
78    try:
79        simout = open(sys.argv[2] + '/simout', 'r')
80    except IOError:
81        print "Failed to open ", sys.argv[2] + '/simout', " for reading"
82        exit(-1)
83
84    # Get the burst size, number of banks and the maximum stride from
85    # the simulation output
86    got_sweep = False
87
88    for line in simout:
89        match = re.match("DRAM sweep with "
90                         "burst: (\d+), banks: (\d+), max stride: (\d+)", line)
91        if match:
92            burst_size = int(match.groups(0)[0])
93            banks = int(match.groups(0)[1])
94            max_size = int(match.groups(0)[2])
95            got_sweep = True
96
97    simout.close()
98
99    if not got_sweep:
100        print "Failed to establish sweep details, ensure simout is up-to-date"
101        exit(-1)
102
103    # Now parse the stats
104    peak_bw = []
105    bus_util = []
106    avg_pwr = []
107
108    for line in stats:
109        match = re.match(".*busUtil\s+(\d+\.\d+)\s+#.*", line)
110        if match:
111            bus_util.append(float(match.groups(0)[0]))
112
113        match = re.match(".*peakBW\s+(\d+\.\d+)\s+#.*", line)
114        if match:
115            peak_bw.append(float(match.groups(0)[0]))
116
117        match = re.match(".*averagePower\s+(\d+\.?\d*)\s+#.*", line)
118        if match:
119            avg_pwr.append(float(match.groups(0)[0]))
120    stats.close()
121
122
123    # Sanity check
124    if not (len(peak_bw) == len(bus_util) and len(bus_util) == len(avg_pwr)):
125        print "Peak bandwidth, bus utilisation, and average power do not match"
126        exit(-1)
127
128    # Collect the selected metric as our Z-axis, we do this in a 2D
129    # grid corresponding to each iteration over the various stride
130    # sizes.
131    z = []
132    zs = []
133    i = 0
134
135    for j in range(len(peak_bw)):
136        if mode == 'u':
137            z.append(bus_util[j])
138        elif mode == 'p':
139            z.append(avg_pwr[j])
140        elif mode == 'e':
141            # avg_pwr is in mW, peak_bw in MiByte/s, bus_util in percent
142            z.append(avg_pwr[j] / (bus_util[j] / 100.0 * peak_bw[j] / 1000.0))
143        else:
144            print "Unexpected mode %s" % mode
145            exit(-1)
146
147        i += 1
148        # If we have completed a sweep over the stride sizes,
149        # start anew
150        if i == max_size / burst_size:
151            zs.append(z)
152            z = []
153            i = 0
154
155    # We should have a 2D grid with as many columns as banks
156    if len(zs) != banks:
157        print "Unexpected number of data points in stats output"
158        exit(-1)
159
160    fig = plt.figure()
161    ax = fig.gca(projection='3d')
162    X = np.arange(burst_size, max_size + 1, burst_size)
163    Y = np.arange(1, banks + 1, 1)
164    X, Y = np.meshgrid(X, Y)
165
166    # the values in the util are banks major, so we see groups for each
167    # stride size in order
168    Z = np.array(zs)
169
170    surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
171                           linewidth=0, antialiased=False)
172
173    # Change the tick frequency to 64
174    start, end = ax.get_xlim()
175    ax.xaxis.set_ticks(np.arange(start, end + 1, 64))
176
177    ax.set_xlabel('Bytes per activate')
178    ax.set_ylabel('Banks')
179
180    if mode == 'u':
181        ax.set_zlabel('Utilisation (%)')
182    elif mode == 'p':
183        ax.set_zlabel('Power (mW)')
184    elif mode == 'e':
185        ax.set_zlabel('Power efficiency (mW / GByte / s)')
186
187    # Add a colorbar
188    fig.colorbar(surf, shrink=0.5, pad=.1, aspect=10)
189
190    plt.show()
191
192if __name__ == "__main__":
193    main()
194