From 2887dd398ce96a6da44b3b38a3624678c8eada73 Mon Sep 17 00:00:00 2001
From: Aidan Chalk <aidan.chalk@stfc.ac.uk>
Date: Thu, 11 May 2017 14:04:11 +0100
Subject: [PATCH] Updated the task script to match peter's new version for
 SWIFT

---
 examples/plot_tasks.py | 156 +++++++++++++++++++++++++----------------
 1 file changed, 95 insertions(+), 61 deletions(-)

diff --git a/examples/plot_tasks.py b/examples/plot_tasks.py
index 84a0952..ca56baa 100644
--- a/examples/plot_tasks.py
+++ b/examples/plot_tasks.py
@@ -2,7 +2,7 @@
 
 """
 Usage:
-  plot_tasks.py TASKTIMERS output.png [Ticks per ms]
+  plot_tasks.py options TASKTIMERS output.png
   
   where TASKTIMERS is a task timers file generated by quicksched.
   
@@ -24,16 +24,39 @@ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 """
 
 import matplotlib
+matplotlib.use("Agg")
 import matplotlib.pyplot as plt
 import matplotlib.colors as colors
 import matplotlib.collections as collections
 import matplotlib.cm as cmx
 import matplotlib.gridspec as gridspec
-matplotlib.use('Agg')
+import matplotlib.ticker as plticker
 import pylab as pl
 import numpy as np
 import sys
 import math
