def count_intervalINF(main, m, M):
    ans = {'events': 0, 'idlist': lt.newList('SINGLE_LINKED')}
    y = 1
    nums = om.keySet(main)

    while y <= lt.size(nums):
        num = lt.getElement(nums, y)
        pair = om.get(main, num)
        mini = me.getValue(pair)

        if float(om.minKey(mini)) > m: m == float(om.minKey(mini))
        if float(om.maxKey(mini)) < M: M == float(om.maxKey(mini))
        sub_nums = get_inter(om.keySet(mini), m, M)

        x = 1
        while x <= lt.size(sub_nums):
            sub_num = lt.getElement(sub_nums, x)
            sub_pair = om.get(mini, sub_num)
            events = me.getValue(sub_pair)

            z = 1
            while z <= lt.size(events):
                e = lt.getElement(events, z)
                id = e['artist_id']
                ans['events'] += 1
                ans['idlist'][id] = 1

                z += 1
            x += 1
        y += 1
    return ans
def reque2(main, e, E, d, D):
    if float(om.minKey(main)) > e: e == float(om.minKey(main))
    if float(om.maxKey(main)) < E: E == float(om.maxKey(main))
    nums = get_inter(om.keySet(main), e, E)

    ans = {'idlist': {}, 'for_show': lt.newList('SINGLE_LINKED')}
    y = 1
    while y <= lt.size(nums):
        num = lt.getElement(nums, y)
        pair = om.get(main, num)
        mini = me.getValue(pair)

        if float(om.minKey(mini)) > d: d == float(om.minKey(mini))
        if float(om.maxKey(mini)) < D: D == float(om.maxKey(mini))
        sub_nums = get_inter(om.keySet(mini), d, D)
        x = 1
        while x <= lt.size(sub_nums):
            sub_num = lt.getElement(sub_nums, x)
            sub_pair = om.get(mini, sub_num)
            events = me.getValue(sub_pair)

            z = 1
            while z <= lt.size(events):
                e = lt.getElement(events, z)
                id = e['track_id']
                lt.addFirst(ans['for_show'], e)
                ans['idlist'][id] = 1

                z += 1
            x += 1
        y += 1
    return ans
def reque1_SUP(main, m, M):
    if (float(om.minKey(main))) > m: m == (float(om.minKey(main)))
    if (float(om.maxKey(main))) < M: M == (float(om.maxKey(main)))
    nums = get_inter(om.keySet(main), m, M)
    dans = count_intervalSUP(main, nums)
    k = len(dans['id_list'].keys())
    ans = {'t_eve': dans['events'], 't_art': k}
    return ans
Exemple #4
0
def getAccidentsInRange(catalog, initial_date, final_date):
    """
    Reto3 - Req3
    Retorna el número de accidentes ocurridos en un rango de fechas
    """
    initial_year = str(initial_date.year)
    final_year = str(final_date.year)

    if initial_date == None and final_date == None:
        print("La fecha ingresada es errónea")
    else:

        if initial_year == final_year:

            keylow = om.get(catalog[initial_year], initial_date)["key"]
            keyhigh = om.get(catalog[initial_year], final_date)["key"]

            return 0, om.values(catalog[initial_year], keylow, keyhigh)
        else:

            keymax = om.maxKey(catalog[initial_year])
            dates_initial_year = om.values(catalog[initial_year], initial_date,
                                           keymax)

            keymin = om.minKey(catalog[final_year])
            dates_final_year = om.values(catalog[final_year], final_date,
                                         keymin)
            return 1, dates_initial_year, dates_final_year

    return None
def findBydate(map, key):
    """
    Busca los accidentes menores que una fecha.
    """
    try:
        min_key = om.minKey(map)
        rank = om.keys(map, min_key, key)
        iterator1 = it.newIterator(rank)
        buckets = lt.newList(datastructure='SINGLE_LINKED')
        while it.hasNext(iterator1):
            key = it.next(iterator1)
            entry = om.get(map, key)
            value = me.getValue(entry)
            lt.addLast(buckets, value)
        #parte dos
        total_accidents = 0
        max_accident = {'size': 0, 'date': None}
        iterator2 = it.newIterator(buckets)
        while it.hasNext(iterator2):
            value = it.next(iterator2)
            lst = value['lstaccident']
            size = int(lt.size(lst))
            if size > max_accident['size']:
                max_accident['size'] = size
                max_accident['date'] = value['date']
            total_accidents = total_accidents + size
        return (max_accident, total_accidents)
    except:
        return None
