Пример #1
0
def clusterLimit(X, linea, ramal, sentido, k_means, geom):
    
    res = np.vstack(np.array([X, k_means.labels_])).transpose()
    pdres = pd.DataFrame(res, columns=['valores','cluster'])
    grupo = pd.merge( pdres.groupby(['cluster']).min(),  pdres.groupby(['cluster']).max(), left_index=True, right_index=True, how='outer', suffixes=('_min', '_max'))
    grupo = grupo.sort('valores_min')
    shplLine = wkt_load(geom)

    #renumero los cluster ordenadamente, pego el centroide
    for idx, i in zip(grupo.index, range(len(grupo))):
        grupo.loc[idx, 'linea'] = linea
        grupo.loc[idx, 'ramal'] = ramal
        grupo.loc[idx, 'sentido'] = sentido
        grupo.loc[idx, 'clusterord'] = i
        grupo.loc[idx, 'centroide']  =  k_means.cluster_centers_[int(idx)]
        puntoaux = shplLine.interpolate(k_means.cluster_centers_[int(idx)], normalized=True)               
        grupo.loc[idx,'latitud'] = puntoaux.y
        grupo.loc[idx,'longitud'] = puntoaux.x
    
    #encontrar los limites de los clusters
    limites = grupo[['valores_min','valores_max']].values
    for idx, i in zip(grupo.index, range(len(grupo))):
        if i == 0:    
            grupo.loc[idx, 'limiteinf'] = 0
            grupo.loc[idx, 'limitesup'] = (limites[i,1]+limites[i+1,0])/2
        else:
            if i == len(limites) - 1:
                grupo.loc[idx, 'limiteinf'] = (limites[i-1,1]+limites[i,0])/2
                grupo.loc[idx, 'limitesup'] = 1
            else:
                grupo.loc[idx, 'limiteinf'] = (limites[i-1,1]+limites[i,0])/2
                grupo.loc[idx, 'limitesup'] = (limites[i,1]+limites[i+1,0])/2
    return grupo
Пример #2
0
def bankfull_width_buffer(flowlines, precip):
    """generate bankfull buffer polygon from precipitation value

    Args:
        flowlines (str): feature class of line features to buffer
        precip (float): mean annual precipitation (mm) for the HUC

    Returns:
        geometry: unioned polygon geometry of buffered lines 
    """

    p = precip / 10.0  # prism data in mm, need cm

    driver = ogr.GetDriverByName("ESRI Shapefile")
    source = driver.Open(flowlines, 1)
    layer = source.GetLayer()

    outpolys = []
    # Buffer width for each flow line feature
    for feature in layer:
        a = feature.GetField("TotDASqKm")
        a = a if a is not None else 0.0
        w = 0.177 * (a**0.397) * (p**0.453)
        geom = feature.GetGeometryRef()
        geom_buffer = geom.Buffer(w)
        outpolys.append(wkt_load(geom_buffer.ExportToWkt()))
        feature = None

    # unary union
    outpoly = unary_union(outpolys)
    source = None

    return outpoly
Пример #3
0
def load_scene(name):
    if name in world.scenes:
        world.current_scene = world.scenes[name]
    else:
        with open(os.path.join(world.config.scene_path, "%s.wkt" % name), 'r') as fd:
            scene = {}
            for line in fd:
                if line.strip():
                    obj, wkt = line.split('|', 2)
                    wkt = wkt.strip()
                    scene[obj.strip()] = wkt_load(wkt)
            world.scenes[name] = scene
            world.current_scene = scene
Пример #4
0
def load_scene(name):
    if name in world.scenes:
        world.current_scene = world.scenes[name]
    else:
        with open(os.path.join(world.config.scene_path, "%s.wkt" % name), 'r') as fd:
            scene = {}
            for line in fd:
                if line.strip():
                    obj, wkt = line.split('|', 2)
                    wkt = wkt.strip()
                    scene[obj.strip()] = wkt_load(wkt)
            world.scenes[name] = scene
            world.current_scene = scene
Пример #5
0
def puntosControlLineaRamal(lineamt, ramalmt, PosEngine):

    sqlcode = (
        "SELECT CODIGOLINEA, RAMAL, LONGITUD, LATITUD, 0 wkt, FILE_ID, C_CONTROL_POINT "
        " FROM PTOCONTROL201505 "
        " WHERE CODIGOLINEA = '%s' "
        "   AND RAMAL = '%s' "
        " ORDER BY FILE_ID " % (lineamt, ramalmt))

    tempListPoint = sql.read_sql(sqlcode, PosEngine)
    if len(tempListPoint) > 0:
        tempListPoint["wkt"] = tempListPoint.apply(
            lambda x: wkt_load('POINT(%s %s)' % (x[2], x[3])), axis=1)
        listShapPoint = tempListPoint.values

        return listShapPoint
    else:
        return []
