increment values in maya python - python

randoms = [rand.uniform(-1,1)for items in range(10)]
x= 0
for i in List:
cm.setKeyframe(at = "%s.cv[x].xValue"%i , t=5, v=rand.choice(randoms))
x+=1
this part of code that i wanna use, but maya can't accept this [x].
someone told me you should do this:
for i in List:
x = 0
cvAttrX = i+".cv["+str(x)+"].xValue"
cm.setKeyframe(at = cvAttrX , t=5, v=rand.choice(randoms))
x+=1
but i got this error:
# Error: line 1: can only concatenate list (not "str") to list
# Traceback (most recent call last):
# File "<maya console>", line 1, in <module>
# File "<maya console>", line 7, in randList
# TypeError: can only concatenate list (not "str") to list #
if someone fix this please explain that deeply to me.
i wanna learn this one very good
and please fix this example too:
randoms = [rand.uniform(cm.floatField(Ceil, q = True , v = True),0.5)for i in range(30)]
for objects in myList:
cm.xform('%s.cv[0]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))])
cm.xform('%s.cv[1]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))])
cm.xform('%s.cv[2]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))])
cm.xform('%s.cv[3]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))])
cm.xform('%s.cv[4]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))])
cm.xform('%s.cv[5]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))])
cm.xform('%s.cv[6]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))])
cm.xform('%s.cv[7]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))])
cm.xform('%s.cv[8]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))])
cm.xform('%s.cv[9]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))])
cm.xform('%s.cv[10]'%objects , r = True , t = [(rand.choice(randoms)),(rand.choice(randoms)),(rand.choice(randoms))])
this is a part of my script if i can do increment i don't wanna write this line for exampla 100 time, i can make intField for that and determine how many do i need
i wanna do something like this but i don't know how
import maya.cmds as cm
import random as rand
myList = cm.ls(sl =True)
cvList = []
randomList = []
def Lister():
for i in myList:
cvList.append(cm.ls('%s.cv[:]'%i , flatten = True))
return cvList
def randomize():
x = 0
randomList.append([rand.uniform(-1,1)for items in range(10)])
for i in cvList:
cm.setKeyframe(at = "%s.cv[x].xValue"%i , t=5, v=rand.choice(randoms))
x+=1

myCurve = cm.ls(sl=1) # Will return [u'curve1']
# Since it returned the object in a list in the next command you have to subscript it.
myCVs = cm.ls(myCurve[0] + ".cv[:]", fl=1)
# Result: [u'curve1.cv[0]',
u'curve1.cv[1]',
u'curve1.cv[2]',
u'curve1.cv[3]',
u'curve1.cv[4]',
u'curve1.cv[5]',
u'curve1.cv[6]',
u'curve1.cv[7]',
u'curve1.cv[8]',
u'curve1.cv[9]',
u'curve1.cv[10]'] #
# We do not need to increment through these, flatten takes care of that. We need only iterate through the list of cvs and concatenate the attribute to the name.
for i in myCVs:
cm.setAttr(i + ".xValue", random.uniform(-1, 1))
print cm.getAttr(i + ".xValue")
# This will move all the cvs on that curve by a random value between -1 and 1.
-0.233699187896
0.353531892619
0.736778238244
-0.767007983153
0.672321920729
0.0556060597496
-0.340945469966
0.252136119281
-0.396852920849
-0.683451384587
0.926232431375

Well first of all you're not even set up for animation. You need something to drive it. Right now if you set your keyframe all this will be happening on one frame. You could do something like:
time = cm.currentTime(q=1)
for i in range(10):
cm.setAttr(myCVs[0]+".xValue", random.choice(test))
cm.setKeyframe(myCurve, shape=1, controlPoints=1)
time = cm.currentTime(time + 1)
Or you could plug i into the time flag of cm.setKeyframe. This way it keyframes the whole curve, the transform, shape, and control points. And you wouldn't have to worry about iterating through all of them. Set the value first then set the keyframe, just like you would if you were actually animating.

Related

I don't know why it's an empty list? max()

# Plot the highest score in history
def draw_best(background):
ip = 'redis-16784.c89.us-east-1-3.ec2.cloud.redislabs.com'
r = redis.Redis(host=ip, password=1206, port=16784, db=0, decode_responses = True)
scores = [eval(i) for i in list(r.hgetall('2048').values())]
best_scores = max(scores)
scoreSurf = BasicFont01.render('Top scoreļ¼š{}'.format(best_scores), True, (0, 0, 0))
scoreRect = scoreSurf.get_rect()
scoreRect.width = math.floor((rate - 0.15) / 2 * screen.get_width())
scoreRect.height = math.floor((1 - rate2) / 3 * 2 * screen.get_height())
scoreRect.topright = (math.floor(0.9 * screen.get_width()), math.floor(0.05 * screen.get_height()))
py.draw.rect(screen, background, [scoreRect.topleft[0], scoreRect.topleft[1], scoreRect.width, scoreRect.height], 0)
screen.blit(scoreSurf, scoreRect)
I think the problem is in these two lines:
scores = [eval(i) for i in list(r.hgetall('2048').values())]
best_scores = max(scores)
The error it showed me was:
ValueError: max() arg is an empty sequence
Obviously, it seems like list(r.hgetall('2048').values()) is a blank sequence/list/array.
Check if it is really empty by defining a variable with the value list(r.hgetall('2048').values()) and then print it out to check.
There is a default keyword that may be helpful. It will return a value if the list is empty. It works as follows:
my_list = []
result = max(my_list, default=None)
print(result) # It will print "None"
You already think that the problem exists in those two lines, then what better way to solve this is to check if it is really in those two lines!

Extracting frequencies from a wav file python

I am familiar with python but new to numpy, so please pardon me if I am wrong.
I am trying to read a .wav file having multiple frequencies (separated by silence). So far I've been able to read the values and find the various parts in the file where there is a sound. Then, I am trying to find the Discrete Cosine Transform and calculate the frequencies from it (ref: how to extract frequency associated with fft values in python)
However, I'm getting an error:
index 46392 is out of bounds for axis 0 with size 25
Here's my code:
import wave
import struct
import numpy as np
def isSilence(windowPosition):
sumVal = sum( [ x*x for x in sound[windowPosition:windowPosition+windowSize+1] ] )
avg = sumVal/(windowSize)
if avg <= 0.0001:
return True
else:
return False
#read from wav file
sound_file = wave.open('test.wav', 'r')
file_length = sound_file.getnframes()
data = sound_file.readframes(file_length)
sound_file.close()
#data = struct.unpack("<h", data)
data = struct.unpack('{n}h'.format(n=file_length), data)
sound = np.array(data)
#sound is now a list of values
#detect silence and notes
i=0
windowSize = 2205
windowPosition = 0
listOfLists = []
listOfLists.append([])
maxVal = len(sound) - windowSize
while True:
if windowPosition >= maxVal:
break
if not isSilence(windowPosition):
while not isSilence(windowPosition):
listOfLists[i].append(sound[windowPosition:windowPosition+ windowSize+1])
windowPosition += windowSize
listOfLists.append([]) #empty list
i += 1
windowPosition += windowSize
frequencies = []
#Calculating the frequency of each detected note by using DFT
for signal in listOfLists:
if not signal:
break
w = np.fft.fft(signal)
freqs = np.fft.fftfreq(len(w))
l = len(signal)
#imax = index of first peak in w
imax = np.argmax(np.abs(w))
fs = freqs[imax]
freq = imax*fs/l
frequencies.append(freq)
print frequencies
Edit: Here is the traceback:
Traceback (most recent call last):
File "final.py", line 61, in <module>
fs = freqs[imax]
IndexError: index 46392 is out of bounds for axis 0 with size 21
The problem was that I assumed listOfLists was actually a list of lists, but actually it was a list of list of lists. The line:
listOfLists[i].append(sound[windowPosition:windowPosition+ windowSize+1])
was appending a list everytime, but I assumed it was appending the elements to existing list.
For instance, if listOfLists was:
[ [1,2,3] ]
Then, listOfLists[0].append([4,5,6]) would give:
[ [ [1,2,3],[4,5,6] ] ]
But I was expecting:
[ [1,2,3,4,5,6] ]
Replacing the problematic line with the code below worked for me:
for v in sound[windowPosition:windowPosition+windowSize+1]:
listOfLists[i].append(v)

Failed to append an element to a numpy array

I'm trying to add the values generated by the function calc_class, but it is not working and I don't know the reason. I've tried to use the numpy.append, numpy.insert and the built-in Python function append unsuccessfully.
This is my piece of code:
def calc_class(test):
expec = []
for new in test:
prob_vector = np.zeros((len(voc)), dtype=bool) #define a 'True' array to store class probabilities
words_in_new = new[0].split() #split the new email into words
words_in_new = list(set(words_in_new)) #remove duplicated words
i = 0
for voc_word in voc: #for each element in voc
if voc_word in words_in_new:
prob_vector[i] = True #set the ith element of prob_vector to True, if voc element is in word
else:
prob_vector[i] = False #set the ith element of prob_vector to False, otherwise
i += 1
prob_ham = 1
for i in range(len(prob_vector)):
if prob_vector[i] == True:
prob_ham *= ham_class_prob[i]
else:
prob_ham *= (1 - ham_class_prob[i])
# alternative: np.prod(ham_class_prob[np.where(prob_vector==True)]) * np.prod(1- ham_class_prob[np.where(prob_vector==False)])
prob_spam = 1
for i in range(len(prob_vector)):
if prob_vector[i] == True:
prob_spam *= spam_class_prob[i]
else:
prob_spam *= (1 - spam_class_prob[i])
p_spam = 0.3
p_ham = 1 - p_spam
p_spam_given_new = (prob_spam * p_spam) / (prob_spam * p_spam + prob_ham * p_ham) # Bayes theorem
print('p(spam|new_email)=', p_spam_given_new[0])
expec.append(p_spam_given_new[0])
print(expec)
The problem is that print(expect) is printing an empty array.
You can use pdb do debug (or ipdb for ipython).
from pdb import set_trace
use "set_trace()" instead of "print('p(spam|new_email)=', p_spam_given_new[0])"(third line counted from end-line), than run your code. It will pause at this line, and you can run any python code there, such as "print(p_spam_given_new)" or just "p_spam_given_new", you can also check "prob_spam", "p_spam" or any other variable you want to check.

Indexerror: list index out of range/numpy

I am really
new to python. I am getiing an error stating Indexerror list index out of range. Kindly help me out. Thanks in advance .
Edit 1
x = np.array([10,0])
Phi = np.array([[ 1. , 0.01],
[ 0. , 1. ]])
Gamma = np.array([[ 0.0001048 ],
[ 0.02096094]])
Z = np.array([[ 0.0001048 ],
[ 0.02096094]])
wd = 0
u_new = 0
x1d = 0
x2d = 0
xd = [[0 for col in range(len(x))] for row in range(1000)]
xd[0][0] = 10
xd[1][0] = 0
k = 10
DistPeriodNo1 = 500
FirstPeriod = 1
k=k+1 #Update PeriodNo(so PeriodNo is now equal to No. of current period)
if (k == 100): #If maximum value of PeriodNo is reached,
k = 11 #set it to 1
DistPeriodNo1 = random.randint(11,99)
if (FirstPeriod == 0):
if (k == DistPeriodNo1):
wd = random.randint(-1,1)
else:
wd = 0
xd[0][k] = Phi*xd[0][k-1] - Gamma*u_new + Z*wd
# >>indexerror list index out of range
xd[1][k] = Phi*xd[1][k-1] - Gamma*u_new + Z*wd
x1d = xd[0][k]
x2d = xd[1][k]
To answer your question in the comments about tracebacks (stack traces): running the following
a = [1,2,3]
b = [True, False]
print(a[2])
print(b[2])
produces one answer and one traceback.
>>>
3
Traceback (most recent call last):
File "C:\Programs\python34\tem.py", line 4, in <module>
print(b[2])
IndexError: list index out of range
The traceback shows what line and what code raised the error. People were asking you to copy the last 4 line and paste them into your question (by editing it).

Matlab to Python conversion - Can't assign to function call

I have recently been trying to convert a piece of Matlab code into Python code.
I have made most of the changes that I need to however, the issue I am having is the line where it says:
y(index(m)) = 1-x(index(m));
I get the error:
"Can't assign to function call"
However I am not sure how to restructure it in order to remove this error.
I have had a look around and people mention "get item" and "set item" however I have tried to use them, but I can't get them to work (probably because I can't figure out the structure)
Here is the full code:
import numpy
N = 100;
B = N+1;
M = 5e4;
burnin = M;
Niter = 20;
p = ones(B,Niter+1)/B;
hit = zeros(B,1);
for j in range(1,Niter):
x = double(rand(1,N)>0.5);
bin_x = 1+sum(x);
index = ceil(N*rand(1,M+burnin));
acceptval = rand(1,M+burnin);
for m in range(1,M+burnin):
y = x;
y(index(m)) = 1-x(index(m));
bin_y = 1+sum(y);
alpha = min(1, p(bin_x,j)/p(bin_y,j) );
if acceptval(m)<alpha:
x = y; bin_x = bin_y;
end
if m > burnin: hit(bin_x) = hit(bin_x)+1; end
end
pnew = p[:,j];
for b in range(1,B-1):
if (hit(b+1)*hit(b) == 0):
pnew(b+1) = pnew(b)*(p(b+1,j)/p(b,j));
else:
g(b,j) = hit(b+1)*hit(b) / (hit(b+1)+hit(b));
g_hat(b) = g(b,j)/sum(g(b,arange(1,j)));
pnew(b+1) = pnew(b)*(p(b+1,j)/p(b,j))+((hit(b+1)/hit(b))^g_hat(b));
end
end
p[:,j+1] = pnew/sum(pnew);
hit[:] = 0;
end
Thanks in advance
The round brackets () indicate a function. For indexing you need [] square brackets - but that is only the first of many, many errors... I am currently going through line by line, but it's taking a while.
This code at least runs... you need to figure out whether the indexing is doing what you are expecting since Python arrays are indexed from zero, and Matlab arrays start at 1. I tried to fix that in a couple of places but didn't go through line by line - that's debugging.
Some key learnings:
There is no end statement... just stop indenting
When you import a library, you need to reference it (numpy.zeros, not zeros)
Lists are indexed from zero, not one
Indexing is done with [], not ()
Creating an array of random numbers is done with [random.random() for r in xrange(N)], not random(N).
... and many other things you will find as you look through the code below.
Good luck!
import numpy
import random
N = int(100);
B = N+1;
M = 5e4;
burnin = M;
Niter = 20;
p = numpy.ones([B,Niter+1])/B;
hit = numpy.zeros([B,1]);
g = numpy.zeros([B, Niter]);
b_hat = numpy.zeros(B);
for j in range(1,Niter):
x = [float(random.randint(0,1)>0.5) for r in xrange(N)];
bin_x = 1+sum(x);
index = [random.randint(0,N-1) for r in xrange(int(M+burnin))];
#acceptval = rand(1,M+burnin);
acceptval = [random.random() for r in xrange(int(M+burnin))];
for m in range(1,int(M+burnin)):
y = x;
y[index[m]] = 1-x[index[m]];
bin_y = 1+sum(y);
alpha = min(1, p[bin_x,j]/p[bin_y,j] );
if acceptval[m]<alpha:
x = y; bin_x = bin_y;
if m > burnin:
hit[bin_x] = hit[bin_x]+1;
pnew = p[:,j];
for b in range(1,B-1):
if (hit[b+1]*hit[b] == 0):
pnew[b+1] = pnew[b]*(p[b+1,j]/p[b,j]);
else:
g[b,j] = hit[b+1]*hit[b] / [hit[b+1]+hit[b]];
g_hat[b] = g[b,j]/sum(g[b,numpy.arange(1,j)]);
pnew[b+1] = pnew[b]*(p[b+1,j]/p[b,j])+((hit[b+1]/hit[b])^g_hat[b]);
p[:,j+1] = pnew/sum(pnew);
hit[:] = 0;

Categories