Exemple #6
0
def auxiliardelaauxiliar(catalog, initial_date, final_date):
    """
    Retorna una tupla dependiendo si el rango abarca uno o dos años
    """
    initial_year = str(initial_date.year)
    final_year = str(final_date.year)

    initial_date_accidents = om.contains(catalog[initial_year], initial_date)
    final_date_accidents = om.contains(catalog[final_year], final_date)

    i = 0

    if i == 0 and initial_date_accidents and final_date_accidents:

        if initial_year == final_year:

            keylow = om.get(catalog[initial_year], initial_date)["key"]
            keyhigh = om.get(catalog[initial_year], final_date)["key"]

            return 0, om.keys(catalog[initial_year], keylow, keyhigh)

        else:

            keymax = om.maxKey(catalog[initial_year])
            dates_initial_year = om.keys(catalog[initial_year], initial_date,
                                         keymax)

            keymin = om.minKey(catalog[final_year])
            dates_final_year = om.keys(catalog[final_year], final_date, keymin)
            return 1, dates_initial_year, dates_final_year

    return None
def Dar_cantidad_fecha_adelante(accidentes, Fecha):
    initialDate = datetime.datetime.strptime(Fecha, '%Y-%m-%d')
    finalDate = datetime.datetime.strptime(
        str(om.minKey(accidentes["Fechas"])), '%Y-%m-%d')
    tot, lista = model.rango_accidentes_severidad(accidentes, finalDate,
                                                  initialDate.date())
    return tot, lista
def getPastAccidents(analyzer, date):
    """
    Retorna el numero de crimenes en un antes de una fecha.
    """
    lst = om.keys(analyzer['datePast'], om.minKey(analyzer['datePast']), date)
    
    return lst
Exemple #9
0
def getAccidentsBeforeDate(analyzer, fecha_final):

    inicio = datetime.datetime.strptime(str(om.minKey(analyzer['dateIndex'])),
                                        '%Y-%m-%d')
    iniciodate = inicio.date()
    lst = getAccidentsByRange(analyzer, iniciodate, fecha_final)
    return lst
def accidentes_anteriores_fecha(analyzer, accidente_limite_superior):
    limite_inferior = om.minKey(analyzer["a-fecha"])
    limite_superior = transformador_fecha(accidente_limite_superior)
    rango = om.values(analyzer["a-fecha"], limite_inferior, limite_superior)
    total = 0
    llave_con_mas_accidentes = {"fecha_mas": None, "cantidad": None}
    for i in range(1, lt.size(rango) + 1):
        elemento = lt.getElement(rango, i)
        total += lt.size(elemento["accidentes_en_esta_fecha"])
        fecha = lt.getElement(elemento["accidentes_en_esta_fecha"],
                              1)["Start_Time"]
        acc_date = datetime.datetime.strptime(fecha, '%Y-%m-%d %H:%M:%S')
        acc_date = acc_date.date()
        fecha = acc_date.strftime('%d de %m de %Y')
        if (llave_con_mas_accidentes["cantidad"] == None):
            llave_con_mas_accidentes["fecha_mas"] = fecha
            llave_con_mas_accidentes["cantidad"] = lt.size(
                elemento["accidentes_en_esta_fecha"])
        elif (llave_con_mas_accidentes["cantidad"] != None):
            if (lt.size(elemento["accidentes_en_esta_fecha"]) >=
                    llave_con_mas_accidentes["cantidad"]):
                llave_con_mas_accidentes["cantidad"] = lt.size(
                    elemento["accidentes_en_esta_fecha"])
                llave_con_mas_accidentes["fecha_mas"] = fecha
    return (llave_con_mas_accidentes, total)
