Beispiel #1
0
    def ext_trans(self, port, msg):
        if port in self.human_port_map:  #garbage 비율  Process
            #print('[check]1')
            data = msg.retrieve()
            ev_t = SystemSimulator().get_engine("sname").get_global_time()
            ag_id = 0
            ag_name = ""

            ag_satisfaction = 0
            #print(ev_t,port,"!!")

            member = data[0]
            ag_id = member.get_id()
            ag_name = member.get_name()
            ag_satisfaction = member.get_satisfaction()
            #print(SystemSimulator().get_engine("sname").get_global_time())

            if self.outp is not None:
                """ To implement verbose mode """
                if ag_name not in self.alist:
                    self.alist[ag_name] = {}

                self.alist[ag_name][ev_t] = ag_satisfaction
                #print(self.alist[ag_name])

            self._cur_state = "PROCESS"
            self.recv_checker_port.append(port)

        if port in self.family_port_map:  #garbage 누적
            #print("fam_port",port)
            data = msg.retrieve()
            ev_t = SystemSimulator().get_engine("sname").get_global_time()
            ag_id = 0
            ag_name = ""
            ag_amount = 0
            ag_satisfaction = 0
            #print(ev_t,port,"!!")
            for member, accumulated in data[0].items():
                self.cur_amount += accumulated
                ag_id = member.get_id()
                ag_name = member.get_name()
                ag_amount = accumulated
                ag_satisfaction = member.get_satisfaction()
                #print(SystemSimulator().get_engine("sname").get_global_time())

                if self.outp is not None:
                    """ To implement verbose mode """
                    if ag_name not in self.dlist:
                        self.dlist[ag_name] = {}

                    self.dlist[ag_name][ev_t] = (ag_amount, ag_satisfaction)
                    #print(self.dlist[ag_name])

        if port == "req_empty":  #garbage 양 반환 process
            #print("[truck]1")
            self.avaliable_amount = msg.retrieve()[0]
            self._cur_state = "PROC_TRUCK"
Beispiel #2
0
        def __init__(self, instance_time, destruct_time, name, engine_name,
                     regions):
            BehaviorModelExecutor.__init__(self, instance_time, destruct_time,
                                           name, engine_name)

            # Open CSV
            self.init_state("REPORT")
            self.insert_state("REPORT", REPORT_FREQ)

            self.regions = regions
            self.engine = SystemSimulator().get_engine(engine_name)
Beispiel #3
0
        def __init__(self, instance_time, destruct_time, name, engine_name,
                     region):
            BehaviorModelExecutor.__init__(self, instance_time, destruct_time,
                                           name, engine_name)

            # Open CSV
            self.init_state("REPORT")
            self.insert_state("REPORT", NETWORK_UPDATE_FREQ)

            self.region = region
            self.agents_to_process = []

            self.engine = SystemSimulator().get_engine(engine_name)
    def ext_trans(self, port, msg):
        # print(port)
        if port == "start":
            self._cur_state = "INITAL_APPROACH"
        elif port == "end":
            self._cur_state = "IDLE"
        elif port in self.garbage_port_map:
            self.garbage_port_map[port] += msg.retrieve()[
                0]  # 각 건물별 쓰레기 수거량 분석
            self.truck_current_storage += msg.retrieve()[0]
            # print("self.truck_current_storage", self.truck_current_storage)
            self.accummulated_garbage += msg.retrieve()[0]

            ev_t = SystemSimulator().get_engine("sname").get_global_time()

            if self.outname is not None:
                with open("{0}/truck.csv".format(self.outname), 'a') as file:
                    file.write(str(ev_t))
                    file.write(",")
                    file.write(str(self.cur_index))
                    file.write(",")
                    file.write(str(self.schedule[self.cur_index - 1][0]))
                    file.write(",")
                    file.write(str(self.truck_current_storage))
                    file.write(",")
                    file.write(str(self.accummulated_garbage))
                    file.write("\n")
