def balance(self, energy_demand): active_engines = filter(lambda engine: engine.is_enabled, self.engines) if len(active_engines) <= 0: return [] rpms = variable(len(active_engines), 'rpms') fixed_engine_costs = matrix([float(engine.engine_type.fixed_engine_cost) for engine in active_engines]) linear_engine_costs = matrix([float(engine.engine_type.linear_engine_cost) for engine in active_engines]) fixed_energy_outputs = matrix([float(engine.engine_type.fixed_energy_output) for engine in active_engines]) linear_energy_outputs = matrix([float(engine.engine_type.linear_energy_output) for engine in active_engines]) minimum_rpms = matrix([float(engine.engine_type.minimum_rpm) for engine in active_engines]) maximum_rpms = matrix([float(engine.engine_type.maximum_rpm) for engine in active_engines]) energy_demand_constraint = ((float(energy_demand) - dot(rpms, linear_energy_outputs) - sum(fixed_energy_outputs)) <= 0) maximum_rpm_constraint = ((rpms - maximum_rpms) <= 0) minimum_rpm_constraint = ((rpms - minimum_rpms) >= 0) constraints = [energy_demand_constraint, maximum_rpm_constraint, minimum_rpm_constraint] objective_function = op((dot(linear_engine_costs, rpms) - sum(fixed_engine_costs)), constraints) objective_function.solve() for i in range(len(active_engines)): engine = active_engines[i] engine.rpm = rpms.value[i] engine.energy_output = float(engine.engine_type.fixed_energy_output) * engine.rpm + float(engine.engine_type.fixed_energy_output) return active_engines
def balance(request, engines, demand): engines = json.loads(engines) enabled_engines = filter(lambda engine: engine["_isEnabled"], engines) print enabled_engines if not enabled_engines: return HttpResponse(json.dumps(enabled_engines)) vector_size = len(enabled_engines) rpms = variable(vector_size, "rpms") fixed_engine_costs = matrix([float(EngineType.objects.get(pk=engine["_engineTypeId"]).fixed_engine_cost) for engine in enabled_engines]) linear_engine_costs = matrix([float(EngineType.objects.get(pk=engine["_engineTypeId"]).linear_engine_cost) for engine in enabled_engines]) fixed_energy_outputs = matrix([float(EngineType.objects.get(pk=int(engine["_engineTypeId"])).fixed_energy_output) for engine in enabled_engines]) linear_energy_outputs = matrix([float(EngineType.objects.get(pk=int(engine["_engineTypeId"])).linear_energy_output) for engine in enabled_engines]) minimum_rpms = matrix([float(EngineType.objects.get(pk=engine["_engineTypeId"]).minimum_rpm) for engine in enabled_engines]) maximum_rpms = matrix([float(EngineType.objects.get(pk=engine["_engineTypeId"]).maximum_rpm) for engine in enabled_engines]) demand_constraint = ((float(demand) - dot(rpms, linear_energy_outputs) - sum(fixed_energy_outputs)) <= 0) maximum_rpm_constraint = ((rpms - maximum_rpms) <= 0) minimum_rpm_constraint = ((rpms - minimum_rpms) >= 0) constraints = [demand_constraint, maximum_rpm_constraint, minimum_rpm_constraint] objective_function = op((dot(linear_engine_costs, rpms) + sum(fixed_engine_costs)), constraints) objective_function.solve() print rpms.value rpmsIndex = 0 for engine in engines: engine["_rpm"] = 0 engine["_energyOutput"] = 0 if engine["_isEnabled"]: print rpms if rpms.value: engine["_rpm"] = rpms.value[rpmsIndex] rpmsIndex += 1 else: engine["_rpm"] = float(EngineType.objects.get(pk=engine["_engineTypeId"]).maximum_rpm) energy_output_per_rpm = float(EngineType.objects.get(pk=engine["_engineTypeId"]).linear_energy_output) base_energy_output = float(EngineType.objects.get(pk=engine["_engineTypeId"]).fixed_energy_output) engine["_energyOutput"] = energy_output_per_rpm * float(engine["_rpm"]) + base_energy_output return HttpResponse(json.dumps(engines));
def _get_convex_opt_assignment(C): m, n = C.shape c = matrix(C.reshape(m * n)) x = variable(m * n) constraints = [ x >= 0, x <= 1, ] # row constraints for i in range(m): #print('setting constraint', i*n, i*n+n) constraints.append(cvx_sum(x[i * n:i * n + n]) == 1) # col constraints # add constraints so max number of assignments to each port in ports2 # is 1 as well for j in range(n): #print(list(range(j, m*n, n))) constraints.append(cvx_sum([x[jj] for jj in range(j, m * n, n)]) <= 1) # NOTE must use external solver (such as glpk), the default one is # _very_ slow op( dot(c, x), constraints, ).solve(solver='glpk') X = np.array(x.value).reshape(m, n) > 0.01 return X
def test_case2(self): x = variable(2) A = matrix([[2., 1., -1., 0.], [1., 2., 0., -1.]]) b = matrix([3., 3., 0., 0.]) c = matrix([-4., -5.]) ineq = (A * x <= b) lp2 = op(dot(c, x), ineq) lp2.solve() self.assertAlmostEqual(lp2.objective.value()[0], -9.0, places=4)
def test_case2(self): x = variable(2) A = matrix([[2.,1.,-1.,0.], [1.,2.,0.,-1.]]) b = matrix([3.,3.,0.,0.]) c = matrix([-4.,-5.]) ineq = ( A*x <= b ) lp2 = op(dot(c,x), ineq) lp2.solve() self.assertAlmostEqual(lp2.objective.value()[0], -9.0, places=4)
def _foe_objective_fn(Q_s): # pi_N, pi_E, pi_W, pi_S, pi_X na = Q_s.shape[0] # Variable vector [pi_N, pi_E, pi_W, pi_S, pi_X, V] x = variable(na) # Maximize the probability distribution pi obj_matrix = np.zeros(len(Q_s)) obj_matrix[-1] = -1 c = matrix(obj_matrix) return dot(c, x)
def calculate_distance_eqopp_2d(data_tuple, theta, tau, eps = 0): data = data_tuple[0] # print(data) data_sensitive = data_tuple[1] data_label = data_tuple[2] N = np.shape(data_sensitive)[0] emp_marginals = np.reshape(get_marginals(sensitives=data_sensitive, target=data_label), [2, 2]) w = -math.log(1./tau - 1) d = distance_func(theta,data,w) C = C_classifier(data, theta, tau) phi1 = phi_function(data_sensitive, data_label, emp_marginals) phi0 = phi_function_0(data_sensitive, data_label, emp_marginals) C_phi1 = np.array(phi1)*(1-2*np.array(C)) C_phi0 = np.array(phi0)*(1-2*np.array(C)) b_phi1 = - np.sum(np.array(phi1)*np.array(C)) b_phi0 = - np.sum(np.array(phi0)*np.array(C)) p = variable(N) opt_A1 = matrix(C_phi1) opt_A0 = matrix(C_phi0) equality1 = (dot(opt_A1,p) ==matrix(b_phi1) ) equality0 = (dot(opt_A0,p) ==matrix(b_phi0) ) opt_c = matrix(d) lp = op(dot(opt_c,p), [equality1,equality0,p>=0,p<=1]) lp.solve() return(lp.objective.value()[0])
def minimax_op(Qs): from cvxopt.modeling import dot, op, variable solvers.options['show_progress'] = False v = variable() p = variable(5) c1 = p >= 0 c2 = sum(p) == 1 c3 = dot(matrix(Qs), p) >= v lp = op(-v, [c1, c2, c3]) lp.solve() success = lp.status == 'optimal' Vs = v.value[0] return Vs, success
def solve(problem): # Variables R = variable(1, 'R') P = variable(1, 'P') S = variable(1, 'S') V = variable(1, 'V') # Variable vector [R, P, S, V] x = variable(4) # minimize cTx == -V c = matrix([0., 0., 0., -1.]) objective = dot(c, x) # Matrices Ainit = np.zeros((0, len(x))) # R = 0, P = 1, S = 2, V = V for row in problem: Ainit = np.vstack([Ainit, [row[0], row[1], row[2], 1]]) # Other known constraints Ainit = np.vstack([Ainit, [1., 1., 1., 0.]]) # R + P + S <= 1 # Ainit = np.vstack([Ainit, [-1., 0., 0., 0.]]) # -R <= 0 # Ainit = np.vstack([Ainit, [0., -1., 0., 0.]]) # -P <= 0 # Ainit = np.vstack([Ainit, [0., 0., -1., 0.]]) # -S <= 0 A = matrix(Ainit) # b = matrix([0., 0., 0., 1., 0., 0., 0.]) b = matrix([0., 0., 0., 1.]) # Linear constraints embedded in matrices ineq = (A * x <= b) lp = op(objective, ineq) lp.solve() # [R, P, S, V] ^ T return ineq.multiplier.value
def solve_lp(a, b, c): """ >>> a = matrix([[-5., 3., 1., 8., 1.], ... [ 5., 5., 4., 6., 1.], ... [-4., 6., 0., 5., 1.], ... [-1.,-1.,-1.,-1., 0.], ... [ 1., 1., 1., 1., 0.], ... [-1., 0., 0., 0., 0.], ... [ 0.,-1., 0., 0., 0.], ... [ 0., 0.,-1., 0., 0.], ... [ 0., 0., 0.,-1., 0.]]) >>> b = matrix([0.,0.,0.,0.,1.]) >>> c = matrix([0.,0.,0., 1.,-1.,0.,0.,0.,0.]) >>> solve_lp(a, b, c) """ variables = c.size[0] x = variable(variables, 'x') eq = (a * x == b) ineq = (x >= 0) lp = op(dot(c, x), [eq, ineq]) lp.solve(solver='glpk') return (lp.objective.value(), x.value)
def _update_learners_weights(self, t, samples_dist): """ Solve equation (3) in the paper, returns the set of lagrange multipliers that matches w """ n = len(samples_dist) batch_size = min(self.max_batch_size, int(n * self.batch_size_ratio)) batch_indices = np.random.choice(a=list(range(n)), replace=False, p=samples_dist, size=batch_size) # Weak learners weights - what we need to find w = modeling.variable(t, 'w') # Slack variables # zetas = {int(i): modeling.variable(1, 'zeta_%d' % int(i)) for i in batch_indices} zetas = modeling.variable(batch_size, 'zetas') # Margin rho = modeling.variable(1, 'rho') # Constraints c1 = (w >= 0) c2 = (sum(w) == 1) c_slacks = (zetas >= 0) c_soft_margins = [ (modeling.dot(matrix(self.u[sample_idx].astype(float).T), w) >= (rho - zetas[int(idx)])) for idx, sample_idx in enumerate(batch_indices) ] # Solve optimisation problems lp = modeling.op(-(rho - self.kappa * modeling.sum(zetas)), [c1, c2, c_slacks] + c_soft_margins) solvers.options['show_progress'] = False lp.solve() return w.value
# The robust LP example of section 10.5 (Examples). from cvxopt import normal, uniform from cvxopt.modeling import variable, dot, op, sum from cvxopt.blas import nrm2 m, n = 500, 100 A = normal(m, n) b = uniform(m) c = normal(n) x = variable(n) op(dot(c, x), A * x + sum(abs(x)) <= b).solve() x2 = variable(n) y = variable(n) op(dot(c, x2), [A * x2 + sum(y) <= b, -y <= x2, x2 <= y]).solve() print("\nDifference between two solutions %e" % nrm2(x.value - x2.value))
def cvxopt(storage_size_list,house_pv,sp_pv,pandr_pv): cost_list=[] for storage_max in storage_size_list: storage_max=float(storage_max) storage_power=storage_max/8 [buy_price,sell_price]=price() pvl=house_pv*solar_data()+sp_pv*solar_data_flat()+pandr_pv*solar_data_10() #PV assumed to be accurately predictied by weather forecast fix_load=load_heat_data()+hot_water() #load which assmued to be accurately predicted, which is heat load float_load=residential()+load_sciencepark()+car_charging() #Load which cannot be predicited accurately, so predicted by data of a week ago use_load=fix_load+np.roll(float_load,7*48) #Estimated total load to be used for cvxopt ''' #use_load=load_heat_data()+hot_water()+residential()+load_sciencepark() eff=math.sqrt(0.85) start=200 end=207 duration=(end-start)*48 day_i=list(range(start*48,end*48)) cml=([-1.]+[0.]*(duration-1)+[1.])*(duration-1)+[-1.] #cml=([-math.sqrt(0.85)]+[0.]*(duration-1)+[math.sqrt(0.85)])*(duration-1)+[-math.sqrt(0.85)] #cml=([-0.85]+[0.]*(duration-1)+[0.85])*(duration-1)+[-0.85] cm=matrix(cml,(duration,duration)) pv=matrix(pvl[day_i],(duration,1)) load=matrix(use_load[day_i],(duration,1)) bp=matrix(buy_price[day_i],(duration,1)) sp=matrix(sell_price[day_i],(duration,1)) storage_max=100000. zero=matrix([0.]*duration,(duration,1)) emax=matrix([storage_max]*duration,(duration,1)) #maximum storage pmax=matrix([50.e3]*duration,(duration,1)) #maximum power to grid charge_pmax=matrix([25000.]*duration,(duration,1)) effm=matrix([eff]*duration,(duration,1)) ieffm=matrix([1/eff]*duration,(duration,1)) #discharge_pmax=matrix([-25000.]*duration,(duration,1)) e=variable(duration) #Stored energy c=variable(duration) #Charging energy d=variable(duration) #Discharging energy b=variable(duration) #Buy s=variable(duration) #Sell i1=(b>=zero) i2=(s>=zero) i3=(e>=zero) i4=(e<=emax) i5=(b<=pmax) i6=(s<=pmax) i7=(c<=charge_pmax) i8=(d<=charge_pmax) i9=(c>=zero) i10=(d>=zero) e1=(c/eff-d*eff+load-pv==b-s) e2=(e[0]==matrix([0.])) e3=(c-d==cm*e) ob=dot(b,bp)-dot(s,sp) lp=op(ob,[i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,e1,e2,e3]) solvers.options['show_progress'] = True lp.solve() ''' eff=math.sqrt(0.85) #Round trip efficiency = 0.85, so each process of charge or discharge has efficiency of sqrt(0.85) start=0 end=365 duration=(end-start)*48 day_i=list(range(start*48,end*48)) cvxopt_balancing=[] cvxopt_buy=np.array([]) #Record power traded with grid, positive = import cvxopt_storage=np.array([]) #Record amount of stored energy day_cost=0 for day in range(start,end): time_index=list(range(day*48,day*48+48)) cml=([-1.]+[0.]*(48-1)+[1.])*(48-1)+[-1.] #List to create matrix to multiply with amount of energy stored in each time period to calculate the change in energy stored #cml=([-math.sqrt(0.85)]+[0.]*(duration-1)+[math.sqrt(0.85)])*(duration-1)+[-math.sqrt(0.85)] #cml=([-0.85]+[0.]*(duration-1)+[0.85])*(duration-1)+[-0.85] cm=matrix(cml,(48,48)) pv=matrix(pvl[time_index],(48,1)) load=matrix(use_load[time_index],(48,1)) bp=matrix(buy_price[time_index],(48,1)) sp=matrix(sell_price[time_index],(48,1)) zero=matrix([0.]*48,(48,1)) emax=matrix([storage_max]*48,(48,1)) #maximum storage pmax=matrix([50.e3]*48,(48,1)) #maximum power to grid charge_pmax=matrix([storage_power]*48,(48,1)) #discharge_pmax=matrix([-25000.]*duration,(duration,1)) e=variable(48) #Stored energy c=variable(48) #Charging energy d=variable(48) #Discharging energy b=variable(48) #Buy s=variable(48) #Sell i1=(b>=zero) i2=(s>=zero) i3=(e>=zero) i4=(e<=emax) i5=(b<=pmax) i6=(s<=pmax) i7=(c<=charge_pmax) #Maximum power of storage i8=(d<=charge_pmax) i9=(c>=zero) i10=(d>=zero) i11=(c[47]-d[47]+e[47]>=matrix([0.])) #Energy in storage always > 0 i12=(c[47]-d[47]+e[47]<=matrix([storage_max])) #Energy in storage always < maximum capacity e1=(c/eff-d*eff+load-pv==b-s) if day == start: e2=(e[0]==matrix([0.])) else: next_storage=cvxopt_storage[-1]-cvxopt_balancing[-1] e2=(e[0]==matrix(next_storage)) e3=(c-d==cm*e) ob=dot(b,bp)-dot(s,sp) lp=op(ob,[i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,e1,e2,e3]) solvers.options['show_progress'] = False lp.solve() day_cost+=lp.objective.value()[0] for t in range(0,48): cvxopt_balancing.append(d.value[t]-c.value[t]) cvxopt_buy=np.append(cvxopt_buy,b.value[t]-s.value[t]) cvxopt_storage=np.append(cvxopt_storage,e.value[t]) #print(b.value[47]-s.value[47]) #print(c.value[47]*eff-d.value[47]/eff+e.value[47]) # print(day_cost) #Calculate actual energy flow based on prediction of CVXOPT buy=[] charge_power_l=[] balancing_l=[] storage=np.array([e.value[0]]) #Initial charge in storage decided by cvxopt excess=(pvl-fix_load-float_load)[day_i] for t in range(duration): if cvxopt_balancing[t]>0: #Storage discharge if cvxopt_balancing[t]>storage[t]: #CVXOPT wants more discharge than currently stored # balancing=-storage[t]*eff #Storage discharge all stored charge_power=-storage[t] # print('a') else: # balancing=-cvxopt_balancing[t]*eff #Do as CVXOPT wants charge_power=-cvxopt_balancing[t] # print('b') else: #Storage charge if cvxopt_balancing[t]>storage_max-storage[t]: #CVXOPT wants to charge more than remaining capacity # balancing=(storage_max-storage[t])/eff #Charge by remaining capacity charge_power=storage_max-storage[t] # print('c') else: # balancing=-cvxopt_balancing[t]/eff #Do as CVXOPT wants charge_power=-cvxopt_balancing[t] # print('d') if charge_power>0: balancing=charge_power/eff else: balancing=charge_power*eff buy.append(-excess[t]+balancing) balancing_l.append(balancing) charge_power_l.append(-charge_power) storage=np.append(storage,storage[t]+charge_power) # print(t,excess[t],charge_power,cvxopt_balancing[t]) # print(buy[t],cvxopt_buy[t]) # print(storage[t],cvxopt_storage[t]) running_cost=market(buy,sell_price[day_i],buy_price[day_i]) # print(running_cost) cost_list.append(running_cost) # print(max(max(buy-cvxopt_buy),-min(buy-cvxopt_buy))) #print(sell_price[day_i]) #print(buy_price[day_i]) balancing_l=np.array(balancing_l) # fig,ax=plt.subplots() #ax.plot(list(range(0,duration)),(fix_load+float_load)[day_i],'-r',label='actual') #ax.plot(list(range(0,duration)),use_load[day_i],'-b',label='estimate') #ax.step(list(range(0,duration)),buy,'-r',label='actual') #ax.step(list(range(0,duration)),cvxopt_buy,'-b',label='estimate') #ax.step(list(range(0,duration)),charge_power_l,'-r',label='actual') #ax.step(list(range(0,duration)),cvxopt_balancing,'-b',label='estimate') #ax.step(list(range(0,duration+1)),storage,'-b',label='estimate') # t_list=np.array(range(49))/2 # p1=ax.step(t_list,pvl[206*48-1:207*48]/500,'-r',label='PV generation') # p2=ax.step(t_list,(fix_load+float_load)[206*48-1:207*48]/500,'-k',label='demand') # p3=ax.fill_between(t_list,0,(pvl-balancing_l)[206*48-1:207*48]/500,step='pre',color='y',label='power output') # ax.set_xlim([0,24]) # plt.xticks([0,6,12,18,24]) # plt.ylabel('power (MW)') # plt.xlabel('time') # plt.ylim([-10,45]) # plt.title('Power Flow on a Summer Day using CVXOPT') # fig.legend(loc='upper center', bbox_to_anchor=(0.77, 0.89), ncol=1) # plt.savefig('summer cvxopt power.png',dpi=600) return cost_list
b = matrix(0.0, (n*2,1)) k = 0 while k<n: # add heat and cool set b[2*k,0]=comfortZone_upper-S[k,0] b[2*k+1,0]=-comfortZone_lower+S[k,0] k=k+1 # time to solve for energy at each timestep #print(cc) #print(AA) #print(b) ineq = (AA*x <= b) if heatorcool == 'heat': lp2 = op(dot(cc,x),ineq) # we want to optimize cost times energy within ineq constraints op.addconstraint(lp2, heatineq) op.addconstraint(lp2,heatlimiteq) if heatorcool == 'cool': lp2 = op(dot(-cc,x),ineq) op.addconstraint(lp2, coolineq) lp2.solve() energy = x.value # print(lp2.objective.value()) temp_indoor = matrix(0.0, (n,1)) temp_indoor[0,0] = temp_indoor_initial p = 1 while p<n: temp_indoor[p,0] = timestep*(c1*(temp_outdoor[p-1,0]-temp_indoor[p-1,0])+c2*energy[p-1,0]+c3*q_solar[p-1,0])+temp_indoor[p-1,0] p = p+1 # Output not used
y = variable() c1 = ( 2*x+y <= 3 ) c2 = ( x+2*y <= 3 ) c3 = ( x >= 0 ) c4 = ( y >= 0 ) lp1 = op(-4*x-5*y, [c1,c2,c3,c4]) lp1.solve() print("\nstatus: %s" %lp1.status) print("optimal value: %f" %lp1.objective.value()[0]) print("optimal x: %f" %x.value[0]) print("optimal y: %f" %y.value[0]) print("optimal multiplier for 1st constraint: %f" %c1.multiplier.value[0]) print("optimal multiplier for 2nd constraint: %f" %c2.multiplier.value[0]) print("optimal multiplier for 3rd constraint: %f" %c3.multiplier.value[0]) print("optimal multiplier for 4th constraint: %f\n" %c4.multiplier.value[0]) x = variable(2) A = matrix([[2.,1.,-1.,0.], [1.,2.,0.,-1.]]) b = matrix([3.,3.,0.,0.]) c = matrix([-4.,-5.]) ineq = ( A*x <= b ) lp2 = op(dot(c,x), ineq) lp2.solve() print("\nstatus: %s" %lp2.status) print("optimal value: %f" %lp2.objective.value()[0]) print("optimal x: \n") print(x.value) print("optimal multiplier: \n") print(ineq.multiplier.value)
y = variable() c1 = (2 * x + y <= 3) c2 = (x + 2 * y <= 3) c3 = (x >= 0) c4 = (y >= 0) lp1 = op(-4 * x - 5 * y, [c1, c2, c3, c4]) lp1.solve() print("\nstatus: %s" % lp1.status) print("optimal value: %f" % lp1.objective.value()[0]) print("optimal x: %f" % x.value[0]) print("optimal y: %f" % y.value[0]) print("optimal multiplier for 1st constraint: %f" % c1.multiplier.value[0]) print("optimal multiplier for 2nd constraint: %f" % c2.multiplier.value[0]) print("optimal multiplier for 3rd constraint: %f" % c3.multiplier.value[0]) print("optimal multiplier for 4th constraint: %f\n" % c4.multiplier.value[0]) x = variable(2) A = matrix([[2., 1., -1., 0.], [1., 2., 0., -1.]]) b = matrix([3., 3., 0., 0.]) c = matrix([-4., -5.]) ineq = (A * x <= b) lp2 = op(dot(c, x), ineq) lp2.solve() print("\nstatus: %s" % lp2.status) print("optimal value: %f" % lp2.objective.value()[0]) print("optimal x: \n") print(x.value) print("optimal multiplier: \n") print(ineq.multiplier.value)
def cvxopt(storage_size_list): cost_list=[] for storage_max in storage_size_list: storage_max=float(storage_max) storage_power=storage_max/4 [buy_price,sell_price]=price() pvl=236000*0.9*0.2*0.9*solar_data()+88000*0.9*0.2*0.9*solar_data_flat() fix_load=load_heat_data()+hot_water() #load which assmued to be accurately predicted, which is heat load float_load=residential()+load_sciencepark() #Load which cannot be predicited accurately, so predicted by data of a week ago use_load=fix_load+np.roll(float_load,7*48) #Estimated total load to be used for cvxopt ''' #use_load=load_heat_data()+hot_water()+residential()+load_sciencepark() eff=math.sqrt(0.85) start=200 end=207 duration=(end-start)*48 day_i=list(range(start*48,end*48)) cml=([-1.]+[0.]*(duration-1)+[1.])*(duration-1)+[-1.] #cml=([-math.sqrt(0.85)]+[0.]*(duration-1)+[math.sqrt(0.85)])*(duration-1)+[-math.sqrt(0.85)] #cml=([-0.85]+[0.]*(duration-1)+[0.85])*(duration-1)+[-0.85] cm=matrix(cml,(duration,duration)) pv=matrix(pvl[day_i],(duration,1)) load=matrix(use_load[day_i],(duration,1)) bp=matrix(buy_price[day_i],(duration,1)) sp=matrix(sell_price[day_i],(duration,1)) storage_max=100000. zero=matrix([0.]*duration,(duration,1)) emax=matrix([storage_max]*duration,(duration,1)) #maximum storage pmax=matrix([50.e3]*duration,(duration,1)) #maximum power to grid charge_pmax=matrix([25000.]*duration,(duration,1)) effm=matrix([eff]*duration,(duration,1)) ieffm=matrix([1/eff]*duration,(duration,1)) #discharge_pmax=matrix([-25000.]*duration,(duration,1)) e=variable(duration) #Stored energy c=variable(duration) #Charging energy d=variable(duration) #Discharging energy b=variable(duration) #Buy s=variable(duration) #Sell i1=(b>=zero) i2=(s>=zero) i3=(e>=zero) i4=(e<=emax) i5=(b<=pmax) i6=(s<=pmax) i7=(c<=charge_pmax) i8=(d<=charge_pmax) i9=(c>=zero) i10=(d>=zero) e1=(c/eff-d*eff+load-pv==b-s) e2=(e[0]==matrix([0.])) e3=(c-d==cm*e) ob=dot(b,bp)-dot(s,sp) lp=op(ob,[i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,e1,e2,e3]) solvers.options['show_progress'] = True lp.solve() ''' eff=math.sqrt(0.85) start=0 end=365 duration=(end-start)*48 day_i=list(range(start*48,end*48)) cvxopt_balancing=[] cvxopt_buy=np.array([]) #Record power traded with grid, positive = import cvxopt_storage=np.array([]) #Record amount of stored energy day_cost=0 for day in range(start,end): time_index=list(range(day*48,day*48+48)) cml=([-1.]+[0.]*(48-1)+[1.])*(48-1)+[-1.] #cml=([-math.sqrt(0.85)]+[0.]*(duration-1)+[math.sqrt(0.85)])*(duration-1)+[-math.sqrt(0.85)] #cml=([-0.85]+[0.]*(duration-1)+[0.85])*(duration-1)+[-0.85] cm=matrix(cml,(48,48)) pv=matrix(pvl[time_index],(48,1)) load=matrix(use_load[time_index],(48,1)) bp=matrix(buy_price[time_index],(48,1)) sp=matrix(sell_price[time_index],(48,1)) zero=matrix([0.]*48,(48,1)) emax=matrix([storage_max]*48,(48,1)) #maximum storage pmax=matrix([50.e3]*48,(48,1)) #maximum power to grid charge_pmax=matrix([storage_power]*48,(48,1)) #discharge_pmax=matrix([-25000.]*duration,(duration,1)) e=variable(48) #Stored energy c=variable(48) #Charging energy d=variable(48) #Discharging energy b=variable(48) #Buy s=variable(48) #Sell i1=(b>=zero) i2=(s>=zero) i3=(e>=zero) i4=(e<=emax) i5=(b<=pmax) i6=(s<=pmax) i7=(c<=charge_pmax) i8=(d<=charge_pmax) i9=(c>=zero) i10=(d>=zero) i11=(c[47]-d[47]+e[47]>=matrix([0.])) i12=(c[47]-d[47]+e[47]<=matrix([storage_max])) e1=(c/eff-d*eff+load-pv==b-s) if day == start: e2=(e[0]==matrix([0.])) else: next_storage=cvxopt_storage[-1]-cvxopt_balancing[-1] e2=(e[0]==matrix(next_storage)) e3=(c-d==cm*e) ob=dot(b,bp)-dot(s,sp) lp=op(ob,[i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,e1,e2,e3]) solvers.options['show_progress'] = False lp.solve() day_cost+=lp.objective.value()[0] for t in range(0,48): cvxopt_balancing.append(d.value[t]-c.value[t]) cvxopt_buy=np.append(cvxopt_buy,b.value[t]-s.value[t]) cvxopt_storage=np.append(cvxopt_storage,e.value[t]) #print(b.value[47]-s.value[47]) #print(c.value[47]*eff-d.value[47]/eff+e.value[47]) # print(day_cost) buy=[] charge_power_l=[] balancing_l=[] storage=np.array([e.value[0]]) #Initial charge in storage decided by cvxopt excess=(pvl-fix_load-float_load)[day_i] for t in range(duration): if cvxopt_balancing[t]>0: #Storage discharge if cvxopt_balancing[t]>storage[t]: #CVXOPT wants more discharge than currently stored # balancing=-storage[t]*eff #Storage discharge all stored charge_power=-storage[t] # print('a') else: # balancing=-cvxopt_balancing[t]*eff #Do as CVXOPT wants charge_power=-cvxopt_balancing[t] # print('b') else: #Storage charge if cvxopt_balancing[t]>storage_max-storage[t]: #CVXOPT wants to charge more than remaining capacity # balancing=(storage_max-storage[t])/eff #Charge by remaining capacity charge_power=storage_max-storage[t] # print('c') else: # balancing=-cvxopt_balancing[t]/eff #Do as CVXOPT wants charge_power=-cvxopt_balancing[t] # print('d') if charge_power>0: balancing=charge_power/eff else: balancing=charge_power*eff buy.append(-excess[t]+balancing) balancing_l.append(balancing) charge_power_l.append(-charge_power) storage=np.append(storage,storage[t]+charge_power) # print(t,excess[t],charge_power,cvxopt_balancing[t]) # print(buy[t],cvxopt_buy[t]) # print(storage[t],cvxopt_storage[t]) running_cost=market(buy,sell_price[day_i],buy_price[day_i]) # print(running_cost) cost_list.append(running_cost) print(max(max(buy-cvxopt_buy),-min(buy-cvxopt_buy))) #print(sell_price[day_i]) #print(buy_price[day_i]) #fig,ax=plt.subplots() #ax.plot(list(range(0,duration)),(fix_load+float_load)[day_i],'-r',label='actual') #ax.plot(list(range(0,duration)),use_load[day_i],'-b',label='estimate') #ax.step(list(range(0,duration)),buy,'-r',label='actual') #ax.step(list(range(0,duration)),cvxopt_buy,'-b',label='estimate') #ax.step(list(range(0,duration)),charge_power_l,'-r',label='actual') #ax.step(list(range(0,duration)),cvxopt_balancing,'-b',label='estimate') #ax.step(list(range(0,duration+1)),storage,'-b',label='estimate') #fig.legend() return cost_list
b[2*k+1,0]=-noOccupancyHeat+S[k,0] k=k+1 else: k = 0 while k<n: b[2*k,0]=adaptiveCool[k,0]-S[k,0] b[2*k+1,0]=-adaptiveHeat[k,0]+S[k,0] k=k+1 # time to solve for energy at each timestep #print(cc) #print(AA) #print(b) ineq = (AA*x <= b) if heatorcool == 'heat': lp2 = op(dot(cc,x),ineq) op.addconstraint(lp2, heatineq) op.addconstraint(lp2,heatlimiteq) if heatorcool == 'cool': lp2 = op(dot(-cc,x),ineq) op.addconstraint(lp2, coolineq) lp2.solve() if x.value == None: energy = matrix(0.00, (13,1)) print('energy consumption') j=0 while j<13: print(energy[j]) j = j+1 j=0
def __init__(self, name, recipe, core_data): '''Set up the LP problem variables and constraints that hold for a given recipe, apart from the used-defined inequalities''' self.ingredient_dict = core_data.ingredient_dict self.oxide_dict = core_data.oxide_dict self.other_dict = core_data.other_dict self.ingredient_analyses = core_data.ingredient_analyses self.attr_dict = core_data.attr_dict self.current_oxides = recipe.oxides self.current_ingredients = recipe.ingredients self.current_attr = list(core_data.attr_dict.keys( )) # Not worth only selecting the ones relevant to the recipe self.current_other = recipe.other if len(self.current_ingredients) == 0: messagebox.showerror( " ", 'Select ingredients from the panel on the left.') elif len(self.current_oxides) == 0: messagebox.showerror( " ", 'It appears all the ingredients in this recipe are oxide-free.' ) elif sum(self.oxide_dict[ox].flux for ox in self.current_oxides) == 0: messagebox.showerror(" ", 'No flux! You have to give a flux.') # Run tests to see if the denominators of other restrictions are identically zero? else: self.go_ahead = True # Create variables self.lp_var = { } # a dictionary for the variables in the linear programming problem self.lp_var['mole'] = variable(len(self.current_oxides), 'mole') # a vector-valued variable self.lp_var['mass'] = variable(len(self.current_oxides), 'mass') # likewise self.lp_var['ingredient'] = variable(len(self.current_ingredients), 'ingredients') if len(self.current_attr) > 0: self.lp_var['attr'] = variable(len(self.current_attr), 'attributes') if len(self.current_other) > 0: self.lp_var['other'] = variable(len(self.current_other), 'other') # Create variables used to normalize: for total in [ 'ingredient_total', 'fluxes_total', 'ox_mass_total', 'ox_mole_total' ]: self.lp_var[total] = variable(1, total) # Create relations self.relations = [] # Relate masses and moles: molar_masses = [ self.oxide_dict[ox].molar_mass for ox in self.current_oxides ] # check order molar_mass_diag = matrix( np.diag(molar_masses).tolist()) # check order self.relations.append(molar_mass_diag * self.lp_var['mole'] == self.lp_var['mass']) # Relate ingredients and oxide masses #analysis_matrix = self._make_matrix(self.ingredient_analyses.loc[self.current_ingredients, self.current_oxides]/100) analysis_matrix = matrix([[ (self.ingredient_analyses[i][ox] * 1.0 if ox in self.ingredient_analyses[i] else 0.0) for ox in self.current_oxides ] for i in self.current_ingredients]) self.relations.append(self.lp_var['mass'] == analysis_matrix * self.lp_var['ingredient']) # Relate ingredients and other attributes. #attr_matrix = self._make_matrix(self.ingredient_analyses.loc[self.current_ingredients, self.other_attributes]) attr_matrix = matrix([[ (self.ingredient_dict[i].attributes[j] / 100 if j in self.ingredient_dict[i].attributes else 0) for j in self.current_attr ] for i in self.current_ingredients]) self.relations.append(self.lp_var['attr'] == attr_matrix * self.lp_var['ingredient']) # Relate other restrictions to the variables that define them # Ensure that only oxides and ingredients already selected are included """other_matrix = matrix([[(self.other_dict[i][j]*1.0 if j in self.ingredient_analyses[i] else 0.0) for j in self.current_other] for i in self.current_ingredients]) """ for i, j in enumerate(self.current_other): lc = self._linear_combination( self.other_dict[j].numerator_coefs) self.relations.append(self.lp_var['other'][i] == lc) # Relate normalizing variables to others flux_gate = matrix( [self.oxide_dict[ox].flux * 1. for ox in self.current_oxides]) self.relations.append(self.lp_var['fluxes_total'] == dot( flux_gate, self.lp_var['mole'])) self.relations.append( self.lp_var['ox_mass_total'] == sum(self.lp_var['mass'])) self.relations.append( self.lp_var['ox_mole_total'] == sum(self.lp_var['mole'])) self.relations.append(self.lp_var['ingredient_total'] == sum( self.lp_var['ingredient']))
# The robust LP example of section 10.5 (Examples). from cvxopt import normal, uniform from cvxopt.modeling import variable, dot, op, sum from cvxopt.blas import nrm2 m, n = 500, 100 A = normal(m,n) b = uniform(m) c = normal(n) x = variable(n) op(dot(c,x), A*x+sum(abs(x)) <= b).solve() x2 = variable(n) y = variable(n) op(dot(c,x2), [A*x2+sum(y) <= b, -y <= x2, x2 <= y]).solve() print("\nDifference between two solutions %e" %nrm2(x.value - x2.value))