Exemplo n.º 1
0
def save_graph(G, filepath):
    data = json_graph.node_link_data(G)

    # dump json to a file
    save_results = check_savepath(filepath)
    if save_results:
        with open(filepath, 'w') as outfile:
            json.dump(data, fp=outfile, cls=MyEncoder)
Exemplo n.º 2
0
def results_to_geojson(results_f, geojson_inf, geojson_outf):
    '''
    Results file is merged with the network geojson file based on the init and term ids
    of each link. Saves geojson with merged results.
    
    - results_f = string, path to results text file from solver
    - geojson_inf = string, path to network geojson
    - geojson_outf = string, path save location for results geojson
    '''
    geodf = create_results_df(results_f, geojson_inf)
    save_results = check_savepath(geojson_outf)
    if save_results:
        with open(geojson_outf, 'w') as f:
            f.write(geodf.to_json())
Exemplo n.º 3
0
def save_plot(df, save_path):
    save_results = check_savepath(save_path)
    if save_results:
        matplotlib.style.use('ggplot')
        pp = PdfPages(save_path)
        plt.figure(figsize=(20, 20), dpi=400)
        df.ix[:,'vmt'].plot.bar()
        plt.title('vmt')
        pp.savefig()
        plt.figure(figsize=(20, 20), dpi=400)
        df.ix[:,'vht'].plot.bar()
        plt.title('vht')
        pp.savefig()
        plt.figure(figsize=(20, 20), dpi=400)
        df.ix[:,'delay'].plot.bar()
        plt.title('delay')
        pp.savefig()
        pp.close()
Exemplo n.º 4
0
def df_vmt_vht_delay(df, output_summary, totalODflow = 0, min_speed = 0):
    '''
    df = results dataframe
    totalODflow = total demand (total number of passengers)
    min_speed = force speed to min_speed if link speed < minspeed
    '''
    #TODO updated names?
    df['vmt'] = df['flow'].astype(float)*df['length'].astype(float)/1609.34
    # tt/fftt represents how many times longer the result takes compared to the free flowing time
    # multiply this by the free flowing time to calculate time traveled from results 
    df['travel time'] = df['fftt'].astype(float)*df['tt/fftt'].astype(float)/3600
    
    if float(min_speed) == 0:
        df['vht'] = df['flow'].astype(float)*df['travel time'].astype(float)
        df['delay'] = df['flow'].astype(float)*(df['travel time'].astype(float)-df['fftt'].astype(float)/3600)
        df['speed'] = (df['length'].astype(float)/1609.34)/df['travel time'].astype(float)
    else:
        df['speed'] = (df['length'].astype(float)/1609.34)/df['travel time'].astype(float)
        df['travel time'] = np.where([df['speed'] > float(min_speed)], df['travel time'], df['length'].astype(float)/(1609.34*float(speed_limit)))[0]
        df['vht'] = df['flow'].astype(float)*df['travel time'].astype(float)
        df['delay'] = df['flow'].astype(float)*(df['travel time'].astype(float)-df['fftt'].astype(float)/3600)
        df['speed_new'] = (df['length'].astype(float)/1609.34)/df['travel time'].astype(float)
    totalvmt = np.sum(df['vmt'])
    totalvht = np.sum(df['vht'])
    totaldelay = np.sum(df['delay'])
    #print("VMT: ", totalvmt, "VHT: ", totalvht, "Total Delay: ", totaldelay)
    if totalODflow != 0:
        d = {'vmt': [totalvmt, float(totalvmt/totalODflow)],
             'vht': [totalvht, float(totalvht/totalODflow)],
             'delay': [totaldelay, float(totaldelay/totalODflow)]}
        totaldf = pd.DataFrame(d, index = ['total','per passenger'])
        save_results = check_savepath(output_summary)
        if save_results:
            with open(output_summary,'w') as f:
                f.write(totaldf.to_csv())
        print('totalvmt: ' + str(totalvmt))
        print('totalvht: ' + str(totalvht))
        print('totaldelay: ' + str(totaldelay))
        print('vmt per traveler: ' + str(totalvmt/totalODflow))
        print('vht per traveler: ' + str(totalvht/totalODflow))
        print('delay per traveler: ' + str(totaldelay/totalODflow))
    return df
