Exemplo n.º 1
0
def TIN2TIF(tin):
    arcpy.env.extent = arcpy.Extent(624127.347083, 2095613.485647, 2684127.347083, 3259613.485647)
    arcpy.TinRaster_3d(in_tin=wrkdir+"\\"+tin,
                       out_raster=wrkdir+"\\"+tin+".tif",
                       data_type="FLOAT",
                       method="LINEAR",
                       sample_distance="CELLSIZE 200",
                       z_factor="1")
Exemplo n.º 2
0
 def tin2raster(self,
                interpolation_method="LINEAR",
                sampling_method="OBSERVATIONS"):
     print(" * converting tin to raster ...")
     arcpy.env.outputCoordinateSystem = self.sr
     arcpy.TinRaster_3d(self.tin,
                        self.raster_tif,
                        data_type="FLOAT",
                        method=interpolation_method,
                        sample_distance=sampling_method,
                        z_factor=1)
     print("   - OK")
Exemplo n.º 3
0
def tin_to_raster(tin, cs, out, template=None, snapRst=None):
    if template:
        tempEnvironment0 = arcpy.env.extent
        arcpy.env.extent = template

    if snapRst:
        tempSnap = arcpy.env.snapRaster
        arcpy.env.snapRaster = snapRst

    arcpy.TinRaster_3d(tin, out, "FLOAT", "LINEAR",
                       "CELLSIZE {}".format(str(cs)), "1")

    if template:
        arcpy.env.extent = tempEnvironment0

    if snapRst:
        arcpy.env.snapRaster = tempSnap

    return out
arcpy.MakeFeatureLayer_management(endPoints, endPointsLyr)

IDs = []
with arcpy.da.SearchCursor(endPointsLyr, ('RIGHT_FID', )) as cursor:
    for row in cursor:
        if row not in IDs:
            IDs.append(row)
IDlist = []
for values in IDs:
    for x in values:
        IDlist.append(x)

for patchID in IDlist:
    selection = arcpy.SelectLayerByAttribute_management(
        endPointsLyr, "ADD_TO_SELECTION", 'RIGHT_FID = ' + str(patchID))
    outTIN = scratchFolder + '\TIN_' + str(patchID)
    depthfield = ' Heights'
    mp = ' Mass_Points'
    none = ' <None>'
    inFeatures = str(selection) + depthfield + mp + none
    arcpy.CreateTin_3d(outTIN, '', inFeatures, "DELAUNAY")
    arcpy.TinRaster_3d(
        outTIN,
        patchOutputFolder + '\Patch_' + str(patchID) + '.tif',
        "FLOAT",
        '',
        "CELLSIZE " + str(cellsize),
    )
    arcpy.SelectLayerByAttribute_management(endPointsLyr, "CLEAR_SELECTION")

print('All processes complete')
Exemplo n.º 5
0
ymax = int(ymaxFloat)
arcpy.AddMessage("X Min, X Max, Y Min, and Y Max are...")
arcpy.AddMessage(xmin)
arcpy.AddMessage(xmax)
arcpy.AddMessage(ymin)
arcpy.AddMessage(ymax)
arcpy.AddMessage("")
#
arcpy.env.extent = arcpy.Extent(xmin, ymin, xmax, ymax)
#
###############################################
# create DEM
outRaster = str(outFolder + "\\" + "Seg_" + inSegment + "_" + inYear + "_" + CellSizeName + ".tif")
arcpy.AddMessage("output raster is: " + outRaster)
CellSizeStatement = str("CELLSIZE " + CellSize)
arcpy.TinRaster_3d(inTIN, outRaster, "FLOAT", "LINEAR", CellSizeStatement, 1)
#
# create mask for area of DEM
RasterMask = str(outFolder + "\\" + "Seg_" + inSegment + "_" + inYear + "_mask.tif")
arcpy.gp.Divide_sa(outRaster, outRaster, RasterMask)
RasterMaskInt = str(outFolder + "\\" + "Seg_" + inSegment + "_" + inYear + "_" + CellSizeName + "_maskInt.tif")
arcpy.gp.Int_sa(RasterMask, RasterMaskInt)
arcpy.AddMessage("output raster mask is: " + RasterMaskInt)
#
# convert raster mask to polygon
#PolyMask = str(workspaceGDB + "\\" + "Seg_" + inSegment + "_" + inYear + "_" + CellSizeName + "_mask_poly")
PolyMask = str(workspaceGDB + "\\" + "Seg_" + inSegment + "_" + inYear + "_" + CellSizeName + "_mask_poly")
arcpy.AddMessage("output polygon mask: " + PolyMask)
arcpy.AddMessage(PolyMask)

arcpy.RasterToPolygon_conversion(RasterMaskInt, PolyMask, "NO_SIMPLIFY", "Value")
# Step 3: Create TINs from depth and velocity point shapefiles
# Create TINs from model points shapefile
print('Creating TINs from model XY point shapefiles...')
mod_depth = arcpy.CreateTin_3d('mod_depth', spatial_reference=spat_ref, 
                               in_features='%s D Mass_Points' % mod_points, 
                               constrained_delaunay='Delaunay')
mod_vel = arcpy.CreateTin_3d('mod_vel', spatial_reference=spat_ref, 
                             in_features='%s V Mass_Points' % mod_points, 
                             constrained_delaunay='Delaunay')


# Step 4: Convert TINS to rasters (depth and velocity)
# Convert TINs to rasters
print('Converting TINs to rasters...')
depth_ras_full = arcpy.TinRaster_3d(mod_depth, 'depth_ras_full.tif', 
                                    sample_distance='CELLSIZE', sample_value=3)
vel_ras_full = arcpy.TinRaster_3d(mod_vel, 'vel_ras_full.tif', 
                                  sample_distance='CELLSIZE', sample_value=3)


# Step 5: Clip rasters to the boundary shapefile
# Clipping rasters
print('Clipping depth and velocity rasters to boundary shapefile...')
extents = arcpy.Describe(bndry_shp).extent
rectangle = '%s %s %s %s' % (extents.XMin, extents.YMin, extents.XMax, extents.YMax)
arcpy.Clip_management(in_raster=depth_ras_full, rectangle=rectangle, out_raster='depth_ras.tif', 
                      in_template_dataset=bndry_shp, clipping_geometry='ClippingGeometry')