def genero_escuchados(catalog, valor_minHora, valor_maxHora):
    """
    """
    total_reproducciones = lt.newList('ARRAY_LIST')
    lista_listas_reproducciones = lt.newList('ARRAY_LIST')
    generos = mp.keySet(catalog['musicaGenero'])
    iteratorgenero = it.newIterator(generos)
    while it.hasNext(iteratorgenero):
        genero = it.next(iteratorgenero)
        cantidad_genero = lt.newList('ARRAY_LIST')
        MapGeneros = mp.get(catalog['musicaGenero'], genero)
        RBTgenero = me.getValue(MapGeneros)
        valor_min = om.minKey(RBTgenero)
        valor_max = om.maxKey(RBTgenero)
        lista_listas_musica = om.values(RBTgenero, valor_min, valor_max)
        lista_lista_musica = it.newIterator(lista_listas_musica)
        while it.hasNext(lista_lista_musica):
            lista_musica = it.next(lista_lista_musica)
            musicas = it.newIterator(lista_musica)
            while it.hasNext(musicas):
                musica = it.next(musicas)
                fecha = musica['created_at']
                fecha = fecha[11:]
                if fecha >= valor_minHora and fecha <= valor_maxHora:
                    if lt.isPresent(cantidad_genero,
                                    (musica['created_at'] + musica['user_id'] +
                                     musica['track_id'])) == 0:
                        lt.addLast(cantidad_genero,
                                   (musica['created_at'] + musica['user_id'] +
                                    musica['track_id']))
                        if lt.isPresent(
                                total_reproducciones,
                            (musica['created_at'] + musica['user_id'] +
                             musica['track_id'])):
                            lt.addLast(
                                total_reproducciones,
                                (musica['created_at'] + musica['user_id'] +
                                 musica['track_id']))
                    else:
                        if lt.isPresent(
                                total_reproducciones,
                            (musica['created_at'] + musica['user_id'] +
                             musica['track_id'])):
                            lt.addLast(
                                total_reproducciones,
                                (musica['created_at'] + musica['user_id'] +
                                 musica['track_id']))
        lt.addLast(lista_listas_reproducciones,
                   (genero, lt.size(cantidad_genero)))
    print('Total of repruductions between ' + valor_minHora + ' and ' +
          valor_maxHora + ' is ' + str(lt.size(total_reproducciones)))
    sa.sort(lista_listas_reproducciones, cmptamanio)
    print('================= GENRES SORTED REPRODUCTIONS ===============')
    i = 1
    while i <= lt.size(lista_listas_reproducciones):
        print('TOP ' + str(i) + ': ' +
              str(lt.getElement(lista_listas_reproducciones, i)[0]) +
              ' with ' +
              str(lt.getElement(lista_listas_reproducciones, i)[1]) + ' reps')
        i += 1
Exemple #12
0
def top3lessUsed(analyzer):
    totaltree = om.newMap(omaptype="RBT", comparefunction=compareIds)
    pqiterator = it.newIterator(vertexNames(analyzer))
    while it.hasNext(pqiterator):
        vert = int(it.next(pqiterator))
        salidas = gr.outdegree(analyzer["graph"], str(vert))
        destinos = gr.indegree(analyzer["graph"], str(vert))
        usototal = salidas + destinos
        if not om.contains(totaltree, usototal):
            om.put(totaltree, usototal, str(vert))
        else:
            A = om.get(totaltree, usototal)
            B = me.getValue(A)
            om.put(totaltree, usototal, str(B)+","+str(vert))
    estaciones = lt.newList(datastructure="ARRAY_LIST")
    while lt.size(estaciones) < 3:
        val = om.get(totaltree, om.minKey(totaltree))
        val1 = me.getValue(val)
        menortotal = val1.split(",")
        for i in menortotal:
            if lt.size(estaciones) < 3:
                K = m.get(analyzer["nameIndex"], i)
                L = me.getValue(K)
                lt.addLast(estaciones, L)
        om.deleteMin(totaltree)
    return estaciones
Exemple #13
0
def plotMostConnectedLandingPointMap(analyzer):
    """
    Crea un mapa interactivo de las conexiones del punto de conexión
    con mayor número de cables conectados
    """
    ordmap = controller.mostConnectedLandingPoint(analyzer)
    key = om.minKey(ordmap)
    vertex = me.getValue(om.get(ordmap, key))
    city = vertex.split('-')[0]
    country = vertex.split('-')[1]
    landingpoint = city + ', ' + country
    vertexcoords = me.getValue(mp.get(analyzer['vertexscoords'], vertex))
    lstvertexs = controller.getAdjacentVertexs(analyzer, vertex)
    lstcoordinates = controller.getVertexsCoordinates(analyzer, lstvertexs)
    map = folium.Map(vertexcoords, zoom_start=2.5)
    folium.Marker(vertexcoords,
                  str(landingpoint),
                  icon=folium.Icon(icon='flag', color='red')).add_to(map)
    for location in lt.iterator(lstcoordinates):
        folium.Marker(location).add_to(map)
        distance = str(hs.haversine(vertexcoords, location)) + " km"
        folium.PolyLine([vertexcoords, location],
                        color="grey",
                        weight=3.5,
                        opacity=0.35,
                        tooltip=distance).add_to(map)
    map.save("map2.html")
Exemple #14
0
def minKey(analyzer):
    """
    Llave mas pequena
    """

    respuesta = om.minKey(analyzer['fechas'])

    return (respuesta)
Exemple #15
0
def getAccidentsBeforeDate(analyzer, initialDate):
    """
    Obtiene el numero de incidentes ocurridos antes de cierta fecha
    """
    org = analyzer["DateIndex"]
    leastDate = om.minKey(org)
    incidents = om.values(org, leastDate, initialDate)
    return incidents
def generos_existentes(catalog, generos):
    """
    Retorna en modo print la informacion de los generos
    """
    lista_repetidos_total = lt.newList('ARRAY_LIST')
    list_generos = generos.split(",")
    for genero in list_generos:
        artistasNoRepetidos = lt.newList('ARRAY_LIST')
        artistasRepetidos = lt.newList('ARRAY_LIST')
        MapGeneros = mp.get(catalog['musicaGenero'], genero)
        RBTgenero = me.getValue(MapGeneros)
        valor_min = om.minKey(RBTgenero)
        valor_max = om.maxKey(RBTgenero)
        lista_listas_musica = om.values(RBTgenero, valor_min, valor_max)
        lista_lista_musica = it.newIterator(lista_listas_musica)
        while it.hasNext(lista_lista_musica):
            lista_musica = it.next(lista_lista_musica)
            musicas = it.newIterator(lista_musica)
            while it.hasNext(musicas):
                musica = it.next(musicas)
                if int(lt.isPresent(artistasNoRepetidos,
                                    musica['artist_id'])) == 0:
                    lt.addLast(artistasNoRepetidos, musica['artist_id'])
                    if int(
                            lt.isPresent(
                                artistasRepetidos,
                                (musica['created_at'] + musica['user_id'] +
                                 musica['track_id']))) == 0:
                        lt.addLast(artistasRepetidos,
                                   (musica['created_at'] + musica['user_id'] +
                                    musica['track_id']))
                        #if int(lt.isPresent(lista_repetidos_total, (musica['created_at'] + musica['user_id'] + musica['track_id']))) == 0:
                        #   lt.addLast(lista_repetidos_total, (musica['created_at'] + musica['user_id'] + musica['track_id']))
                else:
                    if int(
                            lt.isPresent(
                                artistasRepetidos,
                                (musica['created_at'] + musica['user_id'] +
                                 musica['track_id']))) == 0:
                        lt.addLast(artistasRepetidos,
                                   (musica['created_at'] + musica['user_id'] +
                                    musica['track_id']))
                        #if int(lt.isPresent(lista_repetidos_total, (musica['created_at'] + musica['user_id'] + musica['track_id']))) == 0:
                        #   lt.addLast(lista_repetidos_total, (musica['created_at'] + musica['user_id'] + musica['track_id']))

        print(
            str(genero) + ' is between ' + str(valor_min) + ' and ' +
            str(valor_max))
        print('Total of reproduction: ' + str(lt.size(artistasRepetidos)) +
              ' Total of unique artists: ' + str(lt.size(artistasNoRepetidos)))
        print('---------------  Some artists for ' + str(genero) +
              ' -----------')
        i = 0
        while i <= 9:
            print('Artist ' + str(i) + ': ' +
                  lt.getElement(artistasNoRepetidos, i))
            i += 1
    print('Total of reproduction is ' + str(lt.size(lista_repetidos_total)))