Пример #6
0
def puntosControlLinea(line, PosEngine):
    connect = PosEngine.connect()
    cursorRamal = PosEngine.execute(
        "SELECT DISTINCT CODIGOLINEA FROM THE_RAMALES WHERE LINEA2 = '%s'" %
        line)

    listShapPoint = []
    if cursorRamal.rowcount > 0:
        for ramal in cursorRamal.fetchall():
            sqlcode = (
                "SELECT CODIGOLINEA, RAMAL, LONGITUD, LATITUD, 0 wkt, FILE_ID, C_CONTROL_POINT "
                " FROM PTOCONTROL201505 "
                " WHERE CODIGOLINEA = '%s' " % ramal[0])

            tempListPoint = sql.read_sql(sqlcode, PosEngine)
            tempListPoint["wkt"] = tempListPoint.apply(
                lambda x: wkt_load('POINT(%s %s)' % (x[2], x[3])), axis=1)
            listShapPoint = tempListPoint.values
    return listShapPoint
Пример #7
0
def largoRuta(PosEngine):
    cursorRamal = PosEngine.execute(
        "SELECT LINEa, RAMALgeo ramal, sentido, geom FROM lineastrxgeo a, lineascole b where a.lineageo = b.linea2 and a.ramalgeo = ramal and a.baja is null  order by a.lineamt, a.ramalmt"
    )
    pos = 1
    largos = pd.DataFrame()
    for row in cursorRamal.fetchall():
        largos.loc[pos, 'codigolinea'] = row.linea
        largos.loc[pos, 'ramal'] = row.ramal
        largos.loc[pos, 'sentido'] = row.sentido
        shplLineIda = wkt_load(row.geom)
        p2 = 0
        largo = 0
        for i in shplLineIda.coords:
            p1 = i
            if p2 != 0:
                largo = largo + geou.distancia(p1[0], p1[1], p2[0], p2[1])
            p2 = p1
        print(largo)
        largos.loc[pos, 'largo'] = largo
        pos = pos + 1
    largos.to_sql('largos', con=PosEngine)
Пример #8
0
def calcRMSE(PosEngine, lineaDesde, lineaHasta):

    #   cargo todos las rutas
    baseLineasRamales = bk.cargar_lineas(PosEngine).values

    #    recorro las lineas que estan vacias
    sql_code = ("    select codigolinea lineamt, ramal ramalmt "
                " from the_ramales a left outer join  lineastrxgeo b "
                " on  a.codigolinea = cast(b.lineamt as integer) "
                " and a.ramal = b.ramalmt "
                " where b.ramalmt is null "
                "  and cantidad_trx > 1000 "
                "  and linea2 is not null "
                "  and codigolinea > %s "
                "  and codigolinea < %s "
                " order by codigolinea " % (lineaDesde, lineaHasta))

    lineas = PosEngine.execute(sql_code)

    #    for linea in lineas.fetchall():
    for linea in range(1):
        #        lineamt = linea.lineamt
        #        ramalmt = linea.ramalmt
        lineamt = '100'
        ramalmt = '202'

        print('Ejecutando lineamt / ramalmt: %s / %s ...' % (lineamt, ramalmt))

        #       cargo los puntos de control
        listShapPointTotales = puntosControlLineaRamal(lineamt, ramalmt,
                                                       PosEngine)

        if len(listShapPointTotales) > 0:
            #        me quedo con los file_id unicos
            fileids = np.unique(listShapPointTotales[:, 5])
            fileids = fileids.reshape(len(fileids), 1)

            #        para cada file_id
            for fileid in fileids:
                i = 0
                minDistCuad = 0
                RMSE = pd.DataFrame()
                listShapPoint = listShapPointTotales[listShapPointTotales[:, 5]
                                                     == fileid[0]]

                #para cada reccorrido geográfico
                while i < len(baseLineasRamales) and len(listShapPoint) > 0:

                    #           cargo la ruta
                    shplLineString = wkt_load(baseLineasRamales[i][3])
                    distanciaCuadrado = 0

                    #para cada punto de control encontrado
                    for punto in listShapPoint:

                        #               sumo todas las distancias al cuadrado en metros
                        p = shplLineString.interpolate(
                            shplLineString.project(punto[4]))

                        dist = geou.distancia(punto[4].x, punto[4].y, p.x, p.y)
                        #                   solo tomo los puntos que están a menos de 50 km para evitar errores graves en el GPS
                        if dist < 50:
                            #en distancia voy agregando: codigolinea, ramaltrx,  lineageo, ramalgeo, sentido, distnacia del punto de control al punto proyectado
                            distanciaCuadrado = distanciaCuadrado + dist**2

        #           pruebo que el RMSE encontrado sea el minimo para la linea
                    if minDistCuad > distanciaCuadrado or minDistCuad == 0:
                        minDistCuad = distanciaCuadrado
                        minLinea = baseLineasRamales[i][0]
                        minRamal = baseLineasRamales[i][1]
                        minSentido = baseLineasRamales[i][2]
                    i = i + 1

                if len(listShapPoint) > 0:
                    print(
                        'lote:%s - RMSE:%s - linea:%s - ramal:%s - sentido:%s'
                        % (fileid[0],
                           math.sqrt(minDistCuad / len(listShapPoint)),
                           minLinea, minRamal, minSentido))
                    RMSE.loc[0, 'lineamt'] = lineamt
                    RMSE.loc[0, 'ramalmt'] = ramalmt
                    RMSE.loc[0, 'linea'] = minLinea
                    RMSE.loc[0, 'ramal'] = minRamal
                    RMSE.loc[0, 'sentido'] = minSentido
                    RMSE.loc[0, 'file_id'] = fileid[0]
                    RMSE.loc[0, 'rmse'] = math.sqrt(minDistCuad /
                                                    len(listShapPoint))
                    RMSE.to_sql('rmse', con=PosEngine, if_exists='append')

    print('FIN')
