printSoln module problem - python

Hi I found in book:Numerical Methods in engineering with Python the module run_kut5, but for that module I need module printSoln, all provided in the book. Now I cp the code, made necessary line adjustments and so. The code looks like:
# -*- coding: cp1250 -*-
## module printSoln
''' printSoln(X,Y,freq).
Prints X and Y returned from the differential
equation solvers using printput frequency ’freq’.
freq = n prints every nth step.
freq = 0 prints initial and final values only.
'''
def printSoln(X,Y,freq):
def printHead(n):
print "\n x ",
for i in range (n):
print " y[",i,"] ",
print
def printLine(x,y,n):
print "%13.4e"% x,f
for i in range (n):
print "%13.4e"% y[i],
print
m = len(Y)
try: n = len(Y[0])
except TypeError: n = 1
if freq == 0: freq = m
printHead(n)
for i in range(0,m,freq):
printLine(X[i],Y[i],n)
if i != m - 1: printLine(X[m - 1],Y[m - 1],n)
Now, when I run the program it says:
line 24, in <module>
m = len(Y)
NameError: name 'Y' is not defined
But I cp'd from the book :\ So now when I call the run_kut module I get the same error, no Y defined in printSoln...
I'm trying to figure this out but I suck :(
Help, please...

I would guess it's a tabs/spaces problem - check that you don't have mixed tabs and spaces in the indentation.
EDIT: If it's not indentation, and since your error message contains "<module>" and not a filename, I'm guessing you're pasting this into an interactive interpreter.
Instead, you should paste the code into a file called printsoln.py, and then run this in the interactive interpreter:
from printsoln import printSoln
If you still want to paste it all in the interpreter then you'll probably need to remove the blank lines - those after def printSoln and after each internal function. The interactive interpreter uses blank lines to figure out when you're done with a multi-line definition, and tries to evaluate m = len(Y) outside the context of function printSoln. In this context, variable Y doesn't exist.

Related

Print the return of a method in python

I'm fairly new to OOP in python and i cant seem to figure out if I'm doing this the right way. I have a first script called TP2_dat.py in which I solve a problem in AMPL and then at the end i retrieve the variable X as follows (I simplified the code):
import amplpy
import os
class Solver:
def __init__(self, set_k, larg_on, poids):
self.set_K = set_k
self.larg_on = larg_on
self.poids = poids
def solve(self):
...
X = ampl.getVariable('X')
X_val = X.getValues()
X_val_dic = X_val.toDict()
# print(X_val_dic)
return X_val_dic
I tried to do a print instead of a return from the first script and it worked. But now i want to print it from another script as follows so i dont get the None at the end of the print from the second script:
from TP2_dat import Solver
set_K = [1,2,3,4,5,6]
larg_on = [4,3,5,4,6,5]
poids = [0,4,5,2,3,6,4,0,4,3,5,3,5,4,0,4,7,8,2,3,4,0,3,3,3,5,7,3,0,5,6,3,8,3,5,0]
affichage = Solver(set_K, larg_on, poids)
affichage.solve()
print(X_val_dic)
The part that i dont understand is can i do something similar to this? Am i right in thinking to return the value of X_val_dic or should i do something else?
Thanks a lot for your help !!
Since the class method solve returns a value you need to set it equal to a variable or print it directly:
X_val_dic = affichage.solve()
print(X_val_dic)
or
print(affichage.solve())
See this article for more information on pythons variable scoping.

Why can't I import my module into my main code?

