Exemple #1
0
def Req_3(analyzer, initialDate, finalDate):
    """
    Retorna el numero de crimenes en un rago de fechas.
    """
    dicc={}
    cont=0 
    if om.keys(analyzer['dateIndex'], initialDate, finalDate)==None:
        print("")
    else:
        lst = om.keys(analyzer['dateIndex'], initialDate, finalDate)
        iterator= it.newIterator(lst)
        while it.hasNext(iterator):
            crime= it.next(iterator)
            date2= datetime.datetime.strptime(str(crime), "%Y-%m-%d")
            llave= om.get(analyzer["dateIndex"], date2.date())
            entry=me.getValue(llave)
            cont+=lt.size(entry["lstcrimes"])
            iterator2 = it.newIterator(entry['lstcrimes'])
            while it.hasNext(iterator2):
                crime2 = it.next(iterator2)
                estado = str(crime2['Severity'])
                if estado in dicc:
                    dicc[estado] += 1
                else:
                    dicc[estado] = 1
        l = (max(dicc.values()))
        for i in dicc:
            if l == dicc[i]:
                ve = "\nLa categoria con más accidentes en el rango es: " + i + ' con una cantidad de: ' + str(dicc[i])
        print(ve)
        print("La cantidad de accidentes en el rango dado fue de: " + str(cont))
        return lst
Exemple #2
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
Exemple #3
0
def Requerimiento_3(analyzer_context, inst_min, inst_max, temp_min, temp_max):
    instrumentalness = om.keys(analyzer_context["instrumentalness"], inst_min,
                               inst_max)
    tempo = om.keys(analyzer_context["tempo"], temp_min, temp_max)
    iterador = instrumentalness['first']
    fecha_mayor = iterador['info']
    tracks = []
    energia = []
    while iterador['next'] != None:
        iterador = iterador['next']
        llave = iterador['info']
        crimenes = me.getValue(
            om.get(analyzer_context['instrumentalness'], llave))
        c = it.newIterator(crimenes)
        while it.hasNext(c):
            n = it.next(c)
            A = m.get(analyzer_context["eventos"], n)
            B = me.getValue(A)
            tracks.append(B["track_id"])
            energia.append(B["instrumentalness"])
    iterador_2 = tempo["first"]
    informacion = iterador_2["info"]
    tracks_2 = []
    baile = []
    while iterador_2["next"] != None:
        iterador_2 = iterador_2["next"]
        llave_2 = iterador_2["info"]
        crimenes2 = me.getValue(om.get(analyzer_context['tempo'], llave_2))
        c = it.newIterator(crimenes2)
        while it.hasNext(c):
            n = it.next(c)
            A = m.get(analyzer_context["eventos"], n)
            B = me.getValue(A)
            tracks_2.append(B["track_id"])
            baile.append(B["tempo"])
    if len(tracks) == 0 or len(tracks_2) == 0:
        resp = None
    else:
        list_3 = []
        for z in tracks:
            for b in tracks_2:
                if z == b:
                    list_3.append(z)
        unicos = set(list_3)
        rand = random.sample(unicos, 5)
        resp = []
        for i in rand:
            resp.append(
                [i, energia[tracks.index(i)], baile[tracks_2.index(i)]])
    return (resp, len(unicos))
Exemple #4
0
def Requerimiento3(analyzer, minIns, maxIns, minTemp, maxTemp):
    keys_in_range = om.keys(analyzer['instrumentalness'], minIns, maxIns)
    mapa = analyzer['instrumentalness']
    map_respuesta = om.newMap()
    lista_tracks = lt.newList()
    for i in range(lt.size(keys_in_range)):
        key = lt.getElement(keys_in_range, i)
        valores = om.get(mapa, key)
        valores = me.getValue(valores)
        for i in range(lt.size(valores)):
            small = lt.getElement(valores, i)
            if small['tempo'] >= minTemp and small['tempo'] <= maxTemp:
                track_id = small['track_id']
                exist = om.contains(map_respuesta, track_id)
                if not exist:
                    tupla = small['instrumentalness'], small['tempo']
                    om.put(map_respuesta, track_id, tupla)
                    lt.addLast(lista_tracks, track_id)

    print('Total of unique tracks in events: ' + str(lt.size(lista_tracks)))
    i = 0
    while i < 5:
        rand = rd.randint(0, lt.size(lista_tracks))
        track = lt.getElement(lista_tracks, rand)
        tupla_f = om.get(map_respuesta, track)
        tupla_f = me.getValue(tupla_f)
        print('Track ' + str(i + 1) + ' :' + str(track) +
              ' with instrumentalness of ' + str(tupla_f[0]) +
              ' and tempo of ' + str(tupla_f[1]))
        i += 1
def getBestMTaxisByRange(analyzer, initDate, finalDate, M):
    dateslist = om.keys(analyzer['DateIndex'], initDate, finalDate)
    if lt.isEmpty(dateslist):
        return 0
    iterator = it.newIterator(dateslist)
    pointdic = {}
    while it.hasNext(iterator):
        date = it.next(iterator)
        dictaxis = me.getValue(om.get(analyzer["DateIndex"], date))
        for tid in dictaxis:
            if tid not in pointdic:
                pointdic[tid] = {
                    "miles": 0,
                    "total": 0,
                    "services": 0,
                    "points": 0
                }
            pointdic[tid]["miles"] += dictaxis[tid]["miles"]
            pointdic[tid]["total"] += dictaxis[tid]["total"]
            pointdic[tid]["services"] += dictaxis[tid]["services"]
            if pointdic[tid]["total"] != 0:
                pointdic[tid]["points"] = pointdic[tid]["miles"] * pointdic[
                    tid]["services"] / pointdic[tid]["total"]
    qeue = pq.newMinPQ(cmpfunction=compareDegreeMax)
    for taxi in pointdic:
        points = pointdic[taxi]["points"]
        pq.insert(qeue, {"id": taxi, "points": points})
    return qeue
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 #7
0
def Mestudiar(cont, instmin, instmax, tempmin, tempmax):
    tempo = om.keys(cont['tempo'], tempmin, tempmax)
    lista = lt.newList()
    final = {}
    contador = 0
    #recorre el tempo que tiene solo el rango, busca que tengan el inst requerido
    for x in lt.iterator(tempo): 
        r = om.get(cont['tempo'], x)
        valor = r['value']
        real = valor['first']['info']
       
        for i in real:
           
            if type(i)==str:
                pos = lt.isPresent(cont['lstSongs'],i )
                cancion = lt.getElement(cont['lstSongs'], pos)
                inst = cancion['instrumentalness']
               
                if float(inst)>= instmin and float(inst)<= instmax:
                    final[i] = (inst, x )
                    contador+= 1
                    lt.addLast(lista, i)
    #recorre genera 5 numeros aletorios y retorna la info de esas canciones
    print('Total de canciones únicas: ', contador)
    contador = 0
    lista_numeros = []
    while contador<5:
        numero = random.randint(0,lt.size(lista))
        if numero not in lista_numeros:
            contador+=1
            lista_numeros.append(numero)
            cancion = lt.getElement(lista, numero)
            info = final[cancion]
            print('\n Track', contador, ': ', cancion, 'con una instumentalidad de ',info[0], 'y un tempo de ', info[1] )
Exemple #8
0
def getAccidentsByRange(analyzer, initialDate, finalDate):
    """
    Retorna el numero de crimenes en un rago de fechas.
    """
    dicc = {}
    dicct = {}
    lst = om.keys(analyzer['dateIndex'], initialDate, finalDate)
    iterator = it.newIterator(lst)
    while it.hasNext(iterator):
        crime = it.next(iterator)
        date2 = datetime.datetime.strptime(str(crime), '%Y-%m-%d')
        llave = om.get(analyzer['dateIndex'], date2.date())
        entry = me.getValue(llave)
        fecha = str(crime)
        if fecha not in dicct:
            dicct[fecha] = lt.size(entry['lstcrimes'])
        iterator2 = it.newIterator(entry['lstcrimes'])
        while it.hasNext(iterator2):
            crime2 = it.next(iterator2)
            estado = crime2['State']
            if estado in dicc:
                dicc[estado] += 1
            else:
                dicc[estado] = 1
    m = (max(dicct.values()))
    for i in dicct:
        if m == dicct[i]:
            va = "\nLa fecha con más accidentes en el rango es: " + i + ' con una cantidad de: ' + str(dicct[i])
    print(va)
    l = (max(dicc.values()))
    for i in dicc:
        if l == dicc[i]:
            ve = "\nEl estado con más accidentes en el rango es: " + i + ' con una cantidad de: ' + str(dicc[i])
    print(ve)
    return None
Exemple #9
0
def topPuntosTaxiMultiple(analyzer, dateIni, dateFin, top):
    dateanalyzed1 = om.get(analyzer['dates'], dateIni)
    dateanalyzed2 = om.get(analyzer['dates'], dateFin)
    if dateanalyzed1["key"] is not None and dateanalyzed2["key"]:
        valor = om.keys(analyzer["dates"], dateIni, dateFin)
        iterador = it.newIterator(valor)
        taxis = {}
        topRangoTaxis = lt.newList("ARRAY_LIST")
        num = 1
        while it.hasNext(iterador):
            fecha = it.next(iterador)
            lista = topPuntosTaxiSingle(analyzer, fecha, top)
            iterador2 = it.newIterator(lista)
            while it.hasNext(iterador2):
                taxi = it.next(iterador2)
                if str(taxi.keys()) in str(taxis.keys()):
                    taxis[str(taxi.keys())] += float(taxi.values())
                else:
                    taxis.update(taxi)
        while num <= top:
            resultado = maxMinDict.maxDicc(taxis)
            inp = {resultado: taxis[resultado]}
            lt.addLast(topRangoTaxis, inp)
            taxis.pop(resultado)
            num += 1
        return topRangoTaxis
    else:
        return None
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
Exemple #11
0
def getAccidentstimeByRange(analyzer, initialDate, finalDate):
    dicc = {}
    cont = 0
    lst = om.keys(analyzer['hoursIndex'], initialDate, finalDate)
    iterator = it.newIterator(lst)
    while it.hasNext(iterator):
        crime = it.next(iterator)
        date2 = datetime.datetime.strptime(str(crime), '%H:%M:%S')
        llave = om.get(analyzer['hoursIndex'], date2.time())
        entry = me.getValue(llave)
        tiempo = str(crime)
        cont += lt.size(entry['lstaccidents'])
        iterator2 = it.newIterator(entry['lstaccidents'])
        while it.hasNext(iterator2):
            crime2 = it.next(iterator2)
            estado = crime2['Severity']
            if estado in dicc:
                dicc[estado] += 1
            else:
                dicc[estado] = 1
    print("En el rango con tiempo se obtuvieron los siguientes datos: \n")
    for i in dicc:
        if i == "1":
            print("Con una severidad de " + i + " son " + str(dicc[i]) + " accidentes" + " con un porcentaje de: " + str(round((dicc[i]/cont), 2)*100) + "%")
        if i == "2":
            print("Con una severidad de " + i + " son " + str(dicc[i]) + " accidentes" + " con un porcentaje de: " + str(round((dicc[i]/cont), 2)*100) + "%")
        if i == "3":
            print("Con una severidad de " + i + " son " + str(dicc[i]) + " accidentes" + " con un porcentaje de: " + str(round((dicc[i]/cont), 2)*100) + "%")
        if i == "4":
            print("Con una severidad de " + i + " son " + str(dicc[i]) + " accidentes" + " con un porcentaje de: " + str(round((dicc[i]/cont), 2)*100) + "%")   
    print("\nTiene un total de: " + str(cont) + " accidentes")
    return None
