Error exchanging list of floats in a topic - list

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!

Related

python when there is no input for the subscriber it starts publishing error?/! how to solve it?

I have provided the following python code,but the problem is that when it doesnot receive any input, it start showing error. how can i modify the code in a way that this error dosnot appear:
#!/usr/bin/env python from roslib import message import rospy import sensor_msgs.point_cloud2 as pc2 from sensor_msgs.msg import PointCloud2, PointField import numpy as np import ros_numpy from geometry_msgs.msg import Pose
#listener def listen():
rospy.init_node('listen', anonymous=True)
rospy.Subscriber("/Filtered_points_x", PointCloud2, callback_kinect)
def callback_kinect(data):
pub = rospy.Publisher('lidar_distance',Pose, queue_size=10)
data_lidar = Pose()
xyz_array = ros_numpy.point_cloud2.pointcloud2_to_xyz_array(data)
print(xyz_array)
mini_data = min(xyz_array[:,0])
print("mini_data", mini_data)
data_lidar.position.x = mini_data
pub.publish(data_lidar)
print("data_points", data_lidar.position.x)
height = int (data.height / 2)
middle_x = int (data.width / 2)
middle = read_depth (middle_x, height, data) # do stuff with middle
def read_depth(width, height, data) :
if (height >= data.height) or (width >= data.width) :
return -1
data_out = pc2.read_points(data, field_names= ('x','y','z'), skip_nans=True, uvs=[[width, height]])
int_data = next(data_out)
rospy.loginfo("int_data " + str(int_data))
return int_data
if __name__ == '__main__':
try:
listen()
rospy.spin()
except rospy.ROSInterruptException:
pass
the following is the error that i mentioned:
[[ 7.99410915 1.36072445 -0.99567264]]
('mini_data', 7.994109153747559)
('data_points', 7.994109153747559)
[INFO] [1662109961.035894]: int_data (7.994109153747559, 1.3607244491577148, -0.9956726431846619)
[]
[ERROR] [1662109961.135572]: bad callback: <function callback_kinect at 0x7f9346d44230>
Traceback (most recent call last):
File "/opt/ros/kinetic/lib/python2.7/dist-packages/rospy/topics.py", line 750, in _invoke_callback
cb(msg)
File "/home/masoumeh/catkin_ws/src/yocs_velocity_smoother/test4/distance_from_pointcloud.py", line 27, in callback_kinect
mini_data = min(xyz_array[:,0])
ValueError: min() arg is an empty sequence
The code is still receiving input, but specifically it’s receiving an empty array. You’re then trying to splice the empty array, causing the error. Instead you should check that the array has elements before the line min(xyz_array[:,0]). It can be as simple as:
if xyz_array == []:
return
As another note, you’re creating a publisher in the callback. You shouldn’t do this as a new publisher will be created every time it gets called. Instead create it as a global variable.

How to make servo Dynamixel motor to move from 0 --> 90 --> 180 --> 220--->0 degrees

Hello software developers.
I am new in programming and ROS. I am working now with servo motors and want to make the controlling node to rotate motor into some degrees like from 0 --> 90--> 180-->0 degrees.
there is a main code and I would like to add def function into the main node:
#!/usr/bin/env python
import os
import rospy
from std_msgs.msg import String
from controller_motor.msg import Motor
from controller_motor.srv import Motor2
if os.name == 'nt':
import msvcrt
def getch():
return msvcrt.getch().decode()
else:
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
def getch():
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
from dynamixel_sdk import * # Uses Dynamixel SDK library
class DynamixelController(object):
def __init__(self):
#print("1")
self.motor_sub = rospy.Subscriber("/motor_topic", Motor, self.motor_callback)
self.test_motor_client(1) #here we can put request order as 1 for the using id=14 and position= 1500; or as 2 is id same and position is 2500. The cases could be found in the server.py node
def motor_callback(self, data):
_id = data.id
_position = data.position
print("_id : {0}, _position : {1}".format(_id, _position))
self.read_write(_id, _position)
def test_motor_client(self, request):
print("2")
rospy.wait_for_service('test_motor_service')
try:
proxy = rospy.ServiceProxy('test_motor_service', Motor2)
response = proxy(request)
print("response is id : {} position : {}".format(response.id, response.position))
self.read_write(response.id, response.position)
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
def new_rotation(self, response):
print("3")
rospy.wait_for_service('test_mototr_rotation')
try:
proxy = rospy.ServiceProxy('test_motor_rotation', Motor2)
response = proxy(request)
self.read_write(response.id, response.position(arg[0]))
sleep(2)
self.read_write(response.id, response._position(arg[1]))
sleep(2)
self.read_write(response.id, response._position(arg[2]))
sleep(2)
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
def read_write(self, _id, _position):
print("Start the node")
# Control table address
ADDR_PRO_TORQUE_ENABLE = 64 # Control table address is different in Dynamixel model
ADDR_PRO_GOAL_POSITION = 116
ADDR_PRO_PRESENT_POSITION = 132
# Protocol version
PROTOCOL_VERSION = 2.0 # See which protocol version is used in the Dynamixel
# Default setting
DXL_ID = _id # Dynamixel ID : 14
BAUDRATE = 1000000 # Dynamixel default baudrate : 1000000
DEVICENAME = '/dev/ttyUSB0' # Check which port is being used on your controller
# ex) Windows: "COM1" Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*"
TORQUE_ENABLE = 1 # Value for enabling the torque
TORQUE_DISABLE = 0 # Value for disabling the torque
DXL_MINIMUM_POSITION_VALUE = 10 # Dynamixel will rotate between this value
DXL_MAXIMUM_POSITION_VALUE = _position # The position here is already in the degree measurement; and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.)
DXL_MOVING_STATUS_THRESHOLD = 20 # Dynamixel moving status threshold
index = 0
dxl_goal_position = [DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE] # Goal position
# Initialize PortHandler instance
# Set the port path
# Get methods and members of PortHandlerLinux or PortHandlerWindows
portHandler = PortHandler(DEVICENAME)
# Initialize PacketHandler instance
# Set the protocol version
# Get methods and members of Protocol1PacketHandler or Protocol2PacketHandler
packetHandler = PacketHandler(PROTOCOL_VERSION)
# Open port
if portHandler.openPort():
print("Succeeded to open the port")
else:
print("Failed to open the port")
print("Press any key to terminate...")
getch()
quit()
# Set port baudrate
if portHandler.setBaudRate(BAUDRATE):
print("Succeeded to change the baudrate")
else:
print("Failed to change the baudrate")
print("Press any key to terminate...")
getch()
quit()
# Enable Dynamixel Torque
dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_ENABLE)
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
else:
print("Dynamixel has been successfully connected")
while 1:
print("Press any key to continue! (or press ESC to quit!)")
if getch() == chr(0x1b):
break
# Write goal position
dxl_comm_result, dxl_error = packetHandler.write4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_GOAL_POSITION, dxl_goal_position[index])
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
while 1:
# Read present position
dxl_present_position, dxl_comm_result, dxl_error = packetHandler.read4ByteTxRx(portHandler, DXL_ID, ADDR_PRO_PRESENT_POSITION)
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
print("[ID:%03d] GoalPos:%03d PresPos:%03d" % (DXL_ID, dxl_goal_position[index], dxl_present_position))
if not abs(dxl_goal_position[index] - dxl_present_position) > DXL_MOVING_STATUS_THRESHOLD:
break
# Change goal position
if index == 0:
index = 1
else:
index = 0
# Disable Dynamixel Torque
dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE)
if dxl_comm_result != COMM_SUCCESS:
print("%s" % packetHandler.getTxRxResult(dxl_comm_result))
elif dxl_error != 0:
print("%s" % packetHandler.getRxPacketError(dxl_error))
# Close port
portHandler.closePort()
if __name__ == '__main__':
rospy.init_node('read_write', anonymous=True)
controller = DynamixelController()
and here is the server node:
#!/usr/bin/env python
import rospy
from controller_motor.srv import Motor2, Motor2Response
def motor_info(req):
print("receive the request : {}".format(req.order))
if req.order == 1:
_id = 14
#_position = 1500
_positiondegree = 180 # change it degree value
_position = (11.4 * (_positiondegree)) # here is using there 11.4 the number which helps rotate the motor in the correct degree; We get the number encoder number/degree we want to rotate the motor.
elif req.order == 2:
_id = 14
#_position = 2047.5
_positiondegree = 180
_position = (11.4 * (_positiondegree))
print("Response to this request id : {} and postiion : {}".format(_id, _position))
return Motor2Response(_id, _position)
def motor_info_server():
rospy.init_node('test_motor_service')
s = rospy.Service('test_motor_service', Motor2, motor_info)
print("Ready to response some id and position")
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
if __name__ == '__main__':
motor_info_server()
Now when running the motor it rotates to the degree I would like it to rotate. And now I would like to know how could I give some degrees to make motor rotates from 0 to some other degrees and go back to the 0 degree position again.
I guess there might be applied the list and args for some degrees. But I am not well-known how I could do this :)
I would like to get some advice from professionals like you ,guys :)
I know my question could be obvious for professionals. I would like to get experience in the programming and ROS as much as I can :)
I will be so thankful for any help and advise how I could do this :)
Thank to everyone who will share his/her idea:)
I wish you have a good day :)
You have to add a new function to your code in the client file:
def rotate_bot(self,degree):
rospy.wait_for_service('rotate_motor')
try:
proxy = rospy.ServiceProxy('test_motor_rotation', Motor2)
response = proxy(degree)
except rospy.ServiceException as e:
print("Service call failed: %s"%e)
This function basically calls a Service and gives him the amount of degrees the robot has to turn. Also add this function to call the roate function:
def test_rotate(self):
rotate_bot(90)
rotate_bot(90)
rotate_bot(-180)
Now the robot turns from 0 --> 90 --> 180 --> 0
In your server file you have to add the service in the motor_info_server() method:
s = rospy.Service('test_motor_rotation', Motor2, rotate_motor)
and also add the method:
def rotate_motor(req):
print("received the request : {}".format(req.order))
degree = req.order
_id = 14
_positiondegree = degree
_position = (11.4 * (_positiondegree))
return Motor2Response(_id, _position)
If you want to pass doubles as degrees you have to change your message datatype from Motor2 to something else...

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)

Tcl Error: Out of Stack Space With Flask and Matplotlib in Python 2.7

Thanks for your time:
I created a flask server that takes in variables from a form post and outputs a pie or bar graph. While debugging, I noticed this error:
Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "C:\Python27\lib\site-packages\matplotlib\_pylab_helpers.py", line 92, in destroy_all
manager.destroy()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 618, in destroy
self.canvas._tkcanvas.after_cancel(self.canvas._idle_callback)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 616, in after_cancel
self.tk.call('after', 'cancel', id)
TclError: out of stack space (infinite loop?)
Error in sys.exitfunc:
Traceback (most recent call last):
File "C:\Python27\lib\atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
File "C:\Python27\lib\site-packages\matplotlib\_pylab_helpers.py", line 92, in destroy_all
manager.destroy()
File "C:\Python27\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 618, in destroy
self.canvas._tkcanvas.after_cancel(self.canvas._idle_callback)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 616, in after_cancel
self.tk.call('after', 'cancel', id)
_tkinter.TclError: out of stack space (infinite loop?)
This seems to cause the server to reload (successfully for what it's worth) which is a problem. No clue what's going on here, other than tkinter being upset. And, no luck with my google fu.
flask server (w debug settings. Mapped vars are due to a project req.):
# Flask App that functions as a graph end point replacement "DAC-780"
# Standard Library
import os
import uuid
# Third Party
from flask import Flask, request
# Local
from pie import make_pie
from bar import make_bar
app_root = os.path.dirname(os.path.abspath(__file__))
images = os.path.join(app_root, 'static/images')
app = Flask(__name__, static_folder="static")
app._static_folder = os.path.join(app_root, 'static')
#app.route('/charts/<path>', methods=['POST'])
def graph(path):
g_data_list = []
file_name = str(uuid.uuid4())
# if bar graph
if path == "chart4.asp":
# grab vars
g_title = str(request.form['Title'])
x_title = str(request.form['CatTitle'])
y_title = str(request.form['ValTitle'])
ser1 = str(request.form['Ser1'])
ser2 = str(request.form['Ser2'])
cat1 = str(request.form['Cat1'])
cat2 = str(request.form['Cat2'])
cat3 = str(request.form['Cat3'])
cat4 = str(request.form['Cat4'])
cat5 = str(request.form['Cat5'])
cat6 = str(request.form['Cat6'])
cat7 = str(request.form['Cat7'])
cat8 = str(request.form['Cat8'])
cat9 = str(request.form['Cat9'])
cat10 = str(request.form['Cat10'])
cat11 = str(request.form['Cat11'])
cat12 = str(request.form['Cat12'])
cat13 = str(request.form['Cat13'])
s1d1 = int(request.form['S1D1'])
s1d2 = int(request.form['S1D2'])
s1d3 = int(request.form['S1D3'])
s1d4 = int(request.form['S1D4'])
s1d5 = int(request.form['S1D5'])
s1d6 = int(request.form['S1D6'])
s1d7 = int(request.form['S1D7'])
s1d8 = int(request.form['S1D8'])
s1d9 = int(request.form['S1D9'])
s1d10 = int(request.form['S1D10'])
s1d11 = int(request.form['S1D11'])
s1d12 = int(request.form['S1D12'])
s1d13 = int(request.form['S1D13'])
s2d1 = int(request.form['S2D1'])
s2d2 = int(request.form['S2D2'])
s2d3 = int(request.form['S2D3'])
s2d4 = int(request.form['S2D4'])
s2d5 = int(request.form['S2D5'])
s2d6 = int(request.form['S2D6'])
s2d7 = int(request.form['S2D7'])
s2d8 = int(request.form['S2D8'])
s2d9 = int(request.form['S2D9'])
s2d10 = int(request.form['S2D10'])
s2d11 = int(request.form['S2D11'])
s2d12 = int(request.form['S2D12'])
s2d13 = int(request.form['S2D13'])
# vars i mapped but weren't needed for my graph lib
g_type = str(request.form['Type'])
g_cats = str(request.form['Cats'])
g_series = str(request.form['Series'])
cat_title = str(request.form['CatTitle'])
# add data to g_data_list so we can process it
g_data_list.append((ser1, [s1d1, s1d2, s1d3, s1d4, s1d5, s1d6, s1d7, s1d8,
s1d9, s1d10, s1d11, s1d12, s1d13]))
g_data_list.append((ser2, [s2d1, s2d2, s2d3, s2d4, s2d5, s2d6, s2d7, s2d8,
s2d9, s2d10, s2d11, s2d12, s2d13]))
x_labels = [cat1, cat2, cat3, cat4, cat5, cat6, cat7, cat8, cat9, cat10,
cat11, cat12, cat13]
# make a graph to return in html
graph = make_bar(g_title, y_title, x_labels, g_data_list, file_name, cat_title, x_title)
else:
# all others are probably pie graphs
g_title = str(request.form['Title'])
cat1 = str(request.form['Cat1'])
cat2 = str(request.form['Cat2'])
cat3 = str(request.form['Cat3'])
cat4 = str(request.form['Cat4'])
s1d1 = int(request.form['S1D1'])
s1d2 = int(request.form['S1D2'])
s1d3 = int(request.form['S1D3'])
s1d4 = int(request.form['S1D4'])
# vars that aren't needed for replications of the final product, but
# were part of the old code
g_type = str(request.form['Type'])
g_cats = str(request.form['Cats'])
g_series = str(request.form['Series'])
cat_title = str(request.form['CatTitle'])
val_title = str(request.form['ValTitle'])
s1 = str(request.form['Ser1'])
s2 = str(request.form['Ser2'])
# add data
g_data_list.append([cat1, s1d1])
g_data_list.append([cat2, s1d2])
g_data_list.append([cat3, s1d3])
g_data_list.append([cat4, s1d4])
# make graph to send back via html
graph = make_pie(g_title, g_data_list, file_name)
# make a web page with graph and return it
html = """
<html>
<head>
<title>%s</title>
</head>
<body>
<img src="/static/images/%s.png" alt="An Error Occured"/>
</body>
</html>
""" % (g_title, str(file_name))
return html
if __name__ == '__main__':
app.run(port=3456, host="0.0.0.0", debug=True)
bar.py:
# creates a bar chart based on input using matplotlib
import os
import numpy as np
import matplotlib.pyplot as plt
from pylab import rcParams
rcParams['figure.figsize'] = 6.55, 3.8
app_root = os.path.dirname(os.path.abspath(__file__))
images = os.path.join(app_root, 'static/images')
def make_bar(g_title, y_title, x_labels, data_series, file_name, cat_title,
x_title):
n_groups = 13
bar_width = 0.35
opacity = 0.4
fig, ax = plt.subplots()
index = np.arange(n_groups)
error_config = {'ecolor': '0.3'}
plt.bar(index, tuple(data_series[0][1]), bar_width,
alpha=opacity,
color='b',
error_kw=error_config,
label='{}'.format(data_series[0][0]))
plt.bar(index + bar_width, tuple(data_series[1][1]), bar_width,
alpha=opacity,
color='r',
error_kw=error_config,
label='{}'.format(data_series[1][0]))
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
plt.xlabel(x_title, fontsize=10)
plt.ylabel(y_title, fontsize=10)
plt.title(g_title, fontsize=11)
plt.xticks(index + bar_width, tuple(x_labels), fontsize=8)
plt.yticks(fontsize=8)
plt.axis('tight')
lgd = plt.legend(fontsize=8, bbox_to_anchor=(1.15, 0.5))
plt.tight_layout()
plt.draw()
plt.savefig('{}/{}.png'.format(images, file_name),
dpi=100, format='png', bbox_extra_artists=(lgd,),
bbox_inches='tight')
return
pie.py:
# creates a pie chart w/ matplotlib
import os
import matplotlib.pyplot as plt
from pylab import rcParams
app_root = os.path.dirname(os.path.abspath(__file__))
images = os.path.join(app_root, 'static/images')
def make_pie(title, g_data_list, file_name):
rcParams['figure.figsize'] = 5.75, 3
labels = [entry[0] for entry in g_data_list]
sizes = [entry[1] for entry in g_data_list]
ax = plt.subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.7, box.height])
patches, texts = ax.pie(sizes, startangle=90)
ax.legend(patches, labels, loc='center left',
bbox_to_anchor=(.9, 0.5), fontsize=8)
plt.axis('equal')
plt.suptitle(g_title, fontsize=12)
plt.draw()
plt.savefig('{}/{}.png'.format(images, file_name), dpi=100, format='png')
return
I noticed that the function that graphed everything, when run separately, would stay running after I closed the plot window. Adding plt.clf() fixed that problem, and appears to be the solution to mine relating to Flask as well.
Had same problem with seaborn
import matplotlib
matplotlib.use('Agg')
helps me.
details: https://matplotlib.org/faq/usage_faq.html#what-is-a-backend

