Example #1
0
def test5():
    print('test5')

    class X1(sim.Component):
        def process(self):
            while True:
                while True:
                    yield self.request(r1,
                                       2,
                                       5,
                                       r2,
                                       greedy=True,
                                       fail_at=de.now() + 6)
                    if not self.request_failed()():
                        break
                yield self.hold(1)
                self.release(r1, r2)
                yield self.passivate()

    class X2(sim.Component):
        def process(self):
            while True:
                yield self.request((r1, 3), (r2, 1, 1))
                yield self.hold(1)
                self.release(r1)
                yield self.passivate()

    class X3(sim.Component):
        def process(self):
            while True:
                yield self.request(r1, r2)
                yield self.hold(1)
                self.release(r1, r2)
                yield self.passivate()

    class Y(sim.Component):

        #        def __init__(self,*args,**kwargs):
        #            sim.Component.__init__(self,*args,**kwargs)

        def process(self):
            yield self.hold(3)
            x1.cancel()
            yield self.hold(10)
            r2.capacity(1)
            pass

    de = sim.Environment(trace=True)
    q = sim.Queue(name='q')
    r1 = sim.Resource(name='r1', capacity=3)
    r2 = sim.Resource(name='r2', capacity=0)
    r3 = sim.Resource(name='r3', capacity=1)

    x1 = X1()
    x2 = X2()
    x3 = X3()

    y = Y(name='y')
    sim.run(till=21)
Example #2
0
    def init_node(self, graph):
        if self.useful:
            sim.Component.__init__(self)
            coordinate = (self.x, self.y)
            neighbors = list(graph.neighbors(coordinate))
            if len(neighbors) != 2:
                print("Well well well, WE ARE F****D")

            self.left = neighbors[0]
            self.right = neighbors[1]
            self.order = sim.Resource(name="Bridge at " + str(coordinate) +
                                      " => order")
            self.moving = sim.Resource(name="Bridge at " + str(coordinate) +
                                       " => moving")
Example #3
0
 def __init__(self, coordinates_pair):
     super().__init__(coordinates_pair[0], coordinates_pair[1])
     self.intersections = {}
     self.intersections_list = None
     self.claim = sim.Resource()
     self.crossroad_empty = True
     self.last_queue_tmp = None
Example #4
0
def test14():
    class X(sim.Component):
        def process(self):
            yield self.request(*r)
            print(self.claimed_resources())

    de=sim.Environment()
    X()
    r=[sim.Resource() for i in range(10)]
    de.run(till=10)
Example #5
0
def test39():
    class C(sim.Component):
        def process(self):
            yield self.request(r,s='y')

    env=sim.Environment(trace=True)
    x=sim.Uniform(4)
    r = sim.Resource()
    C()
    env.run(4)
    def init_node(self, graph):
        if self.useful:
            sim.Component.__init__(self)
            coordinate = (self.x, self.y)
            neighbors = list(graph.neighbors(coordinate))
            if len(neighbors) != 2:
                print("Well well well, WE ARE F****D")

            self.left = neighbors[0]
            self.right = neighbors[1]
            self.key_in[left] = sim.Resource(
                name="Lock at " + str(coordinate) + " => left key in")
            self.key_in[right] = sim.Resource(
                name="Lock at " + str(coordinate) + " => right key in")
            self.wait_in[left] = sim.Queue(name="Lock at " + str(coordinate) +
                                           " => left queue in")
            self.wait_in[right] = sim.Queue(name="Lock at " + str(coordinate) +
                                            " => right queue in")
            self.key_out = sim.Resource(name="Lock at " + str(coordinate) +
                                        " => key out")
Example #7
0
    def run(self):
        self.of = sys.stdout if self.ofile is None else open(self.ofile, "w")

        print("# Cpu scheduler: %s" % self.cpu_scheduler, file=self.of)
        print("# Quantum: %s" % self.quantum, file=self.of)
        print(
            "pid arrival_time cpu_bursts_time io_bursts_time bursts_time tat ready_wait_time io_wait_time",
            file=self.of)

        self.env = sim.Environment(trace=False)
        self.cpu = sim.Resource("CPU",
                                capacity=1,
                                preemptive=self.cpu_scheduler == "srtf",
                                env=self.env)
        self.io = sim.Resource("I/O", capacity=1, env=self.env)
        ProcessArrival(simulator=self)
        self.env.run()

        if self.of is not None and self.of != sys.stdout:
            self.of.close()
            self.of = None