arcpy.Clip_management(vel_ras_full, rectangle, out_raster='vel_ras.tif', 
                      in_template_dataset=bndry_shp, clipping_geometry='ClippingGeometry')
depth_ras = Raster('depth_ras.tif')
vel_ras = Raster('vel_ras.tif')
    # Create TIN
    arcpy.AddMessage("Creating TIN for {0}".format(stage))
    if stage == "MIN_Z_Value":
        stage_name_for_table = "MIN_Z_Value"
    else:
        stage_name_for_table = "{0}.{1}".format(Table, stage)
    expression = "{0} <None> Soft_Clip <None>;{1} {2} Mass_Points <None>;{3} {4} Hard_Line <None>".format(
        Reaches, New_CrossSections, stage_name_for_table, New_CrossSections,
        stage_name_for_table)
    arcpy.CreateTin_3d(TIN, spatial_ref, expression, "CONSTRAINED_DELAUNAY")

    # TIN to Raster
    arcpy.AddMessage("Converting TIN to raster for {0}".format(stage))
    input_cell_size = "CELLSIZE {0}".format(Cell_Size)
    arcpy.TinRaster_3d(TIN, RasterFromTIN, "FLOAT", "LINEAR", input_cell_size,
                       "1")

    # Raster subtraction
    arcpy.AddMessage(
        "Subtracting the raster from TIN with the input DEM for {0}".format(
            stage))
    arcpy.Minus_3d(RasterFromTIN, DEM, Subtracted)

    # Reclassify raster
    arcpy.AddMessage(
        "Reclassifing the subtracted raster for {0}".format(stage))
    arcpy.Reclassify_3d(Subtracted, "Value", "-999 0.01 1;0.01 999 0",
                        Reclassified, "DATA")

    # Extract by Attributes
    arcpy.AddMessage("Extracting by attributes for {0}".format(stage))
Exemplo n.º 8
0
    def tinraster_3d(self, layer_name, input_fc_name, raster_field_name):
        self.layer_name = layer_name
        self.input_fc_name = input_fc_name
        self.raster_field = raster_field_name

        # Check out any necessary licenses
        print "Checking out extension licenses..."
        arcpy.CheckOutExtension("3D")
        arcpy.CheckOutExtension("spatial")
        # overwrite output
        arcpy.env.overwriteOutput = True

        # tin
        outTIN = os.getcwd() + r'\Data\tin_' + self.layer_name

        # raster
        outRASTER = os.getcwd() + r'\Data\RST_' + self.layer_name

        input_fc = join(os.getcwd(), 'Precip.gdb', layer_name)
        print(input_fc)

        try:
            # Process: Create TIN
            print "Creating TIN..."
            arcpy.CreateTin_3d(
                outTIN,
                "PROJCS['NAD_1983_StatePlane_Texas_Central_FIPS_4203_Feet',"
                "GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',"
                "SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],"
                "UNIT['Degree',0.0174532925199433]],PROJECTION['Lambert_Conformal_Conic'],"
                "PARAMETER['False_Easting',2296583.333333333],"
                "PARAMETER['False_Northing',9842500.0],"
                "PARAMETER['Central_Meridian',-100.3333333333333],"
                "PARAMETER['Standard_Parallel_1',30.11666666666667],"
                "PARAMETER['Standard_Parallel_2',31.88333333333333],"
                "PARAMETER['Latitude_Of_Origin',29.66666666666667],"
                "UNIT['Foot_US',0.3048006096012192]]",
                "'" + self.input_fc_name + "' " + self.raster_field +
                " Mass_Points <None>", "DELAUNAY")

            # arcpy.CreateTin_3d(outTIN, "PROJCS['NAD_1983_StatePlane_Texas_Central_FIPS_4203_Feet',"
            #                            "GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',"
            #                            "SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],"
            #                            "UNIT['Degree',0.0174532925199433]],PROJECTION['Lambert_Conformal_Conic'],"
            #                            "PARAMETER['False_Easting',2296583.333333333],"
            #                            "PARAMETER['False_Northing',9842500.0],"
            #                            "PARAMETER['Central_Meridian',-100.3333333333333],"
            #                            "PARAMETER['Standard_Parallel_1',30.11666666666667],"
            #                            "PARAMETER['Standard_Parallel_2',31.88333333333333],"
            #                            "PARAMETER['Latitude_Of_Origin',29.66666666666667],"
            #                            "UNIT['Foot_US',0.3048006096012192]]",
            #                    "'Database Connections\\Connection to FWSDE.sde\\sde_wjt.\"FREESE\\wjt\".hrap\\"
            #                    "sde_wjt.\"FREESE\\wjt\"." + self.input_fc_name + "' " + self.raster_field +
            #                    " Mass_Points <None>", "DELAUNAY")

            # Process: TIN to Raster
            print "Creating raster..."
            # typical cellsize is 12500
            arcpy.TinRaster_3d(outTIN, outRASTER, "FLOAT", "LINEAR",
                               "CELLSIZE 5000", "1")
            self.run_status = 'OK'
        except Exception as e:
            self.run_status = e
            root = tk.Tk()
            # allows tkMessageBox to be shown without displaying Tkinter root window
            root.withdraw()
            tkMessageBox.showinfo("Python error", e)
            return self.run_status
        return self.run_status
Exemplo n.º 9
0
#output folder
arcpy.env.workspace = 'I:\\asignaturas\\sig-I\\2012-2013\\cuatrimestreB\\teoria\\MT7\\salida'

#tool parameters
tin = 'tin'
grid = 'grid'
data_type = 'FLOAT'
interpolation_method = 'LINEAR'
sampling_method = 'CELLSIZE 10'
factor = 1

if arcpy.CheckExtension("3D") == "Available":
    arcpy.CheckOutExtension("3D")
    #TIN to GRID conversion
    arcpy.TinRaster_3d(tin, grid, data_type, interpolation_method,
                       sampling_method, factor)
    arcpy.CheckInExtension("3D")
