示例#1
0
def generate_traffic(G, paras_file=None, save_file=None, simple_setup=True, starting_date=[2010, 5, 6, 0, 0, 0],\
    coordinates=True, generate_altitudes=True, put_sectors=False, save_file_capacities=None, 
    record_stats_file=None, remove_flights_after_midnight=False, rectificate=None, storymode=False, **paras_control):
    """
    High level function to create traffic on a given network with given parameters. 
    It is not really intented to use as a simulation by itself, but only to generate 
    some synthetic traffic, mainly for the tactical ABM.
    Returns a set of M1 trajectories.
    If simple_setup is True, the function uses some default parameters suitable for 
    quick generation of traffic.
    
    Parameters
    ----------
    G : hybrid network
        on which to generate the traffic.
    paras_file : string, optional
        path for reading the parameters for the simulations. If None, reads my_paras.py.
    save_file : string
        file for saving trajectories with the abm_tactical format.
    simple_setup : boolean
        if False, all parameters must be informed. Otherwise some default parameters
        are used.
    starting_date : list or tuple of int, optional
        gives the starting date for the simulations. It is used to have the right dates 
        in output.
    coordinates : boolean, optional
        If True, return list of coordinates instead list of labels of navpoints.
    generate_altitudes : boolean, optional
        If True, generate synthetic altitudes in output. The altitudes are bootstrapped 
        using the file_traffic file informed in the paras file.
    put_sectors : boolean, optional
        If True, the trajectories in ouput have a fifth element which is the sector.
    save_file_capacities : string, optional
        If not None, the capacities of the network are written in a txt file in a 
        format readable by the tactical ABM.
    record_stats_file : string, optional
        If informed, the visual output of the funtion is written on the file.
    remove_flights_after_midnight : boolean, optional
        If True, remove from the trajectories all the ones which land the day after 
        starting_date.
    rectificate : dictionary, optional
        If informed, the trajctories will be rectified using the function 
        rectificate_trajectories_network_with_time with parameters given by the dictionary
    storymode : boolean, optional
        set the verbosity of the simulation itself.
    paras_control : additional parameters
        of values which are externally controlled. Typically,
        the number of flights.

    Returns
    -------
    trajectories_coords : list
        of trajectories. Each point in the trajectories has the format (x, y, z, t), (x, y, z, t, s)
        or are directly (label, z, t).
    stats : dictionary
        with some results about the simulation, like the number of flights rejected, etc.

    Notes
    -----
    New in 2.9.4.
    Changed in 2.9.5: Added synthetic altitudes generation.

    """
    
    print ("Generating traffic on network...")

    paras = read_paras(paras_file=paras_file, post_process=False)
    if simple_setup:
        paras['file_net'] = None
        paras['G'] = G
        paras['Nfp'] = G.Nfp # Remark: must match number of pre-computed nav-shortest paths per sec-shortest paths.
        paras['Nsp_nav'] = 2
        paras['unit'] = 15
        paras['days'] = 24.*60.
        paras['file_traffic'] = None  
        paras['ACtot'] = 1000 
        paras['control_density'] = False
        paras['departure_times'] = 'uniform' 
        paras['noise'] = 0.
        paras['nA'] = 1.
        paras['par'] = [[1.,0.,0.001], [1.,0.,1000.]]
        paras['STS'] = None
        paras['N_shocks'] = 0.
        paras['parallel'] = True
        paras['old_style_allocation'] = False
        paras['force'] = True
        paras['capacity_factor'] = True
        paras['bootstrap_mode'] = True
        paras['bootstrap_only_time'] = True

    #print (paras_control)
    for p,v in paras_control.items():
        paras[p] = v

    paras = post_process_paras(paras)

    G = paras['G']
    print ("Average capacity:", np.mean([paras['G'].node[n]['capacity'] for n in paras['G'].nodes()]))
    if 'traffic' in paras.keys():
        print ("Number of flights in traffic:", len(paras['traffic']))

    #print ("Capacities:", {n:G.node[n]['capacity'] for n in G.nodes()})

    with clock_time():
        sim = Simulation(paras, G=G, verbose=True)
        sim.make_simu(storymode=storymode)
        sim.compute_flags()
        queue = post_process_queue(sim.queue)
        M0_queue = post_process_queue(sim.M0_queue)
   
    print

    if record_stats_file!=None:
        ff = open(record_stats_file, 'w')
    else:
        ff = sys.stdout

    stats = {}

    print ('Number of rejected flights:', len([f for f in sim.queue if not f.accepted]), '/', len(sim.queue), file=ff)
    print ('Number of rejected flight plans:', len([fp for f in sim.queue for fp in f.FPs if not fp.accepted]), '/', len(sim.queue)*sim.Nfp, file=ff)
    print ('', file=ff)

    stats['rejected_flights'] = len([f for f in sim.queue if not f.accepted])
    stats['rejected_flight_plans'] = len([fp for f in sim.queue for fp in f.FPs if not fp.accepted])
    stats['flights'] = len(sim.queue)

    print ('Global metrics for M1:', file=ff)
    agg_results = extract_aggregate_values_on_queue(queue, paras['par'])
    for met, res in agg_results.items():
        for ac, met_res in res.items():
            print ('-', met, "for companies of type", ac, ":", met_res, file=ff)
    print ('', file=ff)

    if paras['N_shocks']!=0:
        agg_results = extract_aggregate_values_on_queue(M0_queue, paras['par'])
        for met, res in agg_results.items():
            for ac, met_res in res.items():
                print ('-', met, "for companies of type", ac, ":", met_res, file=ff)

    if record_stats_file!=None:
        ff.close()

    trajectories = compute_M1_trajectories(queue, sim.starting_date)
    #signature at this point: (n), tt

    if rectificate!=None:
        eff_target = rectificate['eff_target']
        del rectificate['eff_target']
        trajectories, eff, G, groups_rec = rectificate_trajectories_network_with_time(trajectories, eff_target, deepcopy(G), **rectificate)
        # signature at this point : (n), tt

    if save_file_capacities!=None:
        write_down_capacities(G, save_file=save_file_capacities)
    
    if coordinates:
        Converter = TrajConverter()
        Converter.set_G(G.G_nav)
        fmt_out = '(x, y, z, t, s)' if put_sectors else '(x, y, z, t)'
        trajectories_coords = Converter.convert(trajectories, fmt_in='(n), t', fmt_out=fmt_out,
                                                      #put_sectors=put_sectors, 
                                                      remove_flights_after_midnight=remove_flights_after_midnight,
                                                      starting_date=starting_date)
        # trajectories_coords = convert_trajectories(G.G_nav, trajectories, put_sectors=put_sectors, 
        #                                                                   remove_flights_after_midnight=remove_flights_after_midnight,
        #                                                                   starting_date=starting_date)
        #signature at this point: (x, y, 0, tt) or (x, y, 0, tt, s)
        if generate_altitudes and paras['file_traffic']!=None: 
            print ("Generating synthetic altitudes...")
            # Insert synthetic altitudes in trajectories based on a sampling of file_traffic
            with silence(True):
                small_sample = G.check_all_real_flights_are_legitimate(paras['traffic'], repair=True)
            print ("Kept", len(small_sample), "flights for sampling altitudes.")
            sample_trajectories = convert_distance_trajectories_coords(G.G_nav, small_sample, put_sectors=put_sectors)
            
            trajectories_coords = insert_altitudes(trajectories_coords, sample_trajectories)
            #signature at this point: (x, y, z, tt) or (x, y, z, tt, s)

            dummy_sector = None if not put_sectors else -1
            trajectories_coords = add_first_last_points(trajectories_coords, dummy_sec=dummy_sector)

        if save_file!=None:
            os.system('mkdir -p '+dirname(save_file))
            write_trajectories_for_tact(trajectories_coords, fil=save_file) 

        return trajectories_coords, stats
    else:
        return trajectories, stats
示例#2
0
        return trajectories, stats

if __name__=='__main__': 
    """
    ===========================================================================
    Manual single simulation
    ===========================================================================
    """
    paras_file = None if len(sys.argv)==1 else sys.argv[1]
    paras = read_paras(paras_file=paras_file)

    GG = paras['G'] #ABMvars.G

    print (header(paras,'SimulationO', version, paras_to_display=['ACtot']))

    with clock_time():
        sim = Simulation(paras, G=GG, verbose=True)
        sim.make_simu(storymode=False)
        sim.compute_flags()
        queue = post_process_queue(sim.queue)
        M0_queue = post_process_queue(sim.M0_queue)

    """
    ===========================================================================
    Some snippets to view the results.
    ===========================================================================
    """
    if 0:
        for n in sim.G.nodes():
            #print n, sim.G.node[n]['capacity'], sim.G.node[n]['load']
            if max(sim.G.node[n]['load']) == sim.G.node[n]['capacity']: