def getAccidentsHour(analyzer, dayin, dayend):
    
    aDate = om.keys(analyzer['hour'],dayin,dayend)
    iterator= it.newIterator(aDate)
    sev = m.newMap(numelements=15, maptype='PROBING', comparefunction=compareSeverities)
    cuantos=0
    while (it.hasNext(iterator)):
        info= it.next(iterator)
        valor = om.get(analyzer['hour'],info)['value']
        cuantos += lt.size(valor['accidents'])
        llaves = m.keySet(valor['severities'])
        iterator1= it.newIterator(llaves)
        while(it.hasNext(iterator1)):
            info1= it.next(iterator1)
            val = m.get(valor['severities'], info1)['value']['listBySeverity']
            entry = m.get(sev, info1)
            if(entry is None):
                dic={'severity': info1, 'cuantos':lt.size(val)}
                m.put(sev,info1,dic)
            else:
                entry['value']['cuantos']+=lt.size(val)
    
    data=" "
    cuan=0
    keys= m.keySet(sev)
    ite=it.newIterator(keys)
    while(it.hasNext(ite)):
        inf=it.next(ite)
        value = m.get(sev,inf)['value']['cuantos']
        if(value>cuan):
            cuan= value
            data= inf

            
    print("accidentes totales: "+str(cuantos)+", la severidad con mayor \n accidentes es : "+str(data)+ "con : "+str(cuan)+" accidentes.")
Exemplo n.º 2
0
def getHashtagsByTime(analyzer, initialValue, finalValue):
    """
    Crea un mapa que tiene como llaves el valor 'created_at' de los hashtags
    """
    values = mp.valueSet(analyzer["hashtags"])
    mapHash = om.newMap('RBT')
    for value in lt.iterator(values):
        date = value['created_at']
        time = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S').time()
        hashEntry = om.get(mapHash, time)
        if hashEntry is None:
            hashEntry = newDataEntry(value)
            om.put(mapHash, time, hashEntry)
        else:
            hashEntry = me.getValue(hashEntry)
        lt.addLast(hashEntry, value)

    maps = mp.newMap(maptype='PROBING')
    times = om.values(mapHash, initialValue, finalValue)
    for tracks in lt.iterator(times):
        for uTrack in lt.iterator(tracks):
            entry = mp.get(maps, uTrack['track_id'])
            if entry is None:
                entry = newDataEntry(uTrack)
                mp.put(maps, uTrack['track_id'], entry)
            else:
                entry = me.getValue(entry)
            lt.addLast(entry, uTrack['hashtag'].lower())
    return maps
Exemplo n.º 3
0
def doSentimentAnalysis(analyzer, tempo_lo, tempo_hi):
    lst_events = om.values(analyzer['tempo'], tempo_lo, tempo_hi)
    track_map = analyzer['tracks']
    hashtag_vader_map = analyzer['hashtag_vader']

    tracks = lt.newList()

    for lstevents in lt.iterator(lst_events):
        for ev_ in lt.iterator(lstevents['events']):
            # get id
            entry = om.get(track_map, ev_['track_id'])
            if entry is not None:
                value = me.getValue(entry)
                # iterate over hastags
                vader_vals = []
                for ht_ in lt.iterator(value['hashtags']):
                    vader_val = mp.get(hashtag_vader_map, ht_)
                    if vader_val is not None:
                        vader_val = vader_val['value']
                        try:
                            vader_val = float(vader_val)
                            vader_vals.append(vader_val)
                        except ValueError:
                            continue
            n_hs = len(vader_vals)
            if n_hs == 0:
                mean_vader = 0
            else:
                mean_vader = sum(vader_vals) / n_hs
            track_out = TrackOutput(ev_['track_id'], n_hs, mean_vader)
            lt.addLast(tracks, track_out)

    return tracks, lt.size(tracks)
