I got the error mentioned before in the line 51 of the following code:
import csv
import math
from datetime import datetime
with open('BBDD1') as csv_file:
csv_reader1 = csv.reader(csv_file, delimiter=',')
with open('BBDD2') as csv_file:
csv_reader2 = csv.reader(csv_file, delimiter=',')
contador1=0
contador2=0
cont=0
bbdd1=[]
bbdd2=[]
d=float(input("Ingrese la distancia en metros entre el evento sísmico y la tronadura: "))
for fila1 in csv_reader1:
if fila1 != []:
bbdd1.append(fila1)
for fila2 in csv_reader2:
if fila2 != []:
bbdd2.append(fila2)
#for i in range(50):
#print(i)
#print(len(bbdd1))
#print(float(bbdd1[3][6].replace(",",".")))
i=0
for i in range(len(bbdd1)):
for j in range(len(bbdd2)):
#print(bbdd1[fila1][fila2])
#print(bbdd1[fila1][6])
#print(fila1)
cont+=1
print(i)
print(j)
distancia=((float(bbdd1[i+1][6].replace(",","."))-float(bbdd2[j+1][3]))**2 + (float(bbdd1[i+1][7].replace(",","."))-float(bbdd2[j+1][4]))**2 + (float(bbdd1[i+1][8].replace(",","."))-float(bbdd2[j+1][5]))**2)**0.5
if distancia <d:
print("La distancia es: ", distancia)
print("El evento " + str(bbdd2[j+1][0]) + " está relacionado con la tronadura " + str(bbdd1[i+1][0]))
print("Los números de eventos sísmicos relacionados a las tronaduras con una distancia entre ambas de " + str(d) + " m es de " + str(cont))
I was trying to relation the following 2 database:
bbdd1:
N° Quemada,Fecha,Hora,PK,Avance,Acumulado,Norte,Este,Corte,Fecha y hora,Date time
1,24-09-2019,TB 08:04,"7309,12","3,82","3,82","-468,965","-563,220","1671,935",24-09-2019 08:04,2019-09-24 08:04:00
2,06-10-2019,TA 16:41,"7311,48","2,36","6,18","-467,728","-561,210","1676,133",06-10-2019 16:41,2019-10-06 16:41:00
.
.
.
bbdd2:
Index,Event Date,EventTimeInDay,LocX [m],LocY [m],LocZ [m],Local Magnitude,Log Potency [log m^3],Log Energy [log J],Log(EnergyS/EnergyP),TriggerCount,Fecha y hora,Date time
1,2021/02/16,21:35:03,-502.5,-415.0,1660.8,-1.0,-2.88,-0.61,1.80,8,2021/02/16 21:35:03,2021-02-16 21:35:03
2,2021/03/14,01:20:59,-478.6,-414.9,1690.9,-1.3,-3.37,0.34,1.28,6,2021/03/14 01:20:59,2021-03-14 01:20:59
.
.
.
(There are many more rows, 56 rows in bbdd1 and 3447 rows in bbdd2). The problem is the double "for" because the "i" variable of the first "for" never changes, it gets stuck in i=0 and it should change to i=56 from i=0 with steps of 1.
Related
I'm trying to implement an artificial neural network that I just trained using this code.
import numpy as np
import os
training_path = 'Imagenes/train'
training_names = os.listdir(training_path)
image_paths = []
image_classes = []
class_id = 0
def imglist(path):
return [os.path.join(path,f) for f in os.listdir(path)]
for training_name in training_names:
dir = os.path.join(training_path, training_name)
class_path = imglist(dir)
image_paths += class_path
image_classes += [class_id]*len(class_path)
class_id+=1
des_list = []
sift = cv2.xfeatures2d.SIFT_create(100)
for image_path in image_paths:
im = cv2.imread(image_path, 0)
kp, des = sift.detectAndCompute(im, None)
des_list.append((image_path, des))
descriptors = des_list[0][1]
for image_path, descriptor in des_list[1:]:
descriptors = np.vstack((descriptors,descriptor))
descriptors_float = descriptors.astype(float)
from scipy.cluster.vq import kmeans, vq
k = 1000
voc, variance = kmeans(descriptors_float, k, 1)
im_features = np.zeros((len(image_paths), k), "float32")
for i in range(len(image_paths)):
words, distance = vq(des_list[i][1], voc)
for w in words:
im_features[i][w] += 1
nbr_ocurrences = np.sum((im_features > 0) * 1, axis = 0)
idf = np.array(np.log((1.0*len(image_paths)+1) / (1.0*nbr_ocurrences + 1)), 'float32')
from sklearn.preprocessing import StandardScaler
stdSlr = StandardScaler().fit(im_features)
im_features = stdSlr.transform(im_features)
print(np.shape(im_features))
print(np.shape(image_classes))
from sklearn.neural_network import MLPClassifier
clf = MLPClassifier(hidden_layer_sizes=(50,50), max_iter=5000, alpha=0.001,
solver='sgd', verbose=10, random_state=21,tol=0.000000001)
clf.fit(im_features, np.array(image_classes))
from sklearn.externals import joblib
joblib.dump((clf, training_names, stdSlr, k, voc), 'sift.pkl', compress = 3)
Well basically that's it and what I'm trying to implement is this
import cv2
import numpy as np
from sklearn.externals import joblib
#Cargando parámetros del modelo, clases y desviaciones estandar par normalizar, además de los clusters
clf, class_names, stdSlr, k, voc = joblib.load('sift.pkl')
#Creando SIFT
sift = cv2.xfeatures2d.SIFT_create(100)
#Objeto de video
video = cv2.VideoCapture('video2.mp4')
fgbg = cv2.createBackgroundSubtractorMOG2()
#Ciclo infinito
while True:
#Leer siguiente cuadro
ret, frame = video.read()
#Si hay siguiente cuadro, ret es TRUE de lo contrario es false y se rompe el ciclo
if ret:
porcentaje_escala = 100 # percent of original size
width = int(frame.shape[1] * porcentaje_escala / 100)
height = int(frame.shape[0] * porcentaje_escala / 100)
dim = (width, height)
frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
#Mostramos el cuadro leído
cv2.imshow('Video Original', frame)
#Convertimos el cuadro a escala de grises para procesarlo
frame_gris = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('Escala de Grises',frame_gris)
#Aplicamos MOG acá
fgmask = fgbg.apply(frame_gris)
#Le hacemos thresholding para eliminar las sombras que el MOG2 deja en gris
ret,fgmask = cv2.threshold(fgmask,250,255,cv2.THRESH_BINARY)
#Aplicamos un pequeño filtro para quitarle ruido a la máscara
fgmask = cv2.GaussianBlur(fgmask,(3,3),0)
#Ahora vamos a dilatar y erosionar un poco la máscara para poder darle un espacio blanco al objeto
#no que detecte la forma sino sólo su espacio
kernel = np.ones((8,8),np.uint8)
fgmask = cv2.dilate(fgmask,kernel,iterations = 1)
fgmask = cv2.erode(fgmask,kernel,iterations = 1)
cv2.imshow('Mascara de MOG2',fgmask)
#Ahora hacemos el AND bit a bit de la máscara y la imagen original
res = cv2.bitwise_and(frame,frame,mask = fgmask)
cv2.imshow('resultado',res)
#Hallamos los componentes que comparten bits blancos en la imagen
contours, hierarchy = cv2.findContours(fgmask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[-2:]
#Se dibuja cada contorno si su alto y ancho es mayor a 20 pixeles
ROI=[]
for c in contours:
x,y,w,h = cv2.boundingRect(c)
if((w>20) and (h>20)):
ROI.append(frame[x:x+w,y:y+h])
ROI_Valida=[]
for i in range(len(ROI)):
if(np.shape(ROI[i])[0] > 0):
ROI_Valida.append(ROI[i])
for i in range(len(ROI_Valida)):
kp, des = sift.detectAndCompute(ROI_Valida[i], None)
test_features = np.zeros(k, "float32")
from scipy.cluster.vq import vq
words, distance = vq(des, voc)
for w in words:
test_features[w] += 1
Mostramos la imagen final
if cv2.waitKey(1) & 0xFF == ord('q'):
break;
else:
break;
However in this line in the implementation
words, distance = vq(des, voc)
I'm getting the next error
Traceback (most recent call last):File "C:\Universidad\Trabajo de Grado\Pruebas\p2.py", line 60, in words, distance = vq(des, voc)
File "C:\Python36\lib\site-packages\scipy\cluster\vq.py", line 201, in vq obs = _asarray_validated(obs, check_finite=check_finite)
File "C:\Python36\lib\site-packages\scipy_lib_util.py", line 249, in _asarray_validated raise ValueError('object arrays are not supported')
ValueError: object arrays are not supported
Which doesn't make sense to me as it's the same line used in training with a set of matrix.
I'd appreciate any help.
I am making a definition which will help me replace the varials of a polynomial but I get this error
from sympy import *
x = Symbol('x')
def velocidad_media(t0,t1,poli):
D1=poli.subs(x,t0)
D0=poli.subs(x,t1)
D3=D1-D0
T= t1-t0
Re=D3/T
print("la velocidad media es",Re,"m/s")
pol=input("ingrese la funcion del lanzamiento: ")
a= int(input("ingrese el tiempo inicial en segundos: "))
b=int(input("ingrese el tiempo final en segundos: "))
punt=int(input("ingrese el punto en donde quiere hallar la velocidad instantanea: "))velocidad_media(a,b,pol)`
Error message :
AttributeError: 'str' object has no attribute 'subs'
The input returns a str type, but you are treating it as a sympy expression.
What you can do it to parse the string pol into an sympy expression with the function parse_expr.
e.g.
from sympy import *
from sympy.parsing.sympy_parser import parse_expr
x = Symbol('x')
pol = parse_expr('x**2 + x + 1')
pol.subs(x,1)
I want to open a file to edit what's inside with but i get this error
Traceback (most recent call last):
File "C:/Users/user/PycharmProjects/LittleSmashBros/Editeur de niveau.py", line 95, in <module>
fichier = open("niveau1.txt",)
TypeError: Required argument 'flags' (pos 2) not found
This is not my first time coding something but I am pretty new to this. My textfile is in the right file, it worked before. It stopped working when I added the function fichier_temp. If you could find what's the problem and explain how to solve it. This is my code, sorry for the variable name, I am French.
from tkinter import *
from os import *
fenetre = Tk()
fenetre.title("LittleSmashBros")
fenetre.geometry("1110x720")
bgImage = PhotoImage(file="Greenbg.png")
fond = Canvas(fenetre,width=1110,height=720)
fond.place(x=-2,y=-2)
fond.create_image(0,0,image=bgImage,anchor="nw")
fond.create_rectangle(1080,0,1111,720,fill="black")
#Stocke les images dans des variables
platGauche = PhotoImage(file="platGauche.png")
platMilieu = PhotoImage(file="platMilieu.png")
platDroite = PhotoImage(file="platDroite.png")
#Bouton qui définissent le bloc choisi
typeBloc = "V"
couleurB = "black"
def changeBloc(bloc): typeBloc = bloc
def boutonEnfonce(bouton) :
bloc1.config(bg=couleurB)
bloc2.config(bg=couleurB)
bloc3.config(bg=couleurB)
bouton.config(bg="white")
bloc1 = Button(fenetre,image=platGauche,height=21,width=21,relief=FLAT,bg=couleurB,command=lambda : [changeBloc("G"),boutonEnfonce(bloc1)])
bloc2 = Button(fenetre,image=platMilieu,height=21,width=21,relief=FLAT,bg=couleurB,command=lambda : [changeBloc("M"),boutonEnfonce(bloc2)])
bloc3 = Button(fenetre,image=platDroite,height=21,width=21,relief=FLAT,bg=couleurB,command=lambda : [changeBloc("D"),boutonEnfonce(bloc3)])
bloc1.place(x=1082,y=10)
bloc2.place(x=1082,y=41)
bloc3.place(x=1082,y=72)
#Prend les coordonnées de la souris et donne sa position sur la grille
def cordsouris(cord):
global x0,y0
x0 = cord.x
y0 = cord.y
x1 = 0
x2 = 22
y1 = 0
y2 = 22
testx = False
testy = False
colonne = 0
ligne = 0
while testx == False:
if x1 < x0 < x2:
testx = True
colonne = colonne + 1
else:
colonne = colonne + 1
x1 = x1+21
x2 = x2+21
print(colonne)
while testy == False:
if y1 < y0 < y2:
testy = True
ligne = ligne + 1
else:
ligne = ligne + 1
y1 = y1+21
y2 = y2+21
print(ligne)
return (colonne,ligne)
#Créé la ligne a remplacer
def remplace_str_index(ligne,place,remplacement):
texte = fichier.readline(ligne)
return '%s%s%s'%(texte[:place],remplacement,texte[place+1:])
#Copie l'ancien fichier dans un nouveau avec la modification
def fichier_temp():
fichier = open("niveau1.txt")
colonne,ligne = cordsouris()
with open("temp.txt","w")as temp:
nb = 0
for rang in fichier:
nb = nb+1
if nb==ligne: text = remplace_str_index(ligne,colonne-1,typeBloc)
else : text = rang
temp.write(text)
print(rang)
print(text)
fichier.close()
os.remove("niveau1.txt")
os.rename("temp.txt","niveau1.txt")
#Détecte le click et effectue le changement de bloc
fond.bind("<Button 1>",fichier_temp)
#Place l'image en fonction du fichier texte
fichier = open("niveau1.txt",)
x=0
y=0
for rang in fichier:
for caractere in rang:
if caractere=="S":
fond.delete(fond.find_closest(x,y))
if caractere=="G":
fond.create_image(x,y,image=platGauche,anchor="nw")
if caractere=="M":
fond.create_image(x,y,image=platMilieu,anchor="nw")
if caractere=="D":
fond.create_image(x,y,image=platDroite,anchor="nw")
x = x+21
x = 0
y = y+21
fichier.close()
fenetre.mainloop()
This is exactly why you should never use from X import *.
from os import * overridden the builtin open in Python with os.open (which, unlike the builtin open, does not have a mode).
Either remove the star import or provide a flag like you have in the other places you used os.open.
You need to provide the file open mode
open("niveau1.txt", "r")
This is the problem:
from os import *
It also imports os.open which now overrides the builting open.
If you only import the parts you need from os it will work fine.
I woul like to know :
With the same list len = 100_000 I've an error only if I call quicksort_bad and not quicksort ?
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
def quicksort_bad(arr, inizio=0, fine=-1): # Porzione di arr
if fine == -1:
fine += len(arr)
if inizio < fine : # arr con + elementi
pivot = arr[fine] # prendo l'ultimo come riferimento
iprog = inizio
j = inizio
while j <fine : # considero tutti gli elementi che lo precedono
if arr[j] <= pivot : # confronto se sono minori dell' ultimo
arr[iprog], arr[j]= arr[j], arr[iprog] # scambio con prog
iprog += 1 # incremento indice progressivo dei minori
j +=1
arr[iprog], arr[fine]= arr[fine], arr[iprog] # il primo dei maggiori lo scambio con il pivot
quicksort_bad(arr, inizio, iprog-1) # parte dei minori o uguali
quicksort_bad(arr, iprog + 1, fine) # parte dei maggiori
Hi I am trying to calculate the implied vol but because my variable T is under 0.1 I am getting this strange error. "divide by zero encountered in double_scalars"
I would like to know what I am doing wrong. Thanks.
#Importamos librerias
from math import log,exp,sqrt
from scipy import stats
#Definimos nuestra funcion acumulativa
N = stats.norm.cdf
#Definimos la formula de Black Scholes para una opción Call
def BS(S0,K,T,r,sigma):
S0 = float(S0)
d1 = (log(S0/K)+(r + 0.5 * sigma**2)*T)/(sigma*sqrt(T))
d2 = (log(S0/K)+(r - 0.5*sigma**2)*T)/(sigma*sqrt(T))
value = (S0*N(d1)-K*exp(-r*T)*N(d2))
return value
#Definimos Vega que es la derivada con respecto de sigma
def Vega(S0,K,T,r,sigma):
S0 = float(S0)
d1 = (log(S0/K)+(r + 0.5 * sigma**2)*T)/(sigma*sqrt(T))
vega = S0 * N(d1)*sqrt(T)
return vega
#Definimos la volatilidad implicita usando BS y Vega, usamos el metodo de
#Newton para resolver
def ImpliedVol(S0, K, T, r, C0, sigma_est, it=100):
for i in range(it):
sigma_est -= ((BS(S0,K,T,r, sigma_est)-C0)/Vega(S0,K,T,r,sigma_est))
return sigma_est
#Calculamos de Acuerdo a los parametros
S0 = 173
K = 130
T = 0.02
r = 0.029
C0 = 42
Sigma_init = 0.5
print(ImpliedVol(S0,K,T,r,C0,Sigma_init))