Global function is not defined - python

I am facing this error as I define my module. I am trying to write a program for edit distance problem via dynamic programming method.
Here is the module where I am stuck:
def cost(i,j,M,w,text,pattern,compare): #Defining the cost functions or can say recurrence formula
M[0,j]=0
text1=list(text)
pattern1=list(pattern)
for i in range(1,m+1):
for j in range(1,n+1):
insertions = M[i-1,j]+1
deletions = M[i,j-1]+1
matches=M[i-1,j-1]
if text1[i]==patttern1[j]:
matches = matches+1
return matches
else :
return matches
and the error is :
Traceback (most recent call last): File
"/Users/sayaneshome/Documents/plschk.py", line 202, in
fill(M, w, text, max) #Filling matrix M with scores File
"/Users/sayaneshome/Documents/plschk.py", line 117, in fill c =
cost(i,j,M,w,text,pattern,compare) File
"/Users/sayaneshome/Documents/plschk.py", line 95, in cost if
text1[i]==patttern1[j]: NameError: global name 'patttern1' is not
defined

Your patttern1 has three t's. Remove one to get pattern1.

Related

Pyomo TypeError: unhashable type: 'EqualityExpression'

I am building an energy planning model in Pyomo and I am running into problems building some power grid constraints.
def grid2grid_rule(m, ts):
return m.power['grid','grid', ts] == 0
m.const_grid2grid = Constraint(ts_i, grid2grid_rule)
def import_rule(m, ts):
return m.gridImport[ts] == sum(m.power['grid',derIn,ts] for derIn in elIn)
m.const_import = Constraint(ts_i, rule = import_rule)
def export_rule(m, ts):
return m.gridExport[ts] == sum(m.power[derOut,'grid',ts] for derOut in elOut)
m.const_export = Constraint(ts_i, export_rule)
Definition of Power:
m.power = Var(elOut, elIn, ts_i, within = NonNegativeReals)
Explaining the code:
m.power is a decision variable with 3 indices: The electricity source (elOut), the electricity 'usage' (elIn) and the current timestep index ts_i. elOut and elIn are numpy arrays with strings and ts_i a numpy array with integers from 0 to how many timesteps there are.
The first constraint just says that at any timestep there the electricity cannot flow from the grid to the grid. The import constraint says that the grid imports at each timestep are the sum over all power flows from the grid to electricity takers. The export constraint says that the grid exports at each timestep are a sum of all powerflows from electricity 'givers' to the grid.
Now, my problem is, when I comment the grid2grid and the export constraint, it works and a set of constraints is built as expected. However, for example when I uncomment the export rule, which is almost identical to the import rule, I get this error:
m = build_model('Input_Questionaire.xlsx', 'DER_excel', yeardivision = "repr_day")
ERROR: Constructing component 'const_export_index_1' from data=None failed:
TypeError: Problem inserting gridExport[1] == power[pv_ground,grid,1] +
power[wind_s,grid,1] + power[battery,grid,1] + power[grid,grid,1] into set
const_export_index_1
Traceback (most recent call last):
File "C:\Users\Axel\Anaconda3\lib\site-packages\pyomo\core\base\sets.py", line 824, in add
if tmp in self:
File "C:\Users\Axel\Anaconda3\lib\site-packages\pyomo\core\base\sets.py", line 998, in __contains__
return self._set_contains(element)
File "C:\Users\Axel\Anaconda3\lib\site-packages\pyomo\core\base\sets.py", line 1302, in _set_contains
return element in self.value
TypeError: unhashable type: 'EqualityExpression'
Accompanied with this error:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
...
...
...
File "C:\Users\Axel\Anaconda3\lib\site-packages\pyomo\core\base\sets.py", line 833, in add
raise TypeError("Problem inserting "+str(tmp)+" into set "+self.name)
TypeError: Problem inserting gridExport[1] == power[pv_ground,grid,1] + power[wind_s,grid,1] + power[battery,grid,1] + power[grid,grid,1] into set const_export_index_1
I do not know how to fix it, especially since there is basically no difference in the two Constraints...
Thanks heaps for your help!
Axel
Ugh... just saw it. It's an easy one. :)
you omitted "rule=" portion of the constraint construction, so it is passing in the function as a set or something weird...
Anyhow. Change:
m.const_export = Constraint(ts_i, export_rule)
to:
m.const_export = Constraint(ts_i, rule=export_rule)
same for your grid2grid

how to represent object as variable for graph of seaborn in python?

I have data-frame which has column name price. So i want to draw a distribution plot for that column. and i want to assign the graph name as column_name so that i can the graph when i need in multiple places even though i have number of distribution, I can call required graph separately, here i have column are dynamic.
x = 'price'
y = sns.distplot(df[x])
exec("%s = %s" % (x,y))
print(price)
I have try this code but throwing an error like
Traceback (most recent call last):
File "/home/mahesh/.local/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3287, in run_code
last_expr = (yield from self._async_exec(code_obj, self.user_ns))
File "<ipython-input-36-f28fdca73b33>", line 8, in async-def-wrapper
File "<string>", line 1
price = AxesSubplot(0.125,0.125;0.775x0.755)
^
SyntaxError: invalid syntax
One way is using a function
x = df.price
def displot(j):
sns.distplot(j)
displot(x)

IndexError: list index out of range with different functions

I am not quite sure what it is I am doing wrong with my code to get this error. I've been looking around to see if I could find somebody having the same problem but I have had no success thus far. The code is:
def sort(dislis):
for index in range(0,len(lst)):
currval= dislis[index]
position = index
while position>0 and dislis[position-1]>currval:
dislis[position] = dislis[position-1]
position = position-1
dislis[position]=currval
The traceback error is:
Traceback (most recent call last):
File "C:", line 49, in <module>
distance()
File "", line 47, in distance
sort(dislis)
File "", line 20, in sort
currval= dislis[index]
IndexError: list index out of range
def sort(dislis):
for index in range(0,len(dislis)):
currval= dislis[index]
position = index
while position>0 and dislis[position-1]>currval:
dislis[position] = dislis[position-1]
position = position-1
dislis[position]=currval
return dislis
result = sort([3,4,2,1])
print(result)
A few little bugs in there preventing it from running, try this out instead.
Also, I highly recommend using only spaces, and not tabs at all.

I am trying to solve a system of equation with two variable in tkinter python

Good morning,
I am trying to solve a system of equation with 2 variables in Python, but using Tkinter to display the answers on the screen. I did most of it, but I can not display the answes.
That is the error I am seeing:
enter coException in Tkinter callback
Traceback (most recent call last):
File "C:\Users\edwin\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
return self.func(*args)
File "C:\Users\edwin\AppData\Local\Programs\Python\Python36-32\ed.py", line 122, in Calculate
z = np.linalg.solve ( a, b)
File "C:\Users\edwin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\numpy\linalg\linalg.py", line 375, in solve
r = gufunc(a, b, signature=signature, extobj=extobj)
File "C:\Users\edwin\AppData\Local\Programs\Python\Python36-32\lib\site-packages\numpy\linalg\linalg.py", line 90, in _raise_linalgerror_singular
raise LinAlgError("Singular matrix")
numpy.linalg.linalg.LinAlgError: Singular matrixde here
A singular matrix is not invertible. A singular matrix does not satisfy the property: The equation Ax = b has exactly one solution for each b in Kn. This means that the system you are attempting to solve is either incorrectly converted into matrix form, or does not have a unique solution.

Index out of bound while reading a dataframe

I have a tab separated file that I am trying to parse and for that I am doing this :
header of my file :
chrom coord ref_base var_base A C G T
17 26695663 G A 1 0 1934 0
17 26695664 T A 1 0 1 1935
my code is :
counts = pd.read_csv(args.counts_file, sep='\t')
toto = counts[(counts['chrom'].astype(str) == "17") & (counts['coord'].astype(str) == "26695663")]
print toto["G"].values[0]
this function returns the number wanted which is 1934
Now when I try to create a function that takes arguments the dataframe read from the file, I wrote this function
def get_foreground_counts(chrom, coord, counts, ref_base, var_base):
foreground_counts = counts[(counts['chrom'] == chrom) & (counts['coord'] == coord)]
foreground_ref_counts = foreground_counts[ref_base].values[0]
foreground_var_counts = foreground_counts[var_base].values[0]
return foreground_ref_counts, foreground_var_counts
I got this error that I am trying to figure out but still cant see why
Traceback (most recent call last):
File "test.py", line 203, in <module>
main(args)
File "test.py", line 71, in main
foreground_ref_counts, foreground_var_counts = get_foreground_counts(chrom, coord, counts, ref_base, var_base)
File "test.py", line 137, in get_foreground_counts
foreground_ref_counts = foreground_counts[ref_base].values[0]
IndexError: index out of bounds
Any idea why ?
Thanks
UPDATE
When I try to print foreground_counts[ref_base].values I get this []
What I am passing to the function is chrom (string), coord(string), counts(panda dataframe), ref_base (string), var_base(string) )
In your function, your filter does return zero rows, that's why you get the error. It seems you forgot the .astype(str) in your function's first line.
You could either cast the column type before calling the function or modify that line. The former would be a better approach if you really need to use a string type, otherwise why don't you use integer values for the comparison?.

Categories

Resources