Beispiel #5
0
    class RegionsReportModel(BehaviorModelExecutor):
        def __init__(self, instance_time, destruct_time, name, engine_name,
                     regions):
            BehaviorModelExecutor.__init__(self, instance_time, destruct_time,
                                           name, engine_name)

            # Open CSV
            self.init_state("REPORT")
            self.insert_state("REPORT", REPORT_FREQ)

            self.regions = regions
            self.engine = SystemSimulator().get_engine(engine_name)

        def ext_trans(self, port, msg):
            pass

        def output(self):
            for _id, region in self.regions.items():
                if REPORT_TO_CONSOLE:
                    _content = self.generate_report_contents(
                        _id, region.get_matrix(), region.region_agents, True)
                    print(_content)
                    #print(region.get_matrix())
                if NETWORK_UI_FLAG:
                    _content = self.generate_report_contents(
                        _id, region.get_matrix(), region.region_agents, False)
                    net_manager = NetworkManager()
                    net_manager.udp_send_string(NETWORK_HOST_ADDR,
                                                NETWORK_HOST_PORT,
                                                bytes(_content))

            return None

        def int_trans(self):
            if self._cur_state == "REPORT":
                self._cur_state = "REPORT"

        def generate_report_contents(self,
                                     _id,
                                     _region,
                                     agents,
                                     verbose_mode=True):
            contents = bytearray()
            if verbose_mode:
                str_lst = [agent.get_id() for agent in agents]
                contents = f"periodic|sim_time:{self.engine.get_global_time()}|region_id:{_id}|region:{_region.flatten()}|left:{str_lst}"
            else:
                contents.append(ord('p'))
                contents.extend(struct.pack("d",
                                            self.engine.get_global_time()))
                contents.append(_id)
                contents.append(_region.shape[1])
                contents.append(_region.shape[0])
                for cell in _region.flatten():
                    contents.append(len(cell.agent_lst))
            return contents
Beispiel #6
0
    def output(self):
        for agent in self.agents_to_process:
            if self.check_sim_end(agent.get_id()):
                self.early_exit = True
                print(f"Simulation End Time:{SystemSimulator().get_engine(self.engine_name).get_global_time()}" )
                print(f"Total Agents:{len(self.tot_agent_map)+ len(self.evac_agent_lst)}, Evacuated:{len(self.evac_agent_lst)}, Survival Ratio:{float(len(self.evac_agent_lst)/(len(self.tot_agent_map)+ len(self.evac_agent_lst)))}")
                SystemSimulator().get_engine(self.engine_name).simulation_stop()

        self.agents_to_process.clear()
        return None
Beispiel #7
0
import sys, os

from evsim.system_simulator import SystemSimulator
from evsim.behavior_model_executor import BehaviorModelExecutor
from evsim.system_message import SysMessage
from evsim.definition import *

from config import *

from adev.clock import Clock
from adev.agent import Agent, AgentOpt
from adev.region_manager import RegionManager, UniRegionManager

import random
# Simulation Configuration
se = SystemSimulator()

se.register_engine("sname", SIMULATION_MODE, TIME_DENSITY)

# NETWORK_LIBRARY
if NETWORK_UI_FLAG:
    from ipworks import *
    from evsim.network_manager import NetworkManager

    udp_lib = UDPPort()
    udp_lib.runtime_license = IPWORKS_LICENSE
    #ipport = IPPort()
    #ipport.runtime_license = IPWORKS_LICENSE
    net_manager = NetworkManager()
    net_manager.register_network_library(udp_lib)
    #net_manager.register_network_library(ipport)
Beispiel #8
0
    class RegionReport(BehaviorModelExecutor):
        def __init__(self, instance_time, destruct_time, name, engine_name,
                     region):
            BehaviorModelExecutor.__init__(self, instance_time, destruct_time,
                                           name, engine_name)

            # Open CSV
            self.init_state("REPORT")
            self.insert_state("REPORT", NETWORK_UPDATE_FREQ)

            self.region = region
            self.agents_to_process = []

            self.engine = SystemSimulator().get_engine(engine_name)

        def ext_trans(self, port, msg):
            if port[0:8] == "agent_in":
                self._cur_state = "REPORT"
                port_num = int(re.search(r"\[(\w+)\]", port).group(1))

                data = msg.retrieve()
                #print(self, data)
                #for agent in data:
                self.agents_to_process.append(
                    ("i", self.region.get_entry_points()[port_num], data[0]))
            elif port[0:9] == "agent_out":
                self._cur_state = "REPORT"
                port_num = int(re.search(r"\[(\w+)\]", port).group(1))

                data = msg.retrieve()
                self.agents_to_process.append(
                    ("o", self.region.get_exit_points()[port_num], data[0]))

        def output(self):
            if self.agents_to_process:
                for info in self.agents_to_process:
                    if REPORT_FLAG:
                        msg_contents = self.generate_report_contents(
                            info[0], info[1], info[2], True)
                        print(msg_contents)

                    msg_contents = self.generate_report_contents(
                        info[0], info[1], info[2], False)
                    net_manager = NetworkManager()
                    net_manager.udp_send_string(NETWORK_HOST_ADDR,
                                                NETWORK_HOST_PORT,
                                                bytes(msg_contents))
                    #net_manager.tcp_send_string(msg_contents)

                self.agents_to_process.clear()

            return None

        def int_trans(self):
            if self._cur_state == "REPORT":
                self._cur_state = "REPORT"

        def generate_report_contents(self,
                                     _type,
                                     _coord,
                                     agent_info,
                                     verbose_mode=True):
            _str = ""
            if verbose_mode:
                _str = f"eventual|sim_time:{self.engine.get_global_time()}|region_id:{self.region.get_region_id()}|event_type:{_type}|coord:{_coord}|aid:{agent_info}"
            else:
                _str = bytearray()
                _str.append(ord('e'))
                _str.extend(struct.pack("d", self.engine.get_global_time()))
                _str.append(self.region.get_region_id())
                _str.append(ord(_type))
                _str.append(_coord[0])
                _str.append(_coord[1])
                _str.extend(agent_info.packing())
            return _str
