Showing posts with label computer-graphics. Show all posts
Showing posts with label computer-graphics. Show all posts

Friday, August 26, 2016

Square spiral - drawing with 3D effect (turtle graphics)

By Vasudev Ram

I was doing some work with Python turtle graphics for a project, and came up with this simple program that draws a square-ish spiral in multiple colors. It has a bit of a 3D effect. You can see it as a pyramid with you above, the levels ascending toward you, or you can see it (again from above) as a well with steps, going downward.

Here is the code and a screenshot of its output:
'''
square_spiral.py
A program that draws a "square spiral".
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
'''

import turtle
t = turtle

colors = ['blue', 'green', 'yellow', 'orange', 'red']

def pause():
    _ = raw_input("Press Enter to exit:")

def spiral(t, step, step_incr, angle):
    color_ind = 0
    colors_len = len(colors)
    t.pencolor(colors[color_ind])
    while True:
        t.forward(step)
        step = step + step_incr
        if step > 500:
            break
        t.right(angle)
        color_ind = (color_ind + 1) % colors_len
        t.pencolor(colors[color_ind])

    t.hideturtle()
    pause()

t.speed(0)
spiral(t, 20, 5, 90.2)


- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

My Python posts     Subscribe to my blog by email

My ActiveState recipes



Wednesday, March 2, 2016

Recursive computation of simple functions

By Vasudev Ram
Image: Squares. Attribution: Vasudev Ram.

I got this idea to compute some simple functions using recursion, after browsing a chain of links recently, that happened to lead me to the original paper about Lisp, RECURSIVE FUNCTIONS OF SYMBOLIC EXPRESSIONS AND THEIR COMPUTATION BY MACHINE (Part I), by its inventor, John McCarthy. I remembered that I had come across it, maybe in a public library, in my college days, and had read it then.

Anyway, I didn't understand the whole paper at the time, but did understand some of the examples of recursion. So today I thought of implementing, just for fun, a few simple algorithms in a recursive way, even though there exist simple non-recursive solutions for them.

So here are a few simple recursive algorithms:

1: Recursive computation of list length:

This uses recursion to find the length of a Python list, i.e. it does what the built-in function len() does. Languages that support recursion often use the terms head and tail of a list, to mean the first item of the list, and the rest of the list (not counting the first item). Of course, the tail of a list is also a list, which is where the recursive algorithm comes in. So the length of a list can be defined recursively as:

0, if the list is empty (i.e. contains no items)
or
1 + the length of the tail of the list, if the list is non-empty, i.e. if it has at least one item in it.
This is a recursive definition because we are using the concept of the list's length in the very definition of its length. As long as the recursive calls terminate at some point, the definition will work.

The code for rec_list_len.py:

# Recursive list length computation.

def rec_list_len(lis):
    if not lis:
        return 0
    #print "calling rec_list_len with lis = {}".format(lis)
    return 1 + rec_list_len(lis[1:])

print "Recursive computation of list length:"
print
for lis_siz in range(5):
    lis = range(lis_siz)
    lis_len = rec_list_len(lis)
    print 'List: {}   Length: {}'.format(lis, lis_len)
    print

# Also test rec_list_len on other kinds of sequences than lists:

s = 'hello there'
print 'String: "{}"   Length: {}'.format(s, rec_list_len(s))
print
s = 'the quick brown fox'
print 'String: "{}"   Length: {}'.format(s, rec_list_len(s))
print

student = ('Jack', 25, 'New York')
print 'Tuple: {}   Length: {}'.format(student, rec_list_len(student))
print
student = ('Jill', 27, 'Paris', 'France')
print 'Tuple: {}   Length: {}'.format(student, rec_list_len(student))
print
Running the program gives this output:
$ python rec_list_len.py
Recursive computation of list length:

List: []   Length: 0

List: [0]   Length: 1

List: [0, 1]   Length: 2

List: [0, 1, 2]   Length: 3

List: [0, 1, 2, 3]   Length: 4

String: "hello there"   Length: 11

String: "the quick brown fox"   Length: 19

Tuple: ('Jack', 25, 'New York')   Length: 3

