def reading_line_features_vertices(gp, inputFC, field_peilgebied_id, peilgebieden_centroides_dict):
    ''' leest de vertices van een line feature en plaatst de coordinaten in een dictionary. per peilgebied worden de knopen afzonderlijk
    opgeslagen:
    outputdictionary = { GPGIDENT: {1:'x1 y1',2:x2 y2'}}
    '''
    vertex_dict = {}

    inDesc = gp.describe(inputFC)
    inRows = gp.searchcursor(inputFC)
    inRow = inRows.next()

    while inRow:
        peilgebied_shapefile = inRow.getValue(field_peilgebied_id)
        if peilgebieden_centroides_dict.has_key(peilgebied_shapefile):
            #de gpgident uit de waterlijnenshape komt voor in de dictionary peilgebieden met centroides
            feat = inRow.GetValue(inDesc.ShapeFieldName)
            partnum = 0
            partcount = feat.partcount
            while partnum < partcount:
                part = feat.getpart(partnum)
                part.reset()
                pnt = part.next()
                pnt_count = 0
                while pnt:
                    if not vertex_dict.has_key(peilgebied_shapefile):
                        vertex_dict[peilgebied_shapefile] = {}
                    vertex_dict[peilgebied_shapefile][pnt_count] = pnt
                    pnt = part.next()
                    pnt_count += 1

                partnum += 1
        inRow = inRows.next()

    return vertex_dict
def calculate_to_and_from_point(gp, fc, ident):
    """
    calculated a 2-tuple (x, y) for the frompoint and to_point of a line fc
    """
    result = {}
    row = gp.SearchCursor(fc)
    for item in nens.gp.gp_iterator(row):
        feat = item.GetValue(gp.describe(fc).ShapeFieldName)
        item_id = item.GetValue(ident)
        pnt_list = [(pnt.x, pnt.y) for pnt in nens.gp.gp_iterator(feat.getpart(0))]
        result[item_id] = {"from_x": pnt_list[0][0], "from_y": pnt_list[0][1], "to_x": pnt_list[-1][0], "to_y": pnt_list[-1][1]}

    return result
def get_line_parts(gp, line_fc, line_ident):
    """reads all the lines in the line_fc and return a dict with all line parts
    """
    lineparts = {}
    line_desc = gp.describe(line_fc)
    row = gp.SearchCursor(line_fc)
    for item in nens.gp.gp_iterator(row):
        feat = item.GetValue(line_desc.ShapeFieldName)
        item_id = item.GetValue(line_ident)

        part = feat.getpart(0)
        pnt_list = [(round(pnt.x, 5), round(pnt.y, 5)) for pnt in
                    nens.gp.gp_iterator(part)]

        lineparts[item_id] = pnt_list
    return lineparts
def add_centroids(gp, input_polygon):
    """
    """
    if not turtlebase.arcgis.is_fieldname(gp, input_polygon, "POINT_X"):
        gp.AddField(input_polygon, "POINT_X", "Double")
    if not turtlebase.arcgis.is_fieldname(gp, input_polygon, "POINT_Y"):
        gp.AddField(input_polygon, "POINT_Y", "Double")

    in_desc = gp.describe(input_polygon)
    row = gp.UpdateCursor(input_polygon)
    for item in nens.gp.gp_iterator(row):
        feat = item.GetValue(in_desc.ShapeFieldName)
        x, y = turtlebase.arcgis.calculate_xy(gp, feat.Centroid)
        
        # wegschrijven naar veld
        item.setValue('POINT_X', x)
        item.setValue('POINT_Y', y)
        row.UpdateRow(item)
def create_centroids(gp, multipoints, output_fc, mp_ident):
    """creates a centerpoint fc out of a multipoint fc
    """
    gp.AddXY_management(multipoints)

    mpoint_desc = gp.describe(multipoints)
    center_points = {}

    row = gp.SearchCursor(multipoints)
    for item in nens.gp.gp_iterator(row):
        feat = item.GetValue(mpoint_desc.ShapeFieldName)
        item_id = item.GetValue(mp_ident)
        xcoord, ycoord = calculate_xy(gp, feat)
        
        center_points[item_id] = {"xcoord": xcoord, "ycoord": ycoord}

    workspace = os.path.dirname(output_fc)
    fc_name = os.path.basename(output_fc)
    gp.CreateFeatureClass_management(workspace, fc_name, "Point",
                                "#", "DISABLED", "DISABLED", "#")
    gp.addfield(output_fc, 'proident', "TEXT")
    gp.addfield(output_fc, 'xcoord', "DOUBLE")
    gp.addfield(output_fc, 'ycoord', "DOUBLE")

    rows = gp.InsertCursor(output_fc)
    point = gp.CreateObject("Point")

    for point_id, attributes in center_points.items():
        row = rows.NewRow()
        point.x = attributes['xcoord']
        point.y = attributes['ycoord']
        row.shape = point
        row.SetValue('proident', point_id)
        row.SetValue('xcoord', point.x)
        row.SetValue('ycoord', point.y)

        rows.InsertRow(row)
    del rows
    del row
def read_lines(gp, line_fc, ident=None):
    """
    """
    points = {}
    inDesc = gp.describe(line_fc)

    row = gp.SearchCursor(line_fc)
    id_int = 0
    for item in nens.gp.gp_iterator(row):
        feat = item.GetValue(inDesc.ShapeFieldName)
        shape_length = feat.length
        if ident is None:
            item_id = id_int
            id_int += 1
        else:
            item_id = item.GetValue(ident)

        part = feat.getpart(0)
        pnt_list = [(float(pnt.x), float(pnt.y)) for pnt in nens.gp.gp_iterator(part)]
        points[(item_id, shape_length)] = pnt_list

    return points
def get_pointcloud(gp, point_fc, point_ident, zcoord):
    """
    reads all the points in the pointcloud and return a
    dict with all points that match point_id
    """
    pointcloud = {}
    point_desc = gp.describe(point_fc)

    row = gp.SearchCursor(point_fc)
    for item in nens.gp.gp_iterator(row):
        feat = item.GetValue(point_desc.ShapeFieldName)
        item_id = item.GetValue(point_ident)

        point_x, point_y = calculate_xy(gp, feat)
        pnt_xyz = (point_x,
                  point_y,
                  float(item.GetValue(zcoord)))

        if item_id not in pointcloud:
            pointcloud[item_id] = [pnt_xyz]
        else:
            pointcloud[item_id].append(pnt_xyz)

    return pointcloud
def reading_line_features_nodes(gp, inputFC):
    nodes_dict = {}
    ''' leest de nodes van een line feature in en plaatst de coordinaten in een dictionary.'''
    inDesc = gp.describe(inputFC)
    inRows = gp.searchcursor(inputFC)
    inRow = inRows.next()
    temp_dict = {}

    row_id = 0
    while inRow:
        feat = inRow.GetValue(inDesc.ShapeFieldName)
        row_id += 1
        partnum = 0
        partcount = feat.partcount
        while partnum < partcount:
            part = feat.getpart(partnum)
            part.reset()
            pnt = part.next()
            pnt_count = 0
            while pnt:
                key = str(row_id) + "__" + str(pnt_count)
##                if not nodes_dict.has_key(row_id):
##                        nodes_dict[row_id] = {}
##                nodes_dict[row_id][pnt_count] = str(pnt.x) + " " + str(pnt.y)
                #key_coord = '%.5f' % (pnt.x) + " " + '%.5f' % (pnt.y)
                if temp_dict.has_key(pnt):
                    nodes_dict[key] = pnt
                temp_dict[pnt] = key

                pnt = part.next()
                pnt_count += 1

            partnum += 1
        inRow = inRows.next()

    return nodes_dict
def main():
    try:
        gp = mainutils.create_geoprocessor()
        config = mainutils.read_config(__file__, 'turtle-settings.ini')
        logfile = mainutils.log_filename(config)
        logging_config = LoggingConfig(gp, logfile=logfile)
        mainutils.log_header(__name__)
        #----------------------------------------------------------------------------------------
        # Create workspace
        workspace = config.get('GENERAL', 'location_temp')
        if workspace == "-":
            workspace = tempfile.gettempdir()
            log.info("location temp: %s" % workspace)

        turtlebase.arcgis.delete_old_workspace_gdb(gp, workspace)

        if not os.path.isdir(workspace):
            os.makedirs(workspace)
        workspace_gdb, errorcode = turtlebase.arcgis.create_temp_geodatabase(gp, workspace)
        if errorcode == 1:
            log.error("failed to create a file geodatabase in %s" % workspace)

        #----------------------------------------------------------------------------------------
        #get argv
        log.info("Getting command parameters... ")
        if len(sys.argv) == 7:
            input_peilgebieden_feature = sys.argv[1] #from HydroBase
            input_lgn = sys.argv[2]
            input_conversiontable_dbf = sys.argv[3]
            input_watershape = sys.argv[4]
            output_table = sys.argv[5] #RR_oppervlak in HydroBase
            output_crop_table = sys.argv[6]
        else:
            log.error("Arguments: <LGN raster> <peilgebied HydroBase-table> <conversiontable dbf> <output HydroBase-table>")
            sys.exit(1)

        #----------------------------------------------------------------------------------------
        # Check geometry input parameters
        log.info("Check geometry of input parameters")
        geometry_check_list = []

        lgn_desc = gp.describe(input_lgn)
        if lgn_desc.DataType == 'RasterDataset' or lgn_desc.DataType == 'RasterLayer':
            if lgn_desc.PixelType[0] not in ["S", "U"]:
                errormsg = "input %s is not an integer raster!" % input_lgn
                log.error(errormsg)
                geometry_check_list.append(errormsg)
                # Create shapefile from input raster
            else:
                log.info("Input LGN is a raster, convert to feature class")
                temp_lgn_fc = turtlebase.arcgis.get_random_file_name(workspace_gdb)
                gp.RasterToPolygon_conversion(input_lgn, temp_lgn_fc, "NO_SIMPLIFY")
        elif lgn_desc.DataType == 'ShapeFile' or lgn_desc.DataType == 'FeatureClass':
            if lgn_desc.ShapeType != 'Polygon':
                errormsg = "input %s is not an integer raster!" % input_lgn
                log.error(errormsg)
                geometry_check_list.append(errormsg)
            else:
                # Copy shapefile to workspace
                log.info("Input LGN is a feature class, copy to workspace")
                temp_lgn_fc = turtlebase.arcgis.get_random_file_name(workspace_gdb)
                gp.Select_analysis(input_lgn, temp_lgn_fc)
        else:
            log.error("datatype of LGN is %s , must be a ShapeFile, FeatureClass, RasterDataset or RasterLayer" % lgn_desc.DataType)
            sys.exit(5)

        if not(gp.exists(input_peilgebieden_feature)):
            errormsg = "input %s does not exist!" % input_peilgebieden_feature
            log.error(errormsg)
            geometry_check_list.append(errormsg)

        if not(gp.exists(input_conversiontable_dbf)):
            errormsg = "input %s does not exist!" % input_conversiontable_dbf
            log.error(errormsg)
            geometry_check_list.append(errormsg)

        if len(geometry_check_list) > 0:
            log.error("check input: %s" % geometry_check_list)
            sys.exit(2)

        #----------------------------------------------------------------------------------------
        # Check required fields in input data
        log.info("Check required fields in input data")

        missing_fields = []

        "<check required fields from input data, append them to list if missing>"
        gpgident = config.get('GENERAL', 'gpgident')        
        if not turtlebase.arcgis.is_fieldname(gp, input_peilgebieden_feature, gpgident):
            log.debug(" - missing: %s in %s" % (gpgident, input_peilgebieden_feature))
            missing_fields.append("%s: %s" % (input_peilgebieden_feature, gpgident))

        hectares = config.get('OppervlakteParameters', 'input_oppervlak_area')
        verhard_ha = config.get('OppervlakteParameters', 'input_oppervlak_verhard')
        onvsted_ha = config.get('OppervlakteParameters', 'input_oppervlak_onvsted')
        kassen_ha = config.get('OppervlakteParameters', 'input_oppervlak_kassen')
        onvland_ha = config.get('OppervlakteParameters', 'input_oppervlak_onvland')
        openwat_ha = config.get('OppervlakteParameters', 'input_oppervlak_openwat')
        lgn_id = config.get('OppervlakteParameters', 'input_field_lgncode')
        conversion_fields = [lgn_id, verhard_ha, onvsted_ha, kassen_ha, onvland_ha, openwat_ha, hectares]
        for conversion_field in conversion_fields:
            if not turtlebase.arcgis.is_fieldname(gp, input_conversiontable_dbf, conversion_field):
                log.debug(" - missing: %s in %s" % (conversion_field, input_conversiontable_dbf))
                missing_fields.append("%s: %s" % (input_conversiontable_dbf, conversion_field))

        if len(missing_fields) > 0:
            log.error("missing fields in input data: %s" % missing_fields)
            sys.exit(2)

        #----------------------------------------------------------------------------------------
        # 2a) copy input targetlevel areas to workspace
        log.info("A) Create feature class input_peilgebieden_feature -> tempfile_peilgebied")
        peilgebieden_temp = turtlebase.arcgis.get_random_file_name(workspace_gdb)
        gp.select_analysis(input_peilgebieden_feature, peilgebieden_temp)

        # 2b) intersect(lgn+peilgebieden)
        log.info("B) Intersect lgn_shape + tempfile_peilgebied -> lgn_peilgebieden")
        intersect_temp = os.path.join(workspace_gdb, 'intersect_lgn_gpg')
        gp.Union_analysis("%s;%s" % (temp_lgn_fc, peilgebieden_temp), intersect_temp)

        # 3a) Read conversiontable into memory"
        log.info("C-1) Read conversiontable into memory")
        conversion = nens.gp.get_table(gp, input_conversiontable_dbf, primary_key=lgn_id.lower())

        # 3b) calculate areas for lgn_id
        log.info("C-2) Calculate areas for tempfile_LGN_peilgebied using conversiontable")
        #read gpgident from file
        lgn_fieldnames = nens.gp.get_table_def(gp, temp_lgn_fc)
        if "gridcode" in lgn_fieldnames:
            gridcode = "GRIDCODE"
        elif "grid_code" in lgn_fieldnames:
            gridcode = "grid_code"
        else:
            log.error("Cannot find 'grid_code' or 'gridcode' field in input lgn file")

        gewastypen = {1: config.get('OppervlakteParameters', 'grass_area'),
                      2: config.get('OppervlakteParameters', 'corn_area'),
                      3: config.get('OppervlakteParameters', 'potatoes_area'),
                      4: config.get('OppervlakteParameters', 'sugarbeet_area'),
                      5: config.get('OppervlakteParameters', 'grain_area'),
                      6: config.get('OppervlakteParameters', 'miscellaneous_area'),
                      7: config.get('OppervlakteParameters', 'nonarable_land_area'),
                      8: config.get('OppervlakteParameters', 'greenhouse_area'),
                      9: config.get('OppervlakteParameters', 'orchard_area'),
                      10: config.get('OppervlakteParameters', 'bulbous_plants_area'),
                      11: config.get('OppervlakteParameters', 'foliage_forest_area'),
                      12: config.get('OppervlakteParameters', 'pine_forest_area'),
                      13: config.get('OppervlakteParameters', 'nature_area'),
                      14: config.get('OppervlakteParameters', 'fallow_area'),
                      15: config.get('OppervlakteParameters', 'vegetables_area'),
                      16: config.get('OppervlakteParameters', 'flowers_area'),
                      }
        output_with_area = {}
        output_gewas_areas = {}
        unknown_lgn_codes = {}
        source_str = "lgn:" + os.path.basename(input_lgn) + " pg:" + os.path.basename(input_peilgebieden_feature)
        if len(source_str) > 50:
            source_str = source_str[:50]
        date_str = time.strftime('%x')

        calc_count = 0
        rows = gp.UpdateCursor(intersect_temp)
        for row in nens.gp.gp_iterator(rows):
            value_gpgident = row.GetValue(gpgident)
            if value_gpgident == "":
                continue
            value_gridcode = row.GetValue(gridcode)
            if value_gridcode == 0:
                if value_gpgident in output_with_area:
                    output_with_area[value_gpgident][hectares] += float(row.shape.Area) / 10000
                else:
                    output_with_area[value_gpgident] = {gpgident : value_gpgident, hectares : float(row.shape.Area) / 10000}
                continue
                    
            value_lgn_id = int(value_gridcode)
            value_peilgeb_area = float(row.shape.Area) / 10000 #Area is in m2
            
            if 'gewastype' in conversion[value_lgn_id]:
                gewastype = conversion[value_lgn_id]['gewastype']
            else:
                gewastype = 1
            #add to area
            if value_gpgident in output_with_area:
                add_to_area, gewastype_ha, error = conv_ha(conversion, value_lgn_id, float(value_peilgeb_area), gewastype)
                for key in add_to_area.keys(): #all relevant keys
                    if key in output_with_area[value_gpgident]:
                        output_with_area[value_gpgident][key] += float(add_to_area[key])
                    else:
                        output_with_area[value_gpgident][key] = float(add_to_area[key])
            else:
                output_with_area[value_gpgident], gewastype_ha, error = conv_ha(conversion, value_lgn_id, float(value_peilgeb_area), gewastype)
                output_with_area[value_gpgident][gpgident] = value_gpgident #set GPGIDENT
                if error and not(value_lgn_id in unknown_lgn_codes):
                    log.warning(" - Warning: lgncode " + str(value_lgn_id) + " not known (check conversiontable)")
                    unknown_lgn_codes[value_lgn_id] = 1
            
            if gewastype != 0:
                if value_gpgident not in output_gewas_areas:
                    output_gewas_areas[value_gpgident] = {gpgident: value_gpgident}
                    for key in gewastypen.keys():
                        output_gewas_areas[value_gpgident][gewastypen[key]] = 0
                    
                output_gewas_areas[value_gpgident][gewastypen[gewastype]] += gewastype_ha
                
            output_with_area[value_gpgident]['LGN_SOURCE'] = source_str
            output_with_area[value_gpgident]['LGN_DATE'] = date_str
            calc_count = calc_count + 1
            if calc_count % 100 == 0:
                log.info("Calculating field nr " + str(calc_count))
        #----------------------------------------------------------------------------------------
        if input_watershape != "#":
            log.info("C-3) Calculate open water from watershape")

            # 1) intersect(watershape+peilgebieden)
            log.info("- intersect water_shape + tempfile_peilgebied -> watershape_peilgebieden")
            watershape_intersect = turtlebase.arcgis.get_random_file_name(workspace_gdb)
            gp.Intersect_analysis("%s;%s" % (input_watershape, peilgebieden_temp), watershape_intersect)

            source_watershape = os.path.basename(input_watershape)
            if len(source_watershape) > 50:
                source_watershape = source_watershape[:50]

            watershape_areas = {}
            rows = gp.SearchCursor(watershape_intersect)
            for row in nens.gp.gp_iterator(rows):
                water_area_ha = float(row.shape.Area) / 10000 #Area is in m2
                peilgebied_id = row.GetValue(gpgident)
                if peilgebied_id in watershape_areas:
                    subtotal_area = watershape_areas[peilgebied_id]['area']
                    #overwrite key with sum areas
                    watershape_areas[peilgebied_id] = {'area': subtotal_area + water_area_ha}
                else:
                    #create new key with area
                    watershape_areas[peilgebied_id] = {'area': water_area_ha}
            #update outputtable
            for peilgebied_id in output_with_area.keys():
                if peilgebied_id in watershape_areas:
                    output_with_area[peilgebied_id]['OPNWT_GBKN'] = watershape_areas[peilgebied_id]['area']
                    output_with_area[peilgebied_id]['GBKN_DATE'] = date_str
                    output_with_area[peilgebied_id]['GBKN_SOURCE'] = source_watershape

        #----------------------------------------------------------------------------------------
        # 4) put dictionary area into output_table (HydroBase)
        log.info("D) Saving results... ")

        #definition of fields
        areaFields = {gpgident: {'type': 'TEXT', 'length': '30'},
                      'VERHRD_LGN':{'type': 'DOUBLE'},
                      'ONVSTD_LGN':{'type': 'DOUBLE'},
                      'KASSEN_LGN':{'type': 'DOUBLE'},
                      'ONVLND_LGN':{'type': 'DOUBLE'},
                      'OPENWT_LGN':{'type': 'DOUBLE'},
                      'HECTARES':{'type': 'DOUBLE'},
                      'OPNWT_GBKN':{'type': 'DOUBLE'},
                      'LGN_SOURCE':{'type': 'TEXT', 'length': '50'},
                      'LGN_DATE':{'type': 'TEXT', 'length': '50'},
                      'GBKN_DATE':{'type': 'TEXT', 'length': '50'},
                      'GBKN_SOURCE':{'type': 'TEXT', 'length': '50'}}

        #check if output_table exists. if not, create with correct rows
        log.info("Checking table...")
        if not(gp.exists(output_table)):
            try:
                gp.CreateTable(os.path.dirname(output_table), os.path.basename(output_table))
            except Exception, e:
                log.error("Error: creating table " + output_table)
                log.debug(e)
                sys.exit(14)

        #check if output_table has the correct rows
        log.info("Checking fields...")
        for field_name, field_settings in areaFields.items():
            if 'length' in field_settings:
                if not turtlebase.arcgis.is_fieldname(gp, output_table, field_name):
                    gp.AddField(output_table, field_name, field_settings['type'], '#', '#', field_settings['length'])
            else:
                if not turtlebase.arcgis.is_fieldname(gp, output_table, field_name):
                    gp.AddField(output_table, field_name, field_settings['type'])

        #----------------------------------------------------------------------------------------
        #log.info(output_with_area)
        turtlebase.arcgis.write_result_to_output(output_table, gpgident.lower(), output_with_area)

        #----------------------------------------------------------------------------------------
        # 5) Calculate crop areas
        if output_crop_table != "#":
            
            
            log.info("E) Calculate crop areas... ")
            
            #definition of fields
            cropFields = {gpgident: {'type': 'TEXT', 'length': '30'},
                          'GRAS_HA':{'type': 'DOUBLE'},
                          'MAIS_HA':{'type': 'DOUBLE'},
                          'AARDAPL_HA':{'type': 'DOUBLE'},
                          'BIET_HA':{'type': 'DOUBLE'},
                          'GRAAN_HA':{'type': 'DOUBLE'},
                          'OVERIG_HA':{'type': 'DOUBLE'},
                          'NIETAGR_HA':{'type': 'DOUBLE'},
                          'GLAST_HA':{'type': 'DOUBLE'},
                          'BOOMGRD_HA':{'type': 'DOUBLE'},
                          'BOLLEN_HA':{'type': 'DOUBLE'},
                          'LOOFBOS_HA':{'type': 'DOUBLE'},
                          'NLDBOS_HA':{'type': 'DOUBLE'},
                          'NATUUR_HA':{'type': 'DOUBLE'},
                          'BRAAK_HA':{'type': 'DOUBLE'},
                          'GROENTN_HA':{'type': 'DOUBLE'},
                          'BLOEMEN_HA':{'type': 'DOUBLE'}}

            #check if output_table exists. if not, create with correct rows
            log.info("Checking table...")
            if not(gp.exists(output_crop_table)):
                try:
                    gp.CreateTable(os.path.dirname(output_crop_table), os.path.basename(output_crop_table))
                except Exception, e:
                    log.error("Error: creating table " + output_crop_table)
                    log.debug(e)
                    sys.exit(14)
            
            #check if output_table has the correct rows
            log.info("Checking fields...")
            for field_name, field_settings in cropFields.items():
                if 'length' in field_settings:
                    if not turtlebase.arcgis.is_fieldname(gp, output_crop_table, field_name):
                        gp.AddField(output_crop_table, field_name, field_settings['type'], '#', '#', field_settings['length'])
                else:
                    if not turtlebase.arcgis.is_fieldname(gp, output_crop_table, field_name):
                        gp.AddField(output_crop_table, field_name, field_settings['type'])
                        
            write_result_to_output(gp, output_crop_table, gpgident.lower(), output_gewas_areas)
Exemple #10
0
def main():
    try:
        gp = mainutils.create_geoprocessor()
        config = mainutils.read_config(__file__, 'turtle-settings.ini')
        logfile = mainutils.log_filename(config)
        logging_config = LoggingConfig(gp, logfile=logfile)
        mainutils.log_header(__name__)

        #---------------------------------------------------------------------
        # Create workspace
        workspace = config.get('GENERAL', 'location_temp')
        if workspace == "-":
            workspace = tempfile.gettempdir()

        turtlebase.arcgis.delete_old_workspace_gdb(gp, workspace)

        if not os.path.isdir(workspace):
            os.makedirs(workspace)
        workspace_gdb, errorcode = turtlebase.arcgis.create_temp_geodatabase(
                                        gp, workspace)
        if errorcode == 1:
            log.error("failed to create a file geodatabase in %s" % workspace)

        #---------------------------------------------------------------------
        # Input parameters
        """
        nodig voor deze tool:
        """
        if len(sys.argv) == 4:
            user_input = sys.argv[1]
            flip_field = sys.argv[2].lower()
            output_shape = sys.argv[3]
        else:
            log.warning("usage: <user_input> <output_shape>")
            sys.exit(1)

        tempfiles = []
        input_shape = turtlebase.arcgis.get_random_file_name(workspace, '.shp')
        gp.Select_analysis(user_input, input_shape)
        #---------------------------------------------------------------------
        # Check geometry input parameters
        log.info("Check geometry of input parameters")
        geometry_check_list = []

        #log.debug(" - check <input >: %s" % argument1)
        if not turtlebase.arcgis.is_file_of_type(gp, input_shape, 'Polyline'):
            log.error("%s is not a %s feature class!" % (input_shape, 'Polyline'))
            geometry_check_list.append("%s -> (%s)" % (input_shape, 'Polyline'))

        if len(geometry_check_list) > 0:
            log.error("check input: %s" % geometry_check_list)
            sys.exit(2)
        #---------------------------------------------------------------------
        # Check required fields in input data
        ovk_field = config.get('general', 'ovkident').lower()
        missing_fields = []
        check_fields = {input_shape: ['Sum_OPP_LA', 'Sum_OPP_ST',
                        ovk_field, 'from_x', 'from_y', 'to_x', 'to_y', flip_field]}

        for input_fc, fieldnames in check_fields.items():
            for fieldname in fieldnames:
                if not turtlebase.arcgis.is_fieldname(
                        gp, input_fc, fieldname):
                    errormsg = "fieldname %s not available in %s" % (
                                    fieldname, input_fc)
                    log.error(errormsg)
                    missing_fields.append(errormsg)

        if len(missing_fields) > 0:
            log.error("missing fields in input data: %s" % missing_fields)
            sys.exit(2)
        #---------------------------------------------------------------------
        #create output:
        fields_to_add = [(ovk_field, 'TEXT'),
                         ('incoming', 'SHORT'),
                         ('examined', 'SHORT'),
                         ('terminal', 'SHORT'),
                         ('som_sted', 'DOUBLE'),
                         ('som_land', 'DOUBLE'),
                         ('som_totaal', 'DOUBLE'),
                         ('bottleneck', 'SHORT'),
                         (flip_field, 'SHORT')]
        gp.select_analysis(input_shape, output_shape)

        new_feat = {}
        new_geometry = {}
        log.info("Inlezen geometrie en omdraaien van de geometrie")

        fieldnames_dict = nens.gp.get_table_def(gp, input_shape)
        log.debug(fieldnames_dict)
        desc = gp.describe(input_shape)
        count = 0
        rows = gp.SearchCursor(input_shape)
        row = rows.Next()
        while row:

            flip_boolean = row.getValue(flip_field)

            if flip_boolean == 1:
                count += 1
                #read features
                feat = row.getValue(desc.ShapeFieldName)
                ovkident = row.getValue(ovk_field)
                new_feat = flip_geometry(gp, feat, ovkident, new_feat)
                ##new_feat = feat

                #store geometry information in dictionary
                if ovkident not in new_geometry:
                    new_geometry[ovkident] = {}
                #store all information from the attribute table
                for column in fields_to_add:
                    column = column[0]

                    #columns with from en to for x and y need to be switched as well
                    if column == 'from_x':
                        lookup_column = 'to_x'
                    elif column == 'from_y':
                        lookup_column = 'to_y'
                    elif column == 'to_y':
                        lookup_column = 'from_y'
                    elif column == 'to_x':
                        lookup_column = 'from_x'
                    else:
                        # no switch needed
                        lookup_column = column

                    if column != 'opm':
                        if lookup_column in fieldnames_dict:
                            update_value = row.getValue(lookup_column)
                            try:
                                float_value = float(update_value)
                                new_geometry[ovkident][column] = float_value
                            except:
                                log.debug("geen float")
                                new_geometry[ovkident][column] = row.getValue(lookup_column)
                            log.debug(new_geometry[ovkident][column])
                #waterlijn wordt opgeslagen in dictionary
                if column == 'opm':
                    new_geometry[ovkident][column] = "Lijn is omgedraaid"
                log.info("Opslaan van waterlijn: " + str(ovkident))
            row = rows.Next()
        del row, rows
        #remove the lines that are going to be flipped

        removed_lines = turtlebase.arcgis.get_random_file_name(workspace_gdb)
        #alleen als er inderdaad lijnen gedraaid worden moet de tempfile aangemaakt worden.
        gp.select_analysis(input_shape, removed_lines)

        #first remove lines that are going to be duplicate in the end result. lines are
        # remove from a copy of the input file.
        row = gp.UpdateCursor(removed_lines)
        log.info("Verwijder dubbele rijen")
        for item in nens.gp.gp_iterator(row):
            if item.getValue(flip_field) == 1:
                row.DeleteRow(item)

        temp_shape = turtlebase.arcgis.get_random_file_name(workspace_gdb)
        tempfiles.append(temp_shape)

        #creates new lines in workspace with same name as output_shape
        count = create_line_from_dict(gp, workspace_gdb, new_feat, fields_to_add, new_geometry, temp_shape)
        
        if count == 0:
            log.warning("Er zijn geen lijnen omgedraaid")
            log.warning("Door de gebruiker is in de kolom " + str(flip_field) + " geen 1 ingevuld")
        else:
            tempfiles.append(removed_lines)

        #merge new lines with output
        gp.Merge_management(temp_shape + ";" + removed_lines, output_shape)

        #---------------------------------------------------------------------
        # Delete temporary workspace geodatabase & ascii files
        try:
            log.debug("delete temporary workspace: %s" % workspace_gdb)
            gp.delete(workspace_gdb)
            turtlebase.arcgis.remove_tempfiles(gp, log, tempfiles)

            log.info("workspace deleted")
        except:
            log.debug("failed to delete %s" % workspace_gdb)

        mainutils.log_footer()
    except:
        log.error(traceback.format_exc())
        sys.exit(1)

    finally:
        logging_config.cleanup()
        del gp
def main():
    try:
        gp = mainutils.create_geoprocessor()
        config = mainutils.read_config(__file__, 'turtle-settings.ini')
        logfile = mainutils.log_filename(config)
        logging_config = LoggingConfig(gp, logfile=logfile)
        mainutils.log_header(__name__)

        #---------------------------------------------------------------------
        # Create workspace
        workspace = config.get('GENERAL', 'location_temp')
        if workspace == "-":
            import tempfile
            workspace = tempfile.gettempdir()
        log.info("workspace: %s" % workspace)

        turtlebase.arcgis.delete_old_workspace_gdb(gp, workspace)

        if not os.path.isdir(workspace):
            os.makedirs(workspace)
        workspace_gdb, errorcode = turtlebase.arcgis.create_temp_geodatabase(
                                                                gp, workspace)
        if errorcode == 1:
            log.error("failed to create a file geodatabase in %s" % workspace)

        #---------------------------------------------------------------------
        # Input parameters
        """
        nodig voor deze tool:
        """
        if len(sys.argv) == 5:
            input_level_area_fc = sys.argv[1]
            input_level_area_table = sys.argv[2]
            input_ahn_raster = sys.argv[3]
            output_surface_table = sys.argv[4]
        else:
            log.error("usage: <input_level_area_fc> <input_level_area_table> \
                    <input_ahn_raster> <output_surface_table>")
            sys.exit(1)

        #---------------------------------------------------------------------
        # Check geometry input parameters
        cellsize = gp.describe(input_ahn_raster).MeanCellHeight

        log.info("Check geometry of input parameters")
        geometry_check_list = []

        log.debug(" - check voronoi polygon: %s" % input_level_area_fc)
        if gp.describe(input_level_area_fc).ShapeType != 'Polygon':
            log.error("%s is not a polygon feature class!",
                      input_level_area_fc)
            geometry_check_list.append(input_level_area_fc + " -> (Polygon)")

        if gp.describe(input_ahn_raster).PixelType[0] not in ['U', 'S']:
            log.error("Input AHN is a floating point raster, \
                    for this script an integer is necessary")
            geometry_check_list.append(input_ahn_raster + " -> (Integer)")

        if len(geometry_check_list) > 0:
            log.error("check input: %s" % geometry_check_list)
            sys.exit(2)
        else:
            print "A"
        #---------------------------------------------------------------------
        # Check required fields in input data
        log.info("Check required fields in input data")

        missing_fields = []

        # <check required fields from input data,
        # append them to list if missing>"
        if not turtlebase.arcgis.is_fieldname(
                            gp, input_level_area_fc, config.get(
                            'maaiveldkarakteristiek',
                            'input_peilgebied_ident')):
            log.debug(" - missing: %s in %s" % (
                    config.get('maaiveldkarakteristiek',
                               'input_peilgebied_ident'), input_level_area_fc))
            missing_fields.append("%s: %s" % (
                    input_level_area_fc, config.get('maaiveldkarakteristiek',
                                                    'input_peilgebied_ident')))
        if not turtlebase.arcgis.is_fieldname(
                            gp, input_level_area_table, config.get(
                            'maaiveldkarakteristiek',
                            'input_peilgebied_ident')):
            log.debug(" - missing: %s in %s" % (
                    config.get('maaiveldkarakteristiek',
                               'input_peilgebied_ident'),
                    input_level_area_table))
            missing_fields.append("%s: %s" % (
                            input_level_area_table, config.get(
                                'maaiveldkarakteristiek',
                                'input_peilgebied_ident')))

        if len(missing_fields) > 0:
            log.error("missing fields in input data: %s" % missing_fields)
            sys.exit(2)
        #---------------------------------------------------------------------
        # Environments
        log.info("Set environments")
        temp_level_area = os.path.join(workspace_gdb, "peilgebieden")
        gp.select_analysis(input_level_area_fc, temp_level_area)
        # use extent from level area
        gp.extent = gp.describe(temp_level_area).extent

        #---------------------------------------------------------------------
        # create ahn ascii
        log.info("Create ascii from ahn")

        ahn_ascii = turtlebase.arcgis.get_random_file_name(workspace, ".asc")
        log.debug("ahn ascii: %s" % ahn_ascii)
        gp.RasterToASCII_conversion(input_ahn_raster, ahn_ascii)

        #---------------------------------------------------------------------
        # Add ID Int to level area
        log.info("Create level area ascii")
        area_id_dict = add_integer_ident(gp, temp_level_area, config.get(
                    'maaiveldkarakteristiek', 'id_int').lower(),
                                         config.get('maaiveldkarakteristiek',
                                                    'input_peilgebied_ident'))

        out_raster_dataset = turtlebase.arcgis.get_random_file_name(
                                                        workspace_gdb)
        gp.FeatureToRaster_conversion(temp_level_area, config.get(
            'maaiveldkarakteristiek', 'id_int'), out_raster_dataset, cellsize)

        id_int_ascii = turtlebase.arcgis.get_random_file_name(
                            workspace, ".asc")
        log.debug("id_int_ascii: %s" % id_int_ascii)
        gp.RasterToASCII_conversion(out_raster_dataset, id_int_ascii)

        #---------------------------------------------------------------------
        log.info("Read targetlevel table")
        area_level_dict = nens.gp.get_table(
                            gp, input_level_area_table, primary_key=config.get(
                                'maaiveldkarakteristiek',
                                'input_peilgebied_ident').lower())
        target_level_dict = {}

        for k, v in area_level_dict.items():
            if k in area_id_dict:
                id_int = area_id_dict[k][config.get('maaiveldkarakteristiek',
                                                    'id_int').lower()]
                target_level_dict[id_int] = {
                            'targetlevel': v[config.get(
                            'maaiveldkarakteristiek',
                            'field_streefpeil').lower()],
                            'gpgident': k,
                                             }
        #---------------------------------------------------------------------
        log.info("create S-Curve")
        mv_procent_str = config.get('maaiveldkarakteristiek', 'mv_procent')
        field_range = mv_procent_str.split(', ')
        #scurve_dict = turtlebase.spatial.create_scurve(ahn_ascii,
        # id_int_ascii, target_level_dict, field_range)
        scurve_dict = turtlebase.spatial.surface_level_statistics(
                            ahn_ascii, id_int_ascii,
                            target_level_dict, field_range)
        #---------------------------------------------------------------------
        log.info("Create output table")
        create_output_table(gp, output_surface_table, config.get(
            'maaiveldkarakteristiek', 'input_peilgebied_ident'), field_range)
        #---------------------------------------------------------------------
        # Add metadata
        import time
        date_time_str = time.strftime("%d %B %Y %H:%M:%S")
        source = input_ahn_raster

        for k, v in scurve_dict.items():
            scurve_dict[k]['date_time'] = date_time_str
            scurve_dict[k]['source'] = source

        #---------------------------------------------------------------------
        # Write results to output table
        log.info("Write results to output table")
        turtlebase.arcgis.write_result_to_output(
                            output_surface_table, config.get(
                                'maaiveldkarakteristiek',
                                'input_peilgebied_ident').lower(), scurve_dict)

        #---------------------------------------------------------------------
        # Delete temporary workspace geodatabase & ascii files
        try:
            log.debug("delete temporary workspace: %s" % workspace_gdb)
            #gp.delete(workspace_gdb)

            log.info("workspace deleted")
        except:
            log.warning("failed to delete %s" % workspace_gdb)

        tempfiles = os.listdir(workspace)
        for tempfile in tempfiles:
            if tempfile.endswith('.asc'):
                try:
                    os.remove(os.path.join(workspace, tempfile))
                except Exception, e:
                    log.debug(e)

        mainutils.log_footer()
def main():
    try:
        gp = mainutils.create_geoprocessor()
        config = mainutils.read_config(__file__, 'turtle-settings.ini')
        logfile = mainutils.log_filename(config)
        logging_config = LoggingConfig(gp, logfile=logfile)
        mainutils.log_header(__name__)

        #---------------------------------------------------------------------
        # Create workspace
        workspace = config.get('GENERAL', 'location_temp')
        if workspace == "-":
            workspace = tempfile.gettempdir()

        turtlebase.arcgis.delete_old_workspace_gdb(gp, workspace)

        if not os.path.isdir(workspace):
            os.makedirs(workspace)
        workspace_gdb, errorcode = turtlebase.arcgis.create_temp_geodatabase(
                                        gp, workspace)
        if errorcode == 1:
                log.error("failed to create a file geodatabase in %s" % workspace)
        # Input parameters
        if len(sys.argv) == 11:
            # input parameters
            input_voronoi_polygon = sys.argv[1]
            input_rrcf_waterlevel = sys.argv[2]
            input_ahn_raster = sys.argv[3]
            input_lgn_raster = sys.argv[4]
            input_lgn_conversion = sys.argv[5]

            # output parameters
            output_result_table = sys.argv[6]

            # optional output
            output_inundation = sys.argv[7]
            if output_inundation == "#":
                output_inundation = os.path.join(workspace_gdb, "inun_nbw")

            if len(os.path.basename(output_inundation)) > 13:
                log.error("filename raster output (%s) cannot contain more than 13 characters" % os.path.basename(output_inundation))
                sys.exit(1)

            output_waterdamage = sys.argv[8]
            if output_waterdamage == "#":
                output_waterdamage = os.path.join(workspace_gdb, "damage_nbw")

            if len(os.path.basename(output_waterdamage)) > 13:
                log.error("filename raster output (%s) cannot contain more than 13 characters" % os.path.basename(output_waterdamage))
                sys.exit(1)

            output_inundation_total = sys.argv[9]
            if len(os.path.basename(output_inundation_total)) > 13:
                log.error("filename raster output (%s) cannot contain more than 13 characters" % os.path.basename(output_inundation_total))
                sys.exit(1)

            output_waterdamage_total = sys.argv[10]
            if len(os.path.basename(output_waterdamage_total)) > 13:
                log.error("filename raster output (%s) cannot contain more than 13 characters" % os.path.basename(output_waterdamage_total))
                sys.exit(1)

        else:
            log.error("usage: <input_voronoi_polygon> <input_rrcf_waterlevel> <input_ahn_raster> \
            <input_lgn_raster> <input_lgn_conversion> <output_result_table> \
            <output_inundation> <output_waterdamage> <output inundation total> <output waterdamage total>")
            sys.exit(1)
        #----------------------------------------------------------------------------------------
        temp_voronoi = os.path.join(workspace_gdb, "voronoi")
        gp.select_analysis(input_voronoi_polygon, temp_voronoi)

        # Check geometry input parameters
        cellsize = gp.describe(input_ahn_raster).MeanCellHeight

        log.info("Check geometry of input parameters")
        geometry_check_list = []

        if input_lgn_conversion != "#":
            if not gp.exists(input_lgn_conversion):
                errormsg = "%s does not exist" % input_lgn_conversion
                log.error(errormsg)
                geometry_check_list.append(errormsg)

        log.debug(" - check voronoi polygon: %s" % temp_voronoi)
        if gp.describe(temp_voronoi).ShapeType != 'Polygon':
            log.error("Input voronoi is not a polygon feature class!")
            geometry_check_list.append(temp_voronoi + " -> (Polygon)")

        log.debug(" - check ahn raster %s" % input_ahn_raster)
        if gp.describe(input_ahn_raster).DataType != 'RasterDataset':
            log.error("Input AHN is not a raster dataset")
            sys.exit(1)

        if gp.describe(input_ahn_raster).PixelType[0] not in ['U', 'S']:
            log.error("Input AHN is a floating point raster, for this script an integer is nessecary")
            geometry_check_list.append(input_ahn_raster + " -> (Integer)")

        log.debug(" - check lgn raster %s" % input_lgn_raster)
        if gp.describe(input_lgn_raster).DataType != 'RasterDataset':
            log.error("Input LGN is not a raster dataset")
            sys.exit(1)

        if gp.describe(input_lgn_raster).PixelType[0] not in ['U', 'S']:
            log.error("Input LGN is a floating point raster, for this script an integer is nessecary")
            geometry_check_list.append(input_lgn_raster + " -> (Integer)")

        if gp.describe(input_lgn_raster).MeanCellHeight != float(cellsize):
            log.error("Cell size of LGN is %s, must be %s" % (
                                    gp.describe(input_lgn_raster).MeanCellHeight, cellsize))
            geometry_check_list.append(input_lgn_raster + " -> (Cellsize %s)" % cellsize)

        if len(geometry_check_list) > 0:
            log.error("check input: %s" % geometry_check_list)
            sys.exit(2)
        #----------------------------------------------------------------------------------------
        # Check required fields in database
        log.info("Check required fields in input data")
        # create return period list
        return_periods = config.get('naverwerking_rrcf', 'herhalingstijden').split(", ")
        log.debug(" - return periods: %s" % return_periods)

        missing_fields = []

        for return_period in return_periods:
            if not turtlebase.arcgis.is_fieldname(gp, input_rrcf_waterlevel, "WS_%s" % return_period):
                log.debug(" - missing: %s in %s" % ("WS_%s" % return_period, input_rrcf_waterlevel))
                missing_fields.append("%s: %s" % (input_rrcf_waterlevel, "WS_%s" % return_period))

        #<check required fields from input data, append them to list if missing>"
        field_streefpeil = config.get('naverwerking_rrcf', 'field_streefpeil')
        check_fields = {input_rrcf_waterlevel: [config.get('naverwerking_rrcf', 'calculation_point_ident'), field_streefpeil]}
        if input_lgn_conversion != "#":
            check_fields[input_lgn_conversion] = [config.get('naverwerking_rrcf', 'lgn_conv_ident'),
                                                    config.get('naverwerking_rrcf', 'input_field_k5')]
        for input_fc, fieldnames in check_fields.items():
            for fieldname in fieldnames:
                if not turtlebase.arcgis.is_fieldname(gp, input_fc, fieldname):
                    errormsg = "fieldname %s not available in %s" % (fieldname, input_fc)
                    log.error(errormsg)
                    missing_fields.append(errormsg)

        if len(missing_fields) > 0:
            log.error("missing fields in input data: %s" % missing_fields)
            sys.exit(2)
        #---------------------------------------------------------------------
        # Environments
        log.info("Set environments")
        gp.extent = gp.describe(temp_voronoi).extent  # use extent from LGN

        #---------------------------------------------------------------------
        # read waterlevel table as a dictionary
        log.info("Read waterlevel table")
        waterlevel_dict = nens.gp.get_table(gp, input_rrcf_waterlevel, primary_key=config.get('naverwerking_rrcf', 'calculation_point_ident').lower())
        log.debug(waterlevel_dict)

        # Add fields to output
        for return_period in return_periods:
            if not turtlebase.arcgis.is_fieldname(gp, temp_voronoi, "WS_%s" % return_period):
                log.info(" - add field WS_%s" % return_period)
                gp.addfield(temp_voronoi, "WS_%s" % return_period, "double")

        if not turtlebase.arcgis.is_fieldname(gp, temp_voronoi, field_streefpeil):
                log.info(" - add field %s" % field_streefpeil)
                gp.addfield(temp_voronoi, field_streefpeil, "double")

        # copy waterlevel to voronoi polygons
        rows = gp.UpdateCursor(temp_voronoi)
        for row in nens.gp.gp_iterator(rows):
            row_id = row.GetValue(config.get('naverwerking_rrcf', 'calculation_point_ident'))
            if row_id in waterlevel_dict:
                log.debug(waterlevel_dict[row_id])
                for return_period in return_periods:
                    row.SetValue("WS_%s" % return_period, waterlevel_dict[row_id]['ws_%s' % return_period])
                    row.SetValue(field_streefpeil,
                                 waterlevel_dict[row_id][field_streefpeil.lower()])
                rows.UpdateRow(row)

        #---------------------------------------------------------------------
        # Create waterlevel rasters
        log.info("Create rasters for waterlevels")
        for return_period in return_periods:
            log.info(" - create raster for ws_%s" % return_period)
            out_raster_dataset = workspace_gdb + "/ws_%s" % return_period
            gp.FeatureToRaster_conversion(temp_voronoi, "WS_%s" % return_period, out_raster_dataset, cellsize)

        #---------------------------------------------------------------------
        # Create target level raster
        log.info("Create targetlevel raster")
        out_raster_targetlevel = os.path.join(workspace_gdb, "targetlv")
        gp.FeatureToRaster_conversion(temp_voronoi, field_streefpeil, out_raster_targetlevel, cellsize)

        #---------------------------------------------------------------------
        # Create freeboard raster
        log.info("Create freeboard raster")

        # create ahn ascii
        ahn_ascii = os.path.join(workspace, "ahn.asc")
        log.debug("ahn ascii: %s" % ahn_ascii)
        gp.RasterToASCII_conversion(input_ahn_raster, ahn_ascii)

        targetlevel_ascii = os.path.join(workspace, "targetlvl.asc")
        log.debug("targetlevel ascii: %s" % targetlevel_ascii)
        gp.RasterToASCII_conversion(out_raster_targetlevel, targetlevel_ascii)

        freeboard_ascii = os.path.join(workspace, "freeboard.asc")
        turtlebase.spatial.create_freeboard_raster(ahn_ascii, targetlevel_ascii, freeboard_ascii)

        #----------------------------------------------------------------------------------------
        # Create K5 LGN
        log.info("Reclass LGN to K5 raster")
        lgn_ascii = os.path.join(workspace, "lgn.asc")
        lgn_k5_ascii = os.path.join(workspace, "lgn_k5.asc")

        gp.RasterToASCII_conversion(input_lgn_raster, lgn_ascii)

        if input_lgn_conversion != '#':
            reclass_dict = nens.gp.get_table(gp, input_lgn_conversion,
                                             primary_key=config.get('naverwerking_rrcf', 'lgn_conv_ident').lower())
            turtlebase.spatial.reclass_lgn_k5(lgn_ascii, lgn_k5_ascii, reclass_dict)
        else:
            turtlebase.spatial.reclass_lgn_k5(lgn_ascii, lgn_k5_ascii)

        #----------------------------------------------------------------------------------------
        # Create inundation raster
        # als ws_ > ahn, dan inundatie
        inundation_raster_list = []
        inundation_total_raster_list = []

        log.info("Create inundation rasters")
        # inundatie stedelijk
        return_period_urban = config.get('naverwerking_rrcf', 'herhalingstijd_inundatie_stedelijk')
        if config.get('naverwerking_rrcf', 'percentage_inundatie_stedelijk') != "-":
            log.info(" - create inundation urban")
            waterlevel = "%s/ws_%s" % (workspace_gdb, return_period_urban)
            if gp.exists(waterlevel):
                inundation_urban = os.path.join(workspace, "inun_urban.asc")
                turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel, 1,
                                                            return_period_urban, inundation_urban, workspace, use_lgn=True)
                inundation_raster_list.append(inundation_urban)
                if output_inundation_total != '#':
                    # Inundation without lgn
                    inundation_total_urban = os.path.join(workspace, "inun_total_urban.asc")
                    turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel,
                                                               1, return_period_urban, inundation_total_urban, workspace, use_lgn=False)
                    inundation_total_raster_list.append(inundation_total_urban)
            else:
                log.error("%s does not exists! check ini-file and tempfolder" % waterlevel)

        # inundatie hoogwaardige landbouw
        return_period_agriculture = config.get('naverwerking_rrcf', 'herhalingstijd_inundatie_hoogwaardig')
        if config.get('naverwerking_rrcf', 'percentage_inundatie_hoogwaardig') != "-":
            log.info(" - create inundation agriculture")
            waterlevel = "%s/ws_%s" % (workspace_gdb, return_period_agriculture)
            if gp.exists(waterlevel):
                # Inundation with lgn
                inundation_agriculture = os.path.join(workspace, "inun_agri.asc")
                turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel,
                                                           2, return_period_agriculture, inundation_agriculture, workspace, use_lgn=True)
                inundation_raster_list.append(inundation_agriculture)
                if output_inundation_total != '#':
                    # Inundation without lgn
                    inundation_total_agriculture = os.path.join(workspace, "inun_total_agri.asc")
                    turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel,
                                                               2, return_period_agriculture, inundation_total_agriculture, workspace, use_lgn=False)
                    inundation_total_raster_list.append(inundation_total_agriculture)
            else:
                log.error("%s does not exists! check ini-file and tempfolder" % waterlevel)

        # inundatie akkerbouw
        return_period_rural = config.get('naverwerking_rrcf', 'herhalingstijd_inundatie_akker')
        if config.get('naverwerking_rrcf', 'percentage_inundatie_akker') != "-":
            log.info(" - create inundation rural")
            waterlevel = "%s/ws_%s" % (workspace_gdb, return_period_rural)
            if gp.exists(waterlevel):
                inundation_rural = os.path.join(workspace, "inun_rural.asc")
                turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel,
                                                           3, return_period_rural, inundation_rural, workspace, use_lgn=True)
                inundation_raster_list.append(inundation_rural)
                if output_inundation_total != '#':
                    # Inundation without lgn
                    inundation_total_rural = os.path.join(workspace, "inun_total_rural.asc")
                    turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel,
                                                               3, return_period_rural, inundation_total_rural, workspace, use_lgn=False)
                    inundation_total_raster_list.append(inundation_total_rural)
            else:
                log.error("%s does not exists! check ini-file and tempfolder" % waterlevel)

        # inundatie grasland
        return_period_grass = config.get('naverwerking_rrcf', 'herhalingstijd_inundatie_grasland')
        if config.get('naverwerking_rrcf', 'percentage_inundatie_grasland') != "-":
            log.info(" - create inundation grass")
            waterlevel = "%s/ws_%s" % (workspace_gdb, return_period_grass)
            if gp.exists(waterlevel):
                log.debug("waterlevel grasland = %s" % waterlevel)
                inundation_grass = os.path.join(workspace, "inun_grass.asc")
                turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel,
                                                           4, return_period_grass, inundation_grass, workspace, use_lgn=True)
                inundation_raster_list.append(inundation_grass)
                if output_inundation_total != '#':
                    # Inundation without lgn
                    inundation_total_grass = os.path.join(workspace, "inun_total_grass.asc")
                    turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel,
                                                               4, return_period_grass, inundation_total_grass, workspace, use_lgn=False)
                    inundation_total_raster_list.append(inundation_total_grass)
            else:
                log.error("%s does not exists! check ini-file and tempfolder" % waterlevel)

        if len(inundation_raster_list) > 1:
            log.info("Merge inundation rasters")
            output_inundation_exists = turtlebase.spatial.merge_ascii(inundation_raster_list, output_inundation, workspace)
        else:
            log.error("there are no inundation rasters available")

        if len(inundation_total_raster_list) > 1:
            log.info("Merge inundation total rasters")
            turtlebase.spatial.merge_ascii(inundation_total_raster_list, output_inundation_total, workspace)

        #----------------------------------------------------------------------------------------
        # Create waterdamage raster
        # als ws_ > freeboard, dan overlast
        damage_raster_list = []
        damage_total_raster_list = []

        log.info("Create waterdamage rasters")
        # overlast stedelijk
        return_period_urban_damage = config.get('naverwerking_rrcf', 'herhalingstijd_overlast_stedelijk')
        if config.get('naverwerking_rrcf', 'percentage_overlast_stedelijk') != "-":
            log.info(" - create waterdamage urban")
            waterlevel = "%s/ws_%s" % (workspace_gdb, return_period_urban_damage)
            if gp.exists(waterlevel):
                damage_urban = os.path.join(workspace, "damage_urban.asc")
                turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, freeboard_ascii, waterlevel,
                                                           1, return_period_urban_damage, damage_urban, workspace, use_lgn=True)
                damage_raster_list.append(damage_urban)
                if output_waterdamage_total != '#':
                    # Waterdamage without lgn
                    damage_total_urban = os.path.join(workspace, "damage_total_urban.asc")
                    turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel,
                                                               1, return_period_urban_damage, damage_total_urban, workspace, use_lgn=False)
                    damage_total_raster_list.append(damage_total_urban)
            else:
                log.error("%s does not exists! check ini-file and tempfolder" % waterlevel)

        # overlast hoogwaardig
        return_period_agriculture_damage = config.get('naverwerking_rrcf', 'herhalingstijd_overlast_hoogwaardig')
        if config.get('naverwerking_rrcf', 'percentage_overlast_hoogwaardig') != "-":
            log.info(" - create waterdamage agriculture")
            waterlevel = "%s/ws_%s" % (workspace_gdb, return_period_agriculture_damage)
            if gp.exists(waterlevel):
                damage_agriculture = workspace + "/damage_agri_%s.asc" % return_period_agriculture_damage
                turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, freeboard_ascii, waterlevel,
                                                           2, return_period_agriculture_damage, damage_agriculture, workspace, use_lgn=True)
                damage_raster_list.append(damage_agriculture)
                if output_waterdamage_total != '#':
                    # Waterdamage without lgn
                    damage_total_agriculture = os.path.join(workspace, "damage_total_agri.asc")
                    turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel,
                                                               1, return_period_agriculture_damage, damage_total_agriculture, workspace, use_lgn=False)
                    damage_total_raster_list.append(damage_total_agriculture)
            else:
                log.error("%s does not exists! check ini-file and tempfolder" % waterlevel)

        # overlast akker
        return_period_rural_damage = config.get('naverwerking_rrcf', 'herhalingstijd_overlast_akker')
        if config.get('naverwerking_rrcf', 'percentage_overlast_akker') != "-":
            log.info(" - create waterdamage rural")
            waterlevel = "%s/ws_%s" % (workspace_gdb, return_period_rural_damage)
            if gp.exists(waterlevel):
                damage_rural = workspace + "/damage_rural_%s.asc" % return_period_rural_damage
                turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, freeboard_ascii, waterlevel,
                                                           3, return_period_rural_damage, damage_rural, workspace, use_lgn=True)
                damage_raster_list.append(damage_rural)
                if output_waterdamage_total != '#':
                    # Waterdamage without lgn
                    damage_total_rural = os.path.join(workspace_gdb, "damage_total_rural.asc")
                    turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel,
                                                               1, return_period_rural_damage, damage_total_rural, workspace, use_lgn=False)
                    damage_total_raster_list.append(damage_total_rural)
            else:
                log.error("%s does not exists! check ini-file and tempfolder" % waterlevel)

        # overlast grasland
        return_period_grass_damage = config.get('naverwerking_rrcf', 'herhalingstijd_overlast_grasland')
        if config.get('naverwerking_rrcf', 'percentage_overlast_grasland') != "-":
            log.info(" - create waterdamage grass")
            waterlevel = "%s/ws_%s" % (workspace_gdb, return_period_grass_damage)
            if gp.exists(waterlevel):
                damage_grass = os.path.join(workspace_gdb, "damage_grass.asc")
                turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, freeboard_ascii, waterlevel,
                                                           4, return_period_grass_damage, damage_grass, workspace, use_lgn=True)
                damage_raster_list.append(damage_grass)
                if output_waterdamage_total != '#':
                    # Waterdamage without lgn
                    damage_total_grass = os.path.join(workspace_gdb, "damage_total_grass.asc")
                    turtlebase.spatial.create_inundation_raster(lgn_k5_ascii, ahn_ascii, waterlevel,
                                                               1, return_period_grass_damage, damage_total_grass, workspace, use_lgn=False)
                    damage_total_raster_list.append(damage_total_grass)
            else:
                log.error("%s does not exists! check ini-file and tempfolder" % waterlevel)

        # Merge waterdamage rasters
        if len(damage_raster_list) > 1:
            log.info("Merge waterdamage rasters")
            output_waterdamage_exists = turtlebase.spatial.merge_ascii(damage_raster_list, output_waterdamage, workspace)
        else:
            log.error("there are no waterdamage rasters available")

        if len(damage_total_raster_list) > 1:
            log.info("Merge waterdamage total rasters")
            turtlebase.spatial.merge_ascii(damage_total_raster_list, output_waterdamage_total, workspace)
        #----------------------------------------------------------------------------------------
        # calculate percentage inundation
        """
        input:
        - inundatie / overlast (raster dataset)
        - input_voronoi_polygon (met GPGIDENT) (feature class)
        - lgn_k5 (raster dataset)
        """
        gpgident_field = config.get('General', 'gpgident')
        # dissolve voronoi based on gpgident

        log.debug("dissolve voronoi polygons, based on gpgident")
        temp_fc_gpgident = os.path.join(workspace_gdb, "temp_fc_gpgident")
        gp.Dissolve_management(temp_voronoi, temp_fc_gpgident, gpgident_field)

        # Calculate area total, gpgident
        if not turtlebase.arcgis.is_fieldname(gp, temp_fc_gpgident, "area_total"):
            gp.addfield(temp_fc_gpgident, "area_total", "Double")
        turtlebase.arcgis.calculate_area(gp, temp_fc_gpgident, "area_total")

        gpgident_dict = nens.gp.get_table(gp, temp_fc_gpgident, primary_key=gpgident_field.lower())
        log.debug("gpgident_dict: %s" % gpgident_dict)

        # create feature class from lgn k5 ascii
        output_reclass_lgn = os.path.join(workspace_gdb, "reclass_lgn")
        gp.ASCIIToRaster_conversion(lgn_k5_ascii, output_reclass_lgn)
        temp_fc_lgn = os.path.join(workspace_gdb, "fc_lgn")
        gp.RasterToPolygon_conversion(output_reclass_lgn, temp_fc_lgn, "NO_SIMPLIFY")

        # union lgn with gpg-areas
        temp_fc_union_lgn = os.path.join(workspace_gdb, "fc_union_lgn")
        gp.Union_analysis(temp_fc_gpgident + ";" + temp_fc_lgn, temp_fc_union_lgn)
        dissolve_lyr = turtlebase.arcgis.get_random_layer_name()
        gp.MakeFeatureLayer_management(temp_fc_union_lgn, dissolve_lyr, "%s <> ''" % gpgident_field)
        temp_fc_dissolve_lgn = os.path.join(workspace_gdb, "dissolve_lgn")
        if turtlebase.arcgis.is_fieldname(gp, dissolve_lyr, "GRIDCODE"):
            gp.Dissolve_management(dissolve_lyr, temp_fc_dissolve_lgn, "%s; GRIDCODE" % gpgident_field)
            gridcode = "gridcode"
        elif turtlebase.arcgis.is_fieldname(gp, dissolve_lyr, "grid_code"):
            gp.Dissolve_management(dissolve_lyr, temp_fc_dissolve_lgn, "%s; grid_code" % gpgident_field)
            gridcode = "grid_code"
        else:
            log.error("no field GRIDCODE or grid_code available in %s" % dissolve_lyr)
            sys.exit(2)

        # Calculate area lgn
        if not turtlebase.arcgis.is_fieldname(gp, temp_fc_dissolve_lgn, "area_lgn"):
            gp.addfield(temp_fc_dissolve_lgn, "area_lgn", "Double")
        turtlebase.arcgis.calculate_area(gp, temp_fc_dissolve_lgn, "area_lgn")

        lgn_dict = nens.gp.get_table(gp, temp_fc_dissolve_lgn)
        translate_lgn_dict = translate_dict(lgn_dict, gridcode, 'area_lgn')
        log.debug("translate_lgn_dict: %s" % translate_lgn_dict)

        # Create feature class from inundation_grid
        """ values: 10, 25, 50, 100"""
        if output_inundation_exists == 0:
            temp_fc_inundation = os.path.join(workspace_gdb, "inundation")
            log.info(output_inundation)
            gp.RasterToPolygon_conversion(output_inundation, temp_fc_inundation, "NO_SIMPLIFY")
            temp_fc_union_inundation = os.path.join(workspace_gdb, "union_inun")
            gp.Union_analysis(temp_fc_dissolve_lgn + ";" + temp_fc_inundation, temp_fc_union_inundation)
            dissolve_inundation_lyr = turtlebase.arcgis.get_random_layer_name()
            if turtlebase.arcgis.is_fieldname(gp, temp_fc_union_inundation, "GRIDCODE_1"):
                gp.MakeFeatureLayer_management(temp_fc_union_inundation, dissolve_inundation_lyr, "GRIDCODE_1 > 0")
                gridcode_1 = "gridcode_1"
            elif turtlebase.arcgis.is_fieldname(gp, temp_fc_union_inundation, "GRID_CODE1"):
                gp.MakeFeatureLayer_management(temp_fc_union_inundation, dissolve_inundation_lyr, "GRID_CODE1 > 0")
                gridcode_1 = "grid_code1"
            elif turtlebase.arcgis.is_fieldname(gp, temp_fc_union_inundation, "GRID_CODE_1"):
                gp.MakeFeatureLayer_management(temp_fc_union_inundation, dissolve_inundation_lyr, "GRID_CODE_1 > 0")
                gridcode_1 = "grid_code_1"
            else:
                log.error("No field available named gridcode_1 or grid_code1")
                log.warning(nens.gp.get_table_def(gp, temp_fc_union_inundation))
                sys.exit(1)
            temp_fc_dissolve_inundation = os.path.join(workspace_gdb, "dissolve_inun")
            dissolve_string = "%s;%s;%s" % (gpgident_field.upper(), gridcode, gridcode_1)
            log.debug(" - dissolve layer: %s" % dissolve_inundation_lyr)
            gp.Dissolve_management(dissolve_inundation_lyr, temp_fc_dissolve_inundation, dissolve_string)

            # Calculate area inundation
            if not turtlebase.arcgis.is_fieldname(gp, temp_fc_dissolve_inundation, "area_inund"):
                gp.addfield(temp_fc_dissolve_inundation, "area_inun", "Double")
            turtlebase.arcgis.calculate_area(gp, temp_fc_dissolve_inundation, "area_inun")

            inundation_dict = nens.gp.get_table(gp, temp_fc_dissolve_inundation)
            translate_inundation_dict = translate_dict(inundation_dict, gridcode_1, 'area_inun')
            log.debug("translate_inundation_dict: %s" % translate_inundation_dict)
        else:
            translate_inundation_dict = {}

        # Create feature class from waterdamage grid
        """ values: 10, 15, 25"""
        if output_waterdamage_exists == 0:
            try:
                temp_fc_waterdamage = os.path.join(workspace_gdb, "damage")
                gp.RasterToPolygon_conversion(output_waterdamage, temp_fc_waterdamage, "NO_SIMPLIFY")
                waterdamage = True
            except:
                log.warning("waterdamage raster is empty")
                waterdamage = False

            if waterdamage:
                temp_fc_union_waterdamage = os.path.join(workspace_gdb, "damage_union")
                gp.Union_analysis(temp_fc_dissolve_lgn + ";" + temp_fc_waterdamage, temp_fc_union_waterdamage)

                dissolve_waterdamage_lyr = turtlebase.arcgis.get_random_layer_name()
                gp.MakeFeatureLayer_management(temp_fc_union_waterdamage, dissolve_waterdamage_lyr, "%s > 0" % gridcode_1)

                temp_fc_dissolve_waterdamage = os.path.join(workspace_gdb, "dissolve_damage")
                gp.Dissolve_management(dissolve_waterdamage_lyr, temp_fc_dissolve_waterdamage, "%s; %s; %s" % (gpgident_field, gridcode, gridcode_1))

                # Calculate area waterdamage
                if not turtlebase.arcgis.is_fieldname(gp, temp_fc_dissolve_waterdamage, "area_damag"):
                    gp.addfield(temp_fc_dissolve_waterdamage, "area_damag", "Double")
                turtlebase.arcgis.calculate_area(gp, temp_fc_dissolve_waterdamage, "area_damag")

                waterdamage_dict = nens.gp.get_table(gp, temp_fc_dissolve_waterdamage)
                translate_waterdamage_dict = translate_dict(waterdamage_dict, gridcode_1, 'area_damag')
                log.debug("translate_waterdamage_dict: %s" % translate_waterdamage_dict)
            else:
                translate_waterdamage_dict = {}
        else:
            translate_waterdamage_dict = {}

        no_data_value = float(config.get('naverwerking_rrcf', 'no_data_value'))
        result_dict = {}
        log.info("Calculating results")
        for gpgident, fields in gpgident_dict.items():
            # area_total
            #area_total = fields['area_total']

            #set defaults
            percentage_inundation_urban = no_data_value
            percentage_inundation_agriculture = no_data_value
            percentage_inundation_rural = no_data_value
            percentage_inundation_grass = no_data_value
            toetsing_inundation_urban = 9
            toetsing_inundation_agriculture = 9
            toetsing_inundation_rural = 9
            toetsing_inundation_grass = 9

            percentage_waterdamage_urban = no_data_value
            percentage_waterdamage_agriculture = no_data_value
            percentage_waterdamage_rural = no_data_value
            percentage_waterdamage_grass = no_data_value
            toetsing_waterdamage_urban = 9
            toetsing_waterdamage_agriculture = 9
            toetsing_waterdamage_rural = 9
            toetsing_waterdamage_grass = 9

            if gpgident in translate_inundation_dict:
                log.debug("Calculate percentage inundation for %s" % gpgident)

                hhtijd = config.get('naverwerking_rrcf', 'herhalingstijd_inundatie_stedelijk')
                toetsing_perc = config.get('naverwerking_rrcf', 'percentage_inundatie_stedelijk')
                toetsing_inundation_urban, percentage_inundation_urban = calculate_toetsing(translate_inundation_dict,
                                                                                            gpgident, 1, translate_lgn_dict,
                                                                                            hhtijd, toetsing_perc, no_data_value)

                hhtijd = config.get('naverwerking_rrcf', 'herhalingstijd_inundatie_hoogwaardig')
                toetsing_perc = config.get('naverwerking_rrcf', 'percentage_inundatie_hoogwaardig')
                toetsing_inundation_agriculture, percentage_inundation_agriculture = calculate_toetsing(translate_inundation_dict,
                                                                                                        gpgident, 2, translate_lgn_dict,
                                                                                                        hhtijd, toetsing_perc, no_data_value)

                hhtijd = config.get('naverwerking_rrcf', 'herhalingstijd_inundatie_akker')
                toetsing_perc = config.get('naverwerking_rrcf', 'herhalingstijd_inundatie_akker')
                toetsing_inundation_rural, percentage_inundation_rural = calculate_toetsing(translate_inundation_dict, gpgident,
                                                               3, translate_lgn_dict, hhtijd,
                                                               toetsing_perc, no_data_value)

                hhtijd = config.get('naverwerking_rrcf', 'herhalingstijd_inundatie_grasland')
                toetsing_perc = config.get('naverwerking_rrcf', 'percentage_inundatie_grasland')
                toetsing_inundation_grass, percentage_inundation_grass = calculate_toetsing(translate_inundation_dict, gpgident,
                                                               4, translate_lgn_dict, hhtijd,
                                                               toetsing_perc, no_data_value)

            if gpgident in translate_waterdamage_dict:
                log.debug("Calculate percentage waterdamage for %s" % gpgident)

                hhtijd = config.get('naverwerking_rrcf', 'herhalingstijd_overlast_stedelijk')
                toetsing_perc = config.get('naverwerking_rrcf', 'percentage_overlast_stedelijk')
                toetsing_waterdamage_urban, percentage_waterdamage_urban = calculate_toetsing(translate_inundation_dict, gpgident,
                                                                                              1, translate_lgn_dict, hhtijd,
                                                                                              toetsing_perc, no_data_value)

                hhtijd = config.get('naverwerking_rrcf', 'herhalingstijd_overlast_hoogwaardig')
                toetsing_perc = config.get('naverwerking_rrcf', 'percentage_overlast_hoogwaardig')
                toetsing_waterdamage_agriculture, percentage_waterdamage_agriculture = calculate_toetsing(translate_inundation_dict, gpgident,
                                                                                                          2, translate_lgn_dict, hhtijd,
                                                                                                          toetsing_perc, no_data_value)

                hhtijd = config.get('naverwerking_rrcf', 'herhalingstijd_overlast_akker')
                toetsing_perc = config.get('naverwerking_rrcf', 'herhalingstijd_overlast_akker')
                toetsing_inundation_rural, percentage_waterdamage_rural = calculate_toetsing(translate_inundation_dict, gpgident,
                                                                                             3, translate_lgn_dict, hhtijd,
                                                                                             toetsing_perc, no_data_value)

                hhtijd = config.get('naverwerking_rrcf', 'herhalingstijd_overlast_grasland')
                toetsing_perc = config.get('naverwerking_rrcf', 'percentage_overlast_grasland')
                toetsing_inundation_grass, percentage_waterdamage_grass = calculate_toetsing(translate_inundation_dict, gpgident,
                                                                                             4, translate_lgn_dict, hhtijd,
                                                                                             toetsing_perc, no_data_value)

            result_dict[gpgident] = {
                    gpgident_field: gpgident,
                    config.get('naverwerking_rrcf',
                            'field_percentage_inundatie_stedelijk'):
                                     percentage_inundation_urban,
                    config.get('naverwerking_rrcf',
                            'field_percentage_inundatie_hoogwaardig'):
                                     percentage_inundation_agriculture,
                    config.get('naverwerking_rrcf',
                            'field_percentage_inundatie_akker'):
                                     percentage_inundation_rural,
                    config.get('naverwerking_rrcf',
                            'field_percentage_inundatie_grasland'):
                                      percentage_inundation_grass,
                    config.get('naverwerking_rrcf',
                            'field_percentage_overlast_stedelijk'):
                                      percentage_waterdamage_urban,
                    config.get('naverwerking_rrcf',
                            'field_percentage_overlast_hoogwaardig'):
                                      percentage_waterdamage_agriculture,
                    config.get('naverwerking_rrcf',
                            'field_percentage_overlast_akker'):
                                      percentage_waterdamage_rural,
                    config.get('naverwerking_rrcf',
                            'field_percentage_overlast_grasland'):
                                     percentage_waterdamage_grass,
                    config.get('naverwerking_rrcf',
                            'field_toetsing_inundatie_stedelijk'):
                                     toetsing_inundation_urban,
                    config.get('naverwerking_rrcf',
                            'field_toetsing_inundatie_hoogwaardig'):
                                      toetsing_inundation_agriculture,
                    config.get('naverwerking_rrcf',
                            'field_toetsing_inundatie_akker'):
                                     toetsing_inundation_rural,
                    config.get('naverwerking_rrcf',
                            'field_toetsing_inundatie_grasland'):
                                     toetsing_inundation_grass,
                    config.get('naverwerking_rrcf',
                            'field_toetsing_overlast_stedelijk'):
                                     toetsing_waterdamage_urban,
                    config.get('naverwerking_rrcf',
                            'field_toetsing_overlast_hoogwaardig'):
                                     toetsing_waterdamage_agriculture,
                    config.get('naverwerking_rrcf',
                            'field_toetsing_overlast_akker'):
                                     toetsing_waterdamage_rural,
                    config.get('naverwerking_rrcf',
                            'field_toetsing_overlast_grasland'):
                                     toetsing_waterdamage_grass,
                                     }
        #---------------------------------------------------------------------
        # Create output table
        if not gp.exists(output_result_table):
            log.info("Create new output table")
            temp_result_table = os.path.join(workspace_gdb, "result_table")
            gp.CreateTable_management(os.path.dirname(temp_result_table), os.path.basename(temp_result_table))
            copy_table = True
        else:
            temp_result_table = output_result_table
            copy_table = False

        fields_to_add = [config.get('naverwerking_rrcf',
                            'field_percentage_inundatie_stedelijk'),
                         config.get('naverwerking_rrcf',
                            'field_percentage_inundatie_hoogwaardig'),
                         config.get('naverwerking_rrcf',
                            'field_percentage_inundatie_akker'),
                         config.get('naverwerking_rrcf',
                            'field_percentage_inundatie_grasland'),
                         config.get('naverwerking_rrcf',
                            'field_percentage_overlast_stedelijk'),
                         config.get('naverwerking_rrcf',
                            'field_percentage_overlast_hoogwaardig'),
                         config.get('naverwerking_rrcf',
                            'field_percentage_overlast_akker'),
                         config.get('naverwerking_rrcf',
                            'field_percentage_overlast_grasland'),
                         config.get('naverwerking_rrcf',
                            'field_toetsing_inundatie_stedelijk'),
                         config.get('naverwerking_rrcf',
                            'field_toetsing_inundatie_hoogwaardig'),
                         config.get('naverwerking_rrcf',
                            'field_toetsing_inundatie_akker'),
                         config.get('naverwerking_rrcf',
                            'field_toetsing_inundatie_grasland'),
                         config.get('naverwerking_rrcf',
                            'field_toetsing_overlast_stedelijk'),
                         config.get('naverwerking_rrcf',
                            'field_toetsing_overlast_hoogwaardig'),
                         config.get('naverwerking_rrcf',
                            'field_toetsing_overlast_akker'),
                         config.get('naverwerking_rrcf',
                            'field_toetsing_overlast_grasland')]

        if not turtlebase.arcgis.is_fieldname(gp, temp_result_table, gpgident_field):
            log.debug(" - add field %s to %s" % (gpgident_field, temp_result_table))
            gp.addfield_management(temp_result_table, gpgident_field, 'text')

        for field in fields_to_add:
            if not turtlebase.arcgis.is_fieldname(gp, temp_result_table, field):
                log.debug(" - add field %s to %s" % (field, temp_result_table))
                gp.addfield_management(temp_result_table, field, 'double')

        #----------------------------------------------------------------------------------------
        # Write results to output table
        log.info("Write results to output table")
        turtlebase.arcgis.write_result_to_output(temp_result_table, gpgident_field.lower(), result_dict)

        if copy_table == True:
            gp.TableToTable_conversion(temp_result_table, os.path.dirname(output_result_table), os.path.basename(output_result_table))

        #---------------------------------------------------------------------
        # Delete temporary workspace geodatabase & ascii files
        try:
            log.debug("delete temporary workspace: %s" % workspace_gdb)
            gp.delete(workspace_gdb)

            log.info("workspace deleted")
        except:
            log.debug("failed to delete %s" % workspace_gdb)

        tempfiles = os.listdir(workspace)
        for tempfile in tempfiles:
            if tempfile.endswith('.asc'):
                try:
                    os.remove(os.path.join(workspace, tempfile))
                except Exception, e:
                    log.debug(e)
                    
        mainutils.log_footer()
def main():
    try:
        gp = mainutils.create_geoprocessor()
        config = mainutils.read_config(__file__, 'turtle-settings.ini')
        logfile = mainutils.log_filename(config)
        logging_config = LoggingConfig(gp, logfile=logfile)
        mainutils.log_header(__name__)

        #---------------------------------------------------------------------
        # Create workspace
        workspace = config.get('GENERAL', 'location_temp')
        if workspace == "-":
            workspace = tempfile.gettempdir()

        turtlebase.arcgis.delete_old_workspace_gdb(gp, workspace)

        if not os.path.isdir(workspace):
            os.makedirs(workspace)
        workspace_gdb, errorcode = turtlebase.arcgis.create_temp_geodatabase(
                                        gp, workspace)
        if errorcode == 1:
            log.error("failed to create a file geodatabase in %s" % workspace)

        #---------------------------------------------------------------------
        # Input parameters
        """
        nodig voor deze tool:
        """

        if len(sys.argv) == 5:
            input_polygon_fc = sys.argv[1]
            input_channel_fc = sys.argv[2]
            input_landuse_fc = sys.argv[3]
            output_channel = sys.argv[4]
        else:
            log.warning("usage: python geo_genereren_afv_opp.py <input peilgebieden> <input watergangen> <input landgebruik> <output waterlijnen met oppervlak>")
            sys.exit(1)

        #---------------------------------------------------------------------
        # Check geometry input parameters
        log.info("Check geometry of input parameters")
        geometry_check_list = []

        #log.debug(" - check <input >: %s" % argument1)
        gpg_obj = gp.describe(input_polygon_fc)
        if gpg_obj.ShapeType != 'Polygon':
            geometry_check_list.append("input peilgebieden does not contain polygons, it contains shapetype: %s" % gpg_obj.ShapeType)
        else:
            log.info(" - input peilgebieden is correct")

        ovk_obj = gp.describe(input_channel_fc)
        if ovk_obj.ShapeType != 'Polyline':
            geometry_check_list.append("input channel does not contain polyline, it contains shapetype: %s" % ovk_obj.ShapeType)
        else:
            log.info(" - input channel is correct")

        lu_obj = gp.describe(input_landuse_fc)
        if lu_obj.ShapeType != 'Polygon':
            geometry_check_list.append("input landuse does not contain polygons, it contains shapetype: %s" % lu_obj.ShapeType)
        else:
            log.info(" - input landuse is correct")
        #"<check geometry from input data, append to list if incorrect>"

        if len(geometry_check_list) > 0:
            log.error("check input: %s" % geometry_check_list)
            sys.exit(2)
        #---------------------------------------------------------------------
        # Check required fields in input data
        log.info("Check required fields in input data")

        missing_fields = []
        ovk_field = config.get('general', 'ovkident')
        gpg_field = config.get('general', 'gpgident')
        landuse_type = config.get('afv_opp', 'landuse_type')

        if not turtlebase.arcgis.is_fieldname(gp, input_polygon_fc, ovk_field):
            log.error("missing field '%s' in %s" % (ovk_field, input_polygon_fc))
            missing_fields.append("%s: %s" % (input_polygon_fc, ovk_field))

        if not turtlebase.arcgis.is_fieldname(gp, input_channel_fc, ovk_field):
            log.error("missing field '%s' in %s" % (ovk_field, input_channel_fc))
            missing_fields.append("%s: %s" % (input_channel_fc, ovk_field))

        if not turtlebase.arcgis.is_fieldname(gp, input_landuse_fc, 'type'):
            log.error("missing field 'type' in %s" % input_landuse_fc)
            missing_fields.append("%s: TYPE" % (input_landuse_fc))

        if len(missing_fields) > 0:
            log.error("missing fields in input data: %s" % missing_fields)
            sys.exit(2)
        #---------------------------------------------------------------------
        # Environments

        log.info(" - intersect areas with landuse")
        output_intersect_landuse = workspace_gdb + "/landuse_intersect"
        log.info(output_intersect_landuse)
        gp.intersect_analysis(input_polygon_fc + "; " + input_landuse_fc, output_intersect_landuse)

        landuse_type_list = check_for_landuse_types(gp, output_intersect_landuse, "TYPE")
        if len(landuse_type_list) == 0:
            log.error("missing landuse types 'rural' and 'urban'")
            sys.exit(3)

        #log.info(turtlebase.arcgis.is_fieldname(gp, output_intersect_landuse, 'OPP_LA'))
        if not turtlebase.arcgis.is_fieldname(gp, output_intersect_landuse, 'OPP_LA'):
            log.info("create field OPP_LA")
            gp.addfield(output_intersect_landuse, 'OPP_LA', 'Double')
        if not turtlebase.arcgis.is_fieldname(gp, output_intersect_landuse, 'OPP_ST'):
            log.info("create field OPP_ST")
            gp.addfield(output_intersect_landuse, 'OPP_ST', 'Double')

        if 'urban' in landuse_type_list:
            log.info(" - calculate urban area")
            landuse_urban_lyr = turtlebase.arcgis.get_random_layer_name()
            gp.MakeFeatureLayer_management(output_intersect_landuse, landuse_urban_lyr, " TYPE = 'urban' ")
            turtlebase.arcgis.calculate_area(gp, landuse_urban_lyr, "OPP_ST")

        if 'rural' in landuse_type_list:
            log.info(" - calculate rural area")
            landuse_rural_lyr = turtlebase.arcgis.get_random_layer_name()
            gp.MakeFeatureLayer_management(output_intersect_landuse, landuse_rural_lyr, " TYPE = 'rural' ")
            turtlebase.arcgis.calculate_area(gp, landuse_rural_lyr, "OPP_LA")

        output_dissolve_landuse = workspace_gdb + "/dissolve"
        #tempfiles.append(output_dissolve_landuse)
        log.info("check if output fields exist")
        field_rural = "Sum_OPP_LA"
        field_urban = "Sum_OPP_ST"
        if turtlebase.arcgis.is_fieldname(gp, output_intersect_landuse, field_rural):
            log.info(" - %s already exists, delete field" % field_rural)
            gp.deletefield_management(output_intersect_landuse, field_rural)
        if turtlebase.arcgis.is_fieldname(gp, output_intersect_landuse, field_urban):
            gp.deletefield_management(output_intersect_landuse, field_urban)

        log.info(" - dissolve rural and urban areas")
        remove_null_values(gp, output_intersect_landuse, "OPP_LA")
        remove_null_values(gp, output_intersect_landuse, "OPP_ST")

        gp.Dissolve_management(output_intersect_landuse, output_dissolve_landuse, ovk_field, "OPP_LA sum; OPP_ST sum", "MULTI_PART")

        log.info("Copy landuse area to output")
        dissolve_dict = nens.gp.get_table(gp, output_dissolve_landuse, primary_key=ovk_field.lower())
        output_channel_fc = turtlebase.arcgis.get_random_file_name(workspace_gdb)
        calculate_area_fields(gp, input_channel_fc, output_channel_fc, ovk_field, dissolve_dict, field_rural, field_urban)

        # add from and to coordinates
        log.info("Calculate coordinates")
        update_to_and_from_coordinates(gp, output_channel_fc, ovk_field.lower())
        log.info(" - copy output")
        gp.FeatureclassToFeatureclass_conversion(output_channel_fc, os.path.dirname(output_channel), os.path.basename(output_channel))
        #---------------------------------------------------------------------
        # Delete temporary workspace geodatabase & ascii files
        try:
            log.debug("delete temporary workspace: %s" % workspace_gdb)
            #gp.delete(workspace_gdb)

            log.info("workspace deleted")
        except:
            log.warning("failed to delete %s" % workspace_gdb)

        mainutils.log_footer()
    except:
        log.error(traceback.format_exc())
        sys.exit(1)

    finally:
        logging_config.cleanup()
        del gp
def main():
    try:
        gp = mainutils.create_geoprocessor()
        config = mainutils.read_config(__file__, 'turtle-settings.ini')
        logfile = mainutils.log_filename(config)
        logging_config = LoggingConfig(gp, logfile=logfile)
        mainutils.log_header(__name__)

        #---------------------------------------------------------------------
        # Create workspace
        workspace = config.get('GENERAL', 'location_temp')
        if workspace == "-":
            workspace = tempfile.gettempdir()

        turtlebase.arcgis.delete_old_workspace_gdb(gp, workspace)

        if not os.path.isdir(workspace):
            os.makedirs(workspace)
        workspace_gdb, errorcode = turtlebase.arcgis.create_temp_geodatabase(
                                            gp, workspace)
        if errorcode == 1:
            log.error("failed to create a file geodatabase in %s" % workspace)

        #---------------------------------------------------------------------
        # check inputfields
        log.info("Getting commandline parameters")
        if len(sys.argv) == 8:
            input_level_area_fc = sys.argv[1]
            input_level_area_table = sys.argv[2]
            input_ahn_raster = sys.argv[3]
            input_lgn_raster = sys.argv[4]
            input_lgn_conversion = sys.argv[5]
            input_onderbemalingen = sys.argv[6]
            if input_onderbemalingen == "#":
                use_onderbemalingen = False
            else:
                use_onderbemalingen = True
            output_file = sys.argv[7]
        else:
            log.error("Usage: python toetspuntenbepaling.py <ahn-file> \
                        <lgn-file> <onderbemalingen-optional> \
                        <peilgebieden-feature> <peilvakgegevens-table> \
                        <conversietabel> <outputfile-HydroBase>")
            sys.exit(1)
        #---------------------------------------------------------------------
        # check input parameters
        log.info('Checking presence of input files')
        if not(gp.exists(input_level_area_fc)):
            log.error("inputfile peilgebieden %s does not exist!",
                      input_level_area_fc)
            sys.exit(5)
        if not(gp.exists(input_level_area_table)):
            log.error("inputfile peilvakgegevens %s does not exist!",
                      input_level_area_table)
            sys.exit(5)
        if (use_onderbemalingen and not(gp.exists(input_onderbemalingen))):
            log.error("inputfile onderbemalingen %s does not exist!",
                      input_onderbemalingen)
            sys.exit(5)

        log.info('input parameters checked')

        #---------------------------------------------------------------------
        # Check geometry input parameters
        cellsize = gp.describe(input_ahn_raster).MeanCellHeight

        log.info("Check geometry of input parameters")
        geometry_check_list = []

        log.debug(" - check level area: %s" % input_level_area_fc)
        if gp.describe(input_level_area_fc).ShapeType != 'Polygon':
            errormsg = ("%s is not a polygon feature class!",
                        input_level_area_fc)
            log.error(errormsg)
            geometry_check_list.append(errormsg)

        if turtlebase.arcgis.fc_is_not_empty(gp, input_level_area_fc):
            errormsg = "input '%s' is empty" % input_level_area_fc
            log.error(errormsg)
            sys.exit(1)

        if turtlebase.arcgis.fc_is_not_empty(gp, input_level_area_table):
            errormsg = "input '%s' is empty" % input_level_area_table
            log.error(errormsg)
            sys.exit(1)

        if use_onderbemalingen:
            if turtlebase.arcgis.fc_is_not_empty(gp, input_onderbemalingen):
                errormsg = "input '%s' is empty" % input_onderbemalingen
                log.error(errormsg)
                sys.exit(1)

        log.debug(" - check ahn raster %s" % input_ahn_raster)
        if gp.describe(input_ahn_raster).DataType != 'RasterDataset':
            log.error("Input AHN is not a raster dataset")
            sys.exit(1)

        if gp.describe(input_ahn_raster).PixelType[0] not in ['U', 'S']:
            errormsg = ("Input AHN is a floating point raster, \
                        for this script an integer is nessecary")
            log.error(errormsg)
            geometry_check_list.append(errormsg)

        log.debug(" - check lgn raster %s" % input_lgn_raster)
        if gp.describe(input_lgn_raster).DataType != 'RasterDataset':
            log.error("Input LGN is not a raster dataset")
            sys.exit(1)

        if gp.describe(input_lgn_raster).PixelType[0] not in ['U', 'S']:
            errormsg = ("Input LGN is a floating point raster, \
                        for this script an integer is nessecary")
            log.error(errormsg)
            geometry_check_list.append(errormsg)

        if int(gp.describe(input_lgn_raster).MeanCellHeight) != int(cellsize):
            errormsg = ("Cell size of LGN is %s, must be %s" % (
                            gp.describe(input_lgn_raster).MeanCellHeight,
                            int(cellsize)))
            log.error(errormsg)
            geometry_check_list.append(errormsg)

        if len(geometry_check_list) > 0:
            log.error("check input: %s" % geometry_check_list)
            sys.exit(2)

        #---------------------------------------------------------------------
        # Check required fields in input data
        log.info("Check required fields in input data")
        gpgident = config.get('GENERAL', 'gpgident').lower()
        streefpeil = config.get('toetspunten', 'field_streefpeil').lower()

        missing_fields = []

        # check required fields from input data, append them to list if missing
        if not turtlebase.arcgis.is_fieldname(
                    gp, input_level_area_fc, gpgident):
            log.debug(" - missing: %s in %s", (
                        gpgident, input_level_area_fc))
            missing_fields.append("%s: %s", (
                        input_level_area_fc, gpgident))

        if not turtlebase.arcgis.is_fieldname(
                    gp, input_level_area_table, gpgident):
            log.debug(" - missing: %s in %s", (
                        gpgident, input_level_area_table))
            missing_fields.append("%s: %s", (
                        input_level_area_table, gpgident))

        if not turtlebase.arcgis.is_fieldname(
                    gp, input_level_area_table, streefpeil):
            log.debug(" - missing: %s in %s", (
                        streefpeil, input_level_area_table))
            missing_fields.append("%s: %s", (
                        input_level_area_table, streefpeil))

        if len(missing_fields) > 0:
            log.error("missing fields in input data: %s", missing_fields)
            sys.exit(2)

        #---------------------------------------------------------------------
        # Environments
        log.info("Set environments")
        temp_level_area = os.path.join(workspace_gdb, "peilgebieden")
        if input_level_area_fc.endswith(".shp"):
            log.info("Copy features of level areas to workspace")
            gp.select_analysis(input_level_area_fc, temp_level_area)
        else:
            log.info("Copy level areas to workspace")
            gp.copy_management(input_level_area_fc, temp_level_area)
        # use extent from level area
        gp.extent = gp.describe(temp_level_area).extent

        #---------------------------------------------------------------------
        # Create K5 LGN
        log.info("Translate LGN to NBW-classes")
        lgn_ascii = turtlebase.arcgis.get_random_file_name(
                                            workspace, ".asc")
        lgn_k5_ascii = turtlebase.arcgis.get_random_file_name(
                                            workspace, ".asc")

        gp.RasterToASCII_conversion(input_lgn_raster, lgn_ascii)
        lgn_ident = config.get('toetspunten', 'lgn_conv_ident')

        if input_lgn_conversion != '#':
            reclass_dict = nens.gp.get_table(gp, input_lgn_conversion,
                                             primary_key=lgn_ident)
            turtlebase.spatial.reclass_lgn_k5(
                            lgn_ascii, lgn_k5_ascii, reclass_dict)
        else:
            turtlebase.spatial.reclass_lgn_k5(lgn_ascii, lgn_k5_ascii)
        #---------------------------------------------------------------------
        # create ahn ascii
        log.info("Create ascii from ahn")

        ahn_ascii = turtlebase.arcgis.get_random_file_name(workspace, ".asc")
        log.debug("ahn ascii: %s" % ahn_ascii)
        gp.RasterToASCII_conversion(input_ahn_raster, ahn_ascii)

        #---------------------------------------------------------------------
        # Change ahn and lgn if use_ondermalingen == True
        if use_onderbemalingen:
            log.info("Cut out level deviations")
            gridcode_fieldname = "GRIDCODE"
            if not turtlebase.arcgis.is_fieldname(
                    gp, input_onderbemalingen, gridcode_fieldname):
                log.debug(" - add field %s" % gridcode_fieldname)
                gp.addfield_management(
                    input_onderbemalingen, gridcode_fieldname, "Short")

            row = gp.UpdateCursor(input_onderbemalingen)
            for item in nens.gp.gp_iterator(row):
                item.SetValue(gridcode_fieldname, 1)
                row.UpdateRow(item)

            onderbemaling_raster = turtlebase.arcgis.get_random_file_name(
                                                            workspace_gdb)
            gp.FeatureToRaster_conversion(
                            input_onderbemalingen, gridcode_fieldname,
                            onderbemaling_raster, cellsize)

            onderbemaling_asc = turtlebase.arcgis.get_random_file_name(
                                                    workspace, ".asc")
            gp.RasterToASCII_conversion(onderbemaling_raster,
                                        onderbemaling_asc)

            ahn_ascii = turtlebase.spatial.cut_out_onderbemaling(
                            ahn_ascii, onderbemaling_asc, workspace)
            lgn_k5_ascii = turtlebase.spatial.cut_out_onderbemaling(
                            lgn_k5_ascii, onderbemaling_asc, workspace)

        #---------------------------------------------------------------------
        # Add ID Int to level area
        log.info("Create level area ascii")
        id_int = 'id_int'
        area_id_dict = add_integer_ident(gp, temp_level_area,
                                         id_int, gpgident)

        out_raster_dataset = turtlebase.arcgis.get_random_file_name(
                                                        workspace_gdb)
        gp.FeatureToRaster_conversion(temp_level_area, id_int,
                                      out_raster_dataset, cellsize)

        id_int_ascii = turtlebase.arcgis.get_random_file_name(
                                            workspace, ".asc")
        log.debug("id_int_ascii: %s" % id_int_ascii)
        gp.RasterToASCII_conversion(out_raster_dataset, id_int_ascii)

        #---------------------------------------------------------------------
        log.info("Read targetlevel table")
        area_level_dict = nens.gp.get_table(gp, input_level_area_table,
                                            primary_key=gpgident)
        target_level_dict = {}

        for k, v in area_level_dict.items():
            if k in area_id_dict:
                int_id = area_id_dict[k][id_int]
                target_level_dict[int_id] = {'targetlevel': v[streefpeil],
                                             'gpgident': k}

        toetspunten_fields = ["DFLT_I_ST", "DFLT_I_HL", "DFLT_I_AK",
                              "DFLT_I_GR", "DFLT_O_ST", "DFLT_O_HL",
                              "DFLT_O_AK", "DFLT_O_GR", "MTGMV_I_ST",
                              "MTGMV_I_HL", "MTGMV_I_AK", "MTGMV_I_GR",
                              "MTGMV_O_ST", "MTGMV_O_HL", "MTGMV_O_AK",
                              "MTGMV_O_GR"]
        #---------------------------------------------------------------------
        log.info("calculate toetspunten")
        toetspunten_dict = turtlebase.spatial.calculcate_toetspunten(
                            ahn_ascii, lgn_k5_ascii, id_int_ascii,
                            toetspunten_fields, target_level_dict,
                            onderbemaling="#")
        #---------------------------------------------------------------------
        log.info("Create output table")
        create_output_table(gp, output_file, gpgident, toetspunten_fields)
        #---------------------------------------------------------------------
        # Add metadata
        import time
        date_time_str = time.strftime("%d %B %Y %H:%M:%S")
        source = input_ahn_raster

        for area_id, values in toetspunten_dict.items():
            toetspunten_dict[area_id]['date_time'] = date_time_str
            toetspunten_dict[area_id]['source'] = source

        #---------------------------------------------------------------------
        # Write results to output table
        log.info("Write results to output table")
        turtlebase.arcgis.write_result_to_output(
                    output_file, gpgident, toetspunten_dict)

        #---------------------------------------------------------------------
        # Delete temporary workspace geodatabase & ascii files
        try:
            log.debug("delete temporary workspace: %s" % workspace_gdb)
            gp.delete(workspace_gdb)

            log.info("workspace deleted")
        except:
            log.warning("failed to delete %s" % workspace_gdb)

        tempfiles = os.listdir(workspace)
        for tempfile in tempfiles:
            if tempfile.endswith('.asc'):
                try:
                    os.remove(os.path.join(workspace, tempfile))
                except Exception, e:
                    log.debug(e)

        mainutils.log_footer()
Exemple #15
0
def main():
    try:
        gp = mainutils.create_geoprocessor()
        config = mainutils.read_config(__file__, 'turtle-settings.ini')
        logfile = mainutils.log_filename(config)
        logging_config = LoggingConfig(gp, logfile=logfile)
        mainutils.log_header(__name__)

        #----------------------------------------------------------------------------------------
        # Create workspace
        workspace = config.get('GENERAL', 'location_temp')
        if workspace == "-":
            workspace = tempfile.gettempdir()
        turtlebase.arcgis.delete_old_workspace_gdb(gp, workspace)

        if not os.path.isdir(workspace):
            os.makedirs(workspace)
        workspace_gdb, errorcode = turtlebase.arcgis.create_temp_geodatabase(gp, workspace)
        if errorcode == 1:
            log.error("failed to create a file geodatabase in %s" % workspace)

        #----------------------------------------------------------------------------------------
        # Input parameters
        if len(sys.argv) == 11:
            log.info("Reading input parameters")
            peilgebied = sys.argv[1]
            input_rr_peilgebied = sys.argv[2]
            input_rr_maaiveld = sys.argv[3]
            input_ahn = sys.argv[4]
            input_lgn = sys.argv[5]
            conversion = sys.argv[6]
            input_hymstat = sys.argv[7]
            output_risk_table = sys.argv[8]
            output_risico = sys.argv[9]
            output_risico_inundation = sys.argv[10]
        else:
            log.error("usage: <peilgebied> <input_rr_peilgebied> <input_rr_maaiveld> <input_ahn> <input_lgn>\
                      <conversion> <input_hymstat> <output_risk_table> <output_risico> <output_risico_inundation>")
            sys.exit(1)

        #----------------------------------------------------------------------------------------
        log.info(" - read Conversion table")
        conv_list = [d for d in csv.DictReader(open(conversion))]

        expected_keys = ['LGN', 'K5', 'maxschade', 'sr1', 'sr2', 'sr3',
                         'sr4', 'sr5', 'sr6', 'sr7', 'sr8', 'sr9']
        for k in expected_keys:
            if k not in conv_list[0].keys():
                log.error('could not find key %s in conversion table' % k)
                sys.exit(2)

        schadefuncties = {}
        for item in conv_list:
            schadefuncties[int(item['LGN'])] = item
        #----------------------------------------------------------------------------------------
        log.info(" - read hymstat table")
        csv_list = [d for d in csv.DictReader(open(input_hymstat))]
        expected_hymstat_keys = ['Location', 'Scale par. beta', 'Location par. x0']

        for k in expected_hymstat_keys:
            csv_list[0].keys()
            if k not in csv_list[0].keys():
                log.error('could not find key %s in hymstat table' % k)
                sys.exit(2)

        hymstat = {}
        for item in csv_list:
            hymstat[item[config.get('risico', 'hymstat_id')]] = item
        #----------------------------------------------------------------------------------------
        # Check geometry input parameters
        log.info("Check geometry of input parameters")
        geometry_check_list = []

        #log.debug(" - check <input >: %s" % argument1)

        "<check geometry from input data, append to list if incorrect>"

        if len(geometry_check_list) > 0:
            log.error("check input: %s" % geometry_check_list)
            sys.exit(2)

        #----------------------------------------------------------------------------------------
        # Check required fields in input data
        log.info("Check required fields in input data")

        missing_fields = []

        #<check required fields from input data, append them to list if missing>
        check_fields = {}#check_fields = {input_1: [fieldname1, fieldname2], input_2: [fieldname1, fieldname2]}
        for input_fc, fieldnames in check_fields.items():
            for fieldname in fieldnames:
                if not turtlebase.arcgis.is_fieldname(gp, input_fc, fieldname):
                    errormsg = "fieldname %s not available in %s" % (fieldname, input_fc)
                    log.error(errormsg)
                    missing_fields.append(errormsg)

        if len(missing_fields) > 0:
            log.error("missing fields in input data: %s" % missing_fields)
            sys.exit(2)

        #----------------------------------------------------------------------------------------
        # Environments
        log.info("Set environments")
        temp_peilgebieden = turtlebase.arcgis.get_random_file_name(workspace_gdb)
        gp.Select_analysis(peilgebied, temp_peilgebieden)

        cellsize = gp.describe(input_ahn).MeanCellHeight  # use same cell size as AHN
        gp.extent = gp.describe(temp_peilgebieden).extent  # use extent from Peilgebieden
        gpgident = config.get('GENERAL', 'gpgident')

        #----------------------------------------------------------------------------------------
        # create ahn ascii
        log.info("Create ascii from ahn")

        ahn_ascii = turtlebase.arcgis.get_random_file_name(workspace, ".asc")
        log.debug("ahn ascii: %s" % ahn_ascii)
        gp.RasterToASCII_conversion(input_ahn, ahn_ascii)

        #----------------------------------------------------------------------------------------
        # create lgn ascii
        log.info("Create ascii from lgn")
        #read gpgident from file
        lgn_desc = gp.describe(input_lgn)
        if lgn_desc.DataType == 'ShapeFile' or lgn_desc.DataType == 'FeatureClass':
            lgn_fieldnames = nens.gp.get_table_def(gp, input_lgn)
            if "gridcode" in lgn_fieldnames:
                gridcode = "GRIDCODE"
            elif "grid_code" in lgn_fieldnames:
                gridcode = "grid_code"
            else:
                log.error("Cannot find 'grid_code' or 'gridcode' field in input lgn file")

            temp_lgn = turtlebase.arcgis.get_random_file_name(workspace_gdb)
            gp.FeatureToRaster_conversion(input_lgn, gridcode, temp_lgn, cellsize)
        elif lgn_desc.DataType == 'RasterDataset':
            temp_lgn = input_lgn
            if not lgn_desc.MeanCellHeight == cellsize:
                log.error("LGN cellsize does not match AHN cellsize (%sx%s m)" % cellsize)
                sys.exit(5)
        else:
            log.error("cannot recognize datatype of LGN, must be a fc, shapefile or a raster dataset")
            sys.exit(5)

        lgn_ascii = turtlebase.arcgis.get_random_file_name(workspace, ".asc")
        log.debug("lgn ascii: %s" % lgn_ascii)
        gp.RasterToASCII_conversion(temp_lgn, lgn_ascii)

        #----------------------------------------------------------------------------------------
        log.info("Create ascii from surface level areas")
        if not turtlebase.arcgis.is_fieldname(gp, temp_peilgebieden, "ID_INT"):
            gp.AddField(temp_peilgebieden, "ID_INT", "LONG")

        id_int = 1
        idint_to_peilvakid = {}
        peilvakid_to_idint = {}
        if turtlebase.arcgis.is_fieldname(gp, temp_peilgebieden, gpgident):
            rows = gp.SearchCursor(temp_peilgebieden)
            for row in nens.gp.gp_iterator(rows):
                peilvakid = row.GetValue(gpgident)
                idint_to_peilvakid[id_int] = peilvakid
                peilvakid_to_idint[peilvakid] = id_int
                id_int = id_int + 1 #each row gets a new id_int

        log.info(" - calc value ID_INT")
        rows = gp.UpdateCursor(temp_peilgebieden)
        for row in nens.gp.gp_iterator(rows):
            gpg_ident = row.GetValue(gpgident)
            id_int = peilvakid_to_idint[gpg_ident]
            row.SetValue("ID_INT", id_int)
            rows.UpdateRow(row)

        log.info("Conversion feature peilgebieden to raster")
        InField = "ID_INT"
        temp_peilgebieden_raster = turtlebase.arcgis.get_random_file_name(workspace_gdb)
        gp.FeatureToRaster_conversion(temp_peilgebieden, InField, temp_peilgebieden_raster, cellsize)

        peilgeb_asc = turtlebase.arcgis.get_random_file_name(workspace, ".asc")
        gp.RasterToASCII_conversion(temp_peilgebieden_raster, peilgeb_asc)

        #----------------------------------------------------------------------------------------
        # Read input tables into dictionaries
        log.info("Read input tables")
        log.info(" - read RR_Peilgebied")
        rr_peilgebied = nens.gp.get_table(gp, input_rr_peilgebied, primary_key=gpgident.lower())
        log.info(" - read RR_Maaiveld")
        rr_maaiveld = nens.gp.get_table(gp, input_rr_maaiveld, primary_key=gpgident.lower())

        log.info(" - read conversion table between id_int and gpgident")
        gpg_conv = nens.gp.get_table(gp, temp_peilgebieden, primary_key='id_int')

        #----------------------------------------------------------------------------------------
        log.info("Calculate Risk")
        temp_risico = turtlebase.arcgis.get_random_file_name(workspace, "risk.asc")
        temp_risico_in = turtlebase.arcgis.get_random_file_name(workspace, ".asc")
        risico_tbl = turtlebase.risico.create_risk_grid(ahn_ascii, lgn_ascii,
                                                        peilgeb_asc, rr_peilgebied, rr_maaiveld,
                                                        hymstat, gpg_conv, schadefuncties, temp_risico,
                                                        temp_risico_in, cellsize)

        risk_result = turtlebase.risico.create_risico_dict(risico_tbl, schadefuncties, primary_key=gpgident)
        for k in risk_result.keys():
            risk_result[k]['SOURCE'] = "hymstat: %s, ahn: %s, lgn: %s" % (os.path.basename(input_hymstat),
                                                         os.path.basename(input_ahn),
                                                         os.path.basename(input_lgn))
            risk_result[k]['DATE_TIME'] = time.strftime("%d-%m-%Y, %H:%M:%S")

        gp.ASCIIToRaster_conversion(temp_risico, output_risico, "FLOAT")
        gp.ASCIIToRaster_conversion(temp_risico_in, output_risico_inundation, "FLOAT")

        # Schrijf de resultaten weg als een nieuwe tabel
        if not(gp.exists(output_risk_table)):
            log.info("creating table " + output_risk_table)
            gp.CreateTable(os.path.dirname(output_risk_table), os.path.basename(output_risk_table))

        risk_fields = nens.gp.get_table_def(gp, output_risk_table)
        fields_to_add = [{'fieldname': gpgident, 'fieldtype': 'text', 'length': 50},
                         {'fieldname': 'RIS_GW', 'fieldtype': 'Double'},
                         {'fieldname': 'RIS_GW_ST', 'fieldtype': 'Double'},
                         {'fieldname': 'RIS_GW_HL', 'fieldtype': 'Double'},
                         {'fieldname': 'RIS_GW_AK', 'fieldtype': 'Double'},
                         {'fieldname': 'RIS_GW_GR', 'fieldtype': 'Double'},
                         {'fieldname': 'RIS_GW_NT', 'fieldtype': 'Double'},
                         {'fieldname': 'RIS_IN', 'fieldtype': 'Double'},
                         {'fieldname': 'RIS_IN_ST', 'fieldtype': 'Double'},
                         {'fieldname': 'RIS_IN_HL', 'fieldtype': 'Double'},
                         {'fieldname': 'RIS_IN_AK', 'fieldtype': 'Double'},
                         {'fieldname': 'RIS_IN_GR', 'fieldtype': 'Double'},
                         {'fieldname': 'RIS_IN_NT', 'fieldtype': 'Double'},
                         {'fieldname': 'SOURCE', 'fieldtype': 'text', 'length': 256},
                         {'fieldname': 'DATE_TIME', 'fieldtype': 'text', 'length': 25},
                         {'fieldname': 'COMMENTS', 'fieldtype': 'text', 'length': 256}]

        for field_to_add in fields_to_add:
            if field_to_add['fieldname'].lower() not in risk_fields:
                if 'length' in field_to_add:
                    gp.addfield_management(output_risk_table, field_to_add['fieldname'], field_to_add['fieldtype'], "#", "#", field_to_add['length'])
                else:
                    gp.addfield_management(output_risk_table, field_to_add['fieldname'], field_to_add['fieldtype'])

        turtlebase.arcgis.write_result_to_output(output_risk_table, gpgident, risk_result)
        #----------------------------------------------------------------------------------------
        # Delete temporary workspace geodatabase & ascii files
        try:
            log.debug("delete temporary workspace: %s" % workspace_gdb)
            gp.delete(workspace_gdb)

            log.info("workspace deleted")
        except:
            log.debug("failed to delete %s" % workspace_gdb)

        tempfiles = os.listdir(workspace)
        for tempfile in tempfiles:
            if tempfile.endswith('.asc') or tempfile.endswith('.prj') :
                try:
                    os.remove(os.path.join(workspace, tempfile))
                    log.debug("%s/%s removed" % (workspace, tempfile))
                except Exception, e:
                    log.debug(e)

        mainutils.log_footer()
