rocarvaj
10/11/2012 - 3:40 PM

Convert .dow and .csv files to .lp

Convert .dow and .csv files to .lp

#!/usr/bin/python

"""
Convert an instance from the multicommodity fixed charge
network flow problem in .csv format to .lp file (arc formulation)

Usage: ./csvToLP.py path/to/my/csv/file.csv

Rodolfo Carvajal <rocarvaj@gatech.edu>

"""

import sys
import os
import re
import time
import random

class Arc(object):
    """ An arc in the graph """
    def __init__(self, origin=None, dest=None, varCost=None, fixCost=None, capac=None):
        self.origin = origin
        self.dest = dest
        self.varCost = varCost
        self.fixCost = fixCost
        self.capac = capac

class Comm(object):
    """ A commodity """
    def __init__(self, index=None, origin=None, dest=None, size=None):
        self.origin = origin
        self.dest = dest
        self.size = size
        self.index = index

t_init = time.clock()
filename = sys.argv[1]
print "Reading file:", filename
print "Output file:", filename.split('.csv')[0]+".lp" 

inFile = open(filename, 'r')
outFile = open(filename.split('.csv')[0]+".lp", 'w')
outFile.write("\\ "+filename+"\n")

arcs = []
commodities = []

line = inFile.readline()
line = inFile.readline().rstrip()

## Read nodes
tokens = line.split(',')
numberNodes = int(tokens[1])

for i in range(numberNodes):
	line = inFile.readline()

## Read arcs
line = inFile.readline().rstrip()
tokens = line.split(',')
numberArcs = int(tokens[1])

for i in range(numberArcs):
    line = inFile.readline().rstrip()
    tokens = line.split(',')
    arcs.append(Arc(int(tokens[0]), int(tokens[1]), float(tokens[2]), float(tokens[3]), float(tokens[4])))

## Read commodities
line = inFile.readline().rstrip()
tokens = line.split(',')
numberComms = int(tokens[1])

for i in range(numberComms):
    line = inFile.readline().rstrip()
    tokens = line.split(',')
    commodities.append(Comm(i, int(tokens[0]), int(tokens[1]), float(tokens[2])))

# Done with reading
outFile.write("MINIMIZE\n")
outFile.write(" obj: ")

first = 1
for a in arcs:
    for c in commodities:
        coef = c.size * a.varCost;
        if first == 0:
            outFile.write("+ ")
        else:
            first = 0
        outFile.write(str(coef)+" x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+") ")
    outFile.write("+ "+str(a.fixCost)+" y("+str(a.origin)+","+str(a.dest)+")")
    outFile.write("\n");

## We shuffle the way variables show up in the objective function
#first = 1
#for index in range(numberArcs*(numberComms + 1)):
#    if first == 0:
#        outFile.write("+ ")
#    else:
#        first = 0
#    aIndex = indexArray[index]/(numberComms + 1)
#    cIndex = indexArray[index] % (numberComms + 1)
#    if cIndex == numberComms:
#        outFile.write(str(arcs[aIndex].fixCost)+" y("+str(arcs[aIndex].origin)+","+str(arcs[aIndex].dest)+")")
#    else:
#        coef = commodities[cIndex].size * arcs[aIndex].varCost;
#        outFile.write(str(coef)+" x("+str(arcs[aIndex].origin)+","+str(arcs[aIndex].dest)+","+str(aIndex)+")("+str(commodities[cIndex].index)+") ")
#outFile.write("\n");


outFile.write("\nSubject to\n")

for c in commodities:
    for i in range(1, numberNodes + 1):
        first = 1
        for a in arcs:
            if a.origin == i:
                if first == 0:
                    outFile.write(" +")
                else:
                    first = 0
                outFile.write(" x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+")")
            elif a.dest == i:
                if first == 1:
                    first = 0
                outFile.write(" -")
                outFile.write(" x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+")")
        outFile.write(" = ")
        if c.origin == i:
            outFile.write("1\n")
        elif c.dest == i:
            outFile.write("-1\n")
        else:
            outFile.write("0\n")

for a in arcs:
    first = 1
    for c in commodities:
        if first == 0:
            outFile.write(" +")
        else:
            first = 0
        outFile.write(str(c.size)+" x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+")")
    outFile.write(" - "+str(a.capac)+" y("+str(a.origin)+","+str(a.dest)+")")
    outFile.write(" <= 0\n")