Tuple: ('Jill', 27, 'Paris', 'France')   Length: 4
Notice that in the above output, we also have the length of strings and tuples computed by the same function. This works, even though I initially wrote the function only to compute list lengths, because lists, strings and tuples are all kinds of Python sequences, and the code I've used in the function is valid for any Python sequence that supports slicing. Lists, strings and tuples all do.

Also, if you uncomment the print statement in function rec_list_len, and run the program, you will see that successively smaller segments (tails, really) of the list are being passed to the function on each (recursive) call. This will help understand what is going on, if it seems unclear otherwise.

This program demonstrates, via a simple computation, the essence of the recursive approach to problem-solving: defining the solution in terms of smaller problems of the same kind. But recursion can also be used to solve harder problems, often elegantly and with a relatively simple algorithm, once we have figured out to solve the original problem in terms of sub-problems of the same kind. For example, tree traversal.

[ It's also worth noting that any recursive solution can be transformed (manually, by the programmer) into an iterative solution that does not use recursion, and uses a while or for loop and a stack instead, and this is sometimes done for the sake of efficiency. ]

Once we've worked out the logic for recursive length computation, code for similar computations on a list is straightforward, with only minor changes from the above:

2: Recursive computation of sum of numbers in a list:

This uses recursion to find the sum of the numbers in a Python list, i.e. it does what the built-in function sum() does.
The code for rec_list_sum.py:
# Recursive list sum computation.
# Assumes list items are numbers.

def rec_list_sum(lis):
    if not lis:
        return 0
    return lis[0] + rec_list_sum(lis[1:])

for r in range(5):
    lis = range(r)
    print "Sum:", rec_list_sum(lis), "List:", lis
Program run and output:
Sum: 0 List: []
Sum: 0 List: [0]
Sum: 1 List: [0, 1]
Sum: 3 List: [0, 1, 2]
Sum: 6 List: [0, 1, 2, 3]
3: Recursive computation of product of numbers in a list:

This uses recursion to find the product of the numbers in a Python list.
The code for rec_list_product.py:
# Recursive list product computation.
# Assumes list items are numbers.

def rec_list_product(lis):
    if not lis:
        return 1
    return lis[0] * rec_list_product(lis[1:])

for r in range(1, 7):
    lis = range(1, r)
    print "Product:", rec_list_product(lis), "List:", lis
Program run and output:
$ python rec_list_product.py
Product: 1 List: []
Product: 1 List: [1]
Product: 2 List: [1, 2]
Product: 6 List: [1, 2, 3]
Product: 24 List: [1, 2, 3, 4]
Product: 120 List: [1, 2, 3, 4, 5]
And that images of nested squares at the top of the post? You guessed it, it's generated by a Python turtle graphics program - not the preceding link in this sentence, that's for the graphics module; see below for the program.

It's a recursive program, naturally :)

Here is the code for the squares program, pasted straight from an IPython session, where I wrote and ran it:
In [63]: def square_and_move(side, dist):
   ....:     square(side)
   ....:     t.penup()
   ....:     t.forward(dist)
   ....:     t.right(90)
   ....:     t.forward(dist)
   ....:     t.left(90)
   ....:     t.pendown()
   ....:     side -= 20
   ....:     if side >= 60:
   ....:         square_and_move(side, dist)
   ....:

In [64]: square_and_move(200, 20)
in which, function square has the obvious definition of drawing a square of the given size (the argument 'side'), by moving forward(side) and then doing right(90), four times each.

Here is the basis of another turtle graphics program that let's you draw stuff interactively.

-Enjoy.

- Vasudev Ram - Online Python training and programming

Signup to hear about new products and services I create.

Posts about Python  Posts about xtopdf

My ActiveState recipes

Tuesday, January 19, 2016

Simple drawing program with Python turtle graphics

By Vasudev Ram


Image attribution: Claudio Giovenzana www.longwalk.it

Some time back I had written a post with a simple turtle graphics program in Python:

(The history of turtle graphics is of interest, including the early years, when they used actual robots for the turtles, which were controlled by programs). The Wikipedia page in the link above has the details.)

Here is the post I wrote earlier:

Python, meet Turtle