def infAnalyzer(analyzer):
    """
    Dado un analizador retorna informacion sobre este.
    """
    high = om.height(analyzer['dateIndex'])
    nodes = om.size(analyzer['dateIndex'])
    min_key = om.minKey(analyzer['dateIndex'])
    max_key = om.maxKey(analyzer['dateIndex'])
    return (high, nodes, min_key, max_key)
Exemple #18
0
def GetAccidentsBeforeDate(analyzer, BeforeDate):

    BeforeDateYear = "201" + str(BeforeDate[3])
    BeforeDateMonth = str(BeforeDate[5]) + str(BeforeDate[6])
    BeforeDateDay = str(BeforeDate[8]) + str(BeforeDate[9])
    MinDate = om.minKey(analyzer["Llaves"])

    if BeforeDateDay == "01":
        if BeforeDateMonth == "05" or BeforeDateMonth == "07" or BeforeDateMonth == "08" or BeforeDateMonth == "12":
            BeforeDateDay = "30"
            BeforeDateMonth = (str(
                BeforeDateMonth[0])) + (str(int(BeforeDateMonth[1]) - 1))
        elif BeforeDateMonth == "02" or BeforeDateMonth == "04" or BeforeDateMonth == "06" or BeforeDateMonth == "09" or BeforeDateMonth == "11":
            BeforeDateDay = "31"
            BeforeDateMonth = (str(
                BeforeDateMonth[0])) + (str(int(BeforeDateMonth[1]) - 1))
        elif BeforeDateMonth == "10":
            BeforeDateDay = "30"
            BeforeDateMonth = "09"
        elif BeforeDateMonth == "03":
            if BeforeDateYear == "2016":
                BeforeDateDay = "29"
            else:
                BeforeDateDay = "28"
            BeforeDateMonth = "02"
        else:
            BeforeDateDay = "31"
            BeforeDateMonth = "12"
            BeforeDateYear = "201" + str(int(BeforeDateYear[3]) - 1)
    elif BeforeDateDay[0] == "0":
        BeforeDateDay = str(BeforeDateDay[0]) + str(int(BeforeDateDay[1]) - 1)
    elif BeforeDateDay == "10":
        BeforeDateDay = "09"
    else:
        BeforeDateDay = str(int(BeforeDateDay) - 1)

    MaxDate = BeforeDateYear + "-" + BeforeDateMonth + "-" + BeforeDateDay
    Dates = (om.keys(analyzer["Llaves"], MinDate, MaxDate))

    TotalAccidents = 0
    MaxAccidents = 0
    MostAccidentsDate = "YYYY-MM-DD"

    for i in range(1, (lt.size(Dates) + 1)):
        Date = lt.getElement(Dates, i)
        Pair = om.get(analyzer["Llaves"], Date)
        Accidents = me.getValue(Pair)
        Number = lt.size(Accidents)
        TotalAccidents = TotalAccidents + Number
        if Number > MaxAccidents:
            MaxAccidents = Number
            MostAccidentsDate = Date

    Retorno = lt.newList("ARRAY_LIST", compareIds)
    lt.addLast(Retorno, TotalAccidents)
    lt.addLast(Retorno, MostAccidentsDate)
    return Retorno
