genconstr.R


# 2023年版权,Gurobi优化狗万app足彩,LLC # #在这个例子中,我们展示了使用通用约束建模#一些常见的表达式。我们使用作为一个例子一个sat问题#想看看是否可以满足至少四(或者全部)条款的逻辑# # # L = (x0或~ x1和x2)和(x1和x2 ~或x3)和# (x2 ~ x3或x0)和(x3 ~ x0或x1)和# (~ x0或~ x1和x2)和(~ ~ x1和x2或x3)和# (x2 ~ ~ x3或x0)和(~ x3 ~ x0或x1) # #我们通过引入两个变量为每个文字(本身和其#否定价值),一个变量对于每一个条款,然后两个#变量指示如果我们能满足四个,而另一个确定#的最低条款(如果它,我们可以满足所有条款)#,把这两个变量的目的。#即目标函数将# #最大化Obj0 +其中Obj1 # # Obj0 = MIN (Clause1,……Clause8) #其中Obj1 = 1 - > Clause1 +……+ Clause8 > = 4 # #因此,客观价值将两个当且仅当我们可以满足所有#条款;当且仅当一个至少有四个条款可以满意,否则和# 0。#库(矩阵)库(gurobi) #设置参数参数< -()参数列表美元日志文件< - genconstr。日志' #定义原始数据nLiterals < - 4 nClauses < < - 2 - 8 nObj据nvar < - 2 * nLiterals + nClauses + nObj文字< -函数(n) {n} NotLit < -函数(n) {n + nLiterals}条款< -函数(n) {2 * nLiterals + n} Obj < -函数(n) {2 * nLiterals + nClauses + n}条款< -列表(c(文字(1)NotLit(2),文字(3)),c (NotLit文字(2),(3),文字(4)),c (NotLit文字(3),(4),文字(1)),c(文字(4),NotLit(1),文字(2)),c (NotLit (1) NotLit(2),文字(3)),c (NotLit (2), NotLit(3),文字(4)),c (NotLit (3), NotLit(4),文字(1)),c (NotLit (4), NotLit(1),文字(2)))# < -创建模型模型列表()模型美元modelname < -“genconstr”模型美元modelsense < -“max”#创建目标函数,变量名,和变量类型模型美元vtype < -代表(“B”,据nvar)模型美元乌兰巴托< -代表(1,据nvar)模型美元varnames < - c (sprintf (X % d, seq (nLiterals)), sprintf (notX % d, seq (nLiterals)), sprintf (% d条款,seq (nClauses)), sprintf (Obj % d, seq (nObj)))模型美元obj < - c(代表(0,2 * nLiterals + nClauses),代表(1,nObj)) #创建线性约束链接文字而不是文字模式美元< - spMatrix(据nvar nLiterals,我= c (seq (1, nLiterals), seq (nLiterals)), j = c (seq (1, nLiterals), seq (1 + nLiterals, 2 * nLiterals)), x =代表(1、2 * nLiterals))模型美元constrnames < - c (sprintf (CNSTR_X % d, seq (nLiterals)))模型美元nLiterals rhs < -代表(1)模型美元<——代表(“=”,nLiterals) #创建连接或一般约束条款和文本模式美元genconor < -拉普(1:nClauses,函数(i)列表(resvar =条款(i), var =条款[[我]],name = sprintf (CNSTR_Clause % d ',我)))#设置其中Obj1 = Min(条款[1:nClauses])模型美元genconmin < -列表(列表(resvar = Obj (1), var = c (seq((1)条款(nClauses))), name = ' CNSTR_Obj1 ')) #的指标约束期盼我们下列向量类型#线性求和:# # -一个密集的向量,例如# c(代表(0,2 * nLiterals),代表(1,nClauses),代表(0,nObj)) #——一个稀疏的向量,例如# sparseVector (x =代表(1,nClauses), i = (2 * nLiterals + 1): (2 * nLiterals + nClauses),长度=据nvar) #——所有的系数都是一样的,你可以通过一个向量的长度#一个相应的值,扩展到一个密集的向量与所有的值被给定一个# # #我们使用稀疏向量在本例<——sparseVector (x =代表(1,nClauses), i = (2 * nLiterals + 1): (2 * nLiterals + nClauses),长度=据nvar) #设置methoda信号如果任何条款都满意,例如#我们使用一个指标约束的形式:# (methoda = 1) - >(条款[1:nClauses])和> = 4模型美元genconind < -列表(列表(binvar = Obj (2), binval = 1, a =, = ' > ', rhs = 4, name = ' CNSTR_Obj2 ')) # gurobi_write保存模型(模型、genconstr。lp ', params) #优化结果< - gurobi(模型、params = params) #检查优化状态如果结果美元状态= = '最佳'){如果结果美元objval > 1.9){猫(“逻辑表达式是可以满足的\ n”)}如果(结果美元objval > 0.9){猫(至少四个条款是可以满足的\ n”)}其他{猫(最多的三个条款可能可以满足的\ n”)}}其他{猫(“优化失败\ n”)} #腾出rm (params,模型,结果条款)