Using Python and dask for optimization - python

I am working on a code which was developed using gurobipy, the objective is to integrate Dask package into it.The purpose is to run the code on a larger randomly generated dataset.
Below is the code and the closet I have come to is the code below this code. I am kind of struggling to finish it. I can't figure out how and where to input the Dask package.
import numpy as np
import gurobipy as gbp
import time
import dask.array as da
def GuTransProb():
t1 = time.time()
Demand
# 1000x1000
Cij = np.random.randint(100, 1000, 250000)
Cij = Cij.reshape(500,500)
print Cij
# Supply
Si = np.random.randint(500, 2000, 500)
Si = Si.reshape(500,1)
SiSum = np.sum(Si)
print SiSum
# Demand
Dj = np.sort(Si, axis=None)
DjSum = np.sum(Dj)
client_nodes = range(len(Cij))
print client_nodes
# 2. Create Model, Set MIP Focus, Add Variables, & Update Model
m = gbp.Model(' -- The Transportation Problem -- ')
# Set MIP Focus to 2 for optimality
gbp.setParam('MIPFocus', 2)
client_var = []
for orig in client_nodes:
client_var.append([])
for dest in client_nodes:
client_var[orig].append(m.addVar(vtype=gbp.GRB.CONTINUOUS,
obj=Cij[orig][dest],
name='x'+str(orig+1)+'_'+str(dest+1)))
print client_var
# Update Model Variables
m.update()
# 3. Set Objective Function
m.setObjective(gbp.quicksum(Cij[orig][dest]*client_var[orig][dest]
for orig in client_nodes for dest in client_nodes),
gbp.GRB.MINIMIZE)
# 4. Add Constraints
# Add Supply Constraints
for orig in client_nodes:
m.addConstr(gbp.quicksum(client_var[dest][orig]
for dest in client_nodes) - Si[orig] == 0,
'Supply_Constraint_%d' % orig)
# Add Demand Constraints
for orig in client_nodes:
m.addConstr(gbp.quicksum(client_var[orig][dest]
for dest in client_nodes) - Dj[orig] == 0,
'Demand_Constraint_%d' % orig)
# 5. Optimize and Print Results
try:
m.optimize()
except Exception as e:
print e
t2 = time.time()-t1
print '*****************************************************************************************'
print ' | From SUPPLY Facility to DEMAND Facility x(Si)_(Dj) shipping # of units '
print ' | ↓ ↓ ↓↓ ↓↓'
selected = []
for v in m.getVars():
if v.x > 0:
var = '%s' % v.VarName
value = '%i' % v.x
selected.append(v.x)
print ' | ', var, '_____ Units: ' ,value
print ' | Selected Facility Locations --------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ '
print ' | Candidate Facilities [p] ------------ ', len(selected)
print ' | Supply Sum -------------------------- ', SiSum
print ' | Demand Sum -------------------------- ', DjSum
val = m.objVal
print ' | Objective Value --------------------- ', int(val)
print ' | Real Time to Optimize (sec.) -------- ', t2
print '*****************************************************************************************'
print ' -- The Transportation Problem --'
m.write('path.lp')
try:
GuTransProb()
except Exception as e:
print e
import numpy as np
import gurobipy as gbp
import time
import dask.array as da
# 500x500
Cij = np.random.randint(100, 1000, 250000)
print Cij
Cij = Cij.reshape(500,500)
print Cij
Cij = da.from_array(Cij, chunks=(1000, 1000))
print Cij
# Supply
#Si = np.random.randint(500, 2000, 500)
#Si = Si.reshape(500,1)
#Si = da.from_array(Si, chunks=(100, 100))
Si = np.random.randint(500, 2000, 500)
print Si
Si = Si.reshape(500,1)
print Si
Si = da.from_array(Si, chunks=(1000, 1000))
print Si
SiSum = Si.sum()
print SiSum
# Demand
Dj = np.sort(Si, axis=None)
print Dj
DjSum = np.sum(Dj)
print DjSum
client_nodes = range(len(Cij))
print client_nodes
# 2. Create Model, Set MIP Focus, Add Variables, & Update Model
m = gbp.Model(' -- The Transportation Problem -- ')
# Set MIP Focus to 2 for optimality
gbp.setParam('MIPFocus', 2)
client_var = []
for orig in client_nodes:
client_var.append([])
for dest in client_nodes:
client_var[orig].append(m.addVar(vtype=gbp.GRB.CONTINUOUS,
obj=Cij[orig][dest],
name='x'+str(orig+1)+'_'+str(dest+1)))
print client_var
# Update Model Variables
m.update()
# 3. Set Objective Function
m.setObjective(gbp.quicksum(Cij[orig][dest]*client_var[orig][dest]
for orig in client_nodes for dest in client_nodes),
gbp.GRB.MINIMIZE)
# 4. Add Constraints
# Add Supply Constraints
for orig in client_nodes:
m.addConstr(gbp.quicksum(client_var[dest][orig]
for dest in client_nodes) - Si[orig] == 0,
'Supply_Constraint_%d' % orig)
# Add Demand Constraints
for orig in client_nodes:
m.addConstr(gbp.quicksum(client_var[orig][dest]
for dest in client_nodes) - Dj[orig] == 0,
'Demand_Constraint_%d' % orig)
# 5. Optimize and Print Results
try:
m.optimize()
except Exception as e:
print e
t2 = time.time()-t1
print '*****************************************************************************************'
print ' | From SUPPLY Facility to DEMAND Facility x(Si)_(Dj) shipping # of units '
print ' | ↓ ↓ ↓↓ ↓↓'
selected = []
for v in m.getVars():
if v.x > 0:
var = '%s' % v.VarName
value = '%i' % v.x
selected.append(v.x)
print ' | ', var, '_____ Units: ' ,value
print ' | Selected Facility Locations --------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ '
print ' | Candidate Facilities [p] ------------ ', len(selected)
print ' | Supply Sum -------------------------- ', SiSum
print ' | Demand Sum -------------------------- ', DjSum
val = m.objVal
print ' | Objective Value --------------------- ', int(val)
print ' | Real Time to Optimize (sec.) -------- ', t2
print '*****************************************************************************************'
print ' -- The Transportation Problem --'
m.write('path.lp')
try:
GuTransProb()
except Exception as e:
print e

Related

Double addition function, how to fix

I have a big problem with a part of my code:
the function below, it adds the values of the price column and the quantity column to extract the total amount of the order. But the price column is doubling the value and I can't find the error.
I've tried deleting the variable and clearing the memory cache, thinking it could be accumulating values.. but it's still the same!
This program is using pyqt6 and python3. is a program for issuing sales orders!
global row
# =============================================== SAVING VALUES INSERTED ON THE MAIN SCREEN IN VARIABLES
self.obter_resultado = self.ui.comboBox_produto.currentText()
self.obter_preco = (self.ui.insere_preco.text())
self.obter_quantide = (self.ui.insere_quantidade.text())
self.obter_cliente = (self.ui.insere_cliente.text())
self.obter_prazo = self.ui.comboBox_prazo.currentText()
self.obter_trasportadora = self.ui.comboBox_transport.currentText()
self.obter_frete = self.ui.comboBox_frete.currentText()
self.obter_num_pedido = (self.ui.insere_num_pedido.text())
self.obter_vendedor = self.ui.comboBox_vendedor.currentText()
self.obter_embalagem = self.ui.comboBox_embalagem.currentText()
self.obter_Nf = self.ui.checkBox_NF.isChecked()
self.obter_Snf = self.ui.checkBox_SNF.isChecked()
self.obter_obs = (self.ui.observacoes.text())
# =============================================== INSERTING PRICE, QUANTITY, PRODUCT AND PACKAGING IN THE "PRODUCTS" TABLE
self.ui.tabela_recebe_produto.setRowCount(len(self.obter_resultado))
self.ui.tabela_recebe_produto.setItem(row, 0, QtWidgets.QTableWidgetItem(self.obter_resultado))
self.ui.tabela_recebe_produto.setItem(row, 1, QtWidgets.QTableWidgetItem(self.obter_quantide + " kg"))
self.ui.tabela_recebe_produto.setItem(row, 2, QtWidgets.QTableWidgetItem("R$ " + self.obter_preco))
self.ui.tabela_recebe_produto.setItem(row, 3, QtWidgets.QTableWidgetItem(self.obter_embalagem))
row=row+1
# =============================================== SAVING VALUES TO A TEXT FILE
if os.path.isdir(r"C:\\Users\Public\Documents\Pie"):
print()
else:
os.mkdir(r"C:\\Users\Public\Documents\Pie")
try:
conteudo1 = open(f"C:\\Users\Public\Documents\Pie\Pedido_{self.obter_cliente}.txt", "r", encoding="utf-8").read()
except:
conteudo1 = ""
if re.search("PEDIDO DE VENDA..\n\nVENDEDOR:", conteudo1):
arq = open(f"C:\\Users\Public\Documents\Pie\Pedido_{self.obter_cliente}.txt", "w", encoding="utf-8")
arq.write(conteudo1+"PRODUTO: %s | QUANTIDADE: %s kg | PREÇO: R$ %s\r"%(self.obter_resultado, self.obter_quantide, self.obter_preco))
arq.close()
else:
arq = open(f"C:\\Users\Public\Documents\Pie\Pedido_{self.obter_cliente}.txt", "w", encoding="utf-8")
arq.write(conteudo1+"PEDIDO DE VENDA..\n\nVENDEDOR: %s\nCLIENTE: %s\nPRAZO: %s\nN°PEDIDO: %s\nNF: %s\nSnF: %s\nTRANSPORTADORA: %s\nFRETE: %s\nPRODUTO: %s | QUANTIDADE: %s kg | PREÇO: R$ %s\r\n\n Obs:%s\r"%(self.obter_vendedor, self.obter_cliente, self.obter_prazo, self.obter_num_pedido, self.obter_Nf, self.obter_Snf, self.obter_trasportadora, self.obter_frete, self.obter_resultado, self.obter_quantide, self.obter_preco, self.obter_obs))
arq.close()
# =============================================== GLOBAL VARIABLE TO CALCULATE FREIGHT
global qtdd
global valor
# =============================================== CALCULATION OF FINAL WEIGHT AND QUANTITY
valor = valor + float(self.obter_preco)
qtdd = qtdd + float(self.obter_quantide)
# =============================================== INSERT THE VALUE IN THE LABEL OF THE WEIGHT AND FINAL QUANTITY
valor_total = valor * qtdd
self.ui.recebe_peso_total.setText(str(qtdd))
self.ui.recebe_valor_total.setText(str(valor_total))```
Here you're adding the price which you should not. And why using global variable here?
valor = valor + float(self.obter_preco)
qtdd = qtdd + float(self.obter_quantide)
# =============================================== INSERT THE VALUE IN THE LABEL OF THE WEIGHT AND FINAL QUANTITY
valor_total = valor * qtdd

Include precedence in SPT algorithm scheduling

How can I include a job precedence vector within this code?
In the Prec list, I set which job should go before another from the indexes, but how can I do the evaluation of this condition so that I can rearrange the allocation of jobs?
import numpy as np
M = 5
Pj = np.array([99,184,80,180,51,69,129,152,168,171])
Prec = [[9,2],[2,8],[4,2]]
J = np.array(range(len(Pj)))
#Organización de los índices de trabajos por duración
Pj_SI = np.argsort(Pj)
Pj_SA = Pj[Pj_SI]
J_Order = J[Pj_SI]
# print(Pj_SI)
# print(Pj_SA)
print(np.argsort(J_Order))
#SPT HEURISTIC
M_j = {}
M_pj = {}
M_Cj = {}
for m in range(M):
M_j[m] = []
M_pj[m] = []
M_Cj[m] = []
for i, Pj in enumerate(Pj_SA):
M_pj[(i)%M].append(Pj)
M_j[(i)%M].append(J_Order[i])
if i<M:
M_Cj[(i)%M].append(Pj)
else:
M_Cj[(i)%M].append(M_Cj[(i)%M][len(M_Cj[(i)%M])-1]+Pj)
print("Processing Time in Machines", M_pj)
print("Assignment Order", M_j)
Cmax = []
for m in range(len(M_Cj)):
Cmax.append(np.sum(M_pj[m]))
Makespan = max(Cmax)
print('Machines Load: ', Cmax)
print('Makespan SPT:', Makespan)

IndexError: Peng Robinson equation code for multiple components

I have the following code:
from scipy.constants import R as Rgi
from numpy import *
import numpy as np
import matplotlib.pyplot as plt
Constants
Tccomp = array([190.56,305.32,369.83,425.12,469.7,507.6,282.34,365.57,511.76,553.58,562.16,591.8,512.64,513.92,536.78,400.1,408.00,508.2,591.95,469.15,132.45,154.58,126.2,405.65,430.75,304.26,647.13,535.5]) #k
Pccomp = array([45.90,48.50,42.10,37.70,33.60,30.40,50.30,46.30,45.00,41.00,48.00,41.30,81.40,61.20,51.20,52.70,65.90,47.10,57.40,72.60,37.90,50.20,33.98,113.00,78.60,73.90,219.40,41.50]) # bar
Vccomp = array([0.099,0.146,0.2,0.255,0.315,0.373,0.132,0.188,0.257,0.308,0.261,0.314,0.117,0.168,0.22,0.171,0.115,0.21,0.179,0.142,0.092,0.074,0.089,0.072,0.123,0.095,0.056,0.267]) # m^3/kmol
Zccomp = array([0.286,0.279,0.273,0.272,0.271,0.269,0.283,0.286,0.272,0.274,0.273,0.262,0.224,0.24,0.252,0.271,0.223,0.234,0.208,0.264,0.318,0.287,0.288,0.241,0.269,0.277,0.228,0.249])
Wcomp = array([0.011,0.098,0.149,0.197,0.251,0.304,0.086,0.137,0.196,0.212,0.209,0.262,0.566,0.643,0.617,0.192,0.282,0.307,0.463,0.201,0.0,0.02,0.037,0.253,0.244,0.244,0.343,0.323])
Nombre = array(['Metano','Etano','Propano','Butano','Pentano','Hexano','Etileno','Propileno','Ciclopentano','Ciclohexano','Benceno','Tolueno','Metanol','Etanol','1-Propanol','Dimetileter','Formaldehido','Acetona','Acido Actico','Oxido de etileno','Aire','Oxigeno','Nitrogeno','Amoniaco','Dioxido de azufre','Dioxido de carbono','Agua','Metiletilcetona'])
Rbar = Rgi*10 # bar*cm^3/K*mol
Rgas = Rgi # Kj / Kmol * K
Program interface
print 'Cálculo de la fugacidad de una mezcla de gases reales utilizando Peng Robinson'
print '-----------------------------------------------------------------------------------'
print ' Metano |(0)| '
print ' Etano |(1)| '
print ' Propano |(2)| '
print ' Butano |(3)| '
print ' Pentano |(4)| '
print ' Hexano |(5)| '
print ' Etileno |(6)| '
print ' Propileno |(7)| '
print ' Ciclopentano |(8)| '
print ' Ciclohexano |(9)| '
print ' Benceno |(10)|'
print ' Tolueno |(11)|'
print ' Metanol |(12)|'
print ' Etanol |(13)|'
print ' 1-propanol |(14)|'
print ' Dimetileter |(15)|'
print ' Formaldehido |(16)|'
print ' Acetona |(17)|'
print ' Ácido acético |(18)|'
print ' Óxido de etileno |(19)|'
print ' Aire |(20)|'
print ' Oxígeno |(21)|'
print ' Nitrógeno |(22)|'
print ' Amoniaco |(23)|'
print ' Dióxido de azufre |(24)|'
print ' Agua |(25)|'
print ' Metiletilcetona |(26)|'
print '-------------------------------------------------------------------------------------'
print ' '
print ' '
ncomp = int(input('numero de componentes del sistema : '))
def PRMix(T,P):
comp = zeros(ncomp)
y = zeros(ncomp)
Wcomp = zeros(ncomp)
Tccomp = zeros(ncomp)
Pccomp = zeros(ncomp)
a = zeros(ncomp)
b = zeros(ncomp)
sumbi = zeros(ncomp)
s = (ncomp,ncomp)
aij = zeros(s)
sumaij = zeros(s)
for i in arange(0,ncomp,1):
comp[i] = int(input('Escoja el componente : '))
y[i] = float(input(' Fraccion : '))
print ' '
for i in arange (0,ncomp,1):
Wcomp[i] = Wcomp[int(comp[i])]
Tccomp[i] = Tccomp[int(comp[i])]
Pccomp[i] = Pccomp[int(comp[i])]
kappa = 0.37464 + 1.54226*Wcomp - 0.26992*Wcomp**2
alpha = (1 + kappa*(1 - sqrt(T/Tccomp)))**2
a = 0.45724*(((Rgi**2) * (Tccomp**2))/(Pccomp))*alpha
b = 0.0788*((Rgi*Tccomp)/Pccomp)
for i in arange(0,ncomp,1):
sumbi[i] = y[i]*b[i]
for j in arange(0,ncomp,1):
aij[i,j] = sqrt(a[i]*a[j])
sumaij[i,j] = y[i]*y[j] * aij[i,j]
amix = sum(sumaij)
bmix = sum(sumbi)
Aij = (aij * P) / ((Rgi*T)**2)
Bi = (b * P) / (Rgi * T)
Amix = (amix * P)/((Rgi*T)**2)
Bmix = (bmix * P)/(Rgi * T)
pol = [1,(Bmix - 1), (Amix - 2 * Bmix - 3 * Bmix**2),(Bmix**2 + Bmix**3 -Amix * Bmix)]
Z = roots(pol)
Z = real(Z)
Zvmix = max(Z)
Zlmix = min(Z)
LnPhiV = (Bi/Bmix)*(Zvmix-1) - log(Zvmix-Bmix)-(Amix/(2*Sqrt(2)*Bmix)) * ((2 *(dot(Aij,y)/Amix) -(Bi/Bmix)) * log((Zvmix + (1 + sqrt(2)) * Bmix) / (Zvmix + (1 - sqrt(2)) * Bmix)))
LnPhiL = (Bi/Bmix)*(Zlmix-1) - log(Zlmix-Bmix)-(Amix/(2*Sqrt(2)*Bmix)) * ((2 *(dot(Aij,y)/Amix) -(Bi/Bmix)) * log((Zlmix + (1 + sqrt(2)) * Bmix) / (Zlmix + (1 - sqrt(2)) * Bmix)))
PhiV = exp(LnPhiV)
PhiL = exp(LnPhiL)
However, when I run it I get this error:
Traceback (most recent call last):
line 82, in PRMix
Wcomp[i] = Wcomp[int(comp[i])]
IndexError: index 5 is out of bounds for axis 0 with size 2
>>> IndexError: index 5 is out of bounds for axis 0 with size 2
I can't figure out what's wrong. I tried reading about the error but didn't find anything that applied to my code.

Calculate the future value for only one category using the IRR (Python)

import xlrd
import numpy
fileWorkspace = 'C://Users/jod/Desktop/'
wb1 = xlrd.open_workbook(fileWorkspace + 'assign2.xls')
sh1 = wb1.sheet_by_index(0)
time,amount,category = [],[],[]
for a in range(2,sh1.nrows):
time.append(int(sh1.cell(a,0).value)) # Pulling time from excel (column A)
amount.append(float(sh1.cell(a,1).value)) # Pulling amount from excel (column B)
category.append(str(sh1.cell(a,2).value)) # Pulling category from excel (column C)
#print(time)
#print(amount)
#print(category)
print('\n')
p_p2 = str(sh1.cell(0,1))
p_p1 = p_p2.replace("text:'","")
pp = p_p1.replace("'","")
print(pp) # Printing the type of pay period (Row 1, col B)
c_p2 = str(sh1.cell(1,1))
c_p1 = c_p2.replace("text:'","")
cp = c_p1.replace("'","")
print(cp) # Printing the type of compound period (Row 2, col B)
netflow = 0
outflow = 0
inflow = 0
flow = 0
cat = ["Sales", "Salvage", "Subsidy", "Redeemable", "Utility", "Labor",
"Testing", "Marketing", "Materials", "Logistics"]
if pp == "Years" and cp == "Years": # if pay period and compound period are both in years
IRR = numpy.irr(amount) * 100 # Calculates the internal rate of return (IRR)
print ("IRR:", round(IRR, 2), '%', '\n') # prints (IRR)
for i in time: # for every value in time array
if cat[5] in category: # if "Labor" for cat array is in category array or not
# calculates the present values using all the amount values (col B) instead of
# just using the ones that has "Labor" category label beside them
# Need to make every other value 0, such as beside "Redeemable" and "Salvage"
flow = amount[i] / numpy.power((1 + (IRR/100)), time[i])
if flow>0:
inflow = inflow + flow
if flow<0:
outflow = outflow + flow
print ('Present Value (P) is:', round(flow,0), '\n')
netflow = outflow + inflow
print("In year 0 or current year")
print("-------")
print ('Outflow is: ', round(outflow,0))
print ('Inflow is: ', round(inflow,0))
print ('Netflow is: ', round(netflow,0), '\n')
outflow2 = (round(outflow,0))*(1+(IRR/100))**(9)
inflow2 = (round(inflow,0))*(1+(IRR/100))**(9)
netflow2 = outflow2 + inflow2
print("In year 9")
print("-------")
print ('Outflow is: ', round(outflow2,0))
print ('Inflow is: ', round(inflow2,0))
print ('Netflow is: ', round(netflow2,0), '\n')
I have commented important lines of code for clarification.
Here is the original question:
illustrate the breakdown of major project revenues and expenses by category as a percentage of that project’s future value in year 9. The illustration must also clearly indicate the total future value of the project in year 9 as well as the IRR.
There will be a total of 10 revenue and cost categories that a project may be composed of. The categories are: Sales, salvage, subsidy, redeemable, utility, labor, testing, marketing, materials and logistics. All revenues and expenses will fall in one of these ten categories. The project pay period and compound period will be identified at the top of the Excel sheet. Pay period and compound period may be designated as any of the following: years, quarters, months.
I am getting confused because I am not able to pull the only values from beside the "Labor", "Redeemable", or "Salvage". I just don't know where I am making a mistake, or there is something that is incomplete. Below is the excel file image:
Excel File Image 2
Excel File Image 3
After revising, all cashflows are discounted at the irr. What is done is the following:
i) determineAdjustments takes the pay period (column A) and adjusts if for the year ended (if it is a monthly amount it puts it in the proper year ended) and if its monthly puts in in the month ended (no adjustment necessary). This will divide the pay period by 12 if yearly cash flows are needed (yearly compounding)
ii) IRR is calculated, and the compounding period is used to adjust the monthly IRR for monthly pay periods
iii) all expenses are discounted at the IRR and input into a list for cat_contributions['category_name'] = [discounted period 1, discounted period 2 ... ]
iv) Then the net inflows and outflows are sums of these.
I can't type up data in the spreadsheets from the images as that would take a while, but maybe tinker with this and see if you can get it to work.
from __future__ import division
import xlrd
import numpy
import os
import math
def main(xls = 'xls_name.xlsx', sh = 0):
#save script in same folder as the xls file
os.chdir( os.getcwd() )
wb = xlrd.open_workbook(xls)
sh = wb.sheet_by_index(0)
pay_period = sh.cell_value(0,1)
compounding_period = sh.cell_value(1,1)
compounding_factor, pay_factor = determineAdjustments(
pay_period, compounding_period)
number_of_periods = max( sh.col_values(0, start_rowx = 2) )
flow_per_period = [ 0*i for i in range( int( math.ceil( number_of_periods/pay_factor ) ) + 1 ) ]#list of length number of pay_periods
for r in range(2,sh.nrows):
pay_period = int( math.ceil( sh.cell_value(r,0) / pay_factor ) )
flow_per_period[pay_period] += sh.cell_value(r,1) #unadjusted cash flows
irr = calculateIRR(flow_per_period, compounding_factor)
cat_contributions = sortExpenditures(sh, irr, pay_factor)
total_cat_contributions, netflow, total_outflow, total_inflow = calculateFlows(cat_contributions)
printStats(cat_contributions, irr, compounding_factor, pay_factor,
total_cat_contributions, netflow, total_outflow, total_inflow)
return
def determineAdjustments(pay_period, compounding_period):
if compounding_period == 'years':
compounding_factor = 1
if pay_period == 'months':
pay_factor = 12
if pay_period == 'years':
pay_factor = 1
#assume no days pay periods
if compounding_period == 'months':
compounding_factor = 12
#assume no yearly payouts and that the
#all payments are in months
pay_factor = 1
return compounding_factor, pay_factor
def calculateIRR(cashflow, compounding_factor):
irr = numpy.irr(cashflow)
irr_comp = (1 + irr)**compounding_factor - 1
#seems like in first example it uses rounded irr, can do something like:
#irr_comp = round(irr_comp,4)
return irr_comp
def sortExpenditures(sh, irr, pay_factor):
#percentages and discounting occurs at the IRR caculated in the main
#function
cat = ["Sales", "Salvage", "Subsidy", "Redeemable", "Utility", "Labor",
"Testing", "Marketing", "Materials", "Logistics"]
#python dictionary to sort contributions into categories
cat_contributions = {}
for c in cat:
cat_contributions[c] = []
# create list of contributions of each list item to FV in a dictionary
for r in range(2,sh.nrows):
try:
#discounted cash flow of each expenditure
#using formula FV = expenditure/(1+i)^n
cat_contributions[sh.cell_value(r,2)].append(
sh.cell_value(r,1) / ( (1 + irr) ** (sh.cell_value(r,0)/pay_factor) )
)
except KeyError:
print "No category for type: " + sh.cell_value(r,2) +'\n'
return cat_contributions
def calculateFlows(cat_contributions):
total_outflow = 0
total_inflow = 0
total_cat_contributions = {}
for cat in cat_contributions:
total_cat_contributions[cat] = sum( cat_contributions[cat] )
if total_cat_contributions[cat] < 0:
total_outflow += total_cat_contributions[cat]
else:
total_inflow += total_cat_contributions[cat]
netflow = total_inflow + total_outflow
return total_cat_contributions, netflow, total_outflow, total_inflow
def printStats(cat_contributions, irr, compounding_factor, pay_period,
total_cat_contributions, netflow, total_outflow, total_inflow):
print "IRR: "+str(irr*100) +' %'
if compounding_factor == 1: print "Compounding: Yearly"
if compounding_factor == 12: print "Compounding: Monthly"
if pay_period == 1: "Cashflows: Year Ended"
if pay_period == 12: "Cashflows: Month Ended"
print "Future Value (Net Adjusted Cashflow): " +str(netflow)
print "Adjusted Inflows: " + str(total_inflow)
print "Adjusted Outflows: " + str(total_outflow) +'\n'
for cat in total_cat_contributions:
if total_cat_contributions[cat] != 0:
print '-----------------------------------------------------'
print cat + '\n'
print "Total Contribution to FV " + str( total_cat_contributions[cat] )
if total_cat_contributions[cat] < 0:
print "Contribution to Expenses: " + str ( abs(100 * total_cat_contributions[cat]/total_outflow) )
else:
print "Contribution to Revenues: " + str ( abs(100 * total_cat_contributions[cat]/total_inflow) ) +'\n'
main(xls='Book1.xlsx')

Print in tabulated form

How can I print this in tabulated form?
listex = range(nOfYears)
counter = 1
for i in listex:
if i ==0:
print counter, '\t',startingBalance,'\t', amountofinterest, '\t', next_balance
previous_balance = next_balance
total_interest +=amountofinterest
else:
counter += 1
amountofinterest = previous_balance*interestRate
total_balance = previous_balance+amountofinterest
print counter, '\t', previous_balance,'\t', amountofinterest, '\t', total_balance
previous_balance = total_balance
total_interest += amountofinterest
print '\n', "TOTAL BALANCE IS :", previous_balance
print "TOTAL AMOUNT OF INTEREST IS %.2f:" %(total_interest)
If you want to print this in the shape of a table in console, you should try the tabulate module which is really easy to use. (https://pypi.python.org/pypi/tabulate)
Simple example:
from tabulate import tabulate
table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
["Moon",1737,73.5],["Mars",3390,641.85]]
print tabulate(table)
#----- ------ -------------
#Sun 696000 1.9891e+09
#Earth 6371 5973.6
#Moon 1737 73.5
#Mars 3390 641.85
#----- ------ -------------
If you want to separate columns with \t character, you should check for the csv module and csv writer.

Categories