Receiving the following error: TypeError: float argument required, not instance - python-2.7

I am implementing a big circle class,which does operations like computes area,compares two circle,compares a circle and square etc,but i am having trouble with this small snippet.
class Circle(Point):
def __init__(self, x=0, y=0, r=0):
self.X = x
self.Y = y
self.R = r
self.area = math.pi*r*r
def __str__(self):
return ("A Circle which has centre at " + "(" + "%0.6f" % (self.X) + ", "
+ "%0.6f" % (self.Y) + ")" + "and its radius " + "%0.6f" % (self.R))
def getX(self):
return self.X
def getY(self):
return self.Y
def getR(self):
return self.R
def setR(self):
pass
def area(self):
return math.pi * self.R * self.R
def main():
x = float(input("Enter x coordinate of first circle's centre: "))
y = float(input("Enter y coordinate of the first circle's centre: "))
r = float(input("Enter first circle's radius: "))
pointx1 = x
pointy1 = y
radius1 = r
first_circle = Circle(x, y, r)
print(first_circle)
print("\nArea of first circle is %0.6f" % (first_circle, first_circle.area())
main()
However i get the following error on executing the below code:
print("\nArea of first circle is %0.6f" % (first_circle, first_circle.area))
TypeError: float argument required, not instance
How do i get rid of this.I have calculated self.area in constructor as because i am using it later(haven't shown the code here) to compare two circle's areas which are being sent as argument.Please help.

Remove the first argument in your string format:
print("\nArea of first circle is %0.6f" % (first_circle.area()))
I'm not sure why you put first_circle as an argument since %0.6f is the only part of the string requiring an argument.
Also you need to either rename self.area or rename the method area() because it causes conflicts if they have the same name.

Related

TensorFlow train function with multiple layers

I am new to tensor and trying to understand it. I managed to create one layer model. But I would like now to add 2 more. How can I make my train function working? I would like to train it with hundreds of values X and Y. I implemented all values what I need: Weight and Bias of each layer, but I dont understand how can I use them in my train function. And when it will be trained, how can I use it. Like I do in the last part of a code.
import numpy as np
print("TensorFlow version: {}".format(tf.__version__))
print("Eager execution: {}".format(tf.executing_eagerly()))
x = np.array([
[10, 10, 30, 20],
])
y = np.array([[10, 1, 1, 1]])
class Model(object):
def __init__(self, x, y):
# get random values.
self.W = tf.Variable(tf.random.normal((len(x), len(x[0]))))
self.b = tf.Variable(tf.random.normal((len(y),)))
self.W1 = tf.Variable(tf.random.normal((len(x), len(x[0]))))
self.b1 = tf.Variable(tf.random.normal((len(y),)))
self.W2 = tf.Variable(tf.random.normal((len(x), len(x[0]))))
self.b2 = tf.Variable(tf.random.normal((len(y),)))
def __call__(self, x):
out1 = tf.multiply(x, self.W) + self.b
out2 = tf.multiply(out1, self.W1) + self.b1
last_layer = tf.multiply(out2, self.W2) + self.b2
# Input_Leyer = self.W * x + self.b
return last_layer
def loss(predicted_y, desired_y):
return tf.reduce_sum(tf.square(predicted_y - desired_y))
optimizer = tf.optimizers.Adam(0.1)
def train(model, inputs, outputs):
with tf.GradientTape() as t:
current_loss = loss(model(inputs), outputs)
grads = t.gradient(current_loss, [model.W, model.b])
optimizer.apply_gradients(zip(grads, [model.W, model.b]))
print(current_loss)
model = Model(x, y)
for i in range(10000):
train(model, x, y)
for i in range(3):
InputX = np.array([
[input(), input(), input(), input()],
])
returning = tf.math.multiply(
InputX, model.W, name=None
)
print("I think that output can be:", returning)
Just add new variables to the list:
grads = t.gradient(current_loss, [model.W, model.b, model.W1, model.b1, model.W2, model.b2])
optimizer.apply_gradients(zip(grads, [model.W, model.b, model.W1, model.b1, model.W2, model.b2]))

Pyton2.7 Dot serpenstky triangle Tkinter

For my homework I have to create a program that maps dots to a Tkinter window, and creates a serpenstky triangle out of it. I can create it easily with lines, but I dont understand how I am supposed to get the math to work with dots.
My main question is how would I create a full object with dots using math in python for Tkinter?
from Tkinter import *
from random import randint
# the 2D point class
class Point(object):
def __init__(self,x = 0.0 ,y = 0.0):
self._x = float(x)
self._y = float(y)
#property
def x(self):
return self._x
#x.setter
def x(self):
self._x = x
#property
def y(self):
return self._y
#y.setter
def y(self):
self._y = y
#parts from previous program that I left in here just in case
def __str__(self):
return '(' + str(self.x) + ',' + str(self.y) + ')'
def dist(self,other):
return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
def midpt(self,other):
x=float((self.x + other.x)/2)
y=float((self.y + other.y)/2)
return Point(x,y)
# the coordinate system class: (0,0) is in the top-left corner
# inherits from the Canvas class of Tkinter
class chaosGame(Canvas):
def __init__(self, master):
Canvas.__init__(self, master, bg="white")
self.colors = ["black"]
self.radius = 0
self.pack(fill=BOTH, expand=1)
def plotPoints(self, n):
min_x = 10
min_y = 0
k=1
max_x = 600
max_y = 520
mid_x = (min_x + max_x)/2
mid_y = (min_y + max_y)/2
x1 = 3**k-1
y1 = 3**k-1
for i in range(n):
point = Point((x1), (y1))
self.plot(point.x, point.y)
k+= 1
def vertPoints(self, n):
topPoint = Point((300), (0))
leftPoint = Point((0), (510))
rightPoint = Point((590), (510))
self.vplot(topPoint.x, topPoint.y)
self.vplot(leftPoint.x, leftPoint.y)
self.vplot(rightPoint.x, rightPoint.y)
def vplot(self, x, y):
color = self.colors[randint(0, len(self.colors) - 1)]
self.create_oval(x, y, x + 10, y + 10, fill= "red")
def plot(self, x, y):
color = self.colors[randint(0, len(self.colors) - 1)]
self.create_oval(x, y, x + self.radius, y + self.radius, fill=color)
##########################################################
WIDTH = 600
HEIGHT = 520
# the number of points to plot
NUM_POINTS = 50000
# create the window
window = Tk()
window.geometry("{}x{}".format(WIDTH, HEIGHT))
window.title("Triangles")
# create the coordinate system as a Tkinter canvas inside the window
s = chaosGame(window)
# plot some random points
s.plotPoints(NUM_POINTS)
s.vertPoints(3)
# wait for the window to close
window.mainloop()

how to compare 2 attributes of a class instance

I need to compare every plane (x,y) points. If x or y of American planes is close by 1 than a turn() will apply and change to route of the plane.
Any ideas of how to compare each plane and check if it is close by one?
import random
class CrazyPlane:
def __init__(self,x,y):
self.__x = x
self.__y = y
def update_position(self):
self.__x += random.randint(-1,1)
self.__y += random.randint(-1,1)
def get_position(self):
return self.__x,self.__y
def count_down(self):
for i in range(10,0,-1):
print i
def __eq__(self, other):
return self.value == other
def crash_check(planes):
x = 0
y = 1
flag = True
while (flag):
if (__eq__(planes[x], planes[y])):
print " BOOM!"
else:
y = y + 1
if y == 3:
x = x + 1
y = x + 1
if x == 3:
flag = false
return False
###AND!!!!!!!!!!!!!!!!!!!####
def main():
elal = CrazyPlane.CrazyPlane(1,2)
american = CrazyPlane.CrazyPlane(3,4)
british = CrazyPlane.CrazyPlane(5,6)
lufthansa = CrazyPlane.CrazyPlane(7,8)
planes = [elal,american,british,lufthansa]
flag = True
while (flag):
for plane in planes:
plane.update_position()
if crash_check(planes):
flag = False
print 'Crash'
main()
View on PasteBin

Object of given class callable once, but not again

My code runs fine with one rectangle, but as soon as I add a second rectangle, it says "'point' object is not callable" despite successfully calling it for the first one. I have ran enough tests with different variations on the rectangles to conclude that the only cause is the fact that it is now more than one rectangle it is trying to create. Can anyone please help?
Here's the start of the code, which is used to define different elements and their parameters.
import matplotlib.pyplot as plt
import numpy
elementset = []
pointxs = []
pointys = []
class point(object):
"""General point in 2d space, with stored x value and y value.
Created and used in elements to give them shape.
"""
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
self.isAnchor = False
def __repr__(self):
return "(%d, %d)" % (self.x, self.y)
class element(object):
"""Most general class used to define any element to be used in
the cross-section being worked with. Used as a basis for more
specific classes. Has a coordinate value and a number of points that
need to be generated for the general case.
"""
def __init__(self, anchor_x, anchor_y):
self.num_points = 0
self.anchor_x = float(anchor_x)
self.anchor_y = float(anchor_y)
elementset.append(self)
def getinfo(self):
"""Used for debugging, prints all general info for the element.
Never called in the actual code."""
print "Number of points: " + str(self.num_points)
print "x coordinate: " + str(self.anchor_x)
print "y coordinate: " + str(self.anchor_y)
def debug(self):
self.getinfo()
class rectangle(element):
"""A rectangle, assumed to be aligned such that all sides are
either vertical or horizontal. Calls/assigns variables
created in the element class via super().
"""
def __init__(self, anchor_x, anchor_y, width, height):
super(rectangle, self).__init__(anchor_x, anchor_y)
self.title = "rectangle"
self.num_points = 4
self.width = float(width)
self.height = float(height)
self.generate()
self.calculate()
def generate(self):
"""Creates the points that frame the rectangle using coordinates.
For a rectangle, the anchor point represents the bottom left point."""
self.anchor = point(self.anchor_x, self.anchor_y)
self.pointxpos = point(self.anchor_x + self.width, self.anchor_y)
self.pointxypos = point(self.anchor_x + self.width, self.anchor_y + self.height)
self.pointypos = point(self.anchor_x, self.anchor_y + self.height)
self.points = [self.anchor, self.pointxpos, self.pointxypos, self.pointypos]
self.plotpoints = [self.anchor, self.pointxpos, self.pointxypos, self.pointypos, self.anchor]
And here is the function that calls these (with only 1 rectangle defined):
ar = rectangle(0,0,50,20)
for element in elementset:
if isinstance(element,rectangle):
element.generate()
for point in element.plotpoints:
pointxs.append(point.x)
pointys.append(point.y)
plt.plot(pointxs,pointys, linewidth=3)
elif isinstance(element,square):
pass #placeholder
elif isinstance(element,circle):
pass #placeholder
elif isinstance(element,semicircle):
pass #placeholder
plt.show()
This is successful, plotting a 50x20 rectangle with the bottom left corner at (0,0).
but if i were to add another element below ar:
ar = rectangle(0,0,50,20)
br = rectangle(50,20,10,10)
it throws "'point' object is not callable".
I'm honestly stumped by this, so thank you so much in advance for any given help.
I wonder why this is even successful for the first rectangle. The reason may be that you don't show a true minimal complete verifiable example.
In any case, the problem is as simple as that: Never use the same name for a class as for a (loop-) variable.
I.e. the following works:
ar = rectangle(0,0,50,20)
br = rectangle(23,16,22,13)
elementset.append(ar)
elementset.append(br)
for elefant in elementset:
if isinstance(elefant,rectangle):
elefant.generate()
for wombat in elefant.plotpoints:
pointxs.append(wombat.x)
pointys.append(wombat.y)
plt.plot(pointxs,pointys, linewidth=3)
...apart from the fact that all objects will be connected by a line, but that is probably a different question.

OpenStreetMap generate georeferenced image [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm new to Openstreetmap and mapnick,
I'm trying to export map image which will be geo-referenced
(So it can be used in other applications)
I've installed osm and mapnik inside ubuntu virtual machine
I've tried using generate_image.py script, but generated image is not equal to the bounding box. My python knowledge is not good enough for me to fix the script.
I've also tried using nik2img.py script using verbose mode, for example:
nik2img.py osm.xml sarajevo.png --srs 900913 --bbox 18.227 43.93 18.511 43.765 --dimensions 10000 10000
and tried using the log bounding box
Step: 11 // --> Map long/lat bbox: Envelope(18.2164733537,43.765,18.5215266463,43.93)
Unfortunately generated image is not equal to the bounding box :(
How can I change scripts so I can georeference generated image?
Or do you know an easier way to accomplish this task?
Image i'm getting using the http://www.openstreetmap.org/ export is nicely geo-referenced, but it's not big enough :(
I've managed to change generate_tiles.py to generate 1024x1024 images together with correct bounding box
Changed script is available bellow
#!/usr/bin/python
from math import pi,cos,sin,log,exp,atan
from subprocess import call
import sys, os
from Queue import Queue
import mapnik
import threading
DEG_TO_RAD = pi/180
RAD_TO_DEG = 180/pi
# Default number of rendering threads to spawn, should be roughly equal to number of CPU cores available
NUM_THREADS = 4
def minmax (a,b,c):
a = max(a,b)
a = min(a,c)
return a
class GoogleProjection:
def __init__(self,levels=18):
self.Bc = []
self.Cc = []
self.zc = []
self.Ac = []
c = 1024
for d in range(0,levels):
e = c/2;
self.Bc.append(c/360.0)
self.Cc.append(c/(2 * pi))
self.zc.append((e,e))
self.Ac.append(c)
c *= 2
def fromLLtoPixel(self,ll,zoom):
d = self.zc[zoom]
e = round(d[0] + ll[0] * self.Bc[zoom])
f = minmax(sin(DEG_TO_RAD * ll[1]),-0.9999,0.9999)
g = round(d[1] + 0.5*log((1+f)/(1-f))*-self.Cc[zoom])
return (e,g)
def fromPixelToLL(self,px,zoom):
e = self.zc[zoom]
f = (px[0] - e[0])/self.Bc[zoom]
g = (px[1] - e[1])/-self.Cc[zoom]
h = RAD_TO_DEG * ( 2 * atan(exp(g)) - 0.5 * pi)
return (f,h)
class RenderThread:
def __init__(self, tile_dir, mapfile, q, printLock, maxZoom):
self.tile_dir = tile_dir
self.q = q
self.m = mapnik.Map(1024, 1024)
self.printLock = printLock
# Load style XML
mapnik.load_map(self.m, mapfile, True)
# Obtain <Map> projection
self.prj = mapnik.Projection(self.m.srs)
# Projects between tile pixel co-ordinates and LatLong (EPSG:4326)
self.tileproj = GoogleProjection(maxZoom+1)
def render_tile(self, tile_uri, x, y, z):
# Calculate pixel positions of bottom-left & top-right
p0 = (x * 1024, (y + 1) * 1024)
p1 = ((x + 1) * 1024, y * 1024)
# Convert to LatLong (EPSG:4326)
l0 = self.tileproj.fromPixelToLL(p0, z);
l1 = self.tileproj.fromPixelToLL(p1, z);
# Convert to map projection (e.g. mercator co-ords EPSG:900913)
c0 = self.prj.forward(mapnik.Coord(l0[0],l0[1]))
c1 = self.prj.forward(mapnik.Coord(l1[0],l1[1]))
# Bounding box for the tile
if hasattr(mapnik,'mapnik_version') and mapnik.mapnik_version() >= 800:
bbox = mapnik.Box2d(c0.x,c0.y, c1.x,c1.y)
else:
bbox = mapnik.Envelope(c0.x,c0.y, c1.x,c1.y)
render_size = 1024
self.m.resize(render_size, render_size)
self.m.zoom_to_box(bbox)
self.m.buffer_size = 128
# Render image with default Agg renderer
im = mapnik.Image(render_size, render_size)
mapnik.render(self.m, im)
im.save(tile_uri, 'png256')
print "Rendered: ", tile_uri, "; ", l0 , "; ", l1
# Write geo coding informations
file = open(tile_uri[:-4] + ".tab", 'w')
file.write("!table\n")
file.write("!version 300\n")
file.write("!charset WindowsLatin2\n")
file.write("Definition Table\n")
file.write(" File \""+tile_uri[:-4]+".jpg\"\n")
file.write(" Type \"RASTER\"\n")
file.write(" ("+str(l0[0])+","+str(l1[1])+") (0,0) Label \"Pt 1\",\n")
file.write(" ("+str(l1[0])+","+str(l1[1])+") (1023,0) Label \"Pt 2\",\n")
file.write(" ("+str(l1[0])+","+str(l0[1])+") (1023,1023) Label \"Pt 3\",\n")
file.write(" ("+str(l0[0])+","+str(l0[1])+") (0,1023) Label \"Pt 4\"\n")
file.write(" CoordSys Earth Projection 1, 104\n")
file.write(" Units \"degree\"\n")
file.close()
def loop(self):
while True:
#Fetch a tile from the queue and render it
r = self.q.get()
if (r == None):
self.q.task_done()
break
else:
(name, tile_uri, x, y, z) = r
exists= ""
if os.path.isfile(tile_uri):
exists= "exists"
else:
self.render_tile(tile_uri, x, y, z)
bytes=os.stat(tile_uri)[6]
empty= ''
if bytes == 103:
empty = " Empty Tile "
self.printLock.acquire()
print name, ":", z, x, y, exists, empty
self.printLock.release()
self.q.task_done()
def render_tiles(bbox, mapfile, tile_dir, minZoom=1,maxZoom=18, name="unknown", num_threads=NUM_THREADS):
print "render_tiles(",bbox, mapfile, tile_dir, minZoom,maxZoom, name,")"
# Launch rendering threads
queue = Queue(32)
printLock = threading.Lock()
renderers = {}
for i in range(num_threads):
renderer = RenderThread(tile_dir, mapfile, queue, printLock, maxZoom)
render_thread = threading.Thread(target=renderer.loop)
render_thread.start()
#print "Started render thread %s" % render_thread.getName()
renderers[i] = render_thread
if not os.path.isdir(tile_dir):
os.mkdir(tile_dir)
gprj = GoogleProjection(maxZoom+1)
ll0 = (bbox[0],bbox[3])
ll1 = (bbox[2],bbox[1])
for z in range(minZoom,maxZoom + 1):
px0 = gprj.fromLLtoPixel(ll0,z)
px1 = gprj.fromLLtoPixel(ll1,z)
# check if we have directories in place
zoom = "%s" % z
if not os.path.isdir(tile_dir + zoom):
os.mkdir(tile_dir + zoom)
for x in range(int(px0[0]/1024.0),int(px1[0]/1024.0)+1):
# Validate x co-ordinate
if (x < 0) or (x >= 2**z):
continue
# check if we have directories in place
str_x = "%s" % x
if not os.path.isdir(tile_dir + zoom + '/' + str_x):
os.mkdir(tile_dir + zoom + '/' + str_x)
for y in range(int(px0[1]/1024.0),int(px1[1]/1024.0)+1):
# Validate x co-ordinate
if (y < 0) or (y >= 2**z):
continue
str_y = "%s" % y
tile_uri = tile_dir + zoom + '_' + str_x + '_' + str_y + '.png'
# Submit tile to be rendered into the queue
t = (name, tile_uri, x, y, z)
queue.put(t)
# Signal render threads to exit by sending empty request to queue
for i in range(num_threads):
queue.put(None)
# wait for pending rendering jobs to complete
queue.join()
for i in range(num_threads):
renderers[i].join()
if __name__ == "__main__":
home = os.environ['HOME']
try:
mapfile = "/home/emir/bin/mapnik/osm.xml" #os.environ['MAPNIK_MAP_FILE']
except KeyError:
mapfile = "/home/emir/bin/mapnik/osm.xml"
try:
tile_dir = os.environ['MAPNIK_TILE_DIR']
except KeyError:
tile_dir = home + "/osm/tiles/"
if not tile_dir.endswith('/'):
tile_dir = tile_dir + '/'
#-------------------------------------------------------------------------
#
# Change the following for different bounding boxes and zoom levels
#
#render sarajevo at 16 zoom level
bbox = (18.256, 43.785, 18.485, 43.907)
render_tiles(bbox, mapfile, tile_dir, 16, 16, "World")
Try Maperitive's export-bitmap command, it generates various georeferencing sidecar files
(worldfile, KML, OziExplorer .MAP file).