from visual import box, sphere, vector
def read_points(filename):
"""
Read points from file filename.
>>> read_points("testdata0.txt")
[[0.0, 0.0], [1.0, -1.0], [2.0, 3.0]]
"""
file = open(filename, 'r')
points = [] #initialize our list of points
for line in file:
point = [] #a point is just a list of numbers
str_coords = line.split() #split the line
#"2 3 4" -> ["2", "3", "4"]
for str_coord in str_coords:
coord = float(str_coord) #convert coordinate to number
point.append(coord) #add coordinate to point
points.append(point) #add point to the list of points
file.close()
return points
def save_points(points, fname):
"""
Given a list of points, save them to the file named fname. These
points can be read back in with read_points(fname).
>>> save_points([[0,0],[1,-1],[2,3]], "testdata0.txt")
"""
file = open(fname, 'w')
for point in points:
for coord in point:
print >>file, coord,
print >>file
file.close()
def show_points(points, color=(0,1,0)):
"""
Given a list of 2D or 3D points, draw them as spheres in the active
VPython window. If no color is given, the spheres will be green.
#>>> show_points([[0,0],[1,-1],[2,3]])
"""
for point in points:
sphere(pos=point, radius=.5, color=color)
def show_box(p1, p2, color=(0,0,1)):
"""
Given two points p1 and p2, draw a box in the active VPython window
indicating the rectangle outlined by p1 and p2. If no color is given,
the box will be blue.
#>>> show_box([0,0], [5,5])
"""
# convert the points to vectors to make math much more convenient
p1 = vector(p1)
p2 = vector(p2)
# pos gives the center of the box, so we want it to be the average
# of p1 and p2
# size gives the size of the box, so we want it to be the distance
# between p1 and p2
box(pos=(p1+p2)/2, size=(p1-p2), color=color)
def random_points(n, d):
"""
Generate a list of n random points in d-dimensional space. For example,
if d=2, then the points will be in 2D space (they will have two
coordinates). The space that the points are placed in scales with n and d.
>>> len(random_points(5, 3))
5
"""
from random import uniform
r = int(n**(1./d)+1) # we use this so there is roughly
# the same density of points
# regardless of n or d
points = [] # initialize our list of points
for i in range(n): # n times...
point = [] # initialize our point
# (which is just a list of coords)
for j in range(d): # for each dimension...
point.append(uniform(-r, r))# add a random number to the point
points.append(point) # add our completed point to the list
return points
# Self-test code if this module is run directly...
#
if __name__ == "__main__":
import doctest
doctest.master = None
doctest.testmod()