Indentation in python script - python

Purpose: Given a PDB file, prints out all pairs of Cysteine residues forming disulfide bonds in the tertiary protein structure. Licence: GNU GPL Written By: Eric Miller
#!/usr/bin/env python
import math
def getDistance((x1,y1,z1),(x2,y2,z2)):
d = math.sqrt(pow((x1-x2),2)+pow((y1-y2),2)+pow((z1-z2),2));
return round(d,3);
def prettyPrint(dsBonds):
print "Residue 1\tResidue 2\tDistance";
for (r1,r2,d) in dsBonds:
print " {0}\t\t {1}\t\t {2}".format(r1,r2,d);
def main():
pdbFile = open('2v5t.pdb','r');
maxBondDist = 2.5;
isCysLine = lambda line: (line[0:4] == "ATOM" and line[13:15] == "SG");
cysLines = [line for line in pdbFile if isCysLine(line)];
pdbFile.close();
getCoords = lambda line:(float(line[31:38]),
float(line[39:46]),float(line[47:54]));
cysCoords = map(getCoords, cysLines);
dsBonds = [];
for i in range(len(cysCoords)-1):
for j in range(i+1,len(cysCoords)):
dist = getDistance(cysCoords[i],cysCoords[j]);
residue1 = int(cysLines[i][23:27]);
residue2 = int(cysLines[j][23:27]);
if (dist < maxBondDist):
dsBonds.append((residue1,residue2,dist));
prettyPrint(dsBonds);
if __name__ == "__main__":
main()
When I try to run this script I get indentation problem. I have 2v5t.pdb (required to run the above script) in my working directory. Any solution?

For me the indentation is broken within 'prettyPrint' and in 'main'. Also no need to use ';'. Try this:
#!/usr/bin/env python
import math
# Input: Two 3D points of the form (x,y,z).
# Output: Euclidean distance between the points.
def getDistance((x1, y1, z1), (x2, y2, z2)):
d = math.sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2) + pow((z1 - z2), 2))
return round(d, 3)
# Purpose: Prints a list of 3-tuples (r1,r2,d). R1 and r2 are
# residue numbers, and d is the distance between their respective
# gamma sulfur atoms.
def prettyPrint(dsBonds):
print "Residue 1\tResidue 2\tDistance"
for r1, r2, d in dsBonds:
print " {0}\t\t {1}\t\t {2}".format(r1, r2, d)
# Purpose: Find all pairs of cysteine residues whose gamma sulfur atoms
# are within maxBondDist of each other.
def main():
pdbFile = open('2v5t.pdb','r')
#Max distance to consider a disulfide bond.
maxBondDist = 2.5
# Anonymous function to check if a line from the PDB file is a gamma
# sulfur atom from a cysteine residue.
isCysLine = lambda line: (line[0:4] == "ATOM" and line[13:15] == "SG")
cysLines = [line for line in pdbFile if isCysLine(line)]
pdbFile.close()
# Anonymous function to get (x,y,z) coordinates in angstroms for
# the location of a cysteine residue's gamma sulfur atom.
getCoords = lambda line:(float(line[31:38]),
float(line[39:46]), float(line[47:54]))
cysCoords = map(getCoords, cysLines)
# Make a list of all residue pairs classified as disulfide bonds.
dsBonds = []
for i in range(len(cysCoords)-1):
for j in range(i+1, len(cysCoords)):
dist = getDistance(cysCoords[i], cysCoords[j])
residue1 = int(cysLines[i][23:27])
residue2 = int(cysLines[j][23:27])
if dist < maxBondDist:
dsBonds.append((residue1,residue2,dist))
prettyPrint(dsBonds)
if __name__ == "__main__":
main()

This:
if __name__ == "__main__":
main()
Should be:
if __name__ == "__main__":
main()
Also, the python interpreter will give you information on the IndentationError down to the line. I strongly suggest reading the error messages provided, as developers write them for a reason.

You didn't say where the error was flagged to be but:
if __name__ == "__main__":
main()
Should be:
if __name__ == "__main__":
main()

Related

Generative Art in Python- Upstream Logic causing "Invalid Literal for int()"

I'm a novice coder working on a small generative art exercise to make space-invader sprites, have been stuck on this for a while even though it's probably a trivial problem. The goal of the code is to allow the user to define their own inputs in the command line for a grid of sprite characters, like this:
python spritething.py [SPRITE_DIMENSIONS] [NUMBER] [IMAGE_SIZE]
'''
import PIL, sys, random
from PIL import Image, ImageDraw
origDimension = 1500
r = lambda: random.randint(50,255)
rc = lambda: ('#%02X%02X%02X' % (r(),r(),r()))
listSym = []
def create_square(border, draw, randColor, element, size):
if (element == int(size/2)):
draw.rectangle(border, randColor)
elif (len(listSym) == element+1):
draw.rectangle(border,listSym.pop())
else:
listSym.append(randColor)
draw.rectangle(border, randColor)
def create_invader(border, draw, size):
x0, y0, x1, y1 = border
squareSize = (x1-x0)/size
randColors = [rc(), rc(), rc(), (0,0,0), (0,0,0), (0,0,0)]
i = 1
for y in range(0, size):
i *= -1
element = 0
for x in range(0, size):
topLeftX = x*squareSize + x0
topLeftY = y*squareSize + y0
botRightX = topLeftX + squareSize
botRightY = topLeftY + squareSize
create_square((topLeftX, topLeftY, botRightX, botRightY), draw, random.choice(randColors), element, size)
if (element == int(size/2) or element == 0):
i *= -1;
element += i
def main(size, invaders, imgSize):
origDimension = imgSize
origImage = Image.new('RGB', (origDimension, origDimension))
draw = ImageDraw.Draw(origImage)
invaderSize = origDimension/invaders
padding = invaderSize/size
for x in range(0, invaders):
for y in range(0, invaders):
topLeftX = x*invaderSize + padding/2
topLeftY = y*invaderSize + padding/2
botRightX = topLeftX + invaderSize - padding
botRightY = topLeftY + invaderSize - padding
create_invader((topLeftX, topLeftY, botRightX, botRightY), draw, size)
origImage.save("Examples/Example-"+str(size)+"x"+str(size)+"-"+str(invaders)+"-"+str(imgSize)+".jpg")
if __name__ == "__main__":
main(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]))
'''
When I run this code I get a value error from the last line where the argv's are soposed to go. but I'm not sure where I'm going wrong upstream. Any help greatly appreciated.
'''
---------------------------------------------------------------------------
ValueError Traceback (most recent call
15
16 if __name__ == "__main__":
---> 17 main(int(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3]))
ValueError: invalid literal for int() with base 10: '--ip=127.0.0.1'
'''
Assuming you've got a Python script script.py:
import sys
print(sys.argv)
And you run it from the terminal via:
python script.py firstarg 123 thirdarg
The output will be:
['script.py', 'firstarg', '123', 'thirdarg']
Notice: sys.argv is a list of strings, where each string represents one of the command line arguments passed in when the script was initially executed. Also notice that the first command line argument will always be a string with the script file's name. Even if you run the same script with no "custom" command line arguments, your program will always get at least one command line argument by default (the script's name.)
EDIT - Here is the image that's generated when I run your script (no changes):

How to solve non-numeric type in numeric context error in pyomo python

