class MyTestCase(unittest.TestCase): def setUp(self): self.filter = Filter() data = requests.get("https://pl.wikipedia.org/wiki/Suomenlinna").text self.soup = BeautifulSoup(data, 'lxml') def test_filter(self): resultSet = set({'/wiki/Cmentarzysko_z_epoki_br%C4%85zu_w_Sammallahdenm%C3%A4ki', '/wiki/Finlandia', '/wiki/Helsinki', '/wiki/Komitet_%C5%9Awiatowego_Dziedzictwa#Lista_sesji_Komitetu_Światowego_Dziedzictwa', '/wiki/Kvarken_P%C3%B3%C5%82nocny', '/wiki/Lista_%C5%9Bwiatowego_dziedzictwa_UNESCO', '/wiki/Lista_%C5%9Bwiatowego_dziedzictwa_UNESCO#Kryteria', '/wiki/Lista_%C5%9Bwiatowego_dziedzictwa_UNESCO#Obiekty_UNESCO_według_regionów', '/wiki/Pa%C5%84stwo', '/wiki/Pet%C3%A4j%C3%A4vesi', '/wiki/Po%C5%82udnik_Struvego', '/wiki/Rauma_(miasto)#Zabytkowa_dzielnica_Raumy_(Vanha_Rauma)', '/wiki/Rynek_w_Helsinkach', '/wiki/Suomenlinna', '/wiki/Twierdza', '/wiki/UNESCO', '/wiki/Verla', '/wiki/Vesikko', '/wiki/Ziemia'}) self.assertEqual(resultSet, self.filter.filter(self.soup.find_all('a')))
def evaluarFitness(self, solucion): #Desde el inicio generé la señal S1 #Filtro la señal S1 con los coeficientes de la solución que quiero evaluar #Inicializo el filtro 1 filtro1 = Filter(solucion) #Obtengo la señal de salida del filtro 1 T1 = filtro1.filter(self.S1) #Desde el principio generé la señal S2 #Filtro la señal S2 con los coeficientes de la solución que quiero evaluar #Inicializo el filtro 2 filtro2 = Filter(solucion) #Obtengo la señal de salida del filtro 2 T2 = filtro2.filter(self.S2) #Calcular la potencia media de T1 arreglo_absolutos1 = np.absolute(T1.y) arreglo_cuadrados1 = list( map(lambda elemento: cuadrado(elemento), arreglo_absolutos1)) sumatoria1 = sumatoria(arreglo_cuadrados1) P1 = (float(1) / float(2 * len(T1.y) - 1)) * float(sumatoria1) #print('sumatoria1:', sumatoria1) #print('P1: ', P1) #Calcular la potencia media de T2 arreglo_absolutos2 = np.absolute(T2.y) arreglo_cuadrados2 = list( map(lambda elemento: cuadrado(elemento), arreglo_absolutos2)) sumatoria2 = sumatoria(arreglo_cuadrados2) P2 = (float(1) / float(2 * len(T2.y) - 1)) * float(sumatoria2) #print('sumatoria2:', sumatoria2) #print('P2: ', P2) if self.tfiltro == "pb": #Si el filtro es pasa bajos fitness = P1 - P2 return fitness #De lo contrario el filtro es pasa altos fitness = P2 - P1 return fitness
def getLinks(self, linksFilePath, i): sett = set() linksFilePath = Path(linksFilePath) linksFilePath.touch(exist_ok=True) if (os.stat(linksFilePath).st_size != 0): with open(linksFilePath) as file: url = file.read().split('\n')[i] source = "https://pl.wikipedia.org/" + url data = requests.get(source).text soup = BeautifulSoup(data, 'lxml') filter = Filter() sett = filter.filter(soup.find_all('a')) #nic nie zwraca with open(linksFilePath, 'a') as file: writer = csv.writer(file, delimiter=' ') for link in sett: writer.writerow([link]) # return sett else: print('file empty') return sett
#individuo1 = [0.5999402, -0.5999402, 0, 1, -0.7265425, 0, 1, -2, 1, 1, -1.52169043, 0.6, 1, -2, 1, 1, -1.73631017, 0.82566455] #individuo1 = [-1.0680269827643445, -0.5713375209620128, -2.5686810550062686, 1, -1.507492099868706, 1.1328639399494786, -2.0312789297904277, 2.2819167893422474, 1.0782562420903563, 1, -2.406622049318159, 2.8184691203296985, 1.1009934668113424, 2.937768404798515, -1.2879034426159903, 1, 1.0779804598027694, 0.26138695967438075] individuo1 = [ 0.649111778514992, -2.561895750023369, -2.7064914522189003, 1, 0.42448483253776903, -0.7379594694212431, 2.3639384229526303, 0.7941637159051543, 0.12697375139804645, 1, 1.2652675834117865, 2.0737694481309585, 0.08310102365110283, 0.7794553652514429, -0.34982571481909996, 1, -1.0619745836793708, 1.9163873078077768 ] # Se instancia el filtro filtro = Filter(individuo1) # Se obtiene la señal de salida del filtro output = filtro.filter(input) # Generacion de grafica fig, (ax1, ax2) = chart.subplots(2, 1, sharex=True) ax1.plot(input.t, input.y) ax1.set_title('Entrada del filtro') ax1.axis([0, 1, -10, 10]) ax2.plot(output.t, output.y) ax2.set_title('Salida del filtro') ax2.axis([0, 1, -10, 10]) ax2.set_xlabel('Tiempo [segundos]') chart.tight_layout() chart.show()
def main(): ''' Main program to test I2C communication on the I2C ''' global SLEEP_TIME global TACH_THRESHOLD global rightTachValue global leftTachValue global prevRightTachValue global prevLeftTachValue global rightVelocity global rightStripCount global leftVelocity global leftStripCount global loopCount global leftHigh global leftThresholdHigh global leftThresholdLow global rightHigh global rightThresholdHigh global rightThresholdLow global steeringPotValue global startTime global elapsedTime global fractional global turnGoal # Setup bus pwm = Adafruit_PCA9685.PCA9685() adc = Adafruit_ADS1x15.ADS1115() # Thread goalThread = Thread(target=recvGoal) goalThread.start() try: values = [0] * 4 # motor motorChnl = 14 turnChnl = 15 freq = 60 * 2 pwm.set_pwm_freq(freq) print("Freq = {0}".format(freq)) rightWheelChnl = 1 leftWheelChnl = 2 potChnl = 0 # Data Rate of ADC DATA_RATE = 860 pulseDuration = STOP error = 0.0 avgVelocity = 0.0 steeringError = 0.0 steeringDuration = STOP turnGoal = STRAIGHT # straight steeringAvg = 0.0 # slow turn #steeringPID = PID(0.0, 0.5, 0.5, 25.0) steeringPID = PID(10.0, 4.0, 1.0, 25.0) steeringFilter = Filter(0.9) velocityPID = PID(50.0, 100.0, 0.0, 3.0) velocityFilter = Filter(0.9) velocityPID.setGoal(0.0) while True: if (loopCount % 1 == 0): prevRightTachValue = rightTachValue prevLeftTachValue = leftTachValue steeringPotValue = adc.read_adc(potChnl, gain=GAIN, data_rate=DATA_RATE) rightTachValue = adc.read_adc(rightWheelChnl, gain=GAIN, data_rate=DATA_RATE) leftTachValue = adc.read_adc(leftWheelChnl, gain=GAIN, data_rate=DATA_RATE) steeringFilter.recvMeasurement(steeringPotValue) steeringPotValue = steeringFilter.filter() #steeringPID.setCurrentMeasurement((steeringAvg / MAX_LOOP_COUNT) / 1000.0) steeringPID.setCurrentMeasurement(steeringPotValue / 1000.0) steeringPID.setGoal(turnGoal / 1000.0) #print("LT: {0}".format(rightTachValue)) #print("RT: {0}".format(leftTachValue)) #print("ST: {0}".format(steeringPotValue)) if (rightHigh == 0 and rightTachValue > rightThresholdHigh): rightStripCount += 0.5 rightHigh = 1 if (rightHigh == 1 and rightTachValue < rightThresholdHigh): rightStripCount += 0.5 rightHigh = 0 if (leftHigh == 0 and leftTachValue > leftThresholdHigh): leftStripCount += 0.5 leftHigh = 1 if (leftHigh == 1 and leftTachValue < leftThresholdHigh): leftStripCount += 0.5 leftHigh = 0 #steeringAvg += steeringPotValue loopCount += 1 #print(loopCount) # Steering steeringDuration = steeringPID.control() #steeringError = turnGoal - steeringAvg / MAX_LOOP_COUNT #steeringGain = 100 if steeringDuration > 0: #steeringDuration = 670 # Dead Band steeringDuration = 675 - steeringDuration elif steeringDuration < 0: #steeringDuration = 890 steeringDuration = 875 - steeringDuration #steeringDuration = 775 - steeringError / 7.0 # Max Zone if steeringDuration > 930: steeringDuration = 930 if steeringDuration < 630: steeringDuration = 630 controlChnl(pwm, motorChnl, int(pulseDuration)) controlChnl(pwm, turnChnl, int(steeringDuration)) if (loopCount >= MAX_LOOP_COUNT): elapsedTime = (time.time() * 1000) - startTime startTime = (time.time() * 1000) rightVelocity = ((rightStripCount / 30.0) * 0.36 * math.pi) / (elapsedTime / 1000.0) leftVelocity = ((leftStripCount / 30.0) * 0.36 * math.pi) / (elapsedTime / 1000.0) # Velocity avgVelocity = (leftVelocity + rightVelocity) / 2.0 if pulseDuration > STOP: avgVelocity *= -1 #error = velGoal - avgVelocity # gain #pulseDuration = pulseDuration - error * 60.0 velocityFilter.recvMeasurement(avgVelocity) avgVelocity = velocityFilter.filter() velocityPID.setCurrentMeasurement(avgVelocity) velocityPID.setGoal(velGoal) pulseDuration = STOP - velocityPID.control() if pulseDuration < 550: pulseDuration = 550 if pulseDuration > 1000: pulseDuration = 1000 ''' # Steering steeringDuration = steeringPID.control() #steeringError = turnGoal - steeringAvg / MAX_LOOP_COUNT #steeringGain = 100 if steeringDuration > 0: #steeringDuration = 670 steeringDuration = 648 - steeringDuration elif steeringDuration < 0: #steeringDuration = 890 steeringDuration = 907 - steeringDuration #steeringDuration = 775 - steeringError / 7.0 # Dead Zone if steeringDuration > 930: steeringDuration = 930 if steeringDuration < 630: steeringDuration = 630 ''' print("LV: {0}".format(leftVelocity)) print("RV: {0}".format(rightVelocity)) print("Avg Vel: {0}".format(avgVelocity)) print("S: {0}".format(steeringPotValue)) print("ET: {0}".format(elapsedTime)) print("PD: {0}".format(int(pulseDuration))) print("VG: {0}".format(velGoal)) print("error: {0}".format(error)) print("SD: {0}".format(int(steeringDuration))) print("SG: {0}".format(turnGoal)) print("steering error: {0}".format(steeringError)) print('Steering PID:') print(steeringPID) print('Velocity PID:') print(velocityPID) print('') loopCount = 0 rightStripCount = 0 leftStripCount = 0 steeringAvg = 0.0 #time.sleep(SLEEP_TIME); #for pulse in [ i for i in range(450, 1000) if i % 5 == 0 ]: #controlChnl(pwm, motorChnl, STOP) # tach # Read all ADC values #for pulse in [ i for i in range(450, 1000) if i % 5 == 0 ]: # controlChnl(pwm, motorChnl, pulse) # for i in range(4): # values[i] = adc.read_adc(i, gain=GAIN) # print("values[{0}] = {1}".format(i, values[i])) # time.sleep(1) # Reads ADC values #while True: # for i in range(4): # values[i] = adc.read_adc(i, gain=GAIN) # print("values[{0}] = {1}".format(i, values[i])) # print('') # time.sleep(1) finally: ramp(pwm, motorChnl, pulseDuration, STOP, 1, 5) #ramp(pwm, motorChnl, pulseDuration, STOP) ramp(pwm, turnChnl, steeringDuration, STOP, 1, 5) #print("ramp done") controlChnl(pwm, motorChnl, STOP) controlChnl(pwm, turnChnl, STOP) goalThread.join(timeout=2)
def main(): ''' Hacky version of our contigency plan ''' #------Variable Declarations------ # Tachometer Specific Data rightTachValue = 0 leftTachValue = 0 prevRightTachValue = 0 prevLeftTachValue = 0 rightVelocity = 0 rightStripCount = 0 leftVelocity = 0 leftStripCount = 0 loopCount = 0 leftHigh = 0 leftThresholdHigh = 8500 leftThresholdLow = 6500 rightHigh = 0 rightThresholdHigh = 10000 rightThresholdLow = 8000 steeringPotValue = 0 distTraveled = 0.0 distStartTime = 0.0 distEndTime = 0.0 # Timer startTime = 0 elapsedTime = 0 fractional = 0 # Steering / Turning Setup turnGoal = STRAIGHT steeringAvg = 0.0 steeringPID = PID(1.0, 0.2, 0.0, 3.0) steeringFilter = Filter(0.9) steeringPID.setGoal(turnGoal) # Velocity Setup velDuration = STOP avgVelocity = 0.0 velGoal = 0.5 velocityPID = PID(50.0, 100.0, 0.0, 3.0) velocityFilter = Filter(0.9) velocityPID.setGoal(velGoal) # Distance sensors leftDistSensor = DistanceSensor(echo=DIST_LEFT_ECHO_PIN, trigger=DIST_LEFT_TRIGGER_PIN, max_distance=DIST_MAX_DISTANCE, queue_len=DIST_QUEUE_LENGTH) rightDistSensor = DistanceSensor(echo=DIST_RIGHT_ECHO_PIN, trigger=DIST_RIGHT_TRIGGER_PIN, max_distance=DIST_MAX_DISTANCE, queue_len=DIST_QUEUE_LENGTH) distFilter = Filter(0.8) leftDist = 0.0 rightDist = 0.0 # Line Following Setup wallFollowPID = PID(10000.0, 0.0, 0.0, 0.8) wallFollowPID.setGoal(MAX_WALL_DIST) #--------------------------------- # Setup bus pwm = Adafruit_PCA9685.PCA9685() adc = Adafruit_ADS1x15.ADS1115() try: pwm.set_pwm_freq(FREQ) print("Start") distStartTime = time.time() while True: if (loopCount % 1 == 0): prevRightTachValue = rightTachValue prevLeftTachValue = leftTachValue steeringPotValue = adc.read_adc(POT_CHNL, gain=GAIN, data_rate=DATA_RATE) rightTachValue = adc.read_adc(RIGHT_WHEEL_CHNL, gain=GAIN, data_rate=DATA_RATE) leftTachValue = adc.read_adc(LEFT_WHEEL_CHNL, gain=GAIN, data_rate=DATA_RATE) distTraveled += (avgVelocity / (time.time() - distStartTime)) #distFilter.recvMeasurement(rightDistSensor.distance) #rightDist = distFilter.filter() #distFilter.recvMeasurement(leftDistSensor.distance) #leftDist = distFilter.filter() rightDist = rightDistSensor.distance leftDist = leftDistSensor.distance #print('Left Distance: ', leftDistSensor.distance * 100) #print('Right Distance: ', rightDistSensor.distance * 100) # Wall follow PID wallFollowPID.setCurrentMeasurement(rightDist) turnGoal = (wallFollowPID.control() + STRAIGHT) steeringFilter.recvMeasurement(steeringPotValue) steeringPotValue = steeringFilter.filter() steeringPID.setCurrentMeasurement(steeringPotValue / 1000.0) steeringPID.setGoal(turnGoal / 1000.0) if (rightHigh == 0 and rightTachValue > rightThresholdHigh): rightStripCount += 0.5 rightHigh = 1 if (rightHigh == 1 and rightTachValue < rightThresholdHigh): rightStripCount += 0.5 rightHigh = 0 if (leftHigh == 0 and leftTachValue > leftThresholdHigh): leftStripCount += 0.5 leftHigh = 1 if (leftHigh == 1 and leftTachValue < leftThresholdHigh): leftStripCount += 0.5 leftHigh = 0 loopCount += 1 # Steering steeringDuration = -steeringPID.control() + 0.5 ''' if steeringDuration > 0: #steeringDuration = 670 # Dead Band steeringDuration = 675 - steeringDuration elif steeringDuration < 0: #steeringDuration = 890 steeringDuration = 875 - steeringDuration # Max Zone if steeringDuration > 930: steeringDuration = 930 if steeringDuration < 630: steeringDuration = 630 ''' controlChnl(pwm, MOTOR_CHNL, velDuration) #controlChnl(pwm, MOTOR_CHNL, 0.75) #print("SD: {0}".format(steeringDuration)) controlChnl(pwm, TURN_CHNL, steeringDuration) #controlChnl(pwm, TURN_CHNL, 0.99) #controlChnl(pwm, TURN_CHNL, 930) #controlChnl(pwm, TURN_CHNL, 0.0) #controlChnl(pwm, TURN_CHNL, 780) #controlChnl(pwm, TURN_CHNL, velDuration) #controlChnl(pwm, TURN_CHNL, s) #print("VD: {0}".format(int(velDuration))) #print("SD: {0}".format(int(steeringDuration))) if (loopCount >= MAX_LOOP_COUNT): elapsedTime = (time.time() * 1000) - startTime startTime = (time.time() * 1000) rightVelocity = ((rightStripCount / 30.0) * 0.36 * math.pi) / (elapsedTime / 1000.0) leftVelocity = ((leftStripCount / 30.0) * 0.36 * math.pi) / (elapsedTime / 1000.0) # Velocity avgVelocity = (leftVelocity + rightVelocity) / 2.0 if velDuration > STOP: avgVelocity *= -1 velocityFilter.recvMeasurement(avgVelocity) avgVelocity = velocityFilter.filter() velocityPID.setCurrentMeasurement(avgVelocity) velocityPID.setGoal(velGoal) velDuration = STOP - velocityPID.control() #if velDuration < 550: # velDuration = 550 #if velDuration > 1000: # velDuration = 1000 print('Total Distance: ', distTraveled) print('Left Distance: ', leftDistSensor.distance * 100) print('Right Distance: ', rightDistSensor.distance * 100) print("LDist: {0}".format(leftDist)) print("RDist: {0}".format(rightDist)) print("LDist: {0}".format(leftDistSensor.distance * 100)) print("RDist: {0}".format(rightDistSensor.distance * 100)) print("LV: {0}".format(leftVelocity)) print("RV: {0}".format(rightVelocity)) print("Avg Vel: {0}".format(avgVelocity)) print("S: {0}".format(steeringPotValue)) print("ET: {0}".format(elapsedTime)) print("VD: {0}".format(velDuration)) print("VG: {0}".format(velGoal)) print("SD: {0}".format(steeringDuration)) print("SG: {0}".format(turnGoal)) print('Steering PID:') print(steeringPID) print('Velocity PID:') print(velocityPID) print('Wall Follow PID:') print(wallFollowPID) print('') loopCount = 0 rightStripCount = 0 leftStripCount = 0 steeringAvg = 0.0 finally: #ramp(pwm, MOTOR_CHNL, velDuration, STOP, 1, 5) #ramp(pwm, TURN_CHNL, steeringDuration, STOP, 1, 5) #controlChnl(pwm, MOTOR_CHNL, STOP) #controlChnl(pwm, TURN_CHNL, STOP) pass
def filtrar(): #Obtengo el archivo que se cargó #Los archivos tienen que tener nombre en la columna obligatoriamente para que me funcione f = request.files['archivo1'] fstring = f.read().decode("utf-8-sig").encode("utf-8") fieldnames = [ 'valor' ] #Le voy a poner un valor que yo conozca a la columna porque no se definió el nombre para el archivo de entrada diccionario_csv = [{ k: v for k, v in row.items() } for row in csv.DictReader( fstring.splitlines(), fieldnames=fieldnames, skipinitialspace=True)] #Elimino el primer elemento porque agrega el nombre de columna que yo le puse (fieldnames) diccionario_csv.pop(0) #Creo el arreglo de la señal de entrada para el filtro arreglo_senal_entrada = [] for x in diccionario_csv: ##print(x['valor']) #print(x) arreglo_senal_entrada.append(float(x['valor'])) #Creo la señal senal = Signal() senal.y = arreglo_senal_entrada #Obtengo los coeficientes del filtro que voy a usar para filtrar la señal arreglo_coeficientes = [] arreglo_coeficientes.append(float(request.form['b0'])) arreglo_coeficientes.append(float(request.form['b1'])) arreglo_coeficientes.append(float(request.form['b2'])) arreglo_coeficientes.append(float(request.form['b3'])) arreglo_coeficientes.append(float(request.form['b4'])) arreglo_coeficientes.append(float(request.form['b5'])) arreglo_coeficientes.append(float(request.form['b6'])) arreglo_coeficientes.append(float(request.form['b7'])) arreglo_coeficientes.append(float(request.form['b8'])) arreglo_coeficientes.append(float(request.form['b9'])) arreglo_coeficientes.append(float(request.form['b10'])) arreglo_coeficientes.append(float(request.form['b11'])) arreglo_coeficientes.append(float(request.form['b12'])) arreglo_coeficientes.append(float(request.form['b13'])) arreglo_coeficientes.append(float(request.form['b14'])) arreglo_coeficientes.append(float(request.form['b15'])) arreglo_coeficientes.append(float(request.form['b16'])) arreglo_coeficientes.append(float(request.form['b17'])) print("***** COEFICIENTES *****") print(arreglo_coeficientes) #Creo el filtro con los coeficientes del filtro #arreglo_coeficientes = [0.5999402, -0.5999402, 0, 1, -0.7265425, 0, 1, -2, 1, 1, -1.52169043, 0.6, 1, -2, 1, 1, -1.73631017, 0.82566455] #print(arreglo_coeficientes) filtro = Filter(arreglo_coeficientes) #Se filtra la señal de entrada salida = filtro.filter(senal) #Genero las gráficas fig, (ax1, ax2) = chart.subplots(2, 1, sharex=True) #ax1.plot(input.t, input.y) #ax1.plot([], senal.y) ax1.plot(senal.t, senal.y) ax1.set_title('Entrada del filtro') ax1.axis([0, 1, -10, 10]) ax2.plot(salida.t, salida.y) ax2.set_title('Salida del filtro') ax2.axis([0, 1, -10, 10]) ax2.set_xlabel('Tiempo [segundos]') chart.tight_layout() #chart.show() chart.savefig("salida.png", transparent=True) #plt.savefig("Ejemplo1.jpg") #Devuelvo una respuesta cualquiera return jsonify( estado=200, mensaje='La operación de filtrar se realizó con éxito', )