I wrote some code (named exercise 2) where I define a function (named is_divisible) and it has worked perfectly.
Afterwards to learn how to import functions, I wrote the same code but without the defined function, and created a second module (named is_divisible). But whenever I import this module into the original "exercise 2" I get
No module named 'is_divisible'
I have checked that both python files are in the same folder, the name of the file is correct, and I know the code is well written because it has worked before and it is from a lecturer's of mine. I have also attempted to name the module and the function differently and to instead write:
from divis import is_divisible
but this was also unsuccessful.
Where am I going wrong? I will leave the code below:
import random
import math
import numpy as np
random_list=[]
for i in range (0,5):
r=random.randint(0,10)
random_list.append(r)
print(random_list) #five numbers from 0 to 10 are chosen and appended to a list
new_result=[print('right' for x in random_list if round(np.cosh(x)**2 - np.sinh(x)**2,2) == 1]
#checking the numbers following a maths rule
import is_divisible #trying to import the function is_divisible
divisor=3
idx = is_divisible(random_list, divisor)
for i in idx:
print(f'Value {random_list[i]} (at index {i}) is divisible by {divisor}')
the code for the function is_divisible is:
def is_divisible(x, n):
""" Find the indices of x where the element is exactly divisible by n.
Arguments:
x - list of numbers to test
n - single divisor
Returns a list of the indices of x for which the value of the element is
divisible by n (to a precision of 1e-6 in the case of floats).
Example:
>>> is_divisible([3, 1, 3.1415, 6, 7.5], 3)
[0, 3]
"""
r = []
small = 1e-6
for i, m in enumerate(x):
if m % n < small:
r.append(i)
return r
I know this question has been answered multiple times, but none of the answers seem to work for me or maybe I am not doing it correctly.
Generally, when you type import <Module> the module is the name of the file. So, if you had the function is_divisible inside a Python file named a.py, then to import it you will write from a import is_divisible. If instead, you would like to import the whole file, then you'd write import a.py, then to use the function you would use a.is_divisible(random_list, divisor).
You should also make sure that both files are in the same folder.

invalid syntax error : Quine McCluskey Algorithm in python

i'm totally new in python, and here is some code my friend sent it for me, this is Quine-McCluskey Algorithm that provides answer with getting minterms, the code is somehow simple but because i am not exprienced python programmer i have not much ideas for fixing this problem
this is the source code : Quine-McCluskey (github)
def find_minimum_cost(Chart, unchecked):
P_final = []
#essential_prime = list with terms with only one 1 (Essential Prime Implicants)
essential_prime = find_prime(Chart)
essential_prime = remove_redundant_list(essential_prime)
#print out the essential primes
if len(essential_prime)>0:
s = "\nEssential Prime Implicants :\n"
for i in range(len(unchecked)):
for j in essential_prime:
if j == i:
s= s+binary_to_letter(unchecked[i])+' , '
print s[:(len(s)-3)] #ERROR <--------
#modifiy the chart to exclude the covered terms
for i in range(len(essential_prime)):
for col in range(len(Chart[0])):
if Chart[essential_prime[i]][col] == 1:
for row in range(len(Chart)):
Chart[row][col] = 0
-
File "C:\Users\Lenovo\Desktop\main.py", line 204
print s[:(len(s)-3)]
^
SyntaxError: invalid syntax
the Error is in this line : print s[:(len(s)-3)]
The original author intended for the program to be executed with a python2 interpreter.
He wrote (roughly):
print s
To execute with a modern python3 interpreter, you would instead need:
print(s)

Second Functions program. Some inquiries

My book requires me to Make another program using functions, the catch is that I need to make it a little bit more complex this time, so instead of going for a simple addition I try to solve a very simple physics problem with values given to me by the user, using two functions (velocity and acceleration).
Heres the aim of the program (sampledoc)
Create a program that reads and prints this txt document
Introduces the Program and the name of the script
Uses a function to solve a problem, make the function more complex
User gives distance (x) and time (t)
Program calculates velocity and acceleration
Creates a new txt document and writtes the results in it
Prints the results of the problem directly from the new document.
And heres the code:
from sys import argv
script, textf = argv; sampledoc = open(textf)
def velocity (x, t):
vel = (float(x)) / (float(t))
return float(vel)
def acceleration (v, t):
accel = (float(v)) / (float(t))
return float(accel)
print "Hello my name is TAR or as my creator called me %s" % script; print sampledoc.read(); sampledoc.close()
print "Results will be printed on a new text document, thanks for your preference"
x = float(raw_input("Please introduce the Distance")); t = float(raw_input("Please introduce the time:... "))
vel = velocity(x, t)
accel = acceleration (velocity, t)
results = 'ResultsP.txt'
new_file = open(results, 'w')
new_file.write(str(vel)); new_file.write(str(accel))
new_file.close()
new_file.open(results, 'r')
print new_file.read()
new_file.close()
I know there's something wrong here, somewhere, but my brain isn't working right now, I suppose it has something to do with either the way I am trying to solve this or the ''floats'' I used in the function since I am getting this error:
File "ex21Study.py", line 20, in <module>
accel = acceleration (velocity, t)
File "ex21Study.py", line 10, in acceleration
accel = (float(v)) / (float(t))
TypeError: float() argument must be a string or a number
I googled this and found some answers on other similar issues that said something about converting my results to float or str, however, I tried both and with no fruitful results.
You are passing in a function here:
accel = acceleration (velocity, t)
velocity is not a floating point value; it is a function object. You probably meant to use vel instead here, which you calculated on the preceding line:
vel = velocity(x, t)
accel = acceleration(vel, t)

puLP solver error

I am trying to solve MILP in puLP (Python), and I keep getting the following error:
Traceback (most recent call last):
File "main_lp.py", line 63, in <module>
ans = solve_lp(C)
File "/home/ashwin/Documents/Williams/f2014/math317_or/project/solve_lp.py", line 36, in solve_lp
prob.solve()
File "/usr/local/lib/python2.7/dist-packages/PuLP-1.5.6-py2.7.egg/pulp/pulp.py", line 1619, in solve
status = solver.actualSolve(self, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/PuLP-1.5.6-py2.7.egg/pulp/solvers.py", line 1283, in actualSolve
return self.solve_CBC(lp, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/PuLP-1.5.6-py2.7.egg/pulp/solvers.py", line 1346, in solve_CBC
raise PulpSolverError("Pulp: Error while executing "+self.path)
pulp.solvers.PulpSolverError: Pulp: Error while executing /usr/local/lib/python2.7/dist-packages/PuLP-1.5.6-py2.7.egg/pulp/solverdir/cbc-32
For my linear programming problem, I am attempting to take sums of different vectors as the constraint, and I think I must have done that wrong somehow, because a much simpler problem works with no hitches. I have attached the code (C is an N by N numpy array).
def solve_lp(C):
N = len(C)
prob=LpProblem('Scheduling',LpMinimize)
X = [[LpVariable('X' + str(i+1) + str(j+1), 0, C[i,j],LpBinary)
for j in range(N)] for i in range(N)]
X = np.array(X)
X_o = [LpVariable('X0' + str(i), 0, None, LpBinary) for i in range(N)]
X_t = [LpVariable('X' + str(i) + 't', 0, None, LpBinary) for i in range(N)]
# Objective Function
ones_vec = list(np.ones(len(X_o)))
prob += lpDot(ones_vec,X_o), 'Minimize Buses'
# Constraints
for i in range(N):
row = list(X[i,:]) + [X_t[i]]
ones_vec = list(np.ones(len(row)))
prob += lpDot(ones_vec, row) == 1, 'Only one destination for ' + str(i)
for j in range(N):
col = list(X[:,j]) + [X_o[j]]
ones_vec = list(np.ones(len(col)))
prob += lpDot(ones_vec,col) == 1, 'Only one source for ' + str(j)
prob.solve()
return X, value(prob.objective)
Make sure you don't have duplicate LpVariable names, and watch out for LpVariable names with the unsupported characters -+[] ->/ since all of those characters are silently converted to underscores _
Setting LpSolverDefault.msg = 1 before calling prob.solve() may help by printing the solvers output to the console.
I recently had a similar problem due to Nan inputs in the model. I had the data in a DataFrame where some the cells should not bee converted to variables to improve performance. However, upon creating the objective function and the constraints, I noticed the presence of Nan and when I changed them it worked perfectly.
I think that you have duplicate LpVariable names. I just had the same problem and saw it thanks to levis501's answer. Here:
X = [[LpVariable('X' + str(i+1) + str(j+1), 0, C[i,j],LpBinary)
for j in range(N)] for i in range(N)]
X contains some variables with the same name. For example for i = 0 and j = 10 you get 'X111', and for i = 10 and j = 0 you also get 'X111'.
I had a similar problem, and indeed with duplicate LpVariable names just like levis501's answer and aleon answered.
my code was:
var = [[pulp.LpVariable(f'x{i}{j}', lowBound=0, cat=pulp.LpInteger) for j in range(col)] for i in range(row)]
when i=1 j=11, x would be x111, and when i=11 j=1, x also would be x111
I changed to:
var = [[pulp.LpVariable(f'x{i}_{j}', lowBound=0, cat=pulp.LpInteger) for j in range(col)] for i in range(row)]
After changing, it runs successfully.
I recently had the same error raised aswell. The reason this error code was raised in my case was that my data frame was not correctly populated. i incorrectly had NaN on the RHS on some of my constraints
What is had was something like:
Matrix = df.pivot(1st_dimension, 2nd_dimension, value)
This operation automatically puts NaN for the instances that are not in the original dataframe.
in my case the NaN'sare replaced with 0 which is what i was expecting it to be:
Matrix = Matrix.fillna(0)
I experienced the same issue when launching multiple instances of the LPSolver class. As fmars stated, the problem is that the path 'tmpSol' does not exist, which is defined in the following lines of code within the solvers.py file of pulp:
pid = os.getpid()
tmpLp = os.path.join(self.tmpDir, "%d-pulp.lp" % pid)
tmpMps = os.path.join(self.tmpDir, "%d-pulp.mps" % pid)
tmpSol = os.path.join(self.tmpDir, "%d-pulp.sol" % pid)
This bit of code appears in every solver. The problem is that these paths are deleted later on, but may coincide for different instances of the LPSolver class (as the variable pid is not unique).
The solution is to get a unique path for each instance of LPSolver, using, for example, the current time. Replacing the above lines by the following four will do the trick.
currentTime = time()
tmpLp = os.path.join(self.tmpDir, "%f3-pulp.lp" % currentTime)
tmpMps = os.path.join(self.tmpDir, "%f3-pulp.mps" % currentTime)
tmpSol = os.path.join(self.tmpDir, "%f3-pulp.sol" % currentTime)
Don't forget to
from time import time
Cheers,
Tim
I have met some similar problem which because of some PuLP's bug. When some problem is infeasible and the solver failed to solve the problem, PuLP raise an exception rather than return status equals to infeasible. Below is the reason.
(You may first want to check out latest codebase of PuLP because the line number you paste doesn't match the latest one. I'll explain based on latest one but you can look at yours very simply.)
https://github.com/coin-or/pulp/blob/master/src/pulp/solvers.py#L1405-L1406
This is where exception prompt.
if not os.path.exists(tmpSol):
raise PulpSolverError("Pulp: Error while executing "+self.path)
tmpSol is the temporary file where stores the solution. If PuLP cannot find such solution file, it will throw the exception you saw. And the bug I mentioned above is, if the problem itself is infeasible, then PuLP won't be able to generate such temporary file. So it will always throw such exception.
One thing you can do is, send a pull request to PuLP repo and fix it.
And a simple workaround is, rather than directly invoke
prob.solve()
in your code, you should always do
try:
prob.solve()
except Exception:
logger.debug('Problem infeasible')
I had this problem today, and it was because the temporary files for CBC were trying to be written in a location whose path had spaces in it, and the command that pulp passes to subprocess.Popen() to run CBC does not use quotes, and thus the command was misinterpreted and CBC couldn't find the location to create temp files.
For this I found two solutions:
(1) Explicitly set a temporary file directory that doesn't have spaces in it,
pulp.LpSolverDefault.tmpDir = self.tmp_file_dir # tmp_file_dir can't have spaces!
prob.solve()
or
(2) don't use CBC (my problem is small)
prob.solve(pulp.GLPK_CMD())
I have a work-related constraint that a lot of my work is stuck in directories that have spaces.

Categories

Resources