outFile.write("\nBinaries\n")

#if singlePath == False:
#    outFile.write("Bounds\n")
#    for a in arcs:
#        for c in commodities:
#            outFile.write("0 <= x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+") <= 1")

# y variables
for a in arcs:
    outFile.write("y("+str(a.origin)+","+str(a.dest)+")\n")
    for c in commodities:
        outFile.write("x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+")\n")

outFile.write("End\n")
print "Done in", time.clock() - t_init, "seconds\n"

outFile.close()
#!/usr/bin/python

"""
Convert an instance from the multicommodity fixed charge
network flow problem in .dow format (as in http://www.di.unipi.it/di/groups/optimize/Data/MMCF.html#NetDesMMCF)
to .lp file (arc formulation)

Nodes are numbered from 1, but commodities from 0

Usage: ./dowToLP.py path/to/my/dow/file.dow

Rodolfo Carvajal <rocarvaj@gatech.edu>

"""

import sys
import os
import re
import time
import random

class Arc(object):
    """ An arc in the graph """
    def __init__(self, origin=None, dest=None, varCost=None, fixCost=None, capac=None):
        self.origin = origin
        self.dest = dest
        self.varCost = varCost
        self.fixCost = fixCost
        self.capac = capac

class Comm(object):
    """ A commodity """
    def __init__(self, index=None, origin=None, dest=None, size=None):
        self.origin = origin
        self.dest = dest
        self.size = size
        self.index = index

t_init = time.clock()
filename = sys.argv[1]
print "Reading file:", filename
print "Output file:", filename.split('.dow')[0]+".lp" 

inFile = open(filename, 'r')
outFile = open(filename.split('.dow')[0]+".lp", 'w')
outFile.write("\\ "+filename+"\n")

arcs = []
commodities = []

line = inFile.readline()
line = inFile.readline().rstrip()

tokens = line.split()

numberNodes = int(tokens[0])
numberArcs = int(tokens[1])
numberComms = int(tokens[2])

indexArray = range(numberArcs*(numberComms + 1))

for i in range(numberArcs):
    line = inFile.readline().rstrip()
    tokens = line.split()
    arcs.append(Arc(int(tokens[0]), int(tokens[1]), float(tokens[2]), float(tokens[4]), float(tokens[3])))

for i in range(numberComms):
    line = inFile.readline().rstrip()
    tokens = line.split()
    commodities.append(Comm(i, int(tokens[0]), int(tokens[1]), float(tokens[2])))

# Done with reading

outFile.write("MINIMIZE\n")
outFile.write(" obj: ")

first = 1
for a in arcs:
    for c in commodities:
        coef = c.size * a.varCost;
        if first == 0:
            outFile.write("+ ")
        else:
            first = 0
        outFile.write(str(coef)+" x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+") ")
    outFile.write("+ "+str(a.fixCost)+" y("+str(a.origin)+","+str(a.dest)+")")
    outFile.write("\n");

outFile.write("\nsubject to\n")

for c in commodities:
    for i in range(1, numberNodes + 1):
        first = 1
        for a in arcs:
            if a.origin == i:
                if first == 0:
                    outFile.write(" +")
                else:
                    first = 0
                outFile.write(" x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+")")
            elif a.dest == i:
                if first == 1:
                    first = 0
                outFile.write(" -")
                outFile.write(" x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+")")
        outFile.write(" = ")
        if c.origin == i:
            outFile.write("1\n")
        elif c.dest == i:
            outFile.write("-1\n")
        else:
            outFile.write("0\n")

for a in arcs:
    first = 1
    for c in commodities:
        if first == 0:
            outFile.write(" +")
        else:
            first = 0
        outFile.write(str(c.size)+" x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+")")
    outFile.write(" - "+str(a.capac)+" y("+str(a.origin)+","+str(a.dest)+")")
    outFile.write(" <= 0\n")

outFile.write("\nBinaries\n")

#if singlePath == False:
#    outFile.write("Bounds\n")
#    for a in arcs:
#        for c in commodities:
#            outFile.write("0 <= x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+") <= 1")

# y variables
for a in arcs:
    outFile.write("y("+str(a.origin)+","+str(a.dest)+")\n")
    for c in commodities:
        outFile.write("x("+str(a.origin)+","+str(a.dest)+")("+str(c.index)+")\n")

outFile.write("End\n")
print "Done in", time.clock() - t_init, "seconds\n"

outFile.close()