Exemple #19
0
def AccidentesPorZona(
    analyzer,
    RadioParametro,
    LongitudParametro,
    LatitudParametro,
):
    TotalAccidentes = 0
    Fechas = om.keys(analyzer["Llaves"], om.minKey(analyzer["Llaves"]),
                     om.maxKey(analyzer["Llaves"]))
    Lunes = 0
    Martes = 0
    Miercoles = 0
    Jueves = 0
    Viernes = 0
    Sabado = 0
    Domingo = 0
    for i in range(1, (lt.size(Fechas) + 1)):
        Fecha = lt.getElement(Fechas, i)
        Pareja = om.get(analyzer["Llaves"], Fecha)
        Accidentes = me.getValue(Pareja)
        Numero = lt.size(Accidentes)
        TotalAccidentes = TotalAccidentes + Numero
        for j in range(1, (lt.size(Accidentes) + 1)):
            Accidente = lt.getElement(Accidentes, j)
            if CalculoDeRadio(RadioParametro, LongitudParametro,
                              LatitudParametro, float(Accidente["Start_Lng"]),
                              float(Accidente["Start_Lat"])):
                dia = Dia(Fecha)
                if dia == "Lunes":
                    Lunes += 1
                elif dia == "Martes":
                    Martes += 1
                elif dia == "Miercoles":
                    Miercoles += 1
                elif dia == "Jueves":
                    Jueves += 1
                elif dia == "Viernes":
                    Viernes += 1
                elif dia == "Sabado":
                    Sabado += 1
                elif dia == "Domingo":
                    Domingo += 1

    Total = Lunes + Martes + Miercoles + Jueves + Viernes + Sabado + Domingo
    Retorno = lt.newList("ARRAY_LIST", compareIds)
    lt.addLast(Retorno, Lunes)
    lt.addLast(Retorno, Martes)
    lt.addLast(Retorno, Miercoles)
    lt.addLast(Retorno, Jueves)
    lt.addLast(Retorno, Viernes)
    lt.addLast(Retorno, Sabado)
    lt.addLast(Retorno, Domingo)
    lt.addLast(Retorno, Total)
    return Retorno
def total_antes_de_una_fecha(analyzer, fecha):
    date = fecha_convertidor_consultas(fecha)
    a = om.keys(analyzer["index"], om.minKey(analyzer["index"]), date)
    lt.removeLast(a)
    total = 0
    it1 = lit.newIterator(a)
    while lit.hasNext(it1):
        n = lit.next(it1)
        b = om.get(analyzer["index"], n)
        c = me.getValue(b)
        total += lt.size(c)
    return total
Exemple #21
0
def llavesHasta(cont, date):
    llaves = {}
    for i in range(2016, 2020):
        if cont[str(i)][0] != None:
            if str(i) not in str(date):
                llaves[str(i)] = om.keySet(cont['dateIndex'])
            else:
                initialDate = om.minKey(cont[str(i)][0]['dateIndex'])
                finalDate = om.floor(cont[str(i)][0]['dateIndex'], date)
                llaves[str(i)] = om.keys(cont[str(i)][0]['dateIndex'],
                                         initialDate, finalDate)
                break
    return llaves
def bono(mapa, punto_referencia1, punto_referencia2, radio):
    fecha1 = om.minKey(mapa["a-fecha"])
    fecha2 = om.maxKey(mapa["a-fecha"])
    a_iterar = om.values(mapa["a-fecha"], fecha1, fecha2)
    a_comparar = Bono.distance(punto_referencia1, punto_referencia2, radio)
    xd = lt.newList("ARRAY_LIST")
    for i in range(1, lt.size(a_iterar) + 1):
        accidentes = lt.getElement(a_iterar, i)["accidentes_en_esta_fecha"]
        for e in range(1, lt.size(accidentes) + 1):
            elemento = lt.getElement(accidentes, e)
            if (Bono.distance(punto_referencia1,
                              elemento["Start_Lat"] + elemento["Start_Lng"],
                              radio) == a_comparar):
                lt.addLast(elemento["Start_Time"])