+import argparse
+
+parser = argparse.ArgumentParser(description="Task graphs")
+
+#Read in command line
+parser.add_argument("input", help="Task data file")
+parser.add_argument("outpng", help="Name for output graphic file (PNG)")
+
+parser.add_argument("-l", "--limit", dest="limit", help="Upper time limit in millisecs", default=0, type=int)
+parser.add_argument("-t", "--ticks", dest="tpms", help="Ticks per millisecond", default=2.9e6, type=int)
+parser.add_argument("-e", "--expand", dest="expand", help="Thread expansion factor (def:1)", default=1, type=int)
+parser.add_argument("--height", dest="height", help="Height of plot in inches (def:4)", default=4, type=float)
+parser.add_argument("--width", dest="width", help="Width of plot in inches (def:16)", default=16, type=float)
+parser.add_argument("--legend", dest="nolegend", help="Show the legend (def:false)", default=False, action="store_true")
+parser.add_argument("-v", "--verbose", dest="verbose", help="Show colour assignments and other details (def: false)", default=False, action="store_true")
+
+args=parser.parse_args()
+infile = args.input
+outpng=args.outpng
+delta_t = args.limit
+expand = args.expand
+tpms = args.tpms
 
 #  Basic plot configuration.
 PLOT_PARAMS = {"axes.labelsize": 10,
@@ -42,7 +65,7 @@ PLOT_PARAMS = {"axes.labelsize": 10,
                "legend.fontsize": 12,
                "xtick.labelsize": 11,
                "ytick.labelsize": 11,
-               "figure.figsize" : (16., 4.),
+               "figure.figsize" : (args.width, args.height),
                "figure.subplot.left" : 0.03,
                "figure.subplot.right" : 0.995,
                "figure.subplot.bottom" : 0.1,
@@ -53,47 +76,17 @@ PLOT_PARAMS = {"axes.labelsize": 10,
                "lines.linewidth" : 3.
                }
                
-TASKCOLOURS = ["black",
-               "lightblue",
-               "greenyellow",
-               "navy",
-               "greenyellow",
-               "navy",
-               "indigo",
-               "cyan",
-               "cyan",
-               "green",
-               "yellow",
-               "magenta",
-               "mediumorchid",
-               #"mediumnightblue",
-               "mediumturquoise",
-               "mediumvioletred",
-               "darkred",
-               "darkblue"
-               #,"powerblue"
-               ]
-               
-pl.rcParams.update(PLOT_PARAMS)
-
-if len(sys.argv) == 2 and (sys.argv[1][0:2] == "-h" or sys.argv[1][0:3] == "--h"):
-    from pydoc import help
-    help( "__main__")
-    sys.exit(0)
+colours = ["cyan", "lightgray", "darkblue", "yellow", "tan", "dodgerblue",
+           "sienna", "aquamarine", "bisque", "blue", "green", "brown",
+           "purple", "mocassin", "olivedrab", "chartreuse", "darksage",
+           "darkgreen", "green", "mediumseagreen", "mediumaquamarine",
+           "darkslategrey", "mediumturquoise", "black", "cadetblue", "skyblue",
+           "red", "slategray", "gold", "slateblue", "blueviolet",
+           "mediumorchid", "firebrick", "magenta", "hotpink", "pink"]
 
-#Input from command line
-if len(sys.argv) != 3 and len(sys.argv) != 4:
-    print "Usage: ", sys.argv[0], "TASKTIMERS output.png [ticks-per-ms]"
-    sys.exit(1)
-    
+pl.rcParams.update(PLOT_PARAMS)
 
     
-infile = sys.argv[1]
-outpng = sys.argv[2]
-tpms = 0
-if len(sys.argv) == 4:
-    tpms = int(sys.argv[3])
-    
 #read input.
 data = pl.loadtxt(infile)
 nthread=int(max(data[:,1])) + 1
@@ -110,39 +103,80 @@ end_t = (max(data[:,3]))
 start_t = min(data[:,2])
 delta_t = end_t - start_t
 
+tasks = {}
+tasks[-1] = []
+for i in range(nthread*expand):
+    tasks[i] = []
 
+ecounter = []
+for i in range(nthread):
+  ecounter.append(0)
+
+num_lines = pl.size(data) /4
+
+
+for line in range(num_lines):
+    thread = int(data[line, 1])
+
+    #Expand to cover extra lines if expanding
+    ethread = thread*expand + (ecounter[thread]%expand)
+    ecounter[thread] = ecounter[thread] + 1
+    thread = ethread
+
+    tasks[thread].append({})
+    tasktype = data[line,0]
+    tasks[thread][-1]["type"] = tasktype
+    tic = data[line,2]
+    toc = data[line,3]
+    tasks[thread][-1]["tic"] = tic
+    tasks[thread][-1]["toc"] = toc
+    print tasktype
+    tasks[thread][-1]["colour"] = colours[int(tasktype)]
+
+nthread = nthread * expand
+
+typesseen = []
 
 fig = pl.figure()
 ax = fig.add_subplot(1,1,1)
 ax.set_xlim(-delta_t * 0.03, delta_t * 1.03)
 ax.set_ylim(0, nthread)
 
-print len(data[:,0])
-
-for j in range(nthread):
-    tictocs = np.zeros(len(data[:,0])*2) 
-    types = np.zeros(len(data[:,0])*2) 
-    for i in range(len(data[:,0])):
-        if data[i,1] == j:
-            tictocs[i*2+0] = data[i,2]
-            tictocs[i*2+1] = data[i,3]
-            types[i*2+0] = int(data[i,0])
-            types[i*2+1] = int(data[i,0])
-        #print tictocs
-        #print data[i,1]+0.05
-        
-    for i in range(len(TASKCOLOURS)):
-        print i
-        print types==i
-        collection = collections.BrokenBarHCollection.span_where(tictocs, ymin=j+0.05, ymax=j+0.95, where=types==i, facecolor=TASKCOLOURS[i], linewidths=1, edgecolor="white")
-        ax.add_collection(collection)
+for i in range(nthread):
+    tictocs = []
+    colours = []
     
+    j = 0
+    for task in tasks[i]:
+        print task["toc"] - task["tic"], task["colour"]
+        tictocs.append((task["tic"], task["toc"] - task["tic"]))
+        colours.append(task["colour"])
+        qtask = task["type"]
+        if qtask not in typesseen:
+            pl.plot([],[],color=task["colour"], label=qtask)
+            typesseen.append(qtask)
+
+    ax.broken_barh(tictocs, [i+0.05, 0.90], facecolors = colours, linewidth=0)
+
+    #  Legend and room for it.
+nrow = len(typesseen) / 5
+if args.nolegend:
+    ax.set_ylim(0, nthread + nrow + 1)
+    ax.legend(loc=1, shadow=True, mode="expand", ncol=5)
+    if len(typesseen) * 5 < nrow:
+        nrow = nrow + 1
+    ax.fill_between([0, 0], nthread+0.5, nthread + nrow + 0.5, facecolor="white")
+
 # Start and end of time-step
 ax.plot([start_t, start_t], [0, nthread], 'k--', linewidth=1)
 ax.plot([end_t, end_t], [0, nthread], 'k--', linewidth=1)
 
 ax.set_xlabel("time [ms or ticks]")
-ax.set_ylabel("Thread ID" )
+if expand == 1:
+    ax.set_ylabel("Thread ID" )
+else:
+    ax.set_ylabel("Thread ID * " + str(expand) )
+
 ax.set_yticks(pl.array(range(nthread)), True)
 
 pl.savefig(outpng, format = 'png', dpi = 1000)
-- 
GitLab