Matplotlib Concentration plot can not show up [Python 2.7 (with Eclipse) ] - python-2.7

I would like to ask for help.
Please for help me with my code in Python 2.7. I want plotting concentration of gas release.
Two weeks ago I started with Python, I did not see it before, I have basic knowledge with Pascal, but it is different language.
I do not know why does not work...
This picture showing how it must look like:
flickr.com/photos/95370861#N02/8696658905/in/photostream/lightbox/
My code:
from __future__ import division
from matplotlib.patches import Polygon, Rectangle
import math
import numpy as np
import matplotlib.pyplot as plt
def draw(x, y,ax, color, lw=1):
xr, yr = np.copy(x)[::-1], np.copy(y)[::-1]
for i in range(len(y)):
y[i] = -y[i]
verts = zip(x.tolist() + xr.tolist(), y.tolist() + yr.tolist())
poly = Polygon(verts, facecolor=color, edgecolor='k', lw=lw)
ax.add_patch(poly)
def concentration_chart_plume(x,y, ax, ticks, colors, title):
maxX = 0
for tick, color in zip(ticks[::-1], colors):
x, y = calculation(tick)
draw(np.array(x), np.array(y), ax, color)
maxX = max([maxX] + x)
''' plot parameters '''
plt.xlim(0, maxX)
plt.axis('equal')
plt.xlabel('$x[m]$')
plt.ylabel('$y[m]$')
plt.title(title)
sqrs = [Rectangle((0, 0), 1, 1, fc=clr) for clr in colors[::-1]]
desc = ["> %g" % tick for tick in ticks]
plt.legend(sqrs, desc, title="Concentration $kg/m^3$")
plt.grid()
def calculation(tick,m):
cx = FILE_1
sy = FILE_2
x = FILE_3
y = [sy * np.sqrt(2 * np.log(cx / (tick)))] #I do not know, how can be limited to non-zero values
return (x, y)
if __name__ == "__main__":
''' Concentration plot of continuous gas release '''
title = u"conturs"
colors = ["#9EFF00", "#FFF500", "#FF9900", "#FF2E00"]
ticks = [0.1, 1e-2, 1e-3, 1e-4] # value of concentration kg/m3, I want to show up
fig = plt.figure()
ax = fig.gca()
plt.show()
FILE_1 values:
[ 2.21000000e+00 2.19000000e+00 2.16000000e+00 2.12000000e+00
2.08000000e+00 1.90000000e+00 1.71000000e+00 1.18000000e+00
7.93000000e-01 3.55000000e-01 1.93000000e-01 7.02500000e-02
3.70800000e-02 1.37100000e-02 7.42100000e-03 4.77800000e-03
3.39200000e-03 2.56200000e-03 2.02100000e-03 1.64600000e-03
1.37300000e-03 1.16800000e-03 1.00900000e-03 8.82300000e-04
7.80300000e-04 6.96400000e-04 6.26500000e-04 5.67500000e-04
5.17200000e-04 4.73800000e-04 4.36200000e-04 4.03200000e-04
3.74200000e-04 3.48500000e-04 3.25600000e-04 3.05100000e-04
2.86700000e-04 2.70000000e-04 2.54900000e-04 2.28500000e-04
2.17000000e-04 1.96700000e-04 1.87700000e-04 1.71600000e-04
1.64300000e-04 1.51300000e-04 1.45500000e-04 1.34800000e-04
1.29900000e-04 1.21100000e-04 1.17000000e-04 1.09500000e-04
1.06000000e-04 9.96600000e-05 9.67000000e-05 9.12100000e-05
8.86500000e-05 8.38800000e-05 8.16600000e-05 7.74900000e-05
7.55300000e-05 7.18600000e-05 7.01300000e-05 6.68800000e-05
6.53500000e-05 6.38700000e-05 6.24500000e-05 6.10800000e-05
5.97600000e-05 5.84800000e-05 5.72600000e-05 5.60700000e-05
5.49200000e-05 5.38100000e-05 5.27400000e-05 5.17100000e-05
5.07000000e-05 4.97300000e-05 4.92400000e-05 4.72200000e-05
4.35700000e-05 4.19100000e-05 3.88600000e-05 3.74700000e-05
3.49000000e-05 3.37200000e-05 3.15400000e-05 3.05300000e-05
2.86500000e-05 2.77800000e-05 2.61500000e-05 2.54000000e-05
2.39800000e-05 2.33200000e-05 2.20700000e-05 2.14900000e-05
2.03900000e-05 1.98700000e-05 1.89000000e-05 1.84300000e-05
1.75600000e-05 1.71500000e-05 1.63700000e-05 1.60000000e-05
1.53000000e-05 1.49700000e-05 1.43300000e-05 1.40300000e-05
1.34600000e-05 1.31800000e-05 1.26600000e-05 1.24100000e-05
1.19400000e-05 1.17100000e-05 1.12700000e-05 1.10600000e-05
1.06600000e-05 1.04700000e-05 1.01000000e-05 9.92500000e-06
9.58500000e-06 9.42200000e-06 9.10900000e-06 8.81100000e-06]
and FILE_2 values:
[ 9.21500000e-07 1.68000000e-01 3.13000000e-01 4.47000000e-01
5.58000000e-01 8.37000000e-01 1.08000000e+00 1.67000000e+00
2.20000000e+00 3.31000000e+00 4.30000000e+00 6.53000000e+00
8.50000000e+00 1.29000000e+01 1.68000000e+01 2.03000000e+01
2.37000000e+01 2.68000000e+01 2.98000000e+01 3.27000000e+01
3.55000000e+01 3.82000000e+01 4.08000000e+01 4.34000000e+01
4.59000000e+01 4.83000000e+01 5.07000000e+01 5.31000000e+01
5.54000000e+01 5.77000000e+01 5.99000000e+01 6.21000000e+01
6.43000000e+01 6.65000000e+01 6.86000000e+01 7.07000000e+01
7.28000000e+01 7.49000000e+01 7.69000000e+01 8.09000000e+01
8.29000000e+01 8.68000000e+01 8.87000000e+01 9.25000000e+01
9.44000000e+01 9.81000000e+01 9.99000000e+01 1.04000000e+02
1.05000000e+02 1.09000000e+02 1.11000000e+02 1.14000000e+02
1.16000000e+02 1.19000000e+02 1.21000000e+02 1.24000000e+02
1.26000000e+02 1.29000000e+02 1.31000000e+02 1.34000000e+02
1.36000000e+02 1.39000000e+02 1.41000000e+02 1.44000000e+02
1.46000000e+02 1.47000000e+02 1.49000000e+02 1.50000000e+02
1.52000000e+02 1.53000000e+02 1.55000000e+02 1.57000000e+02
1.58000000e+02 1.60000000e+02 1.61000000e+02 1.63000000e+02
1.64000000e+02 1.66000000e+02 1.66000000e+02 1.69000000e+02
1.73000000e+02 1.75000000e+02 1.80000000e+02 1.82000000e+02
1.87000000e+02 1.89000000e+02 1.93000000e+02 1.96000000e+02
2.00000000e+02 2.02000000e+02 2.07000000e+02 2.09000000e+02
2.13000000e+02 2.15000000e+02 2.20000000e+02 2.22000000e+02
2.26000000e+02 2.28000000e+02 2.33000000e+02 2.35000000e+02
2.39000000e+02 2.41000000e+02 2.46000000e+02 2.48000000e+02
2.52000000e+02 2.54000000e+02 2.59000000e+02 2.61000000e+02
2.65000000e+02 2.67000000e+02 2.72000000e+02 2.74000000e+02
2.78000000e+02 2.80000000e+02 2.84000000e+02 2.86000000e+02
2.91000000e+02 2.93000000e+02 2.97000000e+02 2.99000000e+02
3.03000000e+02 3.06000000e+02 3.10000000e+02 3.14000000e+02]
and FILE_3 values:
[ 2.59000000e+00 2.69000000e+00 2.92000000e+00 3.23000000e+00
3.54000000e+00 4.48000000e+00 5.41000000e+00 8.00000000e+00
1.06000000e+01 1.66000000e+01 2.27000000e+01 3.82000000e+01
5.37000000e+01 9.37000000e+01 1.34000000e+02 1.74000000e+02
2.14000000e+02 2.54000000e+02 2.94000000e+02 3.34000000e+02
3.74000000e+02 4.14000000e+02 4.54000000e+02 4.94000000e+02
5.34000000e+02 5.74000000e+02 6.14000000e+02 6.54000000e+02
6.94000000e+02 7.34000000e+02 7.74000000e+02 8.14000000e+02
8.54000000e+02 8.94000000e+02 9.34000000e+02 9.74000000e+02
1.01400000e+03 1.05400000e+03 1.09400000e+03 1.17400000e+03
1.21400000e+03 1.29400000e+03 1.33400000e+03 1.41400000e+03
1.45400000e+03 1.53400000e+03 1.57400000e+03 1.65400000e+03
1.69400000e+03 1.77400000e+03 1.81400000e+03 1.89400000e+03
1.93400000e+03 2.01400000e+03 2.05400000e+03 2.13400000e+03
2.17400000e+03 2.25400000e+03 2.29400000e+03 2.37400000e+03
2.41400000e+03 2.49400000e+03 2.53400000e+03 2.61400000e+03
2.65400000e+03 2.69400000e+03 2.73400000e+03 2.77400000e+03
2.81400000e+03 2.85400000e+03 2.89400000e+03 2.93400000e+03
2.97400000e+03 3.01400000e+03 3.05400000e+03 3.09400000e+03
3.13400000e+03 3.17400000e+03 3.19500000e+03 3.25500000e+03
3.37500000e+03 3.43500000e+03 3.55500000e+03 3.61500000e+03
3.73500000e+03 3.79500000e+03 3.91500000e+03 3.97500000e+03
4.09500000e+03 4.15500000e+03 4.27500000e+03 4.33500000e+03
4.45500000e+03 4.51500000e+03 4.63500000e+03 4.69500000e+03
4.81500000e+03 4.87500000e+03 4.99500000e+03 5.05500000e+03
5.17500000e+03 5.23500000e+03 5.35500000e+03 5.41500000e+03
5.53500000e+03 5.59500000e+03 5.71500000e+03 5.77500000e+03
5.89500000e+03 5.95500000e+03 6.07500000e+03 6.13500000e+03
6.25500000e+03 6.31500000e+03 6.43500000e+03 6.49500000e+03
6.61500000e+03 6.67500000e+03 6.79500000e+03 6.85500000e+03
6.97500000e+03 7.03500000e+03 7.15500000e+03 7.27500000e+03]
Thank you for your help
Prema