Beispiel #9
0
import contexts

from evsim.system_simulator import SystemSimulator
from evsim.behavior_model_executor import BehaviorModelExecutor
from evsim.system_message import SysMessage
from evsim.definition import *

from crawler import Crawler

from config import *

se = SystemSimulator()

SystemSimulator().register_engine("sname", SIMULATION_MODE)

a = Crawler(0, Infinite, "Peter", "sname")

SystemSimulator().get_engine("sname").insert_input_port("start")
SystemSimulator().get_engine("sname").insert_input_port("report")
SystemSimulator().get_engine("sname").register_entity(a)

SystemSimulator().get_engine("sname").coupling_relation(None, "report", a, "report")
SystemSimulator().get_engine("sname").insert_external_event("report", None)
SystemSimulator().get_engine("sname").simulate()


Beispiel #10
0
def ssimulate():
    se = SystemSimulator()
    se.register_engine("background", SIMULATION_MODE)
    a= Crawler(0, Infinite, "machine", "background")
    se.get_engine("background").insert_input_port("start")
    se.get_engine("background").register_entity(a)
    se.get_engine("background").coupling_relation(None,"start",a,"process")
    se.get_engine("background").insert_external_event("start", None)
    se.get_engine("background").simulate()
Beispiel #11
0
from .eval import Eval

#mail
from celery import Celery
from flask import Flask, render_template
from flask_mail import Mail, Message
from instance.config import *

app = Flask(__name__)
app.config.from_object('config')
app.config.from_pyfile('instance/config.py')
mail = Mail(app)
celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

se = SystemSimulator()


@celery.task
def agent_initiate():
    se.register_engine("sname", SIMULATION_MODE)

    a = Crawler(0, Infinite, "Peter", "sname")
    b = Eval(0, Infinite, "Simon", "sname")

    se.get_engine("sname").insert_input_port("report")
    se.get_engine("sname").register_entity(a)
    se.get_engine("sname").register_entity(b)
    se.get_engine("sname").coupling_relation(None, "report", a, "report")
    se.get_engine("sname").coupling_relation(a, "alert", b, "alert")
    se.get_engine("sname").insert_external_event("report", None)
Beispiel #12
0
    file.close()
    for i in range(len(lines)):  
        line = lines[i].split('\n')[0]
        if not line == "": #빈칸이 아닐경우
            elements = (line.split(','))
            for j in elements: #패밀리 안의 멤버=j
                fam.append(eval(j)) #j를 fam추가
            hlist.append(fam) #fam을 hlist에 추가
            fam=[]    
        else:
            blist.append(hlist)
            hlist = []
        if i == len(lines)-1:
            blist.append(hlist)

    se = SystemSimulator()

    se.register_engine("sname", SIMULATION_MODE, TIME_DENSITY)

    c = Clock(0, simulation_time, "clock", "sname")
    se.get_engine("sname").register_entity(c)
    gt = GarbageTruck(0, simulation_time, "garbage_truck", 'sname', GARBAGETRUCK_SIZE, [e for e in enumerate([TRUCK_DELAY for building in blist])],outputlocation)#4.7*13*3
    se.get_engine("sname").register_entity(gt)

    gv = Government(0, simulation_time,"government","sname")
    se.get_engine("sname").register_entity(gv)

    #Building Register

    i=0
    j=0