I am having an error saying object cannot be interpreted as an integer - typeerror

for f in filenames:
file_path = os.path.join(dirpath, f)
signal, sample_rate = librosa.load(file_path, sr=SAMPLE_RATE)
for d in range(num_segments):
# calculate start and finish sample for current segment
start = samples_per_segment * d
finish = start + samples_per_segment

Related

Need to plot multiple values over each number of iterations (python help)

I'm trying to plot the multiple values one gets for 'f_12' over a certain number of iterations. It should look something like points with high oscillations when there is low iterations 'N' and then it converges to a rough value of 0.204. I'm getting the correct outputs for 'f_12' but I'm having a really hard time doing the plots. New to python here.
start = time.time()
# looking for F_12 via monte carlo method
# Inputs
# N = number of rays to generate
N = 1000
# w = width of plates
w = 1
# h = vertical seperation of plates
# L = horizontal offset of plates (L=w=h)
L = 1
h = 1
p_points = 100
# counter for number of rays and number of hits
rays = 0
hits = 0
while rays < N:
rays = rays + 1
# random origin of rays along w on surface 1
Rx = random.uniform(0, 1)
Rt = random.uniform(0, 1)
Rph = random.uniform(0, 1)
x1 = Rx * w
# polar and azimuth angles - random ray directions
theta = np.arcsin(np.sqrt(Rt))
phi = 2*np.pi*Rph
# theta = np.arcsin(Rt)
xi = x1 + h*np.tan(theta)*np.cos(phi)
if xi >= L and xi <= (L+w):
hit = 1
else:
hit = 0
hits = hits + hit
gap = N/ p_points
r = rays%gap
if r == 0:
F = hits/ rays
plt.figure(figsize=(8, 4))
plt.plot(N, F, linewidth=2)
plt.xlabel("N - Rays")
plt.ylabel("F_12")
plt.show()
f_12 = hits/ N
print(f"F_12 = {f_12} at N = {N} iterations")
# Grab Currrent Time After Running the Code
end = time.time()
#Subtract Start Time from The End Time
total_time = end - start
f_time = round(total_time)
print(f"Running time = {f_time} seconds")

Getting the charge of a single atom, per loop in MD Analysis

I have been trying to use the partial charge of one particular ion to go through a calculation within mdanalysis.
I have tried(This is just a snippet from the code that I know is throwing the error):
Cl = u.select_atoms('resname CLA and prop z <= 79.14')
Lz = 79.14 #Determined from system set-up
Q_sum = 0
COM = 38.42979431152344 #Determined from VMD
file_object1 = open(fors, 'a')
print(dcd, file = file_object1)
for ts in u.trajectory[200:]:
frame = u.trajectory.frame
time = u.trajectory.time
for coord in Cl.positions:
q= Cl.total_charge(Cl.position[coord][2])
coords = coord - (Lz/COM)
q_prof = q * (coords + (Lz / 2)) / Lz
Q_sum = Q_sum + q_prof
print(q)
But I keep getting an error associated with this.
How would I go about selecting this particular atom as it goes through the loop to get the charge of it in MD Analysis? Before I was setting q to equal a constant and the code ran fine so I know it is only this line that is throwing the error:
q = Cl.total_charge(Cl.position[coord][2])
Thanks for the help!
I figured it out with:
def Q_code(dcd, topo):
Lz = u.dimensions[2]
Q_sum = 0
count = 0
CLAs = u.select_atoms('segid IONS or segid PROA or segid PROB or segid MEMB')
ini_frames = -200
n_frames = len(u.trajectory[ini_frames:])
for ts in u.trajectory[ini_frames:]:
count += 1
membrane = u.select_atoms('segid PROA or segid PROB or segid MEMB')
COM = membrane.atoms.center_of_mass()[2]
q_prof = CLAs.atoms.charges * (CLAs.positions[:,2] + (Lz/2 - COM))/Lz
Q_instant = np.sum(q_prof)
Q_sum += Q_instant
Q_av = Q_sum / n_frames
with open('Q_av.txt', 'a') as f:
print('The Q_av for {} is {}'.format(s, Q_av), file = f)
return Q_av

Code or Logic to find number of char appearances in a string composed of consecutive numbers

I am struggling with this exercise where I have to find a number (y) so that when counting the times (nr) the value "1" appears in a string (x) composed of all the consecutive numbers starting from 1 to y, the following conditions are met: nr=y and nr is divisible by 10.
example:
x (string with consecutive from 1 to 12)= 123456789101112
y (the number) = 12
nr (times of "1" appearances) = 5
so i need to find the situation where nr=y and y mod 10 = 0
I've tried creating a vba sub to do this, but it takes forever and cannot seem to find a suitable result:
Sub abc2()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim i As Double
Dim y As Double
Dim nr As Double
Dim x As String
x = 1
y = 1
For i = 1 To 500001
x = x & (y + 1)
y = y + 1
nr = Len(x) - Len(Replace(x, "1", ""))
If nr = y And nr Mod 10 = 0 Then
Range("E1") = y
GoTo out
End If
Next i
out:
Range("A1") = x
Range("B1") = y
Range("C1") = nr
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
I'd really appreciate some suggestions. Maybe it can be solved in some other ingenious way.
Thank you!
Python:
x = ''
y = 0
####################################
# BRUTE FORCE, FINDS ANSWER 199990 #
####################################
#for iteration in range(100000):
# for index in range(10):
# y+=1
# x+=str(y)
# if (y == x.count('1')):
# print 'Found: ' + str(y) + ': ' + x
####################################
# More elegantly and efficiently, just track how many '1's we've added in each step
ones = 0
for iteration in range(100000):
x = ''
for index in range(10):
y += 1
x += str(y)
ones += x.count('1')
if (y == ones):
print 'Found: ' + str(y)
The commented-out solution takes about 2 minutes to execute. The second solution finishes in .46 seconds.

