<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Multiprocessing a nested loop in Python Questions</title>
    <link>https://community.esri.com/t5/python-questions/multiprocessing-a-nested-loop/m-p/1115693#M62950</link>
    <description>&lt;P&gt;Hi everyone,&amp;nbsp;&lt;/P&gt;&lt;P&gt;Can anyone help with using the Multiprocessing.Pool() module to get my nested loop script running via multi-processing?&amp;nbsp; I tried doing it myself but couldn't work out how without getting errors.&amp;nbsp;&lt;/P&gt;&lt;P&gt;I am working with very big datasets which take hours to days to run at each stage of the loop so am in need of a way to make this significantly faster.&lt;/P&gt;&lt;P&gt;See script below:&lt;/P&gt;&lt;P&gt;#Import system modules&lt;BR /&gt;import arcpy&lt;BR /&gt;from arcpy import env&lt;/P&gt;&lt;P&gt;# define list values&lt;BR /&gt;list1 = [ 'x', 'y', 'z']&lt;BR /&gt;list2 = [ 'a', 'b', 'c']&lt;/P&gt;&lt;P&gt;for x in range(len(list1)):&lt;BR /&gt;for y in range(len(list2)):&lt;BR /&gt;try:&lt;BR /&gt;&lt;BR /&gt;#Check out the Network Analyst extension license&lt;BR /&gt;arcpy.CheckOutExtension("Network")&lt;/P&gt;&lt;P&gt;#Set environment settings&lt;BR /&gt;env.overwriteOutput = True&lt;/P&gt;&lt;P&gt;#Set local variables&lt;BR /&gt;inNetworkDataset = "D:/RoadNetwork.gdb/RoadNetwork_ND"&lt;BR /&gt;&lt;BR /&gt;#verify layer name&lt;BR /&gt;outNALayerName = list1[x]&lt;BR /&gt;chunk = list2[y]&lt;BR /&gt;&lt;BR /&gt;#set variables&lt;BR /&gt;impedanceAttribute = "Distance"&lt;BR /&gt;inFacilities = "D:/facilities/" + chunk + ".shp"&lt;BR /&gt;polygonBarriers = "D:/barriers/" + outNALayerName + ".shp"&lt;BR /&gt;outLayerFile = "D:/outputs/" + outNALayerName + "_" + chunk + ".lyr"&lt;BR /&gt;&lt;BR /&gt;#Make a barrier feature layer&lt;BR /&gt;barriersLayer = arcpy.management.MakeFeatureLayer(polygonBarriers,"PolygonBarriers").getOutput(0)&lt;BR /&gt;&lt;BR /&gt;#Create a new service area layer.&lt;BR /&gt;outNALayer = arcpy.na.MakeServiceAreaLayer(inNetworkDataset, outNALayerName,&lt;BR /&gt;impedanceAttribute, "TRAVEL_FROM", "60", "DETAILED_POLYS", "NO_MERGE", "DISKS",&lt;BR /&gt;hierarchy = "NO_HIERARCHY", poly_trim_value = "100", restriction_attribute_name = ["OneWay"])&lt;BR /&gt;outNALayer = outNALayer.getOutput(0)&lt;/P&gt;&lt;P&gt;subLayerNames = arcpy.na.GetNAClassNames(outNALayer)&lt;/P&gt;&lt;P&gt;facilitiesLayerName = subLayerNames["Facilities"]&lt;BR /&gt;polygonbarriersLayerName = subLayerNames["PolygonBarriers"]&lt;/P&gt;&lt;P&gt;#Create field mappings for loading barriers&lt;BR /&gt;fieldMappings = arcpy.na.NAClassFieldMappings(outNALayer,polygonbarriersLayerName)&lt;BR /&gt;fieldMappings["BarrierType"].defaultValue = 0&lt;BR /&gt;&lt;BR /&gt;#Load the facilities and barriers&lt;BR /&gt;arcpy.na.AddLocations(outNALayer, facilitiesLayerName, inFacilities, "", "")&lt;BR /&gt;arcpy.na.AddLocations(outNALayer, polygonbarriersLayerName, polygonBarriers, fieldMappings)&lt;BR /&gt;&lt;BR /&gt;#Solve and save the service area layer&lt;BR /&gt;arcpy.na.Solve(outNALayer)&lt;BR /&gt;arcpy.management.SaveToLayerFile(outNALayer,outLayerFile,"ABSOLUTE")&lt;/P&gt;&lt;P&gt;except Exception as e:&lt;BR /&gt;# If an error occurred, print line number and error message&lt;BR /&gt;import traceback, sys&lt;BR /&gt;tb = sys.exc_info()[2]&lt;BR /&gt;now = datetime.now()&lt;BR /&gt;print now.strftime("%d%m%Y-%H%M%S")&lt;BR /&gt;print "An error occurred on line %i" % tb.tb_lineno&lt;BR /&gt;print str(e)&lt;/P&gt;</description>
    <pubDate>Wed, 10 Nov 2021 16:52:07 GMT</pubDate>
    <dc:creator>SG_Johnson</dc:creator>
    <dc:date>2021-11-10T16:52:07Z</dc:date>
    <item>
      <title>Multiprocessing a nested loop</title>
      <link>https://community.esri.com/t5/python-questions/multiprocessing-a-nested-loop/m-p/1115693#M62950</link>
      <description>&lt;P&gt;Hi everyone,&amp;nbsp;&lt;/P&gt;&lt;P&gt;Can anyone help with using the Multiprocessing.Pool() module to get my nested loop script running via multi-processing?&amp;nbsp; I tried doing it myself but couldn't work out how without getting errors.&amp;nbsp;&lt;/P&gt;&lt;P&gt;I am working with very big datasets which take hours to days to run at each stage of the loop so am in need of a way to make this significantly faster.&lt;/P&gt;&lt;P&gt;See script below:&lt;/P&gt;&lt;P&gt;#Import system modules&lt;BR /&gt;import arcpy&lt;BR /&gt;from arcpy import env&lt;/P&gt;&lt;P&gt;# define list values&lt;BR /&gt;list1 = [ 'x', 'y', 'z']&lt;BR /&gt;list2 = [ 'a', 'b', 'c']&lt;/P&gt;&lt;P&gt;for x in range(len(list1)):&lt;BR /&gt;for y in range(len(list2)):&lt;BR /&gt;try:&lt;BR /&gt;&lt;BR /&gt;#Check out the Network Analyst extension license&lt;BR /&gt;arcpy.CheckOutExtension("Network")&lt;/P&gt;&lt;P&gt;#Set environment settings&lt;BR /&gt;env.overwriteOutput = True&lt;/P&gt;&lt;P&gt;#Set local variables&lt;BR /&gt;inNetworkDataset = "D:/RoadNetwork.gdb/RoadNetwork_ND"&lt;BR /&gt;&lt;BR /&gt;#verify layer name&lt;BR /&gt;outNALayerName = list1[x]&lt;BR /&gt;chunk = list2[y]&lt;BR /&gt;&lt;BR /&gt;#set variables&lt;BR /&gt;impedanceAttribute = "Distance"&lt;BR /&gt;inFacilities = "D:/facilities/" + chunk + ".shp"&lt;BR /&gt;polygonBarriers = "D:/barriers/" + outNALayerName + ".shp"&lt;BR /&gt;outLayerFile = "D:/outputs/" + outNALayerName + "_" + chunk + ".lyr"&lt;BR /&gt;&lt;BR /&gt;#Make a barrier feature layer&lt;BR /&gt;barriersLayer = arcpy.management.MakeFeatureLayer(polygonBarriers,"PolygonBarriers").getOutput(0)&lt;BR /&gt;&lt;BR /&gt;#Create a new service area layer.&lt;BR /&gt;outNALayer = arcpy.na.MakeServiceAreaLayer(inNetworkDataset, outNALayerName,&lt;BR /&gt;impedanceAttribute, "TRAVEL_FROM", "60", "DETAILED_POLYS", "NO_MERGE", "DISKS",&lt;BR /&gt;hierarchy = "NO_HIERARCHY", poly_trim_value = "100", restriction_attribute_name = ["OneWay"])&lt;BR /&gt;outNALayer = outNALayer.getOutput(0)&lt;/P&gt;&lt;P&gt;subLayerNames = arcpy.na.GetNAClassNames(outNALayer)&lt;/P&gt;&lt;P&gt;facilitiesLayerName = subLayerNames["Facilities"]&lt;BR /&gt;polygonbarriersLayerName = subLayerNames["PolygonBarriers"]&lt;/P&gt;&lt;P&gt;#Create field mappings for loading barriers&lt;BR /&gt;fieldMappings = arcpy.na.NAClassFieldMappings(outNALayer,polygonbarriersLayerName)&lt;BR /&gt;fieldMappings["BarrierType"].defaultValue = 0&lt;BR /&gt;&lt;BR /&gt;#Load the facilities and barriers&lt;BR /&gt;arcpy.na.AddLocations(outNALayer, facilitiesLayerName, inFacilities, "", "")&lt;BR /&gt;arcpy.na.AddLocations(outNALayer, polygonbarriersLayerName, polygonBarriers, fieldMappings)&lt;BR /&gt;&lt;BR /&gt;#Solve and save the service area layer&lt;BR /&gt;arcpy.na.Solve(outNALayer)&lt;BR /&gt;arcpy.management.SaveToLayerFile(outNALayer,outLayerFile,"ABSOLUTE")&lt;/P&gt;&lt;P&gt;except Exception as e:&lt;BR /&gt;# If an error occurred, print line number and error message&lt;BR /&gt;import traceback, sys&lt;BR /&gt;tb = sys.exc_info()[2]&lt;BR /&gt;now = datetime.now()&lt;BR /&gt;print now.strftime("%d%m%Y-%H%M%S")&lt;BR /&gt;print "An error occurred on line %i" % tb.tb_lineno&lt;BR /&gt;print str(e)&lt;/P&gt;</description>
      <pubDate>Wed, 10 Nov 2021 16:52:07 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/multiprocessing-a-nested-loop/m-p/1115693#M62950</guid>
      <dc:creator>SG_Johnson</dc:creator>
      <dc:date>2021-11-10T16:52:07Z</dc:date>
    </item>
    <item>
      <title>Re: Multiprocessing a nested loop</title>
      <link>https://community.esri.com/t5/python-questions/multiprocessing-a-nested-loop/m-p/1115721#M62951</link>
      <description>&lt;P&gt;I've taken the liberty to format your code so it's readable.&amp;nbsp; While I don't have any experience with the&amp;nbsp;&lt;SPAN&gt;Multiprocessing.Pool() module, there are a couple things you should probably consider in your code.&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&lt;SPAN&gt;There are several functions that are repeated every time the loop(s) are iterated, and I wonder if this is what is causing you some problems.&amp;nbsp; Perhaps you could include the errors.&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&lt;SPAN&gt;For example, you only need to checkout Network Analyst once; you are checking it out everytime you go through the loop. You should be getting a fatal error everytime you encounter Line 34; makeFeatureLayer because that feature layer is created on the first pass through the loop(s) and already exists in subsequent trips through loops.&amp;nbsp; What is going on in lines 24 &amp;amp; 25:&amp;nbsp; I don't understand your use of index [x] and [y] in the respective list.&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&lt;SPAN&gt;My suggestion is to clean up your code such that you are not repeating yourself every time you go through it and see what happens.&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;#Import system modules
