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
Related
I am want to replace a specific part of the string while using textwrap. But I am getting an unwanted line break. I have tried a lot of ways but still, it is not working. here is my code.
import textwrap
import math
def wrap(string, max_width):
wrapper = textwrap.TextWrapper(width = max_width)
word_list = wrapper.fill(text = string)
return word_list
height, width = map(int,input().split())
square = height * width
i = 0
x = []
while i < square:
x.append("-")
i += 1
k = 0
while k < math.floor(height / 2):
line = math.floor(width / 2) + width * k
x[line] = '|'
x[line + 1]= "."
x[line - 1] = "."
for h in range(1, k + 1):
f = h * 3
line_plus = line + f
line_minus = line - f
x[line_plus] = '|'
x[line_minus] = '|'
x[line_minus - 1] = '.'
x[line_plus - 1] = '.'
x[line_minus + 1] = '.'
q = line_plus + 1
x[q] = '.'
k += 1
a = 0
while a < math.floor(height / 2):
line = math.floor(width / 2) + width * a
line_end = (math.floor(width / 2) + width * a) * (-1)
x[line_end - 1] = '|'
if line > width:
x[line_end + 2] = '|'
x[line_end - 4] = '|'
a += 1
listToStr = ''.join([str(elem) for elem in x])
welcome_pos = math.floor(height / 2) * width + (math.floor(width / 2) - math.floor(7 / 2))
s = listToStr[ 0: welcome_pos] + "welcome" + listToStr[welcome_pos + 7:]
print(wrap(listToStr, width) + "\n")
print(wrap(s, width))
my input is 7 21
Output:
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.
----------welcome----
----------|--|--|----
----------|--|--|----
-------------|-------
---
this is my output. But it is giving a space at line 3 which I don't want. I don't know why this is happening. Please help me.
Maybe this is what you want?
code:
#(above the same)
print(wrap(listToStr,width*height))
print(wrap(s,width*height))
result:
5 4
-..|..|..||--|--||--
-..|..|welcome--||--
I am trying to store the values obtained from excel sheet cells to a list. The code provided basically collects data from different continuous rows and columns and creates a string of those values. I could work upt o storing the string value but I don't really know how to store the strings in a list, Can anyone help me with this?
for i in range(NR):
print("This TC checks the output for")
for j in range(NC):
inputVariable = str(ws[get_column_letter(ColumnStart+j) + str(rowStart-1)].value)
c = str((ws.cell(row = (rowStart + i),column = (ColumnStart +j)).value))
if (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MaxValRow),column = (ColumnStart+j)).value):
b = '(maximum)'
elif (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MinValRow),column = (ColumnStart+j)).value):
b = '(minimum)'
else:
b ='(intermediate)'
Commentstr = str(j+1) + '. The value of input ' + inputVariable + ' =' + " " + c + b
# need to create a list here to store the commentstr for each iteration
NR = no. of rows, NC = no. of columns
my_list=[]
for i in range(NR):
x=0
print("This TC checks the output for")
for j in range(NC):
inputVariable = str(ws[get_column_letter(ColumnStart+j) + str(rowStart-1)].value)
c = str((ws.cell(row = (rowStart + i),column = (ColumnStart +j)).value))
if (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MaxValRow),column = (ColumnStart+j)).value):
b = '(maximum)'
elif (ws.cell(row = (rowStart + i),column = (ColumnStart+j)).value) == (ws.cell(row = (MinValRow),column = (ColumnStart+j)).value):
b = '(minimum)'
else:
b ='(intermediate)'
Commentstr = str(j+1) + '. The value of input ' + inputVariable + ' =' + " " + c + b
my_list[x]=Commentstr
x+=1
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)
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
I am very new to python, and I have been playing around with image editing using the PIL thing. I came up with a code that is supposed to take an image, and break it into 5x10 pixel blocks, and replace each with the average rgb values for that block I tried to do this by increasing x, y by 10,5 respectively, recording the rgb values for each pixel, averaging them, and allocating them to all the pixels in the block.
However, for all my code, the picture is not changing whatsoever.
I HAVE NO IDEA WHY????
Heres the code:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import time
def Edit(iar):
balanceAr = []
newAR = iar
global x
global y
x = 1
y = 1
for eachRow in newAR[::5]:
Pixx = Pix
x1 = x
del x
x = x1
y1 = y
del y
vr1 = Pixx[x1,y1]
vr2 = Pixx[x1,y1 + 1]
vr3 = Pixx[x1,y1 + 2]
vr4 = Pixx[x1,y1 + 3]
vr5 = Pixx[x1,y1 + 4]
yValRAv = int((vr1[0] + vr2[0] + vr3[0] + vr4[0] + vr5[0])/5)
yValGAv = int((vr1[1] + vr2[1] + vr3[1] + vr4[1] + vr5[1])/5)
yValBAv = int((vr1[2] + vr2[2] + vr3[2] + vr4[2] + vr5[2])/5)
for eachPix in eachRow:
x = 1
y = 1
Pixx = Pix
x1 = x
del x
y1 = y
del y
y = y1
vr1 = Pixx[x1,y1]
vr2 = Pixx[x1,y1 + 1]
vr3 = Pixx[x1,y1 + 2]
vr4 = Pixx[x1,y1 + 3]
vr5 = Pixx[x1,y1 + 4]
vr6 = Pixx[x1,y1 + 5]
vr7 = Pixx[x1,y1 + 6]
vr8 = Pixx[x1,y1 + 7]
vr9 = Pixx[x1,y1 + 8]
vr10 = Pixx[x1,y1 + 9]
xValRAv = int((vr1[0] + vr2[0] + vr3[0] + vr4[0] + vr5[0] + vr6[0] + vr7[0] + vr8[0] + vr9[0] + vr10[0])/10)
xValGAv = int((vr1[1] + vr2[1] + vr3[1] + vr4[1] + vr5[1] + vr6[0] + vr7[0] + vr8[0] + vr9[0] + vr10[0])/10)
xValBAv = int((vr1[2] + vr2[2] + vr3[2] + vr4[2] + vr5[2] + vr6[0] + vr7[0] + vr8[0] + vr9[0] + vr10[0])/10)
ValRAv = int((xValRAv + yValRAv)/2)
ValGAv = int((xValGAv + yValGAv)/2)
ValBAv = int((xValBAv + yValBAv)/2)
for count in range(5):
for counter in range(10):
Pixx = Pix
Pixx[(x1 + counter), (y1 + count)] = (ValRAv, ValGAv, ValBAv)
x = x1 + 10
y = y1 + 5
return newAR
iar = newAR
i = Image.open('speaker8.png')
iar = np.array(i)
width, height = i.size
Pix = i.load()
Edit(iar)
fig = plt.figure()
ax1 = plt.subplot2grid((8,6), (0,0), rowspan=20, colspan=15)
ax1.imshow(iar)
plt.show()
Please note that much of this code has been pieced together from exerts of tutorials, so may not be used in the correct way?
Thanks!