I want to read a .tif file and count the number of pixels in an image and determine the density of objects, but when I attempt this y, x = np.indices(image.shape) it gives me then
Value Error (ValueError: too many values to unpack, File "<stdin>", line 1, in <module>).
My code is as follows:
import sys
import os
import numpy as np
from pylab import *
import scipy
import matplotlib.pyplot as plt
import math
#Function
def radial_plot(image):
y, x = np.indices(image.shape) # <----- Problem here???
center = np.array([(x.max()-x.min())/2.0, (x.max()-x.min())/2.0])
r = np.hypot(x - center[0], y - center[1])
ind = np.argsort(r.flat)- center[1])
r_sorted = r.flat[ind]
i_sorted = image.flat[ind]
r_int = r_sorted.astype(int)
deltar = r_int[1:] - r_int[:-1]
rind = np.where(deltar)[0]
nr = rind[1:] - rind[:-1]
csim = np.cumsum(i_sorted, dtype=float)
tbin = csim[rind[1:]] - csim[rind[:-1]]
radial_prof = tbin / nr
return rad
#Main
img = plt.imread('dat.tif')
radial_plot(img)
The issue is that you are attempting to assign more than two values to only two varibles:
>>> a, b = range(2) #Assign two values to two variables
>>> a
0
>>> b
1
>>> a, b = range(3) #Attempt to assign three values to two variables
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
In Python 2.x you can do the following:
>>> a, b = range(3)[0], range(3)[1:]
>>> a
0
>>> b
[1, 2]
Just for completeness, if you had Python 3.x, you could do Extended Iterable Unpacking:
>>> a, *b, c = range(5)
>>> a
0
>>> c
4
>>> b
[1, 2, 3]
Hope this helps
np.indices returns an array representing the indices of the grid. The error basically indicates that there are more than 2 values obtained by calling the indices method. Since it's returning a grid, you can assign it to a variable such as grid and then access the indices accordingly.
The crux of the error is the function call returns more than just 2 values, and in your code you are trying to 'squeeze' them into just 2 variables.
For eg.
s = "this is a random string"
x, y = s.split()
The above code gives you a value error since there are 5 strings obtained by calling split(), while I am trying to accommodate them into just 2 variables.
Related
I'm trying to insert one array into another, but I think I'm having a dimensioning issue with the arrays, leading to a ValueError. The exponential segment I'm trying to insert lives in EXP and prints as I'd expect, but running len() on it returns 1. Why would an array that prints with more than one element return a len() of 1? Code snippet below:
SPR = 48000 # Hz
duration = 0.2 # second
t = numpy.linspace(0, duration, duration * SPR)
p_list = [0, numpy.pi, 0]
SIGNALS = [(16000 * numpy.sin((2 * numpy.pi * t * 20) + p)).astype('int16')
for p in p_list]
EXP = [(16000 * (2**(-100*t))).astype('int16')]
e=EXP[0:4200]
print(e)
print(len(e))
SIGNALS[0][600:4800] = e
returns
[array([16000, 15976, 15953, ..., 0, 0, 0], dtype=int16)]
1
Traceback (most recent call last):
File "/home/pi/Experiments/actronika-exp.py", line 87, in <module>
SIGNALS[0][600:4800] = e
ValueError: setting an array element with a sequence.
The problem is that you are inserting the array inside a list when you do:
X = [np.array([0, ...])]
Thus X is a list with a array inside, I think you should just do:
X = np.array([0, ...])
However, if you need the array inside list thing, you should change this line
e=EXP[0:4200]
to
e=EXP[0][0:4200]
Now you are taking the first array, inside the list EXP.
[array([16000, 15976, 15953, ..., 0, 0, 0], dtype=int16)]
This (e) is a numpy array inside a python list. len(e) returns the list's length, which is 1, since it contains 1 element: the numpy array
I have implemented functions find_maximum and f, that returns the value and passed it as a parameter to another function and just wanted to find the maximum of the given function. Following is my implementation.
import numpy as np
def find_maximum(f, begin_range, end_range, step=0.00001):
return np.maximum(begin_range, np.minimum(f, end_range))
def f(x):
myList = []
for i in range(1,4):
myList.append(0.3333* x**2) - 5*x - 3 + (numpy.cos(3)*x)
return myList
x = 4
print(find_maximum(f, -4, 4, 0.00001))
Following is more explanation
f - A vectorized python function of a single variable f(x), that expects
a numpy array of x values as its only parameter.
begin_range, end_range - real valued numbers with begin_range < end_range,
defining a range that we want to determine the maximum value of the
given function within.
step - The step size to search within the range, defaults to 0.001 The
maximum will be determined to a value within this step size, so it
represents the accuracy with which to find the maximum.
Returns max_loc - returns the location where the function is at the maximum in
the given range. The location of the maximum must be within the range:
begin_range <= max_loc <= end_range
An Error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-b68bd5d55098> in <module>()
29 return myList
30 x = 4
---> 31 print(find_maximum(f, -4, 4, 0.00001))
<ipython-input-6-b68bd5d55098> in find_maximum(f, begin_range, end_range, step)
1 import numpy as np
2 def find_maximum(f, begin_range, end_range, step=0.00001):
----> 3 return np.maximum(begin_range, np.minimum(f, end_range))
4 '''Find the maximum of function f in the range [begin_range, end_range].
5 The function f should be a vectorized python function of a single
TypeError: '<=' not supported between instances of 'function' and 'int'
Expected output
print(find_maximum(f, -4, 4, 0.00001))
>>> -2.14085
Try like this :
x = 4
print(find_maximum(f(x), -4, 4, 0.00001))
You need to run your function before give it to find_maximum
Edit :
You function miss a parenthesis :
def f(x):
myList = []
for i in range(1,4):
myList.append((0.3333* x**2) - 5*x - 3 + (np.cos(3)*x))
return myList
import math
import random
m = 1.5 #mu
l = 2 #lambda
c = 3 #control/number of servers
def single(m, l, c):
p = (l/m)
Po = (1-(l/m))
Ls = (l/(m-l))
Ws = (1/(m-l))
Wq = (l/(m*(m-l)))
Lq = (l**2/(m*(m-l)))
return(p, Po, Ls, Ws, Wq, Lq)
def multi(m, lm, mu):
rho=lm/mu
n=0
sm=0
while(n<=m-1):
sm=(1/math.factorial(n))*pow(rho,n)
n+=1
sm = sm + 1/(1/math.factorial(m))*(pow(rho,m)*m*mu/(m*mu-lm))
lS=lm*mu*pow(rho,m)/((math.factorial(m-1)*(m*mu-lm)**2))*(1/sm)+rho
lQ=lS-rho
#Po = 1/sm
return(lq, ls)
singReturn=single(m, l, c)
multiReturn=multi(3, 2, 1.5)
print("SINGLE SERVER QUEUEING")
print("-----------------------")
print("p: %4.4f \nPo: %4.4f \nLs: %4.4f \nWs: %4.4f \nWq: %4.4f \nLq: %4.4f"%singReturn)
I am being returned and error with:
Traceback (most recent call last):
File "/home/schnipdip/Desktop/final_part1_chris_herzog.py", line 35, in <module>
multiReturn=multi(3, 2, 1.5)
File "/home/_____/Desktop/final_part1_.py", line 28, in multi
sm = sm + 1/(1/math.factorial(m))*(pow(rho,m)*m*mu/(m*mu-lm))
ZeroDivisionError: integer division or modulo by zero
I am trying to find the value of SM and then convert it into the Po variable. The while loop is controlling how many servers there are by m(or c) - 1.
I changed the variables in the loop to see if the variable was being overwritten in memory by a previous value and not resetting for whatever reason. I'm sure that has nothing to do with it.
If you're using Python 2, it's probably due to this part:
... 1/(1/math.factorial(m)) ...
Logically, it doesn't make much sense: mathematically, 1/(1/x) is just a clumsy way to spell plain x. So I bet your code has a logical error there.
But, in Python 2, it also has a programming error: / applied to integers does truncating integer division in Python 2:
>>> import math
>>> m = 3
>>> math.factorial(m)
6
>>> 1 / math.factorial(m)
0
To prevent that, use, e.g., 1.0 instead of 1 to force float division:
>>> 1.0 / math.factorial(m)
0.16666666666666666
I had written a simple pascal triangle code in python but I am getting a error
def factorial(n):
c=1
re=1
for c in range(n):
re = re * c;
return(re)
print "Enter how many rows of pascal triangle u want to show \n"
n=input();
i=1
c=1
for i in range(n):
for c in range(n-i-1):
print ""
for c in range(i):
a = factorial(i);
b = factorial(c);
d = factorial(i-c);
z = (a/(b*d));
print "%d" % z
print "\n"
ERROR:
Traceback (most recent call last):
File "/home/tanmaya/workspace/abc/a.py", line 19, in <module>
z = (a/(b*d));
ZeroDivisionError: integer division or modulo by zero
Your factorial() function returns 0 for any input because of how you defined your range.
The range builtin starts at 0 unless otherwise defined so:
for c in range(n):
re = re * c # no semicolons in Python
is doing:
re = re * 0
on the first iteration so for all subsequent iterations:
re = 0 * c
will always be 0
Start your range at 1 like so
for c in range(1, n):
re *= c # The *= operator is short hand for a = a * b
you can see this more explicityly:
>>> print(list(range(5)))
[0, 1, 2, 3, 4]
>>> print(list(range(1,5)))
[1, 2, 3, 4]
>>>
or instead of rolling your own function use the one that comes with Python:
>>> from math import factorial
>>> factorial(3)
6
Upon closer reading of your code it seems you tried to circumvent this by setting c = 1 outside your for loop. This is not going to work because the variables you declared outside the loop are being reassigned inside it.
ZeroDivisionError means that you were trying to divide or modulo, a number n with 0.
in your case, z = (a/(b*d)) resulted in z = (a/0)
Also, as #theB pointed out, your factorial function is incorrect.
Try fixing those.
Also, you don't really need ; in your code. It's usually the case we put ; when we want to make the code one liner.
I was wondering if it is somehow possible to set the domain of a math. function. For example, when I define the following expression
>>> import sympy as syp
>>> x = syp.Symbol('x')
>>> miles_to_km = x * 1.609344
>>> miles_to_km.evalf()
1.609344*x
Is it possible to limit the domain so that x is in the range [0, inf)? So the goal is that I could then use the sympy.plot function that produces a graph that starts at 0 and only includes positive x-values in contrast to
If we check the manual by doing:
help(syp.plot)
You will get:
...
expr : Expression representing the function of single variable
range: (x, 0, 5), A 3-tuple denoting the range of the free variable.
...
So, you can:
>>> import sympy as syp
>>> x = syp.Symbol('x')
>>> miles_to_km = x * 1.609344
>>> syp.plot(miles_to_km, (x,0,10))
which will give you the following output: