Beispiel #1
0
def fetchConfig():

    file = g_pn + os.sep + 'config.json'

    if not os.path.exists(file):
        msg = "configuration json file not found"
        dzlog(msg, 'error')
        raise arcpy.ExecuteError(msg)

    with open(file, "r") as json_f:

        try:
            json_d = json.load(json_f)

        except ValueError as e:
            msg = "Project config.json file does not contain valid JSON."
            dzlog(msg, 'error')
            raise arcpy.ExecuteError(msg)

    if 'aoistorage' not in json_d:
        json_d['aoistorage'] = 'default'

    if json_d['aoistorage'] == "default":
        json_d['aoistorage'] = g_pn + os.sep + g_aoi_gdb

    return json_d
Beispiel #2
0
def make_topo_layers(topo_folder):
    """
    Writes the layers
    :param topo_folder: We want to make layers for the stuff in this folder
    :return:
    """
    source_code_folder = os.path.dirname(os.path.abspath(__file__))
    symbology_folder = os.path.join(source_code_folder, 'BRATSymbology')
    dem_symbology = os.path.join(symbology_folder, "DEM.lyr")
    slope_symbology = os.path.join(symbology_folder, "Slope.lyr")
    hillshade_symbology = os.path.join(symbology_folder, "Hillshade.lyr")

    for folder in os.listdir(topo_folder):
        dem_folder_path = os.path.join(topo_folder, folder)
        dem_file = None
        for file_name in os.listdir(dem_folder_path):
            if file_name.endswith(".tif"):
                dem_file = os.path.join(dem_folder_path, file_name)
                make_layer(dem_folder_path,
                           dem_file,
                           "DEM",
                           dem_symbology,
                           is_raster=True)

        hillshade_folder = make_folder(dem_folder_path, "Hillshade")
        hillshade_file = os.path.join(hillshade_folder, "Hillshade.tif")
        try:
            arcpy.HillShade_3d(dem_file, hillshade_file)
            make_layer(hillshade_folder,
                       hillshade_file,
                       "Hillshade",
                       hillshade_symbology,
                       is_raster=True)
        except arcpy.ExecuteError as err:
            if get_execute_error_code(err) == "000859":
                arcpy.AddWarning(
                    "Warning: Unable to create hillshade layer. Consider modifying your DEM input if you need a hillshade."
                )
            else:
                raise arcpy.ExecuteError(err)

        slope_folder = make_folder(dem_folder_path, "Slope")
        slope_file = os.path.join(slope_folder, "Slope.tif")
        try:
            out_slope = arcpy.sa.Slope(dem_file)
            out_slope.save(slope_file)
            make_layer(slope_folder,
                       slope_file,
                       "Slope",
                       slope_symbology,
                       is_raster=True)
        except arcpy.ExecuteError as err:
            if get_execute_error_code(err) == "000859":
                arcpy.AddWarning(
                    "Warning: Unable to create hillshade layer. Consider modifying your DEM input if you need a hillshade."
                )
            else:
                raise arcpy.ExecuteError(err)
Beispiel #3
0
def main():
    arcrestZip = 'arcrest.zip'
    arcrestHelperZip = 'arcresthelper.zip'

    get_latest = arcpy.GetParameter(0)
    installInBoth = arcpy.GetParameter(1)
    base_folder = os.path.dirname(__file__)
    #arcpy.AddMessage("%s: " % base_folder)
    base_folder = os.path.dirname(base_folder)
    #arcpy.AddMessage("%s: " % base_folder)
    base_folder = os.path.dirname(base_folder)
    #arcpy.AddMessage("%s: " % base_folder)
    base_file = os.path.splitext(os.path.basename(__file__))[0]

    if get_latest:
        arcrest_zip, arcresthelper_zip = download_arcrest()
    else:
        commondata = os.path.join(base_folder, "commondata")
        if os.path.isdir(os.path.join(commondata, base_file)):
            arcrest_zip = os.path.join(commondata, base_file, arcrestZip)
            arcresthelper_zip = os.path.join(commondata, base_file,
                                             arcrestHelperZip)
        elif os.path.isdir(os.path.join(commondata, "userdata")):
            arcrest_zip = os.path.join(commondata, "userdata", arcrestZip)
            arcresthelper_zip = os.path.join(commondata, "userdata",
                                             arcrestHelperZip)

    site_package = None
    site_package64 = None
    defPath = os.path.dirname(os.__file__)
    if ('ArcGIS' in defPath):
        if ('x64' in defPath):
            site_package = os.path.join(defPath.replace('x64', ''),
                                        'site-packages')
            site_package64 = os.path.join(defPath, 'site-packages')
        else:
            site_package = os.path.join(defPath, 'site-packages')
            site_package64 = os.path.join(
                defPath.replace('ArcGIS', 'ArcGISx64'), 'site-packages')
    else:
        site_package = os.path.join(defPath, 'site-packages')


##    for p in sys.path:
##        if p.lower().find("site-packages") > -1:
##            site_package = p
##            break
##        del p
    if site_package is None:
        raise arcpy.ExecuteError("Could not find the site-package folder")
    installPackages(arcrest_zip, arcresthelper_zip, site_package)

    if site_package64 is not None and installInBoth == True:
        arcpy.AddMessage(" ")
        arcpy.AddMessage("-----------------------------------------------")
        arcpy.AddMessage(" ")
        installPackages(arcrest_zip, arcresthelper_zip, site_package64)
    arcpy.AddMessage(" ")
    arcpy.AddMessage("... Process Complete ...".format(site_package))
Beispiel #4
0
def add_error(id, s=None):
    """ Return errors """

    arcpy.AddIDMessage("ERROR", id, s if s else None)
    if __name__ == '__main__':
        sys.exit(1)
    else:
        raise arcpy.ExecuteError(arcpy.GetIDMessage(id))
Beispiel #5
0
def main():
    try:
        #: Check out network analyst extension.
        if arcpy.CheckExtension("network") == "Available":
            arcpy.CheckOutExtension("network")
        else:
            raise arcpy.ExecuteError(
                "Network Analyst Extension license is not available.")

        # Create a network dataset layer.
        print("Make Route Layer")
        result_object = arcpy.na.MakeRouteAnalysisLayer(
            networkdataset_path, "Route", '', "USE_CURRENT_ORDER", None,
            "LOCAL_TIME_AT_LOCATIONS", "ALONG_NETWORK", None, "DIRECTIONS",
            "LOCAL_TIME_AT_LOCATIONS")

        #: Get the layer object from the result object. The Route layer can now be referenced using the layer object.
        layer_object = result_object.getOutput(0)

        #: Add Stops (these will be the locations in which the distance between them will be calculated)
        print("Add Route Locations")
        arcpy.na.AddLocations(
            layer_object, "Stops", input_stops,
            "Name # #;RouteName " + input_stops_routename_field +
            " #;Sequence # #;TimeWindowStart # #;TimeWindowEnd # #;LocationType # 0;CurbApproach # 0;Attr_TravelMinutes # 0;Attr_Length # 0",
            "5000 Meters", None,
            "'Roads : Limited Access & Ramps' SHAPE;'Roads : Other' SHAPE;UtahRoadsNetwork_Junctions NONE",
            "MATCH_TO_CLOSEST", "APPEND", "NO_SNAP", "5 Meters", "EXCLUDE",
            None)

        #: Solve the Route layer.
        print("Solve Route")
        arcpy.na.Solve(layer_object)

        #: Save the Route layer as a layer file on disk (however, the data in stored here: C:\Users\<username>\AppData\Local\Temp\scratch.gdb)
        print("Save Route as Layer File")
        layer_object.saveACopy(output_layer_file)

        #: Export Route layers (from: C:\Users\<username>\AppData\Local\Temp\scratch.gdb\Route\Routes) to fbdb feature classes
        # List sublayers in layer_object Group and export Routes and Stops
        print("Export Route layer to fgdb feature classes.")
        for lyr in layer_object.listLayers():
            if lyr.isGroupLayer:
                continue
            if str(lyr.name).startswith('Routes') or str(
                    lyr.name).startswith('Stops'):
                arcpy.management.CopyFeatures(
                    lyr, os.path.join(output_route_fgdb, lyr.name + strDate))

        #: Done
        print("Script completed successfully")

    except Exception as e:
        # If an error occurred, print line number and error message
        import traceback, sys
        tb = sys.exc_info()[2]
        print("An error occurred on line %i" % tb.tb_lineno)
        print(str(e))
Beispiel #6
0
def getMaskSize (mapUnits):
    try:
        desc = arcpy.Describe(arcpy.env.mask);
        #arcpy.AddMessage( "getMaskSize()");
        if (desc.dataType == "RasterDataset"):
            raise arcpy.ExecuteError("RasterDataset type is not allowed as Mask!");
        if (desc.dataType == "RasterLayer" or desc.dataType == "RasterDataset"):
            #arcpy.AddMessage( " Counting raster size");                       
            maskrows = arcpy.SearchCursor(desc.catalogpath)        
            maskrow = maskrows.next()
            count =  0
            while maskrow:
                count += maskrow.count
                maskrow = maskrows.next()
            cellsize = float( str(arcpy.env.cellSize.replace(",",".")) )             
            count = count * (cellsize * cellsize);
          
        if (desc.dataType == "FeatureLayer" or desc.dataType == "FeatureClass"):
            #arcpy.AddMessage( " Calculating mask size");           
            maskrows = arcpy.SearchCursor(desc.catalogpath)
            shapeName = desc.shapeFieldName                
            maskrow = maskrows.next()
            count =  0
            while maskrow:
                feat = maskrow.getValue(shapeName)
                count += feat.area;
                maskrow = maskrows.next()
           
        mapUnits = mapUnits.lower().strip()
        if not mapUnits.startswith('meter'):
                arcpy.AddError('Incorrect output map units: Check units of study area.')
        conversion = getMapConversion( mapUnits)
        count = count * conversion;
            #Count is now in Sqkm -> So multiply that with 1000m*1000m / cellsize ^2
            #multiplier = (1000 * 1000) / (cellsize * cellsize); #with 500 x 500 expect "4"
            #arcpy.AddMessage("Debug:" + str(multiplier));
            #count = count * multiplier;
        #arcpy.AddMessage("Size: " + str(count));
        return count
    except arcpy.ExecuteError as e:
            
        raise;
    except:
        # get the traceback object
        tb = sys.exc_info()[2]
        #gp.addError("sdmvalues.py excepted:");
        # tbinfo contains the line number that the code failed on and the code from that line
        tbinfo = traceback.format_tb(tb)[0]
        arcpy.AddError ( tbinfo );
        # concatenate information together concerning the error into a message string
        #pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n    " + \
        #    str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n"
        # generate a message string for any geoprocessing tool errors
        if len(arcpy.GetMessages(2)) > 0:
            msgs = "SDM GP ERRORS:\n" + arcpy.GetMessages(2) + "\n"
            arcpy.AddError(msgs)
        #gp.AddError(pymsg)
        raise;
Beispiel #7
0
 def create_dict_from_json(self, input_json_file):
     if arcpy.Exists(input_json_file):
         with open(input_json_file) as json_file:
             data = json.load(json_file)
         return data
     else:
         arcpy.AddError("Invalid json source")
         arcpy.ExecuteError()
         raise Exception
    def units(self, unit_system):

        if unit_system == "Metric":
            return ["m3", "sq m", "L", "km"]

        elif unit_system == "US Customary":
            return ["yd3", "sq yd", "gal", "mi"]

        raise arcpy.ExecuteError("Error")
    def facility_amt_accepted_stats(self):

        if self.scenario is None:
            return None

        count_facility_qty_accepted = 0
        total_facility_qty_accepted = 0
        average_fac_amt_accepted = None
        percent_fac_of_waste = None

        if self.scenario.waste_medium is not None:

            if self.scenario.waste_medium == 'Volume Liquid':
                column_name = "facility_qty_accepted_volume_liquid"

            elif self.scenario.waste_medium == 'Volume Solid':
                column_name = "facility_qty_accepted_volume_solid"

            else:
                raise arcpy.ExecuteError("Error")

            rows = arcpy.da.SearchCursor(
                in_table=self.network.facilities.dataSource,
                field_names=('objectid', column_name),
                where_clause=None)

            for row in rows:
                count_facility_qty_accepted += 1
                total_facility_qty_accepted += row[1]

            if count_facility_qty_accepted == 0:
                average_fac_amt_accepted = 0
                percent_fac_of_waste = 0

            else:
                average_fac_amt_accepted = total_facility_qty_accepted / count_facility_qty_accepted

                if self.scenario is None or self.scenario.waste_amount is None:
                    percent_fac_of_waste = None

                else:
                    percent_fac_of_waste = self.scenario.waste_amount / total_facility_qty_accepted

                    if percent_fac_of_waste > 1:
                        percent_fac_of_waste = 1

            del rows

        ret = {}
        ret["total_facility_qty_accepted"] = total_facility_qty_accepted
        ret["average_fac_amt_accepted"] = average_fac_amt_accepted
        ret["percent_fac_of_waste"] = percent_fac_of_waste

        return SimpleNamespace(**ret)
 def create_output_gdb(self, gdb_full_path_name):
     #gdb_full_path_name = self.utility.gdb_full_path_name(datetime.today(), base_folder)
     if arcpy.Exists(gdb_full_path_name):
         arcpy.AddError("gdb already exists")
         arcpy.ExecuteError()
         sys.exit("gdb already exists") #TODO - make sure this works as expected
     else:
         base_folder = os.path.dirname(gdb_full_path_name)
         gdb_name = os.path.basename(gdb_full_path_name)
         arcpy.AddMessage("Creating gdb " + str(gdb_name))
         arcpy.CreateFileGDB_management(base_folder, gdb_name)
def make_layer(output_folder,
               layer_base,
               new_layer_name,
               symbology_layer=None,
               is_raster=False,
               description="Made Up Description",
               file_name=None,
               symbology_field=None):
    """
    Creates a layer and applies a symbology to it
    :param output_folder: Where we want to put the layer
    :param layer_base: What we should base the layer off of
    :param new_layer_name: What the layer should be called
    :param symbology_layer: The symbology that we will import
    :param is_raster: Tells us if it's a raster or not
    :param description: The discription to give to the layer file
    :return: The path to the new layer
    """
    new_layer = new_layer_name
    if file_name is None:
        file_name = new_layer_name.replace(' ', '')
    new_layer_save = os.path.join(output_folder, file_name.replace(' ', ''))

    if not new_layer_save.endswith(".lyr"):
        new_layer_save += ".lyr"

    if is_raster:
        try:
            arcpy.MakeRasterLayer_management(layer_base, new_layer)
        except arcpy.ExecuteError as err:
            if get_execute_error_code(err) == "000873":
                arcpy.AddError(err)
                arcpy.AddMessage(
                    "The error above can often be fixed by removing layers or layer packages from the Table of Contents in ArcGIS."
                )
                raise Exception
            else:
                raise arcpy.ExecuteError(err)

    else:
        if arcpy.Exists(new_layer):
            arcpy.Delete_management(new_layer)
        arcpy.MakeFeatureLayer_management(layer_base, new_layer)

    if symbology_layer:
        arcpy.ApplySymbologyFromLayer_management(new_layer, symbology_layer)

    if not os.path.exists(new_layer_save):
        arcpy.SaveToLayerFile_management(new_layer, new_layer_save, "RELATIVE")
        new_layer_instance = arcpy.mapping.Layer(new_layer_save)
        new_layer_instance.description = description
        new_layer_instance.save()
    return new_layer_save
Beispiel #12
0
def login(email, password, server_url):
    """Authenticate the user."""

    api_key = None
    username = None

    try:
        login_result = urllib2.urlopen(
            '{}/footprint/login/'.format(server_url),
            data=urllib.urlencode({'email': email, 'password': password, 'output': 'json'}),
            **ssl_context_kwarg
        )
    except urllib2.HTTPError, e:
        if e.code != 200:
            raise arcpy.ExecuteError("Incorrect Email/Password combination. Please try again.")
Beispiel #13
0
    def copy_sources_to_gdb(self, data_dict, output_gdb):
        arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(self.utility.city_standard_SRID) #only applies on CopyFeatures
        if self.utility.valid_source_values(data_dict):
            try:
                print "Coping data sources to the gdb:"
                print "Input source count - " + str(len(data_dict))
                print "Input source list - " + str(data_dict.keys())
                for key, value in data_dict.items():
                    print "   Copying: " + str(key)
                    full_input_path = self.utility.source_formatter(value)
                    print "       Full input path: " + str(full_input_path)
                    print "           Exists: " + str(arcpy.Exists(full_input_path))
                    print "       Full output path: " + str(os.path.join(output_gdb, key))
                    if arcpy.Describe(self.utility.source_formatter(value)).dataType == 'FeatureClass':
                        arcpy.CopyFeatures_management(full_input_path, os.path.join(output_gdb, key))
                    elif arcpy.Describe(self.utility.source_formatter(value)).dataType == 'Table':
                        arcpy.Copy_management(full_input_path, os.path.join(output_gdb, key))

            except:
                arcpy.ExecuteError()
        else:
            arcpy.AddError("Invalid data source(s)")
            arcpy.ExecuteError()
            raise Exception
    def __init__(self, layerfile=None):

        self.aprx = arcpy.mp.ArcGISProject("CURRENT")
        self.map = self.aprx.listMaps("AllHazardsWasteLogisticsMap")[0]

        if self.map is None:
            raise arcpy.ExecuteError("Error.  Project map not found.")

        if layerfile is not None:
            netfile = arcpy.mp.LayerFile(layerfile)

            self.load_layers(netfile.listLayers('*'))

        else:
            self.load_layers(self.map.listLayers('*'))
   def __init__(self,conditions_layer=None):

      if conditions_layer is not None:
         self.conditions_layer = conditions_layer;

      else:
         aprx = arcpy.mp.ArcGISProject("CURRENT");
         map  = aprx.listMaps("AllHazardsWasteLogisticsMap")[0];

         for lyr in map.listLayers():

            if lyr.supports("name") and lyr.name == "Conditions":
               self.conditions_layer = obj_Layer.Layer(lyr);

         if self.conditions_layer is None:
            raise arcpy.ExecuteError("Error. Conditions layer not found.");
    def __init__(self, system_cache_layer=None):
        if system_cache_layer is not None:
            self.system_cache_layer = system_cache_layer

        else:
            aprx = arcpy.mp.ArcGISProject("CURRENT")
            map = aprx.listMaps("AllHazardsWasteLogisticsMap")[0]

            for lyr in map.listLayers():

                if lyr.supports("name") and lyr.name == "SystemCache":
                    self.system_cache_layer = obj_Layer.Layer(lyr)

            if self.system_cache_layer is None:
                raise arcpy.ExecuteError("Error. SystemCache layer not found.")

        self.loadSystemCache()
    def __init__(self, scenario_layer=None, scenario_id=None):

        if scenario_layer is not None:
            self.scenario_layer = scenario_layer

        else:
            aprx = arcpy.mp.ArcGISProject("CURRENT")
            map = aprx.listMaps("AllHazardsWasteLogisticsMap")[0]

            for lyr in map.listLayers():

                if lyr.supports("name") and lyr.name == "Scenario":
                    self.scenario_layer = obj_Layer.Layer(lyr)

            if self.scenario_layer is None:
                raise arcpy.ExecuteError("Error. Scenario layer not found.")

        if scenario_id is not None:
            self.loadScenarioID(scenario_id)
def _tableToPoints(input_table, crs):
    allowed_types = ["double", "integer", "single", "smallinteger"]
    numeric_fields = [
        f.name for f in arcpy.ListFields(input_table)
        if f.type.lower() in allowed_types
    ]

    x_field = _detectGeometryField(input_table, "x", numeric_fields)
    y_field = _detectGeometryField(input_table, "y", numeric_fields)

    if not (x_field and y_field):
        raise arcpy.ExecuteError(
            "The table doesn't contain X and/or Y columns.")

    res = arcpy.MakeXYEventLayer_management(input_table,
                                            x_field,
                                            y_field,
                                            "xy_layer",
                                            spatial_reference=crs)
    return res.getOutput(0)
Beispiel #19
0
    def load_data(self, appsettings_file, data_source_file):
        missing_from_source_names = self.create_names_missing_from_source_list(appsettings_file, data_source_file)
        if len(missing_from_source_names) == 0:

            missing_from_appsettings = self.create_names_missing_from_appsettings_list(appsettings_file,
                                                                                       data_source_file)
            if len(missing_from_appsettings) > 0:
                print "FYI - these entries are in the input source list but NOT IN the appsettings(required) list: "
                print "   " + str(missing_from_appsettings)
                print "      The extra entries will not be copied to the output gdb."
                filtered_dict = self.remove_extra_values(data_source_file,
                                                     missing_from_appsettings)
                self.copy_sources_to_gdb(filtered_dict, self.now_gdb_full_path_name)
            else:
                self.copy_sources_to_gdb(self.create_input_dict_from_json_dict(data_source_file), self.now_gdb_full_path_name)

        else:
            arcpy.AddError("No data will be copied")
            arcpy.AddError("All appsettings entries are required")
            arcpy.AddMessage("These entries are in the appsettings list but NOT IN the input source list: " + str(missing_from_source_names))
            arcpy.ExecuteError()
Beispiel #20
0
def get_config_entity_id(username, api_key, config_entity_name, server_url):
    """Make an API query of Projects by name and return the id."""

    config_entity_id = None

    url = '{}/footprint/api/v1/project/?format=json&username={}&api_key={}&name={}'.format(
            server_url, urllib.quote(username), urllib.quote(api_key), urllib.quote(config_entity_name))

    config_entity_result = urllib2.urlopen(
        url,
        **ssl_context_kwarg
    )

    try:
        config_entity_data = json.loads(config_entity_result.read())
    except ValueError:
        raise arcpy.ExecuteError("Project lookup returned invalid response.")

    if config_entity_data and 'objects' in config_entity_data:
        if len(config_entity_data['objects']):
            config_entity_id = config_entity_data['objects'][0]['id']

    return config_entity_id
Beispiel #21
0
def updateConfig(key, value):

    file = g_pn + os.sep + 'config.json'

    if not os.path.exists(file):
        msg = "configuration json file not found"
        dzlog(msg, 'error')
        raise arcpy.ExecuteError(msg)

    with open(file, "r") as json_f:
        json_d = json.load(json_f)

    json_d[key] = value

    with open(file, "w") as json_f:
        json.dump(json_d, json_f, indent=3)

    if 'aoistorage' not in json_d:
        json_d['aoistorage'] = 'default'

    if json_d['aoistorage'] == "default":
        json_d['aoistorage'] = g_pn + os.sep + g_aoi_gdb

    return json_d
Beispiel #22
0
    # Move results.txt to data folder
    if arcpy.Exists( os.path.join(shp_output_dir, "results.txt")):
        shutil.move( os.path.join(shp_output_dir, "results.txt"),
                     os.path.join(dir_string, "regression_results\\results.txt"))

    if arcpy.Exists( os.path.join(shp_output_dir, "results.txt.xml")):
        shutil.move( os.path.join(shp_output_dir, "results.txt.xml"),
                     os.path.join(dir_string, "regression_results\\results.txt.xml"))


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

    arcpy.AddMessage("Geographically Weighted Regression Analysis Complete.")

except arcpy.ExecuteError("An error occurred during processing:\n"):
    msgs = arcpy.GetMessages(2)
    arcpy.AddError(msgs)
    arcpy.AddError("\nP Check that inputs are formatted correctly.")

# Reset workspace to home directory
arcpy.env.workspace = Workspace

# Make a Map
make_map(shp_output_dir)

arcpy.AddMessage("End of Processing.")
arcpy.AddMessage("Please find Exploratory Regression Results in data/regression_results/results.txt")