Python has support for turtle graphics in the standard library.

Today I wrote a different kind of turtle graphics program: a simple drawing program that allows you to interactively draw figures using a few keys on the keyboard.

The program is a first version, so is not polished. But it works, as far as I tested it.

You can use the following keys to control the turtle and draw:

- up arrow to move forward
- down arrow to move backward
- left arrow to turn left 45 degrees
- right arrow to turn right 45 degrees
- h or H key to move the turtle to its home position (center of screen, heading east)
- c or C key to clear the screen
- q or Q to quit the program

Note: If you do Clear and then Home, and if your turtle had been away from the home position when you did the Clear, the screen will get cleared, but then the Home action will draw a line from where the turtle just was to its (new) home position. If that happens, just press C again to clear the screen of that line.
The better way is to do Home first and then Clear.

Here is the code for the program:
# Program to do drawing using Python turtle graphics.
# turtle_drawing.py v0.1
# Author: Vasudev Ram
# http://jugad2.blogspot.in/p/about-vasudev-ram.html
# Copyright (C) 2016 Vasudev Ram.

import turtle

# Create and set up screen and turtle.

t = turtle
# May need to tweak dimensions below for your screen.
t.setup(600, 600)
t.Screen()
t.title("Turtle Drawing Program - by Vasudev Ram")
t.showturtle()

# Set movement step and turning angle.
step = 160
angle = 45

def forward():
    '''Move forward step positions.'''
    print "forward", step
    t.forward(step)

def back():
    '''Move back step positions.'''
    print "back", step
    t.back(step)

def left():
    '''Turn left by angle degrees.'''
    print "left", angle
    t.left(angle)

def right():
    '''Turn right by angle degrees.'''
    print "right", angle
    t.right(angle)

def home():
    '''Go to turtle home.'''
    print "home"
    t.home()

def clear():
    '''Clear drawing.'''
    print "clear"
    t.clear()

def quit():
    print "quit"
    t.bye()

t.onkey(forward, "Up")
t.onkey(left, "Left")
t.onkey(right, "Right")
t.onkey(back, "Down")
t.onkey(home, "h")
t.onkey(home, "H")
t.onkey(clear, "c")
t.onkey(clear, "C")
t.onkey(quit, "q")
t.onkey(quit, "Q")