This is the code. I think the solver could be glpk instead of gurobi. I got the error before it tries to solve the problem.
from pyomo.environ import *
from pyomo.opt import SolverFactory, SolverStatus
PrintSolverOutput = False ###
model = ConcreteModel()
model.dual = Suffix(direction =Suffix.IMPORT)
model.X = Var(I,T, within = NonNegativeReals)
model.In = Var(I,T, within = NonNegativeReals)
model.S = Var(T, within = NonNegativeReals)
def Objetivo(model):
return (sum(C[i]*model.X[i,t]*((1+tau[i])**(t-1))+Ch[i]*model.In[i,t]
for i in I for t in T)
+sum(Cs*model.S[t]
for t in T)
)
model.Total_Cost = Objective(rule = Objetivo, sense= minimize)
def Balance(model,i,t):
if t==1:
return model.X[i,t]+I0[i]-model.In[i,t]==D[i,t]
elif t>=2:
return model.X[i,t]+model.IN[i,t-1]-model.In[i,t]==D[i,t]
def Horas(model, t):
return sum(r[i]*model.X[i,t] for i in I) <= H+model.S[t]
def Limite(model,t):
return model.S[T]<=LS
model.RBalance = Constraint(I,T,rule=Balance)
model.RHoras = Constraint(T,rule=Horas)
model.RLimiteoras = Constraint(T,rule=Limite)
opt = SolverFactory("gurobi")
This is the data
I forgot to put the data before.
T = [1,2,3,4,5,6]
I = ['A','B']
D = {('A',1):300,
('A',2):400,
('A',3):500,
('A',4):600,
('A',5):800,
('A',6):700,
('B',1):700,
('B',2):600,
('B',3):500,
('B',4):400,
('B',5):300,
('B',6):400}
tau = {'A':0.02,'B':0.01}
r = {'A':5,'B':3}
H = 3520
LS = 800
C = {'A':150,'B':120}
Ch = {'A':8,'B':4}
Cs = 6
I0 = {'A':100,'B':250}
error
The code is from a youtube tutorial and it worked for him but not for me. Why?
Aside from fixing two typos in your code, this model computes and solves for me without that error. Make these fixes, run it again, re-post the exact error with line number and the exact code that produces the error if stuck...

invalid syntax for moving robot

SyntaxError: invalid syntax
I have a syntax error, but i could not solve it, need help
error: for k, g in groupby(enumerate(ranges), lambda (i,x):i-x):
Also, 1 question if anyone is able to help me
i am using Ubuntu 18.04, i rosrun this file but got [rosrun] Couldn't find executable named sensor_data_listerner.py below /home/sk/catkin_ws/src/testbot_description
is it because of the ROS python version i am using that caused the error?
the following is the code:
#!/usr/bin/env python
import rospy
from std_msgs.msg import String
import sensor_msgs.msg
import random
import numpy as np
from geometry_msgs.msg import Twist
from itertools import *
from operator import itemgetter
LINX = 0.0 #Always forward linear velocity.
THRESHOLD = 1.5 #THRESHOLD value for laser scan.
PI = 3.14
Kp = 0.05
angz = 0
def LaserScanProcess(data):
range_angels = np.arange(len(data.ranges))
ranges = np.array(data.ranges)
range_mask = (ranges > THRESHOLD)
ranges = list(range_angels[range_mask])
max_gap = 40
# print(ranges)
gap_list = []
for k, g in groupby(enumerate(ranges), lambda (i,x):i-x):
gap_list.append(map(itemgetter(1), g))
gap_list.sort(key=len)
largest_gap = gap_list[-1]
min_angle, max_angle = largest_gap[0]*((data.angle_increment)*180/PI), largest_gap[-1]*((data.angle_increment)*180/PI)
average_gap = (max_angle - min_angle)/2
turn_angle = min_angle + average_gap
print(min_angle, max_angle)
print(max_gap,average_gap,turn_angle)
global LINX
global angz
if average_gap < max_gap:
angz = -0.5
else:
LINX = 0.5
angz = Kp*(-1)*(90 - turn_angle)
def main():
rospy.init_node('listener', anonymous=True)
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
rospy.Subscriber("scan", sensor_msgs.msg.LaserScan , LaserScanProcess)
rate = rospy.Rate(10) # 10hz
while not rospy.is_shutdown():
command = Twist()
command.linear.x = LINX
command.angular.z = angz
pub.publish(command)
rate.sleep()
if __name__ == '__main__':
main()
You can't unpack a tuple in the argument list of a lambda expression (or of a def statement) in Python 3. (That's a change from Python 2, where your lambda expression would have been valid.)
You'll have to use
lambda t: t[0] - t[1]
instead.

OpenMDAO/ScipyOptimizer "UnboundLocalError: local variable 'f_new' referenced before assignment"

