Scatter Plot Only Plots the last iteration - python

I am trying to plot several different things in scatter plots by having several subplots and iterating over. Here in an example of what the result actually look like:
('x out: ', ' -511', ' y out: ', ' 1')
('Magnitudo = ', 4.778809128414475)
[0.]
('x out: ', ' -511', ' y out: ', ' -255')
('Magnitudo = ', 5.9840357600793475)
[1.]
('x out: ', ' -511', ' y out: ', ' 1')
('Magnitudo = ', 5.474086008639472)
[0.]
('x out: ', ' 513', ' y out: ', ' -511')
('Magnitudo = ', 5.182103409440737)
[0.]
('x out: ', ' -511', ' y out: ', ' 513')
('Magnitudo = ', 5.1769691160028835)
[0.]
('x out: ', ' -255', ' y out: ', ' -511')
('Magnitudo = ', 6.559643742815329)
[1.]
And this is the matplot I generated:
Result
As you can see, the matplot only shows the last iteration of my result. How do I present all of my iteration into this graph? Thank you. Here's my code. Where did I go wrong?
print ("Gyroskop")
print ("--------")
i="TRUE"
j = 0
mag = []
with open("/home/pi/TA/accelero.csv") as csvFile:
while i == "TRUE":
gyroskop_xout1 = read_word_2c(0x43)
gyroskop_yout1 = read_word_2c(0x45)
acc1 = math.sqrt((gyroskop_xout1*gyroskop_xout1)+(gyroskop_yout1*gyroskop_yout1))
mag.append(acc1)
print ("x out: ", ("%5d" % gyroskop_xout1), " y out: ",("%5d" % gyroskop_yout1))
j=j+1
time.sleep(1)
#---------------------
gyroskop_xout2 = read_word_2c(0x43)
gyroskop_yout2 = read_word_2c(0x45)
acc2 = math.sqrt((gyroskop_xout2*gyroskop_xout2)+(gyroskop_yout2*gyroskop_yout2))
mag.append(acc2)
time.sleep(1)
#--------------------
mag_max = max(mag)
mag_min = min(mag)
amplitude = mag_max - mag_min
# print "A : ",amplitude
h = amplitude/0.001
# print h
# print abs(h)
M_richter = 0
if(h!=0):
M_richter = math.log10(abs(h))
print ("Magnitudo = ",(M_richter))
#mag.clear()
del mag [:]
#accel = deltaM /2
hasil=clf.predict([[1, M_richter]])
print(hasil)
if (M_richter >= 6):
while aaa<5:
GPIO.output(buzzer,GPIO.HIGH)
print ("Beep")
sleep(0.5) # Delay in seconds
GPIO.output(buzzer,GPIO.LOW)
#print ("No Beep")
sleep(0.5)
aaa=aaa+1
csvFile.close()
i = "False"
if j == 10:
i = "False"
X0, X1 = 1, M_richter
plt.scatter(X0,X1, color = 'G')
plt.title('linear SVC')
plt.ylabel('Magnitude')
plt.xlabel('Location')
plt.show()
Y is 1 by default and I want to show all my magnitudo, thank you.

Currently, you are only passing a single point value (X0,X1) to plt.scatter(). You need to pass it a list of values, for example:
plt.scatter([x1,x2,x3,x4], [y1,y2,y3,y4], color = 'G')
However, I'm not completely sure what you are trying to plot here? If you want to plot the magnitude (M_richter) vs. the index j you have to append the calculated M_richter in each iteration to a list and then pass the list to plt.scatter(), and do the same with the values of j. Your script would then look like:
print ("Gyroskop")
print ("--------")
i="TRUE"
j = 0
mag = []
M_richter_values = []
j_values = []
with open("/home/pi/TA/accelero.csv") as csvFile:
while i == "TRUE":
gyroskop_xout1 = read_word_2c(0x43)
gyroskop_yout1 = read_word_2c(0x45)
acc1 = math.sqrt((gyroskop_xout1*gyroskop_xout1)+(gyroskop_yout1*gyroskop_yout1))
mag.append(acc1)
print ("x out: ", ("%5d" % gyroskop_xout1), " y out: ",("%5d" % gyroskop_yout1))
j_values.append(j) # Append value of j to list
j=j+1
time.sleep(1)
#---------------------
gyroskop_xout2 = read_word_2c(0x43)
gyroskop_yout2 = read_word_2c(0x45)
acc2 = math.sqrt((gyroskop_xout2*gyroskop_xout2)+(gyroskop_yout2*gyroskop_yout2))
mag.append(acc2)
time.sleep(1)
#--------------------
mag_max = max(mag)
mag_min = min(mag)
amplitude = mag_max - mag_min
# print "A : ",amplitude
h = amplitude/0.001
# print h
# print abs(h)
M_richter = 0
if(h!=0):
M_richter = math.log10(abs(h))
print ("Magnitudo = ",(M_richter))
M_richter_values.append(M_richter) # Append to list
#mag.clear()
del mag [:]
#accel = deltaM /2
hasil=clf.predict([[1, M_richter]])
print(hasil)
if (M_richter >= 6):
while aaa<5:
GPIO.output(buzzer,GPIO.HIGH)
print ("Beep")
sleep(0.5) # Delay in seconds
GPIO.output(buzzer,GPIO.LOW)
#print ("No Beep")
sleep(0.5)
aaa=aaa+1
csvFile.close()
i = "False"
if j == 10:
i = "False"
X0, X1 = 1, M_richter
plt.scatter(j_values, M_richter_values, color = 'G') # Passing lists instead of scalars
plt.title('linear SVC')
plt.ylabel('Magnitude')
plt.xlabel('Location')
plt.show()