Example #8
0
    def __init__(self, part_seq,
                 random_seed=0,
                 intv=5, trace=False):
        arrRate, procRate, initQue = 1, 1, 0
        self.varList = ['numArr', 'numDep', 'arrRate', 'procRate', 'numBalk', 'queLen']
        self.part_seq = part_seq
        self.random_seed = random_seed
        self.arrRate = arrRate
        self.intArrTime = 1/arrRate
        self.procRate = procRate
        self.procTime = 1/procRate

        # environment should not be default
        # as each model runs independantly in different environment
        self.env = sim.Environment(name="env of particle %s with seed %s"%(part_seq, random_seed),
                                   isdefault_env=False, trace=trace,
                                   # random_seed=random_seed,
                                   )

        self.source = self.CustomerGenerator(name="customergenerator%s."%random_seed, env=self.env)
        self.source.model = self

        self.entity = self.Customer

        self.server = sim.Resource("clerk%s."%random_seed, capacity=1, env=self.env)
        self.server.model = self

        self.queue = self.server.requesters()
        if initQue != 0:
            self.addQue(initQue)

        self.timer = self.Timer(suppress_trace=True, env=self.env)
        self.timer.intv = intv
        self.timer.model = self

        self.customerArrList = []
        self.customerDepList = []

        self.numArr = 0
        self.numDep = 0
        self.procTimeList = []
        self.arrTimeList = []

        self.number_balked = 0
        self.maxLen = 100

        self.trace = {}
        self.traceDict = {}
        for var in self.varList:
            self.traceDict[var] = {}
Example #9
0
def test60():
    class X(sim.Component):
        def process(self):
            yield self.request(r)
            yield self.hold(sim.Uniform(0,2)())
            
    env = sim.Environment()
    r = sim.Resource(name='r',capacity=1)
    for i in range(5):
        X()
    env.trace(True)
    env.run(10)
    occupancy = r.claimed_quantity.mean() / r.capacity.mean()
    r.print_statistics()
    env.run()
Example #10
0
def test61():
    class X(sim.Component):
        def process(self):
            yield self.request(r)
            yield self.hold(1)

    class Y(sim.Component):
        def process(self):
            yield self.request(r)
            yield self.hold(1)
            self.cancel()

    env = sim.Environment(trace=True)
    r = sim.Resource('r', capacity=2)
    X()
    Y()
    env.run()
    print(r.claimed_quantity())
Example #11
0
def test4():
    print('test4')

    class X(sim.Component):
        def process(self):
            yield self.hold(10)
            yield self.request(res, 4)
            yield self.hold(20)
            res.requesters().print_statistics()
            res.claimers().print_statistics()
            for i in range(1):
                self.release(res, 4)

    class Y(sim.Component):
        def process(self):
            yield self.hold(11)
            yield self.request(res, 1, priority=1 - self.i)
            if self.request_failed():
                pass
            else:
                yield self.hold(1)
                self.release(res)

    class Z(sim.Component):
        def process(self):
            yield self.hold(20)
            y[4].reschedule()
            res.capacity(2)

    de = sim.Environment()
    res = sim.Resource(name='res.', capacity=4)
    res.x = 0
    x = X(name='x')
    y = [0]
    for i in range(6):
        c = Y(name='y.')
        c.i = i
        y.append(c)

    z = Z(name='z')
    sim.run(till=1000)
