def maxcutrel(A, solver=None): from cvxopt.base import matrix as m from cvxopt.base import spmatrix as spm from cvxopt import solvers if solver=='dsdp': from cvxopt import dsdp solvers.options['show_progress']=True # solvers.options['show_progress']=False # data type and dimensions try: A = A.weighted_adjacency_matrix() return maxcutrel(A, solver=solver) except (AttributeError,TypeError): try: A = A.adjacency_matrix() return maxcutrel(A, solver=solver) except (AttributeError,TypeError): pass pass try: d = A.nrows() # SDP constraints c = m([-1.]*d) G = [spm(1., [i*(d+1) for i in range(d)], range(d), (d*d,d))] sol = solvers.sdp(c, Gs=G, hs=[m(1.*A.numpy())], solver=solver) return 0.25*(sum(sum(A))+sol['primal objective']),sol #return sol['primal objective'], sol['status'] except AttributeError: print "Wrong matrix format" raise else: print "Unknown error" raise
def linear_program(c, G, h, A=None, b=None, solver=None): """ Solves the dual linear programs: - Minimize `c'x` subject to `Gx + s = h`, `Ax = b`, and `s \geq 0` where `'` denotes transpose. - Maximize `-h'z - b'y` subject to `G'z + A'y + c = 0` and `z \geq 0`. INPUT: - ``c`` -- a vector - ``G`` -- a matrix - ``h`` -- a vector - ``A`` -- a matrix - ``b`` --- a vector - ``solver`` (optional) --- solver to use. If None, the cvxopt's lp-solver is used. If it is 'glpk', then glpk's solver is used. These can be over any field that can be turned into a floating point number. OUTPUT: A dictionary ``sol`` with keys ``x``, ``s``, ``y``, ``z`` corresponding to the variables above: - ``sol['x']`` -- the solution to the linear program - ``sol['s']`` -- the slack variables for the solution - ``sol['z']``, ``sol['y']`` -- solutions to the dual program EXAMPLES: First, we minimize `-4x_1 - 5x_2` subject to `2x_1 + x_2 \leq 3`, `x_1 + 2x_2 \leq 3`, `x_1 \geq 0`, and `x_2 \geq 0`:: sage: c=vector(RDF,[-4,-5]) sage: G=matrix(RDF,[[2,1],[1,2],[-1,0],[0,-1]]) sage: h=vector(RDF,[3,3,0,0]) sage: sol=linear_program(c,G,h) sage: sol['x'] (0.999..., 1.000...) Next, we maximize `x+y-50` subject to `50x + 24y \leq 2400`, `30x + 33y \leq 2100`, `x \geq 45`, and `y \geq 5`:: sage: v=vector([-1.0,-1.0,-1.0]) sage: m=matrix([[50.0,24.0,0.0],[30.0,33.0,0.0],[-1.0,0.0,0.0],[0.0,-1.0,0.0],[0.0,0.0,1.0],[0.0,0.0,-1.0]]) sage: h=vector([2400.0,2100.0,-45.0,-5.0,1.0,-1.0]) sage: sol=linear_program(v,m,h) sage: sol['x'] (45.000000..., 6.2499999...3, 1.00000000...) sage: sol=linear_program(v,m,h,solver='glpk') GLPK Simplex Optimizer... OPTIMAL SOLUTION FOUND sage: sol['x'] (45.0..., 6.25, 1.0...) """ from cvxopt.base import matrix as m from cvxopt import solvers solvers.options['show_progress'] = False if solver == 'glpk': from cvxopt import glpk glpk.options['LPX_K_MSGLEV'] = 0 c_ = m(c.base_extend(RDF).numpy()) G_ = m(G.base_extend(RDF).numpy()) h_ = m(h.base_extend(RDF).numpy()) if A != None and b != None: A_ = m(A.base_extend(RDF).numpy()) b_ = m(b.base_extend(RDF).numpy()) sol = solvers.lp(c_, G_, h_, A_, b_, solver=solver) else: sol = solvers.lp(c_, G_, h_, solver=solver) status = sol['status'] if status != 'optimal': return { 'primal objective': None, 'x': None, 's': None, 'y': None, 'z': None, 'status': status } x = vector(RDF, list(sol['x'])) s = vector(RDF, list(sol['s'])) y = vector(RDF, list(sol['y'])) z = vector(RDF, list(sol['z'])) return { 'primal objective': sol['primal objective'], 'x': x, 's': s, 'y': y, 'z': z, 'status': status }
def linear_program(c,G,h,A=None,b=None,solver=None): """ Solves the dual linear programs: - Minimize `c'x` subject to `Gx + s = h`, `Ax = b`, and `s \geq 0` where `'` denotes transpose. - Maximize `-h'z - b'y` subject to `G'z + A'y + c = 0` and `z \geq 0`. INPUT: - ``c`` -- a vector - ``G`` -- a matrix - ``h`` -- a vector - ``A`` -- a matrix - ``b`` --- a vector - ``solver`` (optional) --- solver to use. If None, the cvxopt's lp-solver is used. If it is 'glpk', then glpk's solver is used. These can be over any field that can be turned into a floating point number. OUTPUT: A dictionary ``sol`` with keys ``x``, ``s``, ``y``, ``z`` corresponding to the variables above: - ``sol['x']`` -- the solution to the linear program - ``sol['s']`` -- the slack variables for the solution - ``sol['z']``, ``sol['y']`` -- solutions to the dual program EXAMPLES: First, we minimize `-4x_1 - 5x_2` subject to `2x_1 + x_2 \leq 3`, `x_1 + 2x_2 \leq 3`, `x_1 \geq 0`, and `x_2 \geq 0`:: sage: c=vector(RDF,[-4,-5]) sage: G=matrix(RDF,[[2,1],[1,2],[-1,0],[0,-1]]) sage: h=vector(RDF,[3,3,0,0]) sage: sol=linear_program(c,G,h) sage: sol['x'] (0.999..., 1.000...) Next, we maximize `x+y-50` subject to `50x + 24y \leq 2400`, `30x + 33y \leq 2100`, `x \geq 45`, and `y \geq 5`:: sage: v=vector([-1.0,-1.0,-1.0]) sage: m=matrix([[50.0,24.0,0.0],[30.0,33.0,0.0],[-1.0,0.0,0.0],[0.0,-1.0,0.0],[0.0,0.0,1.0],[0.0,0.0,-1.0]]) sage: h=vector([2400.0,2100.0,-45.0,-5.0,1.0,-1.0]) sage: sol=linear_program(v,m,h) sage: sol['x'] (45.000000..., 6.2499999...3, 1.00000000...) sage: sol=linear_program(v,m,h,solver='glpk') GLPK Simplex Optimizer... OPTIMAL SOLUTION FOUND sage: sol['x'] (45.0..., 6.25, 1.0...) """ from cvxopt.base import matrix as m from cvxopt import solvers solvers.options['show_progress']=False if solver=='glpk': from cvxopt import glpk glpk.options['LPX_K_MSGLEV'] = 0 c_=m(c.base_extend(RDF).numpy()) G_=m(G.base_extend(RDF).numpy()) h_=m(h.base_extend(RDF).numpy()) if A!=None and b!=None: A_=m(A.base_extend(RDF).numpy()) b_=m(b.base_extend(RDF).numpy()) sol=solvers.lp(c_,G_,h_,A_,b_,solver=solver) else: sol=solvers.lp(c_,G_,h_,solver=solver) status=sol['status'] if status != 'optimal': return {'primal objective':None,'x':None,'s':None,'y':None, 'z':None,'status':status} x=vector(RDF,list(sol['x'])) s=vector(RDF,list(sol['s'])) y=vector(RDF,list(sol['y'])) z=vector(RDF,list(sol['z'])) return {'primal objective':sol['primal objective'],'x':x,'s':s,'y':y, 'z':z,'status':status}
#Problema Quemo Chemical Company from cvxopt import glpk from cvxopt.base import matrix as m c = m([-25000., -18000., -31000.]) #Matriz con los valores de la funcion objetivo A = m([[8000., 7000.], [6000., 4000.], [12000., 8000.]]) #Valores de las variables de las restricciones b = m([20000., 16000.]) #Valores independientes de las restricciones intVars = range(3) #Especificamos que las 3 variables son enteras binVars = range(3) #Especificamos que las 3 variables son binarias sol = glpk.ilp(c, A, b, I=set(intVars), B=set(binVars)) print('Los valores óptimos de las variables son:\n{0}'.format(sol[1])) #Si se encuantra valores optimos se muestran if sol[0]=='optimal': print('El valor óptimo es: {0}'.format((-c.T*sol[1])[0])) # El valor óptimo debemos transponerlo y cambiarle el signo, estamos maximizando. else: print('El problema no devolvió una solución óptima. El estado del solucionador fue {0}'.format(sol[0])) #Si no encuentra dice que no se encontro
c_pickle = [] old_q = 0 for q in num_q: time_count = 0 if nx.has_path(G, 0, 1): if path_flag == False: path_form_charge = old_q path_flag = True else: old_q = q c_model_activated = [] # Initiating charge vector qv = np.zeros(nwires_plus_leads) qv[0] = +q qv[1] = -q Qmatrix = m(qv) # mc_matrix will be updated while noups=True noups = True # Store positions of activated junctions at this charge inter_point_act_charge = [] # Counts how many junctions were activated at this charge nactivated_total = 0 # Counts the time of the avalanche time = 0 # Loop for tries (mc_matrix might be updated at the same charge) while (noups):
#Problema Propuesto "Municipalidad" from cvxopt import glpk from cvxopt.base import matrix as m c = m( [-842628., -421314., -631971., -1263943., -1078564., -1137548., -758365.]) #Matriz con los valores de la funcion objetivo A = m([[1., 1., 1., 0., 0., 0., 1.], [0., 1., 0., 1., 0., 0., 0.], [0., 0., 1., 0., 1., 0., 0.], [0., 0., 0., 1., 1., 1., 0.], [1., 1., 1., 1., 0., 1., 1.], [0., 0., 0., 0., 1., 1., 1.], [1., 1., 0., 0., 0., 0., 1.]]) #Valores de las variables de las restricciones b = m([1., 1., 1., 1., 1., 1, 1.]) #Valores independientes de las restricciones intVars = range(7) #Especificamos que las 7 variables son enteras binVars = range(7) #Especificamos que las 7 variables son binarias sol = glpk.ilp(c, A, b, I=set(intVars), B=set(binVars)) print('Los valores óptimos de las variables son:\n{0}'.format( sol[1])) #Si se encuantra valores optimos se muestran if sol[0] == 'optimal': print('El valor óptimo es: ${0} COP'.format((-c.T * sol[1])[0])) # El valor óptimo debemos transponerlo y cambiarle el signo, estamos maximizando. else: print( 'El problema no devolvió una solución óptima. El estado del solucionador fue {0}' .format(sol[0])) #Si no encuentra dice que no se encontro
1), :] # determine rows corresponding to non-connected nodes mr_nonconnected_plus = mr_nozero_rows_plus[:, ~( mr_nozero_rows_plus == 0 ).all( 0 )] # remove the non-connected nodes, this is done for numerical reasons # some parameters for the symmlq numerical solving routine. til is tolerance, make it smaller for more accuracy, show plots some info to terminal during the routine, maxit limits the routine to a maximum number of iterations tol = 1e-10 show = False maxit = None i0 = 1.0 # test current through the network ic = np.zeros( mr_nonconnected_plus.shape[0]) # initialise the current vector ic[0] = +i0 # current injected into electrode 0 ic[1] = -i0 # current extracted at electrode 1 Imatrix = m(ic) # some function to get ic into correct format for symmlq Amatrix = m( mr_nonconnected_plus ) # # some function to get mr_connected_plus into correct format for symmlq elec_pot_mr = symmlq( Imatrix, Gfun, show=show, rtol=tol, maxit=maxit ) # solve the set of linear equations. elec_pot_mr[0] contains the potential of each node resistance = ((elec_pot_mr[0][0] - elec_pot_mr[0][1]) ) / i0 # resistance of the network between electrodes print(material, resistance)
def linear_program(c, G, h, A=None, b=None, solver=None): r""" Solve the dual linear programs: - Minimize `c'x` subject to `Gx + s = h`, `Ax = b`, and `s \geq 0` where `'` denotes transpose. - Maximize `-h'z - b'y` subject to `G'z + A'y + c = 0` and `z \geq 0`. This function is deprecated. Use :class:`MixedIntegerLinearProgram` instead. This function depends on the optional package ``cvxopt``. INPUT: - ``c`` -- a vector - ``G`` -- a matrix - ``h`` -- a vector - ``A`` -- a matrix - ``b`` --- a vector - ``solver`` (optional) --- solver to use. If None, the cvxopt's lp-solver is used. If it is 'glpk', then glpk's solver is used. These can be over any field that can be turned into a floating point number. OUTPUT: A dictionary ``sol`` with keys ``x``, ``s``, ``y``, ``z`` corresponding to the variables above: - ``sol['x']`` -- the solution to the linear program - ``sol['s']`` -- the slack variables for the solution - ``sol['z']``, ``sol['y']`` -- solutions to the dual program EXAMPLES: First, we minimize `-4x_1 - 5x_2` subject to `2x_1 + x_2 \leq 3`, `x_1 + 2x_2 \leq 3`, `x_1 \geq 0`, and `x_2 \geq 0`:: sage: c=vector(RDF,[-4,-5]) sage: G=matrix(RDF,[[2,1],[1,2],[-1,0],[0,-1]]) sage: h=vector(RDF,[3,3,0,0]) sage: sol=linear_program(c,G,h) # optional - cvxopt doctest:warning... DeprecationWarning: linear_program is deprecated; use MixedIntegerLinearProgram instead See https://trac.sagemath.org/32226 for details. sage: sol['x'] # optional - cvxopt (0.999..., 1.000...) Here we solve the same problem with 'glpk' interface to 'cvxopt':: sage: sol=linear_program(c,G,h,solver='glpk') # optional - cvxopt GLPK Simplex Optimizer... ... OPTIMAL LP SOLUTION FOUND sage: sol['x'] # optional - cvxopt (1.0, 1.0) Next, we maximize `x+y-50` subject to `50x + 24y \leq 2400`, `30x + 33y \leq 2100`, `x \geq 45`, and `y \geq 5`:: sage: v=vector([-1.0,-1.0,-1.0]) sage: m=matrix([[50.0,24.0,0.0],[30.0,33.0,0.0],[-1.0,0.0,0.0],[0.0,-1.0,0.0],[0.0,0.0,1.0],[0.0,0.0,-1.0]]) sage: h=vector([2400.0,2100.0,-45.0,-5.0,1.0,-1.0]) sage: sol=linear_program(v,m,h) # optional - cvxopt sage: sol['x'] # optional - cvxopt (45.000000..., 6.2499999..., 1.00000000...) sage: sol=linear_program(v,m,h,solver='glpk') # optional - cvxopt GLPK Simplex Optimizer... OPTIMAL LP SOLUTION FOUND sage: sol['x'] # optional - cvxopt (45.0..., 6.25..., 1.0...) """ deprecation( 32226, 'linear_program is deprecated; use MixedIntegerLinearProgram instead') from cvxopt.base import matrix as m from cvxopt import solvers solvers.options['show_progress'] = False if solver == 'glpk': from cvxopt import glpk glpk.options['LPX_K_MSGLEV'] = 0 c_ = m(c.base_extend(RDF).numpy()) G_ = m(G.base_extend(RDF).numpy()) h_ = m(h.base_extend(RDF).numpy()) if A is not None and b is not None: A_ = m(A.base_extend(RDF).numpy()) b_ = m(b.base_extend(RDF).numpy()) sol = solvers.lp(c_, G_, h_, A_, b_, solver=solver) else: sol = solvers.lp(c_, G_, h_, solver=solver) status = sol['status'] if status != 'optimal': return { 'primal objective': None, 'x': None, 's': None, 'y': None, 'z': None, 'status': status } x = vector(RDF, list(sol['x'])) s = vector(RDF, list(sol['s'])) y = vector(RDF, list(sol['y'])) z = vector(RDF, list(sol['z'])) return { 'primal objective': sol['primal objective'], 'x': x, 's': s, 'y': y, 'z': z, 'status': status }
Kirchoff_Mat[y][x] = Kirchoff_Mat[x][y] else: pass np.fill_diagonal((Kirchoff_Mat), abs(Kirchoff_Mat.sum(1))) I = 10.0 # total current being pumped through the system i0 = I / ( Lead ) # the current that will be put into each node on the left lead and is then extracted on the right lead ic = np.zeros(Kirch_Dim) # current vector for i in range(0, Lead - 1): # This loop fills in the current vector ic[i] = +i0 # an injection node ic[(Kirch_Dim) - i - 1] = -i0 # an extraction node Kirchoff_Matrix = m( Kirchoff_Mat ) # This just changes the format of Kirchoff_Mat so it can be solved by the symmlq routine Imatrix = m(ic) # puts ic in the format for symmlq # Solving Ax = B (Mr * V = I) with symmlq Amatrix = Kirchoff_Matrix # renamed Amatrix for Gfun function above elec_pot_mr = symmlq( Imatrix, Gfun, show=show, rtol=tol, maxit=maxit ) # result from symmlq. elec_pot_mr[0] is the voltage vector. V_left = list() V_right = list() for k in range(0, Lead - 1): # adding total voltages on each lead V_left.append(elec_pot_mr[0][k]) V_right.append(elec_pot_mr[0][(Kirch_Dim) - 1 - k])
def mnr_scan(Nw, in_node, out_node): t0 = time.time() def Gfun(x, y, trans='N'): ''' Function that passes matrix A to the symmlq routine which solves Ax=B.''' gemv(Amatrix, x, y, trans) resist_info = open( "mnr_conductance_curve_nodes_%s_%s.txt" % (in_node, out_node), "w") num_i = np.arange(0.001, 5, 0.001) Nw.mmr_mr_graph_build() mr_matrix = Nw.mnr_mr_matrix mr_mnr_matrix = mr_matrix neigh_mr = Nw.mnr_neigh nwires_plus_leads = len(Nw.coords) alph = 0.05 #3.5248 expon = 1.1 Roff = 10000.0 Ron = 11.0 for ic in num_i: # Initiating fixed current vector iv = np.zeros(len(mr_matrix)) iv[in_node] = +ic iv[out_node] = -ic Imatrix = m(iv) tol = 1e-10 show = False maxit = None mr_matrix_form = m(mr_matrix) Amatrix = mr_matrix_form elec_pot_mr = symmlq(Imatrix, Gfun, show=show, rtol=tol, maxit=maxit) resistance = (elec_pot_mr[0][in_node] - elec_pot_mr[0][out_node]) / ic #resistance = (pot[0]-pot[1])/ic print('Sheet Resistance: ', resistance, ic) resist_info.write('%s %s\n' % (ic, 1.0 / resistance)) #ax2 = plt.subplot2grid((1,2),(0,1),colspan=3) # Loop over all inter-wire connections for i in range(len(neigh_mr[0])): diffmr = abs(elec_pot_mr[0][neigh_mr[0][i]] - elec_pot_mr[0][neigh_mr[1][i]]) # current passing through the junction jcurr = diffmr / (abs( 1.0 / mr_matrix[neigh_mr[0][i], neigh_mr[1][i]])) # resistance updated as a function of its current new_resis = 1.0 / (alph * jcurr**expon) # thresholds (the junction resistance cannot be bigger than Roff or smaller than Ron) if new_resis > Roff: new_resis = Roff if new_resis < Ron: new_resis = Ron Ron_list.append([neigh_mr[0][i], neigh_mr[1][i], ival]) # modify resistance of the junction mr_matrix[neigh_mr[0][i], neigh_mr[1][i]] = -1.0 / new_resis mr_matrix[neigh_mr[1][i], neigh_mr[0][i]] = -1.0 / new_resis # Reset diagonal elements before updating Mr! np.fill_diagonal(mr_matrix, 0.0) sum_rows_mr = mr_matrix.sum(1) np.fill_diagonal(mr_matrix, abs(sum_rows_mr)) Ron_save = open( "mnr_Ron_list_nodes_%s_%s_scan_end_%s.txt" % (in_node, out_node, ival), "w") for row in Ron_list: Ron_save.write("%s %s %s\n" % (row[0], row[1], row[2])) Ron_save.close() resist_info.close() tf = time.time() print("TOTAL TIME: %s" % (tf - t0))
def jda_scan(Nw, in_node, out_node): def Gfun(x, y, trans='N'): ''' Function that passes matrix A to the symmlq routine which solves Ax=B.''' gemv(Amatrix, x, y, trans) resist_info = open( "jda_conductance_curve_nodes_%s_%s.txt" % (in_node, out_node), "w") num_i = np.arange(0.001, 5, 0.001) Nw.mmr_mr_graph_build() mr_matrix = Nw.jda_mr_matrix mr_jda_matrix = mr_matrix nwires_plus_leads = len(Nw.coords) alph = 0.05 #3.5248 expon = 1.1 Roff = 10000.0 Ron = 11.0 for ival in num_i: Ron_list = [] r_model_activated = [] # Initiating fixed current vector iv = np.zeros(len(mr_matrix)) iv[in_node] = +ival iv[out_node] = -ival Imatrix = m(iv) mr_matrix_form = m(mr_matrix) Amatrix = mr_matrix_form tol = 1e-10 show = False maxit = None elec_pot_mr = symmlq(Imatrix, Gfun, show=False, rtol=tol, maxit=maxit) resistance = abs(elec_pot_mr[0][in_node] - elec_pot_mr[0][out_node]) / ival conductance = 1.0 / resistance print('Sheet Resistance: %s, ic: %s ' % (resistance, ival)) resist_info.write('%s %s\n' % (ival, conductance)) #have to update Gr! # Loop over all inter-wire connections for i in range(nwires_plus_leads): for j in range(i + 1, nwires_plus_leads): if mr_jda_matrix[i][j] != 0: diffmr = abs(elec_pot_mr[0][i] - elec_pot_mr[0][j]) # current passing through the junction jcurr = diffmr / (abs(1.0 / mr_jda_matrix[i][j])) # resistance updated as a function of its current new_resis = 1.0 / (alph * jcurr**expon) # thresholds (the junction resistance cannot be bigger than Roff or smaller than Ron) if new_resis > Roff: new_resis = Roff if new_resis <= Ron: new_resis = Ron Ron_list.append([i, j, ival]) # modify resistance of the junction mr_jda_matrix[i][j] = -1.0 / new_resis mr_jda_matrix[j][i] = -1.0 / new_resis np.fill_diagonal(mr_jda_matrix, 0.0) sum_rows_mr = mr_jda_matrix.sum(1) # Place the sum in the diagonal of Mr. np.fill_diagonal(mr_jda_matrix, abs(sum_rows_mr)) resist_info.close() save_Ron(Ron_list, in_node, out_node, ival)