def Segmentar(self):

        if (len(self.data) == 0):
            self.ObtenerZonasPrueba()

        if (len(self.data) > 0):
            self.where_expression = expresiones_consulta_arcpy.Expresion(
                self.data, self.campos)
            print datetime.today()

            self.ObtenerInformacionPrueba()

            print datetime.today()
            self.OrdenarManzanasFalsoCod()
            print datetime.today()
            self.EnumerarAEUEnViviendasDeManzanas()
            print datetime.today()
            self.CrearAEUS()
            print datetime.today()
            if (self.techo_segunda_pasada_gra_ciud > 0
                    and self.techo_segunda_pasada_peq_ciud > 0):
                print 'segunda pasada'
                self.SegundaPasada()
                print datetime.today()
                self.CrearAEUSSegundaPasada()
                print datetime.today()

            self.InsertarRegistros()
            print datetime.today()

        return len(self.data)
def viviendas(data,campos):
    sql = expresion.Expresion(data, campos)

    conn = conx.Conexion2()
    cursor = conn.cursor()

    sql_query = """select  * from sde.VW_VIVIENDAS_U WHERE {} ORDER BY UBIGEO,ZONA,AEU,FALSO_COD,ID_REG_OR """.format(sql)

    cursor.execute(sql_query)

    list_viv = []
    for row in cursor:
        list_viv.append(row)


    arcpy.CreateTable_management(path_ini, 'tb_vivienda.dbf')


    list_fields = [['UBIGEO', 'TEXT'], ['ZONA', 'TEXT'], ['MANZANA', 'TEXT'], ['FRENTE_ORD', 'SHORT'] ,['ID_REG_OR', 'SHORT'],['AEU', 'TEXT'],
                   ['OR_VIV_AEU', 'SHORT'],['FASE','TEXT'],['P20','TEXT'],['P21','TEXT'],['P22_A','TEXT'],['P23','TEXT'],
                   ['P24','TEXT'],['P25','TEXT'],['P26','TEXT'],['P27_A','TEXT'],['P28','TEXT'],['P32','TEXT'],['FALSO_COD','SHORT']
                   ]
    for field in list_fields:
        arcpy.AddField_management(tb_viviendas_ordenadas, field[0], field[1])

    cursor_insert = arcpy.da.InsertCursor(tb_viviendas_ordenadas,
                                          ['UBIGEO', 'ZONA', 'MANZANA','FRENTE_ORD', 'ID_REG_OR', 'AEU','OR_VIV_AEU','FASE','P20','P21','P22_A','P23','P24','P25','P26','P27_A','P28','P32','FALSO_COD']
                                          )

    for x in list_viv:
        cursor_insert.insertRow(x)

    conn.close()
 def __init__(self,
              cant_viv_techo_gra_ciud=16,
              cant_viv_techo_peq_ciud=16,
              techo_segunda_pasada_gra_ciud=16,
              techo_segunda_pasada_peq_ciud=16,
              cant_zonas_x=10,
              data_x=[],
              uso_falso_cod=1,
              campos_x=["UBIGEO", "ZONA"],
              cant_viv_eleg_segund_pasada=9):
     #self.cant_viv_techo=cant_viv_techo_x
     #print sys.path
     self.data = data_x[:]
     self.cant_zonas = cant_zonas_x
     self.cant_viv_techo_gra_ciud = cant_viv_techo_gra_ciud
     self.cant_viv_techo_peq_ciud = cant_viv_techo_peq_ciud
     self.techo_segunda_pasada_gra_ciud = techo_segunda_pasada_gra_ciud
     self.techo_segunda_pasada_peq_ciud = techo_segunda_pasada_peq_ciud
     self.campos = campos_x
     self.uso_falso_cod = uso_falso_cod
     #############conexion##############################
     self.connx = pymssql.connect(self.server, self.user, self.password,
                                  self.database)
     #################borra####################
     #shutil.rmtree(path=self.path_segmentacion)
     self.CrearCarpetasSegmentacion()
     self.cant_viv_eleg_segund_pasada = cant_viv_eleg_segund_pasada
     if len(data_x) > 0:
         self.where_expression = expresiones_consulta_arcpy.Expresion(
             data_x, campos_x)
def crear_carpetas_exportacion(data,campos):
    arcpy.env.workspace = path_ini
    paths_ini = [

        path_croquis,
        path_listados,

    ]
    paths = [

        path_urbano_croquis,
        path_urbano_listados,



    ]

    for path in paths_ini:
        if os.path.exists(path) == False:
            os.mkdir(path)
    for path in paths:
        if os.path.exists(path) == False:
            os.mkdir(path)
    for el in data:
        for path in paths:
            if os.path.exists(path + "\\" + str(el[0])) == False:
                os.mkdir(path + "\\" + str(el[0]))

    where_expression = expresion.Expresion(data, campos)

    with arcpy.da.SearchCursor(tb_zonas, ['UBIGEO', 'ZONA'], where_expression) as cursor:
        for row in cursor:
            for path in paths:

                if os.path.exists(path + "\\" + str(row[0]) + "\\" + str(row[1])) == False:
                    os.mkdir(path + "\\" + str(row[0]) + "\\" + str(row[1]))

                else:
                    shutil.rmtree(path + "\\" + str(row[0]) + "\\" + str(row[1]))
                    os.mkdir(path + "\\" + str(row[0]) + "\\" + str(row[1]))