def getAccidentsBeforeDate(analyzer, finalDate):
    initialDate = str(minKey(analyzer))
    initialDate = datetime.datetime.strptime(initialDate, '%Y-%m-%d')
    lst = om.keys(analyzer['dateIndex'], initialDate.date(), finalDate)

    if initialDate.date() == finalDate:
        return (0, "no hay fecha anterior")
    else:
        severity1 = 0
        severity2 = 0
        severity3 = 0
        severity4 = 0
        mostAccidentsDate = {'date': None, 'total': 0}

        for pos in range(1, lt.size(lst)):

            keyDate = lt.getElement(lst, pos)
            severity1 += int(getAccidentsBySeverity(analyzer, keyDate, '1'))
            severity2 += int(getAccidentsBySeverity(analyzer, keyDate, '2'))
            severity3 += int(getAccidentsBySeverity(analyzer, keyDate, '3'))
            severity4 += int(getAccidentsBySeverity(analyzer, keyDate, '4'))

            severity1Date = int(getAccidentsBySeverity(analyzer, keyDate, '1'))
            severity2Date = int(getAccidentsBySeverity(analyzer, keyDate, '2'))
            severity3Date = int(getAccidentsBySeverity(analyzer, keyDate, '3'))
            severity4Date = int(getAccidentsBySeverity(analyzer, keyDate, '4'))
            totalDate = severity1Date + severity2Date + severity3Date + severity4Date

            if totalDate >= mostAccidentsDate['total']:
                mostAccidentsDate['date'] = keyDate
                mostAccidentsDate['total'] = totalDate

        total = severity1 + severity2 + severity3 + severity4

        return (total, mostAccidentsDate['date'])
Exemple #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)
Exemple #14
0
def AccidentesPorHora(analyzer, HoraInicial, HoraFinal):
    HoraInicial = AproximacionHora(HoraInicial)
    HoraFinal = AproximacionHora(HoraFinal)
    ListaHoras = om.keys(analyzer["Horas"], HoraInicial, HoraFinal)
    Severity1 = 0
    Severity2 = 0
    Severity3 = 0
    Severity4 = 0
    for i in range(1, (lt.size(ListaHoras) + 1)):
        Hora = lt.getElement(ListaHoras, i)
        Pareja = om.get(analyzer["Horas"], Hora)
        Accidente1 = me.getValue(Pareja)
        for j in range(1, (lt.size(Accidente1) + 1)):
            Accidente = lt.getElement(Accidente1, j)
            if Accidente["Severity"] == "1":
                Severity1 += 1
            elif Accidente["Severity"] == "2":
                Severity2 += 1
            elif Accidente["Severity"] == "3":
                Severity3 += 1
            else:
                Accidente["Severity"] == "4"
                Severity4 += 1
    Total = Severity1 + Severity2 + Severity3 + Severity4
    Retorno = lt.newList("ARRAY_LIST", compareIds)
    lt.addLast(Retorno, Severity1)
    lt.addLast(Retorno, Severity2)
    lt.addLast(Retorno, Severity3)
    lt.addLast(Retorno, Severity4)
    lt.addLast(Retorno, Total)
    return Retorno
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.")
Exemple #16
0
def getAccidentsByState(analyzer,initialDate,finalDate):
    """
    Retorna una 'estructura' con los crimenes dentro de un rango
    """
    
    lst = om.keys(analyzer["dateIndex"], initialDate, finalDate)
    lstiterator = it.newIterator(lst)
    most_accidents_date = lt.getElement(lst,1)
    
    states_count = lt.newList("ARRAY_LIST", compareCount) 
    checklist = lt.newList("ARRAY_LIST", compareNames) 
    
    while it.hasNext(lstiterator):
        date = it.next(lstiterator)
        mapdate = om.get(analyzer["dateIndex"],date)
        map = me.getValue(mapdate)
        accidents = map["lstaccidents"]
        if lt.size(accidents) > lt.size((me.getValue(om.get(analyzer["dateIndex"],most_accidents_date)))["lstaccidents"]):
            most_accidents_date = date
        statemap = map["StateIndex"]
        count_states(statemap,states_count,checklist)
        
    ins.selectionSort(states_count,greater_function)
    
    return (lt.getElement(states_count,1), most_accidents_date)
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
def requerimientoB(analyzer, FechaI, FechaF, FechaO):
    ListaR = op.keys(analyzer["MapaId"], FechaI, FechaF)
    ListaU = op.keys(analyzer["MapaId"], FechaO, FechaO)
    if lt.isEmpty(ListaR) == True:
        OrdenadaR = False
    else:
        PuntosR = Rango(ListaR, analyzer, False)
        OrdenadaR = DiciaLista(PuntosR)
    if lt.isEmpty(ListaU) == True:
        OrdenadaU = False
    else:
        PuntosU = Rango(ListaU, analyzer, FechaO)
        OrdenadaU = DiciaLista(PuntosU)
    ListaFinal = lt.newList("ARRAY_LIST")
    lt.addFirst(ListaFinal, OrdenadaU)
    lt.addLast(ListaFinal, OrdenadaR)
    return ListaFinal