t.listen()
t.mainloop()
Support for more turtle actions (see the Python turtle module's docs linked above) can be added, for many of them on the same pattern as the existing functions, without changing the overall structure of the program. Some others may require changes to the design, which is very simple as of now. (I applied the principle Do The Simplest Thing That Could Possibly Work.)

Also, a point to note: many of the capabilities of the turtle module are available in both procedural and object-oriented versions. Here, to keep it simple, I've used the procedural style.

Here are a few screenshots of drawings I created by running and using this program:

A diamond (just a square tilted):


A square:


A figure made out of squares:


The image at the top of the post is of Olive ridley sea turtles.

- Vasudev Ram - Online Python training and programming

Signup to hear about new products and services I create.

Posts about Python  Posts about xtopdf

My ActiveState recipes

Saturday, January 11, 2014

pngcanvas, a pure Python PNG library

By Vasudev Ram

I saw pngcanvas recently on Github.

pngcanvas is a minimalist pure Python library by Rui Carmo that lets you create PNG images from programs.

I only did a quick trial of it by modifying the test_pngcanvas.py program that comes with it - mainly stripping it down to the minimum needed to create a PNG file (since the program is more about testing the library than being an introductory example).

Here is my modified version, try_pngcanvas.py - some of the imports may not be needed:
#!/usr/bin/env python

from __future__ import (
    absolute_import, division, print_function, unicode_literals
)

import io
import logging

from pngcanvas import *

BUFSIZE = 8*1024  # Taken from filecmp module
HEIGHT = WIDTH = 512

logging.debug("Creating canvas: %d, %d", WIDTH, HEIGHT)
c = PNGCanvas(WIDTH, HEIGHT, color=(0xff, 0, 0, 0xff))
c.rectangle(0, 0, WIDTH - 1, HEIGHT - 1)

logging.debug("Generating gradient...")
c.vertical_gradient(1, 1, WIDTH - 2, HEIGHT - 2,
    (0xff, 0, 0, 0xff), (0x20, 0, 0xff, 0x80))

logging.debug("Drawing some lines...")
c.color = bytearray((0, 0, 0, 0xff))
c.line(0, 0, WIDTH - 1, HEIGHT - 1)
c.line(0, 0, WIDTH / 2, HEIGHT - 1)
c.line(0, 0, WIDTH - 1, HEIGHT / 2)

with open("try_pngcanvas.png", "wb") as png_fil:
    logging.debug("Writing to file...")
    png_fil.write(c.dump())


Here is the PNG image created by the program:


The program worked on the first try, no tweaking needed - a tribute to the author of pngcanvas.

Subjectively, it also seemed to run fast, though the image created is small.

Update: In my initial version, I had deleted the code to create a gradient. That was when the program ran fast. When I added the gradient code back, it ran significantly slower. Like, less than a second, vs. maybe 2 seconds. Not timed, just guessed. (It can be timed, of course, using various methods.) But considering that generating a gradient is a lot more work than just drawing lines, it seems not bad, at least relatively speaking.

I had also blogged some time ago about pypng, another such library:

pypng, pure Python module to encode/decode PNG

Read other Python posts on my blog.

- Vasudev Ram - Dancing Bison Enterprises


O'Reilly 50% Ebook Deal of the Day


Contact Page

Monday, July 1, 2013

Python, meet Turtle

By Vasudev Ram


from time import sleep
import turtle as t

def waitforever():
    while True:
    sleep(10)

def main():
    x = 15
    while True:
        t.forward(x)
        t.right(90)
        x = x + 10
        if x > 500:
            break

    waitforever()

main()


Python Turtle graphics

- Vasudev Ram - Dancing Bison Enterprises

Contact me

Monday, March 18, 2013

VPython - Python plus 3D graphics


By Vasudev Ram

VPython 'is the Python programming language plus a 3D graphics module called "visual" originated by David Scherer in 2000. VPython makes it easy to create navigable 3D displays and animations, even for those with limited programming experience. Because it is based on Python, it also has much to offer for experienced programmers and researchers.' - from the VPython site.

I had come across VPython quite a few years ago, and tried it out a bit at the time. I saw it again today via a chain of links, and was interested to see that it has been updated for recent Python versions. I downloaded and installed the VPython version for Python 2.7.3 and tried out the bouncing ball VPython example. It worked fine.

A couple of interesting points about VPython:

- it has what seems to be a modified version of the Python GUI shell, IDLE, called VIDLE, that works like IDLE, and when you enter and run a VPython program, it displays the 3D graphics output in one of the VIDLE windows. I entered and ran the bouncing ball example using VIDLE.

- going by the bouncing ball example, VPython seems to use some form of partially declarative, rather than procedural code, for parts of what it does, since the example does not actually have any code to update the graphics on the screen - it just 'has computations to update the position of the ball and check whether it hits the floor. The 3D animation is a side effect of these computations.'

Update:

The latest version of VPython has been modified to use wxPython:

https://github.com/BruceSherwood/vpython-wx#readme

- Vasudev Ram - Dancing Bison Enterprises



Monday, December 31, 2012

Cairo, multi-language, cross-platform graphics library, and PyCairo


http://cairographics.org

The cairo graphics library is an interesting toolkit,  used by many well-known products, including GTK+, Mono, Poppler, Mozilla Firefox, WebKit, R, Gnuplot and others.

It supports graphics output to many targets, including the X Window System (Unix and other platforms), Win32, Mac OS X Quartz, PDF, PostScript, PNG and SVG.

Though written in C, it has bindings for many programming languages, including C++ , Factor, Haskell , Lua , Perl , Python , Ruby, Scheme , Smalltalk and others.

Pycairo is the Python binding to cairographics.

http://en.m.wikipedia.org/wiki/Cairo_(graphics).

According to Wikipedia (see above), one of the founders of the cairo library was Keith Packard, who was also one of the key developers of X-Windows:

http://en.m.wikipedia.org/wiki/Keith_Packard

It was interesting to read that, because I had attended a training program on X, XLib, Xt and Motif, at the company where I worked, years ago; this was before X became widely available on Linux desktop computers; we used HP workstations during the course. I remember having a lot of fun during that course, along with the other participants. We kidded each other and the instructor a lot. Who can forget "DC the DC; Window theWindow", etc. :)
(DC being Device Context). Those were C / XLib declarations, from an X book used for the course, which might have been by Packard (or Gettys, IIRC).