Пример #9
0
def distPtoLinea(PosEngine, lineaDesde, lineaHasta, shp, db, tst):
    connect = PosEngine.connect()
    if lineaHasta == '':
        lineaHasta = '999'

    #tomo de lineas cole
    lineascole = sql.read_sql(
        "select trim(to_char(CASE WHEN substring(LINEA FROM '[0-9]*') != '' THEN TO_NUMBER(substring(LINEA FROM '[0-9]*'),'999') END, '999')) linea, ramal, sentido, geom, LINEA lineaaux FROM lineascole WHERE linea >= '%s' and linea < '%s' ORDER BY linea, ramal, sentido"
        % (lineaDesde, lineaHasta), PosEngine)
    lineascole = lineascole.values

    i = 0
    cant = 0

    #para cada reccorrido geográfico
    while i < len(lineascole):
        line = lineascole[i][0]
        lineant = line
        print('Ejecutando linea: %s ...' % line)
        listShapLineString = []
        distancias = []

        listShapPoint = puntosControlLinea(line, PosEngine)
        if shp == 1:
            #genero un shape con todos los puntos de la linea
            shpPuntosControlLinea(line, PosEngine)

        print('     %d Puntos encontrados' % len(listShapPoint))

        #por cada ramal geográfico
        while line == lineant and i < len(lineascole) and len(
                listShapPoint) > 0:
            test = []
            print('         Ramal: %s Sentido: %s' %
                  (lineascole[i][1], lineascole[i][2]))

            if shp == 1:
                #creamos un shape de a linea para la inspeccion visual
                geou.createShpFromWKT(
                    [lineascole[i][3]], 'linea%sRamal%sSentido%s.shp' %
                    (lineascole[i][0], lineascole[i][1], lineascole[i][2]),
                    'LS')

            #shapely del raml de la linea a calcular las distancias
            shplLineString = wkt_load(lineascole[i][3])

            j = 0
            #para cada punto de control encontrado
            for punto in listShapPoint:
                j = j + 1
                #en p calculo la
                p = shplLineString.interpolate(shplLineString.project(
                    punto[4]))
                #en distancia voy agregando: codigolinea, ramaltrx,  lineageo, ramalgeo, sentido, distnacia del punto de control al punto proyectado
                distancias.append([
                    j, punto[0], punto[1], lineascole[i][0], lineascole[i][1],
                    lineascole[i][2],
                    geou.distancia(punto[4].x, punto[4].y, p.x,
                                   p.y), punto[5], punto[6]
                ])

                if tst == 1:
                    test.append([
                        j, punto[0], punto[1], lineascole[i][0],
                        lineascole[i][1], lineascole[i][2],
                        geou.distancia(punto[4].x, punto[4].y, p.x, p.y),
                        punto[5], punto[6], p.x, p.y, punto[4].x, punto[4].y
                    ])

            if tst == 1:
                pdtest = pd.DataFrame(test)
                pdtest.columns = [
                    'punto', 'lineamt', 'ramalmt', 'lineageo', 'ramalgeo',
                    'sentidogeo', 'distancia', 'file_id', 'c_control_point',
                    'long_linea', 'lat_linea', 'long_pto', 'lat_pto'
                ]
                pdtest.to_csv(
                    'linea%sRamal%sSentido%s.csv' %
                    (lineascole[i][0], lineascole[i][1], lineascole[i][2]),
                    sep=';')

            lineant = line
            i = i + 1
            if i < len(lineascole):
                line = lineascole[i][0]

        if len(listShapPoint) > 0:
            if db == 1:
                PtoControl = pd.DataFrame(distancias)
                PtoControl.columns = [
                    'punto', 'lineamt', 'ramalmt', 'lineageo', 'ramalgeo',
                    'sentidogeo', 'distancia', 'file_id', 'c_control_point'
                ]
                PtoControl.to_sql('distancias',
                                  con=PosEngine,
                                  if_exists='append')

        else:
            while line == lineant and i < len(lineascole):
                line = lineascole[i][0]
                i = i + 1