Step 1: Make sure you can actually see a simple plot.
You need to set up python so that the following script shows you something:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,2*np.pi)
y = np.sin(x)
plt.plot(x,y)
plt.show()
If this doesn't work, it's no surprise that you're not seeing anything with your more complicated plot. Getting this working depends on the details of your system, but a good place to start is by figuring out which backend you want to use.
For interactive use, most people who need to interact with plots frequently will just use ipython with pylab, started from the command line as
ipython --pylab
You may need to install ipython and pylab to get this working.
Step 1b: Save output figure?
Alternatively, if the interactive plot isn't working for you, or you just want to save the figure to a file, you can replace plt.show() with
plt.savefig('/path/to/file.png')
You can replace png with pdf or various other file types.
Step 2: Get your code working.
The code you've posted contains several errors, and no request to draw a plot. Here are some corrections I see. Your function definitions have too many variables; they should be
def concentration_chart_plume(ax, ticks, colors, title):
and
def calculation(tick):
Your equation should be something like
y = np.asarray(sy) * np.sqrt(2 * np.log(np.asarray(cx) / (tick)))
Python doesn't know how to multiply lists together, so you have to make them into numpy arrays. Also, you should insert as the second-to-last line of your code (right before plt.show()) the line
concentration_chart_plume(ax, ticks, colors, title)
which actually draws the plot.
Finally, I assume that you're doing something sensible so that your script gets the right values of FILE_1, FILE_2, and FILE_3.
Step 3: Check your equation
I don't know what you're trying to plot, but the equation you're using gives invalid values (as you seem to know) any time the element in cx is less than 1.0. Is this really the right equation? If so, you might want to use something like
cx = [max(1.0, c) for c in cx]
after you set the values of cx, but before you use them. Then, the logarithm will always be 0.0 or greater, so that the square-root exists. This basically throws away smaller values of your data, so I'm assuming that they're just noise or something....
Step N+1: Enjoy the results
After making all of the changes listed in steps 2 and 3 (and correcting the spelling of the title), I get the following very-reasonable-looking plot:

Related

Error exchanging list of floats in a topic

I think that the issue is silly.
I'd like to run the code on two computers and I need to use a list. I followed this Tutorials
I used my PC as a talker and computer of the robot as a listener.
when running the code on my PC, the output is good as I needed.
[INFO] [1574230834.705510]: [3.0, 2.1]
[INFO] [1574230834.805443]: [3.0, 2.1]
but once running the code on the computer of the robot, the output is:
Traceback (most recent call last):
File "/home/redhwan/learn.py", line 28, in <module>
talker()
File "/home/redhwan/learn.py", line 23, in talker
pub.publish(position.data)
File "/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/topics.py", line 886, in publish
raise ROSSerializationException(str(e))
rospy.exceptions.ROSSerializationException: <class 'struct.error'>: 'required argument is not a float' when writing 'data: [3.0, 2.1]'
full code on PC:
#!/usr/bin/env python
import rospy
from std_msgs.msg import Float32
x = 3.0
y = 2.1
def talker():
# if a == None:
pub = rospy.Publisher('position', Float32, queue_size=10)
rospy.init_node('talker', anonymous=True)
# rospy.init_node('talker')
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
position = Float32()
a = [x,y]
# a = x
position.data = list(a)
# position.data = a
# hello_str = [5.0 , 6.1]
rospy.loginfo(position.data)
pub.publish(position.data)
rate.sleep()
if __name__ == '__main__':
try:
talker()
except rospy.ROSInterruptException:
pass
full code on the computer of the robot:
#!/usr/bin/env python
import rospy
from std_msgs.msg import Float32
def callback(data):
# a = list(data)
a = data.data
print a
def listener():
rospy.init_node('listener', anonymous=True)
rospy.Subscriber("position", Float32, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
listener()
when using one number as float everything is OK.
I understand how to publish and subscribe to them separately as the float but I'd like to do it as list
Any ideas or suggestion, it would be appreciated.
When you exchange messages in ROS is preferred to adopt standard messages if there is something relatively simple. Of course, when you develop more sophisticated systems (or modules), you can implement your own custom messages.
So in the case of float array, Float32MultiArray is your friend.
Populating the message in one side will look like that (just an example using a 2 elements float32 array) in C++:
.
.
.
while (ros::ok())
{
std_msgs::Float32MultiArray velocities;
velocities.layout.dim.push_back(std_msgs::MultiArrayDimension());
velocities.layout.dim[0].label = "velocities";
velocities.layout.dim[0].size = 2;
velocities.layout.dim[0].stride = 1;
velocities.data.clear();
velocities.data.push_back(count % 255);
velocities.data.push_back(-(count % 255));
velocities_demo_pub.publish(velocities);
ros::spinOnce();
loop_rate.sleep();
++count;
}
.
.
.
in Python for 8 elements array an example will look like:
.
.
.
while not rospy.is_shutdown():
# compose the multiarray message
pwmVelocities = Float32MultiArray()
myLayout = MultiArrayLayout()
myMultiArrayDimension = MultiArrayDimension()
myMultiArrayDimension.label = "motion_cmd"
myMultiArrayDimension.size = 1
myMultiArrayDimension.stride = 8
myLayout.dim = [myMultiArrayDimension]
myLayout.data_offset = 0
pwmVelocities.layout = myLayout
pwmVelocities.data = [0, 10.0, 0, 10.0, 0, 10.0, 0, 10.0]
# publish the message and log in terminal
pub.publish(pwmVelocities)
rospy.loginfo("I'm publishing: [%f, %f, %f, %f, %f, %f, %f, %f]" % (pwmVelocities.data[0], pwmVelocities.data[1],
pwmVelocities.data[2], pwmVelocities.data[3], pwmVelocities.data[4], pwmVelocities.data[5],
pwmVelocities.data[6], pwmVelocities.data[7]))
# repeat
r.sleep()
.
.
.
and on the other side your callback (in C++), will look like:
.
.
.
void hardware_interface::velocity_callback(const std_msgs::Float32MultiArray::ConstPtr &msg) {
//velocities.clear();
if (velocities.size() == 0) {
velocities.push_back(msg->data[0]);
velocities.push_back(msg->data[1]);
} else {
velocities[0] = msg->data[0];
velocities[1] = msg->data[1];
}
vel1 = msg->data[0];
vel2 = msg->data[1];
//ROS_INFO("Vel_left: [%f] - Vel_right: [%f]", vel1 , vel2);
}
.
.
.
Hope that you got an idea...if you need something more drop me a line!

jmodelica optimization has runtime error

I am trying to follow different papers and tutorials to learn how to solve optimization problems of modelica modells.
In http://www.syscop.de/files/2015ss/events/opcon-thermal-systems/optimization_tool_chain_in_jmodelica.org_toivo_henningsson.pdf I found a very simple tutorial. But when I execute it I get some very open error messages.
I am using Python 2.7 with jupyther.
Here is my Notepad:
from pyjmi import transfer_optimization_problem
import matplotlib.pyplot as plt
import os.path
file_path = os.path.join("D:\Studies", "Integrator.mop")
op = transfer_optimization_problem('optI', file_path)
res = op.optimize()
t = res['time']
x = res['x']
u = res['u']
plt.plot(t,x,t,u)
My modelica file:
package Integrator
model Integrator
Real x(start=2, fixed = true);
input Real u;
equation
der(x) = -u;
end Integrator;
optimization optI(objective = finalTime, objectiveIntegrand = x^2 + u^2, startTime = 0, finalTime(free = true, min = 0.5, max = 2, initialGuess = 1))
Real x (start = 2, fixed = true);
input Real u;
equation
der(x) = -u;
constraint
u <= 2;
x(finalTime) = 0;
end optI;
end Integrator;
When I excute the code I get an RuntimeError, telling me that a java error occured and details where printed. From the Traceback I do not know what the note
This file is compatible with both classic and new-style classes
mean. I know that my setup is working because I executed the CSTR tutorial given by modelon. But now, it try to use my own models and it is giving me that error.
Runtime Error desciption
Using same syntax like in Modelica for import
e.g.
import Modelica.SIunits.Temperature;
where the package structure is part of the model-identification should resolve the issue.
op = transfer_optimization_problem('Integrator.optI', file_path)

Octave library - 'MeanPeakHeight' invalid parameter

I would like to do a peak detection of a .wav file signal in Python with Octave library on a Raspberry pi 3 with Raspbian but there is a problem with the octave.findpeaks function. I had this error:findpeaks : argument 'MeanPeakHeight' did not match any valid parameter of the parser
I have installed all the packages concerning Octave so this is why i don't understand.
This is a part of my program :
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile as wav
from scipy.signal import find_peaks_cwt, butter, lfilter
from pylab import *
import os
from operator import truediv
from easygui import *
from oct2py import octave
"High and Low Frequency for the filter"
low = 100
high = 50
list_file = []
octave.eval("pkg load signal")
def display_wav(wav_file):
samplerate, beat = wav.read('/home/pi/heartbeat_project/heartbeat_songs/%s' %wav_file)
beat_resize = np.fromfile(open('/home/pi/heartbeat_project/heartbeat_songs/%s' %wav_file),np.int16)[4*samplerate:float(beat.shape[0])-4*samplerate]
beat_resize = beat_resize / (2.**15)
timeArray = arange(0,float(beat_resize.shape[0]),1)
timeArray = timeArray / samplerate
ylow = butter_lowpass_filter(samplerate, 5, low, beat_resize)
y = butter_highpass_filter(samplerate, 5, high, ylow)
peaks, indexes = octave.findpeaks(np.array(y),'DoubleSided','MeanPeakHeight',np.std(y))
findpeaks is part of the octave-forge signal package:source file
This function doesn't have a 'MeanPeakHeight' parameter. Is guess this is a typo and you want 'MinPeakHeight'

peak fitting lmfit nan outcome

trying to fit a peak to some data like this:
import scipy
from lmfit.models import GaussianModel
x = shm.PTR_P
y = shm.PORE_V_P
mod = LorentzianModel()
pars = mod.guess(y, x=x)
out = mod.fit(y, pars, x=x)
print(out.fit_report(min_correl=0.25))
and while I can do the fit if I generate the data, if I try to read them from another source it doesn't work. Am not too good at this and have no idea what the issue is. Here is the output:
[x,y]
[(34.145490000000002, 3.4599999999999999e-08),
(29.286449999999999, 4.8399999999999997e-08),
(25.118860000000002, 0.026773140000000001),
(21.544350000000001, 0.068791409999999997),
(18.4785, 0.083200979999999994),
(15.848929999999999, 0.02123179),
(11.659139999999999, 0.01551077),
(10.0, 0.084493879999999993),
(6.3095739999999996, 2.0899999999999998e-07),
(5.4116949999999999, 0.045209140000000002),
(4.6415889999999997, 0.054789360000000002),
(3.4145489999999996, 8.9399999999999993e-08),
(2.9286449999999999, 0.01100814),
(2.5118860000000001, 0.088990659999999999),
(1.84785, 3.5799999999999995e-07),
(1.5848930000000001, 0.099999009999999999),
(1.359356, 0.075139280000000003),
(1.1659139999999999, 0.167379),
(1.0, 0.57693050000000001),
(0.85769590000000007, 1.8658159999999999),
(0.73564230000000008, 8.4961369999999992),
(0.6309574, 25.299099999999999),
(0.54116949999999997, 21.413350000000001),
(0.46415889999999999, 13.408829999999998),
(0.39810719999999999, 8.3584750000000003),
(0.34145490000000006, 5.3982010000000002),
(0.29286440000000002, 3.7518540000000002),
(0.25118859999999998, 2.5325389999999999),
(0.21544349999999998, 1.7722470000000001),
(0.18478499999999998, 1.445808),
(0.15848929999999997, 1.182083),
(0.13593559999999999, 0.94957730000000007),
(0.1165914, 0.67620849999999999),
(0.10000000000000001, 0.46631620000000001),
(0.085769590000000007, 0.41001890000000002),
(0.07356422, 0.30625920000000001),
(0.063095730000000003, 0.24040219999999998),
(0.054116949999999997, 0.1942596),
(0.046415890000000001, 0.11306760000000002),
(0.039810720000000001, 0.099998470000000006),
(0.034145490000000001, 0.099998470000000006),
(0.029286449999999999, 0.02246857),
(0.025118870000000001, 0.077529909999999994)]
I would guess that either there are NaNs in your data or that the initial guess is so far off as to produce NaNs. The initial guess of 0 for sigma seems suspicious -- this should be > 0.
Either way, plotting the data and using np.isnan() would probably help isolate the problem.

How to pass id of a Tkinter Scale through command

I am using Tkinter to create a GUI for a program I am writing that will adjust some Zigbee controlled LED lights that I have. I am using a loop to create multiple copies of a Scale that I'm going to use as a brightness slider. I manage to create the sliders properly, but I am having difficulties actually adjust the sliders correctly. Here's my code:
import simplejson as json
import requests # submits http requests
from Tkinter import *
from ttk import Frame, Button, Label, Style, Notebook
# MD5 hash from http://www.miraclesalad.com/webtools/md5.php
myhash = "d9ffaca46d5990ec39501bcdf22ee7a1"
appname = "dddd" # name content isnt relevant
num_lights = int(3)
class hueApp(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self, *args, **kwds):
# title the app window
self.parent.title("Hue controller")
self.style = Style()
# create grid layout
self.columnconfigure(0, pad=3)
self.columnconfigure(1, pad=3)
self.columnconfigure(2, pad=3)
self.rowconfigure(0, pad=3)
self.scale=[]
self.val=[]
for i in range(num_lights):
print 'i=', i, type(i)
self.val.append(i+1)
print 'val=', self.val, type(self.val)
self.scale.append(Scale(self, from_=255, to_=0, command=lambda i=self.val: self.brightness_adj(i,light_id=i)))
print self.scale[i]
print 'i = ', i, type(i), '\n\n'
self.scale[i].set(150)
self.scale[i].grid(row=1, column=i)
if i == 2:
print '\n', self.scale, '\n'
print self.val, '\n'
self.scale[i].set(200)
self.centerWindow
self.pack()
def brightness_adj(self,light_val, light_id):
#global bri_val
print 'light_id:', light_id, type(light_id)
print 'light_val:', light_val, type(light_val)
print self.val[int(light_id)]
#print int(light_id)
bri_val = self.scale[light_id-1].get()
print bri_val
light = light_id
global huehub
huehub = "http://192.168.0.100/api/"+ myhash + "/lights/" + str(light)
#brightness_logic()
reply = requests.get(huehub)
a=json.loads(reply.text)
#print bri_val
payload = json.dumps({"bri":bri_val})
sethuehub = huehub + "/state"
reply = requests.put(sethuehub, data=payload)
def centerWindow(self):
w = 250
h = 150
sw = self.parent.winfo_screenwidth()
sh = self.parent.winfo_screenheight()
x = (sw-w)/2
y = (sh-h)/2
self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
def main():
root=Tk() #the root window is created
app=hueApp(root) #create an instance of the application class
root.mainloop()
if __name__ == '__main__':
main()
I realize that this code probably gives an error when you try to run it. Basically my problem is that the command for each scale is only send brightness_adj the value of the scale, but I can't get it to pass through the id of the light. I was trying to do this by sending through the index of the self.scale list that it is appended into when it is created. I need to know which light is being adjusted so that I can send a new brightness to the corresponding light bulb. I hope I was clear enough. Thanks in advance!
I'm a little confused about what you're trying to do with the line that assigns callback functions to the scale widgets:
self.scale.append(Scale(self, from_=255, to_=0, command=lambda i=self.val: self.brightness_adj(i,light_id=i)))
since self.val is a list, and you're sending it as both the light_val and the light_id arguments, which I would think should be integers.
Possible fix:
I'm guessing that you want each callback to send a different ID to the brightness_adj function depending on which scale it's assigned to. Here's how I would fix this up:
Add this function to your hueApp class namespace:
def brightnessCallbackFactory(self, id):
return lambda light_val:self.brightness_adj(light_val, id)
Then change the callback assignment line from the above to this:
self.scale.append(Scale(self, from_=255, to_=0, command=self.brightnessCallbackFactory(i)))
That should create callback functions that retain the ID value in their internal namespace and assign them to the corresponding scale widget.