def importar_tablas_corregidas(data,campos):
    arcpy.env.overwriteOutput = True
    if arcpy.Exists("CPV_SEGMENTACION2.sde") == False:
        arcpy.CreateDatabaseConnection_management("Database Connections",
                                                  "CPV_SEGMENTACION2.sde",
                                                  "SQL_SERVER",
                                                  ip_server,
                                                  "DATABASE_AUTH",
                                                  "us_arcgis_seg_2",
                                                  "MBs0p0rt301",
                                                  "#",
                                                  "CPV_SEGMENTACION",
                                                  "#",
                                                  "#",
                                                  "#",
                                                  "#")
    arcpy.env.workspace = "Database Connections/CPV_SEGMENTACION2.sde"
    path_conexion="Database Connections/CPV_SEGMENTACION2.sde"
    where_expression=expresion.Expresion(data, campos)


    temp_ubigeos = ""
    i=0
    for x in data:
        i=i+1
        if (i==1):
            temp_ubigeos="'{}'".format(x[0])
        else:
            temp_ubigeos = "{},'{}'".format(temp_ubigeos,x[0])


    print temp_ubigeos
    sql=expresion.Expresion(data, campos)
    manzanas_Layer = arcpy.MakeQueryLayer_management(path_conexion, 'TB_MZS',"SELECT geom,UBIGEO,CODCCPP,ZONA,MANZANA,VIV_MZ,FALSO_COD,MZS_COND,CANT_BLOCK FROM TB_MANZANA WHERE UBIGEO IN ({}) ".format(temp_ubigeos))
    zonas_Layer = arcpy.MakeQueryLayer_management(path_conexion, 'CPV_SEGMENTACION.dbo.VW_ZONA_CENSAL',"SELECT * FROM CPV_SEGMENTACION.dbo.VW_ZONA_CENSAL WHERE {} ".format(sql))
    eje_vial_Layer = arcpy.MakeQueryLayer_management(path_conexion, 'CPV_SEGMENTACION.dbo.TB_EJE_VIAL',"SELECT * FROM CPV_SEGMENTACION.dbo.TB_EJE_VIAL where UBIGEO IN  ({}) ".format(temp_ubigeos))
    #viviendas_Layer = arcpy.MakeQueryLayer_management(path_conexion, 'CPV_SEGMENTACION.dbo.VW_VIVIENDAS_U',"SELECT * FROM CPV_SEGMENTACION.dbo.VW_VIVIENDAS_U WHERE {} ".format(sql))
    #frentes_mfl = arcpy.MakeQueryLayer_management(path_conexion, 'CPV_SEGMENTACION.dbo.TB_FRENTES',"SELECT * FROM CPV_SEGMENTACION.dbo.VW_FRENTES WHERE {} ".format(sql))
    manzanas_mfl = arcpy.MakeFeatureLayer_management(manzanas_Layer,"manzanas_mfl")
    zonas_mfl=arcpy.MakeFeatureLayer_management(zonas_Layer, "zonas_mfl")
    eje_vial_mfl = arcpy.MakeFeatureLayer_management(eje_vial_Layer, "eje_vial_mfl")



    list_mfl=[[manzanas_mfl,tb_manzanas],
              #[frentes_mfl,tb_frentes]

              ]

    i=0
    for x in list_mfl:
        i=i+1
        temp= arcpy.CopyFeatures_management(x[0], 'in_memory/temp_{}'.format(i))
        arcpy.AddField_management(temp, 'MANZANA2', 'TEXT', 50)
        arcpy.CalculateField_management(temp, 'MANZANA2', '!MANZANA!', "PYTHON_9.3")
        arcpy.DeleteField_management(temp, ['MANZANA'])
        arcpy.CopyFeatures_management(temp, x[1])
        arcpy.AddField_management(x[1], 'MANZANA', 'TEXT', 50)
        arcpy.CalculateField_management(x[1], 'MANZANA', '!MANZANA2!', "PYTHON_9.3")
        arcpy.DeleteField_management(temp, ['MANZANA2'])

    arcpy.CopyFeatures_management(zonas_mfl, tb_zonas)
    arcpy.CopyFeatures_management(eje_vial_mfl, tb_ejes_viales)
    arcpy.TableToTable_conversion(path_conexion + '/CPV_SEGMENTACION.dbo.VW_MZS_CONDOMINIOS', path_ini,"tb_mzs_condominios.dbf")
    arcpy.env.workspace = path_ini+""
    arcpy.DeleteField_management(tb_manzanas, ['AEU','IDMANZANA'])
    arcpy.AddField_management(tb_manzanas, "IDMANZANA", "TEXT")
    expression = "(!UBIGEO!)+(!ZONA!)+(!MANZANA!)"
    arcpy.CalculateField_management(tb_manzanas, "IDMANZANA", expression, "PYTHON_9.3")
    arcpy.AddField_management(tb_manzanas, "AEU", "SHORT")
    arcpy.AddField_management(tb_manzanas, "AEU_2", "SHORT")
    arcpy.AddField_management(tb_manzanas, "FLG_MZ", "SHORT")
    arcpy.Dissolve_management(tb_frentes, tb_frentes_dissolve,['UBIGEO', 'ZONA', 'MANZANA', 'FRENTE_ORD'])


    database = "CPV_SEGMENTACION_GDB"
    if arcpy.Exists("{}.sde".format(database)) == False:
        arcpy.CreateDatabaseConnection_management("Database Connections",
                                                  "{}.sde".format(database),
                                                  "SQL_SERVER",
                                                  ip_server,
                                                  "DATABASE_AUTH",
                                                  "sde",
                                                  "$deDEs4Rr0lLo",
                                                  "#",
                                                  database,
                                                  "#",
                                                  "#",
                                                  "#",
                                                  "#")
    arcpy.env.workspace = "Database Connections/{}.sde".format(database)
    path_conexion2 = "Database Connections/{}.sde".format(database)

    list_capas=[
                ["{}.sde.SEGM_AEU".format(database),tb_aeus,2],
                ["{}.sde.SEGM_RUTA".format(database), tb_rutas, 2],

                ["{}.sde.SEGM_SECCION".format(database), tb_secciones, 1],
                ["{}.sde.SEGM_SITIOS_INTERES".format(database), tb_sitios_interes, 1],
                ["{}.sde.SEGM_SUBZONA".format(database), tb_subzonas, 2],
                ] ##capa orin, destino

    for i,capa in enumerate(list_capas):

        if capa[2]==1:
            #print 'aqui'

            #if capa[1]==tb_viviendas_ordenadas_temp:
            #    x = arcpy.MakeQueryLayer_management(path_conexion2, 'capa{}'.format(i),"select * from {} where {}".format(capa[0], sql))
#
            #else:
            x = arcpy.MakeQueryLayer_management(path_conexion2, 'capa{}'.format(i),"select * from {} where {} ".format(capa[0],sql))

        else:
            x = arcpy.MakeQueryTable_management(capa[0], "capa{}".format(i), "USE_KEY_FIELDS", "objectid", "", sql)


        if capa[1] in (tb_rutas,tb_rutas_puntos):
            #####tratamiento del campo manzana para las Ñ #####

            if capa[1] in (tb_rutas) :
                temp = arcpy.CopyRows_management(capa[0], 'in_memory/temp_m2{}'.format(i))
            else:
                temp = arcpy.CopyFeatures_management(capa[0], 'in_memory/temp_m{}'.format(i))


            arcpy.AddField_management(temp, 'MANZANA2', 'TEXT', 50)
            arcpy.CalculateField_management(temp, 'MANZANA2', '!MANZANA!', "PYTHON_9.3")
            arcpy.DeleteField_management(temp, ['MANZANA'])

            #####copiando archivos

            if capa[1] in (tb_rutas):
                print capa[1]
                temp = arcpy.CopyRows_management(temp, capa[1])
            else:
                temp = arcpy.CopyFeatures_management(temp, capa[1])

            arcpy.AddField_management(capa[1], 'MANZANA', 'TEXT', 50)
            arcpy.CalculateField_management(capa[1], 'MANZANA', '!MANZANA2!', "PYTHON_9.3")
            arcpy.DeleteField_management(capa[1], ['MANZANA2'])

            arcpy.AddField_management(capa[1], 'AEU2', 'TEXT', 3)
            arcpy.CalculateField_management(capa[1], 'AEU2', 'str(!AEU!).zfill(3)', "PYTHON_9.3")
            arcpy.DeleteField_management(capa[1], ['AEU'])
            arcpy.AddField_management(capa[1], 'AEU', 'TEXT', 3)
            arcpy.CalculateField_management(capa[1], 'AEU', '!AEU2!', "PYTHON_9.3")
            arcpy.DeleteField_management(capa[1], ['AEU2'])
        else:
            print capa[1]
            if capa[2] > 1:
                arcpy.CopyRows_management(x, capa[1])
            else:
                arcpy.CopyFeatures_management(x, capa[1])
        for path in paths:
            if os.path.exists(path + "\\" + str(el[0])) == False:
                os.mkdir(path + "\\" + str(el[0]))

    where_expression = expresion.Expresion(data, campos)

    with arcpy.da.SearchCursor(tb_zonas, ['UBIGEO', 'ZONA'], where_expression) as cursor:
        for row in cursor:
            for path in paths:

                if os.path.exists(path + "\\" + str(row[0]) + "\\" + str(row[1])) == False:
                    os.mkdir(path + "\\" + str(row[0]) + "\\" + str(row[1]))

                else:
                    shutil.rmtree(path + "\\" + str(row[0]) + "\\" + str(row[1]))
                    os.mkdir(path + "\\" + str(row[0]) + "\\" + str(row[1]))


data=[[ubigeox,zonax]]
campos=['UBIGEO','ZONA']




where1 = expresion.Expresion(data=[[ubigeox,zonax]], campos=['UBIGEO','ZONA'])
importar_tablas_corregidas(data=data, campos=campos)
crear_carpetas_exportacion(data=data,campos=campos)
ordenar_manzanas_cod_falso(where_expression=where1)

exportar_croquis_urbano_zona_subzona(where_expression=where1)
def exportar_croquis_aeu_corregidos(where_expression=''):
    arcpy.env.workspace = path_ini + ""
    with arcpy.da.UpdateCursor(tb_aeus, [
            "UBIGEO", "ZONA", "CODCCPP", "SECCION", "AEU", "CANT_VIV",
            'CANT_PAG', 'COD_CROQ', 'RUTA_CROQ', 'RUTA_WEB'
    ], where_expression) as cursor:

        for row in cursor:
            ubigeo = row[0]
            ccdd = ubigeo[0:2]
            ccpp = ubigeo[2:4]
            ccdi = ubigeo[4:6]
            zona = row[1]
            codccpp = row[2]
            zona_etiqueta = expresion.EtiquetaZona(zona)
            seccion = '{}'.format(row[3]).zfill(3)
            aeu = '{}'.format(row[4]).zfill(3)
            cant_viv = row[5]
            #######################################Creamos los filtros del AEU############################################################
            where_aeu = "UBIGEO ='{}' AND ZONA='{}' AND AEU='{}'".format(
                ubigeo, zona, aeu)
            where_seccion = "UBIGEO='{}' AND ZONA='{}' AND SECCION='{}'".format(
                ubigeo, zona, seccion)
            where_zona = "UBIGEO='{}' AND ZONA='{}'".format(ubigeo, zona)
            list_manzanas = [[x[0], x[1], x[2]] for x in arcpy.da.SearchCursor(
                tb_rutas, ["UBIGEO", "ZONA", "MANZANA"], where_aeu)]
            where_manzanas = expresion.Expresion(list_manzanas,
                                                 ["UBIGEO", "ZONA", "MANZANA"])
            for x in arcpy.da.SearchCursor(
                    tb_zonas,
                ['DEPARTAMEN', 'PROVINCIA', 'DISTRITO', 'NOMCCPP'],
                    where_zona):
                dep = x[0]
                prov = x[1]
                dist = x[2]
                nomccpp = x[3]
            for x in arcpy.da.SearchCursor(tb_secciones, ["SUBZONA"],
                                           where_seccion):
                subzona = x[0]
            codigo = "{}{}{}{}{}".format(ubigeo, zona, subzona, seccion, aeu)
            #########################################Listamos los layes del mxd #####################################
            mxd = arcpy.mapping.MapDocument(path_plantillas_croquis +
                                            "/CroquisUrbanoAEUCorregido.mxd")
            df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]

            arcpy.MakeFeatureLayer_management(tb_sitios_interes,
                                              "sitios_interes")

            lyrFile1 = arcpy.mapping.Layer("sitios_interes")
            arcpy.ApplySymbologyFromLayer_management(
                lyrFile1, path_plantillas_layers + "/sitios_interes.lyr")
            arcpy.mapping.AddLayer(df, lyrFile1)

            rutas_lineas_mfl = arcpy.mapping.ListLayers(
                mxd, "TB_RUTAS_LINEAS")[0]
            rutas_lineas_mfl.definitionQuery = where_aeu
            manzanas_mfl = arcpy.mapping.ListLayers(mxd, "TB_MZS_ORD")[0]
            manzanas_mfl.definitionQuery = where_manzanas

            frentes_mfl = arcpy.mapping.ListLayers(mxd, "TB_FRENTES")[0]
            frentes_mfl.definitionQuery = where_manzanas
            frentes_mfl_1 = arcpy.mapping.ListLayers(mxd, "TB_FRENTES_1")[0]
            frentes_mfl_1.definitionQuery = where_manzanas

            frentes_mfl_2 = arcpy.mapping.ListLayers(mxd, "TB_FRENTES_2")[0]
            frentes_mfl_2.definitionQuery = where_manzanas

            frentes_mfl_3 = arcpy.mapping.ListLayers(mxd, "TB_FRENTES_3")[0]
            frentes_mfl_3.definitionQuery = where_manzanas

            puntos_multifamiliar_mfl = arcpy.mapping.ListLayers(
                mxd, "TB_RUTAS_PUNTOS")[0]
            if arcpy.Exists(tb_rutas_lineas_multifamiliar):
                rutas_lineas_multifamiliar_mfl = arcpy.mapping.ListLayers(
                    mxd, "TB_RUTAS_LINEAS_MULTI")[0]
                rutas_lineas_multifamiliar_mfl.definitionQuery = where_aeu

            cant_rutas_lineas = int(
                arcpy.GetCount_management(rutas_lineas_mfl).getOutput(0))
            cant_manzanas = int(len(list_manzanas))
            if (cant_rutas_lineas == 0):
                puntos_multifamiliar_mfl.definitionQuery = where_aeu
            else:
                puntos_multifamiliar_mfl.definitionQuery = " AEU=-1"

            ################################################Obtemos la informacion del listado####################################################
            cabecera = [
                ccdd, dep, ccpp, prov, ccdi, dist, codccpp, nomccpp, 'CIUDAD',
                zona_etiqueta, subzona, seccion, aeu, cant_viv
            ]

            data = [[
                v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9],
                v[10], v[11], v[12], v[13]
            ] for v in arcpy.da.SearchCursor(tb_viviendas_ordenadas, [
                "OR_VIV_AEU", "MANZANA", "ID_REG_OR", "FRENTE_ORD", "P20",
                "P21", "P22_A", "P23", "P24", "P25", "P26", "P27_A", "P28",
                "P32"
            ], where_aeu)]

            list_data = []

            informacion = [cabecera, data]

            primera_puerta = data[0]

            ultima_puerta = data[-1]

            if (cant_manzanas <= 1):
                obs = u"<BOL>OBSERVACIONES: </BOL>El AEU N°{} comprende desde: {}{}{}{}{}{}{}{} hasta: {}{}{}{}{}{}{}{}.".format \
                    (aeu,
                     u"La  MZ N°{}".format(primera_puerta[1]),
                     u", {} {}".format(primera_puerta[4], primera_puerta[5]),
                     u", N° de puerta {}".format(primera_puerta[6]) if (
                         primera_puerta[6] != " " and primera_puerta[6] != " ") else "",
                     u", N° de block {}".format(primera_puerta[7]) if (
                         primera_puerta[7] != 0 and primera_puerta[7] != " ") else "",
                     u", Lote N°{}".format(primera_puerta[9]) if (
                         primera_puerta[9] != 0 and primera_puerta[9] != " ") else "",
                     u", Piso N°{}".format(primera_puerta[10]) if (
                         primera_puerta[10] != 0 and primera_puerta[10] != " ") else "",
                     u", Interior N°{}".format(primera_puerta[11]) if (
                         primera_puerta[11] != 0 and primera_puerta[11] != " ") else "",
                     u", {}".format(primera_puerta[13]),
                     u"La  MZ N°{}".format(ultima_puerta[1]),
                     u", {} {}".format(ultima_puerta[4], ultima_puerta[5]),
                     u", N° de puerta {}".format(ultima_puerta[6]) if (
                         ultima_puerta[6] != 0 and ultima_puerta[6] != " ") else "",
                     u", N° de block {}".format(ultima_puerta[7]) if (
                         ultima_puerta[7] != 0 and ultima_puerta[7] != " ")  else "",
                     u", Lote N°{}".format(ultima_puerta[9]) if (
                         ultima_puerta[9] != 0 and ultima_puerta[9] != " ") else "",
                     u", Piso N°{}".format(ultima_puerta[10]) if (
                         ultima_puerta[10] != 0 and ultima_puerta[10] != " ") else "",
                     u", Interior N°{}".format(ultima_puerta[11]) if (
                         ultima_puerta[11] != 0 and ultima_puerta[11] != " ")else "",
                     u", {}".format(ultima_puerta[13])
                     )
            else:

                j = 0
                obs_mzs = ''
                for manzana in list_manzanas:
                    if j == 0:
                        obs_mzs = u'{}'.format(manzana[2])
                    else:
                        obs_mzs = u'{},{}'.format(obs_mzs, manzana[2])
                    j = j + 1

                obs = u"<BOL>OBSERVACIONES: </BOL>El AEU N°{} comprende las manzanas  {} . ".format(
                    aeu, obs_mzs)

            #########################################Asignado los valores de las variables de los croquis ################################################
            list_text_el = [["COD_BARRA", "*{}*".format(codigo)],
                            ["TEXT_COD_BARRA", "*{}*".format(codigo)],
                            ["CCDD", ccdd], ["CCPP", ccpp], ["CCDI", ccdi],
                            ["CODCCPP", codccpp], ["DEPARTAMENTO", dep],
                            ["PROVINCIA", prov], ["DISTRITO", dist],
                            ["NOMCCPP", nomccpp], ["ZONA", zona_etiqueta],
                            ["SUBZONA", subzona], ["SECCION", seccion],
                            ["AEU", aeu], ["CANT_VIV", cant_viv],
                            ["FRASE", obs]]
            for text_el in list_text_el:
                el = arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT",
                                                      text_el[0])[0]
                el.text = text_el[1]
            ##############################################Asignado la escala del dibujo##############################################################################
            df.extent = manzanas_mfl.getSelectedExtent()
            dflinea = arcpy.Polyline(
                arcpy.Array([
                    arcpy.Point(df.extent.XMin, df.extent.YMin),
                    arcpy.Point(df.extent.XMax, df.extent.YMax)
                ]), df.spatialReference)
            distancia = dflinea.getLength("GEODESIC", "METERS")
            if (float(distancia) <= 50):
                df.scale = df.scale * 4
            if (float(distancia) > 50 and float(distancia) <= 100):
                df.scale = df.scale * 3
            if (float(distancia) > 100 and float(distancia) <= 490):
                df.scale = df.scale * 2
            if (float(distancia) > 490 and float(distancia) <= 900):
                df.scale = df.scale * 1.5
            if (float(distancia) > 900 and float(distancia) <= 1200):
                df.scale = df.scale * 1.25
            if (float(distancia) > 1200 and float(distancia) <= 1800):
                df.scale = df.scale * 1.10
            if (float(distancia) > 1800):
                df.scale = df.scale * 1.02

            if df.scale > 2000.0:
                if (df.scale >= 2000.0 and df.scale < 3000.0):
                    d = 10
                elif (df.scale >= 3000.0 and df.scale < 4000.0):
                    d = 15
                elif (df.scale >= 4000.0 and df.scale < 5000.0):
                    d = 18
                elif (df.scale >= 5000.0 and df.scale < 6000.0):
                    d = 20
                else:
                    d = 25
                    ######################################Insertamos los multifamiliares con la geometria modificada y aumentada############################
                if arcpy.Exists(tb_rutas_lineas_multifamiliar) and int(
                        arcpy.GetCount_management(
                            tb_rutas_lineas_multifamiliar)[0]) > 0:
                    tb_multifamiliar_temp = cambiar_longitud_lineas_multifamiliar(
                        tb_rutas_lineas_multifamiliar, d)
                    rutas_lineas_multifamiliar_mfl.definitionQuery = "AEU=-1"
                    arcpy.MakeFeatureLayer_management(tb_multifamiliar_temp,
                                                      "rutas_lineas_multi_2",
                                                      where_aeu)
                    lyrFile2 = arcpy.mapping.Layer("rutas_lineas_multi_2")
                    arcpy.ApplySymbologyFromLayer_management(
                        lyrFile2, path_plantillas_layers +
                        "/rutas_lineas_multifamiliar.lyr")
                    arcpy.mapping.AddLayer(df, lyrFile2)

            ############################################Exportando croquis#########################################
            out_croquis = "{}\\{}\\{}\\{}.pdf".format(path_urbano_croquis,
                                                      ubigeo, zona, codigo)
            out_listado = "{}\\{}\\{}\\{}.pdf".format(path_urbano_listados,
                                                      ubigeo, zona, codigo)
            out_final = "{}\\{}\\{}\\{}.pdf".format(
                path_urbano_croquis_listado, ubigeo, zona, codigo)

            print out_final
            arcpy.mapping.ExportToPDF(mxd,
                                      out_croquis,
                                      data_frame="PAGE_LAYOUT",
                                      resolution=300)
            error_export_pdf(path_urbano_croquis, ubigeo, zona, codigo,
                             out_croquis, mxd)
            obtener_datos_pdf_con_error(out_final)

            pdfDoc = arcpy.mapping.PDFDocumentCreate(out_final)
            pdfDoc.appendPages(out_croquis)
            pdfDoc.appendPages(out_listado)

            pdfDoc.saveAndClose()

            arcpy.mapping.RemoveLayer(df, lyrFile1)
            if ((df.scale > 2000.0)
                    and arcpy.Exists(tb_rutas_lineas_multifamiliar) and int(
                        arcpy.GetCount_management(
                            tb_rutas_lineas_multifamiliar)[0]) > 0):
                arcpy.mapping.RemoveLayer(df, lyrFile2)

            del pdfDoc
            del df
            del mxd
            if os.path.exists(path + "\\" + str(el[0])) == False:
                os.mkdir(path + "\\" + str(el[0]))

    where_expression = expresion.Expresion(data, campos)

    with arcpy.da.SearchCursor(tb_zonas, ['UBIGEO', 'ZONA'],
                               where_expression) as cursor:
        for row in cursor:
            for path in paths:

                if os.path.exists(path + "\\" + str(row[0]) + "\\" +
                                  str(row[1])) == False:
                    os.mkdir(path + "\\" + str(row[0]) + "\\" + str(row[1]))

                else:
                    shutil.rmtree(path + "\\" + str(row[0]) + "\\" +
                                  str(row[1]))
                    os.mkdir(path + "\\" + str(row[0]) + "\\" + str(row[1]))