Exemple #23
0
def getAccidentsBeforeDate(year_RBT, search_date):
    """
    Reto3 - Req2
    Retorna el número de accidentes ocurridos anteriores a una fecha
    """
    Accidents_Date = om.get(year_RBT, search_date)

    if Accidents_Date != None:

        key_date = Accidents_Date["key"]
        keylow = om.minKey(year_RBT)

        return om.keys(year_RBT, keylow, key_date)
    return None
def getAccidentsLast(analyzer, day):
    
    aDate = om.keys(analyzer['date'],om.minKey(analyzer['date']),day)
    iterator= it.newIterator(aDate)
    cuantos=0
    diaMayor=None
    cuantosMayor=0
    while (it.hasNext(iterator)):
        info= it.next(iterator)
        valor = om.get(analyzer['date'],info)['value']
        cuantos += lt.size(valor['accidents'])
        if(lt.size(valor['accidents'])>cuantosMayor):
            cuantosMayor=lt.size(valor['accidents'])
            diaMayor=info
    print("accidentes totales: "+str(cuantos)+", la fecha con mayor accidentes es : "+str(diaMayor))
Exemple #25
0
def auxiliarYearIterator(catalog,year_iterator,criteria,down_limit_date,up_limit_date):
    """
    Función Axuiliar de las funciones Auxiliares.
    """
    if criteria == 0:                   #Caso único para getInRange cuando el rango no soprepasa un año. 
        keylow = om.get(catalog[year_iterator],down_limit_date)['key']
        keyhigh =  om.get(catalog[year_iterator],up_limit_date)['key']
        Year_Dates = om.keys(catalog[year_iterator],keylow,keyhigh)

    elif criteria == 1:                 #Caso en el que se necesita las fechas de todo el año. 
        keyhigh = om.maxKey(catalog[year_iterator])
        keylow = om.minKey(catalog[year_iterator])
        Year_Dates = om.keys(catalog[year_iterator],keylow,keyhigh)
    
    elif criteria == 2:                 #Caso en el que dada una fecha límite superior, se busca la menor llave del árbol.
        keylow = om.minKey(catalog[year_iterator])
        keyhigh = om.get(catalog[year_iterator],up_limit_date)['key']
        Year_Dates = om.keys(catalog[year_iterator],keylow,keyhigh)

    elif criteria == 3:                 #Caso en el que dada una fecha límite inferior, se busca la mayor llave del árbol.
        keyhigh = om.maxKey(catalog[year_iterator])
        keylow = om.get(catalog[year_iterator],down_limit_date)['key']      
        Year_Dates = om.keys(catalog[year_iterator],keylow,keyhigh)
    return Year_Dates
Exemple #26
0
def llavesEnRango(cont, initialDate, finalDate, anio):
    llaves = {}
    if anio['type'] == 0:
        llaves[anio['anio']] = om.keys(cont[anio['anio']][0]['dateIndex'],
                                       initialDate, finalDate)
    else:
        for i in range(int(str(initialDate)[:4]), int(str(finalDate)[:4]) + 1):
            if str(i) in str(initialDate):
                mayor = om.maxKey(cont[str(i)][0]['dateIndex'])
                llaves[str(i)] = om.keys(cont[str(i)][0]['dateIndex'],
                                         initialDate, mayor)
            elif str(i) in str(finalDate):
                menor = om.minKey(cont[str(i)][0]['dateIndex'])
                llaves[str(i)] = om.keys(cont[str(i)][0]['dateIndex'], menor,
                                         finalDate)
            else:
                llaves[str(i)] = om.keySet(cont[str(i)][0]['dateIndex'])
    return llaves
Exemple #27
0
def getEventByTimeAndTempo(mapTempo, mapNum, analyzer):
    """
    Retorna el numero de tracks unicos y un mapa con ellos como
    llave
    """
    tracksMap = mp.newMap(maptype='PROBING')
    maxKey = om.minKey(mapNum)
    entryMaxKey = om.get(mapNum, maxKey)
    valueMaxKey = me.getValue(entryMaxKey)
    entryInterval = mp.get(analyzer['genre_intervals'], valueMaxKey)
    valueInterval = me.getValue(entryInterval)
    lstInterval = om.values(mapTempo, valueInterval[0], valueInterval[1])
    for track in lt.iterator(lstInterval):
        for uTrack in lt.iterator(track):
            trackId = uTrack['track_id']
            mp.put(tracksMap, trackId, uTrack)
    totaltracks = mp.size(tracksMap)
    return tracksMap, totaltracks