Example #12
0
def test24():
    class X1(sim.Component):
        def process(self):
            print('**x1 active')
            yield self.request((r,2))
            yield self.hold(100)
            yield self.passivate()
        def p1(self):
            yield self.hold(0.5)
            yield self.activate(process=self.process())
            yield self.hold(100)
            yield self.passivate()

    class X2(sim.Component):
        def process(self):
            yield self.hold(1)
            x1.activate(at=3,keep_request=True)
            yield self.hold(5)
            x1.request(r)
            yield self.hold(1)
            x1.passivate()
            de.main().passivate()
            yield self.hold(5)
            x1.activate(at=20)

    class X3(sim.Component):
        def process(self):
            a=1
            yield self.hold(1)
        pass

    de=sim.Environment(trace=True)
    x1=X1(process='p1')
    x1.activate(at=0.5,process='process',urgent=True,mode='blabla')
    x2=X2()
    x3=X3()
    print('***name=',x3.running_process())
    x4=sim.Component()
    x3.activate(process='process')
    r=sim.Resource('resource')
    de.run(till=sim.inf)
Example #13
0
def test44():
    import newqueue
    import newerqueue
    import newcomponent

    class X(sim.Component):
        def process(self):
            yield self.hold(10,mode='ok')
            if self == x1:
                yield self.passivate()
            yield self.hold(10,urgent=True)

    class Y(sim.Component):
        def setup(self, a='a'):
            print('a=',a)


        def process(self, text):
            print('-->',text)
            yield self.request((res, 4), fail_at=15)
            x1.activate(mode=5)


    env=sim.Environment(trace=True)
    res = sim.Resource()

    x0=X()
    x1=X(name='')
    x2=X(name=',')
    z=newcomponent.NewComponent()
    q0=sim.Queue()
    q1=newqueue.NewQueue()
    q2=newerqueue.NewerQueue()
    Y(process='process', text='Hello')
    q0.add(x1)
    q1.add(x1)
    q2.add(x1)

    env.run(50)
    env.print_trace_header()
Example #14
0
def test7():
    print('test7')

    class X1(sim.Component):
        def process(self):
            yield self.request(r1,5,r2,2,greedy=True,fail_at=5)
            yield self.passivate()


    class X2(sim.Component):
        def process(self):
            yield self.request(r1,8,r2)
            yield self.passivate()

    class X3(sim.Component):
        def process(self):
            yield self.request(r1,7)
            yield self.passivate()


    de=sim.Environment(trace=True)

    x1=X1()
    x2=X2()
    x3=X3()

    X4=sim.Component()

    r1=sim.Resource(capacity=10,anonymous=True)
    r2=sim.Resource()
    r3=sim.Resource()

    q={}
    for i in range(1,5):
        q[i]=sim.Queue()

    x1.enter(q[1])
    x1.enter(q[2])
    x1.enter(q[3])

    x2.enter(q[1])
    x3.enter(q[1])



    env.run(10)
    r2.capacity(2)
    env.run(20)

    print(sim.default_env)

    print(x1)
    print(x2)
    print(x3)

    print (q[1])
    print (q[2])
    print (q[3])
    print (q[4])

    print(r1)
    print(r2)
    print(r3)

    d=sim.Exponential(10)
    print(d)
    print(sim.Uniform(1,2))
    print(sim.Triangular(40,150,55))
    print(sim.Distribution('Constant(5)'))
Example #15
0
    '''
    Generate new cars that arrive at the gas station.
    '''

    def process(self):
        while True:
            yield self.hold(T_INTER.sample())
            Car()


# Setup and start the simulation
env = sim.Environment(trace=False)
print('Gas Station refuelling')

# Create environment and start processes
gas_station = sim.Resource('gas_station', 2)
fuel_pump = sim.Resource(
    'fuel_pump', capacity=GAS_STATION_SIZE, anonymous=True)
tank_truck = TankTruck()
CarGenerator()

env.run(SIM_TIME)

fuel_pump.capacity.print_histogram()
fuel_pump.claimed_quantity.print_histogram()
fuel_pump.available_quantity.print_histogram()


gas_station.requesters().length.print_histogram()
gas_station.requesters().length_of_stay.print_histogram(30, 0, 10)
import salabim as sim


class CustomerGenerator(sim.Component):
    def process(self):
        while True:
            Customer()
            yield self.hold(sim.Uniform(5, 15).sample())


class Customer(sim.Component):
    def process(self):
        yield self.request(clerks)
        yield self.hold(30)
        self.release()


env = sim.Environment(trace=False)
CustomerGenerator(name='customergenerator')
clerks = sim.Resource('clerk', capacity=3)

env.run(till=50000)

clerks.requesters().length.print_histogram(30, 0, 1)
print()
clerks.requesters().length_of_stay.print_histogram(30, 0, 10)

clerks.print_statistics()
clerks.print_info()

Example #17
0
import salabim as sim


class CustomerGenerator(sim.Component):
    def process(self):
        while True:
            Customer()
            yield self.hold(sim.Uniform(5, 15).sample())


class Customer(sim.Component):
    def process(self):
        yield self.request(clerks)
        yield self.hold(30)
        self.release()


env = sim.Environment(trace=False)
CustomerGenerator()
clerks = sim.Resource('clerk', 3)

env.run(till=50000)

clerks.requesters().length.print_histogram(30, 0, 1)
print()
clerks.requesters().length_of_stay.print_histogram(30, 0, 10)

clerks.print_statistics()
clerks.print_info()
print(clerks.claimed_quantity())
Example #18
0
    """Customer arrives, is served and leaves."""
    def process(self):
        env.print_trace('', self.name(), 'arrrived')

        patience = sim.Uniform(MIN_PATIENCE, MAX_PATIENCE).sample()
        yield self.request(counter, fail_delay=patience)
        wait = env.now() - self.creation_time()

        if self.failed():
            # We reneged
            env.print_trace('', self.name(),
                            'RENEGED after {:6.3f}'.format(wait))
        else:
            # We got to the counter
            env.print_trace('', self.name(), 'waited for {:6.3f}'.format(wait))
            yield self.hold(sim.Exponential(TIME_IN_BANK).sample())
            env.print_trace('', self.name(), 'finished')
            # auto release counter


# Setup and start the simulation

env = sim.Environment(trace=True)

# Start processes and run

counter = sim.Resource(capacity=1)
Source()

env.run()
class Philosopher(sim.Component):
    def setup(self):
        self.rightfork = forks[self.sequence_number()]
        self.leftfork = forks[self.sequence_number() -
                              1 if self.sequence_number() else nphilosophers -
                              1]

    def process(self):
        while True:
            yield self.hold(thinkingtime_mean * sim.Uniform(0.5, 1.5)(),
                            mode='thinking')
            yield self.request(self.leftfork, self.rightfork, mode='waiting')
            yield self.hold(eatingtime_mean * sim.Uniform(0.5, 1.5)(),
                            mode='eating')
            self.release()


eatingtime_mean = 20
thinkingtime_mean = 20
nphilosophers = 8
sim.random_seed(1234567)

while True:
    env = sim.Environment()
    forks = [sim.Resource() for _ in range(nphilosophers)]
    philosophers = [Philosopher() for _ in range(nphilosophers)]

    do_animation()

    env.run()
Example #20
0
cutqueue = sim.Queue("Cutting Queue")
finqueue = sim.Queue("Finishing Queue")
paintqueue = sim.Queue("Painting Queue")
packpranchaqueue = sim.Queue("Packing Prancha Queue")
packwheelqueue = sim.Queue("Packing Wheel Queue")
assemblyqueue = sim.Queue("Assembly Queue")
foundryqueue = sim.Queue("Foundry Queue")
machiningqueue = sim.Queue("Machining Queue")
printingqueue = sim.Queue("Printing Queue")

finish = ["packing", "packingwheel",
          "assembly", "assembly", "assembly", "packing", "packingwheel",
          "assembly", "assembly", "assembly"]

#Resources
prancha = sim.Resource("prancha")
roda = sim.Resource("rodas")
worker = sim.Resource("Worker", capacity=3)
prensa = sim.Resource("prensa", capacity=4)
fornalha = sim.Resource("fornalha", capacity=5)
torno = sim.Resource("torno", capacity=2)
impressora = sim.Resource("impressora", capacity=1)
maq_embalagem = sim.Resource("maq_embalagem", capacity=1)

#Fila Espera Armazem
storage1queue = sim.Queue("storage1")
storage2queue = sim.Queue("storage2")
storage3queue = sim.Queue("storage3")
storage4queue = sim.Queue("storage4")

env.run(till=34560) #22 dias
    def process(self):
        yield self.request(washers)
        duration = sim.Uniform(0, 5)()
        self.duration_anim = sim.AnimateRectangle(
            spec=(0, 0, duration * 10, 20),
            x=100,
            y=lambda arg, t: arg.index(list(self.queues())[0]) * 30 + 50,
            fillcolor="",
            linecolor="yellow",
            arg=self,
            parent=self,
        )
        self.wait_anim.fillcolor = "yellow"
        self.wait_anim.x = 100

        yield self.hold(duration)


env = sim.Environment(trace=False)
env.animate(True)
env.modelname("Demo animation dynamic lambda")
env.background_color("20%gray")
sim.AnimateText("Wash", x=100, y=25, text_anchor="sw")
sim.AnimateText("Wait", x=200, y=25, text_anchor="sw")

washers = sim.Resource(name="washers", capacity=2)
CarGenerator()

env.run(100)
Example #22
0
import salabim as sim


class ClientGenerator(sim.Component):
    def process(self):
        while True:
            yield self.hold(inter_arrival_time_dis.sample())
            Client()


class Client(sim.Component):
    def process(self):
        yield self.request(clerks)
        yield self.hold(service_duration_dis.sample())


env = sim.Environment(trace=True)
number_of_clerks = 5
inter_arrival_time_dis = sim.Exponential(1)
service_duration_dis = sim.Exponential(4)

clerks = sim.Resource(name="clerks", capacity=number_of_clerks)

ClientGenerator()
env.run()
Example #23
0
# Bank, 3 clerks (resources).py
import salabim as sim


class CustomerGenerator(sim.Component):
    def process(self):
        while True:
            Customer()
            yield self.hold(sim.Uniform(5, 15).sample())


class Customer(sim.Component):
    def process(self):
        yield self.request(clerks)
        yield self.hold(30)
        self.release()  # not really required


env = sim.Environment(trace=False)
CustomerGenerator()
clerks = sim.Resource("clerks", capacity=3)

env.run(till=50000)

clerks.print_statistics()
clerks.print_info()
Example #24
0
class Client(sim.Component):
    def process(self):
        self.enter(system)
        yield self.request(servers)
        yield self.hold(sim.Exponential(server_time).sample())
        self.leave()


class ClientGenerator(sim.Component):
    def process(self):
        while True:
            yield self.hold(sim.Exponential(iat).sample())
            Client()


env = sim.Environment()

nservers = 5
iat = 1
server_time = 4

system = sim.Queue("system")

servers = sim.Resource(name="servers", capacity=nservers)

ClientGenerator()

do_animation()
env.run()
Example #25
0
    def process(self):
        while True:
            yield self.hold(sim.Uniform(1, 5)())
            res = sim.Pdf(resources, 1)()
            yield self.request(res)
            yield self.hold(res.sequence_number() * 1 +
                            (env.now() % 24) * 0.01)
            self.release()


env = sim.Environment(time_unit="hours", trace=False)

for _ in range(20):
    X()

resources = [sim.Resource() for _ in range(13)]

env.run(till=env.days(100))

for res in resources:
    print(f"{res.name():13s}total {res.occupancy.mean():10.3f}")
    for hour in range(24):
        print(
            f"{res.name():13s}{hour:2d}-{hour+1:2d} {res.occupancy[hour: hour+1: 24].mean():10.3f}"
        )
    print()

occupancy_aggregated = sum(res.occupancy for res in resources)

print(
    f"Total        total {occupancy_aggregated.mean() / len(resources):10.3f}")
Example #26
0
    def process(self):
        while True:
            yield self.request(res)
            yield self.hold(5)
            self.release(res)


class Part(sim.Component):
    def setup(self, machine):
        self.machine = machine

    def process(self):
        while True:
            yield self.hold(ttf())
            self.machine.interrupt()
            yield self.hold(ttr())
            self.machine.resume()


env = sim.Environment(trace=True)
ttf = sim.Uniform(10, 20)  # time to failure distribution
ttr = sim.Uniform(3, 6)  # time to repair distribution