Exemple #16
0
def main():
    try:
        gp = mainutils.create_geoprocessor()
        config = mainutils.read_config(__file__, 'turtle-settings.ini')
        logfile = mainutils.log_filename(config)
        logging_config = LoggingConfig(gp, logfile=logfile)
        mainutils.log_header(__name__)

        # --------------------------------------------------------------------
        # Create workspace
        workspace = config.get('GENERAL', 'location_temp')
        if workspace == "-":
            workspace = tempfile.gettempdir()

        turtlebase.arcgis.delete_old_workspace_gdb(gp, workspace)

        if not os.path.isdir(workspace):
            os.makedirs(workspace)
        workspace_gdb, errorcode = (
            turtlebase.arcgis.create_temp_geodatabase(gp, workspace))
        if errorcode == 1:
            log.error("failed to create a file geodatabase in %s" % workspace)

        # --------------------------------------------------------------------
        # check inputfields
        log.info("Getting commandline parameters")

        if len(sys.argv) == 6:
            input_peilgebieden = sys.argv[1]
            input_waterlevel_table = sys.argv[2]
            input_ahn_raster = sys.argv[3]
            output_inundation = sys.argv[4]
            output_folder_waterlevel = sys.argv[5]
        else:
            log.error("Usage: python rural_inundatie.py <peilgebieden feature>\
                <input_waterlevel_table> <input_ahn_raster> <output grid>")
            sys.exit(1)

        # --------------------------------------------------------------------
        #check input parameters
        log.info('Checking presence of input files')
        if not(gp.exists(input_peilgebieden)):
            log.error("inputfile peilgebieden: %s does not exist!",
                      input_peilgebieden)
            sys.exit(5)
        if not(gp.exists(input_waterlevel_table)):
            log.error("inputfile resultaten: %s does not exist!",
                      input_waterlevel_table)
            sys.exit(5)
        if not(gp.exists(input_ahn_raster)):
            log.error("inputfile hoogtegrid: %s does not exist!",
                      input_ahn_raster)
            sys.exit(5)

        log.info('input parameters checked')
        # --------------------------------------------------------------------
        # Check geometry input parameters
        cellsize = gp.describe(input_ahn_raster).MeanCellHeight

        log.info("Check geometry of input parameters")
        geometry_check_list = []

        log.debug(" - check level areas: %s" % input_peilgebieden)
        if gp.describe(input_peilgebieden).ShapeType != 'Polygon':
            log.error("Input level area is not a polygon feature class!")
            geometry_check_list.append(input_peilgebieden + " -> (Polygon)")

        log.debug(" - check ahn raster %s" % input_ahn_raster)
        if gp.describe(input_ahn_raster).DataType != 'RasterDataset':
            log.error("Input AHN is not a raster dataset")
            sys.exit(1)

        if gp.describe(input_ahn_raster).PixelType[0] not in ['U', 'S']:
            log.error("Input AHN is a floating point raster,\
             for this script an integer is nessecary")
            geometry_check_list.append(input_ahn_raster + " -> (Integer)")

        if len(geometry_check_list) > 0:
            log.error("check input: %s" % geometry_check_list)
            sys.exit(2)

        log.info('input format checked')
        #---------------------------------------------------------------------
        # Check required fields in input data
        log.info("Check required fields in input data")
        gpgident = config.get('General', 'gpgident')

        missing_fields = []

        # create return period list
        return_periods = config.get(
            'Inundatie', 'herhalingstijden').split(", ")
        log.debug(" - return periods: %s" % return_periods)

        # <check required fields from input data,
        # append them to list if missing>"
        if not turtlebase.arcgis.is_fieldname(
                    gp, input_peilgebieden, gpgident):
            log.debug(" - missing: %s in %s",
                      (gpgident, input_peilgebieden))
            missing_fields.append("%s: %s",
                    (input_peilgebieden, gpgident))

        if not turtlebase.arcgis.is_fieldname(
                gp, input_waterlevel_table, gpgident):
            log.debug(" - missing: %s in %s",
                      (gpgident, input_waterlevel_table))
            missing_fields.append("%s: %s",
                    (input_waterlevel_table, gpgident))

        for return_period in return_periods:
            if not turtlebase.arcgis.is_fieldname(
                    gp, input_waterlevel_table, "WS_%s" % return_period):
                log.debug(" - missing: %s in %s" % ("WS_%s",
                                return_period, input_waterlevel_table))
                missing_fields.append("%s: %s",
                        (input_waterlevel_table, "WS_%s" % return_period))

        if len(missing_fields) > 0:
            log.error("missing fields in input data: %s" % missing_fields)
            sys.exit(2)

        #---------------------------------------------------------------------
        # Environments
        log.info("Setting environments")
        temp_peilgebieden = (
                turtlebase.arcgis.get_random_file_name(workspace_gdb))
        log.debug(" - export level areas")
        gp.select_analysis(input_peilgebieden, temp_peilgebieden)

        # use extent from level areas
        gp.extent = gp.describe(temp_peilgebieden).extent

        # add waterlevel to peilgebieden
        log.info("Read waterlevels from table")
        waterlevel_dict = nens.gp.get_table(
            gp, input_waterlevel_table, primary_key=gpgident.lower())
        join_waterlevel_to_level_area(
                    gp, temp_peilgebieden, gpgident,
                    return_periods, waterlevel_dict)

        #---------------------------------------------------------------------
        log.info("A) Create rasters for waterlevels")
        # Create waterlevel rasters
        if output_folder_waterlevel == "#":
            output_folder_waterlevel = workspace_gdb

        for return_period in return_periods:
            log.info(" - create raster for ws_%s" % return_period)
            out_raster_dataset = os.path.join(
                                    output_folder_waterlevel,
                                     "ws_%s" % return_period)
            if not gp.exists(out_raster_dataset):
                input_field = "WS_%s" % return_period
                gp.FeatureToRaster_conversion(temp_peilgebieden,
                                              input_field,
                                              out_raster_dataset,
                                              int(cellsize))
            else:
                log.error("output waterlevel raster already exists,\
                delete this first or change output folder")
                sys.exit(1)

        #---------------------------------------------------------------------
        log.info("B) Create Inundation raster")
        inundation_raster_list = []

        # create ahn ascii
        ahn_ascii = turtlebase.arcgis.get_random_file_name(workspace, ".asc")
        log.debug("ahn ascii: %s" % ahn_ascii)
        gp.RasterToASCII_conversion(input_ahn_raster, ahn_ascii)

        # inundatie stedelijk
        return_period_urban = config.get(
            'Inundatie', 'herhalingstijd_inundatie_stedelijk')
        if config.get('Inundatie', 'percentage_inundatie_stedelijk') != "-":
            log.debug(" - create inundation urban")
            waterlevel = "%s/ws_%s" % (
                output_folder_waterlevel, return_period_urban)
            if gp.exists(waterlevel):
                inundation_urban = turtlebase.arcgis.get_random_file_name(
                                                          workspace, ".asc")
                turtlebase.spatial.create_inundation_raster(
                                    ahn_ascii, ahn_ascii, waterlevel, 1,
                                    return_period_urban, inundation_urban,
                                    workspace, use_lgn=False)
                inundation_raster_list.append(inundation_urban)
            else:
                log.error("%s does not exists! check ini-file and tempfolder",
                        waterlevel)

        # inundatie hoogwaardige landbouw
        return_period_agriculture = config.get(
            'Inundatie', 'herhalingstijd_inundatie_hoogwaardig')
        if config.get('Inundatie', 'percentage_inundatie_hoogwaardig') != "-":
            log.debug(" - create inundation agriculture")
            waterlevel = "%s/ws_%s" % (
                        output_folder_waterlevel, return_period_agriculture)
            if gp.exists(waterlevel):
                # Inundation with lgn
                inundation_agriculture = (
                    turtlebase.arcgis.get_random_file_name(
                                            workspace, ".asc"))
                turtlebase.spatial.create_inundation_raster(
                                    ahn_ascii, ahn_ascii, waterlevel,
                                    2, return_period_agriculture,
                                    inundation_agriculture, workspace,
                                    use_lgn=False)
                inundation_raster_list.append(inundation_agriculture)
            else:
                log.error("%s does not exists! check ini-file and tempfolder",
                          waterlevel)

        # inundatie akkerbouw
        return_period_rural = config.get(
            'Inundatie', 'herhalingstijd_inundatie_akker')
        if config.get('Inundatie', 'percentage_inundatie_akker') != "-":
            log.debug(" - create inundation rural")
            waterlevel = "%s/ws_%s" % (
                output_folder_waterlevel, return_period_rural)
            if gp.exists(waterlevel):
                inundation_rural = turtlebase.arcgis.get_random_file_name(
                                                        workspace, ".asc")
                turtlebase.spatial.create_inundation_raster(
                                ahn_ascii, ahn_ascii, waterlevel,
                                3, return_period_rural, inundation_rural,
                                workspace, use_lgn=False)
                inundation_raster_list.append(inundation_rural)
            else:
                log.error("%s does not exists! check ini-file and tempfolder",
                          waterlevel)

        # inundatie grasland
        return_period_grass = config.get(
            'Inundatie', 'herhalingstijd_inundatie_grasland')
        if config.get('Inundatie', 'percentage_inundatie_grasland') != "-":
            log.debug(" - create inundation grass")
            waterlevel = ("%s/ws_%s" % (
                            output_folder_waterlevel,
                            return_period_grass))
            if gp.exists(waterlevel):
                inundation_grass = turtlebase.arcgis.get_random_file_name(
                                                        workspace, ".asc")
                turtlebase.spatial.create_inundation_raster(
                                ahn_ascii, ahn_ascii, waterlevel,
                                4, return_period_grass, inundation_grass,
                                workspace, use_lgn=False)
                inundation_raster_list.append(inundation_grass)
            else:
                log.error("%s does not exists! check ini-file and tempfolder",
                          waterlevel)

        if len(inundation_raster_list) > 1:
            log.info(" - merge inundation rasters")
            turtlebase.spatial.merge_ascii(
                inundation_raster_list, output_inundation, workspace)
        else:
            log.error("there are no inundation rasters available")

        #---------------------------------------------------------------------
        # Delete temporary workspace geodatabase & ascii files
        try:
            log.debug("delete temporary workspace: %s" % workspace_gdb)
            #gp.delete(workspace_gdb)

            log.info("workspace deleted")
        except:
            log.warning("failed to delete %s" % workspace_gdb)

        tempfiles = os.listdir(workspace)
        for tempfile in tempfiles:
            if tempfile.endswith('.asc'):
                try:
                    os.remove(os.path.join(workspace, tempfile))
                except Exception, e:
                    log.debug(e)

        mainutils.log_footer()
