File: Util.py

package info (click to toggle)
esys-particle 2.3.5%2Bdfsg2-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 13,132 kB
  • sloc: cpp: 81,480; python: 5,872; makefile: 1,259; sh: 313; perl: 225
file content (221 lines) | stat: -rw-r--r-- 6,744 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#############################################################
##                                                         ##
## Copyright (c) 2003-2017 by The University of Queensland ##
## Centre for Geoscience Computing                         ##
## http://earth.uq.edu.au/centre-geoscience-computing      ##
##                                                         ##
## Primary Business: Brisbane, Queensland, Australia       ##
## Licensed under the Open Software License version 3.0    ##
## http://www.apache.org/licenses/LICENSE-2.0              ##
##                                                         ##
#############################################################
"""
Common functionality between benchmarks.
"""

from __future__        import division, print_function
from time              import time
import math
import sys

from esys.lsm          import *
from esys.lsm.util     import *
from esys.lsm.geometry import *

"""
range(..) in Python 3 returns an iterable (as xrange() in Python 2), but
a list in Python 2.
"""
if sys.version_info[0] > 2:
  iRange = range
else:
  iRange = xrange

logger = Logging.getLogger("benchmarks.Util")

def getDimList(numParticles):
    ppd = int(math.ceil(math.pow(numParticles, (1.0/3.0))))
    return [ppd,ppd,ppd]

def getParticleCollection(numParticles, iterable):
    pIter = iter(iterable)
    pColl = ParticleCollection()
    for i in iRange(0, numParticles):
        pColl.createParticle(next(pIter))
    return pColl
    
def getSimpleBlock(numParticles, radius):
    return \
        getParticleCollection(
            numParticles,
            SimpleBlock(getDimList(numParticles), radius)
        )

def getHexagBlock(numParticles, radius):
    return \
        getParticleCollection(
            numParticles,
            HexagBlock(getDimList(numParticles), radius)
        )

class BenchSim(LsmMpi):
    def __init__(
        self,
        numTimeSteps=10000,
        numParticles=1000,
        spawnExe = "",
        spawnArgList = None
    ):
        self.logger = Logging.getLogger(str(self.__class__.__name__))
        if (spawnArgList == None):
            spawnArgList = []
        self.logger.info("Constructing LsmMpi")
        LsmMpi.__init__(self,1,[1,0,0], spawnExe, spawnArgList)
        self.logger.info("Setting number of time steps to {0:d}".format(numTimeSteps))
        self.setNumTimeSteps(numTimeSteps)
        self.logger.info("Initialising attributes")
        self.numParticles = numParticles
        self.startTime = 0
        self.stopTime  = 0
        self.runTime   = 0

    def doTimedRun(self):
        logger.info("Getting number of particles.")
        numParticles = self.getNumParticles()
        logger.info("Running simulation, {0:d} particles.".format(numParticles))
        self.startTime = time()
        self.run()
        self.stopTime = time()
        self.runTime = self.stopTime - self.startTime
        if (numParticles != self.getNumParticles()):
            raise \
                Exception(
                    "Mismatch between number of particles at start of" +\
                    " simulation ({0:d}) and number at end of simulation ({1:d})."\
                    .format(numParticles, self.getNumParticles())
                )

    def getRunTime(self):
        return self.runTime

class SimSuite:
    def __init__(self, benchSimClass):
        self.simClass = benchSimClass
        self.simList  = []
        self.outputFileName = None
        self.logger = Logging.getLogger("benchmarks.SimSuite")

    def __iter__(self):
        return iter(self.simList)

    def runSimulations(self):
        self.logger.info("Running simulations...")
        for sim in self.simList:
            sim.runSimulation()
            print("Run time for ",sim.getNumParticles(), " = ",sim.getRunTime())

        if (self.outputFileName != None):
            f = file(self.outputFileName, "w")
        else:
            f = sys.stdout
        for sim in self.simList:
            f.write(str(sim.getNumParticles()) + " ")
            f.write(str(sim.getRunTime()) + "\n")

    def run(self):
        self.runSimulations()


    def createSim(
      self,
      numTimeSteps,
      numParticles,
      spawnCmd,
      spawnCmdArgList
    ):
        return \
            self.simClass(
                numTimeSteps,
                numParticles,
                spawnCmd,
                spawnCmdArgList
            )

    def createSims(
        self,
        numTimeSteps,
        numParticlesList,
        outputFileName,
        spawnCmdLineList = None,
        verboseLsm = False
    ):
        setVerbosity(verboseLsm)
        self.outputFileName = outputFileName
        if ((spawnCmdLineList == None) or (len(spawnCmdLineList)==0)):
            spawnCmdLineList = [""]
        self.logger.info("Creating " + str(self.simClass) + " simulations...")
        self.simList = \
          [
            self.createSim(numTimeSteps,numParticles,spawnCmdLineList[0],spawnCmdLineList[1:])
            for numParticles in numParticlesList
          ]

def getOptionParser():
    parser = \
        OptParse.LogOptionParser(
            usage =\
              "usage: %prog [options]\n\n" +\
              "Runs a suite of benchmark simulations for varying number of particles. "
        )
    parser.add_option(
      "-n", "--num-time-steps",
      dest="numTimeSteps",
      type="int",
      metavar="N",
      default=10000,
      help=\
          "The number of time steps for which a simulation is run."+\
          " (default N=10000)"
    )
    parser.add_option(
      "-p", "--num-particles-list",
      dest="numParticlesList",
      type="int_list",
      metavar="L",
      default=[1000],
      help=\
          "A list specifying the number of particles in each simulation"+\
          " (default L=[1000]). One simulation is run for each element in"+\
          " this list."
    )
    parser.add_option(
      "-o", "--output-file-name",
      dest="outputFileName",
      type="string",
      metavar="F",
      default=None,
      help=\
          "Timing data for each simulation is written to this file"+\
          " (default F=None)."
    )
    parser.add_option(
      "-s", "--spawn-cmd-line-list",
      dest="spawnCmdLineList",
      type="string_list",
      metavar="C",
      default=None,
      help=\
          "A list specifying the command and arguments used to spawn MPI"+\
          " worker processes (default L=[1000])."
    )
    parser.add_option(
      "-v", "--verbose-lsm",
      dest="verboseLsm",
      action="store_true",
      default=False,
      help=\
          "Generates (lots of) debug output during simulation run" +\
          " (default no debug output)"
    )

    return parser