worldbank / GSS_Census_Tools

Collected tools for improving the EA demarcation workflow
GNU General Public License v3.0
4 stars 3 forks source link

Automation Issues #3

Open Justin-Q opened 4 years ago

Justin-Q commented 4 years ago

The code we modified worked halfway for the sampled districts we tried it on, it did not complete the whole set of EA's in the district. Also, it did not give any errors or reasons for the uncompletion However, we decided to automate only type two maps. and to work on type threes maps manually. We would be glad if you could modify the code to produce just type two maps and to make map documents which is very important to us for corrections sake.

Find the cde we implemented below. ''' class mappingDistrict(object): """ DEBUGGINGE districtFolder = r'C:\Users\WB411133\OneDrive - WBG\AAA_BPS\GOST\Projects\Ghana_Census_Support\Data\GSS_Data\EDITED_DISTRICTS\2020 GUSHIEGU\TYPE 2' t2Map = r'C:\Users\WB411133\OneDrive - WBG\AAA_BPS\GOST\Projects\Ghana_Census_Support\Data\GSS_Data\t2Map.mxd' t3Map = r'C:\Users\WB411133\OneDrive - WBG\AAA_BPS\GOST\Projects\Ghana_Census_Support\Data\GSS_Data\t3Map.mxd' saMap = r'C:\Users\WB411133\OneDrive - WBG\AAA_BPS\GOST\Projects\Ghana_Census_Support\Data\GSS_Data\saMap.mxd' """ def init (self, districtFolder, t2Map, t3Map, saMap): """ Generate properly formatted mapping

     INPUTS
     districtFolder [string] - path to folder of district level data
     t2Map, t3Map, saMap [ string ] - path to three map templates
     [ optional ] outputMapFolder [ string ] - where to create output maps
     """
     self.districtFolder = districtFolder
     #copy maps               
     self.t2Map = os.path.join(districtFolder, os.path.basename(t2Map))
     self.t3Map = os.path.join(districtFolder, os.path.basename(t3Map))
     self.saMap = os.path.join(districtFolder, os.path.basename(saMap))
     if not os.path.exists(self.t2Map):
         shutil.copy(t2Map, self.t2Map)
     if not os.path.exists(self.t3Map):
         shutil.copy(t3Map, self.t3Map)
     if not os.path.exists(self.saMap):
         shutil.copy(saMap, self.saMap)

 def setMapInputs(self, mapDocument):
     """
     """            
     mxd = arcpy.mapping.MapDocument(mapDocument)
     layers = arcpy.mapping.ListLayers(mxd)
     for l in layers:
         # find the data source and search for the same file in the input folder
         try:
             l.findAndReplaceWorkspacePath('', self.districtFolder, True)
         except:
             logging.warning("Could not fix path for %s" % l.name)
     mxd.save()

def createMapFromMXD_loop(mxd, outputImage, zoomLayer, layerName, labels=[], totalEA=1000, saveMap=False):
 """ Generate map for each feature in a layer

 INPUTS
 outputImage [string] - path to create output images
 """
 #Get reference to output type
 outputType = outputImage[-3:]    
 df = arcpy.mapping.ListDataFrames(mxd)[0]
 #Get a reference to the specific layer of interest
 layers = arcpy.mapping.ListLayers(mxd)
 for l in layers:        
     if l.name == zoomLayer:
         loopLyr = l
         l.visible = True
 # Get list of fields to extract from loop layer
 featCnt = 0
 searchFields = ["OID@", layerName]
 for x in labels:
     searchFields.append(x)
 # get reference to text boxes
 allLabels = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT")
 otherTitle = allLabels[0]
 districtCode = allLabels[1]
 districtName = allLabels[2]
 # loop through the features in loop layer
 with arcpy.da.SearchCursor(loopLyr, searchFields) as cur:
     for feat in cur:
         featCnt += 1
         if featCnt > totalEA:
             sys.exit()
         # Select the feature of interest
         arcpy.SelectLayerByAttribute_management(loopLyr, "NEW_SELECTION", '"FID" = %s' % feat[0])
         df.extent = loopLyr.getSelectedExtent()
         df.scale = df.scale * 1.05
         arcpy.SelectLayerByAttribute_management(loopLyr, "CLEAR_SELECTION", '"FID" = %s' % feat[0])
         #Set EA definition so featured EA is not visible
         loopLyr.definitionQuery = '"FID" = %s' % feat[0]    
         #Update labels
         otherTitle.text = feat[2]
         districtCode.text = feat[3]
         districtName.text = feat[4]                        
         #Export map
         time.sleep(1)
         outputMap = outputImage.replace(".%s" % outputType, "_%s.%s" % (feat[1], outputType))                  
         if outputType == 'png':
             arcpy.mapping.ExportToPNG(mxd, outputMap)
         elif outputType == 'pdf':
             arcpy.mapping.ExportToPDF(mxd, outputMap)            
         if saveMap:
             mxd.saveACopy(outputMap.replace(".%" % outputType, ".mxd"))
         loopLyr.definitionQuery = ""

mxd = arcpy.mapping.MapDocument("CURRENT")
focal_layer = "ZABZUGU NEW FINAL"     # Layer with individual features for which to create atlas
feature_name = "Z020_PROV_"         # column containing unique name for each feature - drives the filenames
labelFields = ["DIST_NAME",feature_name,"Z020_TYPE"] # columns to populate text on map
outputImage = "C:/Users/METSS-050/Desktop/2020 MAP CREATION OUTPUT/Type 2 Maps.pdf"           #Output filename, make sure folder exists

createMapFromMXD_loop(mxd, outputImage, focal_layer, feature_name, labelFields, totalEA=3, saveMap=False)

inFile = r'C:\Users\METSS-050\Desktop\2020 NR ZABZUGU\ZABZUGU NEW FINAL.shp'
with arcpy.da.UpdateCursor(inFile, ['OID@','SHAPE@','ORIENT']) as cur:
 for feat in cur:
     orientation = "LANDSCAPE"
     if feat[1].extent.width < feat[1].extent.height:
         orientation = "PORTRAIT"
     feat[2] = orientation
     cur.updateRow(feat)

def add5(x):
 return(x + 5)

add5(10)

'''