arcpy.AddMessage("******* Output from R Console Below *******")
def execute(self, parameters, messages):

    #########################################################################
    # Step 10
    # Abend if edits are pending
    #########################################################################
    if util.sniff_editing_state():
        raise arcpy.ExecuteError(
            "Error.  Pending edits must be saved or cleared before proceeding."
        )

    #########################################################################
    # Step 20
    # Read the parameters
    #########################################################################
    dest_filename = parameters[2].valueAsText

    scenarioids = []
    val = parameters[3].valueAsText
    scenarioids.append(val)

    #########################################################################
    # Step 30
    # Initialize the workbook and summary sheet
    #########################################################################
    haz = obj_AllHazardsWasteLogisticsTool.AllHazardsWasteLogisticsTool()
    wb = Workbook()
    sum = wb.active
    sum.title = 'Summary'

    sum['A1'] = "All Hazards Waste Logistics Tool Summary"
    ft18 = Font(size=18)
    bldu = Font(bold=True, underline="single")
    bld = Font(bold=True)
    lft = Alignment(horizontal='left')
    rht = Alignment(horizontal='right')
    dol = "$#,##0.00_);($#,##0.00)"

    sum.column_dimensions['A'].width = 20
    sum.column_dimensions['B'].width = 30
    sum.column_dimensions['C'].width = 25
    sum.column_dimensions['D'].width = 20
    sum.column_dimensions['E'].width = 30
    sum.column_dimensions['F'].width = 20
    sum.column_dimensions['G'].width = 30
    sum.column_dimensions['H'].width = 18
    sum.column_dimensions['I'].width = 30
    sum.column_dimensions['J'].width = 15

    sum['A1'].font = ft18
    sum['A2'] = "Version: " + const_version

    row_cnt = 4

    ary_conditionids = []
    ary_factorids = []

    for scenarioid in scenarioids:
        arcpy.AddMessage("Preparing to write report for " + str(scenarioid) +
                         ".")

        sc = obj_Scenario.Scenario(scenario_id=scenarioid)

        if sc.conditionid not in ary_conditionids:
            ary_conditionids.append(sc.conditionid)
        if sc.factorid not in ary_factorids:
            ary_factorids.append(sc.factorid)

        total_number_of_facilities = 0
        total_allocated_amount = 0
        total_number_of_shipments = 0
        total_cplm_cost_usd = 0
        total_fixed_cost_usd = 0
        total_tolls_usd = 0
        total_misc_trans_cost_usd = 0
        total_trans_cost_usd = 0
        total_staging_site_cost_usd = 0
        total_disposal_cost_usd = 0
        total_labor_cost_usd = 0
        total_vehicle_decon_cost_usd = 0
        total_cost_multiplier_usd = 0
        total_cost_usd = 0
        max_trucks_time_to_comp_days = 0
        max_dest_time_to_comp_days = 0
        max_time_days = 0

        unallocated_amount = 0
        cursor_in = arcpy.da.SearchCursor(
            in_table=haz.scenario_results.dataSource,
            field_names=('allocated_amount'),
            where_clause="scenarioid = " + util.sql_quote(scenarioid) +
            " and facility_identifier = 'Unallocated'")

        for row in cursor_in:
            unallocated_amount = row[0]

        cursor_in = arcpy.da.SearchCursor(
            in_table=haz.scenario_results.dataSource,
            field_names=(
                'scenarioid', 'conditionid', 'factorid', 'facility_identifier',
                'facility_rank', 'total_distance', 'distance_unit',
                'total_truck_travel_time', 'time_unit', 'average_speed',
                'speed_unit', 'facility_name', 'facility_address',
                'facility_city', 'facility_state', 'facility_zip',
                'facility_telephone', 'facility_waste_mgt',
                'facility_capacity_trucks_perday', 'facility_qty_accepted',
                'facility_qty_accepted_unit', 'allocated_amount',
                'allocated_amount_unit', 'number_of_shipments',
                'cplm_cost_usd', 'fixed_cost_usd_per_shipment',
                'fixed_cost_usd_per_hour', 'tolls_usd', 'misc_trans_cost_usd',
                'trans_cost_usd', 'staging_site_cost_usd', 'disposal_cost_usd',
                'labor_cost_usd', 'vehicle_decon_cost_usd',
                'cost_multiplier_usd', 'cost_usd', 'trucks_time_to_comp_days',
                'dest_time_to_comp_days', 'time_days', 'username',
                'creationtime'),
            where_clause="scenarioid = " + util.sql_quote(scenarioid) +
            " and facility_identifier <> 'Unallocated'")

        sht = wb.create_sheet(scenarioid)

        sht.column_dimensions['A'].width = 19
        sht.column_dimensions['B'].width = 40
        sht.column_dimensions['C'].width = 25
        sht.column_dimensions['D'].width = 20
        sht.column_dimensions['E'].width = 10
        sht.column_dimensions['F'].width = 10
        sht.column_dimensions['G'].width = 20
        sht.column_dimensions['H'].width = 15
        sht.column_dimensions['I'].width = 20
        sht.column_dimensions['J'].width = 20
        sht.column_dimensions['K'].width = 12
        sht.column_dimensions['L'].width = 15
        sht.column_dimensions['M'].width = 10
        sht.column_dimensions['N'].width = 16
        sht.column_dimensions['O'].width = 10
        sht.column_dimensions['P'].width = 15
        sht.column_dimensions['Q'].width = 10
        sht.column_dimensions['R'].width = 25
        sht.column_dimensions['S'].width = 18
        sht.column_dimensions['T'].width = 18
        sht.column_dimensions['U'].width = 18
        sht.column_dimensions['V'].width = 20
        sht.column_dimensions['W'].width = 30
        sht.column_dimensions['X'].width = 20
        sht.column_dimensions['Y'].width = 18
        sht.column_dimensions['Z'].width = 18
        sht.column_dimensions['AA'].width = 25
        sht.column_dimensions['AB'].width = 25
        sht.column_dimensions['AC'].width = 18
        sht.column_dimensions['AD'].width = 25
        sht.column_dimensions['AE'].width = 25
        sht.column_dimensions['AF'].width = 20

        sht['A1'] = scenarioid
        sht['A1'].font = ft18

        sht['A3'] = "Waste Type"
        sht['A3'].font = bld
        sht['B3'] = sc.waste_type

        sht['A4'] = "Waste Medium"
        sht['A4'].font = bld
        sht['B4'] = sc.waste_medium

        sht['A5'] = "Total Waste Amount"
        sht['A5'].font = bld
        sht['B5'] = sc.waste_amount

        sht['A6'] = "Unallocated Amount"
        sht['A6'].font = bld
        sht['B6'] = unallocated_amount

        sht['A7'] = "Waste Unit"
        sht['A7'].font = bld
        sht['B7'] = sc.waste_unit
        sht['B7'].alignment = rht

        sht['A9'] = "Condition ID"
        sht['A9'].font = bld
        sht['B9'] = sc.conditionid

        sht['A10'] = "Factor ID"
        sht['A10'].font = bld
        sht['B10'] = sc.factorid

        if haz.scenario.map_image == 'Disabled':
            row_sht = 12

        else:
            img = openpyxl.drawing.image.Image(haz.scenario.map_image)
            dpi = 96
            img.width = 8 * dpi
            img.height = 6 * dpi
            img.anchor = 'D2'
            sht.add_image(img)

            row_sht = 32

        sht['A' + str(row_sht)] = "Facility ID"
        sht['A' + str(row_sht)].font = bld

        sht['B' + str(row_sht)] = "Facility Name"
        sht['B' + str(row_sht)].font = bld

        sht['C' + str(row_sht)] = "Facility Address"
        sht['C' + str(row_sht)].font = bld

        sht['D' + str(row_sht)] = "Facility City"
        sht['D' + str(row_sht)].font = bld

        sht['E' + str(row_sht)] = "Facility State"
        sht['E' + str(row_sht)].font = bld

        sht['F' + str(row_sht)] = "Facility Zip"
        sht['F' + str(row_sht)].font = bld

        sht['G' + str(row_sht)] = "Facility Telephone"
        sht['G' + str(row_sht)].font = bld

        sht['H' + str(row_sht)] = "Routing Rank"
        sht['H' + str(row_sht)].font = bld

        sht['I' + str(row_sht)] = "Quantity Accepted"
        sht['I' + str(row_sht)].font = bld

        sht['J' + str(row_sht)] = "Allocated Amount"
        sht['J' + str(row_sht)].font = bld

        sht['K' + str(row_sht)] = "Unit"
        sht['K' + str(row_sht)].font = bld

        sht['L' + str(row_sht)] = "Distance"
        sht['L' + str(row_sht)].font = bld

        sht['M' + str(row_sht)] = "Unit"
        sht['M' + str(row_sht)].font = bld

        sht['N' + str(row_sht)] = "Travel Time"
        sht['N' + str(row_sht)].font = bld

        sht['O' + str(row_sht)] = "Unit"
        sht['O' + str(row_sht)].font = bld

        sht['P' + str(row_sht)] = "Average Speed"
        sht['P' + str(row_sht)].font = bld

        sht['Q' + str(row_sht)] = "Unit"
        sht['Q' + str(row_sht)].font = bld

        sht['R' + str(row_sht)] = "Number of Shipments"
        sht['R' + str(row_sht)].font = bld

        sht['S' + str(row_sht)] = "CPLM Cost ($)"
        sht['S' + str(row_sht)].font = bld

        sht['T' + str(row_sht)] = "Fixed Cost ($)"
        sht['T' + str(row_sht)].font = bld

        sht['U' + str(row_sht)] = "Tolls ($)"
        sht['U' + str(row_sht)].font = bld

        sht['V' + str(row_sht)] = "Misc Trans Costs ($)"
        sht['V' + str(row_sht)].font = bld

        sht['W' + str(row_sht)] = "Total Transportation Cost ($)"
        sht['W' + str(row_sht)].font = bld

        sht['X' + str(row_sht)] = "Staging Site Cost ($)"
        sht['X' + str(row_sht)].font = bld

        sht['Y' + str(row_sht)] = "Disposal Cost ($)"
        sht['Y' + str(row_sht)].font = bld

        sht['Z' + str(row_sht)] = "Labor Cost ($)"
        sht['Z' + str(row_sht)].font = bld

        sht['AA' + str(row_sht)] = "Vehicle Decon Cost ($)"
        sht['AA' + str(row_sht)].font = bld

        sht['AB' + str(row_sht)] = "Total Cost Multiplier ($)"
        sht['AB' + str(row_sht)].font = bld

        sht['AC' + str(row_sht)] = "Total Cost ($)"
        sht['AC' + str(row_sht)].font = bld

        sht['AD' + str(row_sht)] = "Truck Time to Complete (days)"
        sht['AD' + str(row_sht)].font = bld

        sht['AE' + str(row_sht)] = "Destination Time to Complete (days)"
        sht['AE' + str(row_sht)].font = bld

        sht['AF' + str(row_sht)] = "Total Time (days)"
        sht['AF' + str(row_sht)].font = bld

        row_sht += 2

        max_trucks_time_to_comp_days = 0
        max_dest_time_to_comp_days = 0
        max_time_days = 0

        for row in cursor_in:
            conditionid = row[1]
            factorid = row[2]
            facility_identifier = row[3]
            facility_rank = row[4]
            total_distance = row[5]
            distance_unit = row[6]
            total_truck_travel_time = row[7]
            time_unit = row[8]
            average_speed = row[9]
            speed_unit = row[10]
            facility_name = row[11]
            facility_address = row[12]
            facility_city = row[13]
            facility_state = row[14]
            facility_zip = row[15]
            facility_telephone = row[16]
            facility_waste_mgt = row[17]
            facility_capacity_trucks_perday = row[18]
            facility_qty_accepted = row[19]
            facility_qty_accepted_unit = row[20]
            allocated_amount = row[21]
            allocated_amount_unit = row[22]
            number_of_shipments = row[23]
            cplm_cost_usd = row[24]
            fixed_cost_usd_per_shipment = row[25]
            fixed_cost_usd_per_hour = row[26]
            tolls_usd = row[27]
            misc_trans_cost_usd = row[28]
            trans_cost_usd = row[29]
            staging_site_cost_usd = row[30]
            disposal_cost_usd = row[31]
            labor_cost_usd = row[32]
            vehicle_decon_cost_usd = row[33]
            cost_multiplier_usd = row[34]
            cost_usd = row[35]
            trucks_time_to_comp_days = row[36]
            dest_time_to_comp_days = row[37]
            time_days = row[38]
            username = row[39]
            creationtime = row[40]

            total_number_of_facilities += 1
            total_allocated_amount += allocated_amount
            total_number_of_shipments += number_of_shipments
            total_cplm_cost_usd += cplm_cost_usd
            total_fixed_cost_usd += fixed_cost_usd_per_shipment
            total_fixed_cost_usd += fixed_cost_usd_per_hour
            total_tolls_usd += tolls_usd
            total_misc_trans_cost_usd += misc_trans_cost_usd
            total_trans_cost_usd += trans_cost_usd
            total_staging_site_cost_usd += staging_site_cost_usd
            total_disposal_cost_usd += disposal_cost_usd
            total_labor_cost_usd += labor_cost_usd
            total_vehicle_decon_cost_usd += vehicle_decon_cost_usd
            total_cost_multiplier_usd += cost_multiplier_usd
            total_cost_usd += cost_usd

            if trucks_time_to_comp_days > max_trucks_time_to_comp_days:
                max_trucks_time_to_comp_days = trucks_time_to_comp_days

            if dest_time_to_comp_days > max_dest_time_to_comp_days:
                max_dest_time_to_comp_days = dest_time_to_comp_days

            if time_days > max_time_days:
                max_time_days = time_days

            sht['A' + str(row_sht)] = facility_identifier

            sht['B' + str(row_sht)] = facility_name

            sht['C' + str(row_sht)] = facility_address

            sht['D' + str(row_sht)] = facility_city

            sht['E' + str(row_sht)] = facility_state

            sht['F' + str(row_sht)] = facility_zip

            sht['G' + str(row_sht)] = facility_telephone

            sht['H' + str(row_sht)] = facility_rank

            sht['I' + str(row_sht)] = facility_qty_accepted

            sht['J' + str(row_sht)] = allocated_amount

            sht['K' + str(row_sht)] = allocated_amount_unit

            sht['L' + str(row_sht)] = total_distance

            sht['M' + str(row_sht)] = distance_unit

            sht['N' + str(row_sht)] = total_truck_travel_time

            sht['O' + str(row_sht)] = time_unit

            sht['P' + str(row_sht)] = average_speed

            sht['Q' + str(row_sht)] = speed_unit

            sht['R' + str(row_sht)] = number_of_shipments

            sht['S' + str(row_sht)] = cplm_cost_usd
            sht['S' + str(row_sht)].number_format = dol

            sht['T' +
                str(row_sht
                    )] = fixed_cost_usd_per_shipment + fixed_cost_usd_per_hour
            sht['T' + str(row_sht)].number_format = dol

            sht['U' + str(row_sht)] = tolls_usd
            sht['U' + str(row_sht)].number_format = dol

            sht['V' + str(row_sht)] = misc_trans_cost_usd
            sht['V' + str(row_sht)].number_format = dol

            sht['W' + str(row_sht)] = trans_cost_usd
            sht['W' + str(row_sht)].number_format = dol

            sht['X' + str(row_sht)] = staging_site_cost_usd
            sht['X' + str(row_sht)].number_format = dol

            sht['Y' + str(row_sht)] = disposal_cost_usd
            sht['Y' + str(row_sht)].number_format = dol

            sht['Z' + str(row_sht)] = labor_cost_usd
            sht['Z' + str(row_sht)].number_format = dol

            sht['AA' + str(row_sht)] = vehicle_decon_cost_usd
            sht['AA' + str(row_sht)].number_format = dol

            sht['AB' + str(row_sht)] = cost_multiplier_usd
            sht['AB' + str(row_sht)].number_format = dol

            sht['AC' + str(row_sht)] = cost_usd
            sht['AC' + str(row_sht)].number_format = dol

            sht['AD' + str(row_sht)] = trucks_time_to_comp_days

            sht['AE' + str(row_sht)] = dest_time_to_comp_days

            sht['AF' + str(row_sht)] = time_days

            row_sht += 1

        sum['A' + str(row_cnt)] = "ScenarioID"
        sum['A' + str(row_cnt)].font = bldu
        sum['B' + str(row_cnt)] = scenarioid

        sum['A' + str(row_cnt + 1)] = "Waste Type"
        sum['A' + str(row_cnt + 1)].font = bld
        sum['B' + str(row_cnt + 1)] = sc.waste_type

        sum['A' + str(row_cnt + 2)] = "Waste Medium"
        sum['A' + str(row_cnt + 2)].font = bld
        sum['B' + str(row_cnt + 2)] = sc.waste_medium

        sum['A' + str(row_cnt + 3)] = "Total Waste Amount"
        sum['A' + str(row_cnt + 3)].font = bld
        sum['B' + str(row_cnt + 3)] = sc.waste_amount

        sum['A' + str(row_cnt + 4)] = "Allocated Amount"
        sum['A' + str(row_cnt + 4)].font = bld
        sum['B' + str(row_cnt + 4)] = total_allocated_amount

        sum['A' + str(row_cnt + 5)] = "Unallocated Amount"
        sum['A' + str(row_cnt + 5)].font = bld
        sum['B' + str(row_cnt + 5)] = unallocated_amount

        sum['A' + str(row_cnt + 6)] = "Waste Unit"
        sum['A' + str(row_cnt + 6)].font = bld
        sum['B' + str(row_cnt + 6)] = sc.waste_unit
        sum['B' + str(row_cnt + 6)].alignment = rht

        sum['C' + str(row_cnt + 1)] = "ConditionID"
        sum['C' + str(row_cnt + 1)].font = bld
        sum['D' + str(row_cnt + 1)] = sc.conditionid

        sum['C' + str(row_cnt + 2)] = "FactorID"
        sum['C' + str(row_cnt + 2)].font = bld
        sum['D' + str(row_cnt + 2)] = sc.factorid

        sum['C' + str(row_cnt + 3)] = "Total Number of Facilities"
        sum['C' + str(row_cnt + 3)].font = bld
        sum['D' + str(row_cnt + 3)] = total_number_of_facilities

        sum['C' + str(row_cnt + 4)] = "Total Number of Shipments"
        sum['C' + str(row_cnt + 4)].font = bld
        sum['D' + str(row_cnt + 4)] = total_number_of_shipments

        sum['E' + str(row_cnt + 1)] = "Total CPLM Cost ($)"
        sum['E' + str(row_cnt + 1)].font = bld
        sum['F' + str(row_cnt + 1)] = total_cplm_cost_usd
        sum['F' + str(row_cnt + 1)].number_format = dol

        sum['E' + str(row_cnt + 2)] = "Total Fixed Cost ($)"
        sum['E' + str(row_cnt + 2)].font = bld
        sum['F' + str(row_cnt + 2)] = total_fixed_cost_usd
        sum['F' + str(row_cnt + 2)].number_format = dol

        sum['E' + str(row_cnt + 3)] = "Total Tolls ($)"
        sum['E' + str(row_cnt + 3)].font = bld
        sum['F' + str(row_cnt + 3)] = total_tolls_usd
        sum['F' + str(row_cnt + 3)].number_format = dol

        sum['E' + str(row_cnt + 4)] = "Total Misc Trans Costs ($)"
        sum['E' + str(row_cnt + 4)].font = bld
        sum['F' + str(row_cnt + 4)] = total_misc_trans_cost_usd
        sum['F' + str(row_cnt + 4)].number_format = dol

        sum['E' + str(row_cnt + 5)] = "Total Transportation Cost ($)"
        sum['E' + str(row_cnt + 5)].font = bld
        sum['F' + str(row_cnt + 5)] = total_trans_cost_usd
        sum['F' + str(row_cnt + 5)].number_format = dol

        sum['G' + str(row_cnt + 1)] = "Total Staging Site Cost ($)"
        sum['G' + str(row_cnt + 1)].font = bld
        sum['H' + str(row_cnt + 1)] = total_staging_site_cost_usd
        sum['H' + str(row_cnt + 1)].number_format = dol

        sum['G' + str(row_cnt + 2)] = "Total Disposal Cost ($)"
        sum['G' + str(row_cnt + 2)].font = bld
        sum['H' + str(row_cnt + 2)] = total_disposal_cost_usd
        sum['H' + str(row_cnt + 2)].number_format = dol

        sum['G' + str(row_cnt + 3)] = "Total Labor Cost ($)"
        sum['G' + str(row_cnt + 3)].font = bld
        sum['H' + str(row_cnt + 3)] = total_labor_cost_usd
        sum['H' + str(row_cnt + 3)].number_format = dol

        sum['G' + str(row_cnt + 4)] = "Total Vehicle Decon Cost ($)"
        sum['G' + str(row_cnt + 4)].font = bld
        sum['H' + str(row_cnt + 4)] = total_vehicle_decon_cost_usd
        sum['H' + str(row_cnt + 4)].number_format = dol

        sum['G' + str(row_cnt + 5)] = "Total Cost Multiplier ($)"
        sum['G' + str(row_cnt + 5)].font = bld
        sum['H' + str(row_cnt + 5)] = total_cost_multiplier_usd
        sum['H' + str(row_cnt + 5)].number_format = dol

        sum['G' + str(row_cnt + 6)] = "Total Cost ($)"
        sum['G' + str(row_cnt + 6)].font = bld
        sum['H' + str(row_cnt + 6)] = total_cost_usd
        sum['H' + str(row_cnt + 6)].number_format = dol

        sum['I' + str(row_cnt + 1)] = "Trucks Time to Complete (days)"
        sum['I' + str(row_cnt + 1)].font = bld
        sum['J' + str(row_cnt + 1)] = max_trucks_time_to_comp_days

        sum['I' + str(row_cnt + 2)] = "Destination Time to Complete (days)"
        sum['I' + str(row_cnt + 2)].font = bld
        sum['J' + str(row_cnt + 2)] = max_dest_time_to_comp_days

        sum['I' + str(row_cnt + 3)] = "Total Time Days (days)"
        sum['I' + str(row_cnt + 3)].font = bld
        sum['J' + str(row_cnt + 3)] = max_time_days

        row_cnt = +8

    #########################################################################
    # Step 40
    # Add the Factor sheet
    #########################################################################
    ref = wb.create_sheet('Reference')

    ref.column_dimensions['A'].width = 12
    ref.column_dimensions['B'].width = 38
    ref.column_dimensions['C'].width = 25
    ref.column_dimensions['D'].width = 25
    ref.column_dimensions['E'].width = 30
    ref.column_dimensions['F'].width = 25
    ref.column_dimensions['G'].width = 25
    ref.column_dimensions['H'].width = 25

    ref['A1'] = 'Reference'
    ref['A1'].font = ft18

    row_cnt = 3

    for cid in ary_conditionids:
        if cid is not None:
            haz.conditions.loadConditionID(cid)

            ref['A' + str(row_cnt)] = "Condition ID"
            ref['A' + str(row_cnt)].font = bld
            ref['B' + str(row_cnt)] = cid
            row_cnt += 1

            ref['B' + str(row_cnt)] = 'Road Tolls ($/shipment)'
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = haz.conditions.roadtolls
            ref['C' + str(row_cnt)].number_format = dol
            row_cnt += 1

            ref['B' + str(row_cnt)] = 'Misc Costs ($/shipment)'
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = haz.conditions.misccost
            ref['C' + str(row_cnt)].number_format = dol
            row_cnt += 1

            ref['B' + str(
                row_cnt)] = 'Total Cost Multiplier (addt\'l% of total cost)'
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = str(
                haz.conditions.totalcostmultiplier * 100) + "%"
            ref['C' + str(row_cnt)].alignment = rht
            row_cnt += 1

            ref['B' + str(row_cnt)] = 'Vehicle Decon Cost ($/shipment)'
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = haz.conditions.vehicledeconcost
            ref['C' + str(row_cnt)].number_format = dol
            row_cnt += 1

            ref['B' + str(row_cnt)] = 'Staging Site Cost ($/day)'
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = haz.conditions.stagingsitecost
            ref['C' + str(row_cnt)].number_format = dol
            row_cnt += 1

            ref['B' + str(row_cnt)] = 'Number of Trucks Available (trucks)'
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = haz.conditions.numberoftrucksavailable
            row_cnt += 1

            ref['B' + str(row_cnt)] = 'Driving Hours (hrs/day)'
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = haz.conditions.drivinghours
            row_cnt += 1

    row_cnt += 1

    for fid in ary_factorids:
        if fid is not None:
            haz.factors.loadFactorID(fid)

            ref['A' + str(row_cnt)] = "Factor ID"
            ref['A' + str(row_cnt)].font = bld
            ref['B' + str(row_cnt)] = fid
            row_cnt += 1

            ref['B' + str(row_cnt)] = "Shipment Loading"
            ref['B' + str(row_cnt)].font = bld
            row_cnt += 1

            ref['B' + str(row_cnt)] = "Vehicle"
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = "Waste Type"
            ref['C' + str(row_cnt)].font = bld
            ref['D' + str(row_cnt)] = "Waste Medium"
            ref['D' + str(row_cnt)].font = bld
            ref['E' + str(row_cnt)] = "Loading Rate"
            ref['E' + str(row_cnt)].font = bld
            ref['F' + str(row_cnt)] = "Unit per shipment"
            ref['F' + str(row_cnt)].font = bld
            row_cnt += 1

            for item in haz.factors.shipment_loading:
                ref['B' + str(row_cnt)] = item.vehicle
                ref['C' + str(row_cnt)] = item.wastetype
                ref['D' + str(row_cnt)] = item.wastemedium
                ref['E' + str(row_cnt)] = item.loadingrate
                ref['F' + str(row_cnt)] = item.unitpershipment
                ref['F' + str(row_cnt)].alignment = rht
                row_cnt += 1

            ref['B' + str(row_cnt)] = "CPLM Unit Rates"
            ref['B' + str(row_cnt)].font = bld
            row_cnt += 1

            ref['B' + str(row_cnt)] = "Vehicle"
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = "CPLMDist Lower"
            ref['C' + str(row_cnt)].font = bld
            ref['D' + str(row_cnt)] = "CPLMDist Upper"
            ref['D' + str(row_cnt)].font = bld
            ref['E' + str(row_cnt)] = "Waste Type"
            ref['E' + str(row_cnt)].font = bld
            ref['F' + str(row_cnt)] = "Waste Medium"
            ref['F' + str(row_cnt)].font = bld
            ref['G' + str(row_cnt)] = "CPLMUnit Rate"
            ref['G' + str(row_cnt)].font = bld
            ref['H' + str(row_cnt)] = "Unit"
            ref['H' + str(row_cnt)].font = bld
            row_cnt += 1

            for item in haz.factors.cplm_unit_rates:
                ref['B' + str(row_cnt)] = item.vehicle
                ref['C' + str(row_cnt)] = item.cplmdist_lower
                ref['D' + str(row_cnt)] = item.cplmdist_upper
                ref['E' + str(row_cnt)] = item.wastetype
                ref['F' + str(row_cnt)] = item.wastemedium
                ref['G' + str(row_cnt)] = item.cplunit_rate
                ref['H' + str(row_cnt)] = item.unit
                ref['H' + str(row_cnt)].alignment = rht
                row_cnt += 1

            ref['B' + str(row_cnt)] = "Fixed Trans Cost"
            ref['B' + str(row_cnt)].font = bld
            row_cnt += 1

            ref['B' + str(row_cnt)] = "Vehicle"
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = "FixedCost Type"
            ref['C' + str(row_cnt)].font = bld
            ref['D' + str(row_cnt)] = "Waste Type"
            ref['D' + str(row_cnt)].font = bld
            ref['E' + str(row_cnt)] = "Waste Medium"
            ref['E' + str(row_cnt)].font = bld
            ref['F' + str(row_cnt)] = "FixedCost Value"
            ref['F' + str(row_cnt)].font = bld
            ref['G' + str(row_cnt)] = "Unit"
            ref['G' + str(row_cnt)].font = bld
            row_cnt += 1

            for item in haz.factors.fixed_trans_cost:
                ref['B' + str(row_cnt)] = item.vehicle
                ref['C' + str(row_cnt)] = item.fixedcost_type
                ref['D' + str(row_cnt)] = item.wastetype
                ref['E' + str(row_cnt)] = item.wastemedium
                ref['F' + str(row_cnt)] = item.fixedcost_value
                ref['G' + str(row_cnt)] = item.unit
                row_cnt += 1

            ref['B' + str(row_cnt)] = "Labor Costs"
            ref['B' + str(row_cnt)].font = bld
            row_cnt += 1

            ref['B' + str(row_cnt)] = "Labor Category"
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = "Labor Cost"
            ref['C' + str(row_cnt)].font = bld
            ref['D' + str(row_cnt)] = "Unit"
            ref['D' + str(row_cnt)].font = bld
            row_cnt += 1

            for item in haz.factors.labor_costs:
                ref['B' + str(row_cnt)] = item.laborcategory
                ref['C' + str(row_cnt)] = item.laborcost
                ref['D' + str(row_cnt)] = item.unit
                row_cnt += 1

            ref['B' + str(row_cnt)] = "Disposal Fees"
            ref['B' + str(row_cnt)].font = bld
            row_cnt += 1

            ref['B' + str(row_cnt)] = "Waste Type"
            ref['B' + str(row_cnt)].font = bld
            ref['C' + str(row_cnt)] = "Waste Medium"
            ref['C' + str(row_cnt)].font = bld
            ref['D' + str(row_cnt)] = "Disposal Cost"
            ref['D' + str(row_cnt)].font = bld
            ref['E' + str(row_cnt)] = "Unit"
            ref['E' + str(row_cnt)].font = bld
            row_cnt += 1

            for item in haz.factors.disposal_fees:
                ref['B' + str(row_cnt)] = item.wastetype
                ref['C' + str(row_cnt)] = item.wastemedium
                ref['D' + str(row_cnt)] = item.disposalcost
                ref['E' + str(row_cnt)] = item.unit
                row_cnt += 1

            row_cnt += 1

    #########################################################################
    # Step 50
    # Write out the excel file
    #########################################################################
    wb.save(dest_filename)

    #########################################################################
    # Step 60
    #
    #########################################################################
    del wb, sum, sht
    del cursor_in
    del haz, sc

    return