Related

How can I form multiple lists from append

I made this code in order that every time it runs once it gives me a list in the correct sequence, I wanted the code to form a list from the repetition forming p1+p2+p3, but the code gives me all the p1 plus all the p2 plus all the p3, I wish every time it ran I was given a list.
p11 = []
p22 = []
p33 = []
for n in range(0, quantidade):
print('EPISÓDIO', n+1)
for g in range(0, prot):
p1 = ' ' + protagonistasn[g] + ' ' + random.choice(açoes) + ' ' + random.choice(coadjuvantesn) + ' ' + random.choice(locais)
if g <= prot/2 :
p1_1 = p1.replace("#","a")
p11.append(p1_1)
print(p1_1)
elif g > prot/2 :
p1_1 = p1.replace("#", "o")
p11.append(p1_1)
print(p1_1)
for j in range(0, vil):
p2 = ' ' +viloesn[j]+ ' ' + random.choice(açoes) + ' ' + random.choice(protagonistasn) + ' ' + random.choice(locais)
if j <= vil/2:
p2_2 = p2.replace("#", "a")
p22.append(p2_2)
print(p2_2)
elif j > vil/2:
p2_2 = p2.replace("#", "o")
p22.append(p2_2)
print(p2_2)
for h in range(0, prot):
p3 = ' ' + protagonistasn[h] + ' ' + random.choice(açoes) + ' ' + random.choice(viloesn) + ' ' + random.choice(locais)
if h <= prot/2 :
p3_3 = p3.replace("#","a")
p33.append(p3_3)
print(p3_3)
elif h > prot/2 :
p3_3 = p3.replace("#", "o")
p33.append(p3_3)
print(p3_3)
p_total = [p11, p22, p33]
p_tot = []
If I understand you right, you want your p_total list to contain all the p1s, p2s, and p3s from the first iteration, and then all the p1s, p2s, and p3d from the second iteration. Is that right? If so:
p_total = []
for n in range(0, quantidade):
p11 = []
p22 = []
p33 = []
print('EPIS?DIO', n+1)
for g in range(0, prot):
...
print(p3_3)
p_total.extend( [p11, p22, p33] )
p_tot = []
So, start each loop with an empty p11, p22, and p33. At the end of each iteration, append those on to your p_total, instead of holding them until the end.

Creating a schedule via python