data = [[ubigeox, zonax]]
campos = ['UBIGEO', 'ZONA']

where1 = expresion.Expresion(data=[[ubigeox, zonax]],
                             campos=['UBIGEO', 'ZONA'])
where2 = expresion.Expresion(data=[[ubigeox, zonax, aeux]],
                             campos=['UBIGEO', 'ZONA', 'AEU'])
importar_tablas_corregidas(data=data, campos=campos)
ordenar_manzanas_cod_falso(where_expression=where1)
crear_carpetas_exportacion(data=data, campos=campos)
exportar_croquis_aeu_corregidos(where_expression=where2)
Esempio n. 9
0
def importar_tablas_trabajo(data, campos):
    arcpy.env.overwriteOutput = True
    if arcpy.Exists("CPV_SEGMENTACION.sde") == False:
        arcpy.CreateDatabaseConnection_management(
            "Database Connections", "CPV_SEGMENTACION.sde", "SQL_SERVER",
            ip_server, "DATABASE_AUTH", "us_arcgis_seg_2", "MBs0p0rt301", "#",
            "CPV_SEGMENTACION", "#", "#", "#", "#")
    arcpy.env.workspace = "Database Connections/CPV_SEGMENTACION.sde"
    path_conexion = "Database Connections/CPV_SEGMENTACION.sde"
    where_expression = expresiones_consulta_arcpy.Expresion(data, campos)
    temp_ubigeos = ""
    i = 0
    for x in data:
        i = i + 1
        if (i == 1):
            temp_ubigeos = "'{}'".format(x[0])
        else:
            temp_ubigeos = "{},'{}'".format(temp_ubigeos, x[0])

    print temp_ubigeos
    sql = expresiones_consulta_arcpy.Expresion(data, campos)
    print sql
    manzanas_Layer = arcpy.MakeQueryLayer_management(
        path_conexion, 'TB_MZS',
        "SELECT geom,UBIGEO,CODCCPP,ZONA,MANZANA,VIV_MZ,FALSO_COD,MZS_COND,CANT_BLOCK FROM TB_MANZANA WHERE  ({}) "
        .format(sql))
    print 'importo manzanas'
    sitios_interes_Layer = arcpy.MakeQueryLayer_management(
        path_conexion, 'TB_SITIOS_INT',
        "SELECT * FROM TB_SITIO_INTERES WHERE UBIGEO IN ({}) AND (CODIGO<91 AND CODIGO<>26) "
        .format(temp_ubigeos))
    print 'importo sitios interes'
    puntos_inicio_Layer = arcpy.MakeQueryLayer_management(
        path_conexion, 'TB_PUNTO_INICIO',
        "SELECT * FROM TB_PUNTO_INICIO WHERE {} ".format(sql))
    print 'importo puntos inicio'
    zonas_Layer = arcpy.MakeQueryLayer_management(
        path_conexion, 'CPV_SEGMENTACION.dbo.VW_ZONA_CENSAL',
        "SELECT * FROM CPV_SEGMENTACION.dbo.VW_ZONA_CENSAL WHERE {} ".format(
            sql))
    print 'importo zonas'
    eje_vial_Layer = arcpy.MakeQueryLayer_management(
        path_conexion, 'CPV_SEGMENTACION.dbo.TB_EJE_VIAL',
        "SELECT * FROM CPV_SEGMENTACION.dbo.TB_EJE_VIAL where UBIGEO IN  ({}) "
        .format(temp_ubigeos))

    print 'importo ejes viales'
    viviendas_Layer = arcpy.MakeQueryLayer_management(
        path_conexion, 'CPV_SEGMENTACION.dbo.VW_VIVIENDAS_U',
        "SELECT * FROM CPV_SEGMENTACION.dbo.VW_VIVIENDAS_U WHERE {} ".format(
            sql))

    print 'importo viviendas'
    frentes_mfl = arcpy.MakeQueryLayer_management(
        path_conexion, 'CPV_SEGMENTACION.dbo.TB_FRENTES',
        "SELECT * FROM CPV_SEGMENTACION.dbo.TB_FRENTES WHERE {} ".format(sql))

    print 'importo frentes'

    manzanas_mfl = arcpy.MakeFeatureLayer_management(manzanas_Layer,
                                                     "manzanas_mfl")
    sitios_interes_mfl = arcpy.MakeFeatureLayer_management(
        sitios_interes_Layer, "sitios_interes_mfl")
    puntos_inicio_mfl = arcpy.MakeFeatureLayer_management(
        puntos_inicio_Layer, "puntos_inicio_mfl")
    zonas_mfl = arcpy.MakeFeatureLayer_management(zonas_Layer, "zonas_mfl")
    eje_vial_mfl = arcpy.MakeFeatureLayer_management(eje_vial_Layer,
                                                     "eje_vial_mfl")
    viviendas_mfl = arcpy.MakeFeatureLayer_management(viviendas_Layer,
                                                      "viviendas_mfl")

    list_mfl = [[viviendas_mfl, tb_viviendas], [manzanas_mfl, tb_manzanas],
                [frentes_mfl, tb_frentes]]

    i = 0
    for x in list_mfl:
        i = i + 1
        temp = arcpy.CopyFeatures_management(x[0],
                                             'in_memory/temp_{}'.format(i))
        arcpy.AddField_management(temp, 'MANZANA2', 'TEXT', 50)
        arcpy.CalculateField_management(temp, 'MANZANA2', '!MANZANA!',
                                        "PYTHON_9.3")
        arcpy.DeleteField_management(temp, ['MANZANA'])
        arcpy.CopyFeatures_management(temp, x[1])
        arcpy.AddField_management(x[1], 'MANZANA', 'TEXT', 50)
        arcpy.CalculateField_management(x[1], 'MANZANA', '!MANZANA2!',
                                        "PYTHON_9.3")
        arcpy.DeleteField_management(temp, ['MANZANA2'])

    arcpy.CopyFeatures_management(puntos_inicio_mfl, tb_puntos_inicio)
    arcpy.CopyFeatures_management(zonas_mfl, tb_zonas)
    arcpy.CopyFeatures_management(eje_vial_mfl, tb_ejes_viales)
    arcpy.CopyFeatures_management(sitios_interes_mfl, tb_sitios_interes)
    arcpy.TableToTable_conversion(
        path_conexion + '/CPV_SEGMENTACION.dbo.VW_MZS_CONDOMINIOS',
        path_calidad, "tb_mzs_condominios.dbf")
    arcpy.env.workspace = path_calidad + ""
    arcpy.DeleteField_management(tb_manzanas, ['AEU', 'IDMANZANA'])
    arcpy.AddField_management(tb_manzanas, "IDMANZANA", "TEXT")
    expression = "(!UBIGEO!)+(!ZONA!)+(!MANZANA!)"
    arcpy.CalculateField_management(tb_manzanas, "IDMANZANA", expression,
                                    "PYTHON_9.3")
    arcpy.AddField_management(tb_manzanas, "AEU", "SHORT")
    arcpy.AddField_management(tb_manzanas, "AEU_2", "SHORT")
    arcpy.AddField_management(tb_manzanas, "FLG_MZ", "SHORT")
    arcpy.Dissolve_management(tb_frentes, tb_frentes_dissolve,
                              ['UBIGEO', 'ZONA', 'MANZANA', 'FRENTE_ORD'])