Beispiel #24
0
def toa_reflectance_457(band_nums, meta_path, outdir = False):

   """
   This function is used to convert Landsat 4,5, or 7 pixel values from
   digital numbers to Radiance, Reflectance, or Temperature (if using Band 6)

   Inputs:
      band_nums   A list of desired band numbers such as [3,4,5]
      meta_path   The full filepath to the metadata file for those bands
      outdir      Output directory to save converted files. If left False it will save ouput
                   files in the same directory as input files.
   """
   
   OutList = []

   band_nums = core.enf_list(band_nums)
   band_nums = map(str, band_nums)
   TM_ETM_bands = ['1','2','3','4','5','7','8']

   #metadata format was changed August 29, 2012. This tool can process either the new or old format
   f = open(meta_path)
   MText = f.read()

   metadata = grab_meta(meta_path)
   oldMeta = []
   newMeta = []
    
   #the presence of a PRODUCT_CREATION_TIME category is used to identify old metadata
   #if this is not present, the meta data is considered new.
   #Band6length refers to the length of the Band 6 name string. In the new metadata this string is longer
   if "PRODUCT_CREATION_TIME" in MText:
      Meta = oldMeta
      Band6length = 2
   else:
      Meta = newMeta
      Band6length = 8

   #The tilename is located using the newMeta/oldMeta indixes and the date of capture is recorded
   if Meta == newMeta:
      TileName = getattr(metadata, "LANDSAT_SCENE_ID")
      year = TileName[9:13]
      jday = TileName[13:16]
      date = getattr(metadata, "DATE_ACQUIRED")
   elif Meta == oldMeta:
      TileName = getattr(metadata, "BAND1_FILE_NAME")
      year = TileName[13:17]
      jday = TileName[17:20]
      date = getattr(metadata, "ACQUISITION_DATE")

   #the spacecraft from which the imagery was capture is identified
   #this info determines the solar exoatmospheric irradiance (ESun) for each band
   spacecraft = getattr(metadata, "SPACECRAFT_ID")
    
   if   "7" in spacecraft:
      ESun = (1969.0, 1840.0, 1551.0, 1044.0, 255.700, 0., 82.07, 1368.00)
   elif "5" in spacecraft:
      ESun = (1957.0, 1826.0, 1554.0, 1036.0, 215.0, 0. ,80.67)
   elif "4" in spacecraft:
      ESun = (1957.0, 1825.0, 1557.0, 1033.0, 214.9, 0. ,80.72)
   else:
      arcpy.AddError("This tool only works for Landsat 4, 5, or 7")
      raise arcpy.ExecuteError()

   #determing if year is leap year and setting the Days in year accordingly
   if float(year) % 4 == 0: DIY = 366.
   else:DIY=365.

   #using the date to determing the distance from the sun
   theta = 2 * math.pi * float(jday)/DIY

   dSun2 = (1.00011 + 0.034221 * math.cos(theta) + 0.001280 * math.sin(theta) +
           0.000719 * math.cos(2*theta)+ 0.000077 * math.sin(2 * theta))

   SZA = 90. - float(getattr(metadata, "SUN_ELEVATION"))
    
   #Calculating values for each band
   for band_num in band_nums:
      if band_num in TM_ETM_bands:

         print("Processing Band {0}".format(band_num))
         pathname = meta_path.replace("MTL.txt", "B{0}.tif".format(band_num))
         Oraster = arcpy.Raster(pathname)

         #using the oldMeta/newMeta indixes to pull the min/max for radiance/Digital numbers
         if Meta == newMeta:
            LMax    = getattr(metadata, "RADIANCE_MAXIMUM_BAND_" + band_num)
            LMin    = getattr(metadata, "RADIANCE_MINIMUM_BAND_" + band_num)  
            QCalMax = getattr(metadata, "QUANTIZE_CAL_MAX_BAND_" + band_num)
            QCalMin = getattr(metadata, "QUANTIZE_CAL_MIN_BAND_" + band_num)
         elif Meta == oldMeta:
            LMax    = getattr(metadata, "LMAX_BAND" + band_num)
            LMin    = getattr(metadata, "LMIN_BAND" + band_num)  
            QCalMax = getattr(metadata, "QCALMAX_BAND" + band_num)
            QCalMin = getattr(metadata, "QCALMIN_BAND" + band_num)
    
         Radraster = (((LMax - LMin)/(QCalMax-QCalMin)) * (Oraster - QCalMin)) + LMin
         Oraster = 0
    
         #Calculating temperature for band 6 if present
         Refraster = (math.pi * Radraster * dSun2) / (ESun[int(band_num[0])-1] * math.cos(SZA*(math.pi/180)))
         BandPath = "{0}\\{1}_B{2}_TOA-Ref.tif".format(outdir,TileName,band_num)
    
         Refraster.save(BandPath)
         OutList.append(arcpy.Raster(BandPath))
    
         del Refraster,Radraster
    
         arcpy.AddMessage("Reflectance Calculated for Band {0}".format(band_num))
         print("Reflectance Calculated for Band {0}".format(band_num))
   f.close()
   return OutList
