[Tutor] Index Out of Range?List
Stephen P. Molnar
s.molnar at sbcglobal.net
Thu May 4 08:50:28 EDT 2017
On 05/03/2017 08:51 PM, Alan Gauld via Tutor wrote:
> On 04/05/17 00:32, Stephen P. Molnar wrote:
>
>> import numpy as np
>>
>> name = input("Enter Molecule ID: ")
>> name = str(name)
>
> You don't need the str(), input always returns a string.
>
>> name_in =name[:]+'.lac.dat'
>
> And you don't need the [:]. Just use
>
> name_in = name + '.lac.dat'
>
>> print(name_in)
>>
>> atm_chg = []
>
>> """
>> atm_chg = open(name_in,'r')
>> for line in atm_chg:
>> print(line, end=' ')
>> """
> This creates a 3 line string which is not assigned to any object.
> It is not executable code and will not be executed. Maybe you
> are doing it as a way of commenting out a block? If so it would be
> better in a post to just delete it, it just adds confusion
> otherwise. (Well, it confused me! :-)
>
>> with open(name_in) as f:
>> # skip two lines
>> f.readline()
>> f.readline()
>> for line in f.readlines():
>> atm_chg.append(float( line.split()[-1] ))
>>
>> p.asarray({atm_chg})
>
> Where did p come from?
> Should it be np? asarray() sounds like it might be a numpy thing.
> And I'm not sure what the {atm_chg} is supposed to do - create
> a single element set using your list maybe? I get an "unhashable"
> error if I try it at the >>>> prompt.
>
>> When it is run I get:
>>
>> IndexError: list index out of range
>
> I'm pretty sure you get more than that, please post the full
> error text, it's much harder to diagnose problems with just
> the summary.
>
> Since the only indexing you do is in this line
>
>> atm_chg.append(float( line.split()[-1] ))
>
> I'll assume that's where the problem lies.
> Try checking if the string is not empty before using it:
>
> for line in f.readlines():
> if line:
> atm_chg.append(float( line.split()[-1] ))
>
>
>> However, the Variable Explorer shows:
>
> I have no idea what the Variable Explorer is?
> Is it part of your IDE? Or of numpy?
> If the IDE which IDE are you using?
>
>> [-0.780631, 0.114577, 0.309802, 0.357316, -0.001065]
>> [-0.780631, 0.114577, 0.309802, 0.357316, -0.001065]
>> [-0.780631, 0.114577, 0.309802, 0.357316, -0.001065]
>> [-0.780631, 0.114577, 0.309802, 0.357316, -0.001065]
>>
>> One line of which is exactly what I want as input to the next step in
>> the larger calculation.
>>
>> Now, my question is how do I extract just one line of this file?
>
> Any particular line? And which file are you talking about?
> The data should be in the list variable, atm_chg.
> In which case the first line is therefore: atm_chg[0]
>
> Or you can process each line using the usual for loop:
>
> for line in atm_chg:
> # use line here....
>
Thanks for your reply.
The Variable Explorer is part of the Spyder IDE.
I have edited the code:
import numpy as np
name = input("Enter Molecule ID: ")
#name = str(name)
name_in =name[:]+'.lac.dat'
print(name_in)
atm_chg = []
with open(name_in) as f:
# skip two lines
f.readline()
f.readline()
for line in f.readlines():
atm_chg.append(float( line.split()[-1] ))
np.asarray({atm_chg})
Execution still generates the errors:
runfile('/home/comp/Apps/Python/Testing/ReadFile_2.py',
wdir='/home/comp/Apps/Python/Testing')
Enter Molecule ID: A
A.lac.dat
Traceback (most recent call last):
File "<ipython-input-1-8c665940b39f>", line 1, in <module>
runfile('/home/comp/Apps/Python/Testing/ReadFile_2.py',
wdir='/home/comp/Apps/Python/Testing')
File
"/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py",
line 866, in runfile
execfile(filename, namespace)
File
"/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py",
line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/comp/Apps/Python/Testing/ReadFile_2.py", line 27, in <module>
atm_chg.append(float( line.split()[-1] ))
IndexError: list index out of range
from the input file:
runfile('/home/comp/Apps/Python/Testing/ReadFile_2.py',
wdir='/home/comp/Apps/Python/Testing')
Enter Molecule ID: A
A.lac.dat
Traceback (most recent call last):
File "<ipython-input-1-8c665940b39f>", line 1, in <module>
runfile('/home/comp/Apps/Python/Testing/ReadFile_2.py',
wdir='/home/comp/Apps/Python/Testing')
File
"/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py",
line 866, in runfile
execfile(filename, namespace)
File
"/home/comp/Apps/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py",
line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/home/comp/Apps/Python/Testing/ReadFile_2.py", line 27, in <module>
atm_chg.append(float( line.split()[-1] ))
IndexError: list index out of range
Finally, here is the code for which I need input data for the
calculation of the Integrated Charge Transform:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 8 15:17:07 2017
@author: comp
Copyright (c) 2017 Stephen P. Molnar, Ph.D.
"""
import matplotlib.pyplot as plt
import numpy as np
# you don't need pandas, np.genfromtxt() reads this type of txt files.
plt.ion() # interactive plotting, stopps plt.show() from blocking.
#import math # you won't need math if you have numpy
start=1
finish=31
points=300
s = np.linspace(start, finish, points)
np.savetxt('s',s)
name = input("Enter Molecule ID: ")
name = str(name)
print(name)
name_in = name+'.dat'
print(name)
dtype = [('NO', int), ('LB', 'S2'), ('ZA', float), ('FRAG', int),
('MASS', float), ('X', float), ('Y', float), ('Z', float)]
data = np.genfromtxt(name_in, dtype=dtype, skip_header=3)
N = data.shape[0] #number of atoms in molecule
a = np.array([data['X'], data['Y'], data['Z']]) #atomic coordinates
#dist.squareform(dist.pdist(a, "euclidean"))
anrows, ancols = np.shape(a)
a_new = a.reshape(anrows, 1, ancols)
diff = a_new - a
D = (diff ** 2).sum(2)
D = np.sqrt(D)
r = D
def eq7(a, s, Z):
"""
Computes equation 7 in Molnar & King (2001)
"""
N = r.shape[0]
I = np.zeros(s.shape)
for i in range(1, N):
for j in range(i):
I += Z[i] * Z[j] * np.sin(s * r[i, j])/(s * r[i, j])
return I
I = eq7(r, s, data['ZA'])
name = 'I_z-'+str(name)
np.savetxt(name,I)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(s.T, I)
plt.title("Molecular Transform: ${}$".format(name))
fig.gca().set_xlabel("Distance (Å)")
plt.ylabel('Atomic Number Transform (I$_z$)')
plt.show()
I_sq = []
I_sq = I**2
Area = []
Area = np.trapz(I_sq,x=None,dx=0.01,axis=-1)
np.savetxt('I_sq',I_sq)
I_z = np.sqrt(Area)
print('FTz: ',I_z)
#--------------------------------------------------------------------------
# MASS Mollecular Transform FT_m
I = eq7(r, s, data['MASS'])
name = 'I_m-'+str(name)
np.savetxt(name,I)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(s.T, I)
plt.title("Molecular Transform: ${}$".format(name))
fig.gca().set_xlabel("Distance (Å)")
plt.ylabel('MASS Transform (I$_m$)')
plt.show()
I_sq = I**2
Area = np.trapz(I_sq,x=None,dx=0.01,axis=-1)
np.savetxt('I_sq',I_sq,delimiter=' ')
I_z = np.sqrt(Area)
I_m = I_z
print('FT_m: ',I_m)
#------------------------------------------------------------------------------
#Integrated Charge Transform
print(name)
--
Stephen P. Molnar, Ph.D. Life is a fuzzy set
www.molecular-modeling.net Stochastic and multivariate
(614)312-7528 (c)
Skype: smolnar1
More information about the Tutor
mailing list