Exemplo n.º 4
0
def addDate(citibike, date, bikeId, origin, destination, duration):
    if not om.contains(citibike['dates'], date):  # No está la fecha
        ids = {}  # Agregar info
        stops = lt.newList(cmpfunction=compareIds)
        lt.addFirst(stops, origin)
        lt.addFirst(stops, destination)
        ids[bikeId] = (duration, stops)
        om.put(citibike['dates'], date, ids)
    else:  # Está la fecha
        value = om.get(citibike['dates'], date)

        # print(value.keys())
        # print(bikeId)
        if bikeId not in value.keys():  # No está la bici
            stops = lt.newList(cmpfunction=compareIds)  # Agregar bici
            lt.addFirst(stops, origin)
            lt.addFirst(stops, destination)
            value[bikeId] = (duration, stops)
        else:  # Está la bici
            # print(value[bikeId])
            uso = value[bikeId][0]
            value[bikeId] = (uso + duration, value[bikeId][1])
            if not lt.isPresent(value[bikeId][1],
                                origin):  # No está la estación
                lt.addLast(value[bikeId][1], origin)
            else:
                pass
            if not lt.isPresent(value[bikeId][1],
                                destination):  # No está la estación
                lt.addLast(value[bikeId][1], destination)
            else:
                pass
Exemplo n.º 5
0
def getAccidentsByDate(analyzer, date):

    accidentDate = om.get(analyzer['dateIndex'], date)
    if accidentDate:
        if accidentDate['key'] is not None:
            lst = lt.newList('ARRAY_LIST')
            severityMap = me.getValue(accidentDate)['severityIndex']
            severityNum1 = m.get(severityMap, '1')
            severityNum2 = m.get(severityMap, '2')
            severityNum3 = m.get(severityMap, '3')
            severityNum4 = m.get(severityMap, '4')
            if (severityNum1 is not None):
                lt.addLast(lst,
                           (m.size(me.getValue(severityNum1)['lstseverity'])))
            else:
                lt.addLast(lst, 0)
            if (severityNum2 is not None):
                lt.addLast(lst,
                           (m.size(me.getValue(severityNum2)['lstseverity'])))
            else:
                lt.addLast(lst, 0)
            if (severityNum3 is not None):
                lt.addLast(lst,
                           (m.size(me.getValue(severityNum3)['lstseverity'])))
            else:
                lt.addLast(lst, 0)
            if (severityNum4 is not None):
                lt.addLast(lst,
                           (m.size(me.getValue(severityNum4)['lstseverity'])))
            else:
                lt.addLast(lst, 0)
            return (lt.getElement(lst, 1), lt.getElement(lst, 2),
                    lt.getElement(lst, 3), lt.getElement(lst, 4))
    else:
        return 0
Exemplo n.º 6
0
def updateAccidentInHour(hour_RBT,accident):
    """
    RETO3 - REQ5
    Adiciona la hora en la que ocurrió un accidente como llave al RBT.
    Actualiza el entry en el caso de que la hora ya exista:
        Se actualiza el mapa de severidades.
        Se actualiza la lista de accidentes ocurridos en esa hora.
    """
    ocurred_date = accident['Start_Time']
    fifteen_minutes = datetime.timedelta(minutes=15)

    acc_date = datetime.datetime.strptime(ocurred_date, '%Y-%m-%d %H:%M:%S')
    acc_minutes = datetime.timedelta(minutes=acc_date.minute)
   
    if acc_minutes == 00:
        rbt_accident_time = datetime.timedelta(hours=acc_date.hour, minutes = 00)

    elif acc_minutes <= fifteen_minutes:
        rbt_accident_time = datetime.timedelta(hours=acc_date.hour, minutes = 00)

    elif acc_minutes >= fifteen_minutes and acc_minutes <= (fifteen_minutes)*3:
        rbt_accident_time = datetime.timedelta(hours=acc_date.hour, minutes = 30)
    
    elif acc_minutes > (fifteen_minutes)*3:
        rbt_accident_time = datetime.timedelta(hours=(acc_date.hour + 1 ), minutes = 00)

    entry = om.get(hour_RBT,rbt_accident_time)
    if entry is None:
        hour_entry = newEntry()
        om.put(hour_RBT,rbt_accident_time,hour_entry)
    else:
        hour_entry = me.getValue(entry)

    addSeverityToEntry(hour_entry,accident)
Exemplo n.º 7
0
def topCabsInDate(catalog, date):
    """
    Identifica los N taxis con más puntos para en una fecha determinada.
    """
    topPoints = {}
    taxiDate = om.get(catalog['dates'], date)
    if taxiDate:
        if taxiDate[
                'key'] is not None:  #Se ingresa a la información en la fecha ingresada
            taxiMap = me.getValue(taxiDate)['taxiId']
            keySet = m.keySet(taxiMap)
            iteratorKS = it.newIterator(keySet)
            while it.hasNext(
                    iteratorKS
            ):  #Se recorre cada ID de taxi en la fecha ingresada y se calculan sus respectivos puntos
                taxiId = it.next(iteratorKS)
                info = m.get(taxiMap, taxiId)
                services = (m.size(me.getValue(info)['lstTaxi']))
                distance = (me.getValue(info)['distance'])
                cash = (me.getValue(info)['cash'])
                points = (distance / cash) * services
                topPoints[taxiId] = round(points, 3)
            pointsSorted = sorted(
                topPoints.items(), key=operator.itemgetter(1),
                reverse=True)  #Se ordenan los taxis de acuerdo a los puntos
            return topPoints, pointsSorted
    else:
        return 0, 1
Exemplo n.º 8
0
def getAccidentsByDate(date, analyzer):
    try:
        cant1 = 0
        cant2 = 0
        cant3 = 0
        cant4 = 0
        events = om.get(analyzer["dateIndex"], date)
        accidents_date = me.getValue(events)
        total = lt.size(accidents_date["crashes"])
        sev1 = m.get(accidents_date["accident_type"], "1")
        if sev1 != None:
            v1 = me.getValue(sev1)
            cant1 = lt.size(v1["accidents"])
        sev2 = m.get(accidents_date["accident_type"], "2")
        if sev2 != None:
            v2 = me.getValue(sev2)
            cant2 = lt.size(v2["accidents"])
        sev3 = m.get(accidents_date["accident_type"], "3")
        if sev3 != None:
            v3 = me.getValue(sev3)
            cant3 = lt.size(v3["accidents"])
        sev4 = m.get(accidents_date["accident_type"], "4")
        if sev4 != None:
            v4 = me.getValue(sev4)
            cant4 = lt.size(v4["accidents"])
        res = (total, cant1, cant2, cant3, cant4)
    except:
        res = None
    return res
Exemplo n.º 9
0
def updateHour_Tree(catalog, event):
    Hour = timeStrip(event)
    entry = om.get(catalog['hourTree'], Hour)
    if entry is None:
        hourEntry = mp.newMap(numelements=9, maptype='PROBING')

        for genre in lt.iterator(mp.valueSet(catalog['genres'])):
            if float(event['tempo']) >= genre['min_tempo'] and float(
                    event['tempo']) <= genre['max_tempo']:
                eventsInGenre = lt.newList(datastructure='ARRAY_LIST')
                lt.addLast(eventsInGenre, event)
                mp.put(hourEntry, genre['name'], eventsInGenre)

        om.put(catalog['hourTree'], Hour, hourEntry)
    else:
        hourEntry = me.getValue(entry)
        #mete el event al mapa
        for genre in lt.iterator(mp.valueSet(catalog['genres'])):
            if float(event['tempo']) >= genre['min_tempo'] and float(
                    event['tempo']) <= genre['max_tempo']:
                parejaEventsInGenre = mp.get(hourEntry, genre['name'])

                if (parejaEventsInGenre is None):
                    eventsInGenre = lt.newList(datastructure='ARRAY_LIST')
                    lt.addLast(eventsInGenre, event)
                    mp.put(hourEntry, genre['name'], eventsInGenre)
                else:
                    eventsInGenre = me.getValue(parejaEventsInGenre)
                    lt.addLast(eventsInGenre, event)
def getAccidentsByHourRange(analizer, initial_hour, final_hour):
    fechas = om.keys(analizer['hourIndex'], initial_hour, final_hour)
    cant_fechas = lt.size(fechas)
    categorias = m.newMap(numelements=0,
                          maptype='CHAINING',
                          loadfactor=0.5,
                          comparefunction=comparar_categorias)
    cant_accidentes = 0
    i = 1
    while i <= cant_fechas:
        llave = lt.getElement(fechas, i)
        arbol = om.get(analizer['hourIndex'], llave)
        severityIndex = arbol['value']['severityIndex']
        llaves_severityIndex = m.keySet(severityIndex)
        j = 1
        while j <= lt.size(llaves_severityIndex):
            categoria = lt.getElement(llaves_severityIndex, j)
            cat = m.get(severityIndex, categoria)
            accidentes = lt.size(cat['value']['lstofseverities'])
            cant_accidentes += accidentes
            esta_categoria = m.contains(categorias, categoria)
            if not esta_categoria:
                m.put(categorias, categoria, 0)
            cant = m.get(categorias, categoria)
            cant = cant['value']
            cant += accidentes
            m.put(categorias, categoria, cant)
            j += 1
        i += 1
    return cant_accidentes, categorias
Exemplo n.º 11
0
def requerimiento1(diccionario, feature, minm, maxm):
    minm = float(minm)
    maxm = float(maxm)
    feature = feature.lower()
    diccionario[feature] = om.newMap(omaptype='RBT',
                                     comparefunction=compareByFeature)
    iterador = li.newIterator(diccionario['audio-events'])

    while li.hasNext(iterador):
        event = li.next(iterador)
        id = float(event[feature])

        p = om.contains(diccionario[feature], id)
        if not p:
            lista = lt.newList(datastructure='ARRAY_LIST')
            lt.addLast(lista, event)
        else:
            couple = om.get(diccionario[feature], id)
            lista = me.getValue(couple)
            lt.addLast(lista, event)
        om.put(diccionario[feature], id, lista)
    values = om.values(diccionario[feature], minm, maxm)

    total = 0

    iterador2 = li.newIterator(values)
    while li.hasNext(iterador2):
        lista = li.next(iterador2)
        size = lt.size(lista)
        total += size

    return total
def updateHourIndex(map, accidente):
    """
    Se toma la fecha del crimen y se busca si ya existe en el arbol
    dicha fecha.  Si es asi, se adiciona a su lista de crimenes
    y se actualiza el indice de tipos de crimenes.

    Si no se encuentra creado un nodo para esa fecha en el arbol
    se crea y se actualiza el indice de tipos de crimenes
    """
    occurredhour = accidente['Start_Time'][11:]
    hora = int(occurredhour[:2])
    minutos = int(occurredhour[3:5])

    if minutos <= 30:
        minutos = 30
    elif minutos < 60:
        if hora == 23:
            hora = int('23')
            minutos = 59
        else:
            hora += 1
            minutos = int('00')
    segundos = int('00')
    accidenthour = datetime.time(hora, minutos, segundos)

    entry = om.get(map, accidenthour)
    if entry is None:
        datentry = newDataEntryHour(accidente)
        om.put(map, accidenthour, datentry)
    else:
        datentry = me.getValue(entry)
    addHourIndex(datentry, accidente)
    return map
Exemplo n.º 13
0
def estados_en_un_rango(analyzer, initialDate, finalDate):
    lst = om.keys(analyzer["fechas_accidente"], initialDate, finalDate)
    lstiterator = it.newIterator(lst)
    estados = {}
    fecha = ""
    mayor = 0
    while (it.hasNext(lstiterator)):
        lstdate = it.next(lstiterator)
        acc = om.get(analyzer["fechas_accidente"], lstdate)
        lda = me.getValue(acc)
        size_total = 0
        keys = m.keySet(lda["estado_del_accidente"])
        itera = it.newIterator(keys)
        while (it.hasNext(itera)):
            lstk = it.next(itera)
            parej = m.get(lda["estado_del_accidente"], lstk)
            valu = me.getValue(parej)
            size = lt.size(valu["lista_de_accidentes"])
            size_total += size
            if lstk in estados:
                estados[lstk] += size
            else:
                estados[lstk] = size
        if size_total > mayor:
            fecha = lstdate
            mayor = size_total
    estad = mayor_valor(estados)
    return (fecha, estad)