Exemple #19
0
def getRecommendedSongs(analyzer,minEnergy, maxEnergy,minDance, maxDance):

    energyAux=[]
    energySongs=om.keys(analyzer["char2"], minEnergy, maxEnergy)
    s1=0

    for value in lt.iterator(energySongs):   
        charValue = om.get(analyzer["char2"], value)
        ids = me.getValue(charValue)["info"]
        idValues = m.keySet(ids)

        for key in lt.iterator(idValues):   
            if str(key) not in energyAux:
                energyAux.append(key)
                s1+=1

    danceAux=[]
    danceSongs=om.keys(analyzer["char3"], minDance, maxDance)
    s2=0
    for value in lt.iterator(danceSongs):   
        charValue = om.get(analyzer["char3"], value)
        ids = me.getValue(charValue)["info"]
        idValues = m.keySet(ids)

        for key in lt.iterator(idValues):   
            if str(key) not in danceAux:
                danceAux.append(key)
                s2+=1

    ##comparando las dos listas

    combined=combinedList(energyAux,danceAux)

    totSongs=0
   
    for i in combined:
        totSongs+=1

    
    if totSongs>5:
        randomIndex=random.choices(combined, k=5)
    else:
        randomIndex=random.choices(combined, k=totSongs)

    return str(totSongs)+"\n5 pistas aleatorias dentro de los rangos:"+str(randomIndex)
Exemple #20
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 #21
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 #22
0
def Requerimiento_1(analyzer_context, caracteristica, valor_minimo,
                    valor_maximo):
    resp = []
    if caracteristica in "instrumentalidad" or caracteristica in "instrumentalness":
        llaves = om.keys(analyzer_context["instrumentalness"], valor_minimo,
                         valor_maximo)
    elif caracteristica in "vivacidad" or caracteristica in "liveness":
        llaves = om.keys(analyzer_context["liveness"], valor_minimo,
                         valor_maximo)
    elif caracteristica in "speechiness":
        llaves = om.keys(analyzer_context["speechiness"], valor_minimo,
                         valor_maximo)
    elif caracteristica in "bailabilidad" or caracteristica in "danceability":
        llaves = om.keys(analyzer_context["danceability"], valor_minimo,
                         valor_maximo)
    elif caracteristica in "valencia" or caracteristica in "valence":
        llaves = om.keys(analyzer_context["valence"], valor_minimo,
                         valor_maximo)
    elif caracteristica in "volumen" or caracteristica in "loudness":
        llaves = om.keys(analyzer_context["loudness"], valor_minimo,
                         valor_maximo)
    elif caracteristica in "tempo":
        llaves = om.keys(analyzer_context["tempo"], valor_minimo, valor_maximo)
    elif caracteristica in "acústica" or caracteristica in "acousticness":
        llaves = om.keys(analyzer_context["acousticness"], valor_minimo,
                         valor_maximo)
    else:
        resp = None
    if resp != None:
        iterador = llaves['first']
        fecha_mayor = iterador['info']
        crimenesmas = me.getValue(
            om.get(analyzer_context[caracteristica], fecha_mayor))
        val = []
        users = []
        cmas = it.newIterator(crimenesmas)
        while it.hasNext(cmas):
            n = it.next(cmas)
            A = m.get(analyzer_context["eventos"], n)
        while iterador['next'] != None:
            iterador = iterador['next']
            llave = iterador['info']
            crimenes = me.getValue(
                om.get(analyzer_context[caracteristica], llave))
            c = it.newIterator(crimenes)
            while it.hasNext(c):
                n = it.next(c)
                A = m.get(analyzer_context["eventos"], n)
                B = me.getValue(A)
                val.append(B["id"])
                users.append(B["artist_id"])
        unicos = set(users)
        resp = (len(val), len(unicos))
    return resp
