# -*- coding: utf-8 -*-
"""Untitled4.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1xgKGlso_B7GKs7t1qFUNOrB2G3Z3hRKt

Using tool from http://pymprog.sourceforge.net/

"""

!pip install pymprog

from pymprog import model

#Questao "Problema do Transporte"

#########################################################
#PARAMETROS DO PROBLEMA:
#########################################################
demanda = [-5, 3, 0, 1, 0, 11, -10]

#arco origem, destino, peso
arcos = [[0, 1, 7],\
         [0, 2, 3],\
         [0, 5, 7],\
         [1, 2, 1],\
         [1, 3, 5],\
         [2, 1, 3],\
         [2, 4, 2],\
         [2, 5, 4],\
         [3, 1, 1],\
         [4, 3, 5],\
         [4, 5, 1],\
         [5, 6, 3],\
         [6, 3, 11],\
         [6, 4, 2]]

intermediarios=[]
for i in range(len(demanda)):
  if demanda[i] == 0:
    intermediarios.append(i)

fontes=[]
for i in range(len(demanda)):
  if demanda[i] < 0:
    fontes.append(i)    
    
sorvedouros=[]
for i in range(len(demanda)):
  if demanda[i] > 0:
    sorvedouros.append(i)    
    

#########################################################
#DEFINIÇÃO DO MODELO:
#########################################################    
m = model('basic')
x = m.var('x', len(arcos)) 

#função objetivo
m.minimize(sum(arcos[i][2]*x[i] for i in range(len(arcos))))


#quantidade que passa pelos vértices intermediarios
for j in intermediarios:
  soma = 0
  for e in range(len(arcos)):
    u, v, w = arcos[e]
    if v == j: soma += x[e]
    if u == j: soma -= x[e]
  soma == 0 
  
#quantidade que passa pelos vértices fontes
for j in fontes:
  soma = 0
  for e in range(len(arcos)):
    u, v, w = arcos[e]
    if v == j: soma += x[e] 
    if u == j: soma -= x[e]
  soma == demanda[j]

  
#quantidade que passa pelos vértices sorvedouros
for j in sorvedouros:
  soma = 0
  for e in range(len(arcos)):
    u, v, w = arcos[e]
    if v == j: soma += x[e] 
    if u == j: soma -= x[e]
  soma == demanda[j]
  
m.solve() # solve the model
print("###>Objective value: %f"%m.vobj())


for e in range(len(arcos)):
  u, v, w = arcos[e]
  print(str((u, v))+" -> "+str(x[e].primal))

m.end()