Python Numpy Matrix Update Confusion

this is a part of my matrix factorization code (a very weird version of nmf). My issue is that although every time when I iterate, I save the older copies of the W and H matrices, when I compare old_W and W after W finishes updating every time, they are actually the same! So the actual error output is always 0 and the while loop stops after the first iteration. However, "#print old - new" shows that the element W[r][i] is actually updated every time. What is it that I am not seeing?
def csmf(V, l, max_iter, err, alpha=0.01, beta=0.01, lamb=0.01):
W = np.random.rand(V.shape[0], l)
H = np.random.rand(l, V.shape[1])
n = V.shape[0]
N = V.shape[1]
NwOone = 60
NwOtwo = 60
NhOone = 50
NhOtwo = 50
for t in range(max_iter):
old_W = W # save old values
old_H = H
old = criterion(V,old_W,old_H,l,alpha,beta,lamb)
print "iteration ", t
##### update W
print "updating W"
setw = range(0,n)
subset_one = random.sample(setw,NwOone)
subset_two = calcGw(V, W, H, n, l, alpha, beta, NwOtwo)
chosen = np.intersect1d(subset_one,subset_two)
for r in chosen:
for i in range(len(W[0])):
update = wPosNeg(W[r],N,i,l,V,r,beta,H)
old = W[r][i]
W[r][i] = update
new = W[r][i]
#print old - new
##### update H
print "updating H"
seth = range(0,N)
subset_oneh = random.sample(seth,NhOone)
subset_twoh = calcGh(V, W, H, N, l, NhOtwo,lamb)
chosenh = np.intersect1d(subset_oneh,subset_twoh)
for s in chosenh: # column
for i in range(len(H)):
updateh = hPosNeg(H[i],n,i,l,V,s,lamb,W)
H[i][s] = updateh
##### check err
print "Checking criterion"
print criterion(V,W,H,l,alpha,beta,lamb)
print criterion(V,old_W,old_H,l,alpha,beta,lamb)
actual = abs(criterion(V,W,H,l,alpha,beta,lamb) -criterion(V,old_W,old_H,l,alpha,beta,lamb))
if actual <= err: return W, H, actual
return W, H, actual
dmat = np.random.rand(100,80)
W, H, err = csmf(dmat, 1, 10, 0.001, alpha=0.001, beta=0.001, lamb=0.001)
print err
in these lines:
old_W = W # save old values
old_H = H
you are not saving a copy, you are keeping a reference (old_W and W are the same piece of memory).
Try this:
old_W = W.copy() # save old values
old_H = H.copy()

Given value p, return last element of sequence < p - Fortran

I have a sequence of numbers as follows:
1 , 1, 5, 13, 41, 121, 365, ....
The first two values are:
N(1) = 1 and N(2) = 1
As from 3rd value, N(i) = 2*N(i-1) + 3*N(i-2)
The issue I am facing with is: If I give an argument of p, it should return me the last values of the sequence < p (Using fortran77).
For instance, if p = 90, it should return the value 41.
a = 1
b = 1
while b < p:
c = 2 * b + 3 * a
a = b
b = c
return a
The Fortran equivalent is:
function fct(p) result(a)
integer, intent(in) :: p
integer :: a, b, c
a = 1
b = 1
do while (b < p)
c = 2 * b + 3 * a
a = b
b = c
enddo
end function
program test
integer :: fct
external fct
print *,fct(90)
end program
Assuming you already have the sequence in a variable lst, and p set,
max(filter(lambda x:x<=p, lst))
def get_last_element(p):
n1 = 1
n2 = 1
while True:
if n2 > p:
return n1
n1, n2 = n2, 2*n2 + 3 * n1
print(get_last_element(90))
I wrote a piece of code in Fortran 2003. I defined a type which has memory for two last parts of the sequence.The procedure is a recursive function. The type can be used standalone to get n-th part of the sequence or efficiently placed in a loop to find parts in a row (not necessarily beginning at 1) as it has memory of previous parts. (compiler: gfortran 4.8).
The type is defined in mymod.f90 file as
module mymod
implicit none
type seq_t
integer :: saved_i = 0, saved_val_i = 0, saved_val_i_1 = 0
contains
procedure :: getpart => getpart_seq
end type
contains
recursive function getpart_seq(this,i) result(r)
class(seq_t) :: this
integer, intent(in) :: i
integer :: r,r_1,r_2
if (i.eq.1.or.i.eq.2) then
r = 1
elseif(i.eq.this%saved_i) then
r = this%saved_val_i
elseif(i.eq.this%saved_i-1) then
r = this%saved_val_i_1
else
r_1 = this%getpart(i-1)
r_2 = this%getpart(i-2)
r = 2*r_1 + 3*r_2
this%saved_val_i_1 = r_1
end if
this%saved_i = i
this%saved_val_i = r
end function getpart_seq
end module mymod
The main program for the requested case is
program main
use mymod
implicit none
type (seq_t) :: seq
integer :: i,p,tmp_new,tmp_old,ans
! Set the threshold here
p = 90
! loop over parts of the sequence
i = 0
do
i = i + 1
tmp_new = seq%getpart(i)
print*,tmp_new
if (tmp_new>p) then
ans = tmp_old
exit
end if
tmp_old = tmp_new
end do
print*,"The last part of sequence less then",p," is equal to",ans
end program
The outcome is
1
1
5
13
41
121
The last part of sequence less then 90 is equal to 41.