There is a new class. Each instance contain a refernce to next instance.
The goal is to build __repr__(self) function, that represent element of the class with all referenced elements, when each value wrapped by defined symbol. For example by # or *.
Something like this:
****** ****** ******
* 10 * * 20 * * 30 *
****** ****** ******
There is an example:
class Node:
def __init__(self, value):
self.value = value
self.pointer = None
#pointer.setter
def pointer(self, next_node):
self.pointer = next_node
p1 = Node(10)
p2 = Node(20)
p3 = Node(30)
p1.pointer = p2
p2.pointer = p3
print (p1)
That what I did:
def __str__(self):
ans = "{1} {0} {1}".format(self.value, "*")
wrap = "{0:{1}^{2}}".format("", "*", len(ans))
return "{1}\n* {0} *\n{1}".format(ans, wrap)
But it works only for one element.
For printing of all referenced elements i wrote another function:
def show(self):
buf = self
while buf.value:
print(buf)
if buf.pointer:
buf = buf.pointer
else:
break
But it prints each element on a new line. Like this:
******
* 10 *
******
******
* 20 *
******
******
* 30 *
******
The problem is that i don't know how return on first line with some indent and print the next 3 lines elemen.
The question:
Is there some way to build __repr__() function for representing all referenced elements?
That's I have done... Forgive me for this huge code. I am just pretty new in python.
I solved it by .format() funtion. And by printing 3 lines at the output. But i still wait and hope for more elegant solution...
There is also option to change the wrapping character in print_linked_list fuction. And it prints only 5 following values.
def __repr__(self):
return self.print_linked_list()
__str__ = __repr__
def print_linked_list(self, border="*", count=5):
# examples of printing:
# ***** ****** ******* ****** *****
# * 3 * -> * 80 * -> * 100 * -> * 20 * -> * 8 *
# ***** ****** ******* ****** *****
ar = " -> "
wrap, ans_string = str(), str()
buf = self
while buf and count >= 0:
ans = "{0} {1} {0}".format(border, buf.value)
ans_string += ans + (ar if buf.next else "")
wrap += "{0:{1}<{2}}".format("", border, len(ans)) + \
"{:^{}}".format("", len(ar))
buf = buf.next if buf.next else False
count -= 1
return "\n{0}\n{1}\n{0}".format(wrap, ans_string)
Related
Hello I am learning MDAnalysis through python-3.7. Would you please check my code and advise how to resolve the following error:
Traceback (most recent call last):
File "/home/pulokdeb/projects/def-sohrabz/pulokdeb/beluga_python/Closest_atom_Oxy_group.py", line 242, in <module>
eigen_value = iio.eigen_vals()
File "/home/pulokdeb/ENV/lib/python3.7/site-packages/MDAnalysis/core/topologyattrs.py", line 1347, in eigen_vals
com = atomgroup.center_of_mass(pbc=pbc)
NameError: name 'pbc' is not defined
The code (partial) is below:
def radius_of_gyration(group, pbc=False, **kwargs):
"""Radius of gyration.
Parameters
----------
pbc : bool, optional
If ``True``, move all atoms within the primary unit cell before
calculation. [``False``]
.. versionchanged:: 0.8 Added *pbc* keyword
"""
atomgroup = group.atoms
masses = atomgroup.masses
com = atomgroup.center_of_mass(pbc=pbc)
if pbc:
recenteredpos = atomgroup.pack_into_box(inplace=False) - com
else:
recenteredpos = atomgroup.positions - com
rog_sq = np.sum(masses * np.sum(recenteredpos**2,
axis=1)) / atomgroup.total_mass()
return np.sqrt(rog_sq)
transplants[GroupBase].append(
('radius_of_gyration', radius_of_gyration))
I changed a few lines (def_eif_vals) in topologyattrs.py file and got my results. Hope it works for my future simulations.
def shape_parameter(group, pbc=False, **kwargs):
"""Shape parameter.
See [Dima2004a]_ for background information.
Parameters
----------
pbc : bool, optional
If ``True``, move all atoms within the primary unit cell before
calculation. [``False``]
References
----------
.. [Dima2004a] Dima, R. I., & Thirumalai, D. (2004). Asymmetry
in the shapes of folded and denatured states of
proteins. *J Phys Chem B*, 108(21),
6564-6570. doi:`10.1021/jp037128y
<https://doi.org/10.1021/jp037128y>`_
.. versionadded:: 0.7.7
.. versionchanged:: 0.8 Added *pbc* keyword
"""
atomgroup = group.atoms
masses = atomgroup.masses
com = atomgroup.center_of_mass(pbc=pbc)
if pbc:
recenteredpos = atomgroup.pack_into_box(inplace=False) - com
else:
recenteredpos = atomgroup.positions - com
tensor = np.zeros((3, 3))
for x in range(recenteredpos.shape[0]):
tensor += masses[x] * np.outer(recenteredpos[x, :],
recenteredpos[x, :])
tensor /= atomgroup.total_mass()
eig_vals = np.linalg.eigvalsh(tensor)
shape = 27.0 * np.prod(eig_vals - np.mean(eig_vals)
) / np.power(np.sum(eig_vals), 3)
return shape
transplants[GroupBase].append(
('shape_parameter', shape_parameter))
def eigen_vals(group, pbc=False, **kwargs):
""" Changed by Pulok Deb
"""
atomgroup = group.atoms
masses = atomgroup.masses
com = atomgroup.center_of_mass(pbc=pbc)
if pbc:
recenteredpos = atomgroup.pack_into_box(inplace=False) - com
else:
recenteredpos = atomgroup.positions - com
tensor = np.zeros((3, 3))
for x in range(recenteredpos.shape[0]):
tensor += masses[x] * np.outer(recenteredpos[x, :],
recenteredpos[x, :])
tensor /= atomgroup.total_mass()
eig_vals = np.linalg.eigvalsh(tensor)
return eig_vals
transplants[GroupBase].append(
('eigen_vals', eigen_vals))
#warn_if_not_unique
#check_pbc_and_unwrap
I know how to get the factorial answer with recursion
func factorial(n: Int) -> Int {
if n == 0 { return 1 }
else { return n * factorial(n - 1)
}
If I passed factorial(5) the method would return 120, but is it possible to get the calculation?
What I mean is if I had a function called breakDownFactorial and if i called breakDownFactorial(5) it would return 5 * 4 * 3 * 2 * 1, if i called breakDownFactorial(4) it would return 4 * 3 * 2 * 1
and so on.
Well, I'm not entirely sure what you mean by "get the calculation", but to get a string representation of the calculation, you can do something like this:
func breakDownFactorial(n: Int) -> String {
return (1...n).reverse().map(String.init).joinWithSeparator(" * ")
}
breakDownFactorial(5) // 5 * 4 * 3 * 2 * 1
With small modifications, factorial can be converted to breakDownFactorial which returns the string description of the factorial calculation:
func breakDownFactorial(n: Int) -> String {
if n == 0 { return "1" }
else {
return "\(n) * " + breakDownFactorial(n - 1)
}
}
breakDownFactorial(10) // "10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 * 1"
The extra "* 1" accurately reflects how the original factorial function works. If you wish to eliminate it, change the recursive base case to:
if n <= 1 { return "1" }
What I'm trying to do is take numerous(up to 48) 1024x768 images that are color coded images(weather maps, the precip overlay) and add up the precip to fall over the course of time. When I run into non-precip I want to take a box 5x5 around the pixel in question and average the value and use that value as the value of the pixel in question.
I can do this but it takes a long time to accomplish it. I have heard numpy could improve the speed but I still haven't been able to wrap my mind around how it going to improve the speed given the sequence of events that have to take place. It seems like I would still have to do it pixel by pixel. I've included an idea of the code I'm using to accomplish this SLOWLY.
I have this actually as two separate program, one to download the images and the other does the image processing(working up toward merging the two programs in the near future, just trying to get all the bugs worked out before the merger.) Hence some of the download coding may look a little strange. I figure I could probably write the file straight to a variable but I haven't been doing it that way so I stuck with a bit longer approach.
Is there anyway of increasing the speed? I don't see anyway of avoiding pixel by pixel due to the color coding scheme in place(look at the color bar in the lower left it shows the full color scheme...I only included part of it for demo purposes in the coding below.) Some of the coding may be a bit rough since I chopped from the two programs and put the important parts in here...it shows what I'm currently doing and gives the full idea of how I'm going about doing it.
Also, if you happen to see this three to four or more days after it was posted you would need to change the date in the download link to the current date. The files are only kept on the server for 3-4 days before they are removed.
from PIL import Image
import time
import urllib
import os
pathstr = '/'
url = 'http://mag.ncep.noaa.gov/GemPakTier/MagGemPakImages/gfs/20140216/00/gfs_namer_006_1000_500_thick.gif'
urllib.urlretrieve(url,str(pathstr + '20140216006.gif'))
url = 'http://mag.ncep.noaa.gov/GemPakTier/MagGemPakImages/gfs/20140216/00/gfs_namer_012_1000_500_thick.gif'
urllib.urlretrieve(url,str(pathstr + '20140216012.gif'))
url = 'http://mag.ncep.noaa.gov/GemPakTier/MagGemPakImages/gfs/20140216/00/gfs_namer_018_1000_500_thick.gif'
urllib.urlretrieve(url,str(pathstr + '20140216018.gif'))
url = 'http://mag.ncep.noaa.gov/GemPakTier/MagGemPakImages/gfs/20140216/00/gfs_namer_024_1000_500_thick.gif'
urllib.urlretrieve(url,str(pathstr + '20140216024.gif'))
class Convert():
def __init__(self):
self.colorscale2 = [(255,255,255),(127,255,0),(0,205,0),(145,44,238),(16,78,139),
(30,144,255),(0,178,238),(0,238,238),(137,104,205),(0,139,0),
(139,0,139),(139,0,0),(205,0,0),(238,64,0),(255,127,0),(205,133,0),
(255,215,0),(238,238,0),(255,255,0),(139,71,38),(255,0,0),(0,0,255),(0,0,0)]
self.x = 0
self.y = 0
self.grid = 0
self.moist = 0
self.scan = 0
self.turn = 0
self.precip = {}
start = time.time()
for i in range(6, 30, 6):
if i < 10:
filename = '/2014021600' + str(i) + '.gif'
else:
filename = '/201402160' + str(i) + '.gif'
self.im1 = Image.open(filename).convert('RGB')
self.image = self.im1.getdata()
self.size = width, height = self.im1.size
self.coordinates = self.x,self.y = width, height
self.getprecip()
self.turn = 1
print (time.time()-start)
def getprecip(self):
for self.x in range(81, 950):
for self.y in range(29, 749):
if self.turn == 0:
self.moist = 0
else:
self.moist = self.precip[self.x,self.y]
self.coordinates = self.x,self.y
self.scan = 0
self.imagescan()
if self.turn == 0:
self.precip[self.x,self.y] = self.moist
else:
self.precip[self.x,self.y] += self.moist
def imagescan(self):
if self.image[(self.y * 1024) + self.x] == self.colorscale2[0]:
self.moist =0
self.grid -=1
elif self.image[(self.y * 1024) + self.x] == self.colorscale2[1]:
self.moist =.01
elif self.image[(self.y * 1024) + self.x] == self.colorscale2[2]:
self.moist =.1
elif self.image[(self.y * 1024) + self.x] == self.colorscale2[3]:
self.moist =.25
elif self.image[(self.y * 1024) + self.x] == self.colorscale2[4]:
self.moist =.5
#on and on through self.colorscale2[18]
if self.scan == 1:
self.grid += 1
if self.scan == 0:
x = self.x
y = self.y
self.deliso540()
self.x = x
self.y = y
def deliso540(self):
self.grid = 1
self.scan = 1
for p in range(self.x-2,self.x+2):
for q in range(self.y-2,self.y+2):
self.x = p
self.y = q
self.imagescan()
self.moist = self.moist / self.grid
I am getting an Attribute error on the main(). Can someone please help me out?
This is my class:
import math
class Cylinder2():
def __init__(self, cylRadius = 1, cylHeight = 1):
self.__radius = cylRadius
self.__height = cylHeight
def getPerimeter(self):
return (2 * math.pi * self.__radius)
def getEndArea(self):
return (math.pi * (self.__radius ** 2))
def getSideArea(self):
return (2 * (math.pi * (self.__radius * (self.__height))))
def getSurfaceArea(self):
return (2 * (math.pi * (self.__radius) * (self.__height + self.__radius)))
def getVolume(self):
return (math.pi * (self.__radius ** 2) * self.__height)
def setRadius(self, r):
self.__radius = r
def setHeight(self, h):
self.__height = h
def getRadius(self):
return self.__radius
def getHeight(self):
return self.__height
This is the main():
from CylinderModule2 import *
def main():
bottle = Cylinder2(4, 8)
bottle.setRadius(2)
bottle.setHeight(4)
print("The radius and height of the bottle are: ", bottle.__radius, " and ", bottle.__height)
print("The perimeter of the bottle end circle is", ("%.2f" % bottle.getPerimeter()))
print("The end circle area of the bottle is ", ("%.2f" % bottle.getEndArea()))
print("The side area of the bottle is ", ("%.2f" % bottle.getSideArea()))
print("The total surface of the bottle is ", ("%.2f" % bottle.getSurfaceArea()))
print("The volume of the bottle is ", ("%.2f" % bottle.getVolume()))
main()
This is the error I get:
print("The radius and height of the bottle are: ", bottle._radius, " and ", bottle._height)
AttributeError: 'Cylinder2' object has no attribute '__radius'
bottle.__radius and bottle.__height are what can loosely be described as private variables (even though they are not really, you can read about what I mean here: http://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references )
"private" variables can not be directly accessed from outside of the class. In Python, they are denoted by using two underscores (as in __radius).
So what you want to do is using the getters, which are bottle.getRadius() and bottle.getHeight() instead.
I have a function
makeMarks: (first, nextIncrement, classifier) ->
results = new Array()
t = first(#minT)
while t<=#maxT
mark =
t: t
x: this.tToX(t)
class: classifier(t)
results.push(mark)
t = nextIncrement(t)
results
this function works great with the following two functions as parameters
# parameters for hour tickmarks
#firstHour = (t) ->
msPerHour = 1000*60*60
Math.floor(t / msPerHour) * msPerHour
#nextHour = (currentHour) ->
msPerHour = 1000*60*60
currentHour + msPerHour
when called as such
marks = markMaker.makeMarks( #firstMonth, #nextMonth, #classifier)
Now to the problem:
# parameters for month tickmarks
#firstMonth = (minT) ->
msPerDay = 1000*60*60*24
t = Math.floor(minT/msPerDay) * msPerDay
d = new Date(t)
while(d.getDate() isnt 0)
t += msPerDay
d.setTime(t)
t
#nextMonth = (currentMonth) ->
msPerDay = 1000*60*60*24
t = currentMonth + msPerDay
d = new Date(t)
while(d.getDate() isnt 0)
t += msPerDay
d.setTime(t)
t
The hour code works fine, but the month code doesn't seem to terminate.
The getDate function never returns 0. Its minimum value is 1 and it's maximum value is 31. If you're looking for anything outside that range, that's a long wait for a train that don't come.