473,847 Members | 1,821 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

More pythonic circle?

I wrote the following code for a personal project. I need a function
that will plot a filled circle in a two dimensional array. I found
Bresenham's algorithm, and produced this code. Please tell me there's
a better way to do this.

import numpy

def circle(field=No ne,radius,cente r=(0,0),value=2 55,):
'''Returns a list of points within 'radius' distance from point
'center'.'''
if field==None:
field=numpy.zer os((radius,radi us),'u')
cx,cy=center
filllist=[]
dy,dx=0,radius
r2=radius**2
while dy<=(radius*.71 ): # sin of 45 degrees
if dx**2+dy**2<=r2 :
for x in range(dx):
filllist.append ((x,dy))
dy+=1
else:
dx-=1
if dx<dy : break
resultlist=[]
for (i,j) in filllist:
field[cx+i][cy+j]=value
field[cx+j][cy+i]=value
field[cx-j][cy+i]=value
field[cx-i][cy+j]=value
field[cx-i][cy-j]=value
field[cx-j][cy-i]=value
field[cx+j][cy-i]=value
field[cx+i][cy-j]=value
return field

Apr 9 '06 #1
14 3609
OTTOMH, in a rush to go out: never mind Pythonic, following apply to
any language:
(1) accuracy: (a) sue me if I'm wrong, but I think you need range(dx+1)
so that the dx pixel is filled in (b) a few more digits after 0.71
might be useful
(2) efficiency: seems that range(dy, dx+1) would save some wear & tear
on the circuitry :-)
(3) legibility: there's no prize for the script with the absolutely
minimum number of space characters :-)
I think I've got an article on better Bresenham somewhere in the
archives; will dig it out later.
Cheers,
John

Apr 9 '06 #2

John Machin wrote:
OTTOMH, in a rush to go out: never mind Pythonic, following apply to
any language:
(1) accuracy: (a) sue me if I'm wrong, but I think you need range(dx+1)
so that the dx pixel is filled in Hmm. I think you're right. Thanks. (b) a few more digits after 0.71
might be useful Sine of 45 degrees is actually .707... I rounded up, since I was using
<=. Figured that would make it clear. (2) efficiency: seems that range(dy, dx+1) would save some wear & tear
on the circuitry :-) It took me a few minutes to figure out waht you meant here. This will
certainly help reduce the repeated coordinates. Thanks, again.
(3) legibility: there's no prize for the script with the absolutely
minimum number of space characters :-) True. I assume your saying I should make cx,cy,dx, and dy better
names. I probably will. Up to now I was just playing around with
this, and not really expecting anyone else to read it.
I think I've got an article on better Bresenham somewhere in the
archives; will dig it out later.

I'd definitely appreciate it. In fact, I'm trying to find a decent
sphere version, and getting nowhere with google. I tried to figure it
out on my own, and ended up with 48 coordinates for each valid test.
I'm not sure if that's right.

Lee

Apr 9 '06 #3
Em Sáb, 2006-04-08 Ă*s 21:17 -0700, Pythor escreveu:
John Machin wrote:
(3) legibility: there's no prize for the script with the absolutely
minimum number of space characters :-)

True. I assume your saying I should make cx,cy,dx, and dy better
names. I probably will. Up to now I was just playing around with
this, and not really expecting anyone else to read it.


This is kinda funny because you just posted the code to a list with
hundreds of developers. =)

--
Felipe.

Apr 9 '06 #4
Proving yet again that it's possible to write Fortran in any language.

You aren't getting any benefit from numpy or python here. Are you
aiming for speed or legibility?

Also, with this code, you are using radius for the dimensions of the
enclosing box, as well as the radius of the circle, so it's guaranteed
to not to actually produce a whole circle. Recall what python does with
negative indices!

I'll bet this does the trick for you and runs faster than what you've
got

def circle(rad = 5,max_x = 20, max_y = 20,cx = 10, cy= 10, value=255):
radsq = rad * rad
return numpy.array([[((x - cx) ** 2 + (y - cy) ** 2 < radsq) and
value or 0 for x in range(max_x)] for y in range(max_y)],'u')

I think the pure numpy solution should be something like (untested)