Exemple #23
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 state_accidents(analyzer, fechaInicial, fechaFinal):

    llaves = om.keys(analyzer['dateIndex'], fechaInicial, fechaFinal)
    cant_llaves = lt.size(llaves)
    tamanio = lt.size(
        om.values(analyzer['dateIndex'], fechaInicial, fechaFinal))
    i = 1
    estados = m.newMap(numelements=0,
                       maptype='CHAINING',
                       loadfactor=0.5,
                       comparefunction=comparar_estados)

    if (lt.isPresent(llaves, fechaFinal) == 0
            or lt.isPresent(llaves, fechaInicial) == 0):
        return None

    else:
        while i <= cant_llaves:
            llave = lt.getElement(llaves, i)
            tree = om.get(analyzer['dateIndex'], llave)
            stateIndex = tree['value']['stateIndex']
            llaves_stateIndex = m.keySet(stateIndex)
            tamanio_llaves = lt.size(llaves_stateIndex)
            j = 1
            while j <= tamanio_llaves:
                estado = lt.getElement(llaves_stateIndex, j)
                stat = m.get(stateIndex, estado)
                exist_state = m.contains(estados, estado)
                if not exist_state:
                    m.put(estados, estado, 0)
                cant = m.get(estados, estado)
                cant = cant['value']
                cant += tamanio
                m.put(estados, estado, cant)
                j += 1
            i += 1

    z = 1
    mayor = 0
    stat = ' '
    llaves_estados = m.keySet(estados)

    while z <= lt.size(llaves_estados):
        estadod = lt.getElement(llaves_estados, z)
        valor = m.get(estados, estadod)
        valor = valor['value']

        if (valor > mayor):
            mayor = valor
            stat = estadod
        z += 1

    return stat
def total_entre_fechas(analyzer, fecha1, fecha2):
    date1 = fecha_convertidor_consultas(fecha1)
    date2 = fecha_convertidor_consultas(fecha2)
    a = om.keys(analyzer["index"], date1, date2)
    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
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
def req2(catalog, minEnergy, maxEnergy, minDanceability, maxDanceability):

    canciones = mp.newMap(maptype= "PROBING", loadfactor= 0.3)

    rangoEnergy = maxEnergy - minEnergy
    rangoDanceability = maxDanceability - minDanceability

    if rangoEnergy <= rangoDanceability:

        categoria =  "energy"   
        categoria1 = "danceability"
        min = minDanceability
        max = maxDanceability    
        llaves = om.keys(catalog["energy"], minEnergy, maxEnergy)

    else:
        
        categoria =  "danceability"
        categoria1 = "energy"
        min = minEnergy
        max = maxEnergy
        llaves = om.keys(catalog["danceability"], minDanceability, maxDanceability)


    for llave in lt.iterator(llaves):

        entry = om.get(catalog[categoria], llave)
        eventos = me.getValue(entry)

        for evento in lt.iterator(eventos):

            track = lt.getElement(catalog["lista_canciones"], evento)

            category = track[categoria1]

            if category >= min and category <= max:

                mp.put(canciones, track["track_id"], track)

    return canciones
def req3(catalog, minInstrumentalness, maxInstrumentalness, minTempo, maxTempo):

    canciones = mp.newMap(maptype= "PROBING", loadfactor= 0.3)

    rangoInstrumentalness = maxInstrumentalness - minInstrumentalness
    rangoTempo = maxTempo - minTempo

    if rangoTempo <= rangoInstrumentalness:

        categoria =  "tempo"   
        categoria1 = "instrumentalness"
        min = minInstrumentalness
        max = maxInstrumentalness    
        llaves = om.keys(catalog["tempo"], minTempo, maxTempo)

    else:
        
        categoria =  "instrumentalness"
        categoria1 = "tempo"
        min = minTempo
        max = maxTempo
        llaves = om.keys(catalog["instrumentalness"], minInstrumentalness, maxInstrumentalness)


    for llave in lt.iterator(llaves):

        entry = om.get(catalog[categoria], llave)
        eventos = me.getValue(entry)

        for evento in lt.iterator(eventos):

            track = lt.getElement(catalog["lista_canciones"], evento)

            category = track[categoria1]

            if category >= min and category <= max:

                mp.put(canciones, track["track_id"], track)

    return canciones