Esempio n. 10
0
def procesar_calidad(cant_zonas=0, data=[], campos=['UBIGEO', 'ZONA']):

    if len(data) == 0:
        data = conex.obtener_lista_zonas_calidad(cant_zonas)[:]

    importar_tablas_trabajo(data, campos)
    where = expresiones_consulta_arcpy.Expresion(data, campos)
    arcpy.AddField_management(tb_viviendas_ordenadas, 'IDMANZANA', 'TEXT')
    arcpy.CalculateField_management(tb_viviendas_ordenadas, 'IDMANZANA',
                                    '!UBIGEO!+!ZONA!+!MANZANA!', 'PYTHON_9.3')

    # print "Importar"

    list_zonas = [(x[0], x[1])
                  for x in arcpy.da.SearchCursor(tb_zonas, ["UBIGEO", "ZONA"])]
    ######################################################CALIDAD PUERTAS MULTIFAMILIAR AFUERA DEL FRENTE DE MANZANA############################################################

    arcpy.AddField_management(tb_viviendas_ordenadas, 'IDMANZANA', 'TEXT')

    arcpy.CalculateField_management(tb_viviendas_ordenadas, 'IDMANZANA',
                                    '!UBIGEO!+!ZONA!+!MANZANA!', 'PYTHON_9.3')
    manzanas_mfl = arcpy.MakeFeatureLayer_management(tb_manzanas,
                                                     "manzanas_mfl", where)
    viviendas_mfl = arcpy.MakeFeatureLayer_management(tb_viviendas_ordenadas,
                                                      "viviendas_mfl", where)
    frentes_mfl = arcpy.MakeFeatureLayer_management(tb_frentes, "frentes_mfl",
                                                    where)
    mzs_line = arcpy.FeatureToLine_management(manzanas_mfl,
                                              "in_memory/mzs_line")
    puertas_multifamiliar = arcpy.MakeFeatureLayer_management(
        tb_viviendas_ordenadas, "puertas_multifamiliar", "p29=6")
    puertas_multifamiliar_afuera = arcpy.SelectLayerByLocation_management(
        puertas_multifamiliar, "INTERSECT", mzs_line, '', "NEW_SELECTION",
        "INVERT")
    viviendas_selecc_frentes_mfl = arcpy.SelectLayerByLocation_management(
        viviendas_mfl, "INTERSECT", mzs_line)
    viviendas_selecc_frentes = arcpy.CopyFeatures_management(
        viviendas_selecc_frentes_mfl, "in_memory/viv_selecc_frentes")
    arcpy.CopyFeatures_management(puertas_multifamiliar_afuera, error_1)

    ########################################LISTA ZONAS CON ERROR PUERTA MULTIFAMILIAR###############################
    list_1 = list(
        set([(x[0], x[1])
             for x in arcpy.da.SearchCursor(error_1, ["UBIGEO", "ZONA"])]))
    zonas_error_puertas_multi = list(
        set([(x[0], x[1])
             for x in arcpy.da.SearchCursor(error_1, ["UBIGEO", "ZONA"])]))

    # print zonas_error_puertas_multi

    #####################################################CALIDAD EXISTENCIA DE EJES VIALES POR ZONA#######################################################################
    # tb_ejes_viales

    ejes_viales_mfl = arcpy.MakeFeatureLayer_management(
        tb_ejes_viales, "ejes_viales_mfl")
    manzanas_sin_vias = arcpy.SelectLayerByLocation_management(
        manzanas_mfl, "INTERSECT", ejes_viales_mfl, "20 METERS",
        "NEW_SELECTION", "INVERT")
    arcpy.CopyFeatures_management(manzanas_sin_vias, error_2)

    ######################################LISTA DE ZONAS SIN EJES VIALES#############################################
    #list_2 = []
    #for x in arcpy.da.SearchCursor(tb_zonas, ["UBIGEO", "ZONA"]):
    #    where = " UBIGEO='{}' AND ZONA='{}'".format(x[0], x[1])
    #    manzanas_mfl = arcpy.MakeFeatureLayer_management(tb_manzanas, "manzanas_mfl", where)
    #    manzanas_sin_vias_mfl = arcpy.MakeFeatureLayer_management(error_2, "manzanas_sin_vias_mfl", where)
    #    a = int(arcpy.GetCount_management(manzanas_mfl).getOutput(0))
    #    b = int(arcpy.GetCount_management(manzanas_sin_vias_mfl).getOutput(0))
    #    if a != 0:
    #        porcentaje = b / float(a) * 100
    #
    #    else:
    #        porcentaje = 100
    #
    #    if porcentaje > 10:
    #        list_2.append((x[0], x[1]))

    ##################################################CALIDAD  MANZANAS INTERSECTADO CON VIAS########################################

    line_mzs = arcpy.FeatureToLine_management(tb_manzanas_ordenadas,
                                              "in_memory/line_mzs")
    buffer_line = arcpy.Buffer_analysis(line_mzs, "in_memory/buffer_line",
                                        "0.50 meters")
    mzs_cortadas = arcpy.Erase_analysis(tb_manzanas_ordenadas, buffer_line,
                                        "in_memory/erase_mzs")

    #manzanas_ordenadas_mfl = arcpy.MakeFeatureLayer_management(tb_manzanas_ordenadas, "manzanas_ordenadas_mfl")
    manzanas_cortadas_mfl = arcpy.MakeFeatureLayer_management(
        mzs_cortadas, "mzs_cortadas_mfl")

    #vias_dentro_manzana = arcpy.SelectLayerByLocation_management(manzanas_ordenadas_mfl, "INTERSECT", tb_ejes_viales,'', "NEW_SELECTION")
    vias_dentro_manzana = arcpy.SelectLayerByLocation_management(
        manzanas_cortadas_mfl, "INTERSECT", tb_ejes_viales, '',
        "NEW_SELECTION")
    arcpy.CopyFeatures_management(vias_dentro_manzana, error_3)
    #########################################LISTA DE ZONAS CON VIAS DENTRO DE MANZANAS###################################

    list_3 = []

    if (int(arcpy.GetCount_management(error_3).getOutput(0)) > 0):
        list_3 = list(
            set([(x[0], x[1])
                 for x in arcpy.da.SearchCursor(error_3, ["UBIGEO", "ZONA"])]))
    #################Calidad Viviendas afuera de la manzana#################################################

    viviendas_mfl = arcpy.MakeFeatureLayer_management(tb_viviendas_ordenadas,
                                                      "viviendas_mfl", where)

    viviendas_afuera_manzana = arcpy.SelectLayerByLocation_management(
        viviendas_mfl, "INTERSECT", tb_manzanas_ordenadas, '0.2 meters',
        "NEW_SELECTION", "INVERT")

    arcpy.CopyFeatures_management(viviendas_afuera_manzana, error_5)

    ##########################################LISTA DE ZONAS CON VIVIENDAS FUERA DE MANZANA#################

    list_4 = []
    if (int(arcpy.GetCount_management(error_5).getOutput(0)) > 0):
        list_4 = list(
            set([(x[0], x[1])
                 for x in arcpy.da.SearchCursor(error_5, ["UBIGEO", "ZONA"])]))

    #################################################CALIDAD PUNTOS DE INICIO#######################################################################
    lineas_viviendas = arcpy.PointsToLine_management(
        viviendas_selecc_frentes, 'in_memory/lineas_viviendas', "IDMANZANA",
        "ID_REG_OR")
    puntos_extremos = arcpy.FeatureVerticesToPoints_management(
        lineas_viviendas, 'in_memory/puntos_extremos', "BOTH_ENDS")
    puntos_extremos_buffer = arcpy.Buffer_analysis(
        puntos_extremos, 'in_memory/puntos_extremos_buffer', "0.2 meters")
    erase_lineas = arcpy.Erase_analysis(mzs_line, puntos_extremos_buffer,
                                        'in_memory/erase_lineas')
    split = arcpy.SplitLine_management(erase_lineas, "in_memory/split")
    dissolve = arcpy.Dissolve_management(split, "in_memory/dissolve",
                                         "UBIGEO;CODCCPP;ZONA;MANZANA", "",
                                         "MULTI_PART", "DISSOLVE_LINES")
    dissolve_multi = arcpy.MultipartToSinglepart_management(
        dissolve, "in_memory/dissolve_multi")
    dissolve_mfl = arcpy.MakeFeatureLayer_management(dissolve_multi,
                                                     'dissolve_mfl')
    puntos_inicio_mfl = arcpy.MakeFeatureLayer_management(
        tb_puntos_inicio, 'puntos_inicio_mfl')

    segmentos_selec = arcpy.SelectLayerByLocation_management(
        dissolve_mfl, "INTERSECT", tb_viviendas_ordenadas, '', "NEW_SELECTION",
        "INVERT")

    tb_segmentos_selec = arcpy.CopyFeatures_management(
        segmentos_selec, "{}/tb_segmentos_selec.shp".format(path_ini))

    puntos_inici_selec = arcpy.SelectLayerByLocation_management(
        puntos_inicio_mfl, "INTERSECT", tb_segmentos_selec, '',
        "NEW_SELECTION", "INVERT")
    arcpy.CopyFeatures_management(puntos_inici_selec, error_4)

    ################################################LISTA DE ZONAS CON PROBLEMAS DE PUNTO DE INICIO##################################################

    list_5 = []

    if (int(arcpy.GetCount_management(error_4).getOutput(0)) > 0):
        list_5 = list(
            set([(x[0], x[1])
                 for x in arcpy.da.SearchCursor(error_4, ["UBIGEO", "ZONA"])]))

    ############################ Cantidad de frentes############################################################
    '''
    resumen_frentes_viv=arcpy.Statistics_analysis(tb_viviendas_ordenadas,'in_memory/resumen_frentes_viv',[["FRENTE_ORD","MAX"]],["UBIGEO","ZONA","MANZANA"])
    arcpy.AddField_management(resumen_frentes_viv,"ID_MANZANA","text")

    with arcpy.da.UpdateCursor(resumen_frentes_viv, ["UBIGEO","ZONA","MANZANA","ID_MANZANA"]) as cursor:
        for x in cursor:
            x[4]=u'{}{}{}'.format(x[0],x[1],x[2])
            cursor.updateRow(x)

    #arcpy.CalculateField_management(resumen_frentes_viv,"ID_MANZANA","!UBIGEO!+!ZONA!+!MANZANA!","PYTHON_9.3")



    resumen_frentes = arcpy.Statistics_analysis(tb_frentes_dissolve, 'in_memory/resumen_frentes',[["FRENTE_ORD", "MAX"],["FRENTE_ORD", "COUNT"]], ["UBIGEO", "ZONA", "MANZANA"])

    arcpy.AddField_management(resumen_frentes, "ID_MANZANA", "text")

    with arcpy.da.UpdateCursor(resumen_frentes, ["UBIGEO","ZONA","MANZANA","ID_MANZANA"]) as cursor:
        for x in cursor:
            x[4]=u'{}{}{}'.format(x[0],x[1],x[2])
            cursor.updateRow(x)

    arcpy.CalculateField_management(resumen_frentes, "ID_MANZANA", "!UBIGEO!+!ZONA!+!MANZANA!", "PYTHON_9.3")

    arcpy.JoinField_management(resumen_frentes,"ID_MANZANA",resumen_frentes_viv,"ID_MANZANA",["MAX_FRENTE_ORD"])
    mzs_dif_cant_frent=arcpy.TableSelect_analysis(resumen_frentes, error_6, " (MAX_FRENTE_ORD<>MAX_FRENTE_ORD_1)")

    arcpy.AddField_management(error_6, "CANT_FR_V", "SHORT")
    arcpy.CalculateField_management(error_6, "CANT_FR_V", "!MAX_FRENTE_ORD!")

    arcpy.AddField_management(error_6, "CANT_FR_F", "text")
    arcpy.CalculateField_management(error_6, "CANT_FR_F", "!MAX_FRENTE_ORD_1!")
    arcpy.DeleteField_management(error_6,["MAX_FRENTE_ORD","MAX_FRENTE_ORD_1"])

    list_6=[]


    if (int(arcpy.GetCount_management(error_6).getOutput(0)) > 0):
        list_6 = list(set([(x[0], x[1]) for x in arcpy.da.SearchCursor(error_6, ["UBIGEO", "ZONA"])]))

    #mzs_dif_cant_frent_1 = arcpy.TableSelect_analysis(resumen_frentes, error_7_cant_frentes_dif, " CapVivNFr<>COUNT_FRENTE_ORD")
    #list_7 = []
    #if (int(arcpy.GetCount_management(error_7_cant_frentes_dif).getOutput(0)) > 0):
    #    list_7 = list(set([(x[0], x[1]) for x in arcpy.da.SearchCursor(error_7_cant_frentes_dif, ["UBIGEO", "ZONA"])]))
    #arcpy.SelectLayerByLocation_management
    '''

    #####################################################ERROR DE FRENTE DE VIVIENDAS#########################################################

    resultado = arcpy.Intersect_analysis([tb_viviendas_ordenadas, tb_frentes],
                                         'in_memory/results')

    arcpy.Select_analysis(resultado, error_7, 'FRENTE_ORD<>FRENTE_ORD_1')
    fields = arcpy.ListFields(error_7)

    list_campos_validos = [
        'FID', 'Shape', 'UBIGEO', 'CODCCPP', 'ZONA', 'MANZANA', 'ID_REG_OR',
        'FRENTE_ORD'
    ]
    delete_fields = []
    for el in fields:
        if el.name not in list_campos_validos:
            delete_fields.append(el.name)

    arcpy.DeleteField_management(error_7, delete_fields)

    #####################################################ERROR FRENTES DE MANZANAS NO COINCIDEN CON LA MANZANA EN FORMA#################################
    temp_frentes = arcpy.SelectLayerByLocation_management(
        frentes_mfl, "WITHIN", mzs_line, '', "NEW_SELECTION", "INVERT")
    arcpy.CopyFeatures_management(temp_frentes, error_8)

    list_8 = []

    if (int(arcpy.GetCount_management(error_8).getOutput(0)) > 0):
        list_8 = list(
            set([(x[0], x[1])
                 for x in arcpy.da.SearchCursor(error_8, ["UBIGEO", "ZONA"])]))

    ####################################################ERROR NUMERACION DE VIVIENDAS#############################################################

    lineas_viviendas = arcpy.PointsToLine_management(
        viviendas_selecc_frentes, 'in_memory/lineas_viviendas', "IDMANZANA",
        "ID_REG_OR")
    viviendas_selecc_frentes_buffer = arcpy.Buffer_analysis(
        viviendas_selecc_frentes, "in_memory/puntos_extremos_buffer",
        "0.2 meters")

    erase_lineas = arcpy.Erase_analysis(lineas_viviendas,
                                        viviendas_selecc_frentes_buffer,
                                        'in_memory/erase_lineas')
    split = arcpy.SplitLine_management(erase_lineas, path_ini + "/split.shp")

    mz_line_erase = arcpy.Erase_analysis(mzs_line,
                                         viviendas_selecc_frentes_buffer,
                                         "in_memory\mz_line_erase")
    mz_line_erase_multi = arcpy.MultipartToSinglepart_management(
        mz_line_erase, 'in_memory\m_l_e_m')
    result = arcpy.Statistics_analysis(mz_line_erase_multi, 'in_memory/result',
                                       [['FID', "MAX"]], ["Shape"])
    maxids = [[
        x[0]
    ] for x in arcpy.da.SearchCursor(result, ["MAX_FID"], 'FREQUENCY>1')]

    if len(maxids) == 0:
        where_ids = expresiones_consulta_arcpy.Expresion_2([["-1"]],
                                                           [["FID", "SHORT"]])

    else:
        where_ids = expresiones_consulta_arcpy.Expresion_2(
            maxids, [["FID", "SHORT"]])

    arcpy.Select_analysis(mz_line_erase_multi, error_9, where_ids)
    '''
    intersect=arcpy.Intersect_analysis([mz_line_erase_multi, split], path_ini+"/intersect.shp", "ALL", "", "")
    list_id_buffer_mzs_line_erase_multi=list(set( [x[0] for x in arcpy.da.SearchCursor(intersect,["FID_m_l_e_"])]))
    list_intersect= [x[0]  for x  in arcpy.da.SearchCursor(intersect,["FID_m_l_e_"])]


    errores_numeracion=[]
    print list_id_buffer_mzs_line_erase_multi
    print list_intersect

    for x in list_id_buffer_mzs_line_erase_multi:
        cont = 0
        for y in list_intersect:
            if (x==y):
                cont=cont+1


        #print cont
        if (cont>1):
           errores_numeracion.append([x])
    print errores_numeracion
    where_exp=UBIGEO.Expresion_2(errores_numeracion,[["FID","SHORT"]])
    b_m_l_e_m_selecc = arcpy.Select_analysis(mz_line_erase_multi, error_9, where_exp)

    list_9=[]
    if (int(arcpy.GetCount_management(error_9).getOutput(0)) > 0):
        list_9 = list(set([(x[0], x[1]) for x in arcpy.da.SearchCursor(error_9, ["UBIGEO", "ZONA"])]))


    #dissolve = arcpy.Dissolve_management(split, "in_memory/dissolve", "UBIGEO;CODCCPP;ZONA;MANZANA", "","MULTI_PART","DISSOLVE_LINES")
    #dissolve_multi=arcpy.MultipartToSinglepart_management(dissolve, "in_memory/dissolve_multi")
    #arcpy.SelectLayerByLocation_management (dissolve_multi, "INTERSECT",dissolve_multi)
    #arcpy.MultipartToSinglepart_management("intersect", "in_memory/intersect2")

    '''

    #################################################VIVIENDAS Y VIAS#####################################################

    # list_zonas_error=list(set(list_1+list_2+list_3+list_4+list_5+list_6+list_8+list_9))
    # print  list_zonas_error
    #nombre_ejes_viales()

    ################################puertas  hijos multifamiliar en el frente##########################
    puertas_hijos_multifamilar = arcpy.MakeFeatureLayer_management(
        tb_viviendas_ordenadas, "puertas_multifamiliar",
        "(p29=1  or p29=3) and ID_REG_PAD<>0 ")
    error_11_mfl = arcpy.SelectLayerByLocation_management(
        puertas_hijos_multifamilar, "INTERSECT", mzs_line, '', "NEW_SELECTION")
    arcpy.CopyFeatures_management(error_11_mfl, error_11)

    # puertas_hijos_multifamilar=arcpy.MakeFeatureLayer_management(tb_viviendas_ordenadas, "puertas_multifamiliar", "(p29=1  or p29=3) and ID_REG_PAD<>0 ")
    # error_11_mfl=arcpy.SelectLayerByLocation_management(puertas_hijos_multifamilar, "INTERSECT",mzs_line ,'' , "NEW_SELECTION")
    # arcpy.CopyFeatures_management(error_11_mfl, error_11)

    ###############################################ERROR HIJOS SIN PADRES#########################################################################
    '''
    puertas_hijos_multifamilar = arcpy.MakeFeatureLayer_management(tb_viviendas_ordenadas, "puertas_multifamiliar",
                                                                   "(p29=1  or p29=3) and (ID_REG_PAD<>0)" )

    list_puertas_hijos_multifamilar=[[x[0],x[1],x[2],x[3],x[4]] for x in  arcpy.da.SearchCursor(puertas_hijos_multifamilar,["UBIGEO","ZONA","MANZANA","ID_REG_OR","ID_REG_PAD"])]

    list_puertas_multifamiliar=[ '{}{}{}{}'.format(x[0],x[1],x[2],x[3]) for x in arcpy.da.SearchCursor(puertas_multifamiliar,["UBIGEO","ZONA","MANZANA","ID_REG"])]




    where_error_12=""

    i=0

    for el in list_puertas_hijos_multifamilar:
        i=i+1
        id_padre='{}{}{}{}'.format(el[0],el[1],el[2],el[4])
        if  id_padre not in list_puertas_multifamiliar:
            if i==1:
                where_error_12=" (UBIGEO='{}' AND ZONA='{}' AND MANZANA='{}' AND ID_REG_OR={})".format(el[0],el[1],el[2],el[3])
            else:
                where_error_12 = "{} OR (UBIGEO='{}' AND ZONA='{}' AND MANZANA='{}' AND ID_REG_OR={})".format(where_error_12,el[0], el[1],
                                                                                                         el[2], el[3])
    error_12_mfl=arcpy.MakeFeatureLayer_management(tb_viviendas_ordenadas, "error_12",where_error_12 )

    arcpy.CopyFeatures_management(error_12_mfl, error_12)






    #############################ERROR   PUERTAS MULTIFAMILIAR CON MAS DE 2 GEOMETRIAS#########################################
    set_puertas_multi=set(list_puertas_multifamiliar)

    where_error_13=""
    j=0

    for el in set_puertas_multi:
        i=0

        if el in list_puertas_multifamiliar:
           i=i+1

        if i>1:
            j=j+1
            if (j==1):
                where_error_13 = " (UBIGEO='{}' AND ZONA='{}' AND MANZANA='{}' AND ID_REG_OR={})".format(el[0], el[1],el[2], el[3])
            else:
                where_error_13 = "{} OR (UBIGEO='{}' AND ZONA='{}' AND MANZANA='{}' AND ID_REG_OR={})".format(where_error_13,el[0], el[1],
                                                                                                         el[2], el[3])

    error_13_mfl = arcpy.MakeFeatureLayer_management(tb_viviendas_ordenadas, "error_13", where_error_13)

    arcpy.CopyFeatures_management(error_13_mfl, error_13)

   '''

    ################################Insercion de data###########################################

    arcpy.env.workspace = "Database Connections/PruebaSegmentacion.sde"
    arcpy.env.outputCoordinateSystem = arcpy.SpatialReference(4326)
    if arcpy.Exists("GEODATABASE.sde") == False:
        arcpy.CreateDatabaseConnection_management(
            "Database Connections", "GEODATABASE.sde", "SQL_SERVER", ip_server,
            "DATABASE_AUTH", "sde", "$deDEs4Rr0lLo", "#", "GEODB_CPV_SEGM",
            "#", "#", "#", "#")
    arcpy.env.workspace = "Database Connections/GEODATABASE.sde"
    path_conexion2 = "Database Connections/GEODATABASE.sde"
    path_calidad = path_conexion2 + "/GEODB_CPV_SEGM.SDE.CALIDAD_URBANO"
    calidad_error_1_input = path_calidad + '/GEODB_CPV_SEGM.SDE.ERROR_1_INPUT_PUERTA_MULTIFAMILIAR_DENTRO_MZ'
    calidad_error_2_input = path_calidad + '/GEODB_CPV_SEGM.SDE.ERROR_2_INPUT_MANZANAS_SIN_VIAS'
    calidad_error_3_input = path_calidad + '/GEODB_CPV_SEGM.SDE.ERROR_3_INPUT_MANZANAS_VIAS_DENTRO'
    calidad_error_4_input = path_calidad + '/GEODB_CPV_SEGM.SDE.ERROR_4_INPUT_PUNTOS_INICIO'
    calidad_error_5_input = path_calidad + '/GEODB_CPV_SEGM.SDE.ERROR_5_INPUT_VIVIENDAS_AFUERA_MZ'
    calidad_error_7_input = path_calidad + '/GEODB_CPV_SEGM.SDE.ERROR_7_INPUT_VIVIENDAS_ERROR_FRENTE'
    calidad_error_8_input = path_calidad + '/GEODB_CPV_SEGM.SDE.ERROR_8_INPUT_FRENTES_MANZANAS_FORMA'
    calidad_error_9_input = path_calidad + '/GEODB_CPV_SEGM.SDE.ERROR_9_INPUT_ENUMERACION_VIV_POR_FRENTE'
    calidad_error_10_input = path_calidad + '/GEODB_CPV_SEGM.SDE.ERROR_10_INPUT_VIV_ERROR_NOMBRE_VIA'
    calidad_error_11_input = path_calidad + '/GEODB_CPV_SEGM.SDE.ERROR_11_INPUT_PUERTAS_HIJOS_MULTI_EN_FRENTE_MZ'
    #error_7 = path_calidad + "/error_7_viviendas_error_frente.shp"
    list_errores = [
        [error_1, calidad_error_1_input, 1],
        [error_2, calidad_error_2_input, 1],
        [error_3, calidad_error_3_input, 1],
        [error_4, calidad_error_4_input, 1],
        [error_5, calidad_error_5_input, 1],
        [error_8, calidad_error_8_input, 1],
        [error_9, calidad_error_9_input, 1],
        # [error_10, calidad_error_10_input, 1],
        [error_11, calidad_error_11_input, 1],
        [error_7, calidad_error_7_input, 1],
    ]

    conn = conex.Conexion2()
    cursor = conn.cursor()
    for el in data:
        ubigeo = el[0]
        zona = el[1]
        sql_query = """
                DELETE GEODB_CPV_SEGM.SDE.ERROR_1_INPUT_PUERTA_MULTIFAMILIAR_DENTRO_MZ where ubigeo='{ubigeo}' and zona='{zona}'
                DELETE GEODB_CPV_SEGM.SDE.ERROR_2_INPUT_MANZANAS_SIN_VIAS where ubigeo='{ubigeo}' and zona='{zona}'
                delete GEODB_CPV_SEGM.SDE.ERROR_3_INPUT_MANZANAS_VIAS_DENTRO where ubigeo='{ubigeo}' and zona='{zona}'
                delete GEODB_CPV_SEGM.SDE.ERROR_4_INPUT_PUNTOS_INICIO  where ubigeo='{ubigeo}' and zona='{zona}'
                delete GEODB_CPV_SEGM.SDE.ERROR_5_INPUT_VIVIENDAS_AFUERA_MZ  where ubigeo='{ubigeo}' and zona='{zona}'
                delete GEODB_CPV_SEGM.SDE.ERROR_7_INPUT_VIVIENDAS_ERROR_FRENTE  where ubigeo='{ubigeo}' and zona='{zona}'
                delete GEODB_CPV_SEGM.SDE.ERROR_8_INPUT_FRENTES_MANZANAS_FORMA  where ubigeo='{ubigeo}' and zona='{zona}'
                delete GEODB_CPV_SEGM.SDE.ERROR_9_INPUT_ENUMERACION_VIV_POR_FRENTE where ubigeo='{ubigeo}' and zona='{zona}'
                delete GEODB_CPV_SEGM.SDE.ERROR_10_INPUT_VIV_ERROR_NOMBRE_VIA where ubigeo='{ubigeo}' and zona='{zona}'
                delete GEODB_CPV_SEGM.SDE.ERROR_11_INPUT_PUERTAS_HIJOS_MULTI_EN_FRENTE_MZ where ubigeo='{ubigeo}' and zona='{zona}'
                """.format(ubigeo=ubigeo, zona=zona)
        cursor.execute(sql_query)
        conn.commit()
    conn.close()

    i = 0
    for el in list_errores:
        i = i + 1
        print el[0]
        if (int(el[2]) > 1):
            a = arcpy.MakeTableView_management(
                el[0],
                "a{}".format(i),
            )

        else:
            a = arcpy.MakeFeatureLayer_management(el[0], "a{}".format(i))

        arcpy.Append_management(a, el[1], "NO_TEST")

    #for el in list_errores:
    #    i = i + 1


#
#    print where
#
#    if el[2] == 1:
#        a = arcpy.arcpy.MakeFeatureLayer_management(el[1], "a{}".format(i), where)
#    else:
#        a = arcpy.MakeTableView_management(el[1], "a{}".format(i), where)
#
#    if (int(arcpy.GetCount_management(a).getOutput(0)) > 0):
#        arcpy.DeleteRows_management(a)
#
#    print 'borro'
#    if el[2] == 1:
#        b = arcpy.arcpy.MakeFeatureLayer_management(el[0], "b{}".format(i), where)
#    else:
#        b = arcpy.MakeTableView_management(el[0], "b{}".format(i), where)
#
#    if (int(arcpy.GetCount_management(b).getOutput(0)) > 0):
#        arcpy.Append_management(b, el[1], "NO_TEST")
#    print 'inserto'

    for el in data:
        conex.actualizar_errores_input_adicionales(ubigeo=el[0], zona=el[1])