else:
    print('Licencia 3D no disponible')

#-------------------------------------------------------------------------------
# SLOPE MAP
#-------------------------------------------------------------------------------
#importing module
import arcpy

#enable output overwrite
arcpy.env.overwriteOutput = True

#output folder
arcpy.env.workspace = 'I:\\asignaturas\\sig-I\\2012-2013\\cuatrimestreB\\teoria\\MT7\\salida'
def calculate_height(lc_input_features, lc_ws, lc_tin_dir, lc_input_surface,
                     lc_output_features, lc_log_dir, lc_debug,
                     lc_memory_switch):

    try:
        # create dem
        desc = arcpy.Describe(lc_input_features)
        if desc.spatialReference.linearUnitName in ['Foot_US', 'Foot']:
            unit = 'Feet'
        else:
            unit = 'Meters'

        # Generate raster from lasd
        if arcpy.Exists(lc_input_features):
            if arcpy.Exists(lc_output_features):
                arcpy.Delete_management(lc_output_features)

            # make a copy
            bridge_polys = lc_output_features + "_height"

            if arcpy.Exists(bridge_polys):
                arcpy.Delete_management(bridge_polys)

            arcpy.CopyFeatures_management(lc_input_features, bridge_polys)

            # create string field for featureFID
            oidFieldName = arcpy.Describe(bridge_polys).oidFieldName
            common_lib.delete_add_field(bridge_polys, esri_featureID, "TEXT")
            arcpy.CalculateField_management(bridge_polys, esri_featureID,
                                            "!" + oidFieldName + "!",
                                            "PYTHON_9.3")

            msg_body = create_msg_body(
                "Calculating height above surface for: " +
                common_lib.get_name_from_feature_class(lc_input_features), 0,
                0)
            msg(msg_body)

            # create bridge tin
            out_tin = os.path.join(lc_tin_dir, "bridge_tin")
            if arcpy.Exists(out_tin):
                arcpy.Delete_management(out_tin)

            msg_body = create_msg_body(
                "Creating raster for: " +
                common_lib.get_name_from_feature_class(lc_input_features), 0,
                0)
            msg(msg_body)

            arcpy.CreateTin_3d(
                out_tin,
                arcpy.Describe(bridge_polys).spatialReference,
                "{} Shape.Z Hard_Clip <None>".format(bridge_polys), "DELAUNAY")

            # turn to raster
            if 0:
                bridge_raster = "in_memory/bridge_raster"
            else:
                bridge_raster = os.path.join(lc_ws, "bridge_raster")
                if arcpy.Exists(bridge_raster):
                    arcpy.Delete_management(bridge_raster)

            # use same cell size as input surface
            cell_size = arcpy.GetRasterProperties_management(
                lc_input_surface, "CELLSIZEX")[0]

            dataType = "FLOAT"
            method = "LINEAR"
            sampling = "CELLSIZE " + str(cell_size)
            zfactor = "1"

            arcpy.TinRaster_3d(out_tin, bridge_raster, dataType, method,
                               sampling, zfactor)

            add_minimum_height_above_water_surface(lc_ws, bridge_polys,
                                                   bridge_raster,
                                                   lc_input_surface,
                                                   lc_memory_switch)

            # create point file for labeling
            if lc_memory_switch:
                bridge_points = "in_memory/bridge_points"
            else:
                bridge_points = os.path.join(lc_ws, "bridge_points")
                if arcpy.Exists(bridge_points):
                    arcpy.Delete_management(bridge_points)

            arcpy.FeatureToPoint_management(bridge_polys, bridge_points,
                                            "INSIDE")

            bridge_points3D = lc_output_features + "_points_3D"
            if arcpy.Exists(bridge_points3D):
                arcpy.Delete_management(bridge_points3D)

            # create 3D point
            arcpy.FeatureTo3DByAttribute_3d(bridge_points, bridge_points3D,
                                            zmin_field)

            # add unit field
            common_lib.delete_add_field(bridge_points3D, esri_unit, "TEXT")

            expression = """{} IS NOT NULL""".format(
                arcpy.AddFieldDelimiters(bridge_points3D, has_field))

            # select all points with good elevation values
            local_layer = common_lib.get_name_from_feature_class(
                bridge_points3D) + "_lyr"
            select_lyr = arcpy.MakeFeatureLayer_management(
                bridge_points3D, local_layer).getOutput(0)
            arcpy.SelectLayerByAttribute_management(select_lyr,
                                                    "NEW_SELECTION",
                                                    expression, None)

            z_unit = common_lib.get_z_unit(bridge_points3D, lc_debug)

            if z_unit == "Meters":
                expression = "'m'"
            else:
                expression = "'ft'"

            arcpy.CalculateField_management(select_lyr, esri_unit, expression,
                                            "PYTHON_9.3")
            arcpy.SelectLayerByAttribute_management(select_lyr,
                                                    "CLEAR_SELECTION")

            common_lib.delete_fields(bridge_polys, [min_field, zmin_field])
            common_lib.delete_fields(bridge_points3D, [min_field, zmin_field])

            return bridge_polys, bridge_points3D
        else:
            msg_body = create_msg_body(
                "Couldn't find input feature class: " + str(lc_input_features),
                0, 0)
            msg(msg_body, WARNING)

            return None

    except arcpy.ExecuteError:
        # Get the tool error messages
        msgs = arcpy.GetMessages(2)
        arcpy.AddError(msgs)
    except Exception:
        e = sys.exc_info()[1]
        arcpy.AddMessage("Unhandled exception: " + str(e.args[0]))
Exemplo n.º 11
0
        #Create TINs
        for n in xrange(1, len(data) + 1):
            shp = locshp + data2[n - 1] + ".shp"
            #breakl = locshp + data2[n-1] + "_Cliff.shp"
            TIN = loctin + data[n - 1]
            RAS = locras + data[n - 1]
            arcpy.CreateTin_3d(TIN, sr, [[shp, "Z", "masspoints"]],
                               "CONSTRAINED_DELAUNAY")
            arcpy.DelineateTinDataArea_3d(TIN, tin_length)
            print data[n - 1] + ' TIN created'

        #Tins to rasters
        for n in xrange(1, len(data) + 1):
            TIN = loctin + data[n - 1]
            RAS = locras + data[n - 1]
            arcpy.TinRaster_3d(TIN, RAS, "FLOAT", "LINEAR",
                               "CELLSIZE 1.0")  #1 m cell size
            print data[n - 1] + ' raster created'
    else:
        print "Using Rasters created from previous 'Total Analysis' Run"

    #Merge rasters
    for n in xrange(1, len(data) + 1):
        if AnalysisType == "Tidal":
            RAS = locras + 'm_' + data[n - 1]
        else:
            RAS = locras + data[n - 1]
        mRAS = locras + rastype + data[n - 1]
        temp = "in_memory/t1" + integ
        tempn = "t1" + integ
        mRASname = rastype + data[n - 1]
        if AnalysisType == "Tidal":
Exemplo n.º 12
0
# Create a Triangular Irregular Network (TIN) model of the terrain #####################
arcpy.env.workspace = r"E:/GitHub/terrainModeling/chp12data.gdb"
"""
	DEM to TIN
	The TIN data cannot be saved in a geodatabase, so the output data
	should be put into a folder e.g. E:/GitHub/terrainModeling/chp12data.gdb/tin
"""
arcpy.RasterTin_3d("dem", "tin")
"""
	TIN to DEM
	The cell size of the new DEM is 50 meters, values are in the 
	float type, and the methos used to raster the DEM is linear
	interpolation 
"""
arcpy.TinRaster_3d(in_tin=r"chp12data.gdb/tin", out_raster="demFromTIN", \
                   data_type="FLOAT", method="LINEAR", \
                   sample_distance="CELLSIZE 50",z_factor="1")

# Create contour lines ##################################################################
"""
	The input is "dem" and the output is "contour".
	The contour is in 10 meter intervals and starts from 330 meters.
"""
arcpy.Contour_3d(in_raster="dem", out_polyline_features=" contour", \
                 contour_interval="10", base_contour="330", z_factor="1")

# Create slope raster ###################################################################
# the input is DEM, and slope is in the unit of degrees
slopely = arcpy.sa.Slope("dem", "DEGREE")
# save the slope layer into geodatabase (path has been set above)
slopely.save("slope")
Exemplo n.º 13
0
def runScript(uploaderpk):
    print("Starting script")
    startTime = time.time()

    arcpy.env.overwriteOutput = True
    arcpy.env.cellSize = 1
    # Activate spatial analyst extension
    if arcpy.CheckExtension("Spatial") == "Available":
        arcpy.CheckOutExtension("Spatial")

    if arcpy.CheckExtension("3D") == "Available":
        arcpy.CheckOutExtension("3D")

    # basePath = .../apps/findbestroute/workfiles/
    global basePath
    sleep(2)
    basePath = os.path.join(settings.PROJECT_PATH, 'apps', 'findbestroute',
                            'workfiles')
    env.workspace = basePath
    sleep(2)

    mxd = arcpy.mapping.MapDocument(os.path.join(basePath, r'mapdocument.mxd'))

    onlyfiles = []
    kart_path = None
    for file in os.listdir(
            os.path.join(settings.PROJECT_PATH, r"files",
                         r"user_" + str(uploaderpk))):
        if file.endswith(".shp"):
            onlyfiles.append(
                os.path.join(settings.PROJECT_PATH, r"files",
                             r"user_" + str(uploaderpk), file))
        elif file.endswith(".jpg"):
            kart_path = os.path.join(settings.PROJECT_PATH, r"files",
                                     r"user_" + str(uploaderpk), file)

    for el in onlyfiles:
        print("File: " + el.__str__())
    print("Map file: " + kart_path.__str__())
    arealsymboler, linjesymboler, punktsymboler, breakBoolean = geometryType(
        onlyfiles)
    if (breakBoolean):
        print(
            "Datafiles not containing all shapefiles( either point, polyline or polygon)"
        )
        return
    kart = kart_path  #os.path.join(settings.PROJECT_PATH, r"apps", r"findbestroute", r"workfiles", r"inData", r"kart.jpg") #geoProcess(kart_path, arealsymboler)

    start = getStart(punktsymboler)
    destination = getDestination(punktsymboler)
    mask = setMask(start, destination)

    arcpy.env.mask = os.path.join(basePath, r"Trash", r"mask.shp")

    utsnitt = getExtentOfMap(linjesymboler)

    hoydedata = arcpy.Clip_analysis(
        in_features=os.path.join(basePath, r"hoydeData", r"trondheiml.shp"),
        clip_features=utsnitt,
        out_feature_class=os.path.join(basePath, r"Trash", r"hoydedata.shp"),
        cluster_tolerance="")

    #Klipper til symbolene etter mask
    ar = arcpy.Clip_analysis(in_features=arealsymboler,
                             clip_features=mask,
                             out_feature_class=os.path.join(
                                 basePath, r"Trash", r"a5"),
                             cluster_tolerance="")
    ln = arcpy.Clip_analysis(in_features=linjesymboler,
                             clip_features=mask,
                             out_feature_class=os.path.join(
                                 basePath, r"Trash", r"a6"),
                             cluster_tolerance="")
    pt = arcpy.Clip_analysis(in_features=punktsymboler,
                             clip_features=mask,
                             out_feature_class=os.path.join(
                                 basePath, r"Trash", r"a7"),
                             cluster_tolerance="")

    #Runde ned alle symboler
    floorSymbols(ar)
    floorSymbols(ln)
    floorSymbols(pt)

    #Lage buffer paa linjer som er lik bredden de skal ha
    fieldnames = [field.name for field in arcpy.ListFields(ln)]
    if not "WIDTH" in fieldnames:
        arcpy.AddField_management(in_table=ln,
                                  field_name="WIDTH",
                                  field_type="DOUBLE")
    symbols = [
        106, 107, 201, 203, 304, 305, 307, 502, 503, 504, 505, 506, 507, 508,
        509
    ]
    width = [2, 2, 4, 4, 2, 2, 1, 6, 4, 3, 2.5, 2, 2, 2, 2]
    features = arcpy.UpdateCursor(ln)
    for feature in features:
        if feature.SYMBOL in symbols:
            n = symbols.index(feature.SYMBOL)
            feature.WIDTH = width[n]
        features.updateRow(feature)
    del feature, features, n
    ln_buff = arcpy.Buffer_analysis(in_features=ln,
                                    out_feature_class=os.path.join(
                                        basePath, r"Trash", r"a8"),
                                    buffer_distance_or_field="WIDTH",
                                    line_side="FULL",
                                    line_end_type="FLAT",
                                    dissolve_option="LIST",
                                    dissolve_field="SYMBOL")

    #Hente ut alle forbudte symboler
    forbiddenArea = arcpy.Select_analysis(
        in_features=ar,
        out_feature_class=os.path.join(basePath, r"Trash", r"a9"),
        where_clause=
        '"SYMBOL" = 202 OR "SYMBOL" = 211 OR "SYMBOL" = 301 OR "SYMBOL" = 302 OR "SYMBOL" = 307 OR "SYMBOL" = 415 OR "SYMBOL" = 526 OR "SYMBOL" = 527 OR "SYMBOL" = 528 OR "SYMBOL" = 709'
    )
    forbiddenLineBuff = arcpy.Select_analysis(
        in_features=ln_buff,
        out_feature_class=os.path.join(basePath, r"Trash", r"b1"),
        where_clause=
        '"SYMBOL" = 201 OR "SYMBOL" = 307 OR "SYMBOL" = 521 OR "SYMBOL" = 524 OR "SYMBOL" = 528 OR "SYMBOL" = 534 OR "SYMBOL" = 709'
    )

    #Hente ut alle passerbare symboler
    passableArea = arcpy.Select_analysis(
        in_features=ar,
        out_feature_class=os.path.join(basePath, r"Trash", r"b2"),
        where_clause=
        '"SYMBOL" <> 202 AND "SYMBOL" <> 211 AND "SYMBOL" <> 301 AND "SYMBOL" <> 302 AND "SYMBOL" <> 307 AND "SYMBOL" <> 415 AND "SYMBOL" <> 526 AND "SYMBOL" <> 527 AND "SYMBOL" <> 528 AND "SYMBOL" <> 601 AND "SYMBOL" <> 709'
    )
    passableLineBuff = arcpy.Select_analysis(
        in_features=ln_buff,
        out_feature_class=os.path.join(basePath, r"Trash", r"b3"),
        where_clause=
        '"SYMBOL" <> 201 AND "SYMBOL" <> 307 AND "SYMBOL" <> 521 AND "SYMBOL" <> 524 AND "SYMBOL" <> 528 AND "SYMBOL" <> 534 AND "SYMBOL" <> 709'
    )

    #Lage skogflater
    area = arcpy.Update_analysis(in_features=passableArea,
                                 update_features=forbiddenArea,
                                 out_feature_class=os.path.join(
                                     basePath, r"Trash", r"b4"))
    forest = arcpy.Erase_analysis(in_features=mask,
                                  erase_features=area,
                                  out_feature_class=os.path.join(
                                      basePath, r"Trash", r"b5"))
    arcpy.AddField_management(in_table=forest,
                              field_name="SYMBOL",
                              field_type="DOUBLE")
    features = arcpy.UpdateCursor(forest)
    for feature in features:
        feature.SYMBOL = 405
        features.updateRow(feature)
    del feature, features

    #Lage kartet i ArcMap
    area1 = arcpy.Erase_analysis(in_features=passableArea,
                                 erase_features=forbiddenArea,
                                 out_feature_class=os.path.join(
                                     basePath, r"Trash", r"b6"))
    area2 = arcpy.Erase_analysis(in_features=area1,
                                 erase_features=forbiddenLineBuff,
                                 out_feature_class=os.path.join(
                                     basePath, r"Trash", r"b7"))
    passable1 = arcpy.Update_analysis(in_features=area2,
                                      update_features=forest,
                                      out_feature_class=os.path.join(
                                          basePath, r"Trash", r"b8"))
    mapped = arcpy.Update_analysis(in_features=passable1,
                                   update_features=passableLineBuff,
                                   out_feature_class=os.path.join(
                                       basePath, r"Trash", r"b9"))

    #Sette kostnad paa alle flater
    setCost(mapped)
    print('hey')
    costRaster = arcpy.FeatureToRaster_conversion(
        mapped, "COST", os.path.join(basePath, r"Results", r"CostRaster.tif"))

    #Lage sloperaster

    #create a TIN of the area
    tin = arcpy.CreateTin_3d(
        out_tin=os.path.join(basePath, r"Results", r"TIN"),
        spatial_reference="#",
        in_features=os.path.join(basePath, r"Trash", r"hoydedata.shp") +
        " HOEYDE masspoints")

    # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
    # The following inputs are layers or table views: "hoydeTIN"
    tinRaster = arcpy.TinRaster_3d(in_tin=os.path.join(basePath, r"Results",
                                                       r"TIN"),
                                   out_raster=os.path.join(
                                       basePath, r"Results", "hRaster"),
                                   data_type="FLOAT",
                                   method="LINEAR",
                                   sample_distance="CELLSIZE 1",
                                   z_factor="1")

    # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
    # The following inputs are layers or table views: "hraster"
    slope = arcpy.Slope_3d(in_raster=os.path.join(basePath, r"Results",
                                                  r"hRaster"),
                           out_raster=os.path.join(basePath, r"Results",
                                                   r"slope"),
                           output_measurement="DEGREE",
                           z_factor="1")

    # Reklassifisering av slope
    reMapRange = RemapRange([[0, 0.5, 100], [0.5, 1, 101], [1, 2, 102],
                             [2, 3, 103], [3, 4, 104], [4, 5,
                                                        105], [5, 6, 106],
                             [6, 7, 107], [7, 8, 108], [8, 9, 109],
                             [9, 10, 110], [10, 11, 111], [11, 12, 112],
                             [12, 13, 113], [13, 14, 114], [14, 15, 115],
                             [15, 16, 116], [16, 17, 117], [17, 18, 118],
                             [18, 19, 119], [19, 20, 120], [20, 90, 150]])
    slope_reclass = Reclassify(in_raster=os.path.join(basePath, r"Results",
                                                      r"slope"),
                               reclass_field="VALUE",
                               remap=reMapRange)
    slope_reclass.save(os.path.join(basePath, r"Results", r"slopeReclass"))

    # Rasterkalkulator som lager raster som tar hensyn til hoyde i kostnadsrasteret
    finalCostRaster = Raster(
        os.path.join(basePath, r"Results", r"CostRaster.tif")) * (
            Raster(os.path.join(basePath, r"Results", r"slopeReclass")) / 100)

    #Regne ut leastcostpath
    cdr = arcpy.sa.CostDistance(start, finalCostRaster)
    cdr.save(os.path.join(basePath, r"Results", r"costDistance"))
    cbr = arcpy.sa.CostBackLink(start, finalCostRaster)
    cbr.save(os.path.join(basePath, r"Results", r"Costback"))
    cp = arcpy.sa.CostPath(destination, cdr, cbr, "EACH_CELL")
    cp.save(os.path.join(basePath, r"Results", r"costpath"))

    #Gjore om til polygon med litt bredde
    arcpy.RasterToPolygon_conversion(
        in_raster=os.path.join(basePath, r"Results", r"costpath"),
        out_polygon_features=os.path.join(basePath, r"Results", r"cpPoly.shp"),
        simplify="SIMPLIFY")
    arcpy.Buffer_analysis(in_features=os.path.join(basePath, r"Results",
                                                   r"cpPoly.shp"),
                          out_feature_class=os.path.join(
                              basePath, r"Results", r"LCP.shp"),
                          buffer_distance_or_field="2",
                          line_side="FULL",
                          line_end_type="FLAT",
                          dissolve_option="LIST")

    df = arcpy.mapping.ListDataFrames(mxd, "*")[0]
    for lyr in arcpy.mapping.ListLayers(mxd, "", df):
        arcpy.mapping.RemoveLayer(df, lyr)
    print("Deleted lyr's in mxd")
    #Legge til i ArcMap
    templateLayer = arcpy.mapping.Layer(
        os.path.join(basePath, r"Template", r"colorTemplate.lyr"))
    df = arcpy.mapping.ListDataFrames(mxd, "*")[0]
    newlayer = arcpy.mapping.Layer(
        os.path.join(basePath, r"Results", r"LCP.shp"))
    newlayer.transparency = 50
    """ PROBLEMBARN RETT UNDER """
    arcpy.ApplySymbologyFromLayer_management(in_layer=newlayer,
                                             in_symbology_layer=templateLayer)
    #                                            in_symbology_layer = os.path.join(basePath, r"Template", r"colorTemplate.lyr"))
    """ PROBLEMBARN RETT OVER """

    arcpy.mapping.AddLayer(df, newlayer, "BOTTOM")
    arcpy.MakeRasterLayer_management(in_raster=kart,
                                     out_rasterlayer=os.path.join(
                                         basePath, r"Results", r"rasterkart"))
    mapLayer = arcpy.mapping.Layer(
        os.path.join(basePath, r"Results", r"rasterkart"))
    arcpy.mapping.AddLayer(df, mapLayer, "BOTTOM")

    # Lage postsirkler og linje og legge til dette i ArcGIS
    points = arcpy.CreateFeatureclass_management(out_path=os.path.join(
        basePath, r"Trash"),
                                                 out_name="points",
                                                 geometry_type="POINT")

    del destination
    start = getStart(pt)
    destination = getDestination(pt)
    features = arcpy.UpdateCursor(start)
    for feature in features:
        startX = feature.POINT_X
        startY = feature.POINT_Y
    features = arcpy.UpdateCursor(destination)
    for feature in features:
        destX = feature.POINT_X
        destY = feature.POINT_Y
    cursor = arcpy.da.InsertCursor(points, ("fid", "SHAPE@XY"))
    cursor.insertRow((1, (startX, startY)))
    cursor.insertRow((2, (destX, destY)))
    del destination

    outerCircle = arcpy.CreateFeatureclass_management(out_path=os.path.join(
        basePath, r"Trash"),
                                                      out_name="circles1.shp",
                                                      geometry_type="POLYGON")
    innerCircle = arcpy.CreateFeatureclass_management(out_path=os.path.join(
        basePath, r"Trash"),
                                                      out_name="circles2.shp",
                                                      geometry_type="POLYGON")
    circle = arcpy.CreateFeatureclass_management(
        out_path=os.path.join(basePath, r"Trash"),
        out_name="circles.shp",
        geometry_type="POLYGON",
    )
    arcpy.Buffer_analysis(points, outerCircle, 40)
    arcpy.Buffer_analysis(points, innerCircle, 35)
    arcpy.Erase_analysis(outerCircle, innerCircle, circle)
    symLayer = arcpy.mapping.Layer(
        os.path.join(basePath, r"Template", r"color2.lyr"))
    circleLayer = arcpy.mapping.Layer(
        os.path.join(basePath, r"Trash", r"circles.shp"))
    arcpy.ApplySymbologyFromLayer_management(in_layer=circleLayer,
                                             in_symbology_layer=symLayer)
    arcpy.mapping.AddLayer(data_frame=df,
                           add_layer=circleLayer,
                           add_position="TOP")

    # Lage postlinje
    lines = arcpy.CreateFeatureclass_management(out_path=os.path.join(
        basePath, r"Trash"),
                                                out_name="line.shp",
                                                geometry_type="POLYGON")
    directionX = (destX - startX) / (
        math.sqrt(math.pow(destX - startX, 2) + math.pow(destY - startY, 2)))
    directionY = (destY - startY) / (
        math.sqrt(math.pow(destX - startX, 2) + math.pow(destY - startY, 2)))
    features = []
    features.append(
        arcpy.Polyline(
            arcpy.Array([
                arcpy.Point(startX + 45 * directionX,
                            startY + 45 * directionY),
                arcpy.Point(destX - 45 * directionX, destY - 45 * directionY)
            ])))
    lineFeat = arcpy.CopyFeatures_management(
        features, os.path.join(basePath, r"Trash", r"lines.shp"))
    arcpy.Buffer_analysis(in_features=lineFeat,
                          out_feature_class=lines,
                          buffer_distance_or_field=2.5,
                          line_end_type="FLAT")
    lineLayer = arcpy.mapping.Layer(
        os.path.join(basePath, r"Trash", r"line.shp"))
    arcpy.ApplySymbologyFromLayer_management(in_layer=lineLayer,
                                             in_symbology_layer=symLayer)
    arcpy.mapping.AddLayer(data_frame=df,
                           add_layer=lineLayer,
                           add_position="TOP")

    mxd.save()

    #Skrive ut bilde av veivalg
    B = df.extent.XMax - df.extent.XMin
    H = df.extent.YMax - df.extent.YMin

    filename = str(uploaderpk) + "_" + time.strftime(
        "%d-%m-%Y") + "_" + time.strftime("%H-%M-%S") + ".png"
    relative_path_string = os.path.join(r"Dump", filename)
    print("hurr  " + settings.PROJECT_PATH)
    print("durr " + relative_path_string)
    out_path = os.path.join(settings.PROJECT_PATH, "files", r"Dump", filename)
    print(out_path)
    arcpy.mapping.ExportToPNG(map_document=mxd,
                              out_png=out_path,
                              data_frame=df,
                              df_export_width=int(3 * B),
                              df_export_height=int(3 * H),
                              resolution=225)
    print("Finished making image")

    #relative_path = os.path.join(r"Dump", "MapLCP.png")
    img = Image()
    img.uploader = PathUser.objects.get(pk=uploaderpk)
    img.bilde = relative_path_string
    img.save()

    folder = os.path.join(basePath, r"Trash")
    for file in os.listdir(folder):
        filepath = os.path.join(folder, file)
        try:
            if os.path.isfile(filepath):
                print "Removing " + filepath
                os.remove(filepath)
            elif os.path.isdir(filepath):
                print "Removing " + filepath
                shutil.rmtree(filepath)
        except Exception as e:
            print(e)

    folder = os.path.join(basePath, r"Results")
    for file in os.listdir(folder):
        filepath = os.path.join(folder, file)
        try:
            if os.path.isfile(filepath):
                print "Removing " + filepath
                os.remove(filepath)
            elif os.path.isdir(filepath):
                print "Removing " + filepath
                shutil.rmtree(filepath)
        except Exception as e:
            print(e)

    delete_user_uploads.delay(uploaderpk)

    end = time.time()
    print(end - startTime)
Exemplo n.º 14
0
polygon = arcpy.Polygon(arcpy.Array(boundaryPoints))
arcpy.CreateFeatureclass_management(arcpy.env.workspace,
                                    name + '_Boundary.shp', 'POLYGON', polygon)
arcpy.CopyFeatures_management(polygon, name + '_Boundary.shp')
arcpy.AddMessage(name + '_Boundary.shp generated.')

# Create TIN based on topo data and boundary
arcpy.CreateTin_3d(name + '_TIN')
arcpy.EditTin_3d(
    name + '_TIN',
    [[name + '_Points.shp', 'Z', '<None>', 'Mass_Points', False],
     [name + '_Boundary.shp', '<None>', '<None>', 'Soft_Clip', False]])
arcpy.AddMessage(name + '_TIN generated.')

# Create raster out of TIN
arcpy.TinRaster_3d(name + '_TIN',
                   name + '_Raster.tif',
                   'FLOAT',
                   'LINEAR',
                   sample_distance='CELLSIZE {}'.format(cellsize),
                   z_factor=1)
arcpy.AddMessage(name + '_Raster.tif generated.')

# Create hillshade out of raster
arcpy.HillShade_3d(name + '_Raster.tif',
                   name + '_Hillshade.tif',
                   azimuth,
                   altitude,
                   z_factor=1)
arcpy.AddMessage(name + '_Hillshade.tif generated.')
def inundation_map_builder(cut_line_file, profile, output_raster,
                           output_shapefile):

    xs_cut_lines = cut_line_file
    profile = profile
    output_shapefile = output_shapefile
    output_raster = output_raster

    try:
        if arcpy.CheckExtension("3D") == "Available":
            arcpy.CheckOutExtension("3D")
        else:
            # Raise a custom exception
            #
            raise LicenseError

        if arcpy.CheckExtension("Spatial") == "Available":
            arcpy.CheckOutExtension("Spatial")
        else:
            # Raise a custom exception
            #
            raise LicenseError

        # Local variables:
        modelbuild = "D:\\LittleCal_Inundations\\TINS\\modelbuildtin"
        modelbuild11 = "D:\\LittleCal_Inundations\\Rasters\\modelbuild11"
        cook_thorn = "D:\GIS\cook_thorn"
        modelbuild13 = "D:\\LittleCal_Inundations\\Rasters\\" + output_raster
        mdelbuild1int = "D:\\LittleCal_Inundations\\Rasters\\mdelbuild1int"
        modelbuild1dis_shp = "D:\\LittleCal_Inundations\\Shapefiles\\modelbuild1dis.shp"
        modelbuild1_shp = "D:\\LittleCal_Inundations\\Shapefiles\\" + output_shapefile

        mapping_xs = "D:\LittleCal_Inundations\Shapefiles\MappingXS.shp"
        bound_poly = "D:\\LittleCal_Inundations\\Shapefiles\\BoundingPolygonLeveet.shp"

        params = mapping_xs + " " + profile + " Soft_Line <None>; " + bound_poly + " <None> " + "Hard_Clip <None>"

        #params = "XSCutlines2.shp 05FEB2008_2400 Soft_Line <None>; BoundingPolygonLeveet.shp <None> Hard_Clip <None>"

        coord = "PROJCS['NAD83 / Illinois East (ftUS)',GEOGCS['GCS_North_American_1983'," + \
                "DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]]," + \
                "PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]," + \
                "PROJECTION['Transverse_Mercator'],PARAMETER['false_easting',984250.0]," + \
                "PARAMETER['false_northing',0.0],PARAMETER['central_meridian',-88.33333333333333]," + \
                "PARAMETER['scale_factor',0.999975]," + \
                "PARAMETER['latitude_of_origin',36.66666666666666]," + \
                "UNIT['Foot_US',0.3048006096012192]]"

        # Replace a layer/table view name with a path to a dataset (which can be a layer file) or create the layer/table view within the script
        # The following inputs are layers or table views: "Mapping_XS", "XS Cut Lines"
        arcpy.JoinField_management(in_data=mapping_xs,
                                   in_field="ProfileM",
                                   join_table=xs_cut_lines,
                                   join_field="ProfileM",
                                   fields=profile)

        # Process: Create TIN
        arcpy.CreateTin_3d(modelbuild, coord, params, "DELAUNAY")

        # Process: TIN to Raster
        arcpy.TinRaster_3d(modelbuild, modelbuild11, "FLOAT", "LINEAR",
                           "CELLSIZE 2", "1")

        # Process: Raster Calculator
        modelbuild12 = ((Raster(modelbuild11) - Raster(cook_thorn)) *
                        ((Raster(modelbuild11) - Raster(cook_thorn)) > 0))

        # Process: Set Null
        arcpy.gp.SetNull_sa(modelbuild12, modelbuild12, modelbuild13,
                            "VALUE = 0")

        # Process: Int
        arcpy.Int_3d(modelbuild13, mdelbuild1int)

        # Process: Raster to Polygon
        arcpy.RasterToPolygon_conversion(mdelbuild1int, modelbuild1dis_shp,
                                         "SIMPLIFY", "Value")

        arcpy.RepairGeometry_management(modelbuild1dis_shp)

        # Process: Dissolve
        arcpy.Dissolve_management(modelbuild1dis_shp, modelbuild1_shp, "", "",
                                  "MULTI_PART", "DISSOLVE_LINES")

        arcpy.DeleteField_management(in_table=mapping_xs, drop_field=profile)

    except LicenseError:
        print("3D or Spatial Analyst license is unavailable")

    except arcpy.ExecuteError:
        print(arcpy.GetMessages(2))

    finally:
        arcpy.CheckInExtension("3D")
        arcpy.CheckInExtension("Spatial")
Exemplo n.º 16
0
#checking license availability
if arcpy.CheckExtension("3D") == "Available":
    #Take a license
    arcpy.CheckOutExtension("3D")
    #Create a new empty TIN
    arcpy.CreateTin_3d("tin2")
    #Edit TIN
    arcpy.EditTin_3d("tin2", parameters)
    ##    arcpy.EditTin_3d("tin2", inFCs)
    #Tin to raster
    data_type = "FLOAT"
    interp_method = "LINEAR"
    samp_method = "CELLSIZE 10"
    factor = 1
    arcpy.TinRaster_3d(output_folder + "\\tin2", output_folder + "\\grid",
                       interp_method, samp_method, factor)

    #release the license
    arcpy.CheckInExtension("3D")
else:
    print('License not available')

#-------------------------------------------------------------------------------
# CHECKING LICENSES
#-------------------------------------------------------------------------------
import arcpy
arcpy.env.overwriteOutput = True
arcpy.env.workspace = r"C:\ELVLC\DATA\castilla-leon"

#output folder
output = 'C:\ELVLC\DATA\results'
Exemplo n.º 17
0
# -*- coding: utf-8 -*-
import arcpy
"""
此脚本的优势是能够解决用gispro或arcmap不能对县域大量等高线和高程点数据进行处理的问题
"""

# 输入参数
dgx = "I:\\毕节国土空间规划\\分析库\\地形图信息提取.gdb\\等高线_首曲线"
gcd = "I:\\毕节国土空间规划\\分析库\\地形图信息提取.gdb\\高程点"
# 输出参数
cellsize = "5"  # 以米为单位
tin = "F:\\test\\tin"
dem = "F:\\test\\dem"


arcpy.env.overwriteOutput = True
arcpy.AddMessage("begin to create TIN.....")
arcpy.CreateTin_3d(out_tin=tin, spatial_reference="", in_features=[[dgx, "Elevation", "Hard_Line", "<None>"], [gcd, "Elevation", "Mass_Points", "<None>"]], constrained_delaunay="DELAUNAY")
arcpy.AddMessage("begin to create DEM.....")
arcpy.TinRaster_3d(in_tin=tin, out_raster=dem, data_type="FLOAT", method="LINEAR", sample_distance="CELLSIZE " + cellsize, z_factor=1, sample_value=250)

Exemplo n.º 18
0
        

        arcpy.AddMessage('Your TIN ' + str(args.OutputTIN) + ' has been successfully created.')

        #If the user checked the create DEM then create DEM, if user said to delete the TIN then delete TIN
        if args.OutputDEM:
            
            if os.path.exists(args.OutputDEM):
                arcpy.AddMessage(args.OutputDEM + ' already exists.')
                arcpy.CheckInExtension('3D')
                sys.exit()
            else:    
                arcpy.AddMessage('Creating DEM...')
                outDEM = args.OutputDEM
                cellSize = args.CellSize
                arcpy.TinRaster_3d(args.OutputTIN, args.OutputDEM, 'FLOAT', 'NATURAL_NEIGHBORS', 'CELLSIZE ' + args.CellSize)
                arcpy.AddMessage('Your DEM ' + args.OutputDEM + ' was successfully created.\n')
                if args.DeleteTIN:
                    #The folder to contain the TIN automatically changes the users inputs to all lowercase letters, the below makes
                    #the input argument the same and removes the folder
                    shutil.rmtree(os.path.split(args.OutputTIN)[0] + '\\' + os.path.split(args.OutputTIN)[1].lower())
                    arcpy.AddMessage('The input tin ' + args.OutputTIN + ' was removed.')
       
except:
    arcpy.CheckInExtension('3D')
    arcpy.AddMessage(sys.exc_info()[1])
    
finally:
    arcpy.CheckInExtension('3D')