I am trying to use mllfow library to log the variables. The code is very simple and basic. After running my script, I am receiving an error like cannot import name 'BaseSSLError' from 'urllib3.connection'. Please refer below code.
import mlflow
def calculate_nthpower(x, n):
return x**n
if __name__ == '__main__':
# context manager
with mlflow.start_run():
x, n = 2, 5
y = calculate_nthpower(x, n)
mlflow.log_param('x', x)
mlflow.log_param('n', n)
mlflow.log_metric("y", y)
I'm trying to use data from a csv file ( https://www.kaggle.com/jingbinxu/sample-of-car-data ). I only need the horsepower and weight columns as variables for the equation: ( 1/4 mile et = 6.290 * (weight/hp) ** .33 ), but it won't apply it. I don't know if the storage is working or I shouldn't do it as a class. When I run the program it doesn't show any errors, but it doesn't show results either. Then I got to plot the results, but I don't think it's even calculating and storing results. Any help is appreciated. Thanks in advance.
Here's the current code i have:
import numpy as np
class car_race_analysis():
def __init__(self, filename):
import numpy as np
self.data = np.genfromtxt(filename,delimiter= ',', skip_header = 1 )
def race_stats(self,w,h):
#cars in data
cars = np.unique(self.data[:,0])
#storage for output
race_times = []
#for each car
for car in cars:
#mask
mask = self.data[:,0] == car
#get data
w = self.data[mask,12]
h = self.data[mask,18]
#apply formula
qrtr_mile = 6.290 * ( w / h ) ** .33
race_times.append(qrtr_mile)
#new atribute
self.race_times = np.array(race_times)
print(race_times)
def trend_plotter(self):
import matlib.pyplot as plt
#inputs
self.race_stats
cars = np.unique(self.data[:,0])
#plot
plt.plot(cars,self.race_times)
plt.xlabel("Car")
plt.ylabel("1/4 Mile Time")
plt.savefig("trend_plot.png")
filename = 'car_data.csv'
Two problems:
I think you meant matplotlib instead of matlib. Make sure you install it pip3 install matplotlib --user and edit your code accordingly.
Your previous code wasn't working because you weren't instantiating a class or running any methods. The only "work" your program did was to define the class and then set a filename variable.
To solve #2, replace your filename=... line with the code below.
Here's what it does:
It checks to see if the file is being run directly (i.e. from command prompt such as python3 <your_file_name>.py. If this class is being imported and used from a different python file, this code would not be executed. More reading: https://www.geeksforgeeks.org/what-does-the-if-name-main-do/
We instantiate a instance of your class and supply the filename variable since that it was your class' __init__ method expects.
We invoke the trend_plotter method on the instance of the class.
if __name__ == '__main__':
filename = 'car_data.csv'
car_analysis = car_race_analysis(filename)
car_analysis.trend_plotter()
Even with those changes, your program will not work because it has other errors. I made a guess at fixing it, which I've pasted below, but I strongly encourage you do diff my changes to understand what I altered to be sure it does what you want.
import numpy as np
import matplotlib.pyplot as plt
class car_race_analysis():
race_times = []
cars = []
def __init__(self, filename):
import numpy as np
self.data = np.genfromtxt(filename, delimiter=',', skip_header=1)
def race_stats(self, w, h):
#cars in data
self.cars = np.unique(self.data[:, 0])
# storage for output
self.race_times = []
# for each car
for car in self.cars:
# mask
mask = self.data[:, 0] == car
# get data
w = self.data[mask, 12]
h = self.data[mask, 18]
# apply formula
qrtr_mile = 6.290 * (w / h) ** .33
self.race_times.append(qrtr_mile)
# new atribute
self.race_times = np.array(self.race_times)
def trend_plotter(self):
# inputs
self.race_stats(len(self.cars), len(self.race_times))
# plot
plt.plot(self.cars, self.race_times)
plt.xlabel("Car")
plt.ylabel("1/4 Mile Time")
plt.savefig("trend_plot.png")
plt.show()
if __name__ == '__main__':
filename = 'car_data.csv'
car_analysis = car_race_analysis(filename)
car_analysis.trend_plotter()
I want to know if is there a way to make multiprocessing working in this code. What should I change or if there exist other function in multiprocessing that will allow me to do that operation.
You can call the locateOnScreen('calc7key.png') function to get the screen coordinates. The return value is a 4-integer tuple: (left, top, width, height).
I got error:
checkNumber1 = resourceBlankLightTemp[1]
TypeError: 'Process' object does not support indexing
import pyautogui, time, os, logging, sys, random, copy
import multiprocessing as mp
BLANK_DARK = os.path.join('images', 'blankDark.png')
BLANK_LIGHT = os.path.join('images', 'blankLight.png')
def blankFirstDarkResourcesIconPosition():
blankDarkIcon = pyautogui.locateOnScreen(BLANK_DARK)
return blankDarkIcon
def blankFirstLightResourcesIconPosition():
blankLightIcon = pyautogui.locateOnScreen(BLANK_LIGHT)
return blankLightIcon
def getRegionOfResourceImage():
global resourceIconRegion
resourceBlankLightTemp = mp.Process(target = blankFirstLightResourcesIconPosition)
resourceBlankDarkTemp = mp.Process(target = blankFirstDarkResourcesIconPosition)
resourceBlankLightTemp.start()
resourceBlankDarkTemp.start()
if(resourceBlankLightTemp == None):
checkNumber1 = 2000
else:
checkNumber1 = resourceBlankLightTemp[1]
if(resourceBlankDarkTemp == None):
checkNumber2 = 2000
else:
checkNumber2 = resourceBlankDarkTemp[1]
In general, if you just want to use multiprocessing to run existing CPU-intensive functions in parallel, it is easiest to do through a Pool, as shown in the example at the beginning of the documentation:
# ...
def getRegionOfResourceImage():
global resourceIconRegion
with mp.Pool(2) as p:
resourceBlankLightTemp, resourceBlankDarkTemp = p.map(
lambda x: x(), [blankFirstLightResourcesIconPosition,
blankFirstDarkResourcesIconPosition])
if(resourceBlankLightTemp == None):
# ...
I am working on a project for my shop that would allow me to track dimensions for my statistical process analysis. I have a part with 2 dimensions that I will measure 5 samples for. The dimension are OAL (Over All Length) and a Barb Diameter. I got Python and tKinter to create the window and put all the data into the correct place, but it will not export to the CSV file. It keeps telling me that the name is not defined, but the variable does exist and if I use a print command, the correct value comes up in the shell. So I know the variable exists I'm not sure if it's because I'm using tKinter or not. Any help would be appreciated.
import time
from tkinter import *
import threading
import csv
import datetime
def gui():
root = Tk()
root.title("Troy Screw Products")
titleLabel = Label(root,text="Inspection Worksheet")
partNumLabel = Label(root,text="Part #68800")
now = datetime.datetime.now()
typeLabel = ["Barb Dia","Barb Dia","OAL","Knurl","Threads","Chamfer","OD","OD","OD"]
dimLabel = [".356",".333",".437",".376","n/a",".258",".337",".321",".305"]
tolLabel = [".354/.358",".331/.335",".433/.441",".374/.378","1/4-20",".252/.263",".335/.339",".319/.323",".303/.307"]
observations = ["Obs 1","Obs 2","Obs 3","Obs 4","Obs 5"]
cd1Obs = []
Label(text="Inspection Worksheet").grid(row=0,column=0)
Label(text="Part #68800").grid(row=1,column=0)
r=0
for c in typeLabel:
Label(text=c,relief=RIDGE,width=15).grid(row=2,column=r)
r=r+1
r=0
for c in dimLabel:
Label(text=c,relief=RIDGE,width=15).grid(row=3,column=r)
r=r+1
r=0
for c in tolLabel:
Label(text=c,relief=RIDGE,width=15).grid(row=4,column=r)
r=r+1
r=0
for c in tolLabel:
Checkbutton(width=15).grid(row=5,column=r)
r=r+1
Label(text="").grid(row=6,column=1)
Label(text="").grid(row=7,column=1)
Label(text="OAL").grid(row=8,column=2)
Label(text="Barb Dia").grid(row=8,column=6)
r=9
for c in observations:
Label(text=c,width=15).grid(row=r,column=1)
Label(text=c,width=15).grid(row=r,column=5)
r=r+1
dimOneOb1=StringVar()
dimOneOb2=StringVar()
dimOneOb3=StringVar()
dimOneOb4=StringVar()
dimOneOb5=StringVar()
dimTwoOb1=StringVar()
dimTwoOb2=StringVar()
dimTwoOb3=StringVar()
dimTwoOb4=StringVar()
dimTwoOb5=StringVar()
Entry(textvariable=dimOneOb1).grid(row=9,column=2)
Entry(textvariable=dimOneOb2).grid(row=10,column=2)
Entry(textvariable=dimOneOb3).grid(row=11,column=2)
Entry(textvariable=dimOneOb4).grid(row=12,column=2)
Entry(textvariable=dimOneOb5).grid(row=13,column=2)
Entry(textvariable=dimTwoOb1).grid(row=9,column=6)
Entry(textvariable=dimTwoOb2).grid(row=10,column=6)
Entry(textvariable=dimTwoOb3).grid(row=11,column=6)
Entry(textvariable=dimTwoOb4).grid(row=12,column=6)
Entry(textvariable=dimTwoOb5).grid(row=13,column=6)
def submitEntry():
groupOal1=dimOneOb1.get()
groupOal2=dimOneOb2.get()
groupOal3=dimOneOb3.get()
groupOal4=dimOneOb4.get()
groupOal5=dimOneOb5.get()
groupBarb1=dimTwoOb1.get()
groupBarb2=dimTwoOb2.get()
groupBarb3=dimTwoOb3.get()
groupBarb4=dimTwoOb4.get()
groupBarb5=dimTwoOb5.get()
writeCsv()
Button(text="Submit",command=submitEntry).grid(row=14,column=7)
def writeCsv():
with open("CD 68800 OAL.csv", "a") as cdOal: #open file and give file variable name; r=read, w=write, a=append
cdOalWriter = csv.writer(cdOal) #Give writer a variable name
cdOalWriter.writerow([now.strftime("%Y-%m-%d %H:%M"),groupOal1,groupOal2,groupOal3,groupOal4,groupOal5])
csOal.close()
root.mainloop()
op1 = threading.Thread(target = gui)
op1.start()
Simply pass those variables in the method, writeCsv(). Because the groupOas are local to the submitEntry() function, its called function, writeCsv, does not see such objects. Also, below uses the argument unpack idiom, * of list of objects (I comment out the more verbose lines):
def submitEntry():
groupOal1=dimOneOb1.get()
groupOal2=dimOneOb2.get()
groupOal3=dimOneOb3.get()
groupOal4=dimOneOb4.get()
groupOal5=dimOneOb5.get()
group0as = [groupOal1,groupOal2,groupOal3,groupOal4,groupOal5]
groupBarb1=dimTwoOb1.get()
groupBarb2=dimTwoOb2.get()
groupBarb3=dimTwoOb3.get()
groupBarb4=dimTwoOb4.get()
groupBarb5=dimTwoOb5.get()
writeCsv(*group0as)
# writeCsv(groupOal1,groupOal2,groupOal3,groupOal4,groupOal5)
def writeCsv(a, b, c, d, e):
with open("CD 68800 OAL.csv", "a") as cdOal:
cdOalWriter = csv.writer(cdOal)
cdOalWriter.writerow([now.strftime("%Y-%m-%d %H:%M"), a, b, c, d, e])
csOal.close()
This is my first post. Is it possible to change the speed of a playback during playback? I want to simulate a car engine sound and for this the first step is to change the speed of a looped sample according to the RPM of the engine. I know how to increase the speed of a complete sample using pyaudio by changing the rate of the wave file, but I want to have a contineous change of the rate. Is this possible without using the scikits.samplerate package, which allows resampling (and is quite old) or pysonic, which is superold?
This is what I have at the moment:
import pygame, sys
import numpy as np
import pyaudio
import wave
from pygame.locals import *
import random as rd
import os
import time
pygame.init()
class AudioFile:
chunk = 1024
def __init__(self, file, speed):
""" Init audio stream """
self.wf = wave.open(file, 'rb')
self.speed = speed
self.p = pyaudio.PyAudio()
self.stream = self.p.open(
format = self.p.get_format_from_width(self.wf.getsampwidth()),
channels = 1,
rate = speed,
output = True)
def play(self):
""" Play entire file """
data = self.wf.readframes(self.chunk)
while data != '':
self.stream.write(data)
def close(self):
""" Graceful shutdown """
self.stream.close()
self.p.terminate()
a = AudioFile("wave.wav")
a.play()
You should be able to do something with numpy. I'm not really familiar with wave etc. and I would expect your play() method to include a readframes() inside the loop in some way (as I attemp to do here) but you can probably get the idea from this
def play(self):
""" Play entire file """
x0 = np.linspace(0.0, self.chunk - 1.0, self.chunk)
x1 = np.linspace(0.0, self.chunk - 1.0, self.chunk * self.factor) # i.e. 0.5 will play twice as fast
data = ''
while data != '':
f_data = np.fromstring(self.wf.readframes(self.chunk),
dtype=np.int).astype(np.float) # need to use floats for interpolation
if len(f_data) < self.chunk:
x1 = x1[:int(len(f_data) * self.factor)]
data = np.interp(x1, x0, f_data).astype(np.int)
self.stream.write(data)
Obviously this uses the same speed up or slow down factor for the whole play. If you wanted to change it mid play you would have to modify x1 inside the while loop.