def addConnection_directed(analyzer, connection):
    origin = connection['\ufefforigin']
    destination = connection['destination']
    cable_id = connection['cable_name']
    cable_lenght = DistanceHaversine(origin, destination, analyzer)

    verticeA = "<{}>-<{}>".format(origin, cable_id)
    verticeB = "<{}>-<{}>".format(destination, cable_id)

    containsA = gr.containsVertex(analyzer['connections_directed'], verticeA)
    containsB = gr.containsVertex(analyzer['connections_directed'], verticeB)
    if not containsA and not containsB:
        gr.insertVertex(analyzer['connections_directed'], verticeA)
        gr.insertVertex(analyzer['connections_directed'], verticeB)

        listilla = [origin, cable_id, verticeA]

        lt.addLast(analyzer['vertices'], listilla)

        mapa = analyzer['landing_points']
        pareja = om.get(mapa, origin)
        valor = me.getValue(pareja)
        lista_cables = valor['cables']
        lt.addLast(lista_cables, verticeA)

        gr.addEdge(analyzer['connections_directed'], verticeA, verticeB,
                   cable_lenght)
Exemplo n.º 15
0
def EstudyMusic(analyzer, min_instru, max_instru, min_tempo, max_tempo):
    track_map = om.newMap(omaptype='RBT', comparefunction=compareDates)
    videosct = lt.newList("ARRAY_LIST")
    track_map = om.newMap(omaptype='RBT', comparefunction=compareDates)
    videosct = lt.newList("ARRAY_LIST")

    # filtro 1: por minKey y MaxKey de energy
    lst = om.values(analyzer["instrumentalness"], min_instru, max_instru)
    for lstdate in lt.iterator(lst):

        for element in lt.iterator(lstdate["events"]):
            if (element["tempo"] > min_tempo) and (element["tempo"] <
                                                   max_tempo):
                if om.contains(track_map, element["track_id"]) == False:
                    om.put(
                        track_map, element["track_id"], {
                            "instrumentalness": element["instrumentalness"],
                            "tempo": element["tempo"]
                        })
    size = om.size(track_map)
    print("Total of unique track events: ", size)
    for pos in random.sample(range(1, size), 5):
        key = om.select(track_map, pos)
        item = om.get(track_map, key)
        value = me.getValue(item)
        lt.addLast(
            videosct, {
                "track_id": key,
                "instrumentalness": value["instrumentalness"],
                "tempo": value["tempo"]
            })
    return videosct
Exemplo n.º 16
0
def addTaxi(analyzer, trip):

    ids = analyzer["taxis"]
    newPoints = 0
    tripMiles = trip["trip_miles"]
    tripTotal = trip["trip_total"]
    timeStamp = trip["trip_start_timestamp"]
    tripDate = timeStamp[0:10]
    if tripTotal != "0.0" and tripTotal != "":
        newPoints = float(tripMiles) / float(tripTotal)
    else:
        newPoints = 0

    if trip["taxi_id"] not in ids["elements"]:
        lt.addLast(analyzer["taxis"], trip["taxi_id"])
        pointsDate = newPoints, tripDate
        pointsList = lt.newList("ARRAY_LIST", None)
        lt.addLast(pointsList, pointsDate)
        om.put(analyzer["taxisPoints"], trip["taxi_id"], pointsList)
    else:
        info = om.get(analyzer["taxisPoints"], trip["taxi_id"])
        pointsList = info["value"]
        pointsDate = lt.lastElement(pointsList)
        oldPoints = pointsDate[0]
        points = oldPoints + newPoints
        newPointsDate = points, tripDate
        lt.addLast(pointsList, newPointsDate)
        om.put(analyzer["taxisPoints"], trip["taxi_id"], pointsList)

    return analyzer