Beispiel #25
0
def execute(self, parameters, messages):
   
   #########################################################################
   # Step 10 
   # Abend if edits are pending
   #########################################################################
   if util.sniff_editing_state():
      raise arcpy.ExecuteError("Error.  Pending edits must be saved or cleared before proceeding.");

   #########################################################################
   # Step 20 
   # Verify the map
   #########################################################################
   aprx = arcpy.mp.ArcGISProject("CURRENT");
   map = aprx.listMaps("AllHazardsWasteLogisticsMap")[0];
   
   if map is None:
      raise arcpy.ExecuteError("Error.  Project map not found.");
   
   #########################################################################
   # Step 40 
   # Remove the AllHazardsWaste folder and all contents
   #########################################################################
   for lyr in map.listLayers():
   
      if lyr is not None and lyr.supports("name") and  \
      ( lyr.name == "AllHazardsWasteLogisticsTool"  or lyr.longName == "AllHazardsWasteLogisticsTool" ):
         map.removeLayer(lyr);

   arcpy.AddMessage("Map Cleanup Complete.");
   
   #########################################################################
   # Step 50 
   # Cleanup preexisting workspace resources in database
   #########################################################################
   for rez in [
       "ScenarioResults"
      ,"IncidentArea"
      ,"SupportArea"
      ,"UserProvidedFacilities"
      ,"Conditions"
      ,"Scenario"
      ,"ShipmentLoading"
      ,"CPLMUnitRates"
      ,"FixedTransCost"
      ,"LaborCosts"
      ,"DisposalFees"
      ,"SystemCache"
      ,"ClosestFacility"
   ]:
   
      for suf in ["","1","2","3","4","5","6","7","8","9"]:
      
         if arcpy.Exists(os.path.join(arcpy.env.workspace,rez + suf)):

            arcpy.Delete_management(os.path.join(arcpy.env.workspace,rez + suf));
        
   arcpy.AddMessage("Database Cleanup Complete.");
   
   return;
   
   
