本文整理汇总了Python中SimPy.Simulation类的典型用法代码示例。如果您正苦于以下问题:Python Simulation类的具体用法?Python Simulation怎么用?Python Simulation使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Simulation类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: maybeSendShadowReads
def maybeSendShadowReads(self, replicaToServe, replicaSet):
if (random.uniform(0, 1.0) < self.shadowReadRatio):
for replica in replicaSet:
if (replica is not replicaToServe):
shadowReadTask = task.Task("ShadowRead", None)
self.taskArrivalTimeTracker[shadowReadTask] =\
Simulation.now()
self.taskSentTimeTracker[shadowReadTask] = Simulation.now()
self.sendRequest(shadowReadTask, replica)
self.rateLimiters[replica].forceUpdates()
示例2: test_activate
def test_activate():
"""Test of "activate" call"""
s = Simulation()
s.initialize()
r = Activatetest(sim=s)
try:
activate(r,r.run()) ## missing s.
except FatalSimerror:
pass
else:
assert False, "expected FatalSimerror"
s.simulate(until=1)
示例3: updateRates
def updateRates(self, replica, metricMap, task):
# Cubic Parameters go here
# beta = 0.2
# C = 0.000004
# Smax = 10
beta = self.cubicBeta
C = self.cubicC
Smax = self.cubicSmax
hysterisisFactor = self.hysterisisFactor
currentSendingRate = self.rateLimiters[replica].rate
currentReceiveRate = self.receiveRate[replica].getRate()
if (currentSendingRate < currentReceiveRate):
# This means that we need to bump up our own rate.
# For this, increase the rate according to a cubic
# window. Rmax is the sending-rate at which we last
# observed a congestion event. We grow aggressively
# towards this point, and then slow down, stabilise,
# and then advance further up. Every rate
# increase is capped by Smax.
T = Simulation.now() - self.lastRateDecrease[replica]
self.lastRateIncrease[replica] = Simulation.now()
Rmax = self.valueOfLastDecrease[replica]
newSendingRate = C * (T - (Rmax * beta/C)**(1.0/3.0))**3 + Rmax
if (newSendingRate - currentSendingRate > Smax):
self.rateLimiters[replica].rate += Smax
else:
self.rateLimiters[replica].rate = newSendingRate
elif (currentSendingRate > currentReceiveRate
and Simulation.now() - self.lastRateIncrease[replica]
> self.rateInterval * hysterisisFactor):
# The hysterisis factor in the condition is to ensure
# that the receive-rate measurements have enough time
# to adapt to the updated rate.
# So we're in here now, which means we need to back down.
# Multiplicatively decrease the rate by a factor of beta.
self.valueOfLastDecrease[replica] = currentSendingRate
self.rateLimiters[replica].rate *= beta
self.rateLimiters[replica].rate = \
max(self.rateLimiters[replica].rate, 0.0001)
self.lastRateDecrease[replica] = Simulation.now()
assert (self.rateLimiters[replica].rate > 0)
alphaObservation = (replica.id,
self.rateLimiters[replica].rate)
receiveRateObs = (replica.id,
self.receiveRate[replica].getRate())
self.rateMonitor.observe("%s %s" % alphaObservation)
self.receiveRateMonitor.observe("%s %s" % receiveRateObs)
示例4: update
def update(self, now):
#print(self.membrane_potential)
if self.type == 'current':
self.value_record.append(self.value)
self.value *= self.output_current_decay
if self.refact == 'yes':
self.spikes_record.append(self.membrane_potential)
return
self.membrane_potential -= (self.membrane_potential - self.reset_potential)*0.1 #leak
input = 0.0
for source in self.dendrites.keys():
if source.type == 'current':
input += source.value
elif source.type == 'voltage':
pass # Voltage type input, add code here
self.membrane_potential += input * 0.1
if self.membrane_potential < self.reset_potential:
self.membrane_potential = self.reset_potential
record = self.membrane_potential
if self.membrane_potential >= self.threshold:
if simpy.now() > self.last_firing_time:
self.last_firing_time = simpy.now()
event = Event(name = str(self) + " fire")
simpy.activate(event, event.fire(self), delay = 0.0)
record = self.spike_potential
self.spikes_record.append(record)
示例5: configure_scheduling
def configure_scheduling():
global SIMULATION_END_T
sim.initialize()
pynnn.setup()
SIMULATION_END_T = 0
RATE_ENC_RESPAWN_DICT.clear()
POP_ADAPT_DICT.clear()
示例6: visit_greeter
def visit_greeter(self):
name = 'greeter'
if self.debug:
print self.name, "at ",name, simpy.now()
arrive = simpy.now()
yield simpy.request, self, self.resources[name]
wait = simpy.now() - arrive
self.monitors[name].observe(wait)
GREETER_ENABLED = True
if GREETER_ENABLED:
time = random.triangular(low=5/60.0, high=92/60.0, mode=23/60.0)
#time = random.triangular(low=1.77/60.0, high=2.66/60.0, mode=2.38/60.0)
tib = self.numberOfForms * time
else:
tib = 0
yield simpy.hold,self,tib
yield simpy.release, self, self.resources[name]
p = random.random()
if self.preScreened:
for i in self.visit_dispenser():
yield i
else:
for i in self.visit_screener():
yield i
示例7: __init__
def __init__(self, lang_x, lang_y, speak_rate, learn_rate, innovation):
'''Initializes the agent. The variables used are:
lang_x: the x parameter for this agent's language
lang_y: the y parameter for this agent's language
speak_rate: the rate at which this agent initiates conversation.
time between conversation events is random.expovariate(speak_rate)
speak_rate is floored at 0.001.
learn_rate: the amount the speaker changes his language when he hears
another speaker. Changes his language by
learn_rate*(self.lang - other.lang)
innovation: The rate at which this speaker randomly changes his language.
time between innovation events is random.expovaraiate(innovation).
next_conversation: the simulation time for the next conversation initiated
by this agent.
next_innovation: the simulation time for the next innovation introduced by
this agent.'''
Sim.Process.__init__(self)
self.lang_x = lang_x
self.lang_y = lang_y
if speak_rate < 0.001:
speak_rate = 0.001
self.speak_rate = speak_rate
self.learn_rate = learn_rate
self.innovation = innovation
self.next_conversation = Sim.now() + expovariate(speak_rate)
self.next_innovation = Sim.now() + expovariate(innovation)
Agent.all_agents.append(self);
示例8: schedule_arrival
def schedule_arrival(self, transducer, params, pos):
"""
:param transducer:
:param params:
:param pos:
"""
distance_to = distance(pos, params["pos"]())
if distance_to > 0.01: # I should not receive my own transmissions
receive_power = params["power"] - \
attenuation_db(params["frequency"], distance_to)
# Speed of sound in water = 1482.0 m/s
travel_time = distance_to / transducer.physical_layer.medium_speed
packet = params['packet']
if DEBUG:
transducer.logger.debug("{type} from {source} to {dest} will take {t} to get to me {d}m away".format(
type=packet['type'], source=packet['source'],
dest=packet['dest'], t=travel_time, d=int(distance_to))
)
yield Sim.hold, self, travel_time
new_incoming_packet = IncomingPacket(
db2linear(receive_power), params["packet"], transducer.physical_layer)
Sim.activate(
new_incoming_packet, new_incoming_packet.receive(params["duration"]))
示例9: test_schedule_input_presentation
def test_schedule_input_presentation():
schedule_input_presentation(Tns.p1, Tns.s1, None, 10)
assert sim.peek() == sim.now()
schedule_input_presentation(Tns.p1, Tns.s1, start_t=20, duration=10)
assert sim.Globals.allEventTimes() == [0, 20]
from scheduling.pynn_scheduling import SIMULATION_END_T as end_t
assert end_t == 30
示例10: visit_medic
def visit_medic(self):
"""
Lognormal with :
logarithmic mean: 1.024
logarithmic std dev: 0.788
"""
name = 'medic'
if self.debug:
print self.name, "at ",name, simpy.now()
arrive = simpy.now()
yield simpy.request, self, self.resources[name]
wait = simpy.now() - arrive
self.monitors[name].observe(wait)
time = random.lognormvariate(mu=1.024, sigma=0.788)
tib = self.numberOfForms * time
yield simpy.hold,self,tib
yield simpy.release, self, self.resources[name]
p = random.random()
if p < 0.99:
for i in self.visit_dispenser():
yield i
else:
for i in self.visit_exit():
yield i
示例11: __init__
def __init__(self, physical_layer, ambient_noise, channel_event, position_query, sir_thresh, on_success,
name="a_transducer"):
# A resource with large capacity, because we don't want incoming messages to queue,
# We want them to interfere.
Sim.Resource.__init__(self, name=name, capacity=1000)
self.physical_layer = physical_layer
self.logger = physical_layer.logger.getChild(
"{0}".format(self.__class__.__name__))
# Interference is initialized as ambient noise
self.interference = ambient_noise
# Setup our event listener
self.channel_event = channel_event
self.listener = AcousticEventListener(self)
Sim.activate(self.listener, self.listener.listen(
self.channel_event, position_query))
# Function to call when we've received a packet
self.on_success = on_success
# SIR threshold
self.SIR_thresh = sir_thresh
# Controls the half-duplex behavior
self.transmitting = False
# Takes statistics about the collisions
self.collision = False
self.collisions = []
示例12: transmit_packet
def transmit_packet(self, packet):
if not self.is_idle():
# The MAC protocol is the one that should check this before
# transmitting
self.logger.warn(
"I should not do this... the channel is not idle!"
"Trying to send {typ} to {dest}"
"Currently have {q}".format(
typ=packet['type'],
dest=packet['dest'],
q=self.transducer.activeQ
))
if self.variable_power:
tx_range = self.level2distance[str(packet["level"])]
power = distance2intensity(
self.bandwidth, self.freq, tx_range, self.SNR_threshold)
else:
power = self.transmit_power
if power > self.max_output_power_used:
self.max_output_power_used = power
if power > self.max_output_power:
power = self.max_output_power
new_transmission = OutgoingPacket(self)
Sim.activate(
new_transmission, new_transmission.transmit(packet, power))
示例13: generate
def generate(self, number,
interval,
resources,
monitors,
times,
exitResource,
exitMonitor,
entryResource,
entryMonitor,
preScreenedPercentage):
"""
@param number: number of entitites to generate (integer)
@param interval: mean (in minutes) of times inter arrival
@param resources: array of resources (servers)
@param monitors: array of monitors to collect statistics
@param times: avg. service time depending on the resource
"""
for i in range(number):
customerName = "customer%d"%i
c = Customer.Customer(name=customerName,
resources=resources,
monitors=monitors,
times=times,
exitResource=exitResource,
exitMonitor=exitMonitor,
entryResource=entryResource,
entryMonitor=entryMonitor,
preScreenedPercentage=preScreenedPercentage
)
simpy.activate(c,c.visit())
t = random.expovariate(1.0/interval)
yield simpy.hold, self, t
示例14: operate
def operate(self, repairduration, triplength):
"""Travel until the trip is finished.
The bus may break down down several times during the trip.
Parameters:
repairduration -- time to recover from a breakdown and continue
triplength -- duration of the trip
"""
tripleft = triplength
# "tripleft"is the driving time to finish trip
# if there are no further breakdowns
while tripleft > 0:
yield sim.hold, self, tripleft # try to finish the trip
# if a breakdown intervenes
if self.interrupted():
print self.interruptCause.name, 'at %s' % sim.now()
tripleft = self.interruptLeft
# update driving time to finish
# the trip if no more breakdowns
self.interruptReset()
# end self interrupted state
#update next breakdown time
sim.reactivate(br, delay=repairduration)
#impose delay for repairs on self
yield sim.hold, self, repairduration
print 'Bus repaired at %s' % sim.now()
else: # no breakdowns intervened, so bus finished trip
break
print 'Bus has arrived at %s' % sim.now()
示例15: test__schedule_output_rate_encoder
def test__schedule_output_rate_encoder():
setup_clean_simpy()
pynnn.reset()
assert sim.now() + 0. == pynnn.get_current_time() + 0.
assert sim.allEventTimes() == []
_schedule_output_rate_encoder(Tns.rore1, 14, 89042)
_schedule_output_rate_encoder(Tns.rore2, 100, None)
assert sim.allEventTimes() == [14, 100]