def getAccidentsByGeographicZone(analyzer, longitud, latitud, radio):
    cant_accidentes = om.size(analyzer['dateIndex'])
    llaves = om.keys(analyzer['dateIndex'], om.minKey(analyzer['dateIndex']),
                     om.maxKey(analyzer['dateIndex']))
    accidentes = m.newMap(numelements=17,
                          prime=109345121,
                          maptype='CHAINING',
                          loadfactor=0.5,
                          comparefunction=compararDias)
    accidentes_reportados = 0
    i = 1
    while i <= cant_accidentes:
        fecha = om.get(analyzer['dateIndex'], lt.getElement(llaves, i))
        lista_accidentes = fecha['value']['lstaccidents']
        j = 1
        while j <= lt.size(lista_accidentes):
            accidente = lt.getElement(lista_accidentes, j)
            long = float(accidente['Start_Lng'])
            lat = float(accidente['Start_Lat'])
            distancia = haversine(longitud, latitud, long, lat)
            if distancia <= radio:
                fecha = accidente['Start_Time']
                anio = fecha[:4]
                mes = fecha[5:7]
                dia = fecha[8:10]
                dia_semana = calcular_dia(int(dia), int(mes), int(anio))
                esta_dia = m.contains(accidentes, dia_semana)
                if not esta_dia:
                    lista = lt.newList(datastructure='SINGLE_LINKED',
                                       cmpfunction=None)
                    m.put(accidentes, dia_semana, lista)
                lis = m.get(accidentes, dia_semana)
                lis = lis['value']
                lt.addLast(lis, accidente)
                m.put(accidentes, dia_semana, lis)
                accidentes_reportados += 1
            j += 1
        i += 1
    return accidentes_reportados, accidentes
def test_remove(tree):
    tree = om.put(tree, 21, 'book21')
    tree = om.put(tree, 7, 'book7')
    tree = om.put(tree, 30, 'book30')
    tree = om.put(tree, 5, 'book5')
    tree = om.put(tree, 4, 'book4')
    tree = om.put(tree, 3, 'book3')
    tree = om.put(tree, 20, 'book20')
    tree = om.put(tree, 25, 'book25')
    tree = om.put(tree, 35, 'book35')
    tree = om.put(tree, 29, 'book29')
    tree = om.put(tree, 11, 'book11')
    tree = om.put(tree, 15, 'book15')
    tree = om.remove(tree, 21)
    tree = om.put(tree, 10, 'book10')
    tree = om.put(tree, 10, 'book10A')
    assert om.contains(tree, 29) is True
    assert om.contains(tree, 28) is False
    assert om.minKey(tree) == 3
    assert om.maxKey(tree) == 35
    om.deleteMin(tree)
    assert om.contains(tree, 3) is False
Exemple #30
0
def test_contains(tree):
    tree = om.put(tree, 21, 'book21')
    tree = om.put(tree, 7, 'book7')
    tree = om.put(tree, 30, 'book30')
    tree = om.put(tree, 5, 'book5')
    tree = om.put(tree, 4, 'book4')
    tree = om.put(tree, 3, 'book3')
    tree = om.put(tree, 20, 'book20')
    tree = om.put(tree, 25, 'book25')
    tree = om.put(tree, 35, 'book35')
    tree = om.put(tree, 29, 'book29')
    tree = om.put(tree, 11, 'book11')
    tree = om.put(tree, 15, 'book15')
    tree = om.put(tree, 10, 'book10')
    tree = om.put(tree, 10, 'book10A')
    assert om.contains(tree, 29) is True
    assert om.contains(tree, 50) is False
    assert om.minKey(tree) == 3
    assert om.maxKey(tree) == 35
    tree = om.put(tree, 50, 'book50')
    assert om.contains(tree, 50) is True
    assert om.maxKey(tree) == 50