Ejemplo n.º 1
0
def gridIndex(cln_name):

    env.workspace = "C:/Users/Noah/Desktop/grids/" + countyname + " County/shapefiles/{0}".format(
        cln_name)
    feature_classes = arcpy.ListFeatureClasses()

    # Set local variables
    outfc = "{0}_fishnet_26910_grid.shp".format(cln_name)
    infc = "{0}_fishnet_26910.shp".format(cln_name)

    desc = arcpy.Describe(infc)
    originCoord = str(desc.extent.lowerLeft)

    intersect_feature = "INTERSECTFEATURE"
    usePageUnit = "NO_USEPAGEUNIT"
    scale = ""
    polygonWidth = "804.67 Meters"
    polygonHeight = "804.67 Meters"
    numberRows = ""
    numberColumns = ""
    startingPageNum = "1"
    labeling = "LABELFROMORIGIN"

    # Execute GridIndexFeatures
    arcpy.GridIndexFeatures_cartography(outfc, infc, intersect_feature,
                                        usePageUnit, scale, polygonWidth,
                                        polygonHeight, originCoord, numberRows,
                                        numberColumns, startingPageNum,
                                        labeling)

    del outfc
    del infc
Ejemplo n.º 2
0
 def comparison_grid_1_sqkm(self):
     temp_merge = "in_memory\\merge"
     arcpy.Merge_management([self.original, self.simplified], temp_merge)
     temp_grid = "in_memory\\grid"
     arcpy.GridIndexFeatures_cartography(temp_grid, temp_merge,
                                         "INTERSECTFEATURE",
                                         "NO_USEPAGEUNIT", "#",
                                         "1 Kilometers", "1 Kilometers")
     arcpy.Delete_management(temp_merge)
     arcpy.AddMessage("Comparison grid (1 sq km) prepared.")
     return temp_grid
Ejemplo n.º 3
0
    def setMultipage(self, year, mxd, dfmain, gridsize, yesboundary):
        # reset boundary
        if yesboundary != "no":
            arcpy.mapping.ListLayers(mxd, "Project Property",
                                     dfmain)[0].visible = True

        # create grid based on sheets clipped to buffer
        expression = str('"YEAR" LIKE \'%' + str(year) + "%'")
        arcpy.MakeFeatureLayer_management(cfg.selectedmain, "selMainLayer")
        arcpy.SelectLayerByAttribute_management("selMainLayer",
                                                'NEW_SELECTION', expression)

        clipSelected = os.path.join(cfg.scratch, cfg.scratchgdb,
                                    "clip_" + str(year))
        arcpy.Clip_analysis("selMainLayer", cfg.outBufferSHP, clipSelected)

        Gridlrshp = os.path.join(cfg.scratch, cfg.scratchgdb,
                                 "gridlr_" + str(year))
        arcpy.GridIndexFeatures_cartography(Gridlrshp, clipSelected,
                                            "INTERSECTFEATURE", "", "",
                                            gridsize, gridsize)

        gridLayer = arcpy.mapping.ListLayers(mxd, "Grid", dfmain)[0]
        gridLayer.replaceDataSource(os.path.join(cfg.scratch, cfg.scratchgdb),
                                    "FILEGDB_WORKSPACE",
                                    "gridlr" + "_" + str(year))
        gridLayer.visible = True

        # export multipages
        FIPpdfMM = os.path.join(cfg.scratch,
                                'FIPExport_' + str(year) + '_multipage.pdf')
        ddMMDDP = mxd.dataDrivenPages
        ddMMDDP.refresh()
        ddMMDDP.exportToPDF(out_pdf=FIPpdfMM,
                            page_range_type="ALL",
                            resolution=600,
                            image_quality="BEST",
                            georef_info=True)

        # reset view
        dfmain.extent = arcpy.mapping.ListLayers(
            mxd, "Buffer Outline", dfmain)[0].getSelectedExtent(False)
        scale = dfmain.scale * 1.75
        dfmain.scale = ((int(scale) / 100) + 1) * 100

        # reset boundary
        if yesboundary != "fixed":
            arcpy.mapping.ListLayers(mxd, "Project Property",
                                     dfmain)[0].visible = False

        del FIPpdfMM
        del ddMMDDP
        return mxd, dfmain
Ejemplo n.º 4
0
    "ENVELOPE", "LIST", "CITYNO", "MBG_FIELDS")
#SubArea Bounding Polygons
arcpy.MinimumBoundingGeometry_management(
    "SDE.SDE.URBAN_BOUNDARIES",
    "//gisdata/arcgis/GISdata/KDOT/BTP/Projects/MAPINDEX/IndexProcess.mdb/NAD83/cOUNTYlIM",
    "ENVELOPE", "LIST", "CITYNO", "MBG_FIELDS")
#SNICE_Area Bounding Polygons

#DISTRICT Bounding Polygons

#assemble bounding polygons into map index

#create Quads and Quarter Quad Grids that match the FAA Sectionals
arcpy.GridIndexFeatures_cartography("F:/Cart/projects/Graticule/MKC15.shp",
                                    "#", "NO_INTERSECTFEATURE",
                                    "NO_USEPAGEUNIT", "#",
                                    "0.25 DecimalDegrees",
                                    "0.25 DecimalDegrees", "-97 36", "16",
                                    "28", "1", "NO_LABELFROMORIGIN")
arcpy.GridIndexFeatures_cartography("F:/Cart/projects/Graticule/ICT15.shp",
                                    "#", "NO_INTERSECTFEATURE",
                                    "NO_USEPAGEUNIT", "#",
                                    "0.25 DecimalDegrees",
                                    "0.25 DecimalDegrees", "-104 36", "16",
                                    "28", "1", "NO_LABELFROMORIGIN")
arcpy.GridIndexFeatures_cartography("F:/Cart/projects/Graticule/ICT75.shp",
                                    "#", "NO_INTERSECTFEATURE",
                                    "NO_USEPAGEUNIT", "#",
                                    "0.125 DecimalDegrees",
                                    "0.125 DecimalDegrees", "-104 36", "32",
                                    "56", "1", "NO_LABELFROMORIGIN")
arcpy.GridIndexFeatures_cartography("F:/Cart/projects/Graticule/MKC75.shp",
Ejemplo n.º 5
0
def generate_multipage_report(order_obj, cellids_selected, mxd_relief,
                              df_relief, output_jpg_relief):
    df_mm_relief = None
    grid_lyr_shp = os.path.join(config.scratch_folder, 'grid_lyr_relief.shp')
    arcpy.GridIndexFeatures_cartography(grid_lyr_shp, config.order_buffer_shp,
                                        "", "", "", config.grid_size,
                                        config.grid_size)
    # part 1: the overview map
    # add grid layer
    grid_layer = arcpy.mapping.Layer(config.grid_lyr_file)
    grid_layer.replaceDataSource(config.scratch_folder, "SHAPEFILE_WORKSPACE",
                                 "grid_lyr_relief")
    arcpy.mapping.AddLayer(df_relief, grid_layer, "Top")

    df_relief.extent = grid_layer.getExtent()
    df_relief.scale = df_relief.scale * 1.1

    mxd_relief.saveACopy(os.path.join(config.scratch_folder, "mxd_relief.mxd"))
    arcpy.mapping.ExportToJPEG(mxd_relief, output_jpg_relief, "PAGE_LAYOUT",
                               480, 640, 150, "False", "24-BIT_TRUE_COLOR", 85)

    if not os.path.exists(
            os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
        os.mkdir(os.path.join(config.report_path, 'PSRmaps', order_obj.number))
    shutil.copy(output_jpg_relief,
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
    arcpy.AddMessage(
        '      - output jpg image page 1: %s' %
        os.path.join(config.report_path, 'PSRmaps', order_obj.number,
                     os.path.basename(output_jpg_relief)))
    del mxd_relief
    del df_relief

    # part 2: the data driven pages
    page = int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) + 1
    mxd_mm_relief = arcpy.mapping.MapDocument(config.mxd_mm_file_relief)

    df_mm_relief = arcpy.mapping.ListDataFrames(mxd_mm_relief, "*")[0]
    df_mm_relief.spatialReference = order_obj.spatial_ref_pcs

    ### add order geometry and it's bugger to mxd
    utility.add_layer_to_mxd("order_buffer", df_mm_relief,
                             config.buffer_lyr_file, 1.1)
    utility.add_layer_to_mxd("order_geometry_pcs", df_mm_relief,
                             config.order_geom_lyr_file, 1)

    grid_layer_mm = arcpy.mapping.ListLayers(mxd_mm_relief, "Grid",
                                             df_mm_relief)[0]
    grid_layer_mm.replaceDataSource(config.scratch_folder,
                                    "SHAPEFILE_WORKSPACE", "grid_lyr_relief")
    arcpy.CalculateAdjacentFields_cartography(grid_lyr_shp, "PageNumber")
    mxd_mm_relief.saveACopy(
        os.path.join(config.scratch_folder, "mxd_mm_relief.mxd"))

    for item in cellids_selected:
        item = item[:-4]
        relief_layer = arcpy.mapping.Layer(config.relief_lyr_file)
        shutil.copyfile(
            os.path.join(config.path_shaded_relief, item + '_hs.img'),
            os.path.join(
                config.scratch_folder,
                item + '_hs.img'))  #make a local copy, will make it run faster
        relief_layer.replaceDataSource(config.scratch_folder,
                                       "RASTER_WORKSPACE", item + '_hs.img')
        relief_layer.name = item
        arcpy.mapping.AddLayer(df_mm_relief, relief_layer, "BOTTOM")

        for i in range(
                1,
                int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) + 1):
            arcpy.SelectLayerByAttribute_management(
                grid_layer_mm, "NEW_SELECTION", ' "PageNumber" =  ' + str(i))
            df_mm_relief.extent = grid_layer_mm.getSelectedExtent(True)
            df_mm_relief.scale = df_mm_relief.scale * 1.1
            arcpy.SelectLayerByAttribute_management(grid_layer_mm,
                                                    "CLEAR_SELECTION")
            arcpy.mapping.ExportToJPEG(
                mxd_mm_relief, output_jpg_relief[0:-4] + str(i) + ".jpg",
                "PAGE_LAYOUT", 480, 640, 150, "False", "24-BIT_TRUE_COLOR", 85)

            if not os.path.exists(
                    os.path.join(config.report_path, 'PSRmaps',
                                 order_obj.number)):
                os.mkdir(
                    os.path.join(config.report_path, 'PSRmaps',
                                 order_obj.number))
            shutil.copy(
                output_jpg_relief[0:-4] + str(i) + ".jpg",
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))

    del mxd_mm_relief
    del df_mm_relief
    #insert generated .jpg report path into eris_maps_psr table
    psr_obj = models.PSR()
    if os.path.exists(
            os.path.join(config.report_path, 'PSRmaps', order_obj.number,
                         order_obj.number + '_US_RELIEF.jpg')):
        psr_obj.insert_map(order_obj.id, 'RELIEF',
                           order_obj.number + '_US_RELIEF.jpg', 1)
        for i in range(1, page):
            psr_obj.insert_map(
                order_obj.id, 'RELIEF',
                order_obj.number + '_US_RELIEF' + str(i) + '.jpg', i + 1)
    else:
        arcpy.AddMessage('No Relief map is available')
