manbet体育手机客户端


genconstr.m


在这个例子中,我们展示了使用通用约束建模%一些常见的表达式。狗万app足彩我们使用作为一个例子一个sat问题%想看看是否有可能满足至少四(或者全部)条款逻辑的% % % L = (x1, x2 ~或者x3)和(x2 ~ x3或x4)和% (x3或~ x4或x1)和(x4或~ x1和x2)和% (~ ~ x1和x2或x3)和(~ x2 ~ x3或x4)和% (~ x3 ~ x4或x1)和(~ x4或~ x1和x2) % %我们这样做引入两个变量为每个文字(本身及其%否定价值),一个变量对于每一个条款,然后两个%变量指示如果我们能满足四个,而另一个识别%的最低条款(如果它,我们可以满足所有条款)%,把这两个变量的目的。%即目标函数将% %最大化Obj1 + Obj2 % % Obj1 = MIN(Clause2,…, % Obj2 = 2 ->+ Clause8 >= 4% %,当且仅当我们能满足所有%子句时,客观值将为2;1当且仅当至少满足四个子句,否则% 0。% %定义原始数据n = 4;nLiterals = 4;nClauses = 8; nObj = 2; nVars = 2 * nLiterals + nClauses + nObj; Clauses = [ 1, n+2, 3; 2, n+3, 4; 3, n+4, 1; 4, n+1, 2; n+1, n+2, 3; n+2, n+3, 4; n+3, n+4, 1; n+4, n+1, 2 ]; % Create model model.modelname = 'genconstr'; model.modelsense = 'max'; % Set-up data for variables and constraints model.vtype = repmat('B', nVars, 1); model.ub = ones(nVars, 1); model.obj = [zeros(2*nLiterals + nClauses, 1); ones(nObj, 1)]; model.A = sparse(nLiterals, nVars); model.rhs = ones(nLiterals, 1); model.sense = repmat('=', nLiterals, 1); for j = 1:nLiterals model.varnames{j} = sprintf('X%d', j); model.varnames{nLiterals+j} = sprintf('notX%d', j); end for j = 1:nClauses model.varnames{2*nLiterals+j} = sprintf('Clause%d', j); end for j = 1:nObj model.varnames{2*nLiterals+nClauses+j} = sprintf('Obj%d', j); end % Link Xi and notXi for i = 1:nLiterals model.A(i, i) = 1; model.A(i, nLiterals+i) = 1; model.constrnames{i} = sprintf('CNSTR_X%d', i); end % Link clauses and literals for i = 1:nClauses model.genconor(i).resvar = 2 * nLiterals + i; model.genconor(i).vars = Clauses(i:i,1:3); model.genconor(i).name = sprintf('CNSTR_Clause%d', i); end % Link objs with clauses model.genconmin.resvar = 2 * nLiterals + nClauses + 1; for i = 1:nClauses model.genconmin.vars(i) = 2 * nLiterals + i; end model.genconmin.name = 'CNSTR_Obj1'; model.genconind.binvar = 2 * nLiterals + nClauses + 2; model.genconind.binval = 1; model.genconind.a = [zeros(2*nLiterals,1); ones(nClauses,1); zeros(nObj,1)]; model.genconind.sense = '>'; model.genconind.rhs = 4; model.genconind.name = 'CNSTR_Obj2'; % Save model gurobi_write(model, 'genconstr_m.lp'); % Optimize params.logfile = 'genconstr.log'; result = gurobi(model, params); % Check optimization status if strcmp(result.status, 'OPTIMAL') if result.objval > 1.9 fprintf('Logical expression is satisfiable\n'); else if result.objval > 0.9 fprintf('At least four clauses are satisfiable\n'); else fprintf('At most three clauses may be satisfiable\n'); end end else fprintf('Optimization falied\n'); end