p3 = (p9.ggplot(data = df, mapping = p9.aes(x = 'gross_power', y = 'temp_drop_a',show_legend=False, alpha = 0.7))
+ p9.geom_jitter()
+ p9.geom_smooth(se= 'F',method="lm", colour = 'red'))
mygg_data = p9.ggplot_build(p3).data[[2]]
There is no ggplot_build in plotnine and it is not needed. I assume you are trying to plot a regression line. An example is below.
Also se= 'F' will not work. If you do not want to display confidence intervals, it is se= False.
import pandas as pd
from scipy import stats
from plotnine import *
from plotnine.data import mpg as df
df = df[df['cyl']!=5]
def regline(cyl):
data = df[df['cyl']==cyl]
params = stats.linregress(data['displ'],data['hwy'])
if params[0] < 0:
return 'y = {:.4f} - {:.4f} x'.format(params[1],abs(params[0]))
else:
return 'y = {:.4f} + {:.4f} x'.format(params[1],params[0])
regline4 = regline(4)
regline6 = regline(6)
regline8 = regline(8)
p = (ggplot(df, aes(x='displ', y='hwy',color='factor(cyl)'))
+ theme_light(8)
+ geom_jitter(size=0.8, alpha=0.4)
+ geom_smooth(aes(fill='factor(cyl)'),method='lm',alpha=0.3)
+ annotate('text', label=regline4, x=2.05, y=33.5, size=7, color='#005D17', ha='left')
+ annotate('text', label=regline6, x=3.95, y=28, size=7, color='#7E191B', ha='left')
+ annotate('text', label=regline8, x=6.5, y=21.5, size=7, color='#1C2E4A')
+ labs(x='Displacement', y='Miles per gallon (highway)')
+ scale_color_manual(('#005D17','#7E191B','#1C2E4A'))
+ scale_fill_manual(('#50C878','#E78587','#89CFF0'))
+ theme(
legend_title=element_blank(),
legend_key=element_rect(color='white'),
legend_direction='horizontal',
legend_position='bottom',
legend_box_spacing=0.25,
legend_background=element_blank(),
)
)
p
Related
This question already has an answer here:
Unable to fit curves to data points using curve_fit() from scipy because of "Optimal parameters not found" error [python]
(1 answer)
Closed 6 months ago.
I want to automatically calculate a function by giving points on the graph, when I run the following script.
Titration curves are pretty similar to logistic regression, tho, they have different inclinations at the turning points. So it's not 100% the same curve. The best would be to have an output, that gives you the function, similar to this one:
y = (A) / (1 + B^{x-C}) + D
Btw. sorry for my english, it's not my native language. Please ask questions, if it is not clear.
#from https://www.geeksforgeeks.org/graph-plotting-in-python-set-1/ inspired
#YOU HAVE TO HAVE INSTALLED THE FOLLOWING LIBRARIES : matplotlib.pyplot, colorama
# [pip install matplotlib.pyplot]
# [pip install colorama]
# normally alrady installed: math, time
import matplotlib.pyplot as plt
import math
from colorama import Fore
from colorama import Style
import time
### ANALYTE in ml ###
a = input(" Enter the constant volume of the analyte in ml: ")
print(f"{Fore.GREEN}The volume of the analyte is{Style.RESET_ALL}", a, f"{Fore.GREEN}ml{Style.RESET_ALL}")
mol_a = input("Enter the molarity of the analyte: ")
print(f"{Fore.GREEN}The molarity of the analyte is{Style.RESET_ALL}", mol_a)
### TITRANT in ml ###
mol_t = input("Enter the molarity of the titrant: ")
t = float(a)*float(mol_a) / float(mol_t)-0.00001
print(f"{Fore.GREEN}The molarity of the titrant is{Style.RESET_ALL}", mol_t)
# wait 1/2 a sec
print("calculating...")
time.sleep(.5)
print(f"{Fore.GREEN}The volume of the titrant under the equivalence point is{Style.RESET_ALL}",t, f"{Fore.GREEN}ml{Style.RESET_ALL}")
#Volumeof titrant in ml:
t0= 0.00001
t1= math.trunc(float(t)*10000)/10000
t2= float(t)*0.9999
t3= float(t)*0.999
t4= float(t)*0.99
t5= float(t)*0.97
t6= float(t)*0.9
t7= float(t)*0.7
t8= float(t)*0.5
t9= float(t)*0.3
t10= float(t)*0.1
t11= (float(t1))*1.0001
t12= (float(t1))*1.001
t13= (float(t1))*1.01
t14= (float(t1))*1.03
t15= (float(t1))*1.1
t16= (float(t1))*1.3
t17= (float(t1))*1.5
t18= (float(t1))*1.7
t19= (float(t1))*1.9
t20= (float(t1))*2
# mol of Analyte and Titrant:
anzahl_mol_von_starker_analyt = float(a)* 10**(-3)*float(mol_a)
#M = z.B. 0.005 mol
anzahl_mol_von_starker_titrant = float(t)*10**(-3)*float(mol_t)
#pH at this ratio:
berechne_pH_t0 = (-1)*math.log10( (float(anzahl_mol_von_starker_analyt) - float(float(t0)*10**(-3)*float(mol_t))) / (float(t0)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_t1 = ( 7)
berechne_pH_unter_t2 = (-1)*math.log10( (float(anzahl_mol_von_starker_analyt) - float(float(t2)*10**(-3)*float(mol_t))) / (float(t2)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_unter_t3 = (-1)*math.log10( (float(anzahl_mol_von_starker_analyt) - float(float(t3)*10**(-3)*float(mol_t))) / (float(t3)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_unter_t4 = (-1)*math.log10( (float(anzahl_mol_von_starker_analyt) - float(float(t4)*10**(-3)*float(mol_t))) / (float(t4)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_unter_t5 = (-1)*math.log10( (float(anzahl_mol_von_starker_analyt) - float(float(t5)*10**(-3)*float(mol_t))) / (float(t5)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_unter_t6 = (-1)*math.log10( (float(anzahl_mol_von_starker_analyt) - float(float(t6)*10**(-3)*float(mol_t))) / (float(t6)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_unter_t7 = (-1)*math.log10( (float(anzahl_mol_von_starker_analyt) - float(float(t7)*10**(-3)*float(mol_t))) / (float(t7)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_unter_t8 = (-1)*math.log10( (float(anzahl_mol_von_starker_analyt) - float(float(t8)*10**(-3)*float(mol_t))) / (float(t8)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_unter_t9 = (-1)*math.log10( (float(anzahl_mol_von_starker_analyt) - float(float(t9)*10**(-3)*float(mol_t))) / (float(t9)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_unter_t10 = (-1)*math.log10( (float(anzahl_mol_von_starker_analyt) - float(float(t10)*10**(-3)*float(mol_t))) / (float(t10)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_ueber_t11 = 14-(-1)*math.log10( (float(float(t11)*10**(-3)*float(mol_t) - (float(anzahl_mol_von_starker_analyt)))) / (float(t11)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_ueber_t12 = 14-(-1)*math.log10( (float(float(t12)*10**(-3)*float(mol_t) - (float(anzahl_mol_von_starker_analyt)))) / (float(t12)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_ueber_t13 = 14-(-1)*math.log10( (float(float(t13)*10**(-3)*float(mol_t) - (float(anzahl_mol_von_starker_analyt)))) / (float(t13)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_ueber_t14 = 14-(-1)*math.log10( (float(float(t14)*10**(-3)*float(mol_t) - (float(anzahl_mol_von_starker_analyt)))) / (float(t14)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_ueber_t15 = 14-(-1)*math.log10( (float(float(t15)*10**(-3)*float(mol_t) - (float(anzahl_mol_von_starker_analyt)))) / (float(t15)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_ueber_t16 = 14-(-1)*math.log10( (float(float(t16)*10**(-3)*float(mol_t) - (float(anzahl_mol_von_starker_analyt)))) / (float(t16)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_ueber_t17 = 14-(-1)*math.log10( (float(float(t17)*10**(-3)*float(mol_t) - (float(anzahl_mol_von_starker_analyt)))) / (float(t17)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_ueber_t18 = 14-(-1)*math.log10( (float(float(t18)*10**(-3)*float(mol_t) - (float(anzahl_mol_von_starker_analyt)))) / (float(t18)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_ueber_t19 = 14-(-1)*math.log10( (float(float(t19)*10**(-3)*float(mol_t) - (float(anzahl_mol_von_starker_analyt)))) / (float(t19)*10**(-3) + float(a)*10**(-3) ) )
berechne_pH_ueber_t20 = 14-(-1)*math.log10( (float(float(t20)*10**(-3)*float(mol_t) - (float(anzahl_mol_von_starker_analyt)))) / (float(t20)*10**(-3) + float(a)*10**(-3) ) )
# X-axis: Volume of Titrant in ml:
x = [float(t0),float(t1),float(t2),float(t3),float(t4),float(t5),float(t6),float(t7),float(t8),float(t9),float(t10),float(t11),float(t12),float(t13),float(t14),float(t15),float(t16),float(t17),float(t18),float(t19),float(t20)]
# Y-axis: pH-value at this ratio:
y = [berechne_pH_t0,berechne_pH_t1,berechne_pH_unter_t2,berechne_pH_unter_t3,berechne_pH_unter_t4,berechne_pH_unter_t5,berechne_pH_unter_t6,berechne_pH_unter_t7,berechne_pH_unter_t8,berechne_pH_unter_t9,berechne_pH_unter_t10,berechne_pH_ueber_t11,berechne_pH_ueber_t12,berechne_pH_ueber_t13,berechne_pH_ueber_t14,berechne_pH_ueber_t15,berechne_pH_ueber_t16,berechne_pH_ueber_t17,berechne_pH_ueber_t18,berechne_pH_ueber_t19,berechne_pH_ueber_t20 ]
# Hiermit werden die Punkte in das Koordinatensystem geplottet:
plt.scatter(x, y, label= "values", color= "green",
marker= "o", s=30)
# X-axis; title:
plt.xlabel('Volume of titrant in ml')
# Y-axis; title:
plt.ylabel('pH-value at this ratio')
# Title of graph:
plt.title('Titration curve, strong acid, strong base')
# show legend
plt.legend()
# show plot
plt.show()
In order to fit the parameters of a parametric function to data, you can use scipy.optimize.curve_fit:
def my_function(x, A, B, C, D, E):
return A/(1 + B**(x - C)) + D + E*x
parameters, covariance = curve_fit(f = my_function, xdata = x, ydata = y)
If necessary, you can improve the results by passing some bounds for the parameters:
parameters, covariance = curve_fit(f = my_function, xdata = x, ydata = y, bounds = ([0, 0, 0.9*t, -10, -10], [14, 1, 1.1*t, 10, 10]))
Complete Code
# IMPORT
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# INPUT VALUES
a = 100
mol_a = 10
mol_t = 5
# DATA GENERATION
N = 40
t = a*mol_a/mol_t
x1 = np.linspace(0, t - 1e-6, N//2)
x2 = np.linspace(t + 1e-6, 2*t, N//2)
anzahl_mol_von_starker_analyt = a*10**(-3)*mol_a
anzahl_mol_von_starker_titrant = t*10**(-3)*mol_t
y1 = (-1)*np.log10((anzahl_mol_von_starker_analyt - x1*10**(-3)*mol_t)/(x1*10**(-3) + a*10**(-3)))
y2 = 14 - (-1)*np.log10((x2*10**(-3)*mol_t - anzahl_mol_von_starker_analyt)/(x2*10**(-3) + a*10**(-3)))
x = np.concatenate((x1, x2))
y = np.concatenate((y1, y2))
# PARAMETERS FITTING
def my_function(x, A, B, C, D, E):
return A/(1 + B**(x - C)) + D + E*x
parameters, covariance = curve_fit(f = my_function, xdata = x, ydata = y, bounds = ([0, 0, 0.9*t, -10, -10], [14, 1, 1.1*t, 10, 10]))
for parameter, name in zip(parameters, ['A', 'B', 'C', 'D', 'E']):
print(f'{name} = {parameter:14.10f}')
x_fitted = np.linspace(x[0], x[-1], 1000)
y_fitted = my_function(x_fitted, *parameters)
# PLOT
plt.style.use('seaborn-darkgrid')
fig, ax = plt.subplots()
ax.plot(x, y, label = 'data', marker = 'o', linestyle = '')
ax.plot(x_fitted, y_fitted, label = 'fitted curve')
ax.set_xlabel('Volume of titrant in ml')
ax.set_ylabel('pH-value at this ratio')
ax.set_title('Titration curve, strong acid, strong base')
ax.legend(frameon = True)
plt.show()
Result
A = 13.2787117583
B = 0.7311691018
C = 199.8189983959
D = -0.8940392051
E = 0.0054250609
PLOT
I've got a set of points (coordinates X and Y) generated by a mathematical expression and I want to draw the resulting figure in a specific position of the screen (I'd like to determine the position in which to center the drawn figure).
I tried using the following code to test if the formula resulted in the correct figure. But now I need to draw the same contour on a pre-existing image at a specific position.
B = 185
L = 250
W = (L-B)/6
D = (L/2)-L/4
x = np.linspace(-L/2, L/2, 500)
y1 = []
y2 = []
for X in x:
termo1 = sqrt((L**2 - 4*X**2) / (L**2 + 8*W*X + 4*W**2))
termo2 = ((sqrt(5.5*L**2 + 11*L*W + 4*W**2) * (sqrt(3)*B*B - 2*D*sqrt(L**2 + 2*W*L + 4*W**2))
) / (sqrt(3)*B*L*(sqrt(5.5*L**2 + 11*L*W + 4*W**2) - 2*sqrt(L**2 + 2*W*L + 4*W**2))))
termo3 = 1 - sqrt((L*(L**2 + 8*W*X + 4*W**2)) / (2*(L - 2*W)*X**2 +
(L**2 + 8*L*W - 4*W**2)*X + 2*L*W**2 + L**2*W + L**2*W + L**3))
calculo = B/2 * termo1 * (1-termo2 * termo3)
y1.append(calculo)
calculo = -B/2 * termo1 * (1-termo2 * termo3)
y2.append(calculo)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
plt.plot(x, y1, 'r')
plt.plot(x, y2, 'r')
plt.show()
You can do this by creating an onclick event; it will take the mouse cords when click and use them as an offset...I think that's what you are asking for? Though with the current plot x/y limits, it won't show up depending on where you click so I added those in the configuration of the plot.
import numpy as np
from math import sqrt
import matplotlib.pyplot as plt
import os
import matplotlib.image as mpimg
def onclick(event):
global ix, iy
ix, iy = event.xdata, event.ydata
plt.plot(x + ix, y1+ iy, 'r')
plt.plot(x + ix, y2+ iy, 'r')
plt.show()
fig.canvas.mpl_disconnect(cid)
return
B = 185
L = 250
W = (L-B)/6
D = (L/2)-L/4
x = np.linspace(-L/2, L/2, 500)
y1 = []
y2 = []
for X in x:
termo1 = sqrt((L**2 - 4*X**2) / (L**2 + 8*W*X + 4*W**2))
termo2 = ((sqrt(5.5*L**2 + 11*L*W + 4*W**2) * (sqrt(3)*B*B - 2*D*sqrt(L**2 + 2*W*L + 4*W**2))
) / (sqrt(3)*B*L*(sqrt(5.5*L**2 + 11*L*W + 4*W**2) - 2*sqrt(L**2 + 2*W*L + 4*W**2))))
termo3 = 1 - sqrt((L*(L**2 + 8*W*X + 4*W**2)) / (2*(L - 2*W)*X**2 +
(L**2 + 8*L*W - 4*W**2)*X + 2*L*W**2 + L**2*W + L**2*W + L**3))
calculo = B/2 * termo1 * (1-termo2 * termo3)
y1.append(calculo)
calculo = -B/2 * termo1 * (1-termo2 * termo3)
y2.append(calculo)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xlim([-500,500])
ax.set_ylim([-500,500])
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
coords = []
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
I wrote this about a year ago in python 2.x. I have since switched over to 3.x, and I am not getting any errors, but as mentioned above, only one plot is being outputted, the first stdev one. If I use #%% in Spyder to make the code under ...##mean plot##... into its own cell and run the cell, it will make that plot. If I switch the order of the mean and stdev code, then it will just make the one that comes first. I have many similar scripts and they all are having the same issue.
Is it the indentation? I've played around with it to no avail.
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 28 09:16:29 2017
#author: kmiranda
"""
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.basemap as bm
##from ens_function import ens_data, grd_data
from scipy.io import netcdf
for date in np.arange(3,16):
mem=0o01
DTG = '201501%2.2d00' % (date)
nfdir='/u/prob/coupled/rowley/pertobs/kmiranda/scratch/gom/ensemble/post'
ncfn=nfdir + '/ncom_relo_gom_' + DTG + '.%3.3d'%mem + '.nc'
nc1 = netcdf.netcdf_file(ncfn, 'r')
lat = nc1.variables['lat'][:]
lon = nc1.variables['lon'][:]
dep = nc1.variables['depth'][:]
tau = nc1.variables['tau'][:] ## added this. it's probably not right
water_temp = nc1.variables['water_temp']
t0 = np.squeeze(water_temp[1,:,:,:])*1. ##I changed the 0 to 1 here
t0[np.where(t0 == -30000)]=np.nan
bbox=[262.,281.,18.,31.]
ma = bm.Basemap(projection='merc',llcrnrlat=bbox[2],urcrnrlat=bbox[3], \
llcrnrlon=bbox[0],urcrnrlon=bbox[1],lat_ts=0,resolution='i')
s1 = np.zeros(t0.shape)
s2 = np.zeros(t0.shape)
#del lat, lon, dep, water_temp, t0
#nc1.close()
for i in np.arange(1,33):
DTG = '201501%2.2d00' % (date)
nfdir='/u/prob/coupled/rowley/pertobs/kmiranda/scratch/gom/ensemble/post'
ncfn=nfdir + '/ncom_relo_gom_' + DTG + '.%3.3d' %i + '.nc'
nc1 = netcdf.netcdf_file(ncfn, 'r')
water_temp = nc1.variables['water_temp']
t0 = np.squeeze(water_temp[1,:,:,:])*1. ##I changed the 0 to 1 here
t0[np.where(t0 == -30000)]=np.nan
temp = np.ma.masked_invalid(np.squeeze(t0)*water_temp.scale_factor + water_temp.add_offset)
temp.min()
n = i
s1 = s1 + np.power(temp,2)
s2 = s2 + temp
s2.min()
for k in np.arange(0,21,20):
std = np.sqrt((((n * s1)-(np.power(s2,2)))/(n**2)))
mean = s2/n
mean = np.squeeze(mean[k, :, :])
std = np.squeeze(std[k, :, :])
################ stdev plot ####################
x, y = np.meshgrid(lon, lat)
p1 = ma.pcolormesh(x, y, std, shading = 'flat', \
cmap = plt.cm.jet, latlon = True, vmin=0, vmax=0.8)
c = ma.colorbar()
#degree = u'\xb0'
#c.set_label("C%s" % (degree))
#m.colorbar(p1)
ma.drawcoastlines()
ma.fillcontinents(color='#EDE0BE')
ma.drawparallels(np.arange(20., 30., 5.))
ma.drawmeridians(np.arange(270., 280., 5.))
ma.drawcoastlines(linewidth=0.25)
ma.drawcountries(linewidth=0.25)
plt.title('Std Temperature %s %dm' % (DTG, dep[k]))
fig_name =nfdir + '/temp_std_z%06.1f' % dep[k] + '_ncom_relo_gom_' + DTG + '.%3.3d' % int(tau[1]) + '.png'
plt.savefig(fig_name , dpi=200)
plt.show()
plt.clf()
########### mean plot ###################
if k == 0:
vmin =10
vmax = 30
else:
vmin = 10
vmax = 28
p2 = ma.pcolormesh(x, y, mean, shading = 'flat', \
cmap=plt.cm.jet, latlon= True, vmin=vmin, vmax=vmax)
c2 = plt.colorbar()
degree = u'\xb0'
c2.set_label("C%s" % (degree))
ma.drawcoastlines()
ma.fillcontinents(color='#EDE0BE')
ma.drawparallels(np.arange(20., 30., 5.))
ma.drawmeridians(np.arange(270., 280., 5.))
ma.drawcoastlines(linewidth=0.25)
ma.drawcountries(linewidth=0.25)
plt.title('Mean Temperature %s %dm' % (DTG, dep[k]))
fig_name =nfdir + '/temp_avg_z%06.1f' % dep[k] + '_ncom_relo_gom_' + DTG + '.%3.3d' % int(tau[1]) + '.png'
plt.savefig(fig_name , dpi=200)
plt.show()
plt.clf()
I work with Pepper robot for navigation with Python.
How can I get the value of distance between the robot and the obstacle in different directions: Front, Left, Right and rear?
I haven't worked with Pepper for a long time but here's a gist of what I did when experimenting with the lasers.
As far as I remember, the code made the robot rotate on itself, registering the distances from the front, left and right laser sets.
Note that this is probably for an older API.
I'll dig through the docs a bit more, but this might help you!
I've updated the gist with a different version which shows how to enable the lasers using DCM, but it reads only the front values.
Check this for the previous code (older revision of the gist), which reads each direction.
As requested, here's the code for the newest gist.
import qi
import time
import sys
import almath
from matplotlib import pyplot as plt
import math
import random
# robotIP = "150.145.115.50"
robotIP = "194.119.214.251"
port = 9559
session = qi.Session()
print ("Connecting to " + robotIP + ":" + str(port))
session.connect("tcp://" + robotIP + ":" + str(port))
memoryProxy = session.service("ALMemory")
motion_service = session.service("ALMotion")
dcm_service = session.service("DCM")
t = dcm_service.getTime(0)
dcm_service.set(["Device/SubDeviceList/Platform/LaserSensor/Front/Reg/OperationMode/Actuator/Value", "Merge", [[1.0, t]]])
dcm_service.set(["Device/SubDeviceList/Platform/LaserSensor/Right/Reg/OperationMode/Actuator/Value", "Merge", [[1.0, t]]])
dcm_service.set(["Device/SubDeviceList/Platform/LaserSensor/Left/Reg/OperationMode/Actuator/Value", "Merge", [[1.0, t]]])
motion_service.setExternalCollisionProtectionEnabled("All", True)
memoryProxy = session.service("ALMemory")
theta0 = motion_service.getRobotPosition(False)[2]
data = []
speed = 0.5
print theta0
motion_service.moveToward(0.0,0.0,speed)
try:
while memoryProxy.getData("MONITOR_RUN")>0:
theta = motion_service.getRobotPosition(False)[2] -theta0 + 1.57
for i in range(0,15):
if i+1<10:
stringIndex = "0" + str(i+1)
else:
stringIndex = str(i+1)
y_value = memoryProxy.getData("Device/SubDeviceList/Platform/LaserSensor/Front/Horizontal/Seg"+stringIndex+"/X/Sensor/Value")# - 0.0562
x_value = -memoryProxy.getData("Device/SubDeviceList/Platform/LaserSensor/Front/Horizontal/Seg"+stringIndex+"/Y/Sensor/Value")
data.append((theta+(0.523599-i*0.0698132),math.sqrt(x_value*x_value + y_value*y_value)))
except KeyboardInterrupt:
print "Stopped"
motion_service.stopMove()
plt.figure(0)
plt.subplot(111, projection='polar')
data2 = sorted(data)
thetas = []
distances = []
for x in data2:
thetas.append(x[0])
distances.append(x[1])
print len(thetas)
plt.plot(thetas,distances)
plt.show()
And here's the older gist:
import qi
import time
import sys
import almath
from matplotlib import pyplot as plt
import math
# robotIP = "150.145.115.50"
robotIP = "194.119.214.252"
port = 9559
session = qi.Session()
print ("Connecting to " + robotIP + ":" + str(port))
session.connect("tcp://" + robotIP + ":" + str(port))
print ("Connected, starting the test")
memoryProxy = session.service("ALMemory")
motion_service = session.service("ALMotion")
distances = []
front_values = [[],[]]
for i in range(1,16):
# print "Processing front segment ",i
if i<10:
stringIndex = "0" + str(i)
else:
stringIndex = str(i)
y_value = memoryProxy.getData("Device/SubDeviceList/Platform/LaserSensor/Front/Horizontal/Seg"+stringIndex+"/X/Sensor/Value")# - 0.0562
x_value = -memoryProxy.getData("Device/SubDeviceList/Platform/LaserSensor/Front/Horizontal/Seg"+stringIndex+"/Y/Sensor/Value")
# point = [x_value,y_value]
front_values[0].append(x_value)
front_values[1].append(y_value)
left_values = [[],[]]
for i in range(1,16):
# print "Processing front segment ",i
if i<10:
stringIndex = "0" + str(i)
else:
stringIndex = str(i)
y_value = memoryProxy.getData("Device/SubDeviceList/Platform/LaserSensor/Left/Horizontal/Seg"+stringIndex+"/X/Sensor/Value") #- 0.0899
x_value = -memoryProxy.getData("Device/SubDeviceList/Platform/LaserSensor/Left/Horizontal/Seg"+stringIndex+"/Y/Sensor/Value")
# point = [x_value,y_value]
left_values[0].append(-y_value)
left_values[1].append(x_value)
right_values = [[],[]]
for i in range(1,16):
# print "Processing front segment ",i
if i<10:
stringIndex = "0" + str(i)
else:
stringIndex = str(i)
y_value = memoryProxy.getData("Device/SubDeviceList/Platform/LaserSensor/Right/Horizontal/Seg"+stringIndex+"/X/Sensor/Value") #- 0.0899
x_value = -memoryProxy.getData("Device/SubDeviceList/Platform/LaserSensor/Right/Horizontal/Seg"+stringIndex+"/Y/Sensor/Value")
# point = [x_value,y_value]
right_values[0].append(y_value)
right_values[1].append(-x_value)
# for x in left_values[1]:
# x = -x
# for x in right_values[0]:
# x = -x
plt.figure(0)
plt.plot(left_values[0],left_values[1],color="red")
# plt.figure(1)
plt.plot(front_values[0],front_values[1],color="black")
# plt.figure(2)
plt.plot(right_values[0],right_values[1],color="blue")
# plt.figure(1)
# plt.plot(left_values[0],left_values[1],color="red")
# plt.figure(2)
# plt.plot(front_values[0],front_values[1],color="black")
# plt.figure(3)
# plt.plot(right_values[0],right_values[1],color="blue")
df = [0 for i in front_values[0]]
dr = [0 for i in right_values[0]]
dl = [0 for i in left_values[0]]
for i in range(len(front_values[0])):
# print "Processing ", i
df[i] = front_values[0][i]*front_values[0][i] + front_values[1][i]*front_values[1][i]
dr[i] = right_values[0][i]*right_values[0][i] + right_values[1][i]*right_values[1][i]
dl[i] = left_values[0][i]*left_values[0][i] + left_values[1][i]*left_values[1][i]
distances = df+dr+dl
maxTotal = max(distances)
index = distances.index(maxTotal)
maxDistance = math.sqrt(maxTotal)
x_s = front_values[0] + right_values[0] + left_values[0]
y_s = front_values[1] + right_values[1] + left_values[1]
max_x = x_s[index]
max_y = y_s[index]
plt.scatter(max_x,max_y,color="green")
print index
plt.show()
theta = math.atan(max_y/max_x)
motion_service.moveTo(0.0, 0.0, -theta)
This is a coupon collector code to analyze the running time. I need some suggestions on how to improve the running times of this code? I have used the data structure dictionary but is there any other data structure that will perform faster.
import random
import numpy as np
import matplotlib.pyplot as plt
from array import *
import timeit
trailList = {}
def couponcollector(n):
numDic = {}
trails = 0
while len(numDic) < n:
num = np.random.random_integers(n);
trails = trails + 1
if num not in numDic.keys():
numDic[num] = 1
return trails
def starter(n,m):
summ = 0
for i in range(0,m):
r = couponcollector(n)
summ = summ + r
if trailList.has_key(r):
trailList[r] = trailList[r] + 1
else:
trailList[r] = 1
print trailList
#print "Expected Trails"
#print summ/300
nvalues= []
runtimes = []
runtimes1 = []
runtimes2 = []
runtimes3 = []
runtimes4 = []
#color = {300: 'blue', 1000: 'green', 5000: 'red', 10000: 'black'}
def runtimer():
for n in range(300,20000,4000):
nvalues.append(n)
#stmt = 'starter(' + str(n)+','+str(300) + ')'
#stmt1 = 'starter(' + str(n)+','+str(800) + ')'
stmt2 = 'starter(' + str(n)+','+str(1000) + ')'
stmt3 = 'starter(' + str(n)+','+str(3000) + ')'
stmt4= 'starter(' + str(n)+','+str(5000) + ')'
print(nvalues)
#runtimes.append(timeit.timeit(stmt, setup="from __main__ import starter", number = 1))
#runtimes1.append(timeit.timeit(stmt1, setup="from __main__ import starter", number = 1))
runtimes2.append(timeit.timeit(stmt2, setup="from __main__ import starter", number = 1))
print runtimes2
runtimes3.append(timeit.timeit(stmt3, setup="from __main__ import starter", number = 1))
runtimes4.append(timeit.timeit(stmt4, setup="from __main__ import starter", number = 1))
fig = plt.figure()
#plt.plot(nvalues, runtimes, c='blue', label='m = 300')
#plt.plot(nvalues, runtimes1, c='green', label='m = 800')
plt.plot(nvalues, runtimes2, c='red', label='m = 1000')
plt.plot(nvalues, runtimes3, c='blue', label='m = 3000')
plt.plot(nvalues, runtimes4, c='green', label='m = 5000')
plt.ylabel('Runtimes')
plt.xlabel('Coupon Collector Domain Size')
plt.title('Plot of Coupon Collector runtimes')
plt.legend(loc='upper left')
plt.grid(True)
fig.savefig('ccFinal.png')
runtimer()