def getAccidentsBySeverity(analyzer, date):
    entry = om.get(analyzer["date_index"], date)
    dateEntry = me.getValue(entry)
    try:
        entryAccidentsBySeverity1 = m.get(dateEntry["severity_index"], "1")
        accidentsBySeverity1 = me.getValue(entryAccidentsBySeverity1)
        severity1Size = lt.size(accidentsBySeverity1["lstseverities"])
    except:
        severity1Size = 0

    try:
        entryAccidentsBySeverity2 = m.get(dateEntry["severity_index"], "2")
        accidentsBySeverity2 = me.getValue(entryAccidentsBySeverity2)
        severity2Size = lt.size(accidentsBySeverity2["lstseverities"])
    except:
        severity2Size = 0

    try:
        entryAccidentsBySeverity3 = m.get(dateEntry["severity_index"], "3")
        accidentsBySeverity3 = me.getValue(entryAccidentsBySeverity3)
        severity3Size = lt.size(accidentsBySeverity3["lstseverities"])
    except:
        severity3Size = 0

    return severity1Size, severity2Size, severity3Size
Exemplo n.º 18
0
def travel_map(Map, tree=False):
    lst = om.keySet(Map) if tree else m.keySet(Map)
    iter = it.newIterator(lst)
    while it.hasNext(iter):
        key = it.next(iter)
        value = om.get(Map, key) if tree else m.get(Map, key)
        yield key, (None if value is None else value["value"])
Exemplo n.º 19
0
def getBeforeDate(catalog,search_date):
    """
    Función Auxiliar REQ2
    Retorna una lista, cada posición tiene
    las llaves del RBT de un año.

    """       
    year_search_date = search_date.year
    year_bst = catalog[str(year_search_date)]  
    year_RBT_Values_Keys_lst = []

    date_accidents = om.get(year_bst,search_date)
    if date_accidents != None:
        
        yearIterator = int(search_date.year)                            #Se recorren los años desde el ingresado hasta la primera fecha 
        while yearIterator > 2015:                                      #registrada en 2016                                    
            
            if yearIterator == int(year_search_date):
                year_values = auxiliarYearIterator(catalog,str(yearIterator),2,None,search_date)                    
            else:
                year_values = auxiliarYearIterator(catalog,str(yearIterator),1,None,None)
            
            year_RBT_Values_Keys_lst.append(year_values)
            yearIterator = yearIterator - 1    

        return year_RBT_Values_Keys_lst
    return None
Exemplo n.º 20
0
def getAccidentsByDate(analyzer, date):
    """
    Retorna el numero de accidentes en una fecha.
    """
    lst = om.get(analyzer['dateIndex'], date)
    data = lst['value']['lstaccidents']
    return data
Exemplo n.º 21
0
def getAccidentsByDate(analyzer, initialDate):
    """
    Para una fecha determinada, retorna el numero de accidentes
    por severidad .
    """
    accidentdate = om.get(analyzer['dateIndex'], initialDate)
    return me.getValue(accidentdate)
Exemplo n.º 22
0
def addHTinfo(catalog, lista, cancion):
    arbol = catalog['date_RBT']
    fecha = cancion["created_at"]
    entry = om.get(arbol, fecha)
    tabla_Gen = me.getValue(entry)
    llenado(tabla_Gen['generos'], lista, cancion)
    return arbol