bpstewar commented 4 years ago

There are three issues you raised, I think all can be fixed quickly. The final line of the script is below, you need to change a couple arguments in it in order to fix the issues

createMapFromMXD_loop(mxd, 
                      outputImage, 
                      focal_layer, 
                      feature_name, 
                      labelFields, 
                      totalEA=3,        #Set this number to be very high (3000) in order to process everything
                      saveMap=False)    #Set this to True in order to save a mxd of each EA
  1. Not all EAs were processed: set the totalEA = 3000
  2. Need to save a map each time: set saveMap = True
  3. Process only the type 2 EAs: this is a little more complicated. I think the easiest way would be to create a new shapefile of the Type 2 EAs using the Geoprocessing Select Analysis tool. Use that new layer as the input layer
Justin-Q commented 4 years ago

Corrections noted, we will try it and check out the results as soon as possible.

On Wed, Dec 4, 2019 at 3:23 PM Benjamin P. Stewart notifications@github.com wrote:

There are three issues you raised, I think all can be fixed quickly. The final line of the script is below, you need to change a couple arguments in it in order to fix the issues

createMapFromMXD_loop(mxd, outputImage, focal_layer, feature_name, labelFields, totalEA=3, #Set this number to be very high (3000) in order to process everything saveMap=False) #Set this to True in order to save a mxd of each EA

  1. Not all EAs were processed: set the totalEA = 3000
  2. Need to save a map each time: set saveMap = True
  3. Process only the type 2 EAs: this is a little more complicated. I think the easiest way would be to create a new shapefile of the Type 2 EAs using the Geoprocessing Select Analysis tool. Use that new layer as the input layer

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/worldbank/GSS_Census_Tools/issues/3?email_source=notifications&email_token=ANYXTGFKDZJZWERM4EMWSSTQW7DORA5CNFSM4JUZDIQ2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEF5MGSY#issuecomment-561693515, or unsubscribe https://github.com/notifications/unsubscribe-auth/ANYXTGGGTEQ5Z6TJNGR7EMLQW7DORANCNFSM4JUZDIQQ .