#!/usr/bin/env python3
#
#    Computers speed up of Streams benchmark results generated by make streams and plots
#
#    matplotlib can switch between different backends hence this needs to be run 
#    twice to first generate a file and then display a window
#
from __future__ import print_function
import os
#
def process(streamstype,fileoutput):
  import re

  ff = open('scaling.log')
  data = ff.read()
  ff.close()

  s = data.split('\n')
  triads = {}
  speedups = {}
  size = 0
  for i in s[0:-1]:
      i = i.split()
      triads[size] = float(i[1])
      size = size + 1

  if size < 2: return

  triads = list(triads.values())
  speedups = {}
  for i in range(0,size):
    speedups[i] = triads[i]/triads[0]

  try:
    import matplotlib
  except:
    print("Unable to open matplotlib to plot speedup")
    return

  try:
    if fileoutput: matplotlib.use('Agg')
    import matplotlib.pyplot as plt
  except:
    print("Unable to open matplotlib to plot speedup")
    return

  try:
    fig, ax1 = plt.subplots()
    plt.title(streamstype+' Perfect and Streams Speedup')
    ax2 = ax1.twinx()
    ax1.set_autoscaley_on(False)

    r = range(1,size+1)
    speedups = speedups.values()

    # make sure that actual bandwidth values (as opposed to perfect speedup) takes
    # at least a third of the y axis
    ymax = min(size, 3*max(speedups))
    ymin = min(1, min(speedups))
    if ymin < 1: ymin = 0

    ax1.set_xlim(1,size)
    ax1.set_ylim([ymin,ymax])
    ax1.set_xlabel('Number of processes/threads')
    ax1.set_ylabel('Memory Bandwidth Speedup')
    ax1.plot(r,r,'b',r,speedups,'r-o')
    ax2.set_autoscaley_on(False)
    ax2.set_xlim([1,size])
    ax2.set_ylim([min(triads),max(triads)])
    ax2.set_ylabel("Achieved Bandwidth. Megabytes per Second")
    ax2.plot(r,triads,'g-o')

    plt.show()
    if fileoutput: plt.savefig(streamstype+'scaling.png')
    if fileoutput: print("See graph in the file src/benchmarks/streams/"+streamstype+"scaling.png")
  except Exception as e:
    if fileoutput: print("Unable to plot speedup to a file")
    else: print("Unable to display speedup plot")
    return

  ff.close()

#
#
if __name__ ==  '__main__':
  import sys

  process(sys.argv[1],len(sys.argv)-2)