# network dataset of roads, as well as point files of villages and a hospital. The output should be a new shapefile, with speeds as a new column
# in the attribute table.
#

import arcpy
from arcpy import env
import os


try:
    
    #This script requires network analyst to run. This will check if it is available and activate it. If not, an error message will pop up.
    if arcpy.CheckExtension("network") == "Available":
        arcpy.CheckOutExtension("network")
    else:
        raise arcpy.ExecuteError("Network Analyst Extension license is not available.")
    
    #Set environment settings. This includes output directory, workspace, overwrite capablities (to re-run tool over previous results)
    output_dir = r'H:\Morocco_Accessibility\AitOuassif\Ait_Ouassif.gdb\Results'
    
    arcpy.env.workspace = r'H:\Morocco_Accessibility\AitOuassif\Ait_Ouassif.gdb'
    
    arcpy.env.overwriteOutput = True
    
    input_gdb = r'H:\Morocco_Accessibility\AitOuassif\Ait_Ouassif.gdb'
    
    #Refers to the road network itself, which needed to be created independently. The network contains road speeds based on their
    # classification (primary, secondary, etc.), a hierarchy which prioritizes some roads over others, and the assumption that the roads
    # are traverssed with a normal car. 
    # This process can be automated, but seems like more troule than it's worth.
    inNetworkDataset = r"H:\Morocco_Accessibility\AitOuassif\Ait_Ouassif.gdb\Roads\AitOuassif_ND"
Beispiel #27
0
def appendSDMValues(gp, unitCell, TrainPts):
    try:
        arcpy.AddMessage("\n" + "="*10 + " arcsdm values  " + "=" *10);
        with open (os.path.join(os.path.dirname(__file__), "arcsdm_version.txt"), "r") as myfile:
            data=myfile.readlines()
        #Print version information
        arcpy.AddMessage("%-20s %s" % ("", data[0]) ); 
        if not gp.workspace:
            gp.adderror('Workspace not set')
            raise arcpy.ExecuteError("Workspace not set!");
        if not (arcpy.Exists(gp.workspace)):
            gp.adderror('Workspace %s not found'%(gp.workspace))
            raise arcpy.ExecuteError('Workspace %s not found'%(gp.workspace));
        desc = arcpy.Describe(gp.workspace)
        gp.addmessage("%-20s %s (%s)" % ("Workspace: ", gp.workspace, desc.workspaceType));
        
        if not gp.scratchworkspace:
            gp.adderror('Scratch workspace mask not set')
        wdesc = arcpy.Describe(gp.scratchworkspace)       
        gp.addmessage("%-20s %s (%s)" % ("Scratch workspace:",  gp.scratchworkspace, wdesc.workspaceType))
        # TODO: These should be moved to common CHECKENV class/function TR
        
        # Tools wont work if type is different from eachother (joins do not work filesystem->geodatabase! TR
        if (wdesc.workspaceType != desc.workspaceType):
            gp.AddError("Workspace and scratch workspace must be of the same type!");
            raise arcpy.ExecuteError("Workspace type mismatch");
        
        mapUnits = getMapUnits()
        mapUnits = mapUnits.lower().strip()
        if not mapUnits.startswith('meter'):
            gp.addError('Incorrect output map units: Check units of study area.')            
        conversion = getMapConversion(mapUnits)                
        #gp.addMessage("Conversion from map units to km^2: " + str(conversion));
        gp.addmessage("%-20s %s" % ( 'Map Units:',  mapUnits))
     
        
        if not gp.mask:
            gp.adderror('Study Area mask not set');
            raise arcpy.ExecuteError ("Mask not set");
        else:
            if not arcpy.Exists(gp.mask):
                gp.addError("Mask " + gp.mask + " not found!");
                raise arcpy.ExecuteError("Mask not found");
            #gp.AddMessage("Mask set");
            desc = gp.describe(gp.mask);
            gp.addMessage( "%-20s %s" %( "Mask:", "\"" + desc.name + "\" and it is " + desc.dataType));           
            gp.addMessage( "%-20s %s" %( "Mask size:", str(getMaskSize(mapUnits))  ));           
            #gp.AddMessage("Masksize: " + str(getMaskSize()));            
        
        if not gp.cellsize:        
            gp.adderror('Study Area cellsize not set')
        if (gp.cellsize == "MAXOF"):
            arcpy.AddWarning("Cellsize should have definitive value?");
            #raise arcpy.ExecuteError("SDMValues: Cellsize must have value");
            
        
        cellsize = arcpy.env.cellSize #float(str(arcpy.env.cellSize).replace(",","."))
        gp.addmessage("%-20s %s" %("Cell Size:", cellsize))
        #gp.addMessage("Debug: " + str(conversion));
        total_area = getMaskSize(mapUnits) # Now the getMaskSize returns it correctly in sqkm   : * cellsize **2 * conversion
        #gp.addMessage("Debug));
        unitCell = float(unitCell)
        num_unit_cells = total_area / unitCell
        num_tps = gp.GetCount_management(TrainPts)
        gp.addmessage("%-20s %s"% ('# Training Sites:' ,num_tps))
        gp.addmessage("%-20s %s" % ("Unit Cell Area:", "{}km^2, Cells in area: {} ".format(unitCell,num_unit_cells)))
        
        priorprob = num_tps / num_unit_cells
        if not (0 < priorprob <= 1.0):
            arcpy.AddError('Incorrect no. of training sites or unit cell area. TrainingPointsResult {}'.format(priorprob))
            raise arcpy.ExecuteError
            #raise SDMError('Incorrect no. of training sites or unit cell area. TrainingPointsResult {}'.format(priorprob))
        gp.addmessage("%-20s %0.6f" % ('Prior Probability:', priorprob))
        #gp.addmessage("Debug priorprob:" + str(getPriorProb(TrainPts, unitCell))) 
        
        gp.addmessage("%-20s %s" % ('Training Set:', gp.describe(TrainPts).catalogpath))
        gp.addmessage("%-20s %s" % ('Study Area Raster:', gp.describe(gp.mask).catalogpath))
        gp.addmessage("%-20s %s" % ( 'Study Area Area:', str(total_area) + "km^2"))
        #gp.addmessage('Map Units to Square Kilometers Conversion: %f'%conversion)
        arcpy.AddMessage(""); # Empty line at end
    except arcpy.ExecuteError as e:
        if not all(e.args):
            arcpy.AddMessage("Calculate weights caught arcpy.ExecuteError: ");
            args = e.args[0];
            args.split('\n')
            arcpy.AddError(args);
        arcpy.AddMessage("-------------- END EXECUTION ---------------");        
        raise;
    except:
        # get the traceback object
        tb = sys.exc_info()[2]
        # tbinfo contains the line number that the code failed on and the code from that line
        tbinfo = traceback.format_tb(tb)[0]
        gp.addError ( tbinfo );
        # concatenate information together concerning the error into a message string
        #pymsg = "PYTHON ERRORS:\nTraceback Info:\n" + tbinfo + "\nError Info:\n    " + \
        #    str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n"
        # generate a message string for any geoprocessing tool errors
        if len(gp.GetMessages(2)) > 0:
            msgs = "SDM GP ERRORS:\n" + gp.GetMessages(2) + "\n"
            gp.AddError(msgs)
        #gp.AddError(pymsg)
        raise;