Exemple #29
0
def Requerimiento_5(hora_min, hora_max, analyzer_context):
    hora_menor = hora_convertidor_consultas(hora_min)
    hora_mayor = hora_convertidor_consultas(hora_max)
    llaves = om.keys(analyzer_context["created_at"], hora_menor, hora_mayor)
    iterador_2 = llaves["first"]
    informacion = iterador_2["info"]
    usuarios_2 = []
    tempos = []
    while iterador_2["next"] != None:
        iterador_2 = iterador_2["next"]
        llave_2 = iterador_2["info"]
        crimenes2 = me.getValue(om.get(analyzer_context['created_at'],
                                       llave_2))
        c = it.newIterator(crimenes2)
        while it.hasNext(c):
            n = it.next(c)
            A = m.get(analyzer_context["eventos"], n)
            B = me.getValue(A)
            usuarios_2.append(float(B["tempo"]))
            tempos.append(str(B["track_id"]))
    géneros = []
    for i in usuarios_2:
        if i >= 60 and i <= 90:
            géneros.append("Reggae")
        if i >= 70 and i <= 100:
            géneros.append("Down-tempo")
        if i >= 90 and i <= 120:
            géneros.append("Chill-out")
        if i >= 85 and i <= 115:
            géneros.append("Hip-hop")
        if i >= 120 and i <= 125:
            géneros.append("Jazz and Funk")
        if i >= 100 and i <= 130:
            géneros.append("Pop")
        if i >= 60 and i <= 80:
            géneros.append("R&B")
        if i >= 110 and i <= 140:
            géneros.append("Rock")
        if i >= 100 and i <= 160:
            géneros.append("Metal")
    h = defaultdict(list)
    for k, v in zip(géneros, tempos):
        h[k].append(v)
    x = {
        k: v
        for k, v in sorted(
            h.items(), key=lambda item: len(item[1]), reverse=True)
    }
    longi = []
    for i in x:
        longi.append(len(h[i]))
    return (x, longi)
Exemple #30
0
def Requerimiento4(analyzer, str_generos):

    generos_lower = str_generos.lower()
    lista_generos = generos_lower.split(',')
    final = lt.newList()
    for i in range(len(lista_generos)):
        lista_genero = lt.newList()
        mapa = analyzer['genres']
        busqueda_map = om.get(mapa, lista_generos[i])
        tupla = me.getValue(busqueda_map)
        name = me.getKey(busqueda_map)
        minTemp = int(tupla[0])
        maxTemp = int(tupla[1])
        keys_in_range = om.keys(analyzer['tempo'], minTemp, maxTemp)
        events_parciales = lt.size(keys_in_range)

        lt.addLast(lista_genero, events_parciales)

        mp_artistas = om.newMap()
        lt_artistas = lt.newList()

        for i in range(lt.size(keys_in_range)):
            key = float(lt.getElement(keys_in_range, i))
            mapa_tempo = analyzer['tempo']
            valores = om.get(mapa_tempo, key)
            valores = me.getValue(valores)

            for i in range(lt.size(valores)):
                valor = lt.getElement(valores, i)
                exist = om.contains(mp_artistas, valor['artist_id'])

                if not exist:
                    artist_id = valor['artist_id']
                    om.put(mp_artistas, artist_id, valor)
                    while lt.size(lt_artistas) <= 10:
                        lt.addLast(lt_artistas, artist_id)

        artistas_parciales = om.size(mp_artistas)

        lt_final_genero = [
            name, minTemp, maxTemp, events_parciales, artistas_parciales,
            lt_artistas
        ]
        lt.addLast(final, lt_final_genero)

    max_eventos = 0

    for i in range(lt.size(final)):
        listilla = lt.getElement(final, i)
        max_eventos += int(listilla[3])

    requerimiento_4_print(max_eventos, final)