Trying to run the paraboloid example from OpenMDAO documentation but using the ScipyOptimizer, and I get the error in the title. Not sure what I'm doing wrong. I've attached a MWE below.
OpenMDAO 1.7.3, Python 3.6.0.
# -*- coding: utf-8 -*-
"""
Paraboloid tutorial from OpenMDAO documentation:
https://openmdao.readthedocs.io/en/latest/usr-guide/tutorials/paraboloid-tutorial.html
"""
# import print function from Python 3 if we are using Python 2
from __future__ import print_function
# import all the components we need from openmdao module
from openmdao.api import IndepVarComp, Component, Problem, Group, ScipyOptimizer
class Paraboloid(Component):
""" Evaluates the equation f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3 """
def __init__(self):
super(Paraboloid, self).__init__()
self.add_param('x', val=0.0)
self.add_param('y', val=0.0)
self.add_output('f_xy', shape=1)
def solve_nonlinear(self, params, unknowns, resids):
"""f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3
"""
x = params['x']
y = params['y']
unknowns['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0
def linearize(self, params, unknowns, resids):
""" Jacobian for our paraboloid."""
x = params['x']
y = params['y']
J = {}
J['f_xy', 'x'] = 2.0*x - 6.0 + y
J['f_xy', 'y'] = 2.0*y + 8.0 + x
return J
# This if statement executes only if the script is run as a script, not if the
# script is imported as a module. It's not necessary for this demo, but it
# is good coding practice.
if __name__ == "__main__":
# initiallize the overall problem
top = Problem()
# each problem has a root "group" that contains the component evaluating
# the objective function
root = top.root = Group()
# define components with the independent variables and their initial guesses
root.add('p1', IndepVarComp('x', 3.0))
root.add('p2', IndepVarComp('y', -4.0))
# add the component that defines our objective function
root.add('p', Paraboloid())
# connect the components together
root.connect('p1.x', 'p.x')
root.connect('p2.y', 'p.y')
# specify our driver for the problem (optional)
top.driver = ScipyOptimizer()
top.driver.options['optimizer'] = 'SLSQP'
top.driver.options['disp'] = True # don't display optimizer output
# set up the problem
top.setup()
# run the optimization
top.run()
print(top['p.f_xy'])
I figured it out. In a classic moment of brain-fartiness, I forgot to add my design variables and objective functions to the driver. Something like this is what I was missing:
top.driver = ScipyOptimizer()
top.driver.options['optimizer'] = 'SLSQP'
top.driver.add_desvar('p1.x', lower=-50, upper=50)
top.driver.add_desvar('p2.y', lower=-50, upper=50)
top.driver.add_objective('p.f_xy')

Function that computes Runge Kutta not ploting

Hi I am working on a script that will solve and plot an ODE using the Runge Kutta method. I want to have the script use different functions so I can expand upon it later. If I write it with out the function definition it works fine, but with the def() it will not open a plot window or print the results. Than you!
from numpy import *
import matplotlib.pyplot as plt
#H=p^2/2-cosq
#p=dp=-dH/dq
#q=dq=dH/dp
t = 0
h = 0.5
pfa = [] #Create arrays that will hold pf,qf values
qfa = []
while t < 10:
q = 1*t
p = -sin(q*t)
p1 = p
q1 = q
p2 = p + h/2*q1
q2 = q + h/2*p1
p3 = p+ h/2*q2
q3 = q+ h/2*p2
p4 = p+ h/2*q3
q4 = q+ h/2*p4
pf = (p +(h/6.0)*(p1+2*p2+3*p3+p4))
qf = (q +(h/6.0)*(q1+2*q2+3*q3+q4))
pfa.append(pf) #append arrays
qfa.append(qf)
t += h #increase time step
print("test")
plt.plot(pfa,qfa)
print("test1")
plt.show()
print("tes2t")
If you have a function declared, you'll need to call it at some point, e.g.:
def rk(p,q,h):
pass # your code here
if __name__ == '__main__':
rk(1,2,1)
Putting the function call within the if __name__ == '__main__' block will ensure that the function is called only when you run the script directly, not when you import it from another script. ( More on that here in case you're interested: What does if __name__ == "__main__": do? )
And here's an even better option; to avoid hard-coding fn args (your real code should have some error-handling for unexpected command-line input):
def rk(p,q,h):
pass # your code here
if __name__ == '__main__':
import argparse
the_parser = argparse.ArgumentParser()
the_parser.add_argument('integers', type=int, nargs=3)
args = the_parser.parse_args()
p,q,h = args.integers
rk(p,q,h)

Categories

Resources