Robot Pepper / get value of Obstacle detection - python

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)

Related

module 'plotnine' has no attribute 'ggplot_build'

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

How can I apply image write file path?

i = 2 #int
cv2.imwrite([r'C:\Users\Desktop\result (' + str(i) + ').png'], result) #result is 16bit image
I want to save image under the name 'result (2).png'
Because, i is stuck in 'for loop'.
However, the code above causes an error.
Please help me.
add)
## Flat Field Correction (FFC) ##
import numpy as np
import cv2
import matplotlib.pyplot as plt
import numba as nb
import multiprocessing as multi
import parmap
import time
start = time.time()
B = cv2.imread(r'D:\remedi\Exercise\Xray\Offset.png', -1) # offset image
for i in range(2,3):
org_I = cv2.imread(r'D:\remedi\Exercise\Xray\objects\object (' + str(i) + ').png', -1) # original image
w = cv2.imread(r'D:\remedi\Exercise\Xray\white\white (' + str(i) + ').png', -1) # white image
## dead & bad pixel correction
corrected_w = w.copy()
corrected_org_I = org_I.copy()
c = np.mean(corrected_w)
p = np.abs(corrected_w - c)
sens = 0.7
[num_y, num_x] = np.where((p < c*sens) | (p > c*sens))
#[num_y, num_x] = np.where((corrected_w < c*0.97) | (corrected_w > c*1.03))
ar = np.zeros((3,3))
ar2 = np.zeros((3,3))
#pool = multi.Pool(processes=6)
iter = num_y.shape[0]
for n in range(iter):
#parmap.map(bad_pixel_correction, [n, num_y, num_x, ar, ar2, corrected_w, corrected_org_I], pm_pbar=True, pm_processes=6)
for j in range(-1,2):
for k in range(-1,2):
if num_y[n]+j == -1 or num_x[n]+k == -1 or num_y[n]+j == 576 or num_x[n]+k == 576:
ar[j+1][k+1] = 0
ar2[j+1][k+1] = 0
else:
ar[j+1][k+1] = corrected_w[num_y[n]+j][num_x[n]+k]
ar2[j+1][k+1] = corrected_org_I[num_y[n]+j][num_x[n]+k]
ar[1][1] = 0
ar2[1][1] = 0
corrected_w[num_y[n]][num_x[n]] = np.sum(ar)/np.count_nonzero(ar)
corrected_org_I[num_y[n]][num_x[n]] = np.sum(ar2)/np.count_nonzero(ar2)
c = np.mean(corrected_w) # constant
## flat field correction
FFC = np.uint16(np.divide(c*(corrected_org_I-B), (corrected_w-B)))
F = np.fft.fft2(FFC)
Fshift = np.fft.fftshift(F)
magnitude_spectrum3 = 20*np.log(np.abs(Fshift))
[row, col] = org_I.shape
[row2, col2] = np.array([row, col], dtype=np.int) // 2
row2_range = 1
col2_range = 2
Fshift[:row2-row2_range-1, col2-col2_range-1:col2+col2_range] = 0
Fshift[row2+row2_range:, col2-col2_range-1:col2+col2_range] = 0
fishift = np.fft.ifftshift(Fshift)
result = np.fft.ifft2(fishift)
print("time :", time.time() - start)
cv2.imwrite(r'C:\Users\jhjoo\Desktop\corrected_org_I (' + str(i) + ').png', result)
cv2.imwrite(r'C:\Users\jhjoo\Desktop\corrected_org_I (' + str(i) + ').png', corrected_org_I)
cv2.imwrite(r'C:\Users\jhjoo\Desktop\corrected_w (' + str(i) + ').png', corrected_w)
cv2.imwrite takes first argument as a string, not a list. You should fix your code as following:
cv2.imwrite(r'C:\Users\Desktop\result (' + str(i) + ').png', result) #result is 16bit image

Ploting results from Gurobi python

import os
import sys
import math
import cvxopt as cvx
import picos as pic
import pandas as pd
import matplotlib.pyplot as plt
from gurobipy import *
from statsmodels.tsa.arima_model import ARIMA
import numpy as np
from scipy import *
#import DeferableLoad
OPTmodel = Model('OPTIMIZER')
#general parameters
Tamb =22
N = 1440 # maximum iteration
i = range(1, N)
COP= 3.4 # Coeffient of performance
'''
Prediction need to be added here
'''
# Datacenter room defintion
R = 10 #length of room
B = 7
H = 9 #Height of room
L = 10
dT = 60
A = 2*((L*B)+(B*H)+(H*L))
Thick = 0.33 # thickness of wall
k = 0.7 # thermal conductivity of wall
mAir = 1.2 * (L * B * H)
C = 718
landa = k * A / Thick
a0 = 0.05 / dT
a1 = 1
ki = math.exp(-(landa * 60) / (mAir * C)) # value that constant and its related to property of room
kc = (1 - ki) * a0
ko = (1 - ki) * a1
kp = (1 - ki) * (COP / landa)
Tmin= 18
Tmax= 27
Tamb= 22
PcoolingRated = 100
Pbess_rated = 30.462
Pbess_ratedN = -30.462
Ebess_min = 0
Ebess_max = 300
with open ('Pcooling.csv','r') as f:
Pcooling = []
for line in f:
Pcooling.append(line)
f.close()
with open ('ITpower.csv','r') as f1:
ITload = []
for line1 in f1:
ITload.append(line1)
f1.close()
with open ('DR.csv','r') as f2:
DR =[]
for line2 in f2:
DR.append(line2)
f2.close()
print ITload
print Pcooling
print DR
for i in range(1,200):
for it in range(1, 1440):
Tm = np.empty(1440)
Tm.fill(18)
TmA = np.empty(1440)
TmA.fill(27)
Phvac_flex = {}
Phvac_up = {}
Phvac_down_= {}
Phvac_up_ = {}
Pbess_out_ = {}
Pbess_in_ = {}
Phvac_down = {}
Pbess_flex_ = {}
Pbess_flex = {}
Phvac_flex_ = {}
Pbess_in = {}
Pdc = {}
Pdc_base = {}
Pflex_i = {}
Tdc_i = {}
Pbess_out ={}
Ebess_i = {}
Phvac_flex[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS,name="PHVAC_flex"+str(i))
Phvac_up[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_up" + str(i))
Phvac_up_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_up_" + str(i))
Phvac_down_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_down_" + str(i))
Pbess_out_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_out_" + str(i))
Pbess_in_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_in_" + str(i))
Phvac_down[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_down" + str(i))
Pbess_flex_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_flex_" + str(i))
Pbess_flex[i] = OPTmodel.addVar(lb=-GRB.INFINITY,ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_flex" + str(i))
Phvac_flex_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_flex_" + str(i))
Pbess_in[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_in" + str(i))
Pdc[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PDC" + str(i))
Pdc_base[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PDC_base" + str(i))
Pflex_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="Pflex_i" + str(i))
Tdc_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype = GRB.CONTINUOUS, name = "Tdc_i" + str(i))
Pbess_out[i] = OPTmodel.addVar(lb=-GRB.INFINITY,ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_out" + str(i))
Ebess_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS,name="Ebess_i" + str(i))
Pflex_i[1] = 0
Pflex_i[1] = 0
Tdc_i[0] = 18
Phvac_flex[1] = 0
# Phvac_flex_[1] = 0
Phvac_down[1] = 0
Phvac_up[1] = 0
Phvac_down_[1] = 0
Phvac_up_[1] = 0
# Phvac_down_pos[1] = 0
# Phvac_up_pos(1) = 0;
Pbess_flex[1] = 0
# Pbess_flex_[1] = 0
Pbess_out[1] = 0
Pbess_in[1] = 0
# Pbess_out_[1] = 0
Pbess_in_[1] = 0
# Pbess_out_pos[1] = -250
# Pbess_in_pos(1) = 250;
Ebess_i[1] = 150
OPTmodel.update()
'''
if float(DR[i]) > 0:
Phvac_down_[i] = 0
Phvac_up_[i] = float(DR[i])
Pbess_out_[i] = 0
Pbess_in_[i] = float(DR[i])
#Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
#Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
OPTmodel.update()
elif float(DR[i]) < 0:
Phvac_down_[i] = float(DR[i])
Phvac_up_[i] = 0
#Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
Pbess_out_[i] = float(DR[i])
Pbess_in_[i] = 0
#Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
OPTmodel.update()
else:
Phvac_down_[i] = 0
Phvac_up_[i] = 0
Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
Pbess_out_[i] = 0
Pbess_in_[i] = 0
Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
OPTmodel.update()
'''
#print Phvac_up.values()
#print Phvac_flex_[i]
print OPTmodel
OPTmodel.update()
ConHVAC1 = OPTmodel.addConstr(Phvac_flex[i] == Phvac_up[i] + Phvac_down[i], name='ConHVAC1')
ConHVAC2 = OPTmodel.addConstr(0 <= Phvac_flex[i] , name='ConHVAC2')
ConHVAC3 = OPTmodel.addConstr(Phvac_flex[i] <= PcoolingRated, name='ConHVAC3')
PH = pd.read_csv('Pcooling.csv')
PHVAC = PH.values
newList2 = map(lambda x: x / 1000, PHVAC)
p=[]
p=PcoolingRated-newList2[i]
#CONHVAC4 = OPTmodel.addConstr(Phvac_up[i]==np.minimum((Phvac_up_[i]),(float(newList2[i]))))
#Phvac_u(1:MaxIter) == min(Phvac_u_(1:MaxIter), (repelem(Phvac_max, MaxIter) - (Pcooling(1:MaxIter)'/1000)))
ConTemp1 = OPTmodel.addConstr(Tm[it] <= Tdc_i[i] <= TmA[it], name='ConTemp1')
ConBESS1 = OPTmodel.addConstr(Pbess_ratedN <= Pbess_flex[i] <= Pbess_rated, name='ConBESS1')
ConBESS2 = OPTmodel.addConstr(Pbess_flex[i] == Pbess_in[i] + Pbess_out[i], name='ConBESS2')
ConBESS3 = OPTmodel.addConstr(0 <= Pbess_in[i] <= min(Pbess_rated, Pbess_in_[i]), name='ConBESS3')
ConBESS4 = OPTmodel.addConstr(np.maximum(Pbess_ratedN,Pbess_out_[i]) <= Pbess_out[i]<=0 , name='ConBESS4') # need to modifty
ConEBESS1 = OPTmodel.addConstr(Ebess_min <= Ebess_i[i], name='ConEBESS1')
ConEBESS2 = OPTmodel.addConstr(Ebess_i[i] <= Ebess_max, name='ConEBESS2')
D = pd.read_csv('DR.csv').values
DRN = map(lambda x: x / 1000, D)
PDRN=map(lambda x: x / 4.8, DRN)
if float((PDRN[i])) > 0:
CON1 = OPTmodel.addConstr(Pbess_flex_[i] == Pbess_in_[i] + Pbess_out_[i],'CON1')
CON2 = OPTmodel.addConstr(Phvac_flex_[i] == Phvac_up_[i] + Phvac_down_[i],'CON2')
CON3=OPTmodel.addConstr(Phvac_down_[i] == 0, name='CON3')
CON4=OPTmodel.addConstr(Phvac_up_[i] == float((PDRN[i])),name='CON4')
CON5=OPTmodel.addConstr(Pbess_out_[i] == 0,name='CON5')
CON6=OPTmodel.addConstr(Pbess_in_[i] == float((PDRN[i])),name='CON6')
elif float(np.transpose(PDRN[i])) < 0:
CON7=OPTmodel.addConstr(Phvac_down_[i] == float(np.transpose(PDRN[i])),name='CON7')
CON8=OPTmodel.addConstr(Phvac_up_[i] == 0,name='CON8')
# Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
CON9=OPTmodel.addConstr(Pbess_out_[i] == float((PDRN[i])),name='CON9')
CON10=OPTmodel.addConstr(Pbess_in_[i] == 0,name='CON10')
else:
CON11=OPTmodel.addConstr(Phvac_down_[i] == 0,name='CON11')
CON12=OPTmodel.addConstr(Phvac_up_[i] == 0,name='CON12')
CON13=OPTmodel.addConstr(Phvac_flex_[i] == Phvac_down_[i] + Phvac_up_[i],name='CON13')
CON14=OPTmodel.addConstr(Pbess_out_[i] == 0)
CON15=OPTmodel.addConstr(Pbess_in_[i] == 0,name='CON15')
CON16=OPTmodel.addConstr(Pbess_flex_[i] == Pbess_in_[i] + Pbess_out_[i],name='CON16')
OPTmodel.update()
ConPDC = OPTmodel.addConstr(Pdc[i] == Pflex_i[i] + float(ITload[i]), name='ConPDC')
# OPTmodel.addConstr(Tdc_i[i]==(ki*Tdc_i[i-1]+(ko*Tamb)))
#for x in Ebess_i:
#ConEBESS2 = OPTmodel.addConstr(Ebess_i[i] ==((Pbess_in[i] / 0.75) + (Pbess_out[i] * 0.75)))
cooling = np.array(pd.read_csv('Pcooling.csv'))
DRR = pd.read_csv('DR.csv')
DR = DRR.values
IT = pd.read_csv('ITpower.csv')
ITload = IT.values
newList = map(lambda x: x / 1000, ITload)
PH = pd.read_csv('Pcooling.csv')
PHVAC = PH.values
newList2 = map(lambda x: x / 1000, PHVAC)
#for y in Tdc_i:
T=pd.read_csv('TT.csv').values
OPTmodel.addConstr(Tdc_i[i]==((ki*float(T[i]))+(ko*Tamb)+(kc*float(newList[i]))-((kp*(float(newList2[i])))+(Phvac_flex[i]*3.14))))
print Tdc_i.values()
OPTmodel.addConstr(Pbess_out_[i]<=Phvac_flex[i] + Pbess_flex[i]<=Pbess_in_[i])
# Tdc_i[1:len(i)]==(Ki*Tdc_i[1:1438])+(Kc*array2[1:1438])+(Ko*Tamb))
ConBESS5 = OPTmodel.addConstr(Pbess_flex[i] == Pbess_in[i] + Pbess_out[i], name='ConBESS5')
#OPTmodel.addConstr(defIT[i]==DeferableLoad.j2 + DeferableLoad.j3)
# OPTmodel.addConstr(Pdc_base[i]==predictions[i])
ConFLEX = OPTmodel.addConstr(Pflex_i[i] == Pbess_flex[i] + Phvac_flex[i], name='ConFLEX')
PcoolingPredicted = pd.read_csv('PcoolingPredictionResult.csv')
PcoolingPredictedValue = PcoolingPredicted.values
ITPredicted = pd.read_csv('ITpredictionResult.csv')
ITPredictedValue = ITPredicted.values
ConPDCbase = OPTmodel.addConstr(Pdc_base[i] == np.transpose(ITPredictedValue[i]) + np.transpose(PcoolingPredictedValue[i]))
OPTmodel.update()
# OPTmodel.addConstr(Pdc_base[i]==prediction[i])
OPTmodel.setObjective((np.transpose(Pdc_base[i])-float(DR[i]) - (Pdc[i]) ), GRB.MINIMIZE)
OPTmodel.update()
OPTmodel.optimize()
print Pdc_base[i].X
#print Ebess_i[i].X
#print Phvac_flex[i].X
print Tdc_i[i]
print Pdc[i]
print Phvac_flex[i]
print Pbess_flex[i]
print Pbess_out[i]
print Pbess_in[i]
print Ebess_i[i]
print Pbess_flex_[i]
print Phvac_down[i]
print Phvac_up[i]
'''
def get_results(self):
"""
This function gets the results of the current optimization model
Returns
-------
"""
HVACresult = np.zeros(1,N)
BatteryResult = np.zeros(1,N)
SOC = np.zeros(1,N)
#r_Q_dot = np.zeros((self.gp.N_H, self.N_S))
#r_P = np.zeros((self.gp.N_H, self.N_S))
#r_P_self = np.zeros((self.gp.N_H, self.N_S))
#r_P_ex = np.zeros((self.gp.N_H, self.N_S))
#r_Q_dot_gas = np.zeros((self.gp.N_H, self.N_S))
#Load = np.zeros((self.gp.N_H, self.N_S))
try:
for t in range(1,N):
HVACresult[t]= Phvac_flex[t].X
BatteryResult[t]=Pbess_flex[t].X
SOC[t] = Ebess_i[t].X / Ebess_max
except:
pass
return { 'SOC' : SOC , 'BatteryResult': BatteryResult }
print OPTmodel.getVars()
# get results
Temp = {}
Battery = {}
Ebess_result = {}
ITloadd = {}
for t in range(1,N):
Temp[t] = OPTmodel.getVarByName("Tdc_i" )
Battery[t] = OPTmodel.getVarByName("PBESS_flex" )
Ebess_result[t] = OPTmodel.getVarByName("Ebess_i" )
#r_P_e[t] = model.getVarByName("P_export_%s_0" % t).X
fig, axes = plt.subplots(4, 1)
# plot elctricity
ax5 = axes[2]
ax6 = ax5.twinx()
ax5.plot( [Temp[t] for t in range(1,N)], 'g-')
ax6.plot([Ebess_result[t] for t in range(1,N)], 'b-')
ax5.set_xlabel('Time index')
ax5.set_ylabel('Power Import [W]', color='g')
ax6.set_ylabel('Power CHP [W]', color='b')
ax7 = axes[3]
ax7.plot([Battery[t] for t in range(1,N)], 'g-')
ax7.set_ylabel('Power Export [W]', color='g')
'''
print Pflex_i.values()
# print OPTmodel.getVars()
print OPTmodel.feasibility()
print OPTmodel.getObjective()
print Pdc_base.values()
'''
b = map(float, Phvac_flex)
plt.plot(b)
plt.show()
'''
#c = map(float, Pbess_flex_)
#plt.plot(c)
#plt.show()
print OPTmodel
print Tdc_i.values()
# get results
print OPTmodel.getVars()
# print OPTmodel.getAttr('EBESS_i')
status = OPTmodel.status
print status
# print Con10,Con12
print Phvac_flex.values()
print Pbess_flex.values()
print Ebess_i.values()
print OPTmodel.objval
print Tdc_i
print Pbess_in
print Pbess_out.values()
# print Pbess_flex
# print Phvac_flex
# print Ebess_i
print Pflex_i.values()
print Pbess_flex_.values()
#print OPTmodel.getVars()
print OPTmodel.feasibility()
print OPTmodel.getObjective()
print Ebess_i.values()
if OPTmodel.status == GRB.Status.INF_OR_UNBD:
# Turn presolve off to determine whether model is infeasible
# or unbounded
OPTmodel.setParam(GRB.Param.Presolve, 0)
OPTmodel.optimize()
OPTmodel.write("mymodel.lp")
if OPTmodel.status == GRB.Status.OPTIMAL:
print('Optimal objective: %g' % OPTmodel.objVal)
OPTmodel.write('model.sol')
exit(0)
elif OPTmodel.status != GRB.Status.INFEASIBLE:
print('Optimization was stopped with status %d' % OPTmodel.status)
exit(0)
# Model is infeasible - compute an Irreducible Inconsistent Subsystem (IIS)
print('')
print('Model is infeasible')
OPTmodel.computeIIS()
OPTmodel.write("model.ilp")
print("IIS written to file 'model.ilp'")
I want to plot the computed values from gurobi but when I want to get the X attribute of gurobi variable it says that AttributeError: it has no attribute 'X' and the when I cast the value from float to int it just showed me the empty plot but at the lp file I could see the result of each iteration
I am anxiously waiting for your response
cherrs

Cannot Scatter, Plot, Show() In While Loop

import math
import pylab as plt
import numpy
from numpy import sqrt
from scipy.integrate import quad
import random
numpy.seterr(divide='ignore', invalid='ignore')
def integrand (x):
return sqrt(1-x**2)
q1area, err = quad(integrand,0,1)
print "This program estimates the convergence of Pi to a ratio of one."
while True:
print "Please choose from one of the five following options:"
print " 1. 10^1\n 2. 10^2\n 3. 10^3\n"
choice = int(raw_input())
options = {1,2,3}
if choice == 1:
plt.xlim([0,15])
plt.ylim([-5,5])
x = numpy.linspace(0,15,500)
y = numpy.sqrt(1-x**2)
z = 1+x*0
xcord = []
ycord = []
under = []
above = []
pratiolist = []
yvalues = []
xvalues = range(1,11)
for i in range(10):
xcord.append(random.random())
ycord.append(random.random())
for j in ycord:
if (j <= q1area):
under.append(1)
else:
above.append(1)
punder = len(under)
if punder == 0:
punder = punder + 1
pabove = len(above)
if pabove == 0:
pabove = pabove + 1
pratio = punder / float(pabove)
pratiolist.append(pratio)
for k in pratiolist:
rtpi = k / float(math.pi)
yvalues.append(rtpi)
plt.scatter(xvalues,yvalues,c='b')
plt.plot(x,z,'g')
plt.show()
if choice == 2:
plt.xlim([0,110])
plt.ylim([-5,5])
x = numpy.linspace(0,110,500)
y = numpy.sqrt(1-x**2)
z = 1+x*0
xcord = []
ycord = []
under = []
above = []
pratiolist = []
yvalues = []
xvalues = range(1,101)
for i in range(100):
xcord.append(random.random())
ycord.append(random.random())
for j in ycord:
if (j <= q1area):
under.append(1)
else:
above.append(1)
punder = len(under)
if punder == 0:
punder = punder + 1
pabove = len(above)
if pabove == 0:
pabove = pabove + 1
pratio = punder / float(pabove)
pratiolist.append(pratio)
for k in pratiolist:
rtpi = k / float(math.pi)
yvalues.append(rtpi)
plt.scatter(xvalues,yvalues,c='b')
plt.plot(x,z,'g')
plt.show()
if choice == 3:
plt.xlim([0,1100])
plt.ylim([-5,5])
x = numpy.linspace(0,1100,500)
y = numpy.sqrt(1-x**2)
z = 1+x*0
xcord = []
ycord = []
under = []
above = []
pratiolist = []
yvalues = []
xvalues = range(1,1001)
for i in range(1000):
xcord.append(random.random())
ycord.append(random.random())
for j in ycord:
if (j <= q1area):
under.append(1)
else:
above.append(1)
punder = len(under)
if punder == 0:
punder = punder + 1
pabove = len(above)
if pabove == 0:
pabove = pabove + 1
pratio = punder / float(pabove)
pratiolist.append(pratio)
for k in pratiolist:
rtpi = k / float(math.pi)
yvalues.append(rtpi)
plt.scatter(xvalues,yvalues,c='b')
plt.plot(x,z,'g')
plt.show()
while choice not in options:
print "Not a valid choice!\n"
break
#plt.scatter(xvalues,yvalues,c='b')
#plt.plot(x,z,'g')
#plt.show()
The only way I can get the graphs to show is if I place break statements at the end of every if choice == 1,2,3, etc. and then place:
plt.scatter(xvalues,yvalues,c='b')
plt.plot(x,z,'g')
plt.show()
At the bottom of my code. This is inconvenient, I would like my to loop endlessly allowing choice between 1,2,3 without having to rerun the program. Why does Python's graphs crash when they are in whiles?
UPDATE
By using plt.draw(), I was able to get the graph to at least show but it still is not responding.
If by not responding you mean it doesn't show the prompt again this is because plt.show() will cause the program to stop until the window is closed. You can replace the plt.show()'s with plt.draw(), but to actually have windows come up you need to be in interactive mode. This is accomplished by calling plt.ion() sometime before any of the draw calls (I put it before the while True:). I've tested it an this should accomplish the behavior you're looking for.
Edit: Since you aren't redrawing the same data, calling draw() will append the data to the specific plot (i.e. typing 1 in over and over will keep adding points). I don't know what type of behavior you're looking for but you may want to call plt.clf before each scatter call if you want to clear the figure.

Why does my GUI go unresponsive even though I'm outsourcing to a worker thread?

I have a PyQt4 GUI in which I need to save a stack of Numpy arrays as *.tif images. This seems to take a significant amount of time and causes my GUI to go unresponsive for up to several minutes, depending on the number of images in the stack.
The bulk of the processing happens in this loop over the images:
for i in range(0, np.shape(dataStack)[2]):
print('Saving slice ' + str(i + 1))
#Save tumor stack
im1 = Image.fromarray(tumorStack[:,:,i]*255)
im1.save(saveLocationStr + 'Slice' + str(i+1) + '.tif')
#Set up correct number of subplots for review plot.
if T0 is not None:
plt.subplot(141)
else:
plt.subplot(131)
#Plot current brain slice in 1st position
plt.imshow(dataStack[:,:,i], cmap=mpl.cm.bone)
plt.axis('off')
plt.title(patient + '\n' + date + '\n' + 'Slice ' + str(i+1) + ' of ' + str(int(np.shape(dataStack)[2])))
#Select correct next subplot
if T0 is not None:
plt.subplot(142)
else:
plt.subplot(132)
#Get a masked copy of the tumorStack
tempTumorStack = copy.deepcopy(tumorStack[:,:,i])
tempTumorStack = np.ma.masked_where(tempTumorStack == 0, tempTumorStack)
#Plot masked tumor stack over brain data
plt.imshow(dataStack[:,:,i], cmap=mpl.cm.bone)
plt.imshow(tempTumorStack, cmap=mpl.cm.jet_r, interpolation='nearest')
plt.axis('off')
plt.title(modality + ' Region')
#Get the auto-zoomed region and plot it
(x, y) = tumorStack[:,:,i].nonzero()
if( int(np.shape(x)[0]) == 0 or int(np.shape(y)[0]) == 0):
if T0 is not None:
plt.subplot(143)
plt.imshow(T0[:,:,i], cmap=mpl.cm.bone)
plt.axis('off')
plt.title('T0')
#Plot autozoomed with perimiter over brain data
plt.subplot(144)
plt.imshow(np.zeros(np.shape(dataStack[:,:,i])), cmap=mpl.cm.bone)
plt.title('Perimiter of \n' + modality + ' + T0 for SA')
plt.axis('off')
else:
plt.subplot(133)
plt.imshow(np.zeros(np.shape(dataStack[:,:,i])), cmap=mpl.cm.bone)
plt.title('Perimiter of \n' + modality + ' for SA')
plt.axis('off')
else:
minX = np.min(x)
minY = np.min(y)
maxX = np.max(x)
maxY = np.max(y)
zoomedXmin = minX - (minX * .10)
zoomedXmax = (maxX * .10) + maxX
zoomedYmin = minY - (minY * .10)
zoomedYmax = (maxY * .10) + maxY
widthOf = zoomedXmax - zoomedXmin
heigthOf = zoomedYmax - zoomedYmin
#Get perimiter of tumor for autozoomed region
#Can do n=8 if we want
#tempTumorStack = bwperim(tempTumorStack,n=8)
tempTumorStack = mahotas.labeled.borders(tempTumorStack)
tempTumorStack = np.where(tempTumorStack == np.max(tempTumorStack), 1, np.nan)
#Plot T0 then auto-zoomed if user wanted T0
if T0 is not None:
plt.subplot(143)
plt.imshow(T0[:,:,i], cmap=mpl.cm.bone)
plt.axis('off')
plt.title('T0')
#Plot autozoomed with perimiter over brain data
plt.subplot(144)
plt.imshow(dataStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax), i ], cmap=mpl.cm.bone)
plt.imshow(tempTumorStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax) ], cmap=mpl.cm.jet_r)
#plt.xlim(minX, maxX-minX)
#plt.ylim(minY, maxY-minY)
plt.title('Perimiter of \n' + modality + ' + T0 for SA')
plt.axis('off')
#Just plot autozoomed
else:
plt.subplot(133)
plt.imshow(dataStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax), i ], cmap=mpl.cm.bone)
plt.imshow(tempTumorStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax) ], cmap=mpl.cm.jet_r)
plt.title('Perimiter of \n' + modality + ' for SA')
plt.axis('off')
#Finish setting up plot to specs, render, and save it
plt.subplots_adjust(wspace=.5)
plt.axis('off')
plt.tick_params(bottom='off', top='off', left='off', right='off')
plt.draw()
plt.savefig(saveLocationStr + 'MRI_Comparison\\Slice' + str(i+1) + '.png', dpi=200)
I figured I would outsource the expensive work to a PyQt4 worker QThread, so following the example at http://diotavelli.net/PyQtWiki/Threading,_Signals_and_Slots I created a worker class that inherits from QtCore.QThread, called all the above code inside the run method of this class, and created and start()ed an instance of this class where the *.tif stack saving needs to occur in the main window.
The GUI still goes unresponsive as it did previously, but the thread seems to be successfully executing the code. I am concerned that perhaps some package used in the code above is not properly releasing the GIL (as referenced here http://www.riverbankcomputing.com/pipermail/pyqt/2011-August/030470.html). Is there a way to manually ensure this is working?
I have commented out and replaced the *.tif stack saving code with a time.sleep delay, and the GUI still goes unresponsive, so perhaps I am implementing QThread wrong?
Am I missing something else? Have I provided enough information?
edit:
I create the thread in the main window here:
# create instance of saveImageStackWorker(QThread) thread class
self.saveThread = brain_io.saveImageStackWorker()
self.saveThread.populate(self.tumorBrain.pixData, self.tumorBrain.tumor, saveLocationStr, self.measurer, self.tumorBrain.patient, dateForPlots, imageModality, T0pass)
And here is the entire worker thread class I defined, where the function saveImageStack(args) is the same *.tif saving code I provided above:
class saveImageStackWorker(QThread):
"""
"""
def __init__(self, parent=None):
QThread.__init__(self, parent)
def __del__(self):
self.wait()
def populate(self, dataStack, tumorStack, saveLocationStr, measurer, patient, date, modality, T0):
self.dataStack = dataStack
self.tumorStack = tumorStack
self.saveLocationStr = saveLocationStr
self.measurer = measurer
self.patient = patient
self.date = date
self.modality = modality
self.T0 = T0
self.start()
def run(self):
self.saveImageStack(self.dataStack, self.tumorStack, self.saveLocationStr, self.measurer, self.patient, self.date, self.modality, self.T0)
def saveImageStack(self, dataStack, tumorStack, saveLocationStr, measurer, patient, date, modality, T0): #, dateStr, measurer,, saveLocationStr):
"""
Input:
dataStack:
numpy array of the brain image data.
tumorStack:
numpy binary array of tumor data.
modality:
the modality of the image.
T0:
numpy binary array of T0, if you do not
wish to show T0 (i.e. for flair or something)
leave as default None.
Output:
None
Description:
Saves the image stack of tumor and the review plots
to the output directory.
"""
print('Saving image stack from within worker thread...')
font = {'size' : 10}
matplotlib.rc('font', **font)
np.seterr(all='ignore')
warnings.simplefilter('ignore')
for i in range(0, np.shape(dataStack)[2]):
print('Saving slice ' + str(i + 1))
#Save tumor stack
im1 = Image.fromarray(tumorStack[:,:,i]*255)
im1.save(saveLocationStr + 'Slice' + str(i+1) + '.tif')
#Set up correct number of subplots for review plot.
if T0 is not None:
plt.subplot(141)
else:
plt.subplot(131)
#Plot current brain slice in 1st position
plt.imshow(dataStack[:,:,i], cmap=mpl.cm.bone)
plt.axis('off')
plt.title(patient + '\n' + date + '\n' + 'Slice ' + str(i+1) + ' of ' + str(int(np.shape(dataStack)[2])))
#Select correct next subplot
if T0 is not None:
plt.subplot(142)
else:
plt.subplot(132)
#Get a masked copy of the tumorStack
tempTumorStack = copy.deepcopy(tumorStack[:,:,i])
tempTumorStack = np.ma.masked_where(tempTumorStack == 0, tempTumorStack)
#Plot masked tumor stack over brain data
plt.imshow(dataStack[:,:,i], cmap=mpl.cm.bone)
plt.imshow(tempTumorStack, cmap=mpl.cm.jet_r, interpolation='nearest')
plt.axis('off')
plt.title(modality + ' Region')
#Get the auto-zoomed region and plot it
(x, y) = tumorStack[:,:,i].nonzero()
if( int(np.shape(x)[0]) == 0 or int(np.shape(y)[0]) == 0):
if T0 is not None:
plt.subplot(143)
plt.imshow(T0[:,:,i], cmap=mpl.cm.bone)
plt.axis('off')
plt.title('T0')
#Plot autozoomed with perimiter over brain data
plt.subplot(144)
plt.imshow(np.zeros(np.shape(dataStack[:,:,i])), cmap=mpl.cm.bone)
plt.title('Perimiter of \n' + modality + ' + T0 for SA')
plt.axis('off')
else:
plt.subplot(133)
plt.imshow(np.zeros(np.shape(dataStack[:,:,i])), cmap=mpl.cm.bone)
plt.title('Perimiter of \n' + modality + ' for SA')
plt.axis('off')
else:
minX = np.min(x)
minY = np.min(y)
maxX = np.max(x)
maxY = np.max(y)
zoomedXmin = minX - (minX * .10)
zoomedXmax = (maxX * .10) + maxX
zoomedYmin = minY - (minY * .10)
zoomedYmax = (maxY * .10) + maxY
widthOf = zoomedXmax - zoomedXmin
heigthOf = zoomedYmax - zoomedYmin
#Get perimiter of tumor for autozoomed region
#Can do n=8 if we want
#tempTumorStack = bwperim(tempTumorStack,n=8)
tempTumorStack = mahotas.labeled.borders(tempTumorStack)
tempTumorStack = np.where(tempTumorStack == np.max(tempTumorStack), 1, np.nan)
#Plot T0 then auto-zoomed if user wanted T0
if T0 is not None:
plt.subplot(143)
plt.imshow(T0[:,:,i], cmap=mpl.cm.bone)
plt.axis('off')
plt.title('T0')
#Plot autozoomed with perimiter over brain data
plt.subplot(144)
plt.imshow(dataStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax), i ], cmap=mpl.cm.bone)
plt.imshow(tempTumorStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax) ], cmap=mpl.cm.jet_r)
#plt.xlim(minX, maxX-minX)
#plt.ylim(minY, maxY-minY)
plt.title('Perimiter of \n' + modality + ' + T0 for SA')
plt.axis('off')
#Just plot autozoomed
else:
plt.subplot(133)
plt.imshow(dataStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax), i ], cmap=mpl.cm.bone)
plt.imshow(tempTumorStack[int(zoomedXmin):int(zoomedXmax), int(zoomedYmin):int(zoomedYmax) ], cmap=mpl.cm.jet_r)
plt.title('Perimiter of \n' + modality + ' for SA')
plt.axis('off')
#Finish setting up plot to specs, render, and save it
plt.subplots_adjust(wspace=.5)
plt.axis('off')
plt.tick_params(bottom='off', top='off', left='off', right='off')
plt.draw()
plt.savefig(saveLocationStr + 'MRI_Comparison\\Slice' + str(i+1) + '.png', dpi=200)
edit #2:
Adding the code for the method in the main window that starts the thread -
def uploadAndSave(self):
[db, unused] = initGUI.getDbDataBetter()
self.db = db
subtypeID = str(self.dbImage.image_subtype_id.toString())
query = QtSql.QSqlQuery("SELECT subtype_name FROM image_subtypes where "
+ "id = " + subtypeID, self.db)
query.next()
imageModality = str(query.value(0).toString())
dateForPlots = str(self.dbImage.date_of_image.toString()).replace('T',' ')
date = dateForPlots.replace('-','').replace(':','.')
basePath = 'S:\Lab_KSwanson\MRI Project\Test measurements\\' + self.tumorBrain.patient + '\\' + self.measurer + '\\' + date + '\\'
print('Saving images...')
seriesDescription = str(self.dbImage.series_description.toString())
saveLocationStr = brain_io.createOutputFilepath(basePath, seriesDescription, imageModality)
if imageModality.upper().find('T1') < 0:
T0pass = None
else:
T0pass = self.tumorBrain.T0
operation_time = datetime.datetime.now().isoformat().replace('T',' ')[0:19]
# create instance of saveImageStackWorker(QThread) thread class
self.saveThread = brain_io.saveImageStackWorker()
self.saveThread.populate(self.tumorBrain.pixData, self.tumorBrain.tumor, saveLocationStr, self.measurer, self.tumorBrain.patient, dateForPlots, imageModality, T0pass)
# brain_io.saveImageStack(self.tumorBrain.pixData, self.tumorBrain.tumor, saveLocationStr, self.measurer, self.tumorBrain.patient, dateForPlots, imageModality, T0pass)
self.tumorBrain.save(saveLocationStr + date + '.dat')
[db, unused] = initGUI.getDbDataBetter()
query = QtSql.QSqlQuery('SELECT file_path FROM measurements m WHERE m.user_id = ' + self.userIDStr + ' AND m.image_id = '
+ str(self.dbImage.id.toString()) + ' AND m.status = "R"', db)
#If there was a rejected measurement, this will return True
remeasure = query.next()
print('Computing volume, surface area, etc...')
T1 = algorithms.vtk_stats(self.tumorBrain.tumor,
spacing=(self.tumorBrain.xSpacing,
self.tumorBrain.ySpacing,
np.mean(self.tumorBrain.SliceThickness)))
T0 = algorithms.vtk_stats(self.tumorBrain.T0,
spacing=(self.tumorBrain.xSpacing,
self.tumorBrain.ySpacing,
np.mean(self.tumorBrain.SliceThickness)))
mass = tvtk.MassProperties(input=T1.output)
T0mass = tvtk.MassProperties(input=T0.output)
#mySA = algorithms.calculateSurfaceArea(self.tumorBrain.tumor,
# self.tumorBrain.xSpacing,
# self.tumorBrain.ySpacing,
# self.tumorBrain.SliceThickness)
#mySAT0 = algorithms.calculateSurfaceArea(self.tumorBrain.T0,
# self.tumorBrain.xSpacing,
# self.tumorBrain.ySpacing,
# self.tumorBrain.SliceThickness)
#print('mysa = ' + str(mySA))
#area = 0
#for i in range(0, int(self.tumorBrain.tumor.shape[2])):
# tumor_filt = self.tumorBrain.tumor[:,:,i]
# currThreshold = self.thresholdList[i]
# tumor_filt = np.where(tumor_filt > currThreshold, 1, 0)
# area = area + np.sum(np.sum(tumor_filt))
#myVolumeT1 = np.sum(self.tumorBrain.xSpacing**2 * area * self.tumorBrain.SliceThickness)
myVolumeT1 = mass.volume
#T0sum = np.sum(np.sum(np.sum(self.tumorBrain.T0)))
#myVolumeT0 = np.sum(self.tumorBrain.xSpacing**2 * T0sum * self.tumorBrain.SliceThickness)
myVolumeT0 = T0mass.volume
myVolume_T0_T1 = myVolumeT1 + myVolumeT0
T0_radius = ((3.0*(myVolumeT0))/(4.0*math.pi))**(1.0/3.0)
T0_T1_radius = ((3.0*(myVolume_T0_T1))/(4.0*math.pi))**(1.0/3.0)
#print('volume vtk = ' + str(mass.volume))
#print('my volume = ' + str(myVolume_T0_T1))
#print('my radius = ' + str(T0_T1_radius))
if mass.volume + T0mass.volume == 0 or mass.surface_area == 0:
circularity = 0
else:
circularity = ((math.pi)**(1.0/3.0))*((6.0*(myVolume_T0_T1))**(2.0/3.0) / mass.surface_area)
print('SA = ' + str(mass.surface_area))
print('T0 SA = ' + str(T0mass.surface_area))
print('Volume = ' + str(myVolume_T0_T1))
print('T0 Volume = ' + str(myVolumeT0))
print('Radius = ' + str(T0_T1_radius))
print('T0 Radius = ' + str(T0_radius))
print('Circularity = ' + str(circularity))
# Ask to see rendering
msgBox = QtGui.QMessageBox(QtGui.QMessageBox.Question, QtCore.QString('Render'), QtCore.QString('Show Tumor Rendering?'), QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
ret = msgBox.exec_()
if ret == QtGui.QMessageBox.Yes:
algorithms.render_surface(T1, T0)
query = QtSql.QSqlQuery('select max(group_id) from ' +
'measurement_audit_log where measurement_type_id = '
+ "'1'", db)
query.next()
group_id = str(query.value(0).toInt()[0] + 1)
# Check for a measurement assignment.
osUserName = os.environ.get("USERNAME").lower()
query = QtSql.QSqlQuery('SELECT id from users where pathology_user_name = "' + osUserName + '"')
query.next()
user_id = str(query.value(0).toInt()[0])
query = QtSql.QSqlQuery('select id from ' +
'measurement_assignments_audit ' +
'where image_id = ' + str(self.dbImage.id.toString()) + ' ' +
'and measurer_id = ' + user_id + ' ' +
'and status = "P"')
assignment = query.next()
date_of_completion = operation_time[0:10]
if not assignment:
# Create a new assignment
newAssignmentQuery = ('insert into measurement_assignments_audit ' +
'(measurement_assignment_id, assigner_id, measurer_id, image_id, patient_id, date_of_assignment, ' +
'comments, date_of_completion, priority, measurement_group_id, operation_user_id, operation_code, ' +
'operation_time, status) values (0, ' + user_id + ', ' + user_id + ', ' + str(self.dbImage.id.toString()) + ', ' +
str(self.dbImage.patient_id.toString()) + ', "' + date_of_completion + '", ' + '"Self-assigned through brainsegment", "' +
date_of_completion + '", 2, ' + group_id + ', ' + user_id + ', "I", "' + operation_time + '", "P")')
query = QtSql.QSqlQuery(newAssignmentQuery)
else:
# Update the assignment
updateAssignmentQuery = ('update measurement_assignments_audit set date_of_completion = "' + date_of_completion + '", ' +
'measurement_group_id = ' + group_id + ' where id = ' + str(query.value(0).toInt()[0]))
query = QtSql.QSqlQuery(updateAssignmentQuery)
brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 1, 1, T0_T1_radius, saveLocationStr + 'MRI_Comparison', operation_time, str(self.dbImage.id.toString()), group_id)
brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 2, 2, myVolume_T0_T1, saveLocationStr + 'MRI_Comparison', operation_time, str(self.dbImage.id.toString()), group_id)
brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 7, 3, mass.surface_area, saveLocationStr + 'MRI_Comparison', operation_time, str(self.dbImage.id.toString()),group_id)
brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 11, 11, circularity, saveLocationStr + 'MRI_Comparison', operation_time, str(self.dbImage.id.toString()),group_id)
if T0pass is not None:
query = QtSql.QSqlQuery('SELECT image_file_path from images i where i.id = ' + str(self.dbImage.id.toString()), db)
query.next()
#print('SELECT i.image_file_path from images i where i.id = ' + str(self.dbImage.id.toString()))
image_file_path = str(query.value(0).toString()).replace('\\','\\\\')
query = QtSql.QSqlQuery('SELECT id from images i where i.image_file_path = "' + image_file_path + '" and i.image_subtype_id in (14, 15, 20, 21) ', db)
#print('SELECT id from images i where i.image_file_path = "' + image_file_path + '" and i.image_subtype_id in (14, 15, 20, 21) ')
query.next()
T0idStr = str(query.value(0).toString())
T0radius = ((3.0*T0mass.volume)/(4.0*math.pi))**(1.0/3.0)
brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 1, 1, T0_radius, saveLocationStr + 'MRI_Comparison', operation_time, T0idStr, group_id)
brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 2, 2, myVolumeT0, saveLocationStr + 'MRI_Comparison', operation_time, T0idStr, group_id)
brain_io.uploadMeasurement(self.dbImage, self.db, self.version, self.tumorBrain.patient, remeasure, 7, 3, T0mass.surface_area, saveLocationStr + 'MRI_Comparison', operation_time, T0idStr, group_id)
Be sure to generate your images in the backend with matplotlib.use('Agg')
There is some ordering requirement to call the matplotlib.use() prior to the pyplot.
http://matplotlib.org/faq/howto_faq.html
Generate images without having a window appear
The easiest way to do this is use a non-interactive backend (see What is a backend?) such as Agg (for PNGs), PDF, SVG or PS. In your figure-generating script, just call the matplotlib.use() directive before importing pylab or pyplot:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')
If processing an image takes a long time, you should use a multiprocessing.Pool.
For this to work, you should create a list (or other iterable) with data for each image. And you should create a function from the processing code you wrapped in a loop.
Next you use the pools' map_async method to apply the function to all the images. This will execute in different processes, so it shouldn't bother the GUI. As a bonus, it will use all the CPU cores in your machine to do the work.

Categories

Resources