Ejemplo n.º 6
0
def intersectGrid(AggLevel, workingDir, variable):
    '''Intersects the NOAA precipitation data grid with the AggLevel = "Woreda" or "Kebele" shapefile'''

    #create grid shapefile
    Grid = workingDir + "\\All" + variable + "Grid.shp"
    if (os.path.exists(Grid) == False):
        if variable == "Temp":
            origin_coord = "-180 -90"
            nrows = "360"
            ncols = "720"
            polygon_width = "0.5 degrees"
        else:
            origin_coord = "-20.05 -40.05"
            nrows = "801"
            ncols = "751"
            polygon_width = "0.1 degrees"

        polygon_height = polygon_width
        ap.GridIndexFeatures_cartography(Grid, "", "", "", "", polygon_width,
                                         polygon_height, origin_coord, nrows,
                                         ncols)
        ap.DefineProjection_management(
            Grid,
            coor_system="GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',\
        SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
        )

        #add 3 or 4 fields to grid shapefile: latitude (LAT), longitude (LONG) and
        #for precipitation, row (row) of text file corresponding to each grid in the shapefile;
        #for temperature, row (row) and column (col) of netCDF file corresponding to each grid in the shapefile
        ap.AddField_management(Grid, "LAT", "DOUBLE", 7, 2, "", "", "", "", "")
        ap.AddField_management(Grid, "LONG", "DOUBLE", 7, 2, "", "", "", "",
                               "")
        ap.AddField_management(Grid, "row", "SHORT", 6, "", "", "", "", "", "")
        if variable == "Temp":
            ap.AddField_management(Grid, "col", "SHORT", 5, "", "", "", "", "",
                                   "")

        #calculate lat and long fields
        expression1 = "float(!SHAPE.CENTROID!.split()[0])"
        expression2 = "float(!SHAPE.CENTROID!.split()[1])"
        ap.CalculateField_management(Grid, "LONG", expression1, "PYTHON")
        ap.CalculateField_management(Grid, "LAT", expression2, "PYTHON")

        #calculate row and col fields
        if variable == "Temp":
            Grid = calcTempFields(Grid)
        else:
            Grid = calcRainFields(Grid)

    #clip the grid to Ethiopia and convert its .dbf to a .csv for later use
    GridClip = workingDir + "\\" + variable + "GridClip" + AggLevel + ".shp"
    if AggLevel == 'Woreda':
        EthiopiaBorders = os.path.dirname(
            workingDir) + "\\Shapefiles\\WoredasAdindan.shp"
    elif AggLevel == 'Kebele':
        EthiopiaBorders = os.path.dirname(
            workingDir
        ) + "\\Shapefiles\\Ethiopia Kebeles without Somali region.shp"

    ap.Clip_analysis(Grid, EthiopiaBorders, GridClip)
    dbf = GridClip[0:-4] + ".dbf"
    GridCSV = convertDBFtoCSV(dbf)

    #intersect the clipped grid with the woreda or kebele shapefile and project to Adindan
    GridIntersect = workingDir + "\\" + variable + AggLevel + "Intersect.shp"
    ap.Intersect_analysis([GridClip, EthiopiaBorders], GridIntersect)
    GridIntersectProject = GridIntersect[0:-4] + "Project.shp"
    ap.Project_management(
        GridIntersect,
        GridIntersectProject,
        out_coor_system="PROJCS['Adindan_UTM_Zone_37N',GEOGCS['GCS_Adindan',\
    DATUM['D_Adindan',SPHEROID['Clarke_1880_RGS',6378249.145,293.465]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],\
    PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',500000.0],PARAMETER['False_Northing',0.0],\
    PARAMETER['Central_Meridian',39.0],PARAMETER['Scale_Factor',0.9996],PARAMETER['Latitude_Of_Origin',0.0],\
    UNIT['Meter',1.0]]",
        transform_method="Adindan_To_WGS_1984_1",
        in_coor_system="GEOGCS['GCS_WGS_1984',DATUM['D_WGS_1984',\
    SPHEROID['WGS_1984',6378137.0,298.257223563]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]"
    )

    #calculate area of intersection between grid and woreda or kebele shapefile after adding a field to store it
    ap.AddField_management(GridIntersectProject, "PartArea", "DOUBLE", 12, 6,
                           "", "", "", "", "")
    expression = "float(!SHAPE.AREA@SQUAREKILOMETERS!)"
    ap.CalculateField_management(GridIntersectProject, "PartArea", expression,
                                 "PYTHON")

    #convert GridIntersect's .dbf to a .csv for later use
    dbf = GridIntersectProject[0:-4] + ".dbf"
    intersectCSV = convertDBFtoCSV(dbf)

    return intersectCSV, GridCSV
