xref: /petsc/src/benchmarks/benchmarkExample.py (revision 0a2738ab2e686babf58684f1bc293dc212e69788) !
13428b40fSMatthew G Knepley#!/usr/bin/env python
2eda8839fSMatthew G Knepleyimport os,sys
3683aebbfSMatthew G Knepleysys.path.append(os.path.join(os.environ['PETSC_DIR'], 'config'))
490dfb094SAndy R. Terrelsys.path.append(os.getcwd())
5683aebbfSMatthew G Knepleyfrom builder2 import buildExample
619d5f70aSMatthew G Knepleyfrom benchmarkBatch import generateBatchScript
73428b40fSMatthew G Knepley
83428b40fSMatthew G Knepleyclass PETSc(object):
93428b40fSMatthew G Knepley  def __init__(self):
103428b40fSMatthew G Knepley    return
113428b40fSMatthew G Knepley
123428b40fSMatthew G Knepley  def dir(self):
133428b40fSMatthew G Knepley    '''Return the root directory for the PETSc tree (usually $PETSC_DIR)'''
143428b40fSMatthew G Knepley    # This should search for a valid PETSc
153428b40fSMatthew G Knepley    return os.environ['PETSC_DIR']
163428b40fSMatthew G Knepley
173428b40fSMatthew G Knepley  def arch(self):
183428b40fSMatthew G Knepley    '''Return the PETSc build label (usually $PETSC_ARCH)'''
193428b40fSMatthew G Knepley    # This should be configurable
203428b40fSMatthew G Knepley    return os.environ['PETSC_ARCH']
213428b40fSMatthew G Knepley
223428b40fSMatthew G Knepley  def mpiexec(self):
233428b40fSMatthew G Knepley    '''Return the path for the mpi launch executable'''
24e3da8a91SMatthew G Knepley    mpiexec = os.path.join(self.dir(), self.arch(), 'bin', 'mpiexec')
256cbfa02cSMatthew G Knepley    if not os.path.isfile(mpiexec):
26e3da8a91SMatthew G Knepley      return None
27e3da8a91SMatthew G Knepley    return mpiexec
283428b40fSMatthew G Knepley
293428b40fSMatthew G Knepley  def example(self, num):
303428b40fSMatthew G Knepley    '''Return the path to the executable for a given example number'''
313428b40fSMatthew G Knepley    return os.path.join(self.dir(), self.arch(), 'lib', 'ex'+str(num)+'-obj', 'ex'+str(num))
323428b40fSMatthew G Knepley
330790b1abSMatthew G Knepley  def source(self, library, num):
340790b1abSMatthew G Knepley    '''Return the path to the sources for a given example number'''
350790b1abSMatthew G Knepley    d = os.path.join(self.dir(), 'src', library.lower(), 'examples', 'tutorials')
360790b1abSMatthew G Knepley    name = 'ex'+str(num)
370790b1abSMatthew G Knepley    sources = []
380790b1abSMatthew G Knepley    for f in os.listdir(d):
390790b1abSMatthew G Knepley      if f == name+'.c':
402642ea08SMatthew G Knepley        sources.insert(0, f)
410790b1abSMatthew G Knepley      elif f.startswith(name) and f.endswith('.cu'):
420790b1abSMatthew G Knepley        sources.append(f)
430790b1abSMatthew G Knepley    return map(lambda f: os.path.join(d, f), sources)
440790b1abSMatthew G Knepley
453428b40fSMatthew G Knepleyclass PETScExample(object):
463428b40fSMatthew G Knepley  def __init__(self, library, num, **defaultOptions):
473428b40fSMatthew G Knepley    self.petsc   = PETSc()
483428b40fSMatthew G Knepley    self.library = library
493428b40fSMatthew G Knepley    self.num     = num
503428b40fSMatthew G Knepley    self.opts    = defaultOptions
513428b40fSMatthew G Knepley    return
523428b40fSMatthew G Knepley
533428b40fSMatthew G Knepley  @staticmethod
54d006b754SMatthew G Knepley  def runShellCommand(command, cwd = None, log = True):
553428b40fSMatthew G Knepley    import subprocess
563428b40fSMatthew G Knepley
573428b40fSMatthew G Knepley    Popen = subprocess.Popen
583428b40fSMatthew G Knepley    PIPE  = subprocess.PIPE
59d006b754SMatthew G Knepley    if log: print 'Executing: %s\n' % (command,)
603428b40fSMatthew G Knepley    pipe = Popen(command, cwd=cwd, stdin=None, stdout=PIPE, stderr=PIPE, bufsize=-1, shell=True, universal_newlines=True)
613428b40fSMatthew G Knepley    (out, err) = pipe.communicate()
623428b40fSMatthew G Knepley    ret = pipe.returncode
633428b40fSMatthew G Knepley    return (out, err, ret)
643428b40fSMatthew G Knepley
653428b40fSMatthew G Knepley  def optionsToString(self, **opts):
663428b40fSMatthew G Knepley    '''Convert a dictionary of options to a command line argument string'''
673428b40fSMatthew G Knepley    a = []
683428b40fSMatthew G Knepley    for key,value in opts.iteritems():
693428b40fSMatthew G Knepley      if value is None:
703428b40fSMatthew G Knepley        a.append('-'+key)
713428b40fSMatthew G Knepley      else:
723428b40fSMatthew G Knepley        a.append('-'+key+' '+str(value))
733428b40fSMatthew G Knepley    return ' '.join(a)
743428b40fSMatthew G Knepley
75d006b754SMatthew G Knepley  def run(self, numProcs = 1, log = True, **opts):
76e3da8a91SMatthew G Knepley    if self.petsc.mpiexec() is None:
77e3da8a91SMatthew G Knepley      cmd = self.petsc.example(self.num)
78e3da8a91SMatthew G Knepley    else:
7919d5f70aSMatthew G Knepley      cmd = ' '.join([self.petsc.mpiexec(), '-n', str(numProcs), self.petsc.example(self.num)])
80e3da8a91SMatthew G Knepley    cmd += ' '+self.optionsToString(**self.opts)+' '+self.optionsToString(**opts)
8119d5f70aSMatthew G Knepley    if 'batch' in opts and opts['batch']:
8219d5f70aSMatthew G Knepley      del opts['batch']
833849a283SMatthew G Knepley      filename = generateBatchScript(self.num, numProcs, 120, ' '+self.optionsToString(**self.opts)+' '+self.optionsToString(**opts))
843849a283SMatthew G Knepley      # Submit job
85d006b754SMatthew G Knepley      out, err, ret = self.runShellCommand('qsub -q gpu '+filename, log = log)
863849a283SMatthew G Knepley      if ret:
873849a283SMatthew G Knepley        print err
883849a283SMatthew G Knepley        print out
8919d5f70aSMatthew G Knepley    else:
90d006b754SMatthew G Knepley      out, err, ret = self.runShellCommand(cmd, log = log)
913428b40fSMatthew G Knepley      if ret:
923428b40fSMatthew G Knepley        print err
933428b40fSMatthew G Knepley        print out
940790b1abSMatthew G Knepley    return out
953428b40fSMatthew G Knepley
96eda8839fSMatthew G Knepleydef processSummary(moduleName, defaultStage, eventNames, times, events):
973428b40fSMatthew G Knepley  '''Process the Python log summary into plot data'''
983428b40fSMatthew G Knepley  m = __import__(moduleName)
993428b40fSMatthew G Knepley  reload(m)
1003428b40fSMatthew G Knepley  # Total Time
1013428b40fSMatthew G Knepley  times.append(m.Time[0])
1023428b40fSMatthew G Knepley  # Particular events
103eda8839fSMatthew G Knepley  for name in eventNames:
104eda8839fSMatthew G Knepley    if name.find(':') >= 0:
105eda8839fSMatthew G Knepley      stageName, name = name.split(':', 1)
106eda8839fSMatthew G Knepley      stage = getattr(m, stageName)
107eda8839fSMatthew G Knepley    else:
108eda8839fSMatthew G Knepley      stage = getattr(m, defaultStage)
109eda8839fSMatthew G Knepley    if name in stage.event:
1103428b40fSMatthew G Knepley      if not name in events:
1113428b40fSMatthew G Knepley        events[name] = []
112df494a56SMatthew G Knepley      try:
113eda8839fSMatthew G Knepley        events[name].append((stage.event[name].Time[0], stage.event[name].Flops[0]/(stage.event[name].Time[0] * 1e6)))
114df494a56SMatthew G Knepley      except ZeroDivisionError:
115df494a56SMatthew G Knepley        events[name].append((stage.event[name].Time[0], 0))
1163428b40fSMatthew G Knepley  return
1173428b40fSMatthew G Knepley
1186e25a272SMatthew G Knepleydef plotTime(library, num, eventNames, sizes, times, events):
1196e25a272SMatthew G Knepley  from pylab import legend, plot, show, title, xlabel, ylabel
1206e25a272SMatthew G Knepley  import numpy as np
1216e25a272SMatthew G Knepley
1226e25a272SMatthew G Knepley  arches = sizes.keys()
1236e25a272SMatthew G Knepley  data   = []
1246e25a272SMatthew G Knepley  for arch in arches:
1256e25a272SMatthew G Knepley    data.append(sizes[arch])
1266e25a272SMatthew G Knepley    data.append(times[arch])
1276e25a272SMatthew G Knepley  plot(*data)
1286e25a272SMatthew G Knepley  title('Performance on '+library+' Example '+str(num))
1296e25a272SMatthew G Knepley  xlabel('Number of Dof')
1306e25a272SMatthew G Knepley  ylabel('Time (s)')
1316e25a272SMatthew G Knepley  legend(arches, 'upper left', shadow = True)
1326e25a272SMatthew G Knepley  show()
1336e25a272SMatthew G Knepley  return
1346e25a272SMatthew G Knepley
1356e25a272SMatthew G Knepleydef plotEventTime(library, num, eventNames, sizes, times, events, filename = None):
1366e25a272SMatthew G Knepley  from pylab import close, legend, plot, savefig, show, title, xlabel, ylabel
1376e25a272SMatthew G Knepley  import numpy as np
1386e25a272SMatthew G Knepley
1396e25a272SMatthew G Knepley  close()
1406e25a272SMatthew G Knepley  arches = sizes.keys()
1416e25a272SMatthew G Knepley  bs     = events[arches[0]].keys()[0]
1426e25a272SMatthew G Knepley  data   = []
1436e25a272SMatthew G Knepley  names  = []
1446e25a272SMatthew G Knepley  for event, color in zip(eventNames, ['b', 'g', 'r', 'y']):
1456e25a272SMatthew G Knepley    for arch, style in zip(arches, ['-', ':']):
1466e25a272SMatthew G Knepley      if event in events[arch][bs]:
1476e25a272SMatthew G Knepley        names.append(arch+'-'+str(bs)+' '+event)
1486e25a272SMatthew G Knepley        data.append(sizes[arch][bs])
1496e25a272SMatthew G Knepley        data.append(np.array(events[arch][bs][event])[:,0])
1506e25a272SMatthew G Knepley        data.append(color+style)
1516e25a272SMatthew G Knepley      else:
1526e25a272SMatthew G Knepley        print 'Could not find %s in %s-%d events' % (event, arch, bs)
1536e25a272SMatthew G Knepley  print data
1546e25a272SMatthew G Knepley  plot(*data)
1556e25a272SMatthew G Knepley  title('Performance on '+library+' Example '+str(num))
1566e25a272SMatthew G Knepley  xlabel('Number of Dof')
1576e25a272SMatthew G Knepley  ylabel('Time (s)')
1586e25a272SMatthew G Knepley  legend(names, 'upper left', shadow = True)
1596e25a272SMatthew G Knepley  if filename is None:
1606e25a272SMatthew G Knepley    show()
1616e25a272SMatthew G Knepley  else:
1626e25a272SMatthew G Knepley    savefig(filename)
1636e25a272SMatthew G Knepley  return
1646e25a272SMatthew G Knepley
1656e25a272SMatthew G Knepleydef plotEventFlop(library, num, eventNames, sizes, times, events, filename = None):
1666e25a272SMatthew G Knepley  from pylab import legend, plot, savefig, semilogy, show, title, xlabel, ylabel
1676e25a272SMatthew G Knepley  import numpy as np
1686e25a272SMatthew G Knepley
1696e25a272SMatthew G Knepley  arches = sizes.keys()
1706e25a272SMatthew G Knepley  bs     = events[arches[0]].keys()[0]
1716e25a272SMatthew G Knepley  data   = []
1726e25a272SMatthew G Knepley  names  = []
1736e25a272SMatthew G Knepley  for event, color in zip(eventNames, ['b', 'g', 'r', 'y']):
1746e25a272SMatthew G Knepley    for arch, style in zip(arches, ['-', ':']):
1756e25a272SMatthew G Knepley      if event in events[arch][bs]:
1766e25a272SMatthew G Knepley        names.append(arch+'-'+str(bs)+' '+event)
1776e25a272SMatthew G Knepley        data.append(sizes[arch][bs])
1786e25a272SMatthew G Knepley        data.append(1e-3*np.array(events[arch][bs][event])[:,1])
1796e25a272SMatthew G Knepley        data.append(color+style)
1806e25a272SMatthew G Knepley      else:
1816e25a272SMatthew G Knepley        print 'Could not find %s in %s-%d events' % (event, arch, bs)
1826e25a272SMatthew G Knepley  semilogy(*data)
1836e25a272SMatthew G Knepley  title('Performance on '+library+' Example '+str(num))
1846e25a272SMatthew G Knepley  xlabel('Number of Dof')
1856e25a272SMatthew G Knepley  ylabel('Computation Rate (GF/s)')
1866e25a272SMatthew G Knepley  legend(names, 'upper left', shadow = True)
1876e25a272SMatthew G Knepley  if filename is None:
1886e25a272SMatthew G Knepley    show()
1896e25a272SMatthew G Knepley  else:
1906e25a272SMatthew G Knepley    savefig(filename)
1916e25a272SMatthew G Knepley  return
1926e25a272SMatthew G Knepley
193929aa6beSMatthew G. Knepleydef plotEventScaling(library, num, eventNames, procs, events, filename = None):
194929aa6beSMatthew G. Knepley  from pylab import legend, plot, savefig, semilogy, show, title, xlabel, ylabel
195929aa6beSMatthew G. Knepley  import numpy as np
196929aa6beSMatthew G. Knepley
197929aa6beSMatthew G. Knepley  arches = procs.keys()
198929aa6beSMatthew G. Knepley  bs     = events[arches[0]].keys()[0]
199929aa6beSMatthew G. Knepley  data   = []
200929aa6beSMatthew G. Knepley  names  = []
201929aa6beSMatthew G. Knepley  for arch, style in zip(arches, ['-', ':']):
202929aa6beSMatthew G. Knepley    for event, color in zip(eventNames, ['b', 'g', 'r', 'y']):
203929aa6beSMatthew G. Knepley      if event in events[arch][bs]:
204929aa6beSMatthew G. Knepley        names.append(arch+'-'+str(bs)+' '+event)
205929aa6beSMatthew G. Knepley        data.append(procs[arch][bs])
206929aa6beSMatthew G. Knepley        data.append(1e-3*np.array(events[arch][bs][event])[:,1])
207929aa6beSMatthew G. Knepley        data.append(color+style)
208929aa6beSMatthew G. Knepley      else:
209929aa6beSMatthew G. Knepley        print 'Could not find %s in %s-%d events' % (event, arch, bs)
210929aa6beSMatthew G. Knepley  plot(*data)
211929aa6beSMatthew G. Knepley  title('Performance on '+library+' Example '+str(num))
212929aa6beSMatthew G. Knepley  xlabel('Number of Processors')
213929aa6beSMatthew G. Knepley  ylabel('Computation Rate (GF/s)')
214929aa6beSMatthew G. Knepley  legend(names, 'upper left', shadow = True)
215929aa6beSMatthew G. Knepley  if filename is None:
216929aa6beSMatthew G. Knepley    show()
217929aa6beSMatthew G. Knepley  else:
218929aa6beSMatthew G. Knepley    savefig(filename)
219929aa6beSMatthew G. Knepley  return
220929aa6beSMatthew G. Knepley
221303b7b21SMatthew G Knepleydef plotSummaryLine(library, num, eventNames, sizes, times, events):
2223428b40fSMatthew G Knepley  from pylab import legend, plot, show, title, xlabel, ylabel
2233428b40fSMatthew G Knepley  import numpy as np
2243428b40fSMatthew G Knepley  showTime       = False
2253428b40fSMatthew G Knepley  showEventTime  = True
2263428b40fSMatthew G Knepley  showEventFlops = True
2273428b40fSMatthew G Knepley  arches         = sizes.keys()
2283428b40fSMatthew G Knepley  # Time
2293428b40fSMatthew G Knepley  if showTime:
2303428b40fSMatthew G Knepley    data = []
2313428b40fSMatthew G Knepley    for arch in arches:
2323428b40fSMatthew G Knepley      data.append(sizes[arch])
2333428b40fSMatthew G Knepley      data.append(times[arch])
2343428b40fSMatthew G Knepley    plot(*data)
2353428b40fSMatthew G Knepley    title('Performance on '+library+' Example '+str(num))
2363428b40fSMatthew G Knepley    xlabel('Number of Dof')
2373428b40fSMatthew G Knepley    ylabel('Time (s)')
2383428b40fSMatthew G Knepley    legend(arches, 'upper left', shadow = True)
2393428b40fSMatthew G Knepley    show()
2403428b40fSMatthew G Knepley  # Common event time
2413428b40fSMatthew G Knepley  #   We could make a stacked plot like Rio uses here
2423428b40fSMatthew G Knepley  if showEventTime:
243df494a56SMatthew G Knepley    bs    = events[arches[0]].keys()[0]
2443428b40fSMatthew G Knepley    data  = []
2453428b40fSMatthew G Knepley    names = []
246df494a56SMatthew G Knepley    for event, color in zip(eventNames, ['b', 'g', 'r', 'y']):
2473428b40fSMatthew G Knepley      for arch, style in zip(arches, ['-', ':']):
248df494a56SMatthew G Knepley        if event in events[arch][bs]:
249df494a56SMatthew G Knepley          names.append(arch+'-'+str(bs)+' '+event)
250df494a56SMatthew G Knepley          data.append(sizes[arch][bs])
251df494a56SMatthew G Knepley          data.append(np.array(events[arch][bs][event])[:,0])
2523428b40fSMatthew G Knepley          data.append(color+style)
253df494a56SMatthew G Knepley        else:
254df494a56SMatthew G Knepley          print 'Could not find %s in %s-%d events' % (event, arch, bs)
255df494a56SMatthew G Knepley    print data
2563428b40fSMatthew G Knepley    plot(*data)
2573428b40fSMatthew G Knepley    title('Performance on '+library+' Example '+str(num))
2583428b40fSMatthew G Knepley    xlabel('Number of Dof')
2593428b40fSMatthew G Knepley    ylabel('Time (s)')
2603428b40fSMatthew G Knepley    legend(names, 'upper left', shadow = True)
2613428b40fSMatthew G Knepley    show()
2623428b40fSMatthew G Knepley  # Common event flops
2633428b40fSMatthew G Knepley  #   We could make a stacked plot like Rio uses here
2643428b40fSMatthew G Knepley  if showEventFlops:
265df494a56SMatthew G Knepley    bs    = events[arches[0]].keys()[0]
2663428b40fSMatthew G Knepley    data  = []
2673428b40fSMatthew G Knepley    names = []
268df494a56SMatthew G Knepley    for event, color in zip(eventNames, ['b', 'g', 'r', 'y']):
2693428b40fSMatthew G Knepley      for arch, style in zip(arches, ['-', ':']):
270df494a56SMatthew G Knepley        if event in events[arch][bs]:
271df494a56SMatthew G Knepley          names.append(arch+'-'+str(bs)+' '+event)
272df494a56SMatthew G Knepley          data.append(sizes[arch][bs])
273df494a56SMatthew G Knepley          data.append(np.array(events[arch][bs][event])[:,1])
2743428b40fSMatthew G Knepley          data.append(color+style)
275df494a56SMatthew G Knepley        else:
276df494a56SMatthew G Knepley          print 'Could not find %s in %s-%d events' % (event, arch, bs)
2773428b40fSMatthew G Knepley    plot(*data)
2783428b40fSMatthew G Knepley    title('Performance on '+library+' Example '+str(num))
2793428b40fSMatthew G Knepley    xlabel('Number of Dof')
2803428b40fSMatthew G Knepley    ylabel('Computation Rate (MF/s)')
2813428b40fSMatthew G Knepley    legend(names, 'upper left', shadow = True)
2823428b40fSMatthew G Knepley    show()
2833428b40fSMatthew G Knepley  return
2843428b40fSMatthew G Knepley
285303b7b21SMatthew G Knepleydef plotSummaryBar(library, num, eventNames, sizes, times, events):
286e3da8a91SMatthew G Knepley  import numpy as np
287e3da8a91SMatthew G Knepley  import matplotlib.pyplot as plt
288e3da8a91SMatthew G Knepley
289303b7b21SMatthew G Knepley  eventColors = ['b', 'g', 'r', 'y']
290e3da8a91SMatthew G Knepley  arches = sizes.keys()
291e3da8a91SMatthew G Knepley  names  = []
292e3da8a91SMatthew G Knepley  N      = len(sizes[arches[0]])
293e3da8a91SMatthew G Knepley  width  = 0.2
294e3da8a91SMatthew G Knepley  ind    = np.arange(N) - 0.25
295e3da8a91SMatthew G Knepley  bars   = {}
296e3da8a91SMatthew G Knepley  for arch in arches:
297e3da8a91SMatthew G Knepley    bars[arch] = []
298e3da8a91SMatthew G Knepley    bottom = np.zeros(N)
299e3da8a91SMatthew G Knepley    for event, color in zip(eventNames, eventColors):
300e3da8a91SMatthew G Knepley      names.append(arch+' '+event)
301e3da8a91SMatthew G Knepley      times = np.array(events[arch][event])[:,0]
302e3da8a91SMatthew G Knepley      bars[arch].append(plt.bar(ind, times, width, color=color, bottom=bottom))
303e3da8a91SMatthew G Knepley      bottom += times
304e3da8a91SMatthew G Knepley    ind += 0.3
305e3da8a91SMatthew G Knepley
306e3da8a91SMatthew G Knepley  plt.xlabel('Number of Dof')
307e3da8a91SMatthew G Knepley  plt.ylabel('Time (s)')
308e3da8a91SMatthew G Knepley  plt.title('GPU vs. CPU Performance on '+library+' Example '+str(num))
309e3da8a91SMatthew G Knepley  plt.xticks(np.arange(N), map(str, sizes[arches[0]]))
310e3da8a91SMatthew G Knepley  #plt.yticks(np.arange(0,81,10))
311e3da8a91SMatthew G Knepley  #plt.legend( (p1[0], p2[0]), ('Men', 'Women') )
312e3da8a91SMatthew G Knepley  plt.legend([bar[0] for bar in bars[arches[0]]], eventNames, 'upper right', shadow = True)
313e3da8a91SMatthew G Knepley
314e3da8a91SMatthew G Knepley  plt.show()
315e3da8a91SMatthew G Knepley  return
316e3da8a91SMatthew G Knepley
317df494a56SMatthew G Knepleydef getDMComplexSize(dim, out):
318*0a2738abSAndy R. Terrel  '''Retrieves the number of cells from -dm_view output'''
319683aebbfSMatthew G Knepley  size = 0
320683aebbfSMatthew G Knepley  for line in out.split('\n'):
321683aebbfSMatthew G Knepley    if line.strip().startswith(str(dim)+'-cells: '):
322*0a2738abSAndy R. Terrel      sizes = line.strip()[9:].split()
323*0a2738abSAndy R. Terrel      size  = sum(map(int, sizes))
324683aebbfSMatthew G Knepley      break
325683aebbfSMatthew G Knepley  return size
326683aebbfSMatthew G Knepley
327d006b754SMatthew G Knepleydef run_DMDA(ex, name, opts, args, sizes, times, events, log=True):
328683aebbfSMatthew G Knepley  for n in map(int, args.size):
329d006b754SMatthew G Knepley    ex.run(log=log, da_grid_x=n, da_grid_y=n, **opts)
330683aebbfSMatthew G Knepley    sizes[name].append(n*n * args.comp)
331683aebbfSMatthew G Knepley    processSummary('summary', args.stage, args.events, times[name], events[name])
332683aebbfSMatthew G Knepley  return
333683aebbfSMatthew G Knepley
334d006b754SMatthew G Knepleydef run_DMComplex(ex, name, opts, args, sizes, times, events, log=True):
335683aebbfSMatthew G Knepley  # This should eventually be replaced by a direct FFC/Ignition interface
336683aebbfSMatthew G Knepley  if args.operator == 'laplacian':
337683aebbfSMatthew G Knepley    numComp  = 1
338683aebbfSMatthew G Knepley  elif args.operator == 'elasticity':
339683aebbfSMatthew G Knepley    numComp  = args.dim
340683aebbfSMatthew G Knepley  else:
341683aebbfSMatthew G Knepley    raise RuntimeError('Unknown operator: %s' % args.operator)
342683aebbfSMatthew G Knepley
343683aebbfSMatthew G Knepley  for numBlock in [2**i for i in map(int, args.blockExp)]:
344683aebbfSMatthew G Knepley    opts['gpu_blocks'] = numBlock
345683aebbfSMatthew G Knepley    # Generate new block size
346619383dcSAndy R. Terrel    cmd = os.environ.get('PETSC_DIR', '.')
347619383dcSAndy R. Terrel    cmd += '/bin/pythonscripts/PetscGenerateFEMQuadrature.py %d %d %d %d %s %s.h' % (args.dim, args.order, numComp, numBlock, args.operator, os.path.splitext(source[0])[0])
348683aebbfSMatthew G Knepley    print(cmd)
349683aebbfSMatthew G Knepley    ret = os.system('python '+cmd)
350683aebbfSMatthew G Knepley    args.files = ['['+','.join(source)+']']
351683aebbfSMatthew G Knepley    buildExample(args)
352683aebbfSMatthew G Knepley    sizes[name][numBlock]  = []
353683aebbfSMatthew G Knepley    times[name][numBlock]  = []
354683aebbfSMatthew G Knepley    events[name][numBlock] = {}
355683aebbfSMatthew G Knepley    for r in map(float, args.refine):
356d006b754SMatthew G Knepley      out = ex.run(log=log, refinement_limit=r, **opts)
357df494a56SMatthew G Knepley      sizes[name][numBlock].append(getDMComplexSize(args.dim, out))
358683aebbfSMatthew G Knepley      processSummary('summary', args.stage, args.events, times[name][numBlock], events[name][numBlock])
359683aebbfSMatthew G Knepley  return
360683aebbfSMatthew G Knepley
361d006b754SMatthew G Knepleydef outputData(sizes, times, events, name = 'output.py'):
362d006b754SMatthew G Knepley  if os.path.exists(name):
363d006b754SMatthew G Knepley    base, ext = os.path.splitext(name)
364d006b754SMatthew G Knepley    num = 1
365d006b754SMatthew G Knepley    while os.path.exists(base+str(num)+ext):
366d006b754SMatthew G Knepley      num += 1
367d006b754SMatthew G Knepley    name = base+str(num)+ext
368d006b754SMatthew G Knepley  with file(name, 'w') as f:
369d006b754SMatthew G Knepley    f.write('#PETSC_ARCH='+os.environ['PETSC_ARCH']+' '+' '.join(sys.argv)+'\n')
370d006b754SMatthew G Knepley    f.write('sizes  = '+repr(sizes)+'\n')
371d006b754SMatthew G Knepley    f.write('times  = '+repr(times)+'\n')
372d006b754SMatthew G Knepley    f.write('events = '+repr(events)+'\n')
373d006b754SMatthew G Knepley  return
374d006b754SMatthew G Knepley
3753428b40fSMatthew G Knepleyif __name__ == '__main__':
376eda8839fSMatthew G Knepley  import argparse
377eda8839fSMatthew G Knepley
378eda8839fSMatthew G Knepley  parser = argparse.ArgumentParser(description     = 'PETSc Benchmarking',
379eda8839fSMatthew G Knepley                                   epilog          = 'This script runs src/<library>/examples/tutorials/ex<num>, For more information, visit http://www.mcs.anl.gov/petsc',
380eda8839fSMatthew G Knepley                                   formatter_class = argparse.ArgumentDefaultsHelpFormatter)
381eda8839fSMatthew G Knepley  parser.add_argument('--library', default='SNES',                     help='The PETSc library used in this example')
382eda8839fSMatthew G Knepley  parser.add_argument('--num',     type = int, default='5',            help='The example number')
383eda8839fSMatthew G Knepley  parser.add_argument('--module',  default='summary',                  help='The module for timing output')
384eda8839fSMatthew G Knepley  parser.add_argument('--stage',   default='Main_Stage',               help='The default logging stage')
385eda8839fSMatthew G Knepley  parser.add_argument('--events',  nargs='+',                          help='Events to process')
386eda8839fSMatthew G Knepley  parser.add_argument('--batch',   action='store_true', default=False, help='Generate batch files for the runs instead')
387d006b754SMatthew G Knepley  parser.add_argument('--daemon',  action='store_true', default=False, help='Run as a daemon')
388683aebbfSMatthew G Knepley  subparsers = parser.add_subparsers(help='DM types')
389eda8839fSMatthew G Knepley
390683aebbfSMatthew G Knepley  parser_dmda = subparsers.add_parser('DMDA', help='Use a DMDA for the problem geometry')
391683aebbfSMatthew G Knepley  parser_dmda.add_argument('--size', nargs='+',  default=['10'], help='Grid size (implementation dependent)')
392683aebbfSMatthew G Knepley  parser_dmda.add_argument('--comp', type = int, default='1',    help='Number of field components')
393683aebbfSMatthew G Knepley  parser_dmda.add_argument('runs',   nargs='*',                  help='Run descriptions: <name>=<args>')
394683aebbfSMatthew G Knepley
395df494a56SMatthew G Knepley  parser_dmmesh = subparsers.add_parser('DMComplex', help='Use a DMComplex for the problem geometry')
396683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('--dim',      type = int, default='2',        help='Spatial dimension')
397683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('--refine',   nargs='+',  default=['0.0'],    help='List of refinement limits')
398683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('--order',    type = int, default='1',        help='Order of the finite element')
399683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('--operator', default='laplacian',            help='The operator name')
400683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('--blockExp', nargs='+', default=range(0, 5), help='List of block exponents j, block size is 2^j')
401683aebbfSMatthew G Knepley  parser_dmmesh.add_argument('runs',       nargs='*',                      help='Run descriptions: <name>=<args>')
402eda8839fSMatthew G Knepley
403eda8839fSMatthew G Knepley  args = parser.parse_args()
404eda8839fSMatthew G Knepley  print(args)
405683aebbfSMatthew G Knepley  if hasattr(args, 'comp'):
406683aebbfSMatthew G Knepley    args.dmType = 'DMDA'
407683aebbfSMatthew G Knepley  else:
408df494a56SMatthew G Knepley    args.dmType = 'DMComplex'
409683aebbfSMatthew G Knepley
410eda8839fSMatthew G Knepley  ex     = PETScExample(args.library, args.num, log_summary='summary.dat', log_summary_python = None if args.batch else args.module+'.py', preload='off')
411683aebbfSMatthew G Knepley  source = ex.petsc.source(args.library, args.num)
4123428b40fSMatthew G Knepley  sizes  = {}
4133428b40fSMatthew G Knepley  times  = {}
4143428b40fSMatthew G Knepley  events = {}
415d006b754SMatthew G Knepley  log    = not args.daemon
416d006b754SMatthew G Knepley
417d006b754SMatthew G Knepley  if args.daemon:
418d006b754SMatthew G Knepley    import daemon
419d006b754SMatthew G Knepley    print 'Starting daemon'
420d006b754SMatthew G Knepley    daemon.createDaemon('.')
421683aebbfSMatthew G Knepley
422eda8839fSMatthew G Knepley  for run in args.runs:
423eda8839fSMatthew G Knepley    name, stropts = run.split('=', 1)
424eda8839fSMatthew G Knepley    opts = dict([t if len(t) == 2 else (t[0], None) for t in [arg.split('=', 1) for arg in stropts.split(' ')]])
425683aebbfSMatthew G Knepley    if args.dmType == 'DMDA':
4263428b40fSMatthew G Knepley      sizes[name]  = []
4273428b40fSMatthew G Knepley      times[name]  = []
4283428b40fSMatthew G Knepley      events[name] = {}
429d006b754SMatthew G Knepley      run_DMDA(ex, name, opts, args, sizes, times, events, log=log)
430df494a56SMatthew G Knepley    elif args.dmType == 'DMComplex':
431683aebbfSMatthew G Knepley      sizes[name]  = {}
432683aebbfSMatthew G Knepley      times[name]  = {}
433683aebbfSMatthew G Knepley      events[name] = {}
434d006b754SMatthew G Knepley      run_DMComplex(ex, name, opts, args, sizes, times, events, log=log)
435d006b754SMatthew G Knepley  outputData(sizes, times, events)
436d006b754SMatthew G Knepley  if not args.batch and log: plotSummaryLine(args.library, args.num, args.events, sizes, times, events)
437683aebbfSMatthew G Knepley# Benchmark for ex50
438683aebbfSMatthew G Knepley# ./src/benchmarks/benchmarkExample.py --events VecMDot VecMAXPY KSPGMRESOrthog MatMult VecCUSPCopyTo VecCUSPCopyFrom MatCUSPCopyTo --num 50 DMDA --size 10 20 50 100 --comp 4 CPU='pc_type=none mat_no_inode dm_vec_type=seq dm_mat_type=seqaij' GPU='pc_type=none mat_no_inode dm_vec_type=seqcusp dm_mat_type=seqaijcusp cusp_synchronize'
439683aebbfSMatthew G Knepley# Benchmark for ex52
440fd49fd63SMatthew G Knepley# ./src/benchmarks/benchmarkExample.py --events IntegBatchCPU IntegBatchGPU IntegGPUOnly --num 52 DMComplex --refine 0.0625 0.00625 0.000625 0.0000625 --blockExp 4 --order=1 CPU='dm_view show_residual=0 compute_function batch' GPU='dm_view show_residual=0 compute_function batch gpu gpu_batches=8'
441fd49fd63SMatthew G Knepley# ./src/benchmarks/benchmarkExample.py --events IntegBatchCPU IntegBatchGPU IntegGPUOnly --num 52 DMComplex --refine 0.0625 0.00625 0.000625 0.0000625 --blockExp 4 --order=1 --operator=elasticity CPU='dm_view op_type=elasticity show_residual=0 compute_function batch' GPU='dm_view op_type=elasticity show_residual=0 compute_function batch gpu gpu_batches=8'
442fd49fd63SMatthew G Knepley# ./src/benchmarks/benchmarkExample.py --events IntegBatchCPU IntegBatchGPU IntegGPUOnly --num 52 DMComplex --dim=3 --refine 0.0625 0.00625 0.000625 0.0000625 --blockExp 4 --order=1 CPU='dim=3 dm_view show_residual=0 compute_function batch' GPU='dim=3 dm_view show_residual=0 compute_function batch gpu gpu_batches=8'
443