Exemplo n.º 23
0
def musicInTime(maps, time1, time2):
    '''
    Funcion que busca los eventos en un rango de tiempo.
    retorna la cantidad de eventos de escucha totales y
    un mapa con los eventos
    '''
    init = seconds(time1)
    final = seconds(time2)
    if init < 0 or final < 0:
        return 0
    else:
        # thelist = lt.newList("ARRAY_LIST")
        themap = om.newMap(omaptype='RBT')
        eventsq = 0
        # Sacamos lo eventos en el rango deseado por el usuario
        getusers = om.values(maps['time'], init, final)
        # Recorremos la lista de las listas de los eventos
        iterator = ite.newIterator(getusers)
        while ite.hasNext(iterator):
            eventslist = ite.next(iterator)
            # Para encontrar el numero total de eventos en el rango
            newiterator = ite.newIterator(eventslist['lstevent'])
            while ite.hasNext(newiterator):
                event = ite.next(newiterator)
                eventsq += 1
                entry = om.get(themap, float(event['tempo']))
                if entry is None:
                    dataentry = newDataEntry(event)
                    om.put(themap, float(event['tempo']), dataentry)
                else:
                    dataentry = me.getValue(entry)
                    addEntry(dataentry, event)
        return eventsq, themap
Exemplo n.º 24
0
def addSongToTreeEnergy(mapt, cancion):
    caracteristica = 'energy'
    categoria = cancion["energy"]
    entry = om.get(mapt, categoria)
    filtrado = {}
    filtrado["track_id"] = cancion["track_id"]
    filtrado["instrumentalness"] = cancion["instrumentalness"]
    filtrado["tempo"] = cancion["tempo"]
    filtrado["danceability"] = cancion["danceability"]
    filtrado["energy"] = cancion["energy"]
    if entry is None:
        dataentry = newArtEntry(caracteristica, filtrado)
        om.put(mapt, categoria, dataentry)
        lt.addLast(dataentry['canciones'], filtrado)
        lt.addLast(dataentry['artistas'], cancion["artist_id"])
        lt.addLast(dataentry["reproducciones"], cancion["track_id"])

    else:
        dataentry = me.getValue(entry)
        esta_track = lt.isPresent(dataentry['canciones'], filtrado['track_id'])
        if esta_track == 0:
            lt.addLast(dataentry['canciones'], filtrado)
        esta_artista = lt.isPresent(dataentry['artistas'],
                                    cancion['artist_id'])
        if esta_artista == 0:
            lt.addLast(dataentry['artistas'], cancion["artist_id"])
        lt.addLast(dataentry["reproducciones"], cancion["track_id"])
    return mapt
Exemplo n.º 25
0
def reproductionsByCharacteristic(analyzer, option, iValue, fValue):
    """
    Tiene como return el numero de artistas unicos y
    un map con los artistas como llave
    """
    eventsMap = om.newMap("RBT")
    values = mp.valueSet(analyzer["artists"])
    for value in lt.iterator(values):
        for track in lt.iterator(value):
            optionKey = float(track[option])
            optionEntry = om.get(eventsMap, optionKey)
            if optionEntry is None:
                optionEntry = newDataEntry(track)
                om.put(eventsMap, optionKey, optionEntry)
            else:
                optionEntry = me.getValue(optionEntry)
            lt.addLast(optionEntry, track)

    artistMap = mp.newMap(maptype="PROBING")
    valuesFiltered = om.values(eventsMap, iValue, fValue)
    sizeEvents = 0
    for track in lt.iterator(valuesFiltered):
        sizeEvents += lt.size(track)
        for uniqueEvent in lt.iterator(track):
            artistKey = uniqueEvent["artist_id"]
            artistEntry = mp.get(artistMap, artistKey)
            if artistEntry is None:
                artistEntry = newDataEntry(uniqueEvent)
                mp.put(artistMap, artistKey, artistEntry)
            else:
                artistEntry = me.getValue(artistEntry)
            lt.addLast(artistEntry, uniqueEvent)
    return mp.size(artistMap), sizeEvents