Dll load failed, in python 2.7 running on windows 8.1

I'am using Boneh-Lynn-Shacham Identity Based Signature scheme for my final year project for getting encryption keys
from charm.toolbox.pairinggroup import *
from charm.engine.util import *
debug = False
class IBSig():
def __init__(self, groupObj):
global group
group = groupObj
def dump(self, obj):
ser_a = serializeDict(obj, group)
return str(pickleObject(ser_a))
def keygen(self, secparam=None):
g, x = group.random(G2), group.random()
g_x = g ** x
pk = { 'g^x':g_x, 'g':g, 'identity':str(g_x), 'secparam':secparam }
sk = { 'x':x }
return (pk, sk)
def sign(self, x, message):
M = self.dump(message)
if debug: print("Message => '%s'" % M)
return group.hash(M, G1) ** x
def verify(self, pk, sig, message):
M = self.dump(message)
h = group.hash(M, G1)
if pair(sig, pk['g']) == pair(h, pk['g^x']):
return True
return False
def main():
groupObj = PairingGroup('../param/d224.param')
m = { 'a':"hello world!!!" , 'b':"test message" }
bls = IBSig(groupObj)
(pk, sk) = bls.keygen(0)
sig = bls.sign(sk['x'], m)
if debug: print("Message: '%s'" % m)
if debug: print("Signature: '%s'" % sig)
assert bls.verify(pk, sig, m)
if debug: print('SUCCESS!!!')
if __name__ == "__main__":
debug = True
main()
when I am implementing it in python the code was not able to find the module named pairing though I have added Charm module to my library.Getting error like
Traceback (most recent call last):
File "C:\Users\Sailesh\Desktop\bls.py", line 1, in <module>
from charm.toolbox.pairinggroup import *
File "C:\Python27\lib\charm\toolbox\pairinggroup.py", line 2, in <module>
from charm.core.math.pairing import serialize
ImportError: DLL load failed: The specified module could not be found.
I have taken the code from
Boneh-Lynn-Shacham Identity Based Signature code and downloaded the module charm from charm module link. Let me know where is the error or whether the
problem is with the module. I cant figure out what is the problem. Thanks in advance.
Try the 0.43 version directly fron github:
https://github.com/JHUISI/charm/releases