Search code examples
pythonsetcplexdocplexoperations-research

How to import CSV file in Python API of CPLEX


I would like to import this file http://people.brunel.ac.uk/~mastjjb/jeb/orlib/files/scp61.txt . Does CPLEX support this format in Python? I converted the text file to a CSV file then wrote this code cplex.read("scp61.csv") but I got this error"CPLEX Error 1436: Max or Min missing."
There isn't any Max or Min word in the text file.


Solution

  • scp61 contains the data but not the model.

    In python it's possible to parse the file and then call cplex through the docplex python API.

    from docplex.mp.model import Model
    
    
    file = open('scp61.txt', 'r')
    count = 0
    
    values=[]
    print("Using for loop")
    for line in file:
        count += 1
        ar=line.split()
        for i in ar:
            values.append(int(i))
     
    file.close()
    
    n=values[0]
    m=values[1]
    
    print("n=",n)
    print("m=",m)
    
    values2=values[2:]
    
    mdl = Model(name='scp')
    
    #decision variables
    x=[mdl.binary_var(name='x'+str(i)) for i in range(1,m+1) ]
    
    #objective
    mdl.minimize(mdl.sum(x[i-1]*values2[i-1] for i in range(1,m+1)))
    
    index=0
    index=index+m
    i=0
    
    while (index!=len(values2)):
        
        i=i+1
        nbr=values2[index]
       
        index=index+1
        which=[]
        for j in range(0,nbr):
            index=index+1
            
            
            if index==len(values2):
                break
            which.append(values2[index])
        #constraint    
        mdl.add(1<=mdl.sum(x[j-1] for j in which),"ct"+str(i))
    
    mdl.solve(log_output=True,)
    
    for v in mdl.iter_binary_vars():
        if (v.solution_value!=0):
            print(v," = ",v.solution_value)