[Python] cplex 코드를 python 코드로 작성하기

2021. 6. 24. 17:13스터디/Python

0. 모델정의

(cplex)

확장자가 mod인 파일 저장

 

(python)

from docplex.mp.model import Model

mod = Model(name = 'model_name')

 

1. 변수 정의

(cplex)

int A = 3;
range N = 1..A;
float B[N]=[0.2, 0.7, 0.1];
int C[N][N] = [	[0.2, 0.7, 0.1],
                [0.2, 0.7, 0.1],
                [0.2, 0.7, 0.1]];

(python)

A = 3
N = range(1, A+1)
B = [0.2, 0.7, 0.1]
C = [	[0.2, 0.7, 0.1],
        [0.2, 0.7, 0.1],
        [0.2, 0.7, 0.1]]

 

2. 결정변수 정의

(cplex)

dvar boolean V1;
dvar int V2[N];

 

(python)

V1 = mod.binary_var(name='V1')
V2 = {n: mod.binary_var(name='V2_{0}'.format(n)) for n in N}

 

3. 목적함수(Objective)

(cplex)

minimize V1;

 

(python)

mod.minimize(V1)

 

4. 제약조건(subject to)

(cplex)

subject to{
    forall(n in N)
    	B[n]*V2[n] - A <= 1;
        
    forall(n in N)
    	V2[n] < V1;
}

 

(python)

for n in N:
    al.add_constraint(B[n]*V2[n] - A <= 1)

for n in N:
    al.add_constraint(V2[n] < V1)
    

 

5. 실행

(cplex)

실행버튼 클릭

 

(python)

mod_rlt = mod.solve()

# 결과보기
assert mod_rlt
mod_rlt.display()

# 특정 결정변수 도출
## (1) 1개 값
mod_rlt.solution.get_value(V1)

## (2) 2개 이상 값
mod_rlt.solution.get_values(V2)