def circle(rad = 5,max_x = 20, max_y = 20,cx = 10, cy= 10, value=255):
def sqdist(x,y):
return (x - cx) * (x - cx) + (y - cy) * (y - cy)
distarray = numpy.fromfunct ion(sqdist,(max _y,max_x))
return
numpy.asarray(n umpy.choose(gre ater(distarray, rad*rad),(0,val ue),'u')

Neither approach will get you the eightfold speedup that the messy code
was aimed at, but in practice they will spend less time at the
interpreter level and will likely run faster.

mt

Apr 9 '06 #5
On Sat, 08 Apr 2006 21:17:32 -0700, Pythor wrote:
(3) legibility: there's no prize for the script with the absolutely
minimum number of space characters :-)

True. I assume your saying I should make cx,cy,dx, and dy better
names. I probably will. Up to now I was just playing around with
this, and not really expecting anyone else to read it.


No, "minimum number of space characters" means "you don't use enough
spaces", not "your variable names are too short" *wink*

Generally speaking, a little bit of whitespace helps makes text more
readable, at least for native speakers of languages derived from Latin and
other Indo-European languages. Graphic designers tend to manually adjust
the spacing between paragraphs, lines, words and even characters, but it
isn't necessary to go to that extreme to increase readability.

People's tastes vary, and these are not rules, only guidelines, but it is
usual to leave one (and sometimes more) blank lines between functions and
methods, and even between logical sections of a single function.

Within a single line, a good guideline is to leave a single space on
either side of pluses and minuses (e.g. x**2 + 5*x - 3). Likewise, a
single space on both sides of an equal sign and a single space after
commas tend to be usual.

As I said, none of these are hard and fast rules, but breaking up the flow
of tokens will increase readability immensely.

See Guido van Rossum's style guide and the official Python style guide. As
usual, Guido is always right, and if his style guide contradicts me, he's
wrong but you should follow his guide anyway *smiles*

http://www.python.org/doc/essays/styleguide.html
http://www.python.org/dev/peps/pep-0008/

As for variables cx, cy, dx and dy, I don't believe that they are unclear.
If your function is highly mathematical in nature, I believe it is
acceptable if not expected to follow standard mathematical conventions
such as r for radius, x and y for real numbers, z for complex, dx for
delta (change of) x, etc. If in doubt, when initialising the variable add
a comment spelling it out in full.

On the other hand, you do have an argument "value" with default 255, with
not even hint for what it is.
--
Steven.

Apr 9 '06 #6

Michael Tobis wrote:
Proving yet again that it's possible to write Fortran in any language.
Ouch...
You aren't getting any benefit from numpy or python here. Are you
aiming for speed or legibility?
Speed will be a necessity, eventually. I was just really aiming for
something that works, and that I am capable of writing.
Also, with this code, you are using radius for the dimensions of the
enclosing box, as well as the radius of the circle, so it's guaranteed
to not to actually produce a whole circle. Recall what python does with
negative indices!
I'm not sure what you mean here. It produces an eighth-circle, and
then plots each point in the 8 symmetrical positions on the circle.
Except for the (dx+1) point made above, what piece of the circle is
missing?
I'll bet this does the trick for you and runs faster than what you've
got

def circle(rad = 5,max_x = 20, max_y = 20,cx = 10, cy= 10, value=255):
radsq = rad * rad
return numpy.array([[((x - cx) ** 2 + (y - cy) ** 2 < radsq) and
value or 0 for x in range(max_x)] for y in range(max_y)],'u')

I think the pure numpy solution should be something like (untested)

def circle(rad = 5,max_x = 20, max_y = 20,cx = 10, cy= 10, value=255):
def sqdist(x,y):
return (x - cx) * (x - cx) + (y - cy) * (y - cy)
distarray = numpy.fromfunct ion(sqdist,(max _y,max_x))
return
numpy.asarray(n umpy.choose(gre ater(distarray, rad*rad),(0,val ue),'u')
I'll take a look at both of these. At this point, I can't quite wrap
my head around what you're doing for either one.
Neither approach will get you the eightfold speedup that the messy code
was aimed at, but in practice they will spend less time at the
interpreter level and will likely run faster.

mt


Apr 9 '06 #7

Steven D'Aprano wrote:
No, "minimum number of space characters" means "you don't use enough
spaces", not "your variable names are too short" *wink*
Hmm. Guess I can't read too well.
Within a single line, a good guideline is to leave a single space on
either side of pluses and minuses (e.g. x**2 + 5*x - 3). Likewise, a
single space on both sides of an equal sign and a single space after
commas tend to be usual. What I produced was natural for my fingers, but I can see that it's
difficult on the eyes. I'll try to remember that.
As for variables cx, cy, dx and dy, I don't believe that they are unclear.
If your function is highly mathematical in nature, I believe it is
acceptable if not expected to follow standard mathematical conventions
such as r for radius, x and y for real numbers, z for complex, dx for
delta (change of) x, etc. If in doubt, when initialising the variable add
a comment spelling it out in full.

On the other hand, you do have an argument "value" with default 255, with
not even hint for what it is.

Well, value is just a value. It's the number that get's punched into
the array for any points within the circle. I didn't have any better
name I could think of.

Apr 9 '06 #8
"Pythor" wrote:
You aren't getting any benefit from numpy or python here. Are you
aiming for speed or legibility?

Speed will be a necessity, eventually. I was just really aiming for
something that works, and that I am capable of writing.


any special reason you cannot use an existing graphics library ?

</F>

Apr 9 '06 #9

Fredrik Lundh wrote:
"Pythor" wrote:
You aren't getting any benefit from numpy or python here. Are you
aiming for speed or legibility?

Speed will be a necessity, eventually. I was just really aiming for
something that works, and that I am capable of writing.


any special reason you cannot use an existing graphics library ?

</F>

Well, I'm not really interested in pretty pictures, but in the
resulting array. It might be worth using a graphics library and then
converting from an image to an array when I'm done. I've been playing
with PIL for that. But I wanted to see what I could do on my own, too.
In addition, I'll eventually need some functions that are definitely
not in a standard graphics library, and I wanted to get started with
something I thought was relatively simple.

Apr 9 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
1546
by: Nickolay Kolev | last post by:
Hi all, I would like to find a more pythonic way of solving the following: Having a string consisting of letters only, find out the total sound score of the string. The sound score is calculated as the sum of the transition scores between the characters in that string. The transition scores are stored in a 26 x 26 matrix. I.e. the transition A -> F would have the score soundScoreMatrix.
1
7037
by: rdeaton | last post by:
I need to design and code a Java program that calculates and prints the (D) diameter, the (C) circumference, or the (A) area of a circle, given the radius. The program inputs two data items: the calculation needed, and the radius of the circle. The program should continue to ask the user for values until the user enters 'Q' as the calculation type. The program should echo print the input data and prompt appropriately. Label the output and format...
0
1943
by: Chua Wen Ching | last post by:
Hi.. just wonder i draw a circle in the picturebox1 1) and i want to store the circle in memory (only circle) when i store into bmp... i want to see the circle with transparent backrground...
0
1877
by: robert | last post by:
As more and more python packages are starting to use the bloomy (Java-ish) 'logging' module in a mood of responsibility and as I am not overly happy with the current "thickener" style of usage, I want to put this comment and a alternative most simple default framework for discussion. Maybe there are more Python users which like to see that imported (managed) logging issue more down-to-earth and flexible ? ... Vinay Sajip wrote: >...
5
2221
by: akameswaran | last post by:
Disclaimer - I recognize this is not a practical exercise. There are many implementations around that would do the job better, more efficiently (Meaning in C) or whatever. I caught some thread about sorting and started thinking about shell sort.... and as part of my trying to pythonise my mind and break my java mindset So I decided to tackle this old school problem with the python mindset.
16
2538
by: Andy Dingley | last post by:
I'm trying to write rot13, but to do it in a better and more Pythonic style than I'm currrently using. What would you reckon to the following pretty ugly thing? How would you improve it? In particular, I don't like the way a three-way selection is done by nesting two binary selections. Also I dislike stating the same algorithm twice, but can't see how to parameterise them neatly. Yes, I know of .encode() and .translate(). No, I...
3
23235
by: okan | last post by:
Hi everyone, I have a java method public static String circleRelation(double x1, double y1, double r1, double x2, double y2, double r2) that - given two circles in the plane - will decide whether those circles (1) encircle each other, (2) intersect, (3) touch or (4) are totally seperate. The method returns a String which describes the relationship between those circles, e.g.: The first circle encircles the second circle The circles...
9
5516
by: saraaana | last post by:
Given the center and a point on the circle, you can use this formula to find the radius of the circle. Write a program that prompts the user to enter the center and a point on the circle. The program should then output the circle’s radius, diameter, circumference, and area. Your program must have at least the following functions: a. distance: This function takes as its parameters four numbers that represent two points in the plane and returns...
14
14534
by: DeadSilent | last post by:
I have this code and for some reason I keep getting an error where it says "exporting non-public type through public api ".. I'm not sure why this keeps happening but it does so for getCircleInfo / drawCircle. Thanks for your help. - Me. package shapemaker; import java.awt.*; import javax.swing.*;
0
9881
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9727
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10982
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10645
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5718
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5909
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4523
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4116
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.