import arcpy
from arcpy import env


# define list values
list1 = [ 'x', 'y', 'z']
list2 = [ 'a', 'b', 'c']

for x in range(len(list1)):
    for y in range(len(list2)):
        try:
                    
            #Check out the Network Analyst extension license
            arcpy.CheckOutExtension("Network")

            #Set environment settings
            env.overwriteOutput = True

            #Set local variables
            inNetworkDataset = "D:/RoadNetwork.gdb/RoadNetwork_ND"
        
            #verify layer name
            outNALayerName = list1[x]
            chunk = list2[y]
            
            #set variables
            impedanceAttribute = "Distance"
            inFacilities = "D:/facilities/" + chunk + ".shp"
            polygonBarriers = "D:/barriers/" + outNALayerName + ".shp"
            outLayerFile = "D:/outputs/" + outNALayerName + "_" + chunk + ".lyr"
        
            #Make a barrier feature layer 
            barriersLayer = arcpy.management.MakeFeatureLayer(polygonBarriers,"PolygonBarriers").getOutput(0)
            
            #Create a new service area layer.         
            outNALayer = arcpy.na.MakeServiceAreaLayer(inNetworkDataset, outNALayerName,
                                          impedanceAttribute, "TRAVEL_FROM", "60", "DETAILED_POLYS", "NO_MERGE", "DISKS",
                                          hierarchy = "NO_HIERARCHY", poly_trim_value = "100", restriction_attribute_name = ["OneWay"])     
            outNALayer = outNALayer.getOutput(0)

            subLayerNames = arcpy.na.GetNAClassNames(outNALayer)

            facilitiesLayerName = subLayerNames["Facilities"]
            polygonbarriersLayerName = subLayerNames["PolygonBarriers"]

            #Create field mappings for loading barriers
            fieldMappings = arcpy.na.NAClassFieldMappings(outNALayer,polygonbarriersLayerName)
            fieldMappings["BarrierType"].defaultValue = 0
             
            #Load the facilities and barriers 
            arcpy.na.AddLocations(outNALayer, facilitiesLayerName, inFacilities, "", "")
            arcpy.na.AddLocations(outNALayer, polygonbarriersLayerName, polygonBarriers, fieldMappings)
           
            #Solve and save the service area layer 
            arcpy.na.Solve(outNALayer)
            arcpy.management.SaveToLayerFile(outNALayer,outLayerFile,"ABSOLUTE")

        except Exception as e:
            # If an error occurred, print line number and error message
            import traceback, sys
            tb = sys.exc_info()[2]
            now = datetime.now()
            print now.strftime("%d%m%Y-%H%M%S")
            print "An error occurred on line %i" % tb.tb_lineno
            print str(e)&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Wed, 10 Nov 2021 17:11:39 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/multiprocessing-a-nested-loop/m-p/1115721#M62951</guid>
      <dc:creator>JoeBorgione</dc:creator>
      <dc:date>2021-11-10T17:11:39Z</dc:date>
    </item>
    <item>
      <title>Re: Multiprocessing a nested loop</title>
      <link>https://community.esri.com/t5/python-questions/multiprocessing-a-nested-loop/m-p/1115762#M62952</link>
      <description>&lt;P&gt;You should be able to get rid of your loops and let the python Multiprocessing Pool manage running the body of the loop. You have to prepare a list of "parameter sets" that the Pool will use to invoke the body whenever a processor becomes available. In your case the list would look something like this (no guarantee on the exact syntax)&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;parm_list = [('x','a'), ('x','b'),('x','c'),('y','a'),('y','b'),('y','c'),('z','a'),('z','b'),('z','c')] &lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;then your body would be encapsulated in a function something list this&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;def my_body (parm):
    outNALayerName = parm[0]
    chunk = parm[1]
    .....&lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;and you would call it like this&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;LI-CODE lang="python"&gt;p = multiprocessing.Pool(&amp;lt;number of processors&amp;gt;)
p.map(my_body, parm_list)
p.close() &lt;/LI-CODE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;You have to be careful about lock conflicts, for instance if you use duplicate names for your temporary files or try have multiple processes updating the same file.&amp;nbsp;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Wed, 10 Nov 2021 18:21:26 GMT</pubDate>
      <guid>https://community.esri.com/t5/python-questions/multiprocessing-a-nested-loop/m-p/1115762#M62952</guid>
      <dc:creator>DonMorrison1</dc:creator>
      <dc:date>2021-11-10T18:21:26Z</dc:date>
    </item>
  </channel>
</rss>