def main():
    try:
        gp = mainutils.create_geoprocessor()
        config = mainutils.read_config(__file__, 'turtle-settings.ini')
        logfile = mainutils.log_filename(config)
        logging_config = LoggingConfig(gp, logfile=logfile)
        mainutils.log_header(__name__)

        #read conversion settings
        modeltype = "RR+RR_CF"

        #---------------------------------------------------------------------
        #check inputfields
        log.info("Getting commandline parameters")

        if len(sys.argv) == 8:
            peilgebieden_feature = sys.argv[1]
            rr_dataset = sys.argv[2]
            afvoerkunstwerken = sys.argv[4]
            koppelpunten = sys.argv[5]
            settings = sys.argv[6]
            output_dir = sys.argv[7]
        else:
            log.error("Usage: python rural_rr_rrcf_conversie.py \
            <peilgebieden_feature> <rr_dataset> <rr_afvoer> \
            <afvoerkunstwerken> <koppelpunten> <settings>")
            sys.exit(1)

        rr_dataset = rr_dataset.replace("\\", "/")
        rr_dataset = rr_dataset.replace("'", "")
        sys.argv[2] = rr_dataset

        log.info("output_dir: " + output_dir)

        #add extra logfile
        fileHandler2 = logging.FileHandler(output_dir + '\\rr_rrcf_convert.log')
        logging.getLogger("nens.turtle").addHandler(fileHandler2)

        #---------------------------------------------------------------------
        #check input parameters
        log.info('Checking presence of input files')
        if not(gp.exists(peilgebieden_feature)):
            log.error("input_toetspunten " + peilgebieden_feature + " does not exist!")
            sys.exit(5)

        #----------------------------------------------------------------------------------------
        #default settings
        if settings == "#":
            location_script = os.path.dirname(sys.argv[0])
            settings = os.path.join(location_script, config.get('RR', 'rr_rrcf_default_settings'))

        rr_config = mainutils.read_config(settings, os.path.basename(settings))

        if not rr_config.get("column.peilgebied", 'paved_runoff_coefficient'):
            log.warning("paved_runoff_coefficient not available in rr+rrcf-settings, default will be used")
            rr_config.set("column.peilgebied", 'paved_runoff_coefficient', "-")
            rr_config.set("default.peilgebied", 'paved_runoff_coefficient', '0.2')

        #----------------------------------------------------------------------------------------
        # Create workspace
        workspace = config.get('GENERAL', 'location_temp')

        configfilename = os.path.join(workspace, "rr_rrcf_settings_temp.ini")
        configfile = open(configfilename, "wb")
        rr_config.write(configfile)
        configfile.close()
        settings = configfilename
        #----------------------------------------------------------------------------------------
        #checking if feature class contains polygons
        log.info("Checking if feature contains polygons")
        pg_obj = gp.describe(peilgebieden_feature)
        if pg_obj.ShapeType != "Polygon":
            log.error(peilgebieden_feature + " does not contain polygons, please add a feature class with polygons")
            log.error(" - gp message: " + gp.GetMessages(2))
            sys.exit(5)

        # If rr_afvoer is empty, ignore this table, because trrrlib will crash
        if sys.argv[3] != '#':
            if turtlebase.arcgis.fc_is_empty(gp, sys.argv[3]):
                log.warning("rr_afvoer is empty, this table will be ignored")
                sys.argv[3] = '#'

        # add xy coordinates
        xcoord = 'XCOORD'
        ycoord = 'YCOORD'
        if not turtlebase.arcgis.is_fieldname(gp, peilgebieden_feature, xcoord):
            gp.addfield(peilgebieden_feature, xcoord, "Double")
        if not turtlebase.arcgis.is_fieldname(gp, peilgebieden_feature, ycoord):
            gp.addfield(peilgebieden_feature, ycoord, "Double")
        add_xy_coords(gp, peilgebieden_feature, xcoord, ycoord)

        #checking if feature class contains points
        if afvoerkunstwerken != "#":
            log.info("Checking if feature contains points")
            ak_obj = gp.describe(afvoerkunstwerken)
            log.debug("ShapeType afvoerkunstwerken = " + ak_obj.ShapeType)
            if ak_obj.ShapeType != "Point":
                log.error(afvoerkunstwerken + " does not contain points, please add a feature class with points")
                log.error(" - gp message: " + gp.GetMessages(2))
                sys.exit(5)

        #check op punten
        if koppelpunten != "#":
            log.info("Checking if feature contains points")
            kp_obj = gp.describe(koppelpunten)
            log.debug("ShapeType koppelpunten = " + kp_obj.ShapeType)
            if kp_obj.ShapeType != "Point":
                log.error(koppelpunten + " does not contain points, please add a feature class with points")
                log.debug(gp.GetMessages(2))
                sys.exit()

        #copy settings to output directory
        shutil.copyfile(settings, output_dir + '\\RR_RRCF_Settings.ini')

        drainage = config.get('RR', 'drainage')
        log.info("drainage type is " + drainage)

        #export rrcf connection to output folder. Convert feature class to shape
        output_shapefiles = output_dir + '\\shapefiles'
        if not os.path.isdir(output_shapefiles):
            os.makedirs(output_shapefiles)
        log.debug("export rrcf connection nodes to" + output_shapefiles)

        gp.Select_analysis(koppelpunten, output_shapefiles + "\\rrcf_connection.shp")
        log.debug("features exported")

        output_sobek = output_dir + "\\sobek_input"
        if not os.path.isdir(output_sobek):
            os.makedirs(output_sobek)

        log.debug("from trrrlib import trrrlib")
        trrrlib.main({}, sys.argv[1:6] + [settings] + [output_sobek] + [drainage] + [modeltype])
        if os.path.isfile(output_sobek + "/struct.def"):
            os.remove(output_sobek + "/struct.def")
        if os.path.isfile(output_sobek + "/profile.dat"):
            os.remove(output_sobek + "/profile.dat")
        log.info("*********************************************************")
        log.info(modeltype + " Conversie compleet")
        log.info("*********************************************************")

        mainutils.log_footer()
    except:
        log.error(traceback.format_exc())
        sys.exit(1)

    finally:
        logging_config.cleanup()
        del gp
def main():
    try:
        gp = mainutils.create_geoprocessor()
        config = mainutils.read_config(__file__, 'turtle-settings.ini')
        logfile = mainutils.log_filename(config)
        logging_config = LoggingConfig(gp, logfile=logfile)
        mainutils.log_header(__name__)

        #---------------------------------------------------------------------
        # Input parameters
        if len(sys.argv) == 5:
            input_watergangen = sys.argv[1]
            procent = sys.argv[2]
            max_distance = sys.argv[3]
            output_profiles = sys.argv[4]
        else:
            log.warning("usage: <input_watergangen> <procent> <max_distance> <output_profiles>")
            sys.exit(1)
        
        percentage = float(procent) / 100

        gp.CreateFeatureclass_management(os.path.dirname(output_profiles), os.path.basename(output_profiles), "POINT")
        gp.AddField_management(output_profiles, "LOCIDENT", "TEXT")
        gp.AddField_management(output_profiles, "PROIDENT", "TEXT")
    
        in_rows = gp.SearchCursor(input_watergangen)
        in_row = in_rows.Next()
        out_rows = gp.InsertCursor(output_profiles)
        pnt = gp.CreateObject("Point")
        
        inDesc = gp.describe(input_watergangen)
        log.info("draw profiles")
        while in_row:
            ident = in_row.GetValue("OVKIDENT")
            log.info("- %s" % ident)
        
            feat = in_row.GetValue(inDesc.ShapeFieldName)
        
            lengte = feat.length
        
            part = feat.getpart(0)
            pnt_list = [(float(pnt.x), float(pnt.y)) for pnt in nens.gp.gp_iterator(part)]
        
            XY = calculate_sp(percentage, max_distance, lengte, pnt_list)
            pnt.X = XY[0]
            pnt.Y = XY[1]
        
            out_row = out_rows.newRow()
            out_row.shape = pnt
            out_row.setValue("PROIDENT", ident)
            out_row.setValue("LOCIDENT", "%s_a" % ident)
            out_rows.insertRow(out_row)
        
            pnt_list.reverse()
            XY = calculate_sp(percentage, max_distance, lengte, pnt_list)
            pnt.X = XY[0]
            pnt.Y = XY[1]
        
            out_row = out_rows.newRow()
            out_row.shape = pnt
            out_row.setValue("PROIDENT", ident)
            out_row.setValue("LOCIDENT", "%s_b" % ident)
            out_rows.insertRow(out_row)
            in_row = in_rows.Next()
        
        del out_rows
        del in_rows
        
        mainutils.log_footer()
    except:
        log.error(traceback.format_exc())
        sys.exit(1)

    finally:
        logging_config.cleanup()
        del gp
def main():
    try:
        gp = mainutils.create_geoprocessor()
        config = mainutils.read_config(__file__, 'turtle-settings.ini')
        logfile = mainutils.log_filename(config)
        logging_config = LoggingConfig(gp, logfile=logfile)
        mainutils.log_header(__name__)

        #----------------------------------------------------------------------------------------
        # Create workspace
        workspace = config.get('GENERAL', 'location_temp')
        if workspace == "-":
            workspace = tempfile.gettempdir()

        turtlebase.arcgis.delete_old_workspace_gdb(gp, workspace)

        if not os.path.isdir(workspace):
            os.makedirs(workspace)
        workspace_gdb, errorcode = turtlebase.arcgis.create_temp_geodatabase(gp, workspace)
        if errorcode == 1:
            log.error("failed to create a file geodatabase in %s" % workspace)

        #----------------------------------------------------------------------------------------
        # Input parameters
        if len(sys.argv) == 5:
            # input parameter
            input_external_weir = sys.argv[1]
            input_voronoi_polygon = sys.argv[2]
            input_rrcf_waterlevel = sys.argv[3]
            # output parameters
            output_table_external_weir = sys.argv[4]
        else:
            log.error("usage: <input_external_weir> <input_voronoi_polygon> <input rrcf waterlevel> <output_table_external_weir>")
            sys.exit(1)

        temp_voronoi = turtlebase.arcgis.get_random_file_name(workspace_gdb)
        gp.select_analysis(input_voronoi_polygon, temp_voronoi)
        #----------------------------------------------------------------------------------------
        # Check geometry input parameters
        log.info("Check geometry of input parameters")
        geometry_check_list = []

        log.debug(" - check input_external_weir: %s" % input_external_weir)
        if gp.describe(input_external_weir).ShapeType != 'Point':
            log.error("Input_external_weir is not a point feature class!")
            geometry_check_list.append(input_external_weir + " -> (Point)")

        log.debug(" - check voronoi polygon: %s" % temp_voronoi)
        if gp.describe(temp_voronoi).ShapeType != 'Polygon':
            log.error("Input voronoi is not a polygon feature class!")
            geometry_check_list.append(temp_voronoi + " -> (Polygon)")

        if len(geometry_check_list) > 0:
            log.error("check input: %s" % geometry_check_list)
            sys.exit(2)
        #----------------------------------------------------------------------------------------
        # Check required fields in database
        log.info("Check required fields in input data")

        missing_fields = []
        if not turtlebase.arcgis.is_fieldname(gp, temp_voronoi, config.get('toetsing_overstorten', 'calculation_point_ident')):
            log.debug(" - missing: %s in %s" % (config.get('toetsing_overstorten', 'calculation_point_ident'), temp_voronoi))
            missing_fields.append("%s: %s" % (temp_voronoi, config.get('toetsing_overstorten', 'calculation_point_ident')))

        if not turtlebase.arcgis.is_fieldname(gp, input_rrcf_waterlevel, config.get('toetsing_overstorten', 'field_waterstand')):
            log.debug(" - missing: %s in %s" % (config.get('toetsing_overstorten', 'field_waterstand'), input_rrcf_waterlevel))
            missing_fields.append("%s: %s" % (input_rrcf_waterlevel, config.get('toetsing_overstorten', 'field_waterstand')))

        if not turtlebase.arcgis.is_fieldname(gp, input_external_weir, config.get('toetsing_overstorten', 'overstort_ident')):
            log.debug(" - missing: %s in %s" % (config.get('toetsing_overstorten', 'overstort_ident'), input_external_weir))
            missing_fields.append("%s: %s" % (input_external_weir, config.get('toetsing_overstorten', 'overstort_ident')))

        if not turtlebase.arcgis.is_fieldname(gp, input_external_weir, config.get('toetsing_overstorten', 'drempelhoogte')):
            log.debug(" - missing: %s in %s" % (config.get('toetsing_overstorten', 'drempelhoogte'), input_external_weir))
            missing_fields.append("%s: %s" % (input_external_weir, config.get('toetsing_overstorten', 'drempelhoogte')))

        if len(missing_fields) > 0:
            log.error("missing fields in input data: %s" % missing_fields)
            sys.exit(2)

        #----------------------------------------------------------------------------------------
        # read waterlevel table as a dictionary
        log.info("Read waterlevel table")
        waterlevel_dict = nens.gp.get_table(gp, input_rrcf_waterlevel, primary_key=config.get('toetsing_overstorten', 'calculation_point_ident').lower())
        log.debug(waterlevel_dict)

        # Add fields to output
        if not turtlebase.arcgis.is_fieldname(gp, temp_voronoi, config.get('toetsing_overstorten', 'field_waterstand')):
            log.info(" - add field %s" % config.get('toetsing_overstorten', 'field_waterstand'))
            gp.addfield(temp_voronoi, "%s" % config.get('toetsing_overstorten', 'field_waterstand'), "double")

        
        # copy waterlevel to voronoi polygons
        field_config_waterstand = config.get('toetsing_overstorten', 'field_waterstand').lower()
        field_calculation_point_ident = config.get('toetsing_overstorten', 'calculation_point_ident')
        
        rows = gp.UpdateCursor(temp_voronoi)
        for row in nens.gp.gp_iterator(rows):
            row_id = row.GetValue(field_calculation_point_ident)
            
            if waterlevel_dict.has_key(row_id):
                log.debug(waterlevel_dict[row_id])
                row.SetValue(field_config_waterstand, waterlevel_dict[row_id][field_config_waterstand])

                rows.UpdateRow(row)

        #----------------------------------------------------------------------------------------
        # Join external weirs to voronoi using spatial location (spatial join)
        log.info("join waterlevel to external weirs using a spatial location")
        temp_spatial_join = turtlebase.arcgis.get_random_file_name(workspace_gdb)
        #gp.SpatialJoin_analysis(input_external_weir, temp_voronoi, temp_spatial_join, "JOIN_ONE_TO_ONE", "#", "#", "INTERSECTS")
        gp.Intersect_Analysis(input_external_weir + ';' + temp_voronoi, temp_spatial_join)
        
        external_weir_dict = nens.gp.get_table(gp, temp_spatial_join, primary_key=config.get('toetsing_overstorten', 'overstort_ident').lower())

        result_dict = {}
        for k, v in external_weir_dict.items():
            waterlevel = v[config.get('toetsing_overstorten', 'field_waterstand').lower()]
            weir_height = v[config.get('toetsing_overstorten', 'drempelhoogte').lower()]
            if waterlevel is None or weir_height is None:
                waterlevel = -999
                weir_height = -999
                result_value = 9
            else:
                if float(waterlevel) > float(weir_height):
                    result_value = 1
                else:
                    result_value = 0

            result_dict[k] = {config.get('toetsing_overstorten', 'overstort_ident'): k,
                              config.get('toetsing_overstorten', 'field_waterstand'): waterlevel,
                              config.get('toetsing_overstorten', 'drempelhoogte'): weir_height,
                              config.get('toetsing_overstorten', 'field_toetsing_overlast_stedelijk'): result_value}
        #----------------------------------------------------------------------------------------
        # Create output table
        if not gp.exists(output_table_external_weir):
            log.info("Create new output table")
            temp_result_table = turtlebase.arcgis.get_random_file_name(workspace_gdb)
            gp.CreateTable_management(os.path.dirname(temp_result_table), os.path.basename(temp_result_table))
            copy_table = True
        else:
            temp_result_table = output_table_external_weir
            copy_table = False

        fields_to_add = [config.get('toetsing_overstorten', 'field_waterstand'),
                         config.get('toetsing_overstorten', 'drempelhoogte'),
                         config.get('toetsing_overstorten', 'field_toetsing_overlast_stedelijk')]

        if not turtlebase.arcgis.is_fieldname(gp, temp_result_table, config.get('toetsing_overstorten', 'overstort_ident')):
            log.debug(" - add field %s to %s" % (config.get('toetsing_overstorten', 'overstort_ident'), temp_result_table))
            gp.addfield_management(temp_result_table, config.get('toetsing_overstorten', 'overstort_ident'), 'text')

        for field in fields_to_add:
            if not turtlebase.arcgis.is_fieldname(gp, temp_result_table, field):
                log.debug(" - add field %s to %s" % (field, temp_result_table))
                gp.addfield_management(temp_result_table, field, 'double')

        #----------------------------------------------------------------------------------------
        # Write results to output table
        log.info("Write results to output table")
        turtlebase.arcgis.write_result_to_output(temp_result_table, config.get('toetsing_overstorten', 'overstort_ident').lower(), result_dict)

        if copy_table == True:
            gp.TableToTable_conversion(temp_result_table, os.path.dirname(output_table_external_weir), os.path.basename(output_table_external_weir))

        #----------------------------------------------------------------------------------------
        # Delete temporary workspace geodatabase
        try:
            log.debug("delete temporary workspace: %s" % workspace_gdb)
            gp.delete(workspace_gdb)

            log.info("workspace deleted")
        except:
            log.debug("failed to delete %s" % workspace_gdb)

        mainutils.log_footer()
    except:
        log.error(traceback.format_exc())
        sys.exit(1)

    finally:
        logging_config.cleanup()
        del gp