示例#1
0
def mapInstruction(ent: int, args: List[str], script: scriptComponent.Script,
                   event_store: FilterStore) -> scriptComponent.States:
    payload = MapPayload(ent, args[0])
    new_event = EVENT(MapEventTag, payload)
    event_store.put(new_event)
    script.state = scriptComponent.States.BLOQUED
    script.expecting.append(EndOfPathTag)
    return script.state
def release_driver(env: simpy.Environment, driver: Driver,
                   driver_pool: simpy.FilterStore):
    """
    After a trip is completed the driver is released to the nearest driver pool

    :param env: simpy environment
    :param driver: driver object
    :param driver_pool: nearest driver pool
    """
    if env.now % TIME_UNITS_PER_MIN == 0:
        yield env.timeout(1)
    driver.in_trip = False
    driver_pool.put(driver)
示例#3
0
def goInstruction(ent: int, args: List[str], script: scriptComponent.Script,
                  event_store: FilterStore) -> scriptComponent.States:
    if len(args) == 1:
        payload = GotoPoiPayload(ent, args[0])
        new_event = EVENT(GotoPoiEventTag, payload)
    elif len(args) == 2:
        payload = GotoPosPayload(ent, [float(args[0]), float(args[1])])
        new_event = EVENT(GotoPosEventTag, payload)
    else:
        raise Exception('GO instruction failed. Go <poi> OR Go <x> <y>')
    event_store.put(new_event)
    # Needs to block the script
    script.state = scriptComponent.States.BLOCKED
    script.expecting.append(EndOfPathTag)
    return script.state
示例#4
0
文件: io.py 项目: shenyh17/DESaster
def importSingleFamilyResidenceStock(env, stock_df):
    """Define, populate and return a SimPy FilterStore with SingleFamilyResidential() 
    objects to represent a vacant housing stock.
    
    Keyword Arguments:
    env -- Pointer to SimPy env environment.
    stock_df -- Dataframe with required attributes for each vacant home in
                the stock.
    """
    stock_fs = FilterStore(env)

    for i in stock_df.index:
        stock_fs.put(SingleFamilyResidential(stock_df.loc[i]))

    return stock_fs
示例#5
0
 def __init__(self,env,layer,num,next_ports,isleaf):
     self.layer  = layer
     self.num = num
     self.next_ports = FilterStore(env,capacity=2)
     self.next_ports.items = next_ports
     self.isleaf = isleaf
     if self.isleaf:
         self.end_num = 0
    # every day (i.e. a daily schedule is provided by the user). "Weekly"
    # indicates that the user-defined schedule needs to be repeated every week
    # (i.e. a weekly schedule is provided by the user). Finally, the postpone_interruptions
    # parameter is passed to indicate whether interruptions need to be postponed when they
    # cannot start at the pre-specified time according to the schedule.
    r1 = res_creation(env, 'r1', r1_schedule, "daily", postpone_interruptions)
    r2 = res_creation(env, 'r2', r2_schedule, "daily", postpone_interruptions)
    r3 = res_creation(env, 'r3', r3_schedule, "daily", postpone_interruptions)
    r4 = res_creation(env, 'r4', r4_schedule, "daily", postpone_interruptions)
    r5 = res_creation(env, 'r5', r5_schedule, "daily", postpone_interruptions)
    r6 = res_creation(env, 'r6', r6_schedule, "daily", postpone_interruptions)
    r7 = res_creation(env, 'r7', r7_schedule, "daily", postpone_interruptions)

    # Assignment of resources to activities

    resources_A = FilterStore(env, capacity=1)
    resources_A.items = [r1]
    resources_B = FilterStore(env, capacity=1)
    resources_B.items = [r2, r6]
    resources_C = FilterStore(env, capacity=1)
    resources_C.items = [r3]
    resources_D = FilterStore(env, capacity=1)
    resources_D.items = [r4]
    resources_E = FilterStore(env, capacity=1)
    resources_E.items = [r5, r4]
    resources_F = FilterStore(env, capacity=1)
    resources_F.items = [r6]
    resources_G = FilterStore(env, capacity=1)
    resources_G.items = [r7, r3]

    # Activity specification
def handle_trip(env: simpy.Environment, trip_i: Trip,
                driver_pools: simpy.FilterStore, map_grid: Grid, policy: list,
                trip_gen: TripGenerator):
    """
    The progress of the trip is handled by this function.

    Initially till a driver is found this will cycle through driver pools to find a free driver that accepts the trip.

    Then the trip details will be updated in the 'trip_i' object and the function will timeout for the amount of
    distance between the driver and the rider's pickup location.

    The function will again timeout for the duration of the trip and after completion the driver is released back to the
    driver pool.

    :param env: simpy environment
    :param trip_i: trip object to be handled
    :param driver_pools: the FilterStore where drivers without trips are located
    :param map_grid: grid object
    :param policy: the list of policies the drivers will use
    """
    while not trip_i.driver_found and not trip_i.cancelled:
        logging.debug(f"{trip_i.id} looking for driver at {env.now}")
        try:
            # Search the filterStore for drivers with the same pool_id
            # and that has not been assigned to the trip before.
            with driver_pools.get(
                    lambda d: (d.spot_id in trip_i.nearest_spots) and
                (d.id not in trip_i.rejected_drivers)) as req:
                trip_i.driver = yield req
                trip_i.driver_found = True
                logging.debug(
                    f"{trip_i.id} got {trip_i.driver.id} at {env.now}")

                if trip_i.driver_found:
                    driver: Driver = trip_i.driver

                    pickup_distance = map_grid.get_distance(
                        driver.location, trip_i.pickup_loc)
                    trip_distance = map_grid.get_distance(
                        trip_i.pickup_loc, trip_i.drop_loc)
                    pickup_time = np.round(pickup_distance *
                                           TIME_PER_GRID_UNIT)
                    travel_time = np.round(trip_distance * TIME_PER_GRID_UNIT)

                    # current_location = map_grid.get_location_id(driver.location)
                    # destination = map_grid.get_location_id(trip_i.drop_loc)
                    destination_hex_id = trip_gen.grid.hex_overlay.get_closest_hex(
                        [trip_i.drop_loc[0], trip_i.drop_loc[1]]).id

                    state_dict = get_env_state(env, trip_i, driver, "None",
                                               map_grid)
                    env_state: State = state_dict['state']

                    # Observations array TODO - add idle time until this trip
                    observations = [
                        env_state.pickup_distance, env_state.trip_distance,
                        env_state.day_time, trip_i.drop_loc[0],
                        trip_i.drop_loc[1],
                        max(-1, (driver.weekly_target -
                                 env_state.completed_trip_count))
                    ]

                    # Check whether the driver accepts the trip.
                    action = trip_i.driver.accept_ride(policy, observations)
                    DRIVER_ACTIONS.append([
                        trip_i.id, driver.id, trip_i.created_time, env.now,
                        trip_i.pickup_loc, trip_i.drop_loc, driver.location,
                        pickup_time, travel_time, action[0].numpy()
                    ])
                    # time_step = tf_env.step(action)

                    opportunity_cost = rp.opportunity_cost * driver.opportunity_cost_weight * (
                        env.now - driver.idle_time_begin)

                    if action[0].numpy() == 1:
                        logging.debug(
                            f"{driver.id} traveling to pickup point, {trip_i.pickup_loc} from {driver.location}"
                        )
                        trip_i.update_trip(rp.per_km_cost, rp.unit_reward,
                                           pickup_distance, trip_distance,
                                           env_state.day_time)

                        yield env.timeout(pickup_time)

                        add_reward = driver.start_trip(travel_time,
                                                       trip_i.drop_loc, trip_i)
                        logging.debug(
                            f"Trip distance: {trip_distance}, time {env.now}")

                        # calculate driver reward
                        reward = driver.trip_reward_weight * trip_i.get_net_reward(
                        )
                        if add_reward:
                            reward += driver.reward_amount

                    else:
                        env.process(release_driver(env, driver, driver_pools))
                        trip_i.drop_driver(driver.id, driver.location)
                        reward = 0

                    # Save the (state, action) pair in the driver's history.
                    state_dict['observation'] = observations
                    state_dict['reward'] = reward
                    state_dict['action'] = action
                    driver.state_history.append(state_dict)

        # Handle the interrupt call if the trip doesn't find a driver.
        except simpy.Interrupt as interrupt:
            trip_i.update_search_radius()
            trip_i.nearest_spots = map_grid.get_nearest_spot(
                trip_i.pickup_loc, trip_i.search_radius)
            if interrupt.cause['cancel']:
                trip_i.cancelled = True

    if trip_i.cancelled:
        logging.debug(f"{trip_i.id} was cancelled!")
        return

    yield env.timeout(np.round(trip_distance * TIME_PER_GRID_UNIT))

    # Get the closest driver pool id and release the drive to the pool.
    closest_driver_pool_id = map_grid.get_nearest_spot(trip_i.drop_loc)[0]
    driver.spot_id = closest_driver_pool_id
    driver.idle_time_begin = env.now

    env.process(release_driver(env, driver, driver_pools))
    logging.debug(
        f"{trip_i.id} finished the trip and released driver {driver.id} at {env.now} to pool {closest_driver_pool_id}"
    )
示例#8
0
# Apply for insurance, FEMA IA, and SBA in at the same time
insurance_ia_sba_para = Insurance_IA_SBA_Parallel(env)

# Apply for insurance first, then apply to FEMA IA and SBA at the same time
insurance_firstthen_ia_sba_para = Insurance_FirstThen_IA_SBA_Parallel(env)

# Apply for insurance and SBA in that seqence
insurance_sba_seq = Insurance_SBA_Sequential(env)

# Apply for insurance and SBA at the same time
insurance_sba_para = Insurance_SBA_Parallel(env)

# A policy to simulate government buyout to repair homes 
repair_stock = RepairVacantBuilding(env)

owned_stock = FilterStore(env)  # To put the residences associated with owners
rented_stock = FilterStore(env) # To put the residences associated with renters

forsale_stock = FilterStore(env) # To put the homes associated with vacant home sellers
forrent_stock = FilterStore(env) # To put the homes associated with vacant home landlords

owners = importEntities(env, owners_df, 'OwnerHousehold', owned_stock, write_story)

renters = importEntities(env, renters_df, 'RenterHousehold', rented_stock, write_story)

def basic_process(inspection_program, assessment_program, permit_program, repair_program, entity):
        
    yield env.process(inspection_program.process(entity.property, entity))
    
    yield env.process(assessment_program.process(entity.property, entity))