How to print the time of execution PYTHON - python
I have this code, but I want to print the time that a specific part of it takes.
The block of code that I want to know the time is between:
def TSP(lista2d):
import copy
origen = input("Ciudad de origen: ")
resultado = [int(origen)]
iteracion, indicador = int(origen) - 1, 0
distancia, copia = [], copy.deepcopy(lista2d)
for j in range(1, len(lista2d)):
for x in range(len(lista2d)):
lista2d[x][iteracion] = 999
distancia.append(min(lista2d[iteracion]))
for i in range(len(lista2d)):
if min(lista2d[iteracion]) == lista2d[iteracion][i]:
indicador = i
lista2d[indicador][iteracion] = 999
resultado.append(indicador + 1)
iteracion = indicador
resultado.append(int(origen))
a = copia[resultado[-2] - 1][int(origen) - 1]
distancia.append(a)
print("El camino mas corto: " + str(resultado) + "\nCosto total: " + str(sum(distancia)))
TSP([[999,100,150,140,130,120,78,150,90,200,180,190,160,135,144,300,60,77,87,90],
[100,999,200,180,190,160,135,144,90,150,140,130,120,78,300,160,88,99,87,95],
[150,200,999,167,156,169,123,134,156,177,155,188,176,143,192,146,170,152,176,122],
[140,180,167,999,190,198,213,321,252,123,234,111,112,114,167,189,203,205,234,300],
[130,190,156,190,999,333,300,178,167,143,200,111,156,267,299,152,100,90,97,99],
[120,160,169,198,333,999,480,389,412,500,253,222,333,378,287,273,266,255,199,201],
[78,135,123,213,300,480,999,140,150,143,177,194,166,200,181,154,177,133,122,109],
[150,144,134,321,178,389,140,999,149,129,129,136,156,177,141,186,175,153,133,122],
[90,90,156,252,167,412,150,149,999,89,82,83,60,124,59,78,89,99,100,123],
[200,150,177,123,143,500,143,129,89,999,99,200,254,233,211,197,183,154,167,169],
[180,140,155,234,200,253,177,129,82,99,999,77,88,89,289,222,311,471,122,109],
[190,130,188,111,111,222,194,136,83,200,77,999,91,90,93,106,132,100,98,35],
[160,120,176,112,156,333,166,156,60,254,88,91,999,102,103,107,111,113,200,101],
[135,78,143,114,267,378,200,177,124,233,89,90,102,999,77,79,201,166,173,102],
[144,300,192,167,299,287,181,141,59,211,289,93,103,77,999,55,103,105,101,201],
[300,160,146,189,152,273,154,186,78,197,222,106,107,79,55,999,76,78,84,92],
[60,88,170,203,100,266,177,175,89,183,311,132,111,201,103,76,999,93,102,29],
[77,99,152,205,90,255,133,153,99,154,471,100,113,166,105,78,93,999,88,65],
[87,87,176,234,97,199,122,133,100,167,122,98,200,173,101,84,102,88,999,333],
[90,95,122,300,99,201,109,122,123,169,109,35,101,102,201,92,29,65,333,999]])
You can use 'time.time()' for example
Start_time = time.time()
End_time = time.time()
Diff_time = End_time()-Start_time()
Related
My write( ) function is not working, why?
So, im new to coding and im making a registration system for a fictional hospital, that gets the user name, the procedure they had and the date, after that it sum some days to it( to calculate return) and then write on a .txt file, but the write part is not working, how can i solve it? sorry that the prints and variables are on portuguese. def cadastrar(arq, nomep , proc , x, y, z, w): datas = datetime.strptime(w, '%Y-%m-%d') l = 0 m = 0 n = 0 o = 0 p = 0 try: a = open(arq, 'r+') for linha in a: dados = linha.split(';') if dados[1] in ['Procedimento X']: l = datas + \ timedelta(days = 15) m = datas + \ timedelta(days = 152) n = datas + \ timedelta(days = 304) o = datas + \ timedelta(days = 456) try: a.write(f'{nomep};{proc};{x}-{y}-{z}\n;{l};{m};{n};{o}') except: print('\033[31mErro ao escrever.\033[m') else: print(f'\033[92m{nomep} foi cadastrado com sucesso.\033[m') a.close() finally: print('') I want it to write on the txt file but suddently it just stopped working and idk why.
Change a = open(arq, 'r+') to a = open(arq, 'w+')
loop for, and arrays in python
VALOR_VETOR = 6 nota1 = [] nota2 = [] nota3 = [] mediaAluno = [] soma1 = 0 soma2 = 0 soma3 = 0 somaMedia = 0 mediaTurma = 0 print("Digite as notas dos alunos\n\n") for i in range (VALOR_VETOR): print(f"Aluno {i}") valor = float(input(f"Nota 1: ")) nota1.append(valor) valor = float(input(f"Nota 2: ")) nota2.append(valor) valor = float(input(f"Nota 3: ")) nota3.append(valor) valor = (nota1 + nota2 + nota3)/3 mediaAluno.append(valor) print (f"Nota final = {mediaAluno[i]:.1f}") for i in range (VALOR_VETOR): soma1 = soma1 + nota1 soma2 = soma2 + nota2 soma3 = soma3 + nota3 somaMedia = somaMedia + mediaAluno mediaProva1 = soma1/VALOR_VETOR print(f"A media da primeira prova é = {mediaProva1:.1f}") mediaProva2 = soma2/VALOR_VETOR print(f"A media da segunda prova é = {mediaProva2:.1f}") mediaProva3 = soma3/VALOR_VETOR print(f"A media da primeira prova é = {mediaProva1:.1f}") mediaTurma = somaMedia/VALOR_VETOR I am a python learner try, searched, but could not do. please help me. line 23, in valor = (nota1 + nota2 + nota3)/3 TypeError: unsupported operand type(s) for /: 'list' and 'int'
When you use the '+' operator with lists it will return a list with all the 3 lists concatenated for example: l1 = [1,2] l2 = [5,7] l = l1 + l2 # [1,2,5,4] I think you expect to get l =[6,9] also the operator '/' is not defined for a list so l/3 will return an error if you want to to sum individual elements in a list you can use below code i used for loop for clarity but you can use list comprehension or lambda or ... l =[] for i in range(len(l1)): l.append(l1[i] + l2[i]) """ to make the division we can use the same for loop or make another loop""" for x in range(len(l)): l[x] = l[x]/3
valor = (nota1 + nota2 + nota3)/3 //error try this line of code as: valor=(sum(nota1)+sum(nota2)+sum(nota3))/3 //it should work
Unable to select date from datepicker calendar in selenium using python
I'd like to use python selenium to search at https://book.spicejet.com/Search.aspx I reviewed this question but it is not the right answer what I am looking for. I searched for a flight from Kolkata to Goa with 2 adults and 2 Infants. When I am giving passenger details I couldn't able to select infants Date of birth. import time import selenium from selenium import webdriver from selenium.webdriver.support.ui import Select browser = webdriver.Chrome() booking_url = "https://book.spicejet.com/Search.aspx" browser.get(booking_url) departureButton = browser.find_element_by_id("ControlGroupSearchView_AvailabilitySearchInputSearchVieworiginStation1_CTXT").click() browser.find_element_by_partial_link_text("Kolkata").click() arivalButton = browser.find_element_by_id("ControlGroupSearchView_AvailabilitySearchInputSearchViewdestinationStation1_CTXT") arivalButton.click() time.sleep(.3) arivalButton.send_keys("Goa") time.sleep(1) search_date = "20-September 2019" dep_date = search_date.split("-") dep_month = dep_date[1] dep_day = dep_date[0] while browser.find_element_by_class_name("ui-datepicker-title").text != dep_month: browser.find_element_by_css_selector("a[title='Next']").click() browser.find_element_by_xpath("//table//a[text()='"+dep_day+"']").click() time.sleep(1) try: return_date_close = browser.find_element_by_class_name("date-close").click except: pass pax_selct = browser.find_element_by_id("divpaxinfo").click() time.sleep(.2) # __________Adult number_____________ for i in range(0, 2 - 1): adults = browser.find_element_by_id("hrefIncAdt") adults.click() # ____________Set Num of Children___________________ for i in range(0, 0): childrens = browser.find_element_by_id("hrefIncChd") childrens.click() # ____________Set Num of Infant(s)___________________ for i in range(0, 2): infants = browser.find_element_by_id("hrefIncInf") infants.click() donebttn = browser.find_element_by_id("btnclosepaxoption").click() searchBtn = browser.find_element_by_class_name("bookbtn").click() browser.switch_to.default_content() flightarr = [] tbl_row = browser.find_elements_by_class_name("fare-row") time_select=3 price_select=1 new_time_serial = 0 tr_cont = 4 for item in tbl_row: if item.is_displayed(): if new_time_serial == time_select: col = item cont = str(tr_cont) if price_select == 0: price1 = col.find_element_by_xpath('//*[#id="availabilityTable0"]/tbody/tr['+cont+']/td[3]/p').click() elif price_select == 1: price2 = col.find_element_by_xpath('//*[#id="availabilityTable0"]/tbody/tr['+cont+']/td[4]/p').click() new_time_serial = new_time_serial + 1 tr_cont = tr_cont + 1 time.sleep(1) cntn_btn = browser.find_element_by_class_name("button-continue").click() passen_serial = 0 passen_serial_inf = 0 #inf = 1 birth_year = "2017" birth_month = "Nov" birth_day = "30" all_pass_frm = browser.find_element_by_class_name("multicontent") all_pass_entry = all_pass_frm.find_elements_by_class_name("sectionContent") for passen in all_pass_entry: pass_type = passen.find_element_by_class_name("guest-heading").text.split(' ',1)[0] pass_type2 = passen.find_element_by_class_name("guest-heading").text.split(' ',1)[1] if pass_type == "Adult": deg_sel_name = Select(passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_DropDownListTitle_" + str(passen_serial) + "")) deg_sel_name.select_by_index(1) first_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxFirstName_" + str(passen_serial) + "") first_name_in.send_keys("imam") last_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxLastName_" + str(passen_serial) + "") last_name_in.send_keys("Hossain") elif pass_type == "Child": deg_sel_name = Select(passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_DropDownListGender_" + str(passen_serial) + "")) deg_sel_name.select_by_index(2) first_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxFirstName_" + str(passen_serial) + "") first_name_in.send_keys("Korim") last_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxLastName_" + str(passen_serial) + "") last_name_in.send_keys("Hossain") elif pass_type == "Infant": deg_sel_name = Select(passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_DropDownListGender_"+ str(passen_serial_inf) + "_" + str(passen_serial_inf) + "")) deg_sel_name.select_by_index(2) first_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxFirstName_"+ str(passen_serial_inf) + "_" + str(passen_serial_inf) + "") first_name_in.send_keys("Aqiba") last_name_in = passen.find_element_by_id("CONTROLGROUPPASSENGER_PassengerInputViewPassengerView_TextBoxLastName_"+ str(passen_serial_inf) + "_" + str(passen_serial_inf) + "") last_name_in.send_keys("Hassan") dob = passen.find_element_by_id("inputDateContactInfant" +str(pass_type2)+ "").click() dob_cal = browser.find_element_by_class_name("datepickerViewYears") dob_cal_year = dob_cal.find_element_by_class_name("datepickerYears") inf_birth_year = dob_cal.find_element_by_xpath('.//*[#class="datepickerYears"]/tr/td/a/span[text()="'+birth_year+'"]').click() inf_birth_mon = dob_cal.find_element_by_xpath('.//*[#class="datepickerMonths"]/tr/td/a/span[text()="'+birth_month+'"]').click() inf_birth_day = dob_cal.find_element_by_xpath('.//*[#class="datepickerDays"]/tr/td/a/span[text()="'+birth_day+'"]').click() # inf = inf +1 passen_serial_inf = passen_serial_inf + 1 passen_serial = passen_serial + 1 print("Done") I tried with xPath it works for 1st infant but it is not working for 2nd infant. What should i need to do now? is there any way except XPath? And what can i do when passenger number is different?
I have extracted the var declarations and the var increments, there seems to be a mismatch at the declaration statements that could be causing the problem, don't the var declarations need to start at the same number? Set them equal and re-try. var declaration passen_serial_inf = 0 inf = 1 var increments inf = inf +1 passen_serial_inf = passen_serial_inf + 1 passen_serial = passen_serial + 1
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
chatroom quiz bot: How to repeat quiz during idle time?
I am working on a quit bot in Python. Now I want to know how I can repeat the question after a certain idle time. These are my global variables: QUIZ_FILE = 'static/questions.txt' QUIZ_TOTAL_LINES = 29 QUIZ_TIME_LIMIT = 40 QUIZ_IDLE_LIMIT = 3000000 QUIZ_RECURSIVE_MAX = 3000000 QUIZ_CURRENT_ANSWER = {} QUIZ_CURRENT_HINT = {} QUIZ_CURRENT_HINT_NEW = {} QUIZ_CURRENT_TIME = {} QUIZ_IDLENESS = {} QUIZ_IDLE_ANSWER = {} QUIZ_START = {} QUIZ_IDLE_ANSWER_FIRSR = {} QUIZ_NOWORD = '*' MODE = 'M1' PTS = 'P2' ACC = 'A2' Bot Time settings import threading HELP = u'help of command > "!quiz"' def sectomin(time): m = 0 s = 0 if time >= 60: m = time / 60 if (m * 60) != 0: s = time - (m * 60) else: s = 0 else: m = 0 s = time return str(m)+u'min. in '+str(s)+u'sec.' def quiz_timer(groupchat, start_time): global QUIZ_TIME_LIMIT global QUIZ_CURRENT_TIME time.sleep(QUIZ_TIME_LIMIT) if QUIZ_CURRENT_TIME.has_key(groupchat) and QUIZ_CURRENT_ANSWER.has_key(groupchat) and start_time == QUIZ_CURRENT_TIME[groupchat]: QUIZ_CURRENT_ANSWER[groupchat] msg(groupchat, u'(!) time out! ' + sectomin(QUIZ_TIME_LIMIT) + u' passed.\nCorrect answer: ' + QUIZ_CURRENT_ANSWER[groupchat]) if QUIZ_IDLENESS.has_key(groupchat): QUIZ_IDLENESS[groupchat] += 1 else: QUIZ_IDLENESS[groupchat] = 1 if QUIZ_IDLENESS[groupchat] >= QUIZ_IDLE_LIMIT: msg(groupchat, u'(!) quiz will be automatically completed for inaction! ' + str(QUIZ_IDLE_LIMIT) + ' unanswered questions.') del QUIZ_CURRENT_ANSWER[groupchat] quiz_list_scores(groupchat) else: quiz_ask_question(groupchat) Method of asking question def quiz_ask_question(groupchat): global answer global QUIZ_CURRENT_TIME global question global QUIZ_IDLE_ANSWER global QUIZ_IDLE_ANSWER_FIRSR QUIZ_IDLE_ANSWER = {groupchat:{}} (question, answer) = quiz_new_question() QUIZ_CURRENT_ANSWER[groupchat] = answer QUIZ_CURRENT_HINT[groupchat] = None QUIZ_CURRENT_HINT_NEW[groupchat] = None QUIZ_CURRENT_TIME[groupchat] = time.time() threading.Thread(None, quiz_timer, 'gch'+str(random.randrange(0,9999)), (groupchat, QUIZ_CURRENT_TIME[groupchat])).start() msg(groupchat, u'(?) question: \n' + question) I want to automatically recall the question every few seconds during sleep/idle time. I cannot make it to work so that the bot can ask questions between QUIZ_TIME_LIMIT = 40 automatically. Code to recall question on request def handler_quiz_resend(type, source, body): global question groupchat = source[1] if QUIZ_CURRENT_ANSWER.has_key(groupchat): res = u'(*) current question: \n'+question reply(type, source, res) else: reply(type, source, u'no quiz, '+HELP)