示例#1
0
def job(place):
    try:
        s = abm.Sim(sim=sim, place=place)

        if s.load_agents():
            s.load_agent_meta()
            s.init_scenario(scenario=scenario)
            print s.agents_file()
            sys.stdout.flush()
            s.load_result_meta()

            detail = []
            for d in s.DX_destin.keys():
                detail.append({
                    "type": "Feature",
                    "properties": {
                        "name": place,
                        "destin": d,
                        'pop': s.n_destin[d],
                        'D10%': np.percentile(s.DX_destin[d], 10),
                        'D50%': np.percentile(s.DX_destin[d], 50),
                        'D90%': np.percentile(s.DX_destin[d], 90),
                        'T10%': np.percentile(s.T_destin[d], 10),
                        'T50%': np.percentile(s.T_destin[d], 50),
                        'T90%': np.percentile(s.T_destin[d], 90),
                    },
                    "geometry": mapping(Point(s.h.nodes[d]))
                })
            overview = [{
                "type": "Feature",
                "properties": {
                    "name": place,
                    "pop": s.n,
                    "no_of_destins": len(s.DX_destin.keys()),
                    "video": s.video_file(),
                    'D10%': np.percentile(s.DX, 10),
                    'D50%': np.percentile(s.DX, 50),
                    'D90%': np.percentile(s.DX, 90),
                    'T10%': np.percentile(s.T, 10),
                    'T50%': np.percentile(s.T, 50),
                    'T90%': np.percentile(s.T, 90),
                },
                "geometry": mapping(s.h.boundary)
            }]
            print overview
            print detail
        else:
            raise ValueError(
                'Output files cannot be initialised for some reason (e.g. no destinations available).'
            )
        return overview, detail
    except KeyboardInterrupt:
        print 'KeyboardInterrupt caught in child...'
    except (ValueError, AttributeError, NameError, IOError) as e:
        print e
        print '{}: {}'.format(place, e)
        logging.critical(place)
        logging.exception(e)
示例#2
0
def do_calculations(city):
    '''
    Multiprocessing runs this subroutine for each city in parallel

    Parameters
    ----------

    city : string
        A string that describes name of city boundary in OSM.

    Returns
    -------

    return_code: integer
        A number that signifies the outcome of the simulation.
            0: One of (ValueError, AttributeError, NameError, IOError)
            1: Successful
            2: Already done
    '''

    # Number of completed scenarios for this city in this run
    return_code = 0
    scenario = 'undefined'

    try:
        simulation = abm.Sim(sim=sim,city=city,p_factor=cities.p_factor,n=None,destins=None,fresh_place=False)

        # Iterate through the scenarios
        for scenario in simulation.scenarios:
            simulation.init_scenario(scenario=scenario)

            # If the results cannot be loaded, run simulation
            if not simulation.load_results():
                simulation.run_sim(fps=20,bitrate=4000,video=True,live_video=False)
            else:
                print '{0}[{1}]: This scenario has already been simulated with the given parameters!'.format(city, scenario)
                sys.stdout.flush()

            return_code += 1

        return return_code
    except KeyboardInterrupt:
        print 'KeyboardInterrupt caught in child...'
        return
    except Exception as e:
        logging.critical(city)
        logging.exception(e)
        print '{0}[{1}]: {2}'.format(city,scenario,e)
        print '----------------------------------------------------------------------'
        print 'Following has been logged to [{0}]'.format(logfile)
        print '----------------------------------------------------------------------'
        print traceback.format_exc()
        print '----------------------------------------------------------------------'
        return return_code
示例#3
0
import sys

sys.path.append('core')
import abm
import db

reload(abm)
reload(db)

from matplotlib import pyplot as plt
import numpy as np
import pickle
import os

s = abm.Sim('bristol25', 'City of Bristol')
s.h.init_destins()
s.h.init_route()

s.scenario = 'k5-original'

s.h.init_SG(subgraph='nearest')

# -----------------------------------------

# reading N from tstep folder

# Copy and paste from here
tstep = 0

# Number of bins for that particular destin
示例#4
0
]

# self = abm.Sim('flood','Carlisle')
p = db.Population((-2.960970689433074, 54.88321937312177, -2.8861928154524805,
                   54.91133135582124))

destin_type = {'invdistprob': True, 'nearest': False}

combinations = {
    ('invdistprob', 'ia'): 'k5-idp',
    ('invdistprob', 'ff'): 'ff-idp',
    ('nearest', 'ia'): 'k5',
    ('nearest', 'ff'): 'ff',
}

sim = abm.Sim('flood', 'Carlisle')
sim.n = int(round(sum(p.pop)))
sim.scenarios = combinations.values()

sim.h.destins = []
for k, v in enumerate(ec):
    ec[k]['nearest_node'] = sim.h.nearest_node(*v['approx_coord'])
    sim.h.destins.append(ec[k]['nearest_node'])

nodes_not_in_bbox = set(sim.h.G.nodes()).difference(nodes_in_bbox)

for u, v, d in sim.h.G.edges_iter(nodes_not_in_bbox, data=True):
    d['pop_dist'] = 0

# sim.fresh=True
sim.run_by_agent(rerun=False)
reload(abm)
reload(db)

import logging
from collections import OrderedDict

sim = 'bristol50'

logging.basicConfig(filename='logs/{0}.log'.format(sim), level=logging.DEBUG)

places = abm.Places(sim).names

description = {'ff': 'Normal Scenario', 'ia': 'Evacuation Scenario'}

city = 'City of Bristol'
self = abm.Sim(sim, city)


# Save each exit to a different file
def do_calculations(city):
    try:
        return_code = 1
        # self = abm.Sim(sim,city)
        content = OrderedDict()
        t90 = {}

        for scenario in ['ff', 'ia']:
            self.scenarios = [scenario]
            self.run()
            content['Video: {0}'.format(
                description[scenario])] = '{0}.mp4'.format(self.df_agents_file)
示例#6
0
import sys
sys.path.append('core')
import abm, db
reload(abm)
reload(db)

# self = abm.Sim('flood','Carlisle')
self = abm.Sim('test_abm_buffer',(-2.88612967859241, 54.91133135582125, -2.9609706894330743, 54.88327220183169))
self.n = 10000
self.use_buffer = True
self.run_by_agent()
示例#7
0
import sys
sys.path.append('core')
import abm, db
reload(abm)
reload(db)

sim = abm.Sim('abm_test', 'City of London')
sim.scenarios = ['k5']
sim.n = 1000
sim.run_by_agent(verbose=False)

# Generate video
import matplotlib.pyplot as plt
plt.close('all')
sim.init_scenario('k5')
sim.load_events()
v = abm.Viewer(sim, video=True)
v.path(which='speed')
示例#8
0
import sys

sys.path.append('core')

import abm
import db

reload(abm)
reload(db)
# s=abm_new.Sim('flood','Carlisle')
s = abm.Sim('flood', (-2.88612967859241, 54.91133135582125,
                      -2.9609706894330743, 54.88327220183169))
s.scenarios = ['ia']
s.n = 100000
s.run_sim()
示例#9
0
import abm
reload(abm)
import db
reload(db)
s = abm.Sim('test', 'City of Bristol')
s.n = 500000
properties = s.load_agent_times()
fname = '{0}/time.json'.format(s.agents_file())
s.h.geojson_edges(fname, properties)