Exemplo n.º 5
0
def update_capacity(attr_dict, percent_cap, geojson_inf, 
                    geojson_outf, graph_f=None):
    
    '''
    update a network file by changing the capacity according to the fields in attr_dict
    
    - attr_dict = {key: [list of values that will be changed]}
        example: {'county': ['Alameda', 'Berkeley', 'Emeryville']}
    - precent_cap = type decimal, percent of existing capacity roads will now have
    - geojson_in = type str, filepath network geojson file
    - geojson_out = type str, filepath save locations of modified network geojson file
    - graph_f = path of updated networkx or None if don't want to save networkx graph
    
    '''

    links = gpd.read_file(geojson_inf)

    roads_to_update = 1
    for k,v in attr_dict.items():
        # if k == 'type':
        #     v = [r+';' for r in v]
        roads_to_update = roads_to_update & links[k].isin(v)

        
    # Change capacity of city Arterials and save to dataframe
    links['capacity'] = np.where(roads_to_update,
                                 links['capacity']*percent_cap,
                                 links['capacity'])

    save_results = check_savepath(geojson_outf)
    if save_results:
        with open(geojson_outf, 'w') as f:
            f.write(links.to_json())

    if graph_f != None:
        geojson_to_networkx(geojson_outf, graph_f)
Exemplo n.º 6
0
def label_road_network(input_shp, road_network_geojson, attributes, geojson_outf, rename_attributes = None):
    #####################append_city_names#####################
    # read links geojson
    '''
    Generalized function of append_city_names:
    Allows user to specify which attributes to keep from the input shape file. 
    Spatial join shape file with network, so that network file now has identifying labels

    - input_shp: type str, filepath for generalized shapefile for cities, neighborhoods, from any state 
    - road_network_geojson: type str, filepath for input geoJSON network file 
    - attributes: type str OR str array, selected attributes that will be joined
    - geojson_outf: type str, filepath for output file with identifying labels 
    - rename_attributes: type str OR str array, either string or array of strings (should match attributes), can be used if user
      would like to rename the attributes to more user-friendly names

    Example:
    label_road_network('maryland_counties.shp','network.geojson','countyname00','new_network.geojson', 'CountyName')
    '''
    links = gpd.GeoDataFrame.from_file(road_network_geojson)

    # read input shapefile
    shape = gpd.GeoDataFrame.from_file(input_shp)

    # if only one attribute  
    if type(attributes) == str:
        attributes = [attributes]

    # check if column name in input_shp
    for x in attributes:
        if x not in shape.columns:
            raise ValueError("Column name {} is not in input_shp".format(x))

    if len(attributes) != (len(rename_attributes)):
        raise ValueError("Number of attributes different from number of rename attributes.")
    rename_columns = {}
    for i in range(len(attributes)):
        rename_columns.update({attributes[i]:rename_attributes[i]})
    shape = shape.rename(columns = rename_columns)

    # chedk if each attribute is already a property in the road network
    for x in rename_attributes:
        if x in links.columns:
            rejoin = input("Attribute '{}' already in the network geojson, do you want to redo join? (y/n)".format(x))
            if rejoin:
                links = links.drop(x, 1)
            else:
                rename_attributes.remove(x)

    # if there are any files left to join
    if len(rename_attributes) == 0:
        print ("There are no new attributes to join")
        return None
    
    rename_attributes.append('geometry')
    shape = shape[rename_attributes]        


    # spatial join
    links_w_city = sjoin(links, shape, 'left')

    links_w_city = links_w_city.reset_index().drop_duplicates(subset='index').set_index('index')
    links_w_city = links_w_city.drop('index_right',1)
    save_results = check_savepath(geojson_outf)
    if save_results:
        with open(geojson_outf, 'w') as f:
            f.write(links_w_city.to_json())