Пример #10
0
def proyLinea(PosEngine, lineaDesde, lineaHasta):

    print('Este procedimeinto graba en proyeccionruta y luego en THE_VIAJESMAYO')
   
    cursorRamal = PosEngine.execute("SELECT a.LINEAMT, A.RAMALMT,A.LINEAGEO,A.RAMALGEO, sentido, geom "
                                    " FROM lineastrxgeo a, lineascole b "
                                    " where a.lineageo = b.linea2 and a.ramalgeo = ramal "
                                    "   and a.baja is null  AND lineageo >= '%s' "
                                    "   and lineageo < '%s' "
                                    "order by a.lineageo, a.ramalgeo" % (lineaDesde, lineaHasta))  
    
    listShapPoint = []
    if cursorRamal.rowcount > 0 :
        # por cada ramal de la linea
        for ramal in cursorRamal.fetchall():      
            lineamt = ramal[0]
            ramalmt = ramal[1]
            lineageo  = ramal[2]
            sentido = ramal[4]
            print('procesando codigolinea %s lineaGEO %s ramal %s sentido %s' % (ramal[0], lineageo, ramal[1], ramal[4]) ) 
        
            #recupero para cada viaje lo longitud y la latitud de los puntos de control anterior y siguiente, 
            #ademas se recupera el porcentaje del recorrido en que se encuentra el viaje desde el punto de control anterior al siguiente
            #finalmente se recupera el sentido primer punto de control
            sqlcode = ("SELECT B.NROTARJETAEXTERNO, B.CODIGOTRXTARJETA, A.LONGITUD longitudpto1, A.LATITUD latitudpto1, "
                       " C.LONGITUD longitudpto2, C.LATITUD latitudpto2, B.PORC_RECORRIDO, A.SENTIDO "
                        " FROM  PTOCONTROL201505B A, THE_VIAJESMAYO B, PTOCONTROL201505B C "
                        " WHERE A.FILE_ID = B.FILE_ID "
                        "  AND A.C_CONTROL_POINT = B.C_CONTROL_POINT1  "
                        "  AND B.FILE_ID = C.FILE_ID "
                        "  AND B.C_CONTROL_POINT2 = C.C_CONTROL_POINT "                        
                        "  AND B.CODIGOLINEA = %s "
                        "  AND B.RAMAL = '%s' "
                        "  AND a.SENTIDO = '%s' "
                        "  AND B.DISTANCIA IS NULL  "
                        " ORDER BY B.FECHATRX " % (ramal[0],ramal[1], ramal[4]))

            viajes = sql.read_sql(sqlcode  , PosEngine)            
            
            #paso a shapely
            shplLine = wkt_load(ramal[5])
            
            viajestemp = pd.DataFrame()
            viajestemp['nrotarjetaexterno'] = ''
            viajestemp['codigotrxtarjeta']= ''
            viajestemp['latitudpto3'] = 0
            viajestemp['longitudpto3'] = 0
            viajestemp['distancia'] = 0
            
            shplLineIda = wkt_load(ramal[5]) 
            
            cantidad = len(viajes)

            for i, row in viajes.iterrows():                
                if mod(i, cantidad/100) == 0:
                    print('Puntos procesados al: %i porciento' % int(i*100/cantidad))
                    
                shplPoint1 = wkt_load("POINT(%s %s)" %  (row['longitudpto1'] , row['latitudpto1']))
                projPoint1 = shplLine.project(shplPoint1, normalized=True)
            
                shplPoint2 = wkt_load("POINT(%s %s)" %  (row['longitudpto2'] , row['latitudpto2']))
                projPoint2 = shplLine.project(shplPoint2, normalized=True)

                dist = projPoint1 + ((projPoint2 -projPoint1) * float(row['porc_recorrido']))
                puntoenlinea3 = shplLine.interpolate(dist, normalized=True)       
                
                viajestemp.loc[i,'nrotarjetaexterno'] = row['nrotarjetaexterno']
                viajestemp.loc[i,'codigotrxtarjeta'] = row['codigotrxtarjeta']
                viajestemp.loc[i,'latitudpto3'] = puntoenlinea3.y
                viajestemp.loc[i,'longitudpto3'] = puntoenlinea3.x
                viajestemp.loc[i,'distancia'] = dist
            
            viajestemp.to_sql('proyeccionruta', con=PosEngine, if_exists='append')

    print ('Actualizando tabla THE_VIAJESMAYO...')

#    sql_code = (" UPDATE THE_VIAJESMAYO A "
#                " SET LATITUDPTO3 = B.LATITUDPTO3, "
#                " LONGITUDPTO3 = B.LONGITUDPTO3, "
#                " DISTANCIA = B.DISTANCIA "
#                " FROM PROYECCIONRUTA B "
#                " WHERE A.NROTARJETAEXTERNO = B.NROTARJETAEXTERNO "
#                "  AND A.CODIGOTRXTARJETA = B.CODIGOTRXTARJETA "
#            )

    PosEngine.execute(sql_code)
Пример #11
0
def proyeccionLineaRamal(linea, ramal, viajes):

    #consqliteLineas  = sqlite3.connect('d:\\DataMining\\Tesis\\DATASET SUBE\\base.db')
    consqliteLineas  = sqlite3.connect('base.db')
    consqliteLineas.text_factory = str

    #RECUPERO LAS SECUENCIAS DE VIAJES 
    
    viajes['latitudpto3'] = 0
    viajes['longitudpto3'] = 0
    viajes['sentido'] = ''
    viajes['error'] = ''
    viajes['distancia'] = 0

    #RECUPERO LOS RECORRIDOS TEORICOS
    lineascole = sql.read_frame('select linea, ramal, sentido, geom  from lineascole where linea = %s and ramal = "%s" order by linea, ramal, sentido' % (linea, ramal), consqliteLineas)

    #tomo los recorridos de ida y de vuelta 
    lineaIDA    = lineascole[(lineascole['LINEA'] == linea) & (lineascole['RAMAL'] == ramal) & (lineascole['SENTIDO'] == 'I')]['GEOM'].values
    lineaVUELTA = lineascole[(lineascole['LINEA'] == linea) & (lineascole['RAMAL'] == ramal) & (lineascole['SENTIDO'] == 'V')]['GEOM'].values

    #paso a shapely
    shplLineIda = wkt_load(lineaIDA[0])
    shplLineVuelta = wkt_load(lineaVUELTA[0])
    #createShpFromWKT([lineascole[0][3]], 'controlsLinea.shp', 'LS')
    
    cantidad = len(viajes)

    for i, row in viajes.iterrows():
        if mod(i, cantidad/100) == 0:
            print('Puntos procesados al: %i porciento' % int(i*100/cantidad))
        
        #proyecciones sobre la IDA
        shplPoint1 = wkt_load("POINT(%s %s)" %  (row['longitudpto1'] , row['latitudpto1']))
        projPoint1 = shplLineIda.project(shplPoint1, normalized=True)
    
        shplPoint2 = wkt_load("POINT(%s %s)" %  (row['longitudpto2'] , row['latitudpto2']))
        projPoint2 = shplLineIda.project(shplPoint2, normalized=True)
    
        #supongo que el uso fue en la IDA
        shpLineaUsada = shplLineIda
        sentido = 'Ida'
        #si son iguales, posiblemente sea un punto alejado, outlier
        if projPoint1 == projPoint2:
            viajes.loc[i,'error'] = 'Mismo punto'
            continue
    
        #la proyeccion del punto 1 debe ser menor a la del punto 2. 
        #en caso contrario es porque el vehiculo está circulando en la otra direccion
        if projPoint1 > projPoint2:
            #proyecciones sobre la vuelta
            shplPoint1 = wkt_load("POINT(%s %s)" %  (row['longitudpto1'] , row['latitudpto1']))
            projPoint1 = shplLineVuelta.project(shplPoint1, normalized=True)
        
            shplPoint2 = wkt_load("POINT(%s %s)" %  (row['longitudpto2'] , row['latitudpto2']))
            projPoint2 = shplLineVuelta.project(shplPoint2, normalized=True)    
            
            #si paso esto supongo que el viaje fue en la VUELTA
            shpLineaUsada = shplLineVuelta    
            sentido = 'Vuelta'
            #si la proyeccion de la VUELTA queda mal tambien, se descarta el punto
            if projPoint1 > projPoint2:
                viajes.loc[i,'error'] = 'Sentido no detectado'
                continue
        
        #calculo la interpolacion entre los dos puntos 
        #puntoenlinea1 = shpLineaUsada.interpolate(projPoint1, normalized=True).wkt
        #puntoenlinea2 = shpLineaUsada.interpolate(projPoint2, normalized=True).wkt
        dist = projPoint1 + ((projPoint2 -projPoint1) * float(row['porc_recorrido']))
        puntoenlinea3 = shpLineaUsada.interpolate(dist, normalized=True)   
        
        
        viajes.loc[i,'latitudpto3'] = puntoenlinea3.y
        viajes.loc[i,'longitudpto3'] = puntoenlinea3.x
        viajes.loc[i,'sentido'] = sentido
        viajes.loc[i,'distancia'] = dist
        viajes.loc[i,'projectpto1'] = projPoint1
        viajes.loc[i,'latsobrelineapto1'] = shpLineaUsada.interpolate(projPoint1, normalized=True).y
        viajes.loc[i,'lonsobrelineapto1'] = shpLineaUsada.interpolate(projPoint1, normalized=True).x
        viajes.loc[i,'projectpto2'] = projPoint2  
        viajes.loc[i,'latsobrelineapto2'] = shpLineaUsada.interpolate(projPoint2, normalized=True).y
        viajes.loc[i,'lonsobrelineapto2'] = shpLineaUsada.interpolate(projPoint2, normalized=True).x
        viajes.loc[i, 'proj1o2'] = projPoint1 if (row['porc_recorrido'] <= 0.5) else projPoint2
        
    return viajes
