Пример #1
0
def get_type(coordinates_conv_dict, start_end_ids_dict,  other, base, link_id):
    _a_ = start_end_ids_dict[link_id][0]
    _b_ = start_end_ids_dict[link_id][1]
    _len_ = start_end_ids_dict[link_id][2]
    print "{0}:{1}->{2}".format(link_id, _a_, _b_)
    # if any of these nodes are not in the list, just ouput
    if _a_ not in coordinates_conv_dict or _b_ not in coordinates_conv_dict:
        #route_not_found_or_not_identified_dict[link_id] = _len_
        return _len_, np.nan, 1  # one or more of the nodes not in base network
    if _len_ < 2 * buffer_dist / 5280:  # if the links are comparable in size to the buffer distance
        #miniature_links_dict[link_id] = _len_
        return _len_, np.nan, 4  # length of the link is too small compared to buffer
    # prepare ND
    # use the key to buffer/clip/create ND
    #network_dataset_ND = "in_memory/ND1"
    other_f = "other_f"
    arcpy.MakeFeatureLayer_management(other, other_f)
    no_tolerance_buffer_dist = "1000 feet"
    where_clause = """ "_ID_" = %d""" % link_id
    arcpy.SelectLayerByAttribute_management(other_f, "NEW_SELECTION", where_clause)
    arcpy.Buffer_analysis(other_f, buffer_shp, no_tolerance_buffer_dist)
    arcpy.Clip_analysis(base, buffer_shp, network_dataset)
    #arcpy.na.CreateNetworkDataset("in_memory_n1", network_dataset_ND, "", "NO_ELEVATION" )
    arcpy.BuildNetwork_na(network_dataset_ND)
    (a_list, b_list) = (coordinates_conv_dict[_a_], coordinates_conv_dict[_b_])
    minimum_distance = get_route_distance(a_list, b_list, network_dataset_ND)
    if minimum_distance == 99999:  # any route not found in the buffer layer
        minimum_distance = get_route_distance(a_list, b_list, all_dataset_ND)
        if minimum_distance == 99999:
            #route_not_found_or_not_identified_dict[link_id] = _len_
            return _len_, np.nan, 1  # nodes mapped but route not found in base network
        else:
            #route_found_within_network_dict[link_id] = [minimum_distance, _len_]
            return _len_, minimum_distance, 2  # route not found within buffer
    else:
        #route_found_within_buffer_dict[link_id] = [minimum_distance, _len_]
        return _len_, minimum_distance, 3  # routes found within buffer
Пример #2
0
SnappedNodes = 'M:/RAIL/OngoingWork/newconnections/railway_ln/allnodes_Snapped_rail2'

newoldnodesconversion = 'M:/RAIL/OngoingWork/new_old_node_conversion.csv'

o = "C:\\GIS\\o.shp"  #temporary files
d = "C:\\GIS\\d.shp"
m = "C:\\GIS\\m.shp"
temp = "C:\\GIS\\teemp.shp"
temp1 = "C:\\GIS\\teemp1.shp"
temp2 = "C:\\GIS\\teemp2.shp"

B1_ND = "M:/RAIL/OngoingWork/newconnections/railway_ln/Rail2_ND.nd"
feature = "M:/RAIL/OngoingWork/newconnections/intermediate/feature_unlocked.shp"  #i guess this is just a temporary layer/ no worries

arcpy.CheckOutExtension("Network")
arcpy.BuildNetwork_na(B1_ND)  #because the Rail2_ND file may have been changed
print("Network Rebuilt")
arcpy.MakeRouteLayer_na(B1_ND, "Route", "Length")

allnodes = Dbf5(all_nodes + '.dbf').to_dataframe()
Links_Final2 = Dbf5(linksfinal + '.dbf').to_dataframe()


#creates a dictionary of two columns
def get_dictionary(columnA, columnB, dataframe_name):
    dict = {}
    for i in range(len(Links_Final2)):
        dict[dataframe_name[columnA][i]] = []
        dict[dataframe_name[columnB][i]] = []
    for i in range(len(dataframe_name)):
        dict[dataframe_name[columnA][i]].append(dataframe_name[columnB][i])