I'm currently working on trying to build a scheduler that will assign parts to specific time slots. This is what I've come up with currently, but I'm curious to know if there is a better way to do this. I'm fairly new to coding in python, so really have just working with while/for loops and if/else statements. I'm sure there is a way, so hopefully someone out there can show me the light.
import pandas as pd
from datetime import datetime, timedelta
day_start = str('2021-07-28 06:30')
break_1_start = str('2021-07-28 08:50')
lunch_start = str('2021-07-28 12:00')
break_2_start = str('2021-07-28 14:50')
day_end = str('2021-07-28 17:40')
day_start = datetime.strptime(day_start, "%Y-%m-%d %H:%M")
break_1_start = datetime.strptime(break_1_start, "%Y-%m-%d %H:%M")
break_1_end = break_1_start + timedelta(minutes=20)
lunch_start = datetime.strptime(lunch_start, "%Y-%m-%d %H:%M")
lunch_end = lunch_start + timedelta(minutes=30)
break_2_start = datetime.strptime(break_2_start, "%Y-%m-%d %H:%M")
break_2_end = break_2_start + timedelta(minutes=20)
day_end = datetime.strptime(day_end, "%Y-%m-%d %H:%M")
sched_df = pd.DataFrame({"Time": [day_start, break_1_start, break_1_end, lunch_start, lunch_end,
break_2_start, break_2_end, day_end]})
print(sched_df)
demand_df = pd.DataFrame({"PartNo": ['Part1', 'Part2', 'Part3', 'Part4', 'Part5'],
"TTJ": [75, 100, 180, 30, 60]})
demand_df = demand_df.astype({'TTJ': float})
print(demand_df)
a = 0
b = 1
c = 2
x = sched_df.iloc[a]['Time']
y = sched_df.iloc[0]['Time']
z = 0
for n in range(0, len(demand_df)):
while y < sched_df.iloc[1]['Time']:
y = x + timedelta(minutes=demand_df.iloc[a]['TTJ'])
if y > sched_df.iloc[1]['Time']:
end = sched_df.iloc[1]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', end.time())
start = sched_df.iloc[1]['Time']
end = sched_df.iloc[2]['Time']
print('Break time from : ', start.time(), ' to ', end.time())
xyz = sched_df.iloc[1]['Time'] - x
delta = xyz.total_seconds()
minutes = float(delta // 60)
z = demand_df.iloc[a]['TTJ'] - minutes
x = end + timedelta(minutes=z)
counter = a
else:
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', y.time())
x = y
a = a+1
if x > sched_df.iloc[3]['Time']:
start = sched_df.iloc[2]['Time']
end = sched_df.iloc[3]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', end.time())
xyz = x-end
delta = xyz.total_seconds()
minutes = float(delta // 60)
z = minutes
start = sched_df.iloc[3]['Time']
end = sched_df.iloc[4]['Time']
print('Lunch time from : ', start.time(), ' to ', end.time())
start = sched_df.iloc[4]['Time']
x = start + timedelta(minutes=z)
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', x.time())
z = 0
a = a + 1
else:
start = sched_df.iloc[2]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', x.time())
z = 0
a = a + 1
y = x
for n in range(0, len(demand_df)):
while y < sched_df.iloc[3]['Time']:
y = x + timedelta(minutes=demand_df.iloc[a]['TTJ'])
if y > sched_df.iloc[3]['Time']:
end = sched_df.iloc[3]['Time']
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', end.time())
start = sched_df.iloc[3]['Time']
end = sched_df.iloc[4]['Time']
print('Lunch time from : ', start.time(), ' to ', end.time())
xyz = sched_df.iloc[3]['Time'] - x
delta = xyz.total_seconds()
minutes = float(delta // 60)
z = demand_df.iloc[a]['TTJ'] - minutes
start = sched_df.iloc[4]['Time']
x = start + timedelta(minutes=z)
print(demand_df.iloc[a]['PartNo'], 'time from : ', start.time(), ' to ', x.time())
z = 0
a = a + 1
else:
print(demand_df.iloc[a]['PartNo'], 'time from : ', x.time(), ' to ', y.time())
x = y
a = a + 1
Any help will be appreciated.
I'm not sure what exactly your problem is, but if you say you are new to python programming you could read through some comparable projects.
A project that comes to my mind would be pyschedule for example. The solution approaches should be similar to those to your problem.

Python Download Script

When I run this, the Progress % is backwards, does anyone know how to make it 0% at the beginning and 100% when it completes?
import time
x = 25
y = x
t = 0
downloading = True
while downloading:
time.sleep(1)
t += 1
x -= 1
f = ((x/y) * 100)
print('Time:', str(t) + ',', 'Progress: ', '{0:.2}'.format(str(f)) + '%,', 'Remaining: ' + str(x), 'MB', end="\r")
if(x == 0):
print('\nComplete!')
break
Just use (1-x/y) instead of x/y in f.
import time
x = 25
y = x
t = 0
downloading = True
while downloading:
time.sleep(0.01)
t += 1
x -= 1
f = ((1-x/y) * 100)
print('Time:', str(t) + ',', 'Progress: ', '{0:.3}'.format(str(f)) + '%,', 'Remaining: ' + str(x), 'MB', end="\r")
if(x == 0):
print('\nComplete!')
break
Also note that you should use '{0:.3}'.format(str(f)) so that 100% can be displayed correctly.

Why is y not defined?

In this code for some reason the variable y is not defined for the first if statement only. I need to know why it says that y is not defined. Also if you need code for finding WOEID here it is.
import urllib2
def make_word(words):
result = ""
for i in words:
result += i
return result
continents = ['asia', 'north%20america', 'south%20america', 'europe', 'asia', 'australia', 'antarctica']
a = raw_input('Put in a place: ')
a = a.lower()
if ' ' in a:
for h in a:
if h == ' ':
y = a.replace(' ', '%20')
page = urllib2.urlopen('http://woeid.rosselliot.co.nz/lookup/%s' % a).read()
f = page.find('Ohio')
if y not in continents:
if f != -1:
start = page.find('woeid="', f) + 7
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
if f == -1:
f = page.find('United States')
if f != -1:
start = page.find('woeid="', f) + 7
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
if y in continents:
if f == -1:
f = page.find('')
start = page.find('woeid="', f) + 7
print page[start:]
end = page.find('"', start)
print 'The WOEID for %s: %s' % (a, page[start:end])
You only define y in very specific circumstances:
if ' ' in a:
for h in a:
if h == ' ':
y = a.replace(' ', '%20')
So only if there is a space in a do you produce y.
Don't create a new variable here, and don't URL-encode manually. Use the urllib.quote() function instead:
from urllib import quote
y = quote(a.lower())
You appear to be mixing a and y throughout your code. Perhaps you need to use more meaningful names here:
place = raw_input('Put in a place: ')
place_quoted = quote(place.lower())
page = urllib2.urlopen('http://woeid.rosselliot.co.nz/lookup/%s' % place_quoted).read()
if place_quoted not in continents:
if ' ' in a: #This conditions fails in your code and the y variable is not initialized/ set.
if y not in continents: # when this line executes, it has no reference for y, throws the error "undefined"
Better initialize a default value at the start of your code.
Eg : y = None (or) handle your variable properly.

Taylor polynomial calculation

I am currently doing a python exercise for my University studies. I am very stuck at this task:
The taylor polynomial of degree N for the exponential function e^x is given by:
N
p(x) = Sigma x^k/k!
k = 0
Make a program that (i) imports class Polynomial (found under), (ii) reads x and a series of N values from the command line, (iii) creates a Polynomial instance representing the Taylor polynomial, and (iv) prints the values of p(x) for the given N values as well as the exact value e^x. Try the program out with x = 0.5, 3, 10 and N = 2, 5, 10, 15, 25.
Polynomial.py
import numpy
class Polynomial:
def __init__(self, coefficients):
self.coeff = coefficients
def __call__(self, x):
"""Evaluate the polynomial."""
s = 0
for i in range(len(self.coeff)):
s += self.coeff[i]*x**i
return s
def __add__(self, other):
# Start with the longest list and add in the other
if len(self.coeff) > len(other.coeff):
result_coeff = self.coeff[:] # copy!
for i in range(len(other.coeff)):
result_coeff[i] += other.coeff[i]
else:
result_coeff = other.coeff[:] # copy!
for i in range(len(self.coeff)):
result_coeff[i] += self.coeff[i]
return Polynomial(result_coeff)
def __mul__(self, other):
c = self.coeff
d = other.coeff
M = len(c) - 1
N = len(d) - 1
result_coeff = numpy.zeros(M+N+1)
for i in range(0, M+1):
for j in range(0, N+1):
result_coeff[i+j] += c[i]*d[j]
return Polynomial(result_coeff)
def differentiate(self):
"""Differentiate this polynomial in-place."""
for i in range(1, len(self.coeff)):
self.coeff[i-1] = i*self.coeff[i]
del self.coeff[-1]
def derivative(self):
"""Copy this polynomial and return its derivative."""
dpdx = Polynomial(self.coeff[:]) # make a copy
dpdx.differentiate()
return dpdx
def __str__(self):
s = ''
for i in range(0, len(self.coeff)):
if self.coeff[i] != 0:
s += ' + %g*x^%d' % (self.coeff[i], i)
# Fix layout
s = s.replace('+ -', '- ')
s = s.replace('x^0', '1')
s = s.replace(' 1*', ' ')
s = s.replace('x^1 ', 'x ')
#s = s.replace('x^1', 'x') # will replace x^100 by x^00
if s[0:3] == ' + ': # remove initial +
s = s[3:]
if s[0:3] == ' - ': # fix spaces for initial -
s = '-' + s[3:]
return s
def simplestr(self):
s = ''
for i in range(0, len(self.coeff)):
s += ' + %g*x^%d' % (self.coeff[i], i)
return s
def _test():
p1 = Polynomial([1, -1])
p2 = Polynomial([0, 1, 0, 0, -6, -1])
p3 = p1 + p2
print p1, ' + ', p2, ' = ', p3
p4 = p1*p2
print p1, ' * ', p2, ' = ', p4
print 'p2(3) =', p2(3)
p5 = p2.derivative()
print 'd/dx', p2, ' = ', p5
print 'd/dx', p2,
p2.differentiate()
print ' = ', p5
p4 = p2.derivative()
print 'd/dx', p2, ' = ', p4
if __name__ == '__main__':
_test()
Now I'm really stuck at this, and I would love to get an explaination! I am supposed to write my code in a separate file. I'm thinking about making an instance of the Polynomial class, and sending in the list in argv[2:], but that doesn't seem to be working. Do I have to make a def to calculate the taylor polynomial for the different values of N before sending it in to the Polynomial class?
Any help is great, thanks in advance :)
Not quite finished, but this answers your main question I believe. Put class Polynomial in poly.p and import it.
from poly import Polynomial as p
from math import exp,factorial
def get_input(n):
''' get n numbers from stdin '''
entered = list()
for i in range(n):
print 'input number '
entered.append(raw_input())
return entered
def some_input():
return [[2,3,4],[4,3,2]]
get input from cmd line
n = 3
a = get_input(n)
b = get_input(n)
#a,b = some_input()
ap = p(a)
bp = p(b)
print 'entered : ',a,b
c = ap+bp
print 'a + b = ',c
print exp(3)
x = ap
print x
sum = p([0])
for k in range(1,5):
el = x
for j in range(1,k):
el el * x
print 'el: ',el
if el!=None and sum!=None:
sum = sum + el
print 'sum ',sum
output
entered : [2, 3, 4] [4, 3, 2]
a + b = 6*1 + 6*x + 6*x^2
20.0855369232
2*1 + 3*x + 4*x^2
sum 2*1 + 3*x + 4*x^2
el: 4*1 + 12*x + 25*x^2 + 24*x^3 + 16*x^4
sum 6*1 + 15*x + 29*x^2 + 24*x^3 + 16*x^4
el: 4*1 + 12*x + 25*x^2 + 24*x^3 + 16*x^4
el: 8*1 + 36*x + 102*x^2 + 171*x^3 + 204*x^4 + 144*x^5 + 64*x^6
sum 14*1 + 51*x + 131*x^2 + 195*x^3 + 220*x^4 + 144*x^5 + 64*x^6
el: 4*1 + 12*x + 25*x^2 + 24*x^3 + 16*x^4
el: 8*1 + 36*x + 102*x^2 + 171*x^3 + 204*x^4 + 144*x^5 + 64*x^6
el: 16*1 + 96*x + 344*x^2 + 792*x^3 + 1329*x^4 + 1584*x^5 + 1376*x^6 + 768*x^7 + 256*x^8
sum 30*1 + 147*x + 475*x^2 + 987*x^3 + 1549*x^4 + 1728*x^5 + 1440*x^6 + 768*x^7 + 256*x^8
I solved the task in the following way, though im not sure if it answers question (iv).
The output just compares the exact value of e**x to the calculated value from module Polynomial.
from math import factorial, exp
from Polynomial import *
from sys import *
#Reads x and N from the command line on the form [filename.py, x-value, N-value]
x = eval(argv[1])
N = eval(argv[2])
#Creating list of coefficients on the form [1 / i!]
list_coeff = [1./factorial(i) for i in range(N)]
print list_coeff
#Creating an instance of class Polynomial
p1 = Polynomial(list_coeff)
print 'Calculated value of e**%f = %f ' %(x, p1.__call__(x))
print 'Exact value of e**%f = %f'% (x, exp(x))
"""Test Execution
Terminal > python Polynomial_exp.py 0.5 5
[1.0, 1.0, 0.5, 0.16666666666666666, 0.041666666666666664]
Calculated value of e**0.500000 = 1.648438
Exact value of e**0.500000 = 1.648721
"""

Categories

Resources