Пример #12
0
def sentido_init(linea, ramal, PtoControl, baseLineasRamales, tst):
    #parte 1: recorro os puntos de control en orden y voy poniendo un sentido inicial según se encuetren mas cerca de uno o de otro
    #           en caso de que estén quidistantes se asigna un sentido aleatorio
    #           además se hacen las mediciones a los sentidos de IDA y VUELTA que luego serán usados en el paso 2

    #    print('Inicializando Sentido...')

    if len(np.unique(PtoControl.file_id)) != 1:
        print('ERROR: solo es posible procesar un FILE_ID')
        exit(0)

#    lineasColeIda = sql.read_sql("SELECT linea, ramal, sentido, geom  FROM LineasCole WHERE LINEA = %s AND RAMAL = '%s' AND SENTIDO = 'I'" %(linea, ramal), consqliteBase  )
#    lineasColeVuelta = sql.read_sql("SELECT linea, ramal, sentido, geom  FROM LineasCole WHERE LINEA = %s AND RAMAL = '%s' AND SENTIDO = 'V'" %(linea, ramal), consqliteBase  )

    lineasColeIda = recuperar_linea(linea, ramal, 'I', baseLineasRamales)
    lineasColeVuelta = recuperar_linea(linea, ramal, 'V', baseLineasRamales)

    shplLineStrIda = wkt_load(lineasColeIda['geom'].values[0])
    shplLineStrVuelta = wkt_load(lineasColeVuelta['geom'].values[0])

    sentidoAleatorio = 'I'

    for i, rowpto in PtoControl.iterrows():

        shplPointaux = wkt_load("POINT(%s %s)" %
                                (rowpto['longitud'], rowpto['latitud']))

        #        shplProjIda = shplLineStrIda.project(Point(rowpto['longitud'], rowpto['latitud']))
        shplProjIda = shplLineStrIda.project(shplPointaux, normalized=True)
        shplPoint = shplLineStrIda.interpolate(shplProjIda, normalized=True)
        distanciaIda = distancia(rowpto['longitud'], rowpto['latitud'],
                                 shplPoint.x, shplPoint.y) * 1000
        PtoControl.loc[i, 'DistAIda'] = distanciaIda
        PtoControl.loc[i, 'MilePostIda'] = shplProjIda

        #        shplProjVuelta = shplLineStrVuelta.project(Point(rowpto['longitud'], rowpto['latitud']))
        shplProjVuelta = shplLineStrVuelta.project(shplPointaux,
                                                   normalized=True)
        shplPoint = shplLineStrVuelta.interpolate(shplProjVuelta,
                                                  normalized=True)
        distanciaVuelta = distancia(rowpto['longitud'], rowpto['latitud'],
                                    shplPoint.x, shplPoint.y) * 1000
        PtoControl.loc[i, 'DistAVuelta'] = distanciaVuelta
        PtoControl.loc[i, 'MilePostVuelta'] = shplProjVuelta

        if distanciaIda == distanciaVuelta:
            PtoControl.loc[i, 'Sentido'] = sentidoAleatorio
            sentidoAleatorio = 'V' if sentidoAleatorio == 'I' else 'I'
        else:
            if distanciaIda < distanciaVuelta:
                PtoControl.loc[i, 'Sentido'] = 'I'
            else:
                PtoControl.loc[i, 'Sentido'] = 'V'

        if tst == 1:
            PtoControl.loc[i, 'SentidoHis'] = PtoControl.loc[i, 'Sentido']
        else:
            PtoControl.loc[i, 'SentidoHis'] = ''

        PtoControl.loc[i, 'MilePost'] = shplProjIda if PtoControl['Sentido'][
            i] == 'I' else shplProjVuelta

    return PtoControl