Пример #3
0
                                 (currentSpeed))

        # Change Expo speed, recalculate fields
        arcpy.CalculateField_management("ExpoLine_split", "avgspd",
                                        "%d" % (currentSpeed), "PYTHON", "#")
        arcpy.CalculateField_management("ExpoLine_split", "Cost",
                                        "[TotalLengt]*21.46/ [avgspd]", "VB",
                                        "#")
        arcpy.CalculateField_management("ExpoLine_split", "DPS",
                                        "[TotalLengt]/ [avgspd]", "VB", "#")
        arcpy.AddMessage(
            "Expo speed changed to %d, cost and DPS recalculated.  Rebuilding ND."
            % (currentSpeed))

        # Rebuild Network
        arcpy.BuildNetwork_na(inND)
        arcpy.AddMessage("ND Rebuild completed")
        time.sleep(loopTime)

        # Add lcoations
        inOrigins = fcTAZ
        inDestinations = fcTAZ
        ##        arcpy.AddLocations_na(inOD, "Origins", inOrigins,
        ##                              "Name ID_TAZ12A #;SourceID SourceID #;SourceOID SourceOID #;PosAlong PosAlong #;SideOfEdge SideOfEdge #", append = "CLEAR")
        ##        arcpy.AddLocations_na(inOD, "Destinations", inDestinations,
        ##                              "Name ID_TAZ12A #;SourceID SourceID #;SourceOID SourceOID #;PosAlong PosAlong #;SideOfEdge SideOfEdge #", append = "CLEAR")
        #Add using geometries instead.  Should only add 2 min per iteration or 40 min overall
        arcpy.AddLocations_na(inOD,
                              "Origins",
                              inOrigins,
                              "Name ID_TAZ12A #",
Пример #4
0
old_n = old_nodes_shp
new_n = new_nodes_shp
old_l = old_links_shp
new_l = new_links_clipped
old_ns = snapped_old_nodes
new_ngt = "../../RAIL11/RAIL/gis/allnodes.shp"
empty = "C:/gis/empty.shp"
empty_memory = "in_memory/e1"
memory_1 = "in_memory/m1"
memory_2 = "in_memory/m2"

arcpy.CopyFeatures_management(empty, empty_memory)

arcpy.env.overwriteOutput = True  # overwrite files if its already present
arcpy.CheckOutExtension("Network")
arcpy.BuildNetwork_na(B1_ND)
arcpy.MakeRouteLayer_na(B1_ND, B1_route, "Length")
arcpy.MakeFeatureLayer_management(new_l, "newlf")


# how far is the nearest node (old network)
def get_near_node_dict(nodelayer):
    arcpy.Project_management(nodelayer, temp1, arcpy.SpatialReference(102039))
    fid_id_dict = {
        row.getValue("FID"): row.getValue("_ID_")
        for row in arcpy.SearchCursor(temp1)
    }
    arcpy.Near_analysis(temp1, temp1)
    near_node_dict = {
        row.getValue("_ID_"):
        [row.getValue("NEAR_Fid"),
Пример #5
0
# Input: Specify a value for Impedance Cutoff (maximum distance from a facility for which a voter will be assigned)
cutoff = str(arcpy.GetParameterAsText(3))

# Input: Facilities point FC to be added as Facilities (potential polling places)
polling_facilities = str(arcpy.GetParameterAsText(4))

# Input: Voters point FC to be added as Demand Points (subset of given percentage of voter points)
Voters = arcpy.GetParameterAsText(5)

Solve_Succeeded = "true"


# Run Processes...

# Process: Build Network
arcpy.BuildNetwork_na(Network)

# Process: Make Location-Allocation Layer
LAlayer = arcpy.MakeLocationAllocationLayer_na(Network, str(AnalysisLayer), "Length", "DEMAND_TO_FACILITY",
    "MINIMIZE_FACILITIES", "1", cutoff, "LINEAR", "1", "10", "", "ALLOW_UTURNS", "", "NO_HIERARCHY",
    "STRAIGHT_LINES", "1", "")

# Process: Add Locations: Facilities (Potential Polling Places)
arcpy.AddLocations_na(LAlayer, "Facilities", polling_facilities,
    "Name Name #;Capacity Capacity #", "1000 Feet", "NAME",
    "street_network SHAPE", "MATCH_TO_CLOSEST", "APPEND", "SNAP", "", "INCLUDE", "#")

# Process: Add Locations: Demand Points (Voters)
arcpy.AddLocations_na(LAlayer, "Demand Points", Voters, "", "1000 Feet", "",
    "street_network SHAPE", "MATCH_TO_CLOSEST", "APPEND", "SNAP", "", "INCLUDE", "#")
Пример #6
0
def solve_network(config_json):
    # This function creates a network dataset from a template,
    # builds the network, adds the nearest station points as stops,
    # and solves for the least-cost route

    # check network analyst license
    arcpy.CheckOutExtension("network")
    print('Network Analyst License Confirmed!')

    # set directory and path for network geodatabase
    config_data = read_config_json(config_json)
    project_dir = config_data['directories']['project_dir']
    save_dir = config_data['directories']['save_dir']
    direction_save_name = config_data['filenames']['direction_save_name']
    gdb_dir = project_dir + r'/Data'
    gdb_name = r'Bikeshare_GDB'
    gdb_path = gdb_dir + r'/' + gdb_name + r'.gdb'
    feature_dataset_name = 'Bikeshare'
    gdb_feature_path = gdb_path + r'/' + feature_dataset_name

    # set arcpy workspace
    arcpy.env.workspace = gdb_path

    # create network dataset from template
    arcpy.CreateNetworkDatasetFromTemplate_na(
        (project_dir + r'/Bikeshare_ND_template.xml'),      # network dataset template location
        gdb_feature_path                                    # feature dataset for network
    )

    # build network dataset
    arcpy.BuildNetwork_na(gdb_feature_path + r'/Bikeshare_ND')

    # create layer for least-cost route analysis
    arcpy.MakeRouteLayer_na(
        "Bikeshare_ND",             # input network dataset
        "Route",                    # output route analysis layer
        "Time",                     # impedance attribute
    )

    # add nearest station routing points
    arcpy.AddLocations_na(
        "Route",                    # input route analysis layer
        "Stops",                    # "Stops" analysis sub-layer
        "Bike_Stations_Intersect",  # input features table
        "Name Name #",              # field mapping
        "5000 Meters",              # search tolerance
        "ORIG_FID",                 # sort field
    )

    # solve the routing problem
    arcpy.Solve_na(
        "Route",                    # input route analysis layer
    )

    # export bike route as feature
    arcpy.FeatureClassToGeodatabase_conversion(
        r"Route\Routes",
        gdb_feature_path
    )

    print('Network Route Complete!')

    # export route directions
    arcpy.Directions_na(
        "Route",                                            # input route analysis layer
        "TEXT",                                             # export format
        (save_dir + r'/' + direction_save_name + r'.txt'),  # export path
        "Meters",                                           # distance units
        "REPORT_TIME",                                      # write travel time
        "Minutes"                                           # travel time units
    )
    print('Route Directions Exported!')
Пример #7
0
def test_network_routing(the_scenario, logger):

    # already called aftot_setup.setup() to initialize and clean up :
    # - starting with populate network template with modes and intermodal.
    # no other facilities yet (e.g. raw material producers or destinations).

    # Setup Facilities for the Test
    # i.   - append facilities to the network dataset template
    # ii.  - hook the facilities with artificial links
    # --------------------------------------------------------

    ftot_facilities.raw_material_producers_setup(the_scenario, logger)
    ftot_facilities.ultimate_destinations_setup(the_scenario, logger)
    ftot_facilities.hook_facilities_into_network(
        the_scenario, logger, False)  # false means pipeline doesn't get used

    #   assign baseline costs to the network
    ftot_supporting_gis.assign_network_costs(
        the_scenario, logger, False,
        None)  # false means pipeline doesn't get used

    # delete the route cache from the previous test
    delete_routes_cache_db(logger, the_scenario)

    # test 0 : baseline as is.
    # ---------------------------
    logger.info("START TEST 0: baseline as is")
    temp_start_time = datetime.datetime.now()

    # reset artificial link costs to what they should be
    logger.info("reset_flow_restrictions to what they should be")
    reset_artificial_link_flow_restrictions(logger, the_scenario)

    # - build the network template
    ftot_supporting_gis.build_the_network(the_scenario, logger)

    # - route as is
    ftot_routing.initial_routing(the_scenario, logger)

    # output route information and maps
    # -----------------------------------
    # some sort of test or diagnostics. what is the baseline?
    # report out the following from the main.db:
    # GENERAL - number of routes, avg. cost, total cost,
    get_main_db_route_info(the_scenario, logger)

    # report out from the routes_cahce.db
    get_route_cache_db_route_info(the_scenario, logger)

    logger.info("TODO: output route information and maps")

    temp_end_time = datetime.datetime.now()
    temp_total_time = temp_end_time - temp_start_time
    logger.result("END TEST 0: baseline as is. Total time: {:.10}".format(
        temp_total_time))

    # todo - mnp - 06152015 -- test 1 runs fine, but test 2 fails at "start: delete_temp_gdbs".
    # this test has 4 messages: No routing solution found -- the other methods have 2. ???
    # WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'C:\\FTOT\\branches\\2017_06_15_V3_SP1\\Scenarios\\prototype_testing\\proto1\\test5_ASCENT_a2j\\temp_route_gdbs\\tmp_route_solve_batch_0.gdb\\a00000009.gdbtable'
    #    # test 1 : no available modes - all artificial links cost -1
    #    # ----------------------------------------------------------
    #    logger.info("START TEST 1: no available modes - all artificial links cost -1")
    #    temp_start_time = datetime.datetime.now()
    #
    #    # delete the route cache from the previous test
    #    delete_routes_cache_db(logger, the_scenario)
    #
    #    # set artificial link costs to -1
    #    logger.info("set_flow_restrictions for all aritificial links to -1")
    #    ftot_supporting_gis.set_flow_restrictions(logger, the_scenario, "no_modes")
    #
    #    # build the network inline since the only thing that changed is network artificial link costs
    #    logger.info("Building the network again with new impedences")
    #    arcpy.BuildNetwork_na(os.path.join(the_scenario.main_gdb, "Network/Network_ND"))
    #
    #    # do the routing
    #    logger.info("Do the routing again.")
    #    try:
    #        ftot_routing.initial_routing(the_scenario, logger)
    #        logger.error("FAIL: the routing should have failed, but didn't. check your artificial links.")
    #    except:
    #        logger.result("PASS: the routing failed as expected because there are no valid routes.")
    #
    #    #TODO - need to deeper check to make sure that if the scenario solves a valid route
    #    get_main_db_route_info(the_scenario, logger)
    #    temp_end_time = datetime.datetime.now()
    #    temp_total_time = temp_end_time - temp_start_time
    #    logger.result("END TEST 1: no modes. Total time: {:.10}".format(temp_total_time))

    #
    # test 2 : only available mode: road  - all other artificial links cost -1
    # ----------------------------------------------------------
    logger.info(
        "START TEST 2 : only available mode: road  - all other artificial links cost -1"
    )
    temp_start_time = datetime.datetime.now()

    # delete the route cache from the previous test
    delete_routes_cache_db(logger, the_scenario)

    # reset artificial link costs to what they should be
    logger.info("reset_flow_restrictions to what they should be")
    reset_artificial_link_flow_restrictions(logger, the_scenario)

    # set artificial link costs to -1 for everything but road
    logger.info("set flow restrictions on rail, water, pipeline")
    for mode in ['rail', 'water', 'pipeline']:
        ftot_supporting_gis.set_flow_restrictions(logger, the_scenario,
                                                  "no_modes", mode)

    # build the network inline since the only thing that changed is network artificial link costs
    logger.info("Building the network again with new impedences")
    arcpy.BuildNetwork_na(
        os.path.join(the_scenario.main_gdb, "Network/Network_ND"))

    # do the routing
    logger.info("Do the routing again.")
    ftot_routing.initial_routing(the_scenario, logger)

    get_main_db_route_info(the_scenario, logger)
    get_route_cache_db_route_info(the_scenario, logger)

    temp_end_time = datetime.datetime.now()
    temp_total_time = temp_end_time - temp_start_time
    logger.result(
        "END TEST 2: road only. Total time: {:.10}".format(temp_total_time))

    # test 3: only available mode: rail  - all other artificial links cost -1
    # ----------------------------------------------------------
    logger.info(
        "START TEST 3 : only available mode: rail - all other artificial links cost -1"
    )
    temp_start_time = datetime.datetime.now()

    # delete the route cache from the previous test
    delete_routes_cache_db(logger, the_scenario)

    # reset artificial link costs to what they should be
    logger.info("reset_flow_restrictions to what they should be")
    reset_artificial_link_flow_restrictions(logger, the_scenario)

    # set artificial link costs to -1 for everything but road
    logger.info("set flow restrictions on road, water, pipeline")
    for mode in ['road', 'water', 'pipeline']:
        ftot_supporting_gis.set_flow_restrictions(logger, the_scenario,
                                                  "no_modes", mode)

    # build the network inline since the only thing that changed is network artificial link costs
    logger.info("Building the network again with new impedences")
    arcpy.BuildNetwork_na(
        os.path.join(the_scenario.main_gdb, "Network/Network_ND"))

    # do the routing
    logger.info("Do the routing again.")
    ftot_routing.initial_routing(the_scenario, logger)

    get_main_db_route_info(the_scenario, logger)
    get_route_cache_db_route_info(the_scenario, logger)

    temp_end_time = datetime.datetime.now()
    temp_total_time = temp_end_time - temp_start_time
    logger.result(
        "END TEST 3: rail only. Total time: {:.10}".format(temp_total_time))

    # test 4: only available mode: water - all other artificial links cost -1
    # ----------------------------------------------------------
    logger.info(
        "START TEST 4 : only available mode: water- all other artificial links cost -1"
    )
    temp_start_time = datetime.datetime.now()

    # delete the route cache from the previous test
    delete_routes_cache_db(logger, the_scenario)

    # reset artificial link costs to what they should be
    logger.info("reset_flow_restrictions to what they should be")
    reset_artificial_link_flow_restrictions(logger, the_scenario)

    # set artificial link costs to -1 for everything but road
    logger.info("set flow restrictions on road, water, pipeline")
    for mode in ['road', 'rail', 'pipeline']:
        ftot_supporting_gis.set_flow_restrictions(logger, the_scenario,
                                                  "no_modes", mode)

    # build the network inline since the only thing that changed is network artificial link costs
    logger.info("Building the network again with new impedences")
    arcpy.BuildNetwork_na(
        os.path.join(the_scenario.main_gdb, "Network/Network_ND"))

    # do the routing
    logger.info("Do the routing again.")
    try:
        ftot_routing.initial_routing(the_scenario, logger)
    except:
        logger.warning(
            "WARNING: the routing has no valid routes on the water mode.")
        logger.result(
            "WARNING: the routing has no valid routes on the water mode.")

    #TODO - need to deeper check to make sure that if the scenario solves a valid route
    get_main_db_route_info(the_scenario, logger)
    get_route_cache_db_route_info(the_scenario, logger)

    temp_end_time = datetime.datetime.now()
    temp_total_time = temp_end_time - temp_start_time
    logger.result(
        "END TEST 4: water only. Total time: {:.10}".format(temp_total_time))

    # test 5: only available mode: pipeline - all other artificial links cost -1
    # --------------------------------------------------------------------------
    # todo - mnp - 06152017 - this will fail if pipeline is not connected in the setup phase.
    logger.info(
        "START TEST 5 : only available mode: pipeline - all other artificial links cost -1"
    )
    temp_start_time = datetime.datetime.now()

    # delete the route cache from the previous test
    delete_routes_cache_db(logger, the_scenario)

    # reset artificial link costs to what they should be
    logger.info("reset_flow_restrictions to what they should be")
    reset_artificial_link_flow_restrictions(logger, the_scenario)

    # set artificial link costs to -1 for everything but road
    logger.info("set flow restrictions on road, water, pipeline")
    for mode in ['road', 'rail', 'water']:
        ftot_supporting_gis.set_flow_restrictions(logger, the_scenario,
                                                  "no_modes", mode)

    # build the network inline since the only thing that changed is network artificial link costs
    logger.info("Building the network again with new impedences")
    arcpy.BuildNetwork_na(
        os.path.join(the_scenario.main_gdb, "Network/Network_ND"))

    # do the routing
    logger.info("Do the routing again.")
    try:
        ftot_routing.initial_routing(the_scenario, logger)
    except:
        logger.warning(
            "WARNING: the routing has no valid routes on the pipeline mode.")
        logger.result(
            "WARNING: the routing has no valid routes on the pipeline mode.")

    get_main_db_route_info(the_scenario, logger)
    get_route_cache_db_route_info(the_scenario, logger)

    temp_end_time = datetime.datetime.now()
    temp_total_time = temp_end_time - temp_start_time
    logger.result("END TEST 5: pipeline only. Total time: {:.10}".format(
        temp_total_time))
def calculateNetworkServiceArea(inFacilities, roads, workspace):
    #allow overwrite table on
    arcpy.env.overwriteOutput = True    
    #set new workspace as the input workspace
    arcpy.env.workspace = workspace 
    #check that the projections of feature classes align
    spatial_ref1 = arcpy.Describe(inFacilities).spatialReference
    spatial_ref2 = arcpy.Describe(roads).spatialReference
    if spatial_ref1.name != spatial_ref2.name:
        print(inFacilities + " needs to be projected as " + roads + " to match the coordinate system of the clip feature class.")
        print(inFacilities + " is projected as " + spatial_ref1.name + " and " + roads + " is projected as " + spatial_ref2.name)
    else:
        print("The coordinate systems for both layers match.")    
    #check that the feature classes are the correct type
    #roads should be polyline shapefile
    #facilties (schools) should be a point file
    #use try to identify errors in the types of data  
    try:
        #use the describe function to determine the element data type
        desc_inFacilities = arcpy.Describe(inFacilities)
        desc_roads = arcpy.Describe(roads)
        if desc_inFacilities.shapeType != "Point":
            print("Error shapeType: ", inFacilities, "needs to be a point type!")
            sys.exit(1)
        if desc_roads.shapeType != "Polyline":
            print("Error shapeType: ", roads, "needs to be a polyline type!")
            sys.exit(1)     
        #define folder pathway
        folder = workspace
        #create geodatabase name
        out_name = "myGeodatabase.gdb"
        #Create a geodatabase using arcpy 
        arcpy.CreateFileGDB_management(folder, out_name)
        #pass input shapefiles into feature class in geodatabase
        inFeatures = inFacilities
        inFeatures2 = roads
        outLocation = "myGeodatabase.gdb"
        outLocation2 = "myGeodatabase.gdb"
        outFeatureClass = "inFacilities"
        outFeatureClass2 = "roads"
        #pass input facitilies into geodatabase
        arcpy.FeatureClassToFeatureClass_conversion(inFeatures, outLocation, 
                                            outFeatureClass)
        #pass input roads into geodatabase
        arcpy.FeatureClassToFeatureClass_conversion(inFeatures2, outLocation2, 
                                            outFeatureClass2)
        #test for existence of the geodatabse
        if arcpy.Exists(myGeodatabase):
            #set workspace to user input geodatabase
            arcpy.env.workspace = myGeodatabase
            print("Environment workspace is set to: ", myGeodatabase)
        else:
            print("Workspace", myGeodatabase, "does not exist!")
            sys.exit(1)  
        #set variable for the road network
        roads_shp = folder + roads
        #describe the road shapefile 
        desc = arcpy.Describe(roads_shp)
        #check to make sure that network analysis extension is enabled
        arcpy.CheckOutExtension("network")
        #create new featuredataset
        arcpy.CreateFeatureDataset_management(arcpy.env.workspace, "featuredataset", desc.spatialReference)
        #copy features to the new dataset
        arcpy.CopyFeatures_management(roads_shp, "featuredataset/roads")
        #create network dataset in an exisiting feature dataset 
        arcpy.na.CreateNetworkDataset("featuredataset", "roads_ND", ["roads"])
        #constructs the network connectivity and also attribute information of a network dataset
        arcpy.BuildNetwork_na("featuredataset/roads_ND")
        #use make serivce area layer
        #define variables
        network = os.path.join(myGeodatabase, "inFacilities", "roads_ND")
        layer_name = "schoolRoadNetwork"
        impedance = "distanceAway"
        #set variables for 600, 1200, and 1800 meters
        #generate polygons as rings
        #use this function to set analysis properties of the netwrok service area and determine accessibility to schools based on roads
        result_object = arcpy.na.MakeServiceAreaLayer(network, layer_name,
                                    impedance, "TRAVEL_FROM", "200 400 600 800 1000 1200 1400 1600 1800 2000",
                                    "DETAILED_POLYS", "MERGE", "RINGS")
    Reader.updateRow(row)
    del row
del Reader
###########################
arcpy.SetProgressorPosition(90)
#Poistetaan tiedostosta turhat kentät:
arcpy.DeleteField_management(
    LiikenneElementit,
    "JuncType;JuncType2;JuncType3;JuncType4;JuncType5;DynTyyppi")

msg("Aikasakot laskettu!")
arcpy.SetProgressorPosition(95)
Valmis()
msg("----------------------")
msg("Build Network Dataset")
arcpy.SetProgressorLabel("AIKASAKKOJEN LASKENTA...Build Network Dataset...")
Aloitus()
#Buildataan NetworkDataset uudestaan, jolloin se on heti valmis käytettäväksi:
arcpy.BuildNetwork_na(NetworkData)
Valmis()
arcpy.SetProgressorPosition(100)

msg("----------------------")
msg("VALMIS! Nyt käyttämääsi Network Datasettiin on laskettu todenmukaisemmat läpiajoajat sarakkeisiin: Kokopva_aa, Keskpva_aa sekä Ruuhka_aa."
    )
msg("Network Dataset on nyt valmis käytettäväksi reititysanalyyseihin.")
msg("Halutessasi voit suorittaa 4. työvaiheen, jossa otetaan matka-ajan lisäksi huomioon kävelyyn sekä parkkipaikan etsintään kuluva aika (Kokonaismatkaketju)."
    )
msg("----------------------")
def calculateNetworkServiceArea(inFacilities, roads, workspace):
    import arcpy
    import sys

    arcpy.env.overwriteOutput = True

    try:
        ##Create new gdb
        arcpy.CreateFileGDB_management(workspace, 'serviceArea.gdb')
        arcpy.env.workspace = 'serviceArea.gdb'
    except:
        raise NameError('Input workspace does not exist!')
    try:
        arcpy.CheckOutExtension("network")
    except:
        print("Network Analyst Extension not available")

    ## Check input feature class spatial reference
    roads_desc = arcpy.Describe(roads)
    roads_desc_name = roads_desc.spatialReference.name
    facilities_desc = arcpy.Describe(inFacilities)
    facilities_desc_name = facilities_desc.spatialReference.name

    if roads_desc.shapeType != 'Polyline':
        raise TypeError('Roads must be a Polyline!')

    if facilities_desc.shapeType != 'Point':
        raise TypeError('Facilities must be a Point!')

    if roads_desc_name != facilities_desc_name:
        print(
            "Projections do not match, updating inFacilities in inFacilities_reprojected to match roads: "
            + roads_desc_name)
        arcpy.management.Project(inFacilities, 'inFacilities_reprojected',
                                 roads_desc.spatialReference)
        inFacilities = arcpy.env.workspace + '/inFacilities_reprojected'
        print(
            "Projection updated, both inFacilities and roads are projected in: "
            + roads_desc_name)
    else:
        print("Input feature class spatial references match.")

    ## Create feature dataset
    arcpy.CreateFeatureDataset_management(arcpy.env.workspace,
                                          'featuredataset',
                                          roads_desc.spatialReference)

    ## Copy input feature classes to featuredataset
    arcpy.CopyFeatures_management(roads, 'featuredataset/roads')
    arcpy.CopyFeatures_management(inFacilities, 'featuredataset/inFacilities')

    ## Create network dataset and build the network
    arcpy.na.CreateNetworkDataset('featuredataset', 'roads_ND', ['roads'])
    arcpy.BuildNetwork_na('featuredataset/roads_ND')

    ## Generating the Service Area Layer with service areas from 200 - 2000 meters, increasing at 200m intervals.
    routeLy = arcpy.na.MakeServiceAreaLayer(
        'featuredataset/roads_ND',
        'myRoute',
        'Length',
        "TRAVEL_FROM",
        '200 400 600 800 1000 1200 1400 1600 1800 2000',
        'DETAILED_POLYS',
        'MERGE',
        'RINGS',
        overlap="OVERLAP",
        hierarchy="USE_HIERARCHY")

    ## Standard processing features
    routeLayer = routeLy.getOutput(0)
    na_classes = arcpy.na.GetNAClassNames(routeLayer, 'INPUT')
    field_mappings = arcpy.na.NAClassFieldMappings(routeLayer,
                                                   na_classes['Facilities'])
    field_mappings['Attr_Length'].defaultValue = 0
    arcpy.na.AddLocations(routeLayer, na_classes["Facilities"],
                          "featuredataset/inFacilities", field_mappings)

    ## Compute the service areas
    arcpy.na.Solve(routeLayer)