Beispiel #28
0
def DNtoReflectance(Lbands,
                    MetaData,
                    OutputType="Reflectance/Temperature",
                    Save=False,
                    OutputFolder=""):
    """This function is used to convert Landsat 4,5, or 7 pixel values from
    digital numbers to Radiance, Reflectance, or Temperature (if using Band 6)

    -----Inputs------
    Lbands: GeoTIFF files containing individual bands of Landsat imagery. These
    must have the original names as downloaded and must be from a single scene.

    MetaData: The metadata text file that is downloaded with the Landsat Bands themselves.
    This may be either the old or new MTL.txt file.

    OutputType: Choose whether the output should be:
                "Radiance"
                "Reflectance/Temperature" - Calculates Reflectance for spectral bands
                                            and Temperature in Kelvin for Thermal bands

    Save: Boolean value that indicates whether the output rasters will be saved permanantly
            Each band will be saved as an individual GeoTIFF file and be named
            accoriding to the original filename and the output pixel unit

            *if this is true, then the OutputFolder variable must also be set

    OutputFolder: Folder in which to save the output rasters

    -----Outputs-----

    A list of arcpy raster objects in a sequence that mirrors that of the input Lbands

    """
    OutList = []

    #These lists will be used to parse the meta data text file and locate relevant information
    #metadata format was changed August 29, 2012. This tool can process either the new or old format
    newMeta = [
        'LANDSAT_SCENE_ID = "', 'DATE_ACQUIRED = ', "SUN_ELEVATION = ",
        "RADIANCE_MAXIMUM_BAND_{0} = ", "RADIANCE_MINIMUM_BAND_{0} = ",
        "QUANTIZE_CAL_MAX_BAND_{0} = ", "QUANTIZE_CAL_MIN_BAND_{0} = "
    ]

    oldMeta = [
        'BAND1_FILE_NAME = "', "ACQUISITION_DATE = ", "SUN_ELEVATION = ",
        "LMAX_BAND{0} = ", "LMIN_BAND{0} = ", "QCALMAX_BAND{0} = ",
        "QCALMIN_BAND{0} = "
    ]
    f = open(MetaData)
    MText = f.read()

    #the presence of a PRODUCT_CREATION_TIME category is used to identify old metadata
    #if this is not present, the meta data is considered new.
    #Band6length refers to the length of the Band 6 name string. In the new metadata this string is longer
    if "PRODUCT_CREATION_TIME" in MText:
        Meta = oldMeta
        Band6length = 2
    else:
        Meta = newMeta
        Band6length = 8

    #The tilename is located using the newMeta/oldMeta indixes and the date of capture is recorded
    if Meta == newMeta:
        TileName = MText.split(Meta[0])[1].split('"')[0]
        year = TileName[9:13]
        jday = TileName[13:16]
    elif Meta == oldMeta:
        TileName = MText.split(Meta[0])[1].split('"')[0]
        year = TileName[13:17]
        jday = TileName[17:20]

    date = MText.split(Meta[1])[1].split('\n')[0]

    #the spacecraft from which the imagery was capture is identified
    #this info determines the solar exoatmospheric irradiance (ESun) for each band
    spacecraft = MText.split('SPACECRAFT_ID = "')[1].split('"')[0]
    if "7" in spacecraft:
        ESun = (1969.0, 1840.0, 1551.0, 1044.0, 255.700, 0., 82.07, 1368.00)
    elif "5" in spacecraft:
        ESun = (1957.0, 1826.0, 1554.0, 1036.0, 215.0, 0., 80.67)
    elif "4" in spacecraft:
        ESun = (1957.0, 1825.0, 1557.0, 1033.0, 214.9, 0., 80.72)
    else:
        arcpy.AddError("This tool only works for Landsat 4, 5, or 7")
        raise arcpy.ExecuteError()

    #determing if year is leap year and setting the Days in year accordingly
    if float(year) % 4 == 0: DIY = 366.
    else: DIY = 365.

    #using the date to determing the distance from the sun
    theta = 2 * math.pi * float(jday) / DIY

    dSun2 = (1.00011 + 0.034221 * math.cos(theta) +
             0.001280 * math.sin(theta) + 0.000719 * math.cos(2 * theta) +
             0.000077 * math.sin(2 * theta))

    SZA = 90. - float(MText.split(Meta[2])[1].split("\n")[0])

    #Calculating values for each band
    for pathname in Lbands:
        try:
            BandNum = pathname.split("\\")[-1].split("B")[1][0]
        except:
            msg = "Error reading Band {0}. Bands must have original names as downloaded.".format(
                str(inputbandnum))
            arcpy.AddError(msg)
            print(msg)
            raise arcpy.ExecuteError

        #changing Band 6 name to match metadata
        if BandNum == "6" and spacecraft[8] == "7":
            BandNum = pathname.split("\\")[-1].split("B")[1][0:Band6length]

        print("Processing Band {0}".format(BandNum))

        Oraster = arcpy.Raster(pathname)

        #using the oldMeta/newMeta indixes to pull the min/max for radiance/Digital numbers
        LMax = float(MText.split(Meta[3].format(BandNum))[1].split("\n")[0])
        LMin = float(MText.split(Meta[4].format(BandNum))[1].split("\n")[0])
        QCalMax = float(MText.split(Meta[5].format(BandNum))[1].split("\n")[0])
        QCalMin = float(MText.split(Meta[6].format(BandNum))[1].split("\n")[0])

        Radraster = (((LMax - LMin) / (QCalMax - QCalMin)) *
                     (Oraster - QCalMin)) + LMin
        Oraster = 0

        if OutputType == "Radiance":
            Radraster.save("{0}\\{1}_B{2}_Radiance.tif".format(
                OutputFolder, TileName, BandNum))
            Radraster = 0

        elif OutputType == "Reflectance/Temperature":
            #Calculating temperature for band 6 if present
            if "6" in BandNum:
                Refraster = 1282.71 / (arcpy.sa.Ln((666.09 / Radraster) + 1.0))
                BandPath = "{0}\\{1}_B{2}_Temperature.tif".format(
                    OutputFolder, TileName, BandNum)
            #Otherwise calculate reflectance
            else:
                Refraster = (math.pi * Radraster * dSun2) / (
                    ESun[int(BandNum[0]) - 1] * math.cos(SZA * math.pi / 180))
                BandPath = "{0}\\{1}_B{2}_TOA_Reflectance.tif".format(
                    OutputFolder, TileName, BandNum)

            if Save == True:
                Refraster.save(BandPath)
                OutList.append(arcpy.Raster(BandPath))
            else:
                OutList.append(Refraster)
            del Refraster, Radraster

        arcpy.AddMessage("Reflectance Calculated for Band {0}".format(BandNum))
        print("Reflectance Calculated for Band {0}".format(BandNum))
    f.close()
    return OutList
Weight = Demand
"""
#################################################

try:
    # import libraries
    import arcpy
    from arcpy import env
    import arcpy.na
    import os

    # Check for NA extension
    if arcpy.CheckOutExtension("network") == "Available":
        arcpy.CheckOutExtension("network")
    else:
        raise arcpy.ExecuteError("Network analyst extension is not available.")

    # Environment settings
    output_dir = r'D:\Python_Tools_Code\Location_Allocation'  # switch out with your workspace file path
    env.workspace = os.path.join(output_dir, "Loc_Alloc_py.gdb")
    env.overwriteOutput = True

    # Set network route feature dataset and input data -- set local environment parameters
    na_network_data_source = r'C:\ArcGIS\Business Analyst\US_2018\Data\Streets Data\NorthAmerica.gdb\Routing\Routing_ND'  # point to Routing_ND feature dataset
    input_gdb = r'D:\Python_Tools_Code\Location_Allocation\Loc_Alloc_py\Loc_Alloc_py.gdb'  # point to user geodatabase file path

    # User input variable for layer name and travel mode type
    layer_name = str(input("Enter location allocation layer name: ")
                     )  # create layer name for Location Allocation model
    travel_mode = str(input("Enter the travel mode type: "))
Beispiel #30
0
def toa_radiance_457(band_nums, meta_path, outdir=None):
    """
    Top of Atmosphere radiance (in Watts/(square meter x steradians x micrometers))
    conversion for Landsat 4, 5, and 7 data. To be performed on raw
    Landsat 4, 5, or 7 level 1 data.

    :param band_nums:   A list of desired band numbers such as [3, 4, 5]
    :param meta_path:   The full filepath to the metadata file for those bands
    :param outdir:      Output directory to save converted files.

    :return output_filelist:    List of filepaths created by this function.
    """

    output_filelist = []
    meta_path = os.path.abspath(meta_path)

    band_nums = core.enf_list(band_nums)
    band_nums = map(str, band_nums)

    #metadata format was changed August 29, 2012. This tool can process either the new or old format
    f = open(meta_path)
    MText = f.read()

    metadata = landsat_metadata(meta_path)

    #the presence of a PRODUCT_CREATION_TIME category is used to identify old metadata
    #if this is not present, the meta data is considered new.
    #Band6length refers to the length of the Band 6 name string. In the new metadata this string is longer
    if "PRODUCT_CREATION_TIME" in MText:
        Meta = "oldMeta"
        Band6length = 2
    else:
        Meta = "newMeta"
        Band6length = 8

    #The tilename is located using the newMeta/oldMeta indixes and the date of capture is recorded
    if Meta == "newMeta":
        TileName = getattr(metadata, "LANDSAT_SCENE_ID")
        year = TileName[9:13]
        jday = TileName[13:16]
        date = getattr(metadata, "DATE_ACQUIRED")

    elif Meta == "oldMeta":
        TileName = getattr(metadata, "BAND1_FILE_NAME")
        year = TileName[13:17]
        jday = TileName[17:20]
        date = getattr(metadata, "ACQUISITION_DATE")

    #the spacecraft from which the imagery was capture is identified
    #this info determines the solar exoatmospheric irradiance (ESun) for each band
    spacecraft = getattr(metadata, "SPACECRAFT_ID")

    if "7" in spacecraft:
        ESun = (1969.0, 1840.0, 1551.0, 1044.0, 255.700, 0., 82.07, 1368.00)
        TM_ETM_bands = ['1', '2', '3', '4', '5', '7', '8']

    elif "5" in spacecraft:
        ESun = (1957.0, 1826.0, 1554.0, 1036.0, 215.0, 0., 80.67)
        TM_ETM_bands = ['1', '2', '3', '4', '5', '7']

    elif "4" in spacecraft:
        ESun = (1957.0, 1825.0, 1557.0, 1033.0, 214.9, 0., 80.72)
        TM_ETM_bands = ['1', '2', '3', '4', '5', '7']

    else:
        arcpy.AddError("This tool only works for Landsat 4, 5, or 7")
        raise arcpy.ExecuteError()

    #Calculating values for each band
    for band_num in band_nums:
        if band_num in TM_ETM_bands:

            print("Processing Band {0}".format(band_num))
            pathname = meta_path.replace("MTL.txt",
                                         "B{0}.tif".format(band_num))
            Oraster = arcpy.Raster(pathname)

            null_raster = arcpy.sa.SetNull(Oraster, Oraster, "VALUE = 0")

            #using the oldMeta/newMeta indixes to pull the min/max for radiance/Digital numbers
            if Meta == "newMeta":
                LMax = getattr(metadata,
                               "RADIANCE_MAXIMUM_BAND_{0}".format(band_num))
                LMin = getattr(metadata,
                               "RADIANCE_MINIMUM_BAND_{0}".format(band_num))
                QCalMax = getattr(metadata,
                                  "QUANTIZE_CAL_MAX_BAND_{0}".format(band_num))
                QCalMin = getattr(metadata,
                                  "QUANTIZE_CAL_MIN_BAND_{0}".format(band_num))

            elif Meta == "oldMeta":
                LMax = getattr(metadata, "LMAX_BAND{0}".format(band_num))
                LMin = getattr(metadata, "LMIN_BAND{0}".format(band_num))
                QCalMax = getattr(metadata, "QCALMAX_BAND{0}".format(band_num))
                QCalMin = getattr(metadata, "QCALMIN_BAND{0}".format(band_num))

            Radraster = (((LMax - LMin) / (QCalMax - QCalMin)) *
                         (null_raster - QCalMin)) + LMin
            Oraster = 0
            del null_raster

            band_rad = "{0}_B{1}".format(TileName, band_num)

            #create the output name and save the TOA radiance tiff
            if outdir is not None:
                outdir = os.path.abspath(outdir)
                outname = core.create_outname(outdir, band_rad, "TOA_Rad",
                                              "tif")
            else:
                folder = os.path.split(meta_path)[0]
                outname = core.create_outname(folder, band_rad, "TOA_Rad",
                                              "tif")

            Radraster.save(outname)
            output_filelist.append(outname)

            del Radraster

            print("toa radiance saved for Band {0}".format(band_num))

        #if listed band is not a TM/ETM+ sensor band, skip it and print message
        else:
            print(
                "Can only perform reflectance conversion on TM/ETM+ sensor bands"
            )
            print("Skipping band {0}".format(band_num))

    f.close()
    return output_filelist