Пример #13
0
def asignOrigen(PosEngine, lineaDesde, lineaHasta):

    print('-------- HELLO --- I will asign you the origin bus stops to every trip ----')
   
    cursorRamal = PosEngine.execute("SELECT a.LINEAMT, A.RAMALMT,A.LINEAGEO,A.RAMALGEO, sentido, geom FROM lineastrxgeo a, lineascole b where a.lineageo = b.linea2 and a.ramalgeo = ramal and a.baja is null  AND lineageo >= '%s' and lineageo < '%s' order by a.lineageo, a.ramalgeo" % (lineaDesde, lineaHasta))  
    
    if cursorRamal.rowcount > 0 :
        # por cada ramal de la linea
        for ramal in cursorRamal.fetchall():      
            
            lineamt = ramal[0]
            ramalmt = ramal[1]
            sentido = ramal[4]
            
            print('procesando codigolinea %s ramal %s sentido %s' % (lineamt,ramalmt, sentido) ) 
        
            #cargo las paradas para la linea - ramal - sentido
            sqlcode = ("SELECT clusterord, limiteinf FROM paradas where linea = '%s'and ramal = '%s' and sentido = '%s' order by clusterord" % (lineamt, ramalmt, sentido) )
            paradas = sql.read_sql(sqlcode  , PosEngine)  
            paradas = paradas.values.astype(np.float)
            
            if len(paradas) > 0:
                
                #recupero para cada viaje lo longitud y la latitud de los puntos de control anterior y siguiente, 
                #ademas se recupera el porcentaje del recorrido en que se encuentra el viaje desde el punto de control anterior al siguiente
                #finalmente se recupera el sentido del punto de control anterior
                sqlcode = ("SELECT B.NROTARJETAEXTERNO, B.CODIGOTRXTARJETA, A.LONGITUD longitudpto1, A.LATITUD latitudpto1, "
                           " C.LONGITUD longitudpto2, C.LATITUD latitudpto2, B.PORC_RECORRIDO "
                            " FROM  PTOCONTROL201505B A, THE_VIAJESMAYO B, PTOCONTROL201505B C "
                            " WHERE A.FILE_ID = B.FILE_ID "
                            "  AND A.C_CONTROL_POINT = B.C_CONTROL_POINT1  "
                            "  AND B.FILE_ID = C.FILE_ID "
                            "  AND B.C_CONTROL_POINT2 = C.C_CONTROL_POINT "                        
                            "  AND B.CODIGOLINEA = %s "
                            "  AND B.RAMAL = '%s' "
                            "  AND a.SENTIDO = '%s' "
                            "  AND B.DISTANCIA IS NULL  " % (lineamt, ramalmt, sentido))
    
                viajes = sql.read_sql(sqlcode  , PosEngine)            
           
                #paso a shapely
                shplLine = wkt_load(ramal[5])
                
                cantidad = len(viajes)
    
                for i, row in viajes.iterrows():                
                    if mod(i, cantidad/100) == 0:
                        print('Puntos procesados al: %i porciento' % int(i*100/cantidad))
                        
                    shplPoint1 = wkt_load("POINT(%s %s)" %  (row['longitudpto1'] , row['latitudpto1']))
                    projPoint1 = shplLine.project(shplPoint1, normalized=True)
                
                    shplPoint2 = wkt_load("POINT(%s %s)" %  (row['longitudpto2'] , row['latitudpto2']))
                    projPoint2 = shplLine.project(shplPoint2, normalized=True)
    
                    #la distancia está calculada como la proporcion del recorrido entre el pto de control anterior y siguiente
                    dist = projPoint1 + ((projPoint2 -projPoint1) * float(row['porc_recorrido']))
                    if dist > 0:
                        nroParada = paradas[paradas[:,1] < dist].argmax(axis=0)[0]