I also remember a colleague of mine, creating a rudimentary version of a graphical paint program, like MS Paint, in Motif,  during the Motif part of the course, in under an hour or so. That was probably my first introduction to the power of frameworks, and to the concept of callbacks (in C). I don't think I really grokked them at the time, though I did, later.

http://cairographics.org/samples/

I had come across cairo some time ago, and made a note of it, because of its support for PDF output, an area I'm interested in, and also because of its  Python support.

I saw it again today via the page  below on preshing.com (which is the same site where I saw the info for my recent post on Mandelbrot graphics and Python):

http://preshing.com/20110920/the-python-with-statement-by-example

The above page gives a nice example of the use of Python's with statement, in the context of using PyCairo to draw some rectangles, each rotated by some angle from the previous one, without the transformations being additive (in a sense - see the post for details).

- Vasudev Ram

Saturday, December 29, 2012

Mandelbrot poster contains its own Python code as Mandelbrot

High-Resolution Mandelbrot in Obfuscated Python

Seen via a tweet by @atulnene.

http://www.google.com/images?q=mandelbrot


http://en.m.wikipedia.org/wiki/Mandelbrot_set

Interesting that the set is mentioned in popular culture.

See above links for songs, etc., that refer to it.
I even saw a comparison between it and mandalas, which doesn't
seem far-fetched, since mandalas have some connection
with mathematics.

http://en.m.wikipedia.org/wiki/Mandala

http://en.m.wikipedia.org/wiki/Benoit_Mandelbrot

Thursday, December 6, 2012

Try the R language online

Code School - Try R

Looks interesting. R is a programming language with an emphasis on statistics and computer graphics.

Hacker News thread about Try R, has many more links to R learning resources,and a good discussions of R's pros and cons vs. other options, including Python with numpy / scipy, etc.:

http://news.ycombinator.com/item?id=4878393

- Vasudev Ram
www.dancingbison.com

Friday, September 14, 2012

Lissajous hippo, retrocomputing and the IBM PC Jr.

By Vasudev Ram


The image below is of a Lissajous figure, found from a Google image search.



I was reminded about Lissajous curves by an interesting blog post I read recently on Fred Wilson's blog:

A VC: After School Programming

While the post is about a new initiative of Codecademy, one of his portfolio companies, there were a lot of comments on the post by readers who got into computers at an early age, describing the computers they worked on then, and what they did using them. That reminded me of my own experiences on the same lines.

I had written a lot of (amateur) computer graphics and other programs, including a program to make the computer act as a piano, long ago, on an old home computer of mine, a used IBM PC Jr., which was the first computer I owned. It was given as a present to me by my aunt from the States, when she came to India for a visit, back when I was in college and had just started learning programming. (I actually got introduced to computers and programming by a high school friend of mine who was an electronics hobbyist, who had got hold of a Casio programmable calculator and lent it to me for a while. Though it was technically called a calculator, it was a sort of micro computer, since it had BASIC in ROM, and you could write BASIC programs on it, and those programs could even display computer graphics on its LCD screen.) The IBM PC Jr. was, ultimately, a commercial failure (see the linked Wikipedia article), for a few reasons (less powerful than a regular business PC, non-expandable, priced too high for a hobbyist computer, etc.) But it had many cool and powerful features, including good graphics (for the time), and quite good sound abilities (3 channels, or so) and even music (you could play notes not just in regular tone but in legato and staccato). And all of this was programmable in their version of BASIC.

For old times' sake, I also googled for the IBM PC Jr., and found this interesting web site about it, by an aficionado of the machine. I count myself as one too :)

Mike's PCJr page

- Vasudev Ram - Dancing Bison Enterprises