Ejemplo n.º 7
0
def generate_flood_report(order_obj):
    arcpy.AddMessage('  -- Start generating PSR flood report...')
    start = timeit.default_timer() 
    eris_id = 0
    Setting.output_jpg_flood = config.output_jpg(order_obj,config.Report_Type.flood)
    page = 1
    
    config.buffer_dist_flood = str(order_obj.psr.search_radius['10683']) + ' MILES'
    ### create buffer map based on order geometry
    arcpy.Buffer_analysis(config.order_geometry_pcs_shp, config.order_buffer_shp, config.buffer_dist_flood) 
    
    arcpy.MakeFeatureLayer_management(config.data_flood, 'flood_lyr') 
    arcpy.SelectLayerByLocation_management('flood_lyr', 'intersect',  config.order_buffer_shp)
    arcpy.CopyFeatures_management('flood_lyr', config.flood_selectedby_order_shp)
    
    arcpy.MakeFeatureLayer_management(config.data_flood_panel, 'flood_panel_lyr') 
    arcpy.SelectLayerByLocation_management('flood_panel_lyr', 'intersect',  config.order_buffer_shp)
    arcpy.CopyFeatures_management('flood_panel_lyr', config.flood_panel_selectedby_order_shp)
    
    arcpy.Statistics_analysis(config.flood_selectedby_order_shp, os.path.join(config.scratch_folder,"summary_flood.dbf"), [['FLD_ZONE','FIRST'], ['ZONE_SUBTY','FIRST']],'ERIS_CLASS')
    arcpy.Sort_management(os.path.join(config.scratch_folder,"summary_flood.dbf"), os.path.join(config.scratch_folder,"summary_sorted_flood.dbf"), [["ERIS_CLASS", "ASCENDING"]])
    
    mxd_flood = arcpy.mapping.MapDocument(config.mxd_file_flood)
    df_flood = arcpy.mapping.ListDataFrames(mxd_flood,"Flood*")[0]
    df_flood.spatialReference = order_obj.spatial_ref_pcs
    
    df_flood_small = arcpy.mapping.ListDataFrames(mxd_flood,"Study*")[0]
    df_flood_small.spatialReference = order_obj.spatial_ref_pcs
    del df_flood_small
    
    utility.add_layer_to_mxd("order_buffer",df_flood,config.buffer_lyr_file, 1.1)
    utility.add_layer_to_mxd("order_geometry_pcs", df_flood,config.order_geom_lyr_file,1)
    arcpy.RefreshActiveView()
    
    if not config.if_multi_page: # single-page
        mxd_flood.saveACopy(os.path.join(config.scratch_folder, "mxd_flood.mxd"))  
        arcpy.mapping.ExportToJPEG(mxd_flood, Setting.output_jpg_flood, "PAGE_LAYOUT", resolution=75, jpeg_quality=40)
        if not os.path.exists(os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        arcpy.AddMessage('      - output jpg image path (overview map): %s' % os.path.join(config.report_path, 'PSRmaps', order_obj.number,os.path.basename(Setting.output_jpg_flood)))
        shutil.copy(Setting.output_jpg_flood, os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        del mxd_flood
        del df_flood
    else: # multi-page
        grid_lyr_shp = os.path.join(config.scratch_folder, 'grid_lyr_flood.shp')
        arcpy.GridIndexFeatures_cartography(grid_lyr_shp, config.order_buffer_shp, "", "", "", config.grid_size, config.grid_size)
        
        # part 1: the overview map
        # add grid layer
        grid_layer = arcpy.mapping.Layer(config.grid_lyr_file)
        grid_layer.replaceDataSource(config.scratch_folder,"SHAPEFILE_WORKSPACE","grid_lyr_flood")
        arcpy.mapping.AddLayer(df_flood,grid_layer,"Top")

        df_flood.extent = grid_layer.getExtent()
        df_flood.scale = df_flood.scale * 1.1

        mxd_flood.saveACopy(os.path.join(config.scratch_folder, "mxd_flood.mxd"))
        arcpy.mapping.ExportToJPEG(mxd_flood, Setting.output_jpg_flood, "PAGE_LAYOUT", 480, 640, 75, "False", "24-BIT_TRUE_COLOR", 40)
        if not os.path.exists(os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        shutil.copy(Setting.output_jpg_flood, os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        arcpy.AddMessage('      - output jpg image page 1: %s' % os.path.join(config.report_path, 'PSRmaps', order_obj.number,os.path.basename(Setting.output_jpg_flood)))
        del mxd_flood
        del df_flood
        
        ### part 2: the data driven pages
        
        page = int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0))  + page
        arcpy.AddMessage('  -- number of pages: %s' % str(page))
        Setting.mxd_multi_flood = arcpy.mapping.MapDocument(config.mxd_mm_file_flood)

        Setting.df_mm_flood = arcpy.mapping.ListDataFrames(Setting.mxd_multi_flood,"Flood*")[0]
        Setting.df_mm_flood.spatialReference = order_obj.spatial_ref_pcs
        utility.add_layer_to_mxd("order_buffer",Setting.df_mm_flood,config.buffer_lyr_file,1.1)
        utility.add_layer_to_mxd("order_geometry_pcs", Setting.df_mm_flood,config.order_geom_lyr_file,1)
        
        Setting.grid_layer_mm = arcpy.mapping.ListLayers(Setting.mxd_multi_flood,"Grid" ,Setting.df_mm_flood)[0]
        Setting.grid_layer_mm.replaceDataSource(config.scratch_folder,"SHAPEFILE_WORKSPACE","grid_lyr_flood")
        arcpy.CalculateAdjacentFields_cartography(grid_lyr_shp, "PageNumber")
        Setting.mxd_multi_flood.saveACopy(os.path.join(config.scratch_folder, "mxd_mm_flood.mxd"))
       
        if not os.path.exists(os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        
        ### execute multi-page report bu multi-task processing
        # page = 10
        parameter_dic = {}
        path_list = [os.path.join(config.scratch_folder, "mxd_mm_flood.mxd"), Setting.output_jpg_flood]
        for i in range(1,page):
            parameter_dic[i] = path_list
            
        # execute_multi_task()
        result = generate_multi_page_multi_processing(parameter_dic.items())
def EliminatebyGrid(tsa, vri, outFC, fraction=2):
    #--Need a temporary DB to assemble this stuff
    DeleteExists(
        os.path.join(os.environ['TEMP'],
                     'ElimTemp{0}.gdb'.format(processGroup)))
    elimDB = CreateTempDB(os.environ['TEMP'],
                          name='ElimTemp{0}'.format(processGroup))
    #--Get Extents of Grids to create as fraction of TSA width, height
    lyrTSA = 'lyrTSA'
    gp.MakeFeatureLayer_management(tsa, lyrTSA)
    desc = gp.Describe(lyrTSA)
    ext = gp.Describe(lyrTSA).extent
    extW = (
        (ext.XMax - ext.XMin) /
        fraction) + 1  #--Add 1m to ensure we are not touching edge of grids
    extH = ((ext.YMax - ext.YMin) / fraction) + 1
    gridTemp = os.path.join(elimDB, 'Grid')
    idTemp = os.path.join(elimDB, 'VRI_ID')
    #WriteLog(kennyloggins, 'extW - {0}\n'.format(str(extW)), True)
    #WriteLog(kennyloggins, 'extH - {0}\n'.format(str(extH)), True)
    gp.GridIndexFeatures_cartography(gridTemp,
                                     tsa,
                                     "INTERSECTFEATURE",
                                     "NO_USEPAGEUNIT",
                                     polygon_width=extW,
                                     polygon_height=extH)
    gp.Identity_analysis(vri, gridTemp, idTemp, "ALL", 1)
    outElims = []
    with arcpy.da.SearchCursor(gridTemp, ['SHAPE@', 'PageName']) as cursor:
        for row in cursor:
            try:
                pg = row[1]
                WriteLog(kennyloggins,
                         '----Doing Sub-Eliminate on - {0}\n'.format(str(pg)),
                         True)
                lyrIDTemp = 'lyrIDTemp'
                lyrGridTemp = 'lyrGridTemp'
                outGrid = os.path.join(elimDB, 'Temp_{0}_1Grid'.format(pg))
                outElim = os.path.join(elimDB, 'Temp_{0}_2Elim'.format(pg))
                arcpy.MakeFeatureLayer_management(
                    idTemp, lyrIDTemp, "PageName = '{0}'".format(pg))
                arcpy.env.extent = arcpy.Describe(lyrIDTemp).extent
                arcpy.CopyFeatures_management(lyrIDTemp, outGrid)
                arcpy.Delete_management(lyrIDTemp)
                arcpy.MakeFeatureLayer_management(outGrid, lyrGridTemp)
                arcpy.SelectLayerByAttribute_management(
                    lyrGridTemp, "NEW_SELECTION",
                    "({0}/10000) <= 0.5".format(GetAreaField(outGrid)))
                arcpy.Eliminate_management(lyrGridTemp,
                                           outElim,
                                           "LENGTH",
                                           ex_features=gridTemp)
                outElims.append(outElim)
                arcpy.Delete_management(lyrGridTemp)
                arcpy.Delete_management(outGrid)
                WriteLog(
                    kennyloggins,
                    '----Done Sub-Eliminate - {0}\n'.format(str(outElims)),
                    True)
            except Exception, e:
                WriteLog(kennyloggins,
                         '***Error in Grid by Fraction - {0}\n'.format(str(e)),
                         True)
Ejemplo n.º 9
0
def generate_flood_report(order_obj):
    arcpy.AddMessage('  -- Start generating PSR flood report...')
    start = timeit.default_timer()   
  
    eris_id = 0
    Setting.output_jpg_flood = config.output_jpg(order_obj,config.Report_Type.flood)
    page = 1
    if '10683' not in order_obj.psr.search_radius.keys():
        arcpy.AddMessage('      -- Flood search radius is not availabe')
        return
    config.buffer_dist_flood = str(order_obj.psr.search_radius['10683']) + ' MILES'
    arcpy.Buffer_analysis(config.order_geometry_pcs_shp, config.order_buffer_shp, config.buffer_dist_flood) ### create buffer map based on order geometry
    
    arcpy.MakeFeatureLayer_management(config.data_flood, 'flood_lyr') 
    arcpy.SelectLayerByLocation_management('flood_lyr', 'intersect',  config.order_buffer_shp)
    arcpy.CopyFeatures_management('flood_lyr', config.flood_selectedby_order_shp)
    
    arcpy.MakeFeatureLayer_management(config.data_flood_panel, 'flood_panel_lyr') 
    arcpy.SelectLayerByLocation_management('flood_panel_lyr', 'intersect',  config.order_buffer_shp)
    arcpy.CopyFeatures_management('flood_panel_lyr', config.flood_panel_selectedby_order_shp)
    
    arcpy.Statistics_analysis(config.flood_selectedby_order_shp, os.path.join(config.scratch_folder,"summary_flood.dbf"), [['FLD_ZONE','FIRST'], ['ZONE_SUBTY','FIRST']],'ERIS_CLASS')
    arcpy.Sort_management(os.path.join(config.scratch_folder,"summary_flood.dbf"), os.path.join(config.scratch_folder,"summary_sorted_flood.dbf"), [["ERIS_CLASS", "ASCENDING"]])
    
    mxd_flood = arcpy.mapping.MapDocument(config.mxd_file_flood)
    df_flood = arcpy.mapping.ListDataFrames(mxd_flood,"Flood*")[0]
    df_flood.spatialReference = order_obj.spatial_ref_pcs
    
    df_flood_small = arcpy.mapping.ListDataFrames(mxd_flood,"Study*")[0]
    df_flood_small.spatialReference = order_obj.spatial_ref_pcs
    del df_flood_small
    
    utility.add_layer_to_mxd("order_buffer",df_flood,config.buffer_lyr_file, 1.1)
    utility.add_layer_to_mxd("order_geometry_pcs", df_flood,config.order_geom_lyr_file,1)
    arcpy.RefreshActiveView()
    
    psr_obj = models.PSR()
    
    if not config.if_multi_page: # single-page
        mxd_flood.saveACopy(os.path.join(config.scratch_folder, "mxd_flood.mxd"))  
        arcpy.mapping.ExportToJPEG(mxd_flood, Setting.output_jpg_flood, "PAGE_LAYOUT", resolution=75, jpeg_quality=40)
        if not os.path.exists(os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        arcpy.AddMessage('      - output jpg image path (overview map): %s' % os.path.join(config.report_path, 'PSRmaps', order_obj.number,os.path.basename(Setting.output_jpg_flood)))
        shutil.copy(Setting.output_jpg_flood, os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        del mxd_flood
        del df_flood
    else: # multi-page
        grid_lyr_shp = os.path.join(config.scratch_folder, 'grid_lyr_flood.shp')
        arcpy.GridIndexFeatures_cartography(grid_lyr_shp, config.order_buffer_shp, "", "", "", config.grid_size, config.grid_size)
        
        # part 1: the overview map
        # add grid layer
        grid_layer = arcpy.mapping.Layer(config.grid_lyr_file)
        grid_layer.replaceDataSource(config.scratch_folder,"SHAPEFILE_WORKSPACE","grid_lyr_flood")
        arcpy.mapping.AddLayer(df_flood,grid_layer,"Top")

        df_flood.extent = grid_layer.getExtent()
        df_flood.scale = df_flood.scale * 1.1

        mxd_flood.saveACopy(os.path.join(config.scratch_folder, "mxd_flood.mxd"))
        arcpy.mapping.ExportToJPEG(mxd_flood, Setting.output_jpg_flood, "PAGE_LAYOUT", 480, 640, 75, "False", "24-BIT_TRUE_COLOR", 40)
        if not os.path.exists(os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        shutil.copy(Setting.output_jpg_flood, os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        arcpy.AddMessage('      - output jpg image page 1: %s' % os.path.join(config.report_path, 'PSRmaps', order_obj.number,os.path.basename(Setting.output_jpg_flood)))
        del mxd_flood
        del df_flood
        # part 2: the data driven pages
        
        page = int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0))  + page
        Setting.mxd_multi_flood = arcpy.mapping.MapDocument(config.mxd_mm_file_flood)

        Setting.df_mm_flood = arcpy.mapping.ListDataFrames(Setting.mxd_multi_flood,"Flood*")[0]
        Setting.df_mm_flood.spatialReference = order_obj.spatial_ref_pcs
        utility.add_layer_to_mxd("order_buffer",Setting.df_mm_flood,config.buffer_lyr_file,1.1)
        utility.add_layer_to_mxd("order_geometry_pcs", Setting.df_mm_flood,config.order_geom_lyr_file,1)
        
        Setting.grid_layer_mm = arcpy.mapping.ListLayers(Setting.mxd_multi_flood,"Grid" ,Setting.df_mm_flood)[0]
        Setting.grid_layer_mm.replaceDataSource(config.scratch_folder,"SHAPEFILE_WORKSPACE","grid_lyr_flood")
        arcpy.CalculateAdjacentFields_cartography(grid_lyr_shp, "PageNumber")
        Setting.mxd_multi_flood.saveACopy(os.path.join(config.scratch_folder, "mxd_mm_flood.mxd"))
       
        if not os.path.exists(os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(os.path.join(config.report_path, 'PSRmaps', order_obj.number))

        for i in range(1,page):
            arcpy.SelectLayerByAttribute_management(Setting.grid_layer_mm, "NEW_SELECTION", ' "PageNumber" =  ' + str(i))
            Setting.df_mm_flood.extent = Setting.grid_layer_mm.getSelectedExtent(True)
            Setting.df_mm_flood.scale = Setting.df_mm_flood.scale * 1.1
            arcpy.SelectLayerByAttribute_management(Setting.grid_layer_mm, "CLEAR_SELECTION")

            title_text = arcpy.mapping.ListLayoutElements(Setting.mxd_multi_flood, "TEXT_ELEMENT", "title")[0]
            title_text.text = '      - Flood Hazard Zones - Page ' + str(i)
            title_text.elementPositionX = 0.5946
            arcpy.RefreshTOC()

            arcpy.mapping.ExportToJPEG(Setting.mxd_multi_flood, Setting.output_jpg_flood[0:-4]+str(i)+".jpg", "PAGE_LAYOUT", 480, 640, 75, "False", "24-BIT_TRUE_COLOR", 40)
          
            shutil.copy(Setting.output_jpg_flood[0:-4]+str(i)+".jpg", os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        
        del Setting.mxd_multi_flood
        del Setting.df_mm_flood
        
        ### update tables in DB
        for i in range(1,page):
            psr_obj.insert_map(order_obj.id, 'FLOOD', order_obj.number + '_US_FLOOD' + str(i) + '.jpg', i + 1)
        
    flood_panels = ''
    if (int(arcpy.GetCount_management(os.path.join(config.scratch_folder,"summary_flood.dbf")).getOutput(0))== 0):
        # no floodplain records selected....
        arcpy.AddMessage('      - No floodplain records are selected....')
        if (int(arcpy.GetCount_management(config.flood_panel_selectedby_order_shp).getOutput(0))== 0):
            # no panel available, means no data
            arcpy.AddMessage('      - no panels available in the area')
        else:
            # panel available, just not records in area
            in_rows = arcpy.SearchCursor(config.flood_panel_selectedby_order_shp)
            for in_row in in_rows:
                # arcpy.AddMessage('      - : ' + in_row.FIRM_PAN)    # panel number
                # arcpy.AddMessage('      - %s' % in_row.EFF_DATE)      # effective date
                flood_panels = flood_panels + in_row.FIRM_PAN+'(effective:' + str(in_row.EFF_DATE)[0:10]+') '
                del in_row
            del in_rows
        
        if len(flood_panels) > 0:
            eris_id += 1
            # arcpy.AddMessage('      - erisid for flood_panels is ' + str(eris_id))
            psr_obj.insert_order_detail(order_obj.id,eris_id, '10683')   
            psr_obj.insert_flex_rep(order_obj, eris_id, '10683', 2, 'N', 1, 'Available FIRM Panels in area: ', flood_panels)
        psr_obj.insert_map(order_obj.id, 'FLOOD', order_obj.number + '_US_FLOOD.jpg', 1)
    else:
        in_rows = arcpy.SearchCursor(config.flood_panel_selectedby_order_shp)
        for in_row in in_rows:
            # arcpy.AddMessage('      : ' + in_row.FIRM_PAN)      # panel number
            # arcpy.AddMessage('      - %s' %in_row.EFF_DATE)             # effective date
            flood_panels = flood_panels + in_row.FIRM_PAN+'(effective:' + str(in_row.EFF_DATE)[0:10]+') '
            del in_row
        del in_rows

        in_rows = arcpy.SearchCursor(os.path.join(config.scratch_folder,"summary_flood.dbf"))
        eris_id += 1
        psr_obj.insert_order_detail(order_obj.id , eris_id, '10683')
        psr_obj.insert_flex_rep(order_obj.id, eris_id, '10683', 2, 'N', 1, 'Available FIRM Panels in area: ', flood_panels)
        
        for in_row in in_rows:
            # note the column changed in summary dbf
            # arcpy.AddMessage('      : ' + in_row.ERIS_CLASS)    # eris label
            # arcpy.AddMessage('      : ' + (in_row.FIRST_FLD_))           # zone type
            # arcpy.AddMessage('      : '+ (in_row.FIRST_ZONE))           # subtype

            eris_id += 1
            config.flood_ids.append([in_row.ERIS_CLASS,eris_id])
            
            psr_obj.insert_order_detail(order_obj.id,eris_id, '10683')   
            psr_obj.insert_flex_rep(order_obj.id, eris_id, '10683', 2, 'S1', 1, 'Flood Zone ' + in_row.ERIS_CLASS, '')
            psr_obj.insert_flex_rep(order_obj.id, eris_id, '10683', 2, 'N', 2, 'Zone: ', in_row.FIRST_FLD_)
            psr_obj.insert_flex_rep(order_obj.id, eris_id, '10683', 2, 'N', 3, 'Zone subtype: ', in_row.FIRST_ZONE)
            del in_row
        del in_rows
        psr_obj.insert_map(order_obj.id, 'FLOOD', order_obj.number + '_US_FLOOD.jpg'+'.jpg', 1)
    end = timeit.default_timer()
    arcpy.AddMessage((' -- End generating PSR flood report. Duration:', round(end -start,4)))
Ejemplo n.º 10
0
def generate_multipage_report(order_obj, mxd_wetland, output_jpg_wetland,
                              df_wetland):
    grid_lyr_shp = os.path.join(config.scratch_folder, 'grid_lyr_wetland.shp')
    arcpy.GridIndexFeatures_cartography(grid_lyr_shp, config.order_buffer_shp,
                                        "", "", "", config.grid_size,
                                        config.grid_size)

    # part 1: the overview map
    # add grid layer
    grid_layer = arcpy.mapping.Layer(config.grid_lyr_file)
    grid_layer.replaceDataSource(config.scratch_folder, "SHAPEFILE_WORKSPACE",
                                 "grid_lyr_wetland")
    arcpy.mapping.AddLayer(df_wetland, grid_layer, "Top")

    df_wetland.extent = grid_layer.getExtent()
    df_wetland.scale = df_wetland.scale * 1.1

    mxd_wetland.saveACopy(
        os.path.join(config.scratch_folder, "mxd_wetland.mxd"))
    arcpy.mapping.ExportToJPEG(mxd_wetland, output_jpg_wetland, "PAGE_LAYOUT",
                               480, 640, 150, "False", "24-BIT_TRUE_COLOR", 85)

    if not os.path.exists(
            os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
        os.mkdir(os.path.join(config.report_path, 'PSRmaps', order_obj.number))
    shutil.copy(output_jpg_wetland,
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
    arcpy.AddMessage(
        '      - Wetland Output: %s' %
        os.path.join(config.report_path, 'PSRmaps', str(order_obj.number)))
    del mxd_wetland
    del df_wetland

    ### part 2: the data driven pages
    page = int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) + 1
    mxd_mm_wetland = arcpy.mapping.MapDocument(config.mxd_mm_file_wetland)
    df_mm_wetland = arcpy.mapping.ListDataFrames(mxd_mm_wetland, "big")[0]
    df_mm_wetland.spatialReference = order_obj.spatial_ref_pcs

    utility.add_layer_to_mxd("order_buffer", df_mm_wetland,
                             config.buffer_lyr_file, 1.1)
    utility.add_layer_to_mxd("order_geometry_pcs", df_mm_wetland,
                             config.order_geom_lyr_file, 1)

    grid_layer_mm = arcpy.mapping.ListLayers(mxd_mm_wetland, "Grid",
                                             df_mm_wetland)[0]
    grid_layer_mm.replaceDataSource(config.scratch_folder,
                                    "SHAPEFILE_WORKSPACE", "grid_lyr_wetland")
    arcpy.CalculateAdjacentFields_cartography(grid_lyr_shp, "PageNumber")
    mxd_mm_wetland.saveACopy(
        os.path.join(config.scratch_folder, "grid_layer_mm.mxd"))

    for i in range(
            1,
            int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) + 1):
        arcpy.SelectLayerByAttribute_management(grid_layer_mm, "NEW_SELECTION",
                                                ' "PageNumber" =  ' + str(i))
        df_mm_wetland.extent = grid_layer_mm.getSelectedExtent(True)
        df_mm_wetland.scale = df_mm_wetland.scale * 1.1
        arcpy.SelectLayerByAttribute_management(grid_layer_mm,
                                                "CLEAR_SELECTION")

        titleTextE = arcpy.mapping.ListLayoutElements(mxd_mm_wetland,
                                                      "TEXT_ELEMENT",
                                                      "title")[0]
        titleTextE.text = "Wetland Type - Page " + str(i)
        titleTextE.elementPositionX = 0.468
        arcpy.RefreshTOC()

        arcpy.mapping.ExportToJPEG(mxd_mm_wetland,
                                   output_jpg_wetland[0:-4] + str(i) + ".jpg",
                                   "PAGE_LAYOUT", 480, 640, 150, "False",
                                   "24-BIT_TRUE_COLOR", 85)
        if not os.path.exists(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        shutil.copy(
            output_jpg_wetland[0:-4] + str(i) + ".jpg",
            os.path.join(config.report_path, 'PSRmaps', order_obj.number))
    del mxd_mm_wetland
    del df_mm_wetland
Ejemplo n.º 11
0
#-------------------------------------------------------------------------------
# Name:        module1
# Purpose:
#
# Author:      LerchM
#
# Created:     09.07.2015
# Copyright:   (c) LerchM 2015
# Licence:     PNE Wind internal
#-------------------------------------------------------------------------------

import arcpy, os
from arcpy import env

mxd = arcpy.mapping.MapDocument(
    r"X:\01_Projekte_Deutschland\PR Nordrhein-Westfalen\Rhein-Sieg-Kreis\150702_Rhein-Sieg-Kreis_tmp.mxd"
)
df = arcpy.mapping.ListDataFrames(mxd)[0]

arcpy.env.workspace = r"X:\01_Projekte_Deutschland\PR Nordrhein-Westfalen\Rhein-Sieg-Kreis\01 - Geodatabase\Rhein_Sieg_Kreis.gdb"
arcpy.env.overwriteOutput = True
outFC = "grid_index"
inFC = "Rhein_Sieg_Kreisgrenze_150702"
width = 10000
height = 10000
arcpy.GridIndexFeatures_cartography(outFC, inFC, "INTERSECTFEATURE", "", "",
                                    width, height)
Ejemplo n.º 12
0
def create_map(order_obj):
    point = arcpy.Point()
    array = arcpy.Array()
    feature_list = []
    width = arcpy.Describe(config.order_buffer_shp).extent.width / 2
    height = arcpy.Describe(config.order_buffer_shp).extent.height / 2

    if (width > 662 or height > 662):
        if (width / height > 1):
            # buffer has a wider shape
            width = width * 1.1
            height = width

        else:
            # buffer has a vertically elonged shape
            height = height * 1.1
            width = height
    else:
        width = 662 * 1.1
        height = 662 * 1.1
    width = width + 6400  #add 2 miles to each side, for multipage soil
    height = height + 6400  #add 2 miles to each side, for multipage soil
    xCentroid = (arcpy.Describe(config.order_buffer_shp).extent.XMax +
                 arcpy.Describe(config.order_buffer_shp).extent.XMin) / 2
    yCentroid = (arcpy.Describe(config.order_buffer_shp).extent.YMax +
                 arcpy.Describe(config.order_buffer_shp).extent.YMin) / 2
    point.X = xCentroid - width
    point.Y = yCentroid + height
    array.add(point)
    point.X = xCentroid + width
    point.Y = yCentroid + height
    array.add(point)
    point.X = xCentroid + width
    point.Y = yCentroid - height
    array.add(point)
    point.X = xCentroid - width
    point.Y = yCentroid - height
    array.add(point)
    point.X = xCentroid - width
    point.Y = yCentroid + height
    array.add(point)
    feat = arcpy.Polygon(array, order_obj.spatial_ref_pcs)
    array.removeAll()
    feature_list.append(feat)

    frame_soil = os.path.join(config.scratch_folder, "frame_soil.shp")
    arcpy.CopyFeatures_management(feature_list, frame_soil)
    arcpy.SelectLayerByLocation_management(config.soil_lyr, 'intersect',
                                           frame_soil)
    arcpy.CopyFeatures_management(config.soil_lyr,
                                  config.soil_selectedby_frame)

    # add another column to soil_disp just for symbology purpose
    arcpy.AddField_management(
        os.path.join(config.scratch_folder, config.soil_selectedby_frame),
        "FIDCP", "TEXT", "", "", "", "", "NON_NULLABLE", "REQUIRED", "")
    arcpy.CalculateField_management(
        os.path.join(config.scratch_folder, config.soil_selectedby_frame),
        'FIDCP', '!FID!', "PYTHON_9.3")

    mxd_soil = arcpy.mapping.MapDocument(config.mxd_file_soil)
    df_soil = arcpy.mapping.ListDataFrames(mxd_soil, "*")[0]
    df_soil.spatialReference = order_obj.spatial_ref_pcs

    ssurgo_lyr = arcpy.mapping.ListLayers(mxd_soil, "SSURGO*", df_soil)[0]
    ssurgo_lyr.replaceDataSource(config.scratch_folder, "SHAPEFILE_WORKSPACE",
                                 'soil_selectedby_frame')
    ssurgo_lyr.symbology.addAllValues()
    config.soil_lyr = ssurgo_lyr

    utility.add_layer_to_mxd("order_buffer", df_soil, config.buffer_lyr_file,
                             1.1)
    utility.add_layer_to_mxd("order_geometry_pcs", df_soil,
                             config.order_geom_lyr_file, 1)
    arcpy.RefreshActiveView()
    output_jpg_soil = config.output_jpg(order_obj, config.Report_Type.soil)
    if not config.if_multi_page:  # single-page
        mxd_soil.saveACopy(os.path.join(config.scratch_folder, "mxd_soil.mxd"))
        arcpy.mapping.ExportToJPEG(mxd_soil, output_jpg_soil, "PAGE_LAYOUT",
                                   480, 640, 150, "False", "24-BIT_TRUE_COLOR",
                                   85)
        if not os.path.exists(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        shutil.copy(
            output_jpg_soil,
            os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        arcpy.AddMessage(
            '      - output jpg image %s' %
            os.path.join(config.report_path, 'PSRmaps', order_obj.number,
                         os.path.basename(output_jpg_soil)))
        del mxd_soil
        del df_soil
    else:  # multipage
        grid_lyr_shp = os.path.join(config.scratch_folder, 'grid_lyr_soil.shp')
        arcpy.GridIndexFeatures_cartography(grid_lyr_shp,
                                            config.order_buffer_shp, "", "",
                                            "", config.grid_size,
                                            config.grid_size)
        # part 1: the overview map
        # add grid layer
        grid_layer = arcpy.mapping.Layer(config.grid_lyr_file)
        grid_layer.replaceDataSource(config.scratch_folder,
                                     "SHAPEFILE_WORKSPACE", "grid_lyr_soil")
        arcpy.mapping.AddLayer(df_soil, grid_layer, "Top")

        df_soil.extent = grid_layer.getExtent()
        df_soil.scale = df_soil.scale * 1.1

        mxd_soil.saveACopy(os.path.join(config.scratch_folder, "mxd_soil.mxd"))
        arcpy.mapping.ExportToJPEG(mxd_soil, output_jpg_soil, "PAGE_LAYOUT",
                                   480, 640, 150, "False", "24-BIT_TRUE_COLOR",
                                   85)
        if not os.path.exists(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        shutil.copy(
            output_jpg_soil,
            os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        arcpy.AddMessage(
            '      - output jpg image page 1: %s' %
            os.path.join(config.report_path, 'PSRmaps', order_obj.number,
                         os.path.basename(output_jpg_soil)))
        del mxd_soil
        del df_soil

        # part 2: the data driven pages maps
        page = int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) + 1
        mxd_mm_soil = arcpy.mapping.MapDocument(config.mxd_mm_file_soil)

        df_mm_soil = arcpy.mapping.ListDataFrames(mxd_mm_soil, "*")[0]
        df_mm_soil.spatialReference = order_obj.spatial_ref_pcs

        utility.add_layer_to_mxd("order_buffer", df_mm_soil,
                                 config.buffer_lyr_file, 1.1)
        utility.add_layer_to_mxd("order_geometry_pcs", df_mm_soil,
                                 config.order_geom_lyr_file, 1)

        ssurgo_lyr = arcpy.mapping.ListLayers(mxd_mm_soil, "SSURGO*",
                                              df_mm_soil)[0]
        ssurgo_lyr.replaceDataSource(config.scratch_folder,
                                     "SHAPEFILE_WORKSPACE",
                                     "soil_selectedby_frame")
        ssurgo_lyr.symbology.addAllValues()
        config.soil_lyr = ssurgo_lyr

        grid_layer_mm = arcpy.mapping.ListLayers(mxd_mm_soil, "Grid",
                                                 df_mm_soil)[0]
        grid_layer_mm.replaceDataSource(config.scratch_folder,
                                        "SHAPEFILE_WORKSPACE", "grid_lyr_soil")
        arcpy.CalculateAdjacentFields_cartography(grid_lyr_shp, 'PageNumber')
        mxd_mm_soil.saveACopy(
            os.path.join(config.scratch_folder, "mxd_mm_soil.mxd"))

        for i in range(
                1,
                int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) + 1):
            arcpy.SelectLayerByAttribute_management(
                grid_layer_mm, "NEW_SELECTION", ' "PageNumber" =  ' + str(i))
            df_mm_soil.extent = grid_layer_mm.getSelectedExtent(True)
            df_mm_soil.scale = df_mm_soil.scale * 1.1
            arcpy.SelectLayerByAttribute_management(grid_layer_mm,
                                                    "CLEAR_SELECTION")

            title_text = arcpy.mapping.ListLayoutElements(
                mxd_mm_soil, "TEXT_ELEMENT", "title")[0]
            title_text.text = "SSURGO Soils - Page " + str(i)
            title_text.elementPositionX = 0.6156
            arcpy.RefreshTOC()

            arcpy.mapping.ExportToJPEG(mxd_mm_soil,
                                       output_jpg_soil[0:-4] + str(i) + ".jpg",
                                       "PAGE_LAYOUT", 480, 640, 150, "False",
                                       "24-BIT_TRUE_COLOR", 85)
            if not os.path.exists(
                    os.path.join(config.report_path, 'PSRmaps',
                                 order_obj.number)):
                os.mkdir(
                    os.path.join(config.report_path, 'PSRmaps',
                                 order_obj.number))
            shutil.copy(
                output_jpg_soil[0:-4] + str(i) + ".jpg",
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        del mxd_mm_soil
        del df_mm_soil
        ### Update DB if multiple pages
        psr_obj = models.PSR()
        for i in range(1, page):
            psr_obj.insert_map(order_obj.id, 'SOIL',
                               order_obj.number + str(i) + '.jpg', i + 1)

    eris_id = 0
    ### Udpate DB
    psr_obj = models.PSR()
    for map_unit in config.report_data:
        eris_id = eris_id + 1
        mu_key = str(map_unit['Mukey'])
        config.soil_ids.append([map_unit['Musym'], eris_id])
        psr_obj.insert_order_detail(order_obj.id, eris_id, mu_key)
        psr_obj.insert_flex_rep(
            order_obj.id, eris_id, '9334', 2, 'S1', 1, 'Map Unit ' +
            map_unit['Musym'] + " (%s)" % map_unit["Soil_Percent"], '')
        psr_obj.insert_flex_rep(order_obj.id, eris_id, '9334', 2, 'N', 2,
                                'Map Unit Name:', map_unit['Map Unit Name'])
        if len(map_unit) < 6:  #for Water, Urbanland and Gravel Pits
            psr_obj.insert_flex_rep(
                order_obj.id, eris_id, '9334', 2, 'N', 3,
                'No more attributes available for this map unit', '')
        else:  # not do for Water or urban land
            psr_obj.insert_flex_rep(order_obj.id, eris_id, '9334', 2, 'N', 3,
                                    'Bedrock Depth - Min:',
                                    map_unit['Bedrock Depth - Min'])
            psr_obj.insert_flex_rep(order_obj.id, eris_id, '9334', 2, 'N', 4,
                                    'Watertable Depth - Annual Min:',
                                    map_unit['Watertable Depth - Annual Min'])
            if (map_unit['Drainage Class - Dominant'] == '-99'):
                psr_obj.insert_flex_rep(order_obj.id, eris_id, '9334', 2, 'N',
                                        5, 'Drainage Class - Dominant:',
                                        'null')
            else:
                psr_obj.insert_flex_rep(order_obj.id, eris_id, '9334', 2, 'N',
                                        5, 'Drainage Class - Dominant:',
                                        map_unit['Drainage Class - Dominant'])
            if (map_unit['Hydrologic Group - Dominant'] == '-99'):
                psr_obj.insert_flex_rep(order_obj.id, eris_id, '9334', 2, 'N',
                                        6, 'Hydrologic Group - Dominant:',
                                        'null')
            else:
                psr_obj.insert_flex_rep(
                    order_obj.id, eris_id, '9334', 2, 'N', 6,
                    'Hydrologic Group - Dominant:',
                    map_unit['Hydrologic Group - Dominant'] + ' - ' +
                    config.hydrologic_dict[
                        map_unit['Hydrologic Group - Dominant']])
            psr_obj.insert_flex_rep(order_obj.id, eris_id, '9334', 2, 'N', 7,
                                    'Major components are printed below', '')

            k = 7
            if 'component' in map_unit.keys():
                k = k + 1
                for comp in map_unit['component']:
                    psr_obj.insert_flex_rep(order_obj.id, eris_id, '9334', 2,
                                            'S2', k, comp[0][0], '')
                    for i in range(1, len(comp)):
                        k = k + 1
                        psr_obj.insert_flex_rep(order_obj.id, eris_id, '9334',
                                                2, 'S3', k, comp[i][0],
                                                comp[i][1])
    psr_obj.insert_map(order_obj.id, 'SOIL', order_obj.number + 'US_SOIL.jpg',
                       1)
Ejemplo n.º 13
0
def exportPDFBy_ZB(ZB, layer_target, layer_other, mxd):

    layer_target.definitionQuery = "ZB = '" + ZB + "'"
    layer_other.definitionQuery = "ZB <> '" + ZB + "'"
    arcpy.SelectLayerByAttribute_management(r"数据\地块-当前组", "NEW_SELECTION",
                                            "[ZB] = '" + ZB + "'")
    df = arcpy.mapping.ListDataFrames(mxd)[0]
    df.zoomToSelectedFeatures()
    if df.scale < MaxScale:
        df.scale = MaxScale
    else:
        df.scale = getScale(df.scale)
    arcpy.SelectLayerByAttribute_management(r"数据\地块-当前组", "CLEAR_SELECTION")
    mxdPageSize = mxd.pageSize
    global MinScale
    WH = getWidthHeight(mxd)

    global param
    setTitleText(mxd, param[0] + ZB + param[1])
    arcpy.RefreshTOC()
    arcpy.RefreshActiveView()
    global PDFOutPath

    WidthHeight = WH[0] / WH[1]
    if mxdPageSize[0] / mxdPageSize[1] >= 1 and WidthHeight >= 1:
        #横版
        if df.scale > MinScale:
            # 进入分幅模式
            tempGird = arcpy.CreateScratchName()
            arcpy.Delete_management(tempGird)
            arcpy.Delete_management(tempGird)

            arcpy.GridIndexFeatures_cartography(
                tempGird,
                r"数据\地块-当前组",
                "",
                "",
                "",
                (mxdPageSize[0] - 5) / 100 * (MinScale - 400),
                (mxdPageSize[1] - 5) / 100 * (MinScale - 400),
            )
            layers = arcpy.mapping.ListLayers(mxd)
            grid_layer = None
            for layer in layers:
                tgname = tempGird[tempGird.rindex("\\") + 1:]
                if layer.name == tgname:
                    grid_layer = layer
                    break
            cursors = arcpy.SearchCursor(grid_layer.dataSource)
            list_PageNumber = []
            for cursor in cursors:
                list_PageNumber.append(cursor.getValue("PageNumber"))
            for pn in list_PageNumber:
                grid_layer.definitionQuery = "PageNumber = " + str(pn)
                arcpy.SelectLayerByAttribute_management(
                    tgname, "NEW_SELECTION", "PageNumber = " + str(pn))
                df.zoomToSelectedFeatures()
                arcpy.SelectLayerByAttribute_management(
                    tgname, "CLEAR_SELECTION")
                grid_layer.visible = False
                df.scale = MinScale
                strpn = str(pn)
                while (len(strpn)) < 3:
                    strpn = "0" + strpn
                setTitleText(mxd, param[0] + ZB + param[1] + strpn)
                arcpy.RefreshTOC()
                arcpy.RefreshActiveView()
                arcpy.mapping.ExportToPDF(
                    mxd, PDFOutPath + "\\" + param[0] + ZB + param[1] + strpn +
                    '.pdf', "PAGE_LAYOUT", 0, 0, 300, "NORMAL")
                mxd.saveACopy(PDFOutPath + "\\" + param[0] + ZB + param[1] +
                              strpn + '.mxd')
                tempdf = arcpy.mapping.ListDataFrames(mxd)[0]
                grid_layer.visible = True
            arcpy.Delete_management(tempGird)
            arcpy.Delete_management(tempGird)
            arcpy.mapping.RemoveLayer(tempdf, grid_layer)

        else:
            #直接出图
            arcpy.mapping.ExportToPDF(
                mxd, PDFOutPath + "\\" + param[0] + ZB + param[1] + '.pdf',
                "PAGE_LAYOUT", 0, 0, 300, "NORMAL")
            mxd.saveACopy(PDFOutPath + "\\" + param[0] + ZB + param[1] +
                          '.mxd')

    if mxdPageSize[0] / mxdPageSize[1] < 1 and WidthHeight < 1:
        if df.scale > MinScale:
            # 进入分幅模式
            tempGird = arcpy.CreateScratchName()
            arcpy.Delete_management(tempGird)
            arcpy.Delete_management(tempGird)

            arcpy.GridIndexFeatures_cartography(
                tempGird,
                r"数据\地块-当前组",
                "",
                "",
                "",
                (mxdPageSize[0] - 5) / 100 * (MinScale - 400),
                (mxdPageSize[1] - 5) / 100 * (MinScale - 400),
            )
            layers = arcpy.mapping.ListLayers(mxd)
            grid_layer = None
            for layer in layers:
                tgname = tempGird[tempGird.rindex("\\") + 1:]
                if layer.name == tgname:
                    grid_layer = layer
                    break
            cursors = arcpy.SearchCursor(grid_layer.dataSource)
            list_PageNumber = []
            for cursor in cursors:
                list_PageNumber.append(cursor.getValue("PageNumber"))
            for pn in list_PageNumber:
                grid_layer.definitionQuery = "PageNumber = " + str(pn)
                arcpy.SelectLayerByAttribute_management(
                    tgname, "NEW_SELECTION", "PageNumber = " + str(pn))
                df.zoomToSelectedFeatures()
                arcpy.SelectLayerByAttribute_management(
                    tgname, "CLEAR_SELECTION")
                grid_layer.visible = False
                df.scale = MinScale
                strpn = str(pn)
                while (len(strpn)) < 3:
                    strpn = "0" + strpn
                setTitleText(mxd, param[0] + ZB + param[1] + strpn)
                arcpy.RefreshTOC()
                arcpy.RefreshActiveView()
                arcpy.mapping.ExportToPDF(
                    mxd, PDFOutPath + "\\" + param[0] + ZB + param[1] + strpn +
                    '.pdf', "PAGE_LAYOUT", 0, 0, 300, "NORMAL")
                mxd.saveACopy(PDFOutPath + "\\" + param[0] + ZB + param[1] +
                              strpn + '.mxd')
                tempdf = arcpy.mapping.ListDataFrames(mxd)[0]
                grid_layer.visible = True
            arcpy.Delete_management(tempGird)
            arcpy.Delete_management(tempGird)
            arcpy.mapping.RemoveLayer(tempdf, grid_layer)
        else:
            arcpy.mapping.ExportToPDF(
                mxd, PDFOutPath + "\\" + param[0] + ZB + param[1] + '.pdf',
                "PAGE_LAYOUT", 0, 0, 300, "NORMAL")
            mxd.saveACopy(PDFOutPath + "\\" + param[0] + ZB + param[1] +
                          '.mxd')
Ejemplo n.º 14
0
def generate_ogw_report(order_obj):
    arcpy.AddMessage(
        '  -- Start generating PSR Oil, Gas and Water wells map report...')
    start = timeit.default_timer()
    ### set scratch folder
    arcpy.env.workspace = config.scratch_folder
    arcpy.env.overwriteOutput = True
    centre_point = order_obj.geometry.trueCentroid
    elevation = psr_utility.get_elevation(centre_point.X, centre_point.Y)
    if elevation != None:
        centre_point.Z = float(elevation)
    ### create order geometry center shapefile
    order_rows = arcpy.SearchCursor(config.order_geometry_pcs_shp)
    point = arcpy.Point()
    array = arcpy.Array()
    feature_list = []
    arcpy.CreateFeatureclass_management(
        config.scratch_folder, os.path.basename(config.order_center_pcs),
        "POINT", "", "DISABLED", "DISABLED", order_obj.spatial_ref_pcs)
    arcpy.AddField_management(config.order_center_pcs, "Site_z", "DOUBLE",
                              "12", "6", "", "", "NULLABLE", "NON_REQUIRED",
                              "")
    insert_cursor = arcpy.InsertCursor(config.order_center_pcs)
    feat = insert_cursor.newRow()
    for order_row in order_rows:
        # Set X and Y for start and end points
        geometry = order_row.SHAPE
        geometry_gcs = geometry.projectAs(order_obj.spatial_ref_gcs)
        site_elevation = psr_utility.get_elevation(geometry_gcs.trueCentroid.X,
                                                   geometry_gcs.trueCentroid.Y)
        point.X = geometry.trueCentroid.X
        point.Y = geometry.trueCentroid.Y
        array.add(point)
        center_point = arcpy.Multipoint(array)
        array.removeAll()
        feature_list.append(center_point)
        feat.shape = point
        feat.Site_Z = float(site_elevation)
        insert_cursor.insertRow(feat)
    del feat
    del insert_cursor
    del order_row
    del order_rows
    del point
    del array

    output_jpg_wells = config.output_jpg(order_obj, config.Report_Type.wells)
    if '10685' not in order_obj.psr.search_radius.keys():
        arcpy.AddMessage('      -- OGW search radius is not availabe')
        return
    config.buffer_dist_ogw = str(
        order_obj.psr.search_radius['10685']) + ' MILES'
    ds_oid_wells_max_radius = '10093'  # 10093 is a federal source, PWSV
    ds_oid_wells = []
    for key in order_obj.psr.search_radius:
        if key not in [
                '9334', '10683', '10684', '10685', '10688', '10689', '10695',
                '10696'
        ]:  #10695 is US topo, 10696 is HTMC, 10688 and 10689 are radons
            ds_oid_wells.append(key)
            if (order_obj.psr.search_radius[key] >
                    order_obj.psr.search_radius[ds_oid_wells_max_radius]):
                ds_oid_wells = key

    merge_list = []
    for ds_oid in ds_oid_wells:
        buffer_wells_fc = os.path.join(config.scratch_folder,
                                       "order_buffer_" + str(ds_oid) + ".shp")
        arcpy.Buffer_analysis(
            config.order_geometry_pcs_shp, buffer_wells_fc,
            str(order_obj.psr.search_radius[ds_oid]) + " MILES")
        wells_clip = os.path.join(config.scratch_folder,
                                  'wells_clip_' + str(ds_oid) + '.shp')
        arcpy.Clip_analysis(config.eris_wells, buffer_wells_fc, wells_clip)
        arcpy.Select_analysis(
            wells_clip,
            os.path.join(config.scratch_folder,
                         'wells_selected_' + str(ds_oid) + '.shp'),
            "DS_OID =" + str(ds_oid))
        merge_list.append(
            os.path.join(config.scratch_folder,
                         'wells_selected_' + str(ds_oid) + '.shp'))
    arcpy.Merge_management(merge_list, config.wells_merge)
    del config.eris_wells

    # Calculate Distance with integration and spatial join- can be easily done with Distance tool along with direction if ArcInfo or Advanced license
    wells_merge_pcs = os.path.join(config.scratch_folder,
                                   "wells_merge_pcs.shp")
    arcpy.Project_management(config.wells_merge, wells_merge_pcs,
                             order_obj.spatial_ref_pcs)
    arcpy.Integrate_management(wells_merge_pcs, ".5 Meters")

    # Add distance to selected wells
    arcpy.SpatialJoin_analysis(wells_merge_pcs, config.order_geometry_pcs_shp,
                               config.wells_sj, "JOIN_ONE_TO_MANY", "KEEP_ALL",
                               "#", "CLOSEST", "5000 Kilometers",
                               "Distance")  # this is the reported distance
    arcpy.SpatialJoin_analysis(
        config.wells_sj, config.order_center_pcs, config.wells_sja,
        "JOIN_ONE_TO_MANY", "KEEP_ALL", "#", "CLOSEST", "5000 Kilometers",
        "Dist_cent")  # this is used for mapkey calculation
    if int(
            arcpy.GetCount_management(os.path.join(
                config.wells_merge)).getOutput(0)) != 0:
        arcpy.AddMessage('      - Water Wells section, exists water wells')
        add_fields()
        with arcpy.da.UpdateCursor(config.wells_sja,
                                   ['X', 'Y', 'Elevation']) as update_cursor:
            for row in update_cursor:
                row[2] = psr_utility.get_elevation(row[0], row[1])
                update_cursor.updateRow(row)
        # generate map key
        gis_utility.generate_map_key(config.wells_sja)
        # Add Direction to ERIS sites
        add_direction()

        arcpy.Select_analysis(config.wells_sja, config.wells_final,
                              '"MapKeyTot" = 1')
        arcpy.Sort_management(config.wells_final, config.wells_display,
                              [["MapKeyLoc", "ASCENDING"]])

        arcpy.AddField_management(config.wells_display, "Ele_Diff", "DOUBLE",
                                  "12", "6", "", "", "NULLABLE",
                                  "NON_REQUIRED", "")
        arcpy.CalculateField_management(config.wells_display, 'Ele_Diff',
                                        '!Elevation!-!Site_z!', "PYTHON_9.3",
                                        "")

        arcpy.AddField_management(config.wells_display, "Elev_Rank", "SHORT",
                                  "12", "6", "", "", "NULLABLE",
                                  "NON_REQUIRED", "")
        # categorize elevation for symbology
        elevation_ranking()
        ## create a map with water wells and ogw wells
        mxd_wells = arcpy.mapping.MapDocument(config.mxd_file_wells)
        df_wells = arcpy.mapping.ListDataFrames(mxd_wells, "*")[0]
        df_wells.spatialReference = order_obj.spatial_ref_pcs

        lyr = arcpy.mapping.ListLayers(mxd_wells, "wells", df_wells)[0]
        lyr.replaceDataSource(config.scratch_folder, "SHAPEFILE_WORKSPACE",
                              "wells_display")
    else:
        arcpy.AddMessage('  - WaterWells section, no water wells exists')
        mxd_wells = arcpy.mapping.MapDocument(config.mxd_file_wells)
        df_wells = arcpy.mapping.ListDataFrames(mxd_wells, "*")[0]
        df_wells.spatialReference = order_obj.spatial_ref_pcs
    for item in ds_oid_wells:
        psr_utility.add_layer_to_mxd("order_buffer_" + str(item), df_wells,
                                     config.buffer_lyr_file, 1.1)
    psr_utility.add_layer_to_mxd("order_geometry_pcs", df_wells,
                                 config.order_geom_lyr_file, 1)
    # create single-page
    if not config.if_multi_page or int(
            arcpy.GetCount_management(config.wells_sja).getOutput(0)) == 0:
        mxd_wells.saveACopy(
            os.path.join(config.scratch_folder, "mxd_wells.mxd"))
        arcpy.mapping.ExportToJPEG(mxd_wells, output_jpg_wells, "PAGE_LAYOUT",
                                   480, 640, 150, "False", "24-BIT_TRUE_COLOR",
                                   85)
        if not os.path.exists(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        shutil.copy(
            output_jpg_wells,
            os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        # arcpy.AddMessage('      - output jpg image: %s' % os.path.join(config.report_path, 'PSRmaps', order_obj.number,os.path.basename(output_jpg_wells)))
        del mxd_wells
        del df_wells
    else:  # multipage
        grid_lyr_shp = os.path.join(config.scratch_folder,
                                    'grid_lyr_wells.shp')
        #note the tool takes featureclass name only, not the full path
        arcpy.GridIndexFeatures_cartography(
            grid_lyr_shp,
            os.path.join(config.scratch_folder,
                         "order_buffer_" + ds_oid_wells_max_radius + '.shp'),
            "", "", "", config.grid_size, config.grid_size)
        # part 1: the overview map
        #add grid layer
        grid_layer = arcpy.mapping.Layer(config.grid_lyr_file)
        grid_layer.replaceDataSource(config.scratch_folder,
                                     "SHAPEFILE_WORKSPACE", "grid_lyr_wells")
        arcpy.mapping.AddLayer(df_wells, grid_layer, "Top")
        # turn the site label off
        well_lyr = arcpy.mapping.ListLayers(mxd_wells, "wells", df_wells)[0]
        well_lyr.showLabels = False
        df_wells.extent = grid_layer.getExtent()
        df_wells.scale = df_wells.scale * 1.1
        mxd_wells.saveACopy(
            os.path.join(config.scratch_folder, "mxd_wells.mxd"))
        arcpy.mapping.ExportToJPEG(mxd_wells, output_jpg_wells, "PAGE_LAYOUT",
                                   480, 640, 150, "False", "24-BIT_TRUE_COLOR",
                                   85)
        if not os.path.exists(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        shutil.copy(
            output_jpg_wells,
            os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        arcpy.AddMessage(
            '      - output jpg image page 1: %s' %
            os.path.join(config.report_path, 'PSRmaps', order_obj.number,
                         os.path.basename(output_jpg_wells)))
        del mxd_wells
        del df_wells
        # part 2: the data driven pages
        page = int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) + 1
        mxd_mm_wells = arcpy.mapping.MapDocument(config.mxd_mm_file_wells)
        df_mm_wells = arcpy.mapping.ListDataFrames(mxd_mm_wells)[0]
        df_mm_wells.spatialReference = order_obj.spatial_ref_pcs
        for item in ds_oid_wells:
            psr_utility.add_layer_to_mxd("order_buffer_" + str(item),
                                         df_mm_wells, config.buffer_lyr_file,
                                         1.1)
        psr_utility.add_layer_to_mxd("order_geometry_pcs", df_mm_wells,
                                     config.order_geom_lyr_file, 1)

        grid_layer_mm = arcpy.mapping.ListLayers(mxd_mm_wells, "Grid",
                                                 df_mm_wells)[0]
        grid_layer_mm.replaceDataSource(config.scratch_folder,
                                        "SHAPEFILE_WORKSPACE",
                                        "grid_lyr_wells")
        arcpy.CalculateAdjacentFields_cartography(grid_lyr_shp, 'PageNumber')
        lyr = arcpy.mapping.ListLayers(
            mxd_mm_wells, "wells",
            df_mm_wells)[0]  #"wells" or "Wells" doesn't seem to matter
        lyr.replaceDataSource(config.scratch_folder, "SHAPEFILE_WORKSPACE",
                              "wells_display")

        for i in range(
                1,
                int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) + 1):
            arcpy.SelectLayerByAttribute_management(
                grid_layer_mm, "NEW_SELECTION", ' "PageNumber" =  ' + str(i))
            df_mm_wells.extent = grid_layer_mm.getSelectedExtent(True)
            df_mm_wells.scale = df_mm_wells.scale * 1.1
            arcpy.SelectLayerByAttribute_management(grid_layer_mm,
                                                    "CLEAR_SELECTION")
            title_text = arcpy.mapping.ListLayoutElements(
                mxd_mm_wells, "TEXT_ELEMENT", "MainTitleText")[0]
            title_text.text = "Wells & Additional Sources - Page " + str(i)
            title_text.elementPositionX = 0.6438
            arcpy.RefreshTOC()
            arcpy.mapping.ExportToJPEG(
                mxd_mm_wells, output_jpg_wells[0:-4] + str(i) + ".jpg",
                "PAGE_LAYOUT", 480, 640, 150, "False", "24-BIT_TRUE_COLOR", 85)
            if not os.path.exists(
                    os.path.join(config.report_path, 'PSRmaps',
                                 order_obj.number)):
                os.mkdir(
                    os.path.join(config.report_path, 'PSRmaps',
                                 order_obj.number))
            shutil.copy(
                output_jpg_wells[0:-4] + str(i) + ".jpg",
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        del mxd_mm_wells
        del df_mm_wells
        ### Save wells data in database
        save_wells_to_db(order_obj, page)

    end = timeit.default_timer()
    arcpy.AddMessage(
        (' -- End generating PSR Oil, Gas and Water wells report. Duration:',
         round(end - start, 4)))
Ejemplo n.º 15
0
fields = "Area_Biome"
#Open loop:
for fc in fclist:
    #set to overwrite existing outputs
    arcpy.env.workspace = outpath
    arcpy.env.overwriteOutput = True
    # set names of source files, out files and path directories
    out_feature_string = str(fc[:-4]) + "_fishnet"
    out_feature_string_ = out_feature_string.replace(" ", "_")
    out_feature_class = os.path.join(outpath, out_feature_string_)
    in_features = os.path.join(inpath, str(fc))
    out_table = os.path.join(out_table_dir, str(fc[:-4]).replace(" ", "_"))
    #Make fishnet based on biome layer extent and set output projection as Mollweide
    try:
        arcpy.GridIndexFeatures_cartography(
            out_feature_class, in_features, intersect_feature, use_page_unit,
            scale, polygon_width, polygon_height, origin_coord, number_rows,
            number_columns, starting_page_number, label_from_origin)
        print "creating fishnet " "%s" % out_feature_class + " from " + "%s" % in_features
    except Exception:
        e = sys.exc_info()[1]
        print(e.args[0])
    arcpy.AddGeometryAttributes_management(out_feature_class + ".shp",
                                           Geometry_Properties, Length_Unit,
                                           Area_Unit, Coordinate_System)
    print "geometry attribute added :  " "%s" % Geometry_Properties + " in " + "%s" % Area_Unit
    arcpy.DeleteField_management(out_feature_class + ".shp", drop_fields)
    print "deleting fields :  " "%s" % drop_fields
##    arcpy.TabulateIntersection_analysis(out_feature_class + ".shp",zone_fields,in_features,out_table,class_fields,sum_fields,xy_tolerance,out_units)
##    print "calculating area of biome per grid cell :  " "%s" % out_table
##    # changing field precision of area and percentage fields by creating new field, copying numbers in original field and deleting original fields
##    arcpy.AddField_management(out_table, "New_Area", "FLOAT")
Ejemplo n.º 16
0
def generate_geology_report(order_obj):
    arcpy.AddMessage('  -- Start generating PSR geology report...')
    start = timeit.default_timer()
    ### set scratch folder
    arcpy.env.workspace = config.scratch_folder
    arcpy.env.overwriteOutput = True
    output_jpg_geology = config.output_jpg(order_obj,
                                           config.Report_Type.geology)
    page = 1
    if '10685' not in order_obj.psr.search_radius.keys():
        arcpy.AddMessage('      -- Geology search radius is not availabe')
        return
    config.buffer_dist_geology = str(
        order_obj.psr.search_radius['10685']) + ' MILES'

    ### create buffer map based on order geometry
    arcpy.Buffer_analysis(config.order_geometry_pcs_shp,
                          config.order_buffer_shp, config.buffer_dist_geology)

    arcpy.MakeFeatureLayer_management(config.data_geology, 'geology_lyr')
    arcpy.SelectLayerByLocation_management('geology_lyr', 'intersect',
                                           config.order_buffer_shp)
    arcpy.CopyFeatures_management('geology_lyr',
                                  config.geology_selectedby_order_shp)

    arcpy.Statistics_analysis(
        config.geology_selectedby_order_shp,
        os.path.join(config.scratch_folder, "summary_geology.dbf"),
        [['UNIT_NAME', 'FIRST'], ['UNIT_AGE', 'FIRST'], ['ROCKTYPE1', 'FIRST'],
         ['ROCKTYPE2', 'FIRST'], ['UNITDESC', 'FIRST'],
         ['ERIS_KEY_1', 'FIRST']], 'ORIG_LABEL')
    arcpy.Sort_management(
        os.path.join(config.scratch_folder, "summary_geology.dbf"),
        os.path.join(config.scratch_folder, "summary_sorted_geol.dbf"),
        [["ORIG_LABEL", "ASCENDING"]])

    mxd_geology = arcpy.mapping.MapDocument(config.mxd_file_geology)
    df_geology = arcpy.mapping.ListDataFrames(mxd_geology, "*")[0]
    df_geology.spatialReference = order_obj.spatial_ref_pcs

    ### add order and order_buffer layers to geology mxd file
    utility.add_layer_to_mxd("order_buffer", df_geology,
                             config.buffer_lyr_file, 1.1)
    utility.add_layer_to_mxd("order_geometry_pcs", df_geology,
                             config.order_geom_lyr_file, 1)

    if not config.if_multi_page:  # single-page
        #df.scale = 5000
        mxd_geology.saveACopy(
            os.path.join(config.scratch_folder, "mxd_geology.mxd"))
        arcpy.mapping.ExportToJPEG(mxd_geology, output_jpg_geology,
                                   "PAGE_LAYOUT", 480, 640, 150, "False",
                                   "24-BIT_TRUE_COLOR", 85)
        if not os.path.exists(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        shutil.copy(
            output_jpg_geology,
            os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        arcpy.AddMessage(
            '      - output jpg image: %s' %
            os.path.join(config.report_path, 'PSRmaps', order_obj.number,
                         os.path.basename(output_jpg_geology)))
        del mxd_geology
        del df_geology
    else:  # multipage
        grid_lyr_shp = os.path.join(config.scratch_folder,
                                    'grid_lyr_geology.shp')
        arcpy.GridIndexFeatures_cartography(grid_lyr_shp,
                                            config.order_buffer_shp, "", "",
                                            "", config.grid_size,
                                            config.grid_size)

        # part 1: the overview map
        # add grid layer
        grid_layer = arcpy.mapping.Layer(config.grid_lyr_file)
        grid_layer.replaceDataSource(config.scratch_folder,
                                     "SHAPEFILE_WORKSPACE", "grid_lyr_geology")
        arcpy.mapping.AddLayer(df_geology, grid_layer, "Top")

        df_geology.extent = grid_layer.getExtent()
        df_geology.scale = df_geology.scale * 1.1

        mxd_geology.saveACopy(
            os.path.join(config.scratch_folder, "mxd_geology.mxd"))
        arcpy.mapping.ExportToJPEG(mxd_geology, output_jpg_geology,
                                   "PAGE_LAYOUT", 480, 640, 150, "False",
                                   "24-BIT_TRUE_COLOR", 85)

        if not os.path.exists(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number)):
            os.mkdir(
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        shutil.copy(
            output_jpg_geology,
            os.path.join(config.report_path, 'PSRmaps', order_obj.number))
        arcpy.AddMessage(
            '      - output jpg image page 1: %s' %
            os.path.join(config.report_path, 'PSRmaps', order_obj.number,
                         os.path.basename(output_jpg_geology)))
        del mxd_geology
        del df_geology

        # part 2: the data driven pages

        page = int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) + 1
        mxd_mm_geology = arcpy.mapping.MapDocument(config.mxd_mm_file_geology)

        df_mm_geology = arcpy.mapping.ListDataFrames(mxd_mm_geology, "*")[0]
        df_mm_geology.spatialReference = order_obj.spatial_ref_pcs
        utility.add_layer_to_mxd("order_buffer", df_mm_geology,
                                 config.buffer_lyr_file, 1.1)
        utility.add_layer_to_mxd("order_geometry_pcs", df_mm_geology,
                                 config.order_geom_lyr_file, 1)

        grid_layer_mm = arcpy.mapping.ListLayers(mxd_mm_geology, "Grid",
                                                 df_mm_geology)[0]
        grid_layer_mm.replaceDataSource(config.scratch_folder,
                                        "SHAPEFILE_WORKSPACE",
                                        "grid_lyr_geology")
        arcpy.CalculateAdjacentFields_cartography(grid_lyr_shp, "PageNumber")
        mxd_mm_geology.saveACopy(
            os.path.join(config.scratch_folder, "mxd_mm_geology.mxd"))

        for i in range(
                1,
                int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) + 1):
            arcpy.SelectLayerByAttribute_management(
                grid_layer_mm, "NEW_SELECTION", ' "PageNumber" =  ' + str(i))
            df_mm_geology.extent = grid_layer_mm.getSelectedExtent(True)
            df_mm_geology.scale = df_mm_geology.scale * 1.1
            arcpy.SelectLayerByAttribute_management(grid_layer_mm,
                                                    "CLEAR_SELECTION")

            title_text = arcpy.mapping.ListLayoutElements(
                mxd_mm_geology, "TEXT_ELEMENT", "title")[0]
            title_text.text = "Geologic Units - Page " + str(i)
            title_text.elementPositionX = 0.6303
            arcpy.RefreshTOC()

            arcpy.mapping.ExportToJPEG(
                mxd_mm_geology, output_jpg_geology[0:-4] + str(i) + ".jpg",
                "PAGE_LAYOUT", 480, 640, 150, "False", "24-BIT_TRUE_COLOR", 85)
            if not os.path.exists(
                    os.path.join(config.report_path, 'PSRmaps',
                                 order_obj.number)):
                os.mkdir(
                    os.path.join(config.report_path, 'PSRmaps',
                                 order_obj.number))
            shutil.copy(
                output_jpg_geology[0:-4] + str(i) + ".jpg",
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
            # arcpy.AddMessage('      - output jpg image: %s' % os.path.join(config.report_path, 'PSRmaps', order_obj.number, os.path.basename(output_jpg_geology[0:-4]+str(i)+".jpg")))
        del mxd_mm_geology
        del df_mm_geology
        psr_obj = models.PSR()
        for i in range(1, page):
            psr_obj.insert_map(order_obj.id, 'GEOL',
                               order_obj.number + '_US_GEOL' + str(i) + '.jpg',
                               i + 1)

    if (int(
            arcpy.GetCount_management(
                os.path.join(config.scratch_folder,
                             "summary_sorted_geol.dbf")).getOutput(0)) == 0):
        # no geology polygon selected...., need to send in map only
        arcpy.AddMessage('No geology polygon is selected....')
        psr_obj = models.PSR()
        psr_obj.insert_map(order_obj.id, 'GEOL',
                           order_obj.number + '_US_GEOLOGY.jpg',
                           1)  #note type 'SOIL' or 'GEOL' is used internally
    else:
        eris_id = 0
        psr_obj = models.PSR()
        in_rows = arcpy.SearchCursor(
            os.path.join(config.scratch_folder,
                         config.geology_selectedby_order_shp))
        for in_row in in_rows:
            # note the column changed in summary dbf
            # arcpy.AddMessage("Unit label is: " + in_row.ORIG_LABEL)
            # arcpy.AddMessage(in_row.UNIT_NAME)     # unit name
            # arcpy.AddMessage(in_row.UNIT_AGE)      # unit age
            # arcpy.AddMessage( in_row.ROCKTYPE1)      # rocktype 1
            # arcpy.AddMessage( in_row.ROCKTYPE2)      # rocktype2
            # arcpy.AddMessage( in_row.UNITDESC)       # unit description
            # arcpy.AddMessage( in_row.ERIS_KEY_1)     # eris key created from upper(unit_link)
            eris_id = eris_id + 1
            config.geology_ids.append([in_row.ERIS_KEY_1, eris_id])
            psr_obj.insert_order_detail(order_obj.id, eris_id, '10685')
            psr_obj.insert_flex_rep(order_obj.id, eris_id, '10685', 2, 'S1', 1,
                                    'Geologic Unit ' + in_row.ORIG_LABEL, '')
            psr_obj.insert_flex_rep(order_obj.id, eris_id, '10685', 2, 'N', 2,
                                    'Unit Name: ', in_row.UNIT_NAME)
            psr_obj.insert_flex_rep(order_obj.id, eris_id, '10685', 2, 'N', 3,
                                    'Unit Age: ', in_row.UNIT_AGE)
            psr_obj.insert_flex_rep(order_obj.id, eris_id, '10685', 2, 'N', 4,
                                    'Primary Rock Type ', in_row.ROCKTYPE1)
            psr_obj.insert_flex_rep(order_obj.id, eris_id, '10685', 2, 'N', 4,
                                    'Secondary Rock Type: ', in_row.ROCKTYPE2)
            if in_row.UNITDESC == None:
                node_scr = 'No description available.'
                psr_obj.insert_flex_rep(order_obj.id, eris_id, '10685', 2, 'N',
                                        6, 'Unit Description: ', node_scr)
            else:
                psr_obj.insert_flex_rep(order_obj.id, eris_id, '10685', 2, 'N',
                                        6, 'Unit Description: ',
                                        in_row.UNITDESC.encode('utf-8'))
            del in_row
        del in_rows
        psr_obj.insert_map(order_obj.id, 'GEOL',
                           order_obj.number + '_US_GEOLOGY.jpg', 1)

    end = timeit.default_timer()
    arcpy.AddMessage((' -- End generating PSR geology report. Duration:',
                      round(end - start, 4)))
Ejemplo n.º 17
0
                                            tab_fc, fields)
    elif not exists:
        arcpy.TabulateIntersection_analysis(om_fc_m, "PageNumber", clip_fc,
                                            tab_fc, fields)

    arcpy.Delete_management(clip_fc)


def clip_and_tabulate(omid, source_fc, fields):
    clip_fc = clip(omid, source_fc)
    tabulate(omid, source_fc, clip_fc, fields)


print("Creating %s" % omg_fc)
arcpy.GridIndexFeatures_cartography(omg_fc, grid_source_fc,
                                    "NO_INTERSECTFEATURE", "", "",
                                    "4320 meters", "4320 meters", "", "", "",
                                    "0")
print("Done creating %s" % omg_fc)

print("Creating %s" % subset_grid_fc)
nuke(subset_grid_fc)
arcpy.MakeFeatureLayer_management(omg_fc, "BLARG")
arcpy.SelectLayerByLocation_management("BLARG", "INTERSECT", subset_source_fc)
arcpy.CopyFeatures_management("BLARG", subset_grid_fc)
print("Done creating %s" % subset_grid_fc)

arcpy.Delete_management(omg_fc)
arcpy.Delete_management("BLARG")

# with arcpy.da.SearchCursor(subset_grid_fc, "PageNumber", "PageNumber in (1012, 1013, 1014)") as cursor:
with arcpy.da.SearchCursor(subset_grid_fc, "PageNumber") as cursor:
Ejemplo n.º 18
0
def generate_wetland_report(order_obj):
    arcpy.AddMessage('  -- Start generating PSR wetland report...')
    start = timeit.default_timer()
    ### set scratch folder
    arcpy.env.workspace = config.scratch_folder
    arcpy.env.overwriteOutput = True

    output_jpg_wetland = config.output_jpg(order_obj,
                                           config.Report_Type.wetland)
    output_jpg_ny_wetland = os.path.join(
        config.scratch_folder,
        str(order_obj.number) + '_NY_WETL.jpg')

    ### Wetland Map
    if '10684' not in order_obj.psr.search_radius.keys():
        arcpy.AddMessage('      -- Wetland search radius is not availabe')
        return
    config.buffer_dist_wetland = str(
        order_obj.psr.search_radius['10684']) + ' MILES'
    arcpy.Buffer_analysis(config.order_geometry_pcs_shp,
                          config.order_buffer_shp, config.buffer_dist_wetland)
    mxd_wetland = arcpy.mapping.MapDocument(config.mxd_file_wetland)
    df_wetland = arcpy.mapping.ListDataFrames(mxd_wetland, "big")[0]
    df_wetland.spatialReference = order_obj.spatial_ref_pcs
    df_wetland_small = arcpy.mapping.ListDataFrames(mxd_wetland, "small")[0]
    df_wetland_small.spatialReference = order_obj.spatial_ref_pcs
    del df_wetland_small
    ### add order and order_buffer layers to wetland mxd file
    utility.add_layer_to_mxd("order_buffer", df_wetland,
                             config.buffer_lyr_file, 1.1)
    utility.add_layer_to_mxd("order_geometry_pcs", df_wetland,
                             config.order_geom_lyr_file, 1)

    # print the maps
    if not config.if_multi_page:  # sinle page report
        generate_singlepage_report(order_obj, mxd_wetland, output_jpg_wetland,
                                   config.scratch_folder)
    else:  # multipage report
        generate_multipage_report(order_obj, mxd_wetland, output_jpg_wetland,
                                  df_wetland)
### Create wetland report for Newyork province
    if order_obj.province == 'NY':
        arcpy.AddMessage("      - Starting NY wetland section: " +
                         time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        buffer_wetland_shp = os.path.join(config.scratch_folder,
                                          "buffer_wetland.shp")
        mxd_wetland_ny = arcpy.mapping.MapDocument(config.mxd_file_wetlandNY)
        df_wetland_ny = arcpy.mapping.ListDataFrames(mxd_wetland_ny, "big")[0]
        df_wetland_ny.spatialReference = order_obj.spatial_ref_pcs
        ### add order and order_buffer layers to wetland Newyork mxd file
        utility.add_layer_to_mxd("order_buffer", df_wetland_ny,
                                 config.buffer_lyr_file, 1.1)
        utility.add_layer_to_mxd("order_geometry_pcs", df_wetland_ny,
                                 config.order_geom_lyr_file, 1)

        page = 1
        ### print the maps
        if not config.if_multi_page:
            mxd_wetland_ny.saveACopy(
                os.path.join(config.scratch_folder, "mxd_wetland_ny.mxd"))
            arcpy.mapping.ExportToJPEG(mxd_wetland_ny, output_jpg_ny_wetland,
                                       "PAGE_LAYOUT", 480, 640, 150, "False",
                                       "24-BIT_TRUE_COLOR", 85)
            shutil.copy(
                output_jpg_ny_wetland,
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
            arcpy.AddMessage(
                '      - Wetland Output for NY state: %s' %
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))
            del mxd_wetland_ny
            del df_wetland_ny
        else:  # multipage
            grid_lyr_shp = os.path.join(config.scratch_folder,
                                        'grid_lyr_wetland.shp')
            arcpy.GridIndexFeatures_cartography(
                grid_lyr_shp, buffer_wetland_shp, "", "", "", config.grid_size,
                config.grid_size
            )  #note the tool takes featureclass name only, not the full path

            # part 1: the overview map
            # add grid layer
            grid_layer = arcpy.mapping.Layer(config.grid_lyr_file)
            grid_layer.replaceDataSource(config.scratch_folder,
                                         "SHAPEFILE_WORKSPACE",
                                         "grid_lyr_wetland")
            arcpy.mapping.AddLayer(df_wetland_ny, grid_layer, "Top")

            df_wetland_ny.extent = grid_layer.getExtent()
            df_wetland_ny.scale = df_wetland_ny.scale * 1.1

            mxd_wetland_ny.saveACopy(
                os.path.join(config.scratch_folder, "mxd_wetland_ny.mxd"))
            arcpy.mapping.ExportToJPEG(mxd_wetland_ny, output_jpg_ny_wetland,
                                       "PAGE_LAYOUT", 480, 640, 150, "False",
                                       "24-BIT_TRUE_COLOR", 85)
            if not os.path.exists(
                    os.path.join(config.report_path, 'PSRmaps',
                                 order_obj.number)):
                os.mkdir(
                    os.path.join(config.report_path, 'PSRmaps',
                                 order_obj.number))
            shutil.copy(
                output_jpg_ny_wetland,
                os.path.join(config.report_path, 'PSRmaps', order_obj.number))

            del mxd_wetland_ny
            del df_wetland_ny

            # part 2: the data driven pages

            page = int(
                arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) + page
            mxd_mm_wetland_NY = arcpy.mapping.MapDocument(
                config.mxdMMfile_wetlandNY)

            df_mm_wetland_ny = arcpy.mapping.ListDataFrames(
                mxd_mm_wetland_NY, "big")[0]
            df_mm_wetland_ny.spatialReference = order_obj.spatial_ref_pcs
            ### add order and order_buffer layers to wetland Newyork multipage mxd file
            utility.add_layer_to_mxd("order_buffer", df_mm_wetland_ny,
                                     config.buffer_lyr_file, 1.1)
            utility.add_layer_to_mxd("order_geometry_pcs", df_mm_wetland_ny,
                                     config.order_geom_lyr_file, 1)

            grid_layer_mm = arcpy.mapping.ListLayers(mxd_mm_wetland_NY, "Grid",
                                                     df_mm_wetland_ny)[0]
            grid_layer_mm.replaceDataSource(config.scratch_folder,
                                            "SHAPEFILE_WORKSPACE",
                                            "grid_lyr_wetland")
            arcpy.CalculateAdjacentFields_cartography(grid_lyr_shp,
                                                      "PageNumber")
            mxd_mm_wetland_NY.saveACopy(
                os.path.join(config.scratch_folder, "mxd_mm_wetland_NY.mxd"))

            for i in range(
                    1,
                    int(arcpy.GetCount_management(grid_lyr_shp).getOutput(0)) +
                    1):
                arcpy.SelectLayerByAttribute_management(
                    grid_layer_mm, "NEW_SELECTION",
                    ' "PageNumber" =  ' + str(i))
                df_mm_wetland_ny.extent = grid_layer_mm.getSelectedExtent(True)
                df_mm_wetland_ny.scale = df_mm_wetland_ny.scale * 1.1
                arcpy.SelectLayerByAttribute_management(
                    grid_layer_mm, "CLEAR_SELECTION")
                title_text = arcpy.mapping.ListLayoutElements(
                    df_mm_wetland_ny, "TEXT_ELEMENT", "title")[0]
                title_text.text = "NY Wetland Type - Page " + str(i)
                title_text.elementPositionX = 0.468
                arcpy.RefreshTOC()
                arcpy.mapping.ExportToJPEG(
                    mxd_mm_wetland_NY,
                    output_jpg_ny_wetland[0:-4] + str(i) + ".jpg",
                    "PAGE_LAYOUT", 480, 640, 150, "False", "24-BIT_TRUE_COLOR",
                    85)
                if not os.path.exists(
                        os.path.join(config.report_path, 'PSRmaps',
                                     order_obj.number)):
                    os.mkdir(
                        os.path.join(config.report_path, 'PSRmaps',
                                     order_obj.number))
                shutil.copy(
                    output_jpg_ny_wetland[0:-4] + str(i) + ".jpg",
                    os.path.join(config.report_path, 'PSRmaps',
                                 order_obj.number))
                arcpy.AddMessage(
                    '      -- Wetland Output for NY state: %s' % os.path.join(
                        config.report_path, 'PSRmaps', order_obj.number))
            del mxd_mm_wetland_NY
            del df_mm_wetland_ny

        psr_obj = models.PSR()
        for i in range(
                1, page
        ):  #insert generated .jpg report path into eris_maps_psr table
            psr_obj.insert_map(order_obj.id, 'WETLAND',
                               order_obj.number + '_NY_WETL' + str(i) + '.jpg',
                               int(i) + 1)

    end = timeit.default_timer()
    arcpy.AddMessage((' -- End generating PSR Wetland report. Duration:',
                      round(end - start, 4)))