#                        print([dist,nroParada])
                        sql.execute("UPDATE THE_VIAJESMAYO SET PARADAORIGEN = %s, SENTIDO = '%s' WHERE NROTARJETAEXTERNO = '%s' AND CODIGOTRXTARJETA = '%s' " %(nroParada,sentido, row['nrotarjetaexterno'], int(row['codigotrxtarjeta'])), PosEngine)
            
            else:
                print('No tiene paradas asociadas')
    else:
        print('NO DATA available for this linea')
Пример #14
0
def addFechaDestino(PosEngine):
    cursorLineas = PosEngine.execute("SELECT DISTINCT linea, ramal, sentido FROM PARADAS ORDER BY LINEA, RAMAL, SENTIDO")  
    baseLineasRamales = bk.cargar_lineas(PosEngine)
    
    for curLinea in cursorLineas.fetchall():   
        lineamt = curLinea.linea
        ramalmt = curLinea.ramal
        sentido = curLinea.sentido
        [ramal, linea] = bk.ramalGeo(PosEngine, int(lineamt) ,ramalmt)
        print('procesando codigolinea %s ramal %s sentido %s' % (linea, ramal, sentido)) 
        
#        recupero el shape de la linea
        lineasCole = recuperar_linea(linea, ramal, sentido, baseLineasRamales)
        shplLineStr = wkt_load(lineasCole['geom'].values[0])
        
#        recuoero todos los viajes que tienen un procesado P para esa linea
#        me quedo con los segundospto de origen, parada destino, file_id
#        recupero la parada de destino y su centroide
        
        sqlcode = (" SELECT nrotarjetaexterno, codigotrxtarjeta, file_id,   "
                   "        extract(epoch from cast(fechatrx as timestamp with time zone)) - 946695600 segundospto, " #SE suma 946695600 que es la diferencia en segundos desde 1970 a 2000
                   "        c_control_point2, paradadestin, centroide "
                    " FROM THE_VIAJESMAYO A, PARADAS B "
                    " WHERE A.CODIGOLINEA = CAST(B.LINEA AS INTEGER) "
                    " 	AND A.RAMAL = B.RAMAL "
                    " 	AND A.SENTIDO = B.SENTIDO  "
                    " 	AND A.PARADADESTIN = B.CLUSTERORD  "
                    "  AND PROCESADO = 'P'"
                    "  AND A.CODIGOLINEA = %s "
                    "  AND A.RAMAL = '%s' "
                    "  AND A.SENTIDO = '%s' " % (lineamt, ramalmt, sentido) )
        
        viajes = sql.read_sql(sqlcode, PosEngine)
        
        for i, row in viajes.iterrows():
            
            controlPointOrigen = int(row.c_control_point2)
            centroideParada = row.centroide
            file_id = int(row.file_id)
            segundospto = row.segundospto
            
#           para este viaje recupero los puntos de control mayores a los segundospto
        
            sqlcode = (" 	SELECT segundospto, c_control_point,   "
                       "          TO_DATE('20000101 00:00:00', 'YYYYMMDD HH24:MI:SS') + SEGUNDOSPTO * INTERVAL '1 SECOND' fechadestino, "
                       "          latitud, longitud "
                        " FROM ptocontrol201505b "
                        " WHERE FILE_ID = %s " 
                        " AND  SEGUNDOSPTO > %s "
                        " AND C_CONTROL_POINT > %s "
                        " ORDER BY C_CONTROL_POINT " % (file_id, segundospto, controlPointOrigen) )
            
            ptosControl = sql.read_sql(sqlcode, PosEngine)  
            
            diferencia = 1
            
            for j, rowpto in ptosControl.iterrows():
                
#                algunos puntos gps vienen en cero                
                if rowpto['longitud'] < -57 and rowpto['latitud'] < -33:
    #               proyecto los puntos de conrtol, y calculo la diferencia proyectada contra el centroide de la parada
    #               mientras la distancias se achique sigo, cuando se agranda corto
        
                    shplPointaux = wkt_load("POINT(%s %s)" %  (rowpto['longitud'], rowpto['latitud'])) 
                    shplProj  = shplLineStr.project(shplPointaux, normalized=True)
                    if (centroideParada - shplProj.real) < diferencia and (centroideParada - shplProj.real) > 0:
                        diferencia = centroideParada - shplProj.real
                    else:
                        break
                
#               actualizo el registro en viaje
                sql.execute("UPDATE THE_VIAJESMAYO SET C_CONTROL_POINT_DEST = %s, FECHA_DEST = to_timestamp('%s','YYYY-MM-DD HH24:MI:SS') WHERE NROTARJETAEXTERNO = '%s' AND CODIGOTRXTARJETA = '%s' " %(rowpto['c_control_point'], rowpto['fechadestino'], row['nrotarjetaexterno'], int(row['codigotrxtarjeta'])), PosEngine)