Exemplo n.º 26
0
def muestradatos(analyzer):

    keys = om.keySet(analyzer['mapaTaxi'])

    itera = it.newIterator(keys)
    #mapa ordenado
    while (it.hasNext(itera)):
        key = it.next(itera)

        entryMapa = om.get(analyzer['mapaTaxi'], key)

        valorMapa = me.getValue(entryMapa)

        itera2 = it.newIterator(valorMapa['lstidtaxi'])
        while (it.hasNext(itera2)):
            valor = it.next(
                itera2
            )  #   {'idtaxi': None, 'servicios':None, 'millas':None, 'totalDinero': None, 'puntos': None}
            #if valor['totalDinero'] == 0:
            if ('7075c4988c577798c58b800dbb9742376dbbb74a84ce6ead178e7d00afcaafa6ac936cd9af7b6685991b9121b629de30650958fa926c5472da0083a63ed285c7'
                    in valor['idtaxi']):

                print(valor['idtaxi'])
                print(valor['servicios'])
                print(valor['millas'])
                print(valor['totalDinero'])
                print(valor['puntos'])
                print("")
Exemplo n.º 27
0
def addtomap(citibike, trip):
    fecha = trip["starttime"]
    fecha = transformador_fecha(fecha, 1)
    existe = om.get(citibike["mapa_fecha"], fecha)
    if existe is None:
        mapa = structure_map()
        llave = trip["bikeid"]
        ruta = gr.newGraph(
            datastructure="ADJ_LIST",
            directed=True,
            size=50,
            comparefunction=compareStations,
        )
        addTripV2(ruta, trip)
        m.put(mapa, llave, ruta)
        om.put(citibike["mapa_fecha"], fecha, mapa)
    else:
        llave = trip["bikeid"]
        existe = me.getValue(existe)
        existev2 = m.get(existe, llave)
        if existev2 is None:
            ruta = gr.newGraph(
                datastructure="ADJ_LIST",
                directed=True,
                size=50,
                comparefunction=compareStations,
            )
            addTripV2(ruta, trip)
            m.put(existe, llave, ruta)
        else:
            grafo = me.getValue(existev2)
            addTripV2(grafo, trip)
Exemplo n.º 28
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")
Exemplo n.º 29
0
def getEventsByInstrumentalnessAndTempo(analyzer, initialValue1, finalValue1, initialValue2, finalValue2):
    """
    Retorna el número de pistas y el map de pistas para las características
    de contenido 'instrumentalness' y 'tempo' en un rango de valores
    """
    map = om.newMap('RBT', compareValues)
    lstinstrumentalness = om.values(analyzer['instrumentalness'], initialValue1, finalValue1)
    for lstevents in lt.iterator(lstinstrumentalness):
        for event in lt.iterator(lstevents['events']):
            key = float(event['tempo'])
            existkey = om.contains(map, key)
            if existkey:
                entry = om.get(map, key)
                value = me.getValue(entry)
            else:
                value = newValue(key)
                om.put(map, key, value)
            lt.addLast(value['events'], event)

    tracks = mp.newMap(maptype='PROBING')
    lsttempo = om.values(map, initialValue2, finalValue2)
    for lstevents in lt.iterator(lsttempo):
        for event in lt.iterator(lstevents['events']):
            track = event['track_id']
            mp.put(tracks, track, event)
    totaltracks = mp.size(tracks)
    return totaltracks, tracks
Exemplo n.º 30
0
def get_accidents_severity_by_hour_range(analyzer, keylo, keyhi):
    entry = om.get(analyzer["hour_index"], "05:30")
    hour_range = om.values(analyzer["hour_index"], keylo, keyhi)
    iterator = it.newIterator(hour_range)
    severity_1 = 0
    severity_2 = 0
    severity_3 = 0
    severity_4 = 0
    total = 0
    while it.hasNext(iterator):
        hour = it.next(iterator)
        for severity_number in range(1, 5):
            severity_entry = m.get(hour["severity_index"],
                                   str(severity_number))
            if severity_entry is not None:
                severity = me.getValue(severity_entry)
                size = lt.size(severity["lstseverities"])
                if severity_number == 1:
                    severity_1 = severity_1 + size
                elif severity_number == 2:
                    severity_2 = severity_2 + size
                elif severity_number == 3:
                    severity_3 = severity_3 + size
                else:
                    severity_4 = severity_4 + size
                total = severity_1 + severity_2 + severity_3 + severity_4
            else:
                pass
    return total, severity_1, severity_2, severity_3, severity_4