res = sim.Resource()

for _ in range(2):
    Machine()

env.run(400)
Example #27
0
class CarGenerator(sim.Component):
    """
    Generate new cars that arrive at the gas station.
    """
    def process(self):
        while True:
            yield self.hold(T_INTER.sample())
            Car()


# Setup and start the simulation
env = sim.Environment(trace=False)
print("Gas Station refuelling")

# Create environment and start processes
gas_station = sim.Resource("gas_station", 2)
fuel_pump = sim.Resource("fuel_pump",
                         capacity=GAS_STATION_SIZE,
                         anonymous=True)
tank_truck = TankTruck()
CarGenerator()

env.run(SIM_TIME)

fuel_pump.capacity.print_histogram()
fuel_pump.claimed_quantity.print_histogram()
fuel_pump.available_quantity.print_histogram()

gas_station.requesters().length.print_histogram()
gas_station.requesters().length_of_stay.print_histogram(30, 0, 10)
Example #28
0
            self.release(key_out)
            yield self.request((key_out, 1, 1000), mode=None)


env = sim.Environment()

locklength = 60
switchtime = 10
intime = 2
outtime = 2
meanlength = 30
iat = 30

lockmeters = {}
key_in = {}
lockqueue = sim.Queue('lockqueue')
key_out = sim.Resource(name=' key_out')

for side in (left, right):
    lockmeters[side] = sim.Resource(capacity=locklength, name=sidename(
        side) + ' lock meters', anonymous=True)
    key_in[side] = sim.Resource(name=sidename(side) + ' key in')
    shipgenerator = Shipgenerator(name=sidename(side) + 'Shipgenerator')
    shipgenerator.side = side

lock = Lock('Lock')
lock.side = left

do_animation()
env.run()
Example #29
0
        while True:
            self.job_time = JOB_DURATION
            self.remaining_time = self.job_time
            while self.remaining_time > 1e-8:
                yield self.request((repairman, 1, 1), mode='wait')
                yield self.hold(self.remaining_time, mode='work')
                self.remaining_time -= (self.env.now() - self.mode_time())
            other.release()
            self.parts_made += 1


# Setup and start the simulation
print('Machine shop')
env = sim.Environment()
random.seed(RANDOM_SEED)  # This helps reproducing the results

repairman = sim.Resource('repairman')

machines = [Machine(n=i) for i in range(NUM_MACHINES)]
other = Other(name='other')

# Execute!
do_animation()
env.run(till=SIM_TIME)

# Analyis/results
print('Machine shop results after %s weeks' % WEEKS)
for machine in machines:
    print('%s made %d parts.' % (machine.name(), machine.parts_made))
repairman.print_statistics()
# HOUSEKEEPING STATEMENTS
env = sim.Environment()
TruckGenerator()
# Assignment of input data to variables
# General
sim.random_seed(RND_NUM_STREAM)
warmup_time = WARMUP_TIME
simulation_time = SIMULATION_TIME
# Facilities (Resources)
shovels_number = SHOVELS_NUMBER
crushers_number = CRUSHERS_NUMBER
# Trucks
trucks_number = TRUCKS_NUMBER
trucks_interarrival_time = TRUCKS_INTERARRIVAL_TIME
# Trucks Times
truck_loading_time = TRUCK_LOADING_TIME
truck_travel_to_crusher_time = TRUCK_TRAVEL_TO_CRUSHER_TIME
truck_unload_into_crusher_time = TRUCK_UNLOAD_INTO_CRUSHER_TIME
truck_return_from_crusher_to_shovel_time = TRUCK_RETURN_FROM_CRUSHER_TO_SHOVEL_TIME
# Failure & Repair Times
truck_mttf = TRUCK_MTTF
truck_mttr = TRUCK_MTTR
# Declarations
shovels = sim.Resource(name="SHOVEL", capacity=shovels_number)
crushers = sim.Resource(name='CRUSHER', capacity=crushers_number)
queue_loading = sim.Queue('Queue_for_Loading')
queue_crusher = sim.Queue('Queue_for_Crusher')

if __name__ == '__main__':
    main()