Emil Sekerinski, McMaster University, Winter Term 16/17 ...

15
Emil Sekerinski, McMaster University, WinterTerm 16/17 COMP SCI 1MD3 Introduction to Programming

Transcript of Emil Sekerinski, McMaster University, Winter Term 16/17 ...

EmilSekerinski,McMasterUniversity,WinterTerm16/17COMPSCI1MD3IntroductiontoProgramming

Considerfloodingavalley(dambreak,tides,spring):whatisthewaterlevelatspecificpointsinthevalleyaftersometime?Insteadofusinganalyticalmodels(differentialequations),computersallowsuchproblemstobesimulateddiscretely:¡  Thewaterlevelinthevalleyisrepresentedbypointsonagrid¡  Theevolutionisapproximatedbydiscretetimesteps

Similarproblemsare:oilspill(howfardoesthespillspreadaftersometime),tsunami(howhighisthewaveandwhenwillitreachacertainpoint),spreadofdiseases,bacteriagrowth

Thespeedwithwhichthewaterspreadsisdeterminedbyarulethatisappliedtoeachcell,forexample:¡  acellthathasanyoneofits

neighbourswithtwicetheheightofitsownwater,takeshalfthatheightasitsown(roundingup).

¡  acellthathasamajorityofneighbourswithheightshigherthanitselfincreasesitsownheightbyone.

Thisruleisappliedtoallcellssimultaneouslytocomputethewaterlevelatthenexttimestep.

Variousnotionsofneighborsarepossible,e.g.8or4neighborsinasquaregrid,orevenotherformsofgrids.Inacellularautomatonasingleruledeterminesthenewstateofeachcellbasedonitsneighbors.Allcellsareupdatedatonce.(Eachcellisanautomaton,e.g.afinitestatemachine.)

AparticularlysimplecellularautomatonistheGameofLife,developedbymathematicianJohnConwayin1970,andpopularizedthroughMartinGardner'scolumninScientificAmerican.Onasquaregrid,eachcelliseitheraliveofdead(onebitpercell):¡  anydeadcellwithexactly3neighboursbecomesalive:birth¡  anylivecellwith2or3liveneighboursremainsalive:survival¡  anylivecellwithfewerthan2liveneighboursdies:deathby

loneliness¡  anylivecellwithmorethan3liveneighboursdies:deathby

overcrowding

class LifeBoard: "Game of Life board, a rectangular board with live and dead cells"

def __init__(self, width, height): """Create a new Game of Life board of specified size.""" self.live = set() self.width, self.height = width, height def makeRandom(self): "Fill the board with a random pattern" self.live.clear() for x in range(self.width): for y in range(self.height): if random.random() > 0.5: self.live.add((x, y)) def toggle(self, x, y): """Toggle a cell's state between live and dead; do nothing if (x, y) are outside the board.""" if (0 <= x < self.width) and (0 <= y < self.height): if (x, y) in self.live: self.live.remove((x, y)) else: self.live.add((x, y))

def erase(self): "Clear the entire board." self.live.clear()

def step(self): "Compute the next generation according to Conway's rule." n = set() for x in range(self.width): for y in range(self.height): c = 0 for xp in range(x - 1, x + 2): for yp in range(y - 1, y + 2): c = c + ((x, y) != (xp, yp) in self.live) if (x, y) in self.live: if c in (2, 3): n.add((x, y)) # survival else: if c == 3: n.add((x, y)) # birth self.live = n

Weassumethattheeventstobesimulatedoccuratdiscretetimepoints.Atypicalexampleisthatofwaitinglines.Eventsare:¡  customersarrive¡  customersareserved¡  customersleaveThearrivalintervalsandthetimeforservicearedescribedbyadistribution,ratherthanbeingfixed.Examples:¡  drive-through,gasstations,supermarkets,banks¡  trafficsystems¡  requeststowebserver¡  computernetworks

AsimplestatisticofawaitinglineisthemeannumberofcustomerswaitingorinserviceoveragivenperiodoflengthT.ThemeanLiscomputedasL=W/TwhereWisthecumulativewaitingtime,definedastheareaunderthegraph.Thegraphiscalledthepathofthequeue.

class Path: def __init__(self): self.w, self.n, self.t = 0, 0, 0 def up(self, t): self.w = self.w + self.n * (t - self.t) self.n, self.t = self.n + 1, t def down(self, t): self.w = self.w + self.n * (t - self.t) self.n, self.t = self.n - 1, t def mean(self, t_end): return (self.w + \ self.n * (t_end - self.t)) / t_end

Aqueueisdatastructurethatsupportsenqueuinganddequeuingofitems.Last-infirst-outqueue,alsocalledastack,canberepresentedbyalist:

initially: q = []enqueuex: q.append(x)addslastitemdequeue: q.pop()removesandreturnslastitem

First-infirst-outqueue,canalsoberepresentedasalist:

initially: q = []enqueuex: q.append(x)dequeue: q.pop(0)removesandreturnsfirstitem

Priorityqueueorderselementsaccordingtoacertaincriterionandretrievestheleastelement,irrespectiveofwhenitwasadded.Ifweassumethattheelementsareorderedby<,thequeuecanbestoredasaset:

initially: q = set()enqueuex: q.add(x)dequeue: r = min(q); q.remove(r)

class Event: def __init__(self, time, actor, msg): self.time, self.actor, self.msg = time, actor, msg def __lt__(self, other): return self.time < other.time

class Simulator: def __init__(self): self.calendar, self.time = set(), 0.0 def schedule(self, time, actor, msg): self.calendar.add(Event(self.time + time, actor, msg)) def simulate(self, dt): t_end = self.time + dt while self.time <= t_end and len(self.calendar) > 0: cur = min(self.calendar) self.calendar.remove(cur) self.time = cur.time cur.actor.handle(cur.msg) return len(self.calendar) > 0

¡  Customersproceedthroughasystemofqueuingstations.Weassumethatcustomersdecidewhichstationtovisitandrequestservicefromthatstation

¡  Sourcesgeneratecustomers¡  Stationsconsistsofaserverandwaitingline.Thestation

notifiesthecustomerwhentheserverisready.Thecustomer(notthestation)determinestheservicingperiod

Westudyasystemwithasinglestationandtwoexponentialdistributions: