print "Processing variable " + ncVar  #NSN:REMOVE
        ncVarFolderPath = scratchPath + os.sep + ncVar.lower()
        if not os.path.exists(ncVarFolderPath):
            os.makedirs(
                ncVarFolderPath)  #TODO: Check if exist, delete if necessary

        for t in range(ncTimeDimSize):
            outNcFeatureLayer = "outNcFeatureLayer"
            rowDimensions = str(ncXDim + ';' + ncYDim)
            ncTimeDimValue = str(ncTimeDim + ' ' + str(t))
            valueSelectionMethod = "BY_INDEX"
            #print rowDimensions, ncTimeDimValue #NSN:REMOVE

            #Execute MakeNetCDFFeatureLayer
            result = arcpy.MakeNetCDFFeatureLayer_md(
                inNetCDFFile, ncVar, ncXDimAuCoord, ncYDimAuCoord,
                outNcFeatureLayer, rowDimensions, "", "", ncTimeDimValue,
                valueSelectionMethod)

            rasSuffix = str(t).zfill(len(str(ncTimeDimSize)))
            outRasName = ncVar.lower(
            ) + rasSuffix + ".img"  #Creating grid, add .tif for tiff
            outRasName = ncVarFolderPath + os.sep + outRasName
            print outRasName  #NSN:REMOVE

            # Execute NaturalNeighbor and save it
            cellSize = min(
                ncXDimAuCoordInterval,
                ncYDimAuCoordInterval) / 2  #0.052 adjust if necessary
            outRas = NaturalNeighbor(outNcFeatureLayer, ncVar, cellSize)
            outRas.save(
                outRasName)  #TODO: Uncomment this if you comment out clipping
    def execute(self, parameters, messages):
        """The source code of the tool."""
        # Describe the supplied netCDF File.
        ncFP = arcpy.NetCDFFileProperties(parameters[0].valueAsText)
        selectedVars = parameters[1].valueAsText.split(';')

        # Coordinate variables can be identified via values of their standard
        # name attribute or values of their untis attribute.

        XCoordNamesList = [
            "longitude", "projection_x_coordinate", "grid_longitude"
        ]
        YCoordNamesList = [
            "latitude", "projection_y_coordinate", "grid_longitude"
        ]
        XUnitNamesList = [
            "degrees_east", "degree_east", "degree_E", "degrees_E", "degreeE",
            "degreesE"
        ]
        YUnitNamesList = [
            "degrees_north", "degree_north", "degree_N", "degrees_N",
            "degreeN", "degreesN"
        ]
        XAxisNameList = ["X"]
        YAxisNameList = ["Y"]

        # Case #1: Trajectory variable can be identified under two conditions;
        # the presence of a attribute name of 'positive' on a variable or
        # the presence of the units variable with a units of pressure (pascal).

        x_variable = ''
        y_variable = ''
        ZVariable = ''

        if (not x_variable) or (not y_variable):
            try:
                coordAttributeValue = ncFP.getAttributeValue(
                    str(selectedVars[0]), "coordinates")
                coordVariables = coordAttributeValue.split(' ')
                for element in coordVariables:
                    try:
                        ZAttribute = ncFP.getAttributeValue(
                            element, "positive")
                        if ZAttribute.upper() == 'UP' or ZAttribute.upper() \
                        == 'DOWN':
                            ZVariable = element
                    except:
                        pass

                    try:
                        SNattributeValue = ncFP.getAttributeValue(
                            element, "standard_name")
                    except:
                        SNattributeValue = "missing"

                    try:
                        UNattributeValue = ncFP.getAttributeValue(
                            element, "units")
                        if UNattributeValue.upper() == 'PASCAL':
                            ZVariable = element
                    except:
                        UNattributeValue = "missing"

                    try:
                        AXattributeValue = ncFP.getAttributeValue(
                            element, "axis")
                    except:
                        AXattributeValue = "missing"

                    if SNattributeValue in XCoordNamesList:
                        x_variable = element
                    if SNattributeValue in YCoordNamesList:
                        y_variable = element
                    if UNattributeValue in XUnitNamesList:
                        x_variable = element
                    if UNattributeValue in YUnitNamesList:
                        y_variable = element
                    if AXattributeValue in XAxisNameList:
                        x_variable = element
                    if AXattributeValue in YAxisNameList:
                        y_variable = element

            except:
                CoordAttributeValue = "missing"

        # Convert the python list of selected variable into a single
        # (comma delimited) string if necessary.

        if selectedVars.count > 1:
            variable_list = ','.join([str(x) for x in selectedVars])
        else:
            variable_list = selectedVars[0]

        # Set the row dimensions parameter of the Make NetCDF Feature Layer tool
        # to the trajectory dimension name.

        try:
            dimNames = ncFP.getDimensionsByVariable(selectedVars[0])
            row_dimension = str(dimNames[-1])
        except:
            row_dimension = ""

        if (x_variable) and (y_variable) and (row_dimension):
            if (debug):
                arcpy.AddWarning("netCDFFile Name: %s" % \
                    parameters[0].valueAsText)
                arcpy.AddWarning("Variable List: %s" % variable_list)
                arcpy.AddWarning("x_variable: %s" % x_variable)
                arcpy.AddWarning("y_variable: %s" % y_variable)
                arcpy.AddWarning("Output Feature Layer: %s " % \
                    parameters[2].valueAsText)
                arcpy.AddWarning("Row Dimensions: %s " % row_dimension)
                arcpy.AddWarning("Z Variable: %s " % ZVariable)

            result1 = arcpy.MakeNetCDFFeatureLayer_md(
                parameters[0].valueAsText, variable_list, x_variable,
                y_variable, parameters[2].valueAsText, row_dimension,
                ZVariable)

            # Force the netCDF Feature Layer to be added to the display
            arcpy.SetParameter(3, result1)
        else:
            if (not x_variable) or (not y_variable):
                msg1 = "Unable to automatically determine x and y variables " \
                   + "from the netCDF file. Use Make NetCDF Feature Layer tool."
                arcpy.AddError(msg1)
            if (not row_dimension):
                msg1 = "Unable to automatically determine row dimension " \
                     + "variable(s) from the netCDF file. Use Make NetCDF " \
                    + "Feature Layer tool."
                arcpy.AddError(msg1)
        return
    def mpprocess(output_directory, variable_name, input_woa_netcdf,
                  interpolation_procedure, interpolation_resolution,
                  coordinate_system, extraction_extent, createxyz,
                  depth_range):
        try:
            i = depth_range

            status = "Started"

            arcpy.env.extent = extraction_extent

            arcpy.AddMessage("Processing depth: " + str(int(i)))

            out_temp_layer = variable_name[0:4] + str(int(i)) + ".shp"
            dimensionValues = "depth " + str(int(i))

            output_dir_geographic = os.path.join(
                output_directory, "temp", "Geographic",
                variable_name[0:4] + str(int(i)))
            output_geographic = os.path.join(output_dir_geographic,
                                             variable_name[0:4] + str(int(i)))

            output_dir_projected = os.path.join(
                output_directory, "temp", "Projected",
                variable_name[0:4] + str(int(i)))
            output_projected = os.path.join(output_dir_projected,
                                            variable_name[0:4] + str(int(i)))

            if not os.path.exists(
                    os.path.join(output_dir_projected,
                                 "xy_coords.yxz")) or os.path.exists(
                                     os.path.join(output_dir_geographic,
                                                  "xy_coords.yxz")):

                if not os.path.exists(output_dir_geographic):
                    os.makedirs(output_dir_geographic)

                if not os.path.exists(output_dir_projected):
                    os.makedirs(output_dir_projected)

                env.workspace = os.path.join(output_directory, "temp",
                                             variable_name[0:4] + str(int(i)))

                # 1 Extract layer to a temporary feature class
                arcpy.MakeNetCDFFeatureLayer_md(
                    in_netCDF_file=input_woa_netcdf,
                    variable=variable_name,
                    x_variable="lon",
                    y_variable="lat",
                    out_feature_layer=out_temp_layer,
                    row_dimension="lat;lon",
                    z_variable="",
                    m_variable="",
                    dimension_values=dimensionValues,
                    value_selection_method="BY_VALUE")

                # 2 Interpolate to higher resolution and 3 save to output directory
                if interpolation_procedure == "IDW":
                    status = "Interpolating " + str(int(i)) + " using IDW"
                    arcpy.gp.Idw_sa(out_temp_layer, variable_name,
                                    output_geographic,
                                    interpolation_resolution, "2",
                                    "VARIABLE 10", "")
                elif interpolation_procedure == "Spline":
                    status = "Interpolating " + str(int(i)) + " using Spline"
                    arcpy.CopyFeatures_management(
                        out_temp_layer,
                        os.path.join(output_dir_geographic, "out.shp"))
                    arcpy.gp.Spline_sa(out_temp_layer, variable_name,
                                       output_geographic,
                                       interpolation_resolution, "TENSION",
                                       "0.1", "10")
                    arcpy.Delete_management(
                        os.path.join(output_directory, "temp", "Geographic",
                                     variable_name[0:4] + str(int(i)),
                                     "out.shp"))
                elif interpolation_procedure == "Kriging":
                    status = "Interpolating " + str(
                        int(i)) + " using Ordinary Kriging"
                    arcpy.gp.Kriging_sa(
                        out_temp_layer, variable_name, output_geographic,
                        "Spherical " + str(interpolation_resolution),
                        interpolation_resolution, "VARIABLE 10", "")

                elif interpolation_procedure == "None":
                    status = "Making a raster for " + str(int(i))
                    arcpy.MakeNetCDFRasterLayer_md(
                        in_netCDF_file=input_woa_netcdf,
                        variable=variable_name,
                        x_dimension="lon",
                        y_dimension="lat",
                        out_raster_layer=output_geographic,
                        band_dimension="",
                        dimension_values="",
                        value_selection_method="BY_VALUE")

                if len(coordinate_system) > 1:
                    status = "Reprojecting " + variable_name[0:4] + str(
                        int(i)) + "."
                    arcpy.ProjectRaster_management(output_geographic,
                                                   output_projected,
                                                   coordinate_system,
                                                   "NEAREST", "#", "#", "#",
                                                   "#")

                if createxyz == "Only Geographic" or createxyz == "Both":
                    status = "Building geographic xy coords for " + variable_name[
                        0:4] + str(int(i)) + "."
                    raster_to_xyz(output_geographic,
                                  variable_name[0:4] + str(int(i)),
                                  output_dir_geographic, 349000000.0)

                    df = pd.read_csv(os.path.join(
                        output_dir_geographic,
                        variable_name[0:4] + str(int(i)) + ".yxz"),
                                     header=0,
                                     names=["y", "x", "z"],
                                     sep=" ",
                                     dtype={
                                         "y": np.float32,
                                         "x": np.float32,
                                         "z": np.float32
                                     })
                    master = df[["x", "y"]].copy()
                    master.columns = ["x", "y"]
                    master = np.round(master, 4)
                    master.to_pickle(
                        os.path.join(output_dir_geographic, "xy_coords.yxz"))
                    del master, df
                    gc.collect()

                if createxyz == "Only Projected" or createxyz == "Both":
                    status = "Building projected xy coords for " + variable_name[
                        0:4] + str(int(i)) + "."
                    raster_to_xyz(output_projected,
                                  variable_name[0:4] + str(int(i)),
                                  output_dir_projected, 349000000.0)

                    df = pd.read_csv(os.path.join(
                        output_dir_projected,
                        variable_name[0:4] + str(int(i)) + ".yxz"),
                                     header=0,
                                     names=["y", "x", "z"],
                                     sep=" ",
                                     dtype={
                                         "y": np.float32,
                                         "x": np.float32,
                                         "z": np.float32
                                     })
                    master = df[["x", "y"]].copy()
                    master.columns = ["x", "y"]
                    master = np.round(master, 4)
                    master.to_pickle(
                        os.path.join(output_dir_projected, "xy_coords.yxz"))
                    del master, df
                    gc.collect()
            else:
                arcpy.AddMessage("Skipping " + str(int(i)) + ".")
        except:
            arcpy.AddMessage("Failed on " + str(int(i)) + ",at status: " +
                             str(status))
            arcpy.AddMessage(arcpy.GetMessages())
Ejemplo n.º 4
0
    def execute(self, parameters, messages):

        t_start = time.clock()

        arcpy.env.overwriteOutput = True

        for param in parameters:
            arcpy.AddMessage("Parameter: %s = %s" % (param.name, param.valueAsText))

        input_woa_netcdf = parameters[0].valueAsText
        variable_name = parameters[1].valueAsText
        lat_name = parameters[2].valueAsText
        lon_name = parameters[3].valueAsText
        depth_name = parameters[4].valueAsText
        depths = parameters[5].valueAsText
        interpolation_procedure = parameters[6].valueAsText
        interpolation_resolution = parameters[7].valueAsText
        extraction_extent = parameters[8].valueAsText
        temporary_directory = parameters[9].valueAsText
        output_directory = parameters[10].valueAsText
        coordinate_system = parameters[11].valueAsText
        createxyz = parameters[12].valueAsText

        if not os.path.exists(output_directory):
            os.makedirs(output_directory)

        if not os.path.exists(os.path.join(output_directory, "Projected")):
            os.makedirs(os.path.join(output_directory, "Projected"))

        if not os.path.exists(os.path.join(output_directory, "Geographic")):
            os.makedirs(os.path.join(output_directory, "Geographic"))

        if not os.path.exists(temporary_directory):
            os.makedirs(temporary_directory)

        arcpy.env.extent = extraction_extent

        arcpy.AddMessage("Extracting " + str(input_woa_netcdf) + ".")

        # Set environment variables and build other variables for processing
        arcpy.env.mask = ""
        arcpy.env.workspace = temporary_directory
        depth_range = load_depth_string(depths)

        # Process goes: 1) Convert depth layer to a point file. 2) Interpolate to selected resolution using your selected
        # interpolation procedure, 3) Save that layer back into a layer with the name of the variable, plus the
        # actual depth value associated with it, you will end up with a specified direction of n rasters (n = number of
        # depth layers.

        # First lets give an indication of the magnitude of this analysis
        arcpy.AddMessage("There are " + str(len(depth_range)) + " depths to process.")

        count_geo = 0
        count_proj = 0

        for i in depth_range:
            arcpy.AddMessage("Working on " + str(int(i)))

            # Set some values that we will use to extract data from the NetCDF file
            out_temp_layer = os.path.join(output_directory, "out.shp")

            dimensionValues = str(depth_name) + " " + str(int(i))

            arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(4326)

            # 1 Extract layer to a temporary feature class
            arcpy.MakeNetCDFFeatureLayer_md(in_netCDF_file=input_woa_netcdf, variable=variable_name, x_variable=str(lon_name),
                                            y_variable=str(lat_name),
                                            out_feature_layer=out_temp_layer,
                                            row_dimension=str(lat_name) + ";" + str(lon_name),
                                            z_variable="", m_variable="", dimension_values=dimensionValues,
                                            value_selection_method="BY_VALUE")

            # 2 Interpolate to higher resolution and 3 save to output directory
            if interpolation_procedure == "IDW":
                arcpy.AddMessage("Interpolating " + str(int(i)) + " using IDW")
                arcpy.gp.Idw_sa(out_temp_layer, variable_name,
                                os.path.join(output_directory, "Geographic", variable_name[0:4] + str(int(i))),
                                interpolation_resolution, "2", "VARIABLE 10", "")
            elif interpolation_procedure == "Spline":
                arcpy.AddMessage("Interpolating " + str(int(i)) + " using Spline")
                arcpy.gp.Spline_sa(out_temp_layer, variable_name,
                                   os.path.join(output_directory, "Geographic", variable_name[0:4] + str(int(i))),
                                   interpolation_resolution, "TENSION", "0.1", "10")
                arcpy.Delete_management(os.path.join(output_directory, "out.shp"))
            elif interpolation_procedure == "Kriging":
                arcpy.AddMessage("Interpolating " + str(int(i)) + " using Ordinary Kriging")
                arcpy.gp.Kriging_sa(out_temp_layer, variable_name,
                                    os.path.join(output_directory, "Geographic", variable_name[0:4] + str(int(i))),
                                    "Spherical " + str(interpolation_resolution), interpolation_resolution,
                                    "VARIABLE 10", "")

            elif interpolation_procedure == "Natural Neighbor":
                arcpy.AddMessage("Interpolating " + str(int(i)) + " using Natural Neighbor")
                arcpy.NaturalNeighbor_3d(out_temp_layer, variable_name,
                                         os.path.join(output_directory, "Geographic", variable_name[0:4] + str(int(i))),
                                         interpolation_resolution)

            elif interpolation_procedure == "Natural Neighbor and IDW":
                arcpy.AddMessage("Interpolating " + str(int(i)) + " using Natural Neighbor and IDW")

                if not os.path.exists(os.path.join(output_directory, "temp", "idw")):
                    os.makedirs(os.path.join(output_directory, "temp", "idw"))

                if not os.path.exists(os.path.join(output_directory, "temp", "nat")):
                    os.makedirs(os.path.join(output_directory, "temp", "nat"))

                arcpy.NaturalNeighbor_3d(out_temp_layer, variable_name,
                                         os.path.join(output_directory, "temp", "nat", variable_name[0:4] + str(int(i))),
                                         interpolation_resolution)

                arcpy.gp.Idw_sa(out_temp_layer, variable_name,
                                os.path.join(output_directory, "temp", "idw", variable_name[0:4] + str(int(i))),
                                interpolation_resolution, "2", "VARIABLE 10", "")

                input_rasters = [os.path.join(output_directory, "temp", "nat", variable_name[0:4] + str(int(i))),
                                 os.path.join(output_directory, "temp", "idw", variable_name[0:4] + str(int(i)))]

                arcpy.MosaicToNewRaster_management(input_rasters=input_rasters,
                                                   output_location=os.path.join(out_dir, "Geographic"),
                                                   raster_dataset_name_with_extension=str(i),
                                                   coordinate_system_for_the_raster="",
                                                   pixel_type="8_BIT_UNSIGNED", cellsize="",
                                                   number_of_bands="1", mosaic_method="FIRST", mosaic_colormap_mode="FIRST")

            elif interpolation_procedure == "None":
                arcpy.AddMessage("Making a raster for " + str(int(i)))
                arcpy.MakeNetCDFRasterLayer_md(in_netCDF_file=input_woa_netcdf, variable=variable_name,
                                               x_dimension=lon_name, y_dimension=lat_name,
                                               out_raster_layer=variable_name[0:4] + str(int(i)),
                                               band_dimension="", dimension_values="",
                                               value_selection_method="BY_VALUE")
                arcpy.CopyRaster_management(variable_name[0:4] + str(int(i)),
                                            os.path.join(output_directory, "Geographic", variable_name[0:4] + str(int(i))),
                                            "", "", "", "NONE", "NONE", "")

            if len(coordinate_system) > 1:
                arcpy.AddMessage("Reprojecting " + variable_name[0:4] + str(int(i)) + ".")
                arcpy.ProjectRaster_management(os.path.join(output_directory, "Geographic", variable_name[0:4] + str(int(i))),
                                               os.path.join(output_directory, "Projected", variable_name[0:4] + str(int(i))),
                                               coordinate_system, "NEAREST", "#", "#", "#", "#")

            arcpy.AddMessage("Generating master file for trilinear interpolation")

            if createxyz == "Only Geographic" or createxyz == "Both":
                if not os.path.exists(os.path.join(output_directory, "Geographic_yxz")):
                    os.makedirs(os.path.join(output_directory, "Geographic_yxz"))
                raster_to_xyz(os.path.join(output_directory, "Geographic", variable_name[0:4] + str(int(i))),
                              variable_name[0:4] + str(int(i)),
                              os.path.join(output_directory, "Geographic_yxz"), 349000000.0)
                depth = int(filter(str.isdigit, str(i)))

                if count_geo == 0:
                    df = pd.read_csv(os.path.join(output_directory, "Geographic_yxz", variable_name[0:4] + str(int(i)) + ".yxz"),
                                     header=0, names=["y", "x", "z"], sep=" ", dtype={"y": np.float64,  "x": np.float64, "z": np.float64})
                    master = df[["x", "y", "z"]].copy()
                    master.columns = ["x", "y", int(depth)]
                    master.to_pickle(os.path.join(output_directory, "Geographic_yxz", "master.pkl"))
                    os.remove(os.path.join(output_directory, "Geographic_yxz", variable_name[0:4] + str(int(i)) + ".yxz"))
                    del df, master
                    gc.collect()
                    count_geo = 1
                if count_geo == 1:
                    master = pd.read_pickle(os.path.join(output_directory, "Geographic_yxz", "master.pkl"))
                    df = pd.read_csv(os.path.join(output_directory, "Geographic_yxz", variable_name[0:4] + str(int(i)) + ".yxz"),
                                     header=0, names=["y", "x", "z"], sep=" ", dtype={"y": np.float64,  "x": np.float64, "z": np.float64})
                    master[int(depth)] = df["z"].copy()
                    master.to_pickle(os.path.join(output_directory, "Geographic_yxz", "master.pkl"))
                    os.remove(os.path.join(output_directory, "Geographic_yxz", variable_name[0:4] + str(int(i)) + ".yxz"))
                    del df, master
                    gc.collect()

            if createxyz == "Only Projected" or createxyz == "Both":
                if not os.path.exists(os.path.join(output_directory, "Projected_yxz")):
                    os.makedirs(os.path.join(output_directory, "Projected_yxz"))
                raster_to_xyz(os.path.join(output_directory, "Projected", variable_name[0:4] + str(int(i))),
                              variable_name[0:4] + str(int(i)),
                              os.path.join(output_directory, "Projected_yxz"), 349000000.0)

                depth = int(filter(str.isdigit, str(i)))

                if count_proj == 0:
                    df = pd.read_csv(os.path.join(output_directory, "Projected_yxz", variable_name[0:4] + str(int(i)) + ".yxz"),
                                     header=0, names=["y", "x", "z"], sep=" ", dtype={"y": np.float64,  "x": np.float64, "z": np.float64})
                    master = df[["x", "y"]].copy()
                    master.columns = ["x", "y"]
                    master = np.round(master, 4)
                    master.to_pickle(os.path.join(output_directory, "Projected_yxz", "xy_coords.pkl"))
                    master.to_pickle(os.path.join(output_directory, "Projected", "xy_coords.pkl"))
                    del master
                    gc.collect()
                    master_z = df[["z"]].copy()
                    master_z.columns = [int(depth)]
                    master_z = np.round(master_z, 4)
                    master_z.to_pickle(os.path.join(output_directory, "Projected_yxz", str(int(i)) + ".pkl"))
                    os.remove(os.path.join(output_directory, "Projected_yxz", variable_name[0:4] + str(int(i)) + ".yxz"))
                    del df, master_z
                    gc.collect()
                    count_proj = 1
                elif count_proj == 1:
                    df = pd.read_csv(os.path.join(output_directory, "Projected_yxz", variable_name[0:4] + str(int(i)) + ".yxz"),
                                     header=0, names=["y", "x", "z"], sep=" ", dtype={"y": np.float64,  "x": np.float64, "z": np.float64})
                    master_z = df[["z"]].copy()
                    master_z.columns = [int(depth)]
                    master_z = np.round(master_z, 4)
                    master_z.to_pickle(os.path.join(output_directory, "Projected_yxz", str(int(i)) + ".pkl"))
                    os.remove(os.path.join(output_directory, "Projected_yxz", variable_name[0:4] + str(int(i)) + ".yxz"))
                    del df, master_z
                    gc.collect()

        arcpy.AddMessage("Making pyramids and statistics for outputs")
        arcpy.BuildPyramidsandStatistics_management(in_workspace=os.path.join(output_directory, "Geographic"), include_subdirectories="NONE",
                                                    build_pyramids="BUILD_PYRAMIDS",
                                                    calculate_statistics="CALCULATE_STATISTICS", BUILD_ON_SOURCE="NONE",
                                                    block_field="", estimate_statistics="NONE", x_skip_factor="1",
                                                    y_skip_factor="1", ignore_values="", pyramid_level="-1",
                                                    SKIP_FIRST="NONE", resample_technique="NEAREST",
                                                    compression_type="DEFAULT", compression_quality="75",
                                                    skip_existing="SKIP_EXISTING")
        if len(coordinate_system) > 1:
            arcpy.BuildPyramidsandStatistics_management(in_workspace=os.path.join(output_directory, "Projected"), include_subdirectories="NONE",
                                                        build_pyramids="BUILD_PYRAMIDS",
                                                        calculate_statistics="CALCULATE_STATISTICS", BUILD_ON_SOURCE="NONE",
                                                        block_field="", estimate_statistics="NONE", x_skip_factor="1",
                                                        y_skip_factor="1", ignore_values="", pyramid_level="-1",
                                                        SKIP_FIRST="NONE", resample_technique="NEAREST",
                                                        compression_type="DEFAULT", compression_quality="75",
                                                        skip_existing="SKIP_EXISTING")

        arcpy.AddMessage("Script complete in %s seconds." % (time.clock() - t_start))

        return
    def execute(self, parameters, messages):
        """The source code of the tool."""
        # Describe the supplied netCDF File.
        ncFP = arcpy.NetCDFFileProperties(parameters[0].valueAsText)
        selectedVars = parameters[1].valueAsText.split(';')

        # Coordinate variables can be identified via values of their standard
        # name attribute or values of their untis attribute.

        XCoordNamesList = [
            "longitude", "projection_x_coordinate", "grid_longitude"
        ]
        YCoordNamesList = [
            "latitude", "projection_y_coordinate", "grid_longitude"
        ]
        XUnitNamesList = [
            "degrees_east", "degree_east", "degree_E", "degrees_E", "degreeE",
            "degreesE"
        ]
        YUnitNamesList = [
            "degrees_north", "degree_north", "degree_N", "degrees_N",
            "degreeN", "degreesN"
        ]
        XAxisNameList = ["X"]
        YAxisNameList = ["Y"]

        # Case 1: Data are organized by a single station dimension and there
        # are spatial variables also organized by that station dimension.

        dimNames = ncFP.getDimensionsByVariable(str(selectedVars[0]))
        # Must assume that the station dimension is the right most dimension.
        station_dimension = dimNames[-1]
        varNames = ncFP.getVariablesByDimension(station_dimension)
        x_variable = ""
        y_variable = ""
        row_dimension = ""
        for var in varNames:
            if (debug):
                arcpy.AddMessage(var)
            # Identify the coordinate variable by its standard name, units, or
            # axis attribute.

            try:
                SNattributeValue = ncFP.getAttributeValue(var, "standard_name")
            except:
                SNattributeValue = "missing"

            try:
                UNattributeValue = ncFP.getAttributeValue(var, "units")
            except:
                UNattributeValue = "missing"

            try:
                AXattributeValue = ncFP.getAttributeValue(var, "axis")
            except:
                AXattributeValue = "missing"

            if SNattributeValue in XCoordNamesList:
                x_variable = var
            if SNattributeValue in YCoordNamesList:
                y_variable = var
            if UNattributeValue in XUnitNamesList:
                x_variable = var
            if UNattributeValue in YUnitNamesList:
                y_variable = var
            if AXattributeValue in XAxisNameList:
                x_variable = var
            if AXattributeValue in YAxisNameList:
                y_variable = var

        # Case #2: Two dimensional lat/long coordinate variable
        # If unsuccessful in locating variable for x and y coordinates based on
        # station dimension, check to see if variable of interest is
        # georeferenced via a 2 dimensional lat/long coordinate variable

        # Coordinate Variable Method will only work if CDL conforms to the
        # CF 1.6 convention (section 2.4) that "All other dimensions should,
        # whenever possible, be placed to the left of the spatiotemporal
        # dimensions."

        if (not x_variable) or (not y_variable):
            try:
                coordAttributeValue = ncFP.getAttributeValue(
                    str(selectedVars[0]), "coordinates")
                coordVariables = coordAttributeValue.split(' ')
                for element in coordVariables:
                    try:
                        SNattributeValue = ncFP.getAttributeValue(
                            element, "standard_name")
                    except:
                        SNattributeValue = "missing"

                    try:
                        UNattributeValue = ncFP.getAttributeValue(
                            element, "units")
                    except:
                        UNattributeValue = "missing"

                    try:
                        AXattributeValue = ncFP.getAttributeValue(
                            element, "axis")
                    except:
                        AXattributeValue = "missing"

                    if SNattributeValue in XCoordNamesList:
                        x_variable = element
                    if SNattributeValue in YCoordNamesList:
                        y_variable = element
                    if UNattributeValue in XUnitNamesList:
                        x_variable = element
                    if UNattributeValue in YUnitNamesList:
                        y_variable = element
                    if AXattributeValue in XAxisNameList:
                        x_variable = element
                    if AXattributeValue in YAxisNameList:
                        y_variable = element

            except:
                CoordAttributeValue = "missing"

        # Convert the python list of selected variable into a single
        # (comma delimited) string if necessary.
        if selectedVars.count > 1:
            variable_list = ','.join([str(x) for x in selectedVars])
        else:
            variable_list = selectedVars[0]

        # Set the row dimensions parameter of the Make NetCDF Feature Layer tool
        # to the right-most dimension name of the first variable (this
        # should be the name of the station dimension.
        try:
            dimNames = ncFP.getDimensionsByVariable(selectedVars[0])
            row_dimension = str(dimNames[-1])
        except:
            row_dimension = ""

        if (x_variable) and (y_variable) and (row_dimension):
            if (debug):
                arcpy.AddWarning("netCDFFile Name: %s" % \
                    parameters[0].valueAsText)
                arcpy.AddWarning("Variable List: %s" % variable_list)
                arcpy.AddWarning("x_variable: %s" % x_variable)
                arcpy.AddWarning("y_variable: %s" % y_variable)
                arcpy.AddWarning("Output Feature Layer: %s " % \
                    parameters[2].valueAsText)
                arcpy.AddWarning("Row Dimensions: %s " % row_dimension)

            result1 = arcpy.MakeNetCDFFeatureLayer_md(
                parameters[0].valueAsText, variable_list, x_variable,
                y_variable, parameters[2].valueAsText, row_dimension)
            # Force the netCDF Feature Layer to be added to the display
            arcpy.SetParameter(3, result1)
        else:
            if (not x_variable) or (not y_variable):
                msg1 = "Unable to automatically determine x and y variables " \
                   + "from the netCDF file. Use Make NetCDF Feature Layer tool."
                arcpy.AddError(msg1)
            if (not row_dimension):
                msg1 = "Unable to automatically determine row dimension " \
                     + "variable(s) from the netCDF file. Use Make NetCDF " \
                    + "Feature Layer tool."
                arcpy.AddError(msg1)
        return
    def execute(self, parameters, messages):
        """The source code of the tool."""

        # Describe the supplied netCDF File.
        ncFP = arcpy.NetCDFFileProperties(parameters[0].valueAsText)
        selectedVars = parameters[1].valueAsText.split(';')

        # Coordinate variables can be identified via values of their standard
        # name attribute or values of their untis attribute.

        XCoordNamesList = ["longitude", "projection_x_coordinate",
                            "grid_longitude"]
        YCoordNamesList = ["latitude", "projection_y_coordinate",
                           "grid_longitude"]
        XUnitNamesList = ["degrees_east", "degree_east", "degree_E",
                           "degrees_E", "degreeE", "degreesE" ]
        YUnitNamesList = ["degrees_north", "degree_north", "degree_N",
                              "degrees_N", "degreeN", "degreesN"]
        XAxisNameList = ["X"]
        YAxisNameList = ["Y"]

        # Case 1: Independent latitude, Longitude, Vertical and Time Axes
        # Get the dimensions associated with the first variable.  We can use a
        # single variable because tool validation guarentees that all the
        # selected variables have the same dimensions.
        dimNames = ncFP.getDimensionsByVariable(str(selectedVars[0]))
        x_variable = ""
        y_variable = ""
        for dimension in dimNames:
            # Per CF 1.6 (Chapter 5, preamble): "All of a variable's dimensions
            # that are latitude, longitude, vertical, or time dimensions must
            # have corresponding coordinate variables, i.e., one-dimensional
            # variables with the same name as the dimension."
            # Identify the coordinate variable by its standard name or units.

            try:
                SNattributeValue = ncFP.getAttributeValue(dimension,
                    "standard_name")
            except:
                SNattributeValue = "missing"

            try:
                UNattributeValue = ncFP.getAttributeValue(dimension, "units")
            except:
                UNattributeValue = "missing"

            try:
                AXattributeValue = ncFP.getAttributeValue(dimension,"axis")
            except:
                AXattributeValue = "missing"

            if SNattributeValue in XCoordNamesList:
                x_variable = dimension
            if SNattributeValue in YCoordNamesList:
                y_variable = dimension
            if UNattributeValue in XUnitNamesList:
                x_variable = dimension
            if UNattributeValue in YUnitNamesList:
                y_variable = dimension
            if AXattributeValue in XAxisNameList:
                x_variable = dimension
            if AXattributeValue in YAxisNameList:
                y_variable = dimension

        # Set the row dimensions parameter of the Make NetCDF Feature Layer tool
        # to the names of the latitude and longitude dimensions
        rowDimensions = ""
        rowDimensions = x_variable + ";" + y_variable


        # Case #2: 2 dimensional lat/long coordinate variable
        # If unsuccessful in locating variable for x and y coordinates based on
        # latitude and longitude, check to see if variable of interest is
        # georeferenced via a 2 dimensional lat/long coordinate variable

        # Coordinate Variable Method will only work if CDL conforms to the
        # CF 1.6 convention (section 2.4) that "All other dimensions should,
        # whenever possible, be placed to the left of the spatiotemporal
        # dimensions."

        if (not x_variable) or (not y_variable):
            try:
                coordAttributeValue = ncFP.getAttributeValue(str(selectedVars[0]),
                    "coordinates")
                coordVariables = coordAttributeValue.split(' ')
                for element in coordVariables:
                    try:
                        SNattributeValue = ncFP.getAttributeValue(element,
                            "standard_name")
                    except:
                        SNattributeValue = "missing"

                    try:
                        UNattributeValue = ncFP.getAttributeValue(element,
                            "units")
                    except:
                        UNattributeValue = "missing"

                    try:
                        AXattributeValue = ncFP.getAttributeValue(element,
                            "axis")
                    except:
                        AXattributeValue = "missing"

                    if SNattributeValue in XCoordNamesList:
                        x_variable = element
                    if SNattributeValue in YCoordNamesList:
                        y_variable = element
                    if UNattributeValue in XUnitNamesList:
                        x_variable = element
                    if UNattributeValue in YUnitNamesList:
                        y_variable = element
                    if AXattributeValue in XAxisNameList:
                        x_variable = element
                    if AXattributeValue in YAxisNameList:
                        y_variable = element

                # Set the row dimensions parameter of the Make NetCDF Feature
                # Layer tool to the names of the coordinate variables
                dimNames = ncFP.getDimensionsByVariable(str(selectedVars[0]))
                rowDimensions = str(dimNames[-1]) + ";" + str(dimNames[-2])


            except:
                CoordAttributeValue = "missing"

        # Convert the python list of selected variables into a single
        # (comma delimited string if necessary.
        if selectedVars.count > 1:
            variable_list = ','.join([str(x) for x in selectedVars])
        else:
            variable_list = selectedVars[0]

        if (x_variable) and (y_variable):
            if (debug):
                arcpy.AddWarning("netCDFFile Name: %s" \
                    % parameters[0].valueAsText)
                arcpy.AddWarning("Variable List: %s" % variable_list)
                arcpy.AddWarning("x_variable: %s" % x_variable)
                arcpy.AddWarning("y_variable: %s" % y_variable)
                arcpy.AddWarning("Output Feature Layer: %s " \
                    % parameters[2].valueAsText)
                arcpy.AddWarning("Row Dimensions: %s " % rowDimensions)

            result1 = arcpy.MakeNetCDFFeatureLayer_md(parameters[0].valueAsText,
                                            variable_list,
                                            x_variable,
                                            y_variable,
                                            parameters[2].value,
                                            rowDimensions)
            # Force the netCDF Feature Layer to be added to the display
            arcpy.SetParameter(3, result1)
        else:
            arcpy.AddError("Unable to automatically determine x and y " +
                "variables from the netCDF file. Use Make NetCDF " +
                "Feature Layer tool.")
        return