Skip to content

Commit effb240

Browse files
committed
First commit
0 parents  commit effb240

34 files changed

+870
-0
lines changed

9781484227428.jpg

45.5 KB
Loading

Chapter 10/RangeImager.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
2+
import breve
3+
4+
class AggressorController( breve.BraitenbergControl ):
5+
def __init__( self ):
6+
breve.BraitenbergControl.__init__( self )
7+
self.depth = None
8+
self.frameCount = 0
9+
self.leftSensor = None
10+
self.leftWheel = None
11+
self.n = 0
12+
self.rightSensor = None
13+
self.rightWheel = None
14+
self.simSpeed = 0
15+
self.startTime = 0
16+
self.vehicle = None
17+
self.video = None
18+
AggressorController.init( self )
19+
20+
def init( self ):
21+
self.n = 0
22+
while ( self.n < 10 ):
23+
breve.createInstances( breve.BraitenbergLight, 1 ).move( breve.vector( ( 20 * breve.breveInternalFunctionFinder.sin( self, ( ( self.n * 6.280000 ) / 10 ) ) ), 1, ( 20 * breve.breveInternalFunctionFinder.cos( self, ( ( self.n * 6.280000 ) / 10 ) ) ) ) )
24+
self.n = ( self.n + 1 )
25+
26+
self.vehicle = breve.createInstances( breve.BraitenbergVehicle, 1 )
27+
self.watch( self.vehicle )
28+
self.vehicle.move( breve.vector( 0, 2, 18 ) )
29+
self.leftWheel = self.vehicle.addWheel( breve.vector( -0.500000, 0, -1.500000 ) )
30+
self.rightWheel = self.vehicle.addWheel( breve.vector( -0.500000, 0, 1.500000 ) )
31+
self.leftWheel.setNaturalVelocity( 0.000000 )
32+
self.rightWheel.setNaturalVelocity( 0.000000 )
33+
self.rightSensor = self.vehicle.addSensor( breve.vector( 2.000000, 0.400000, 1.500000 ) )
34+
self.leftSensor = self.vehicle.addSensor( breve.vector( 2.000000, 0.400000, -1.500000 ) )
35+
self.leftSensor.link( self.rightWheel )
36+
self.rightSensor.link( self.leftWheel )
37+
self.leftSensor.setBias( 15.000000 )
38+
self.rightSensor.setBias( 15.000000 )
39+
self.video = breve.createInstances( breve.Image, 1 )
40+
self.video.setSize( 176, 144 )
41+
self.depth = breve.createInstances( breve.Image, 1 )
42+
self.depth.setSize( 176, 144 )
43+
self.startTime = self.getRealTime()
44+
45+
def postIterate( self ):
46+
self.frameCount = ( self.frameCount + 1 )
47+
self.simSpeed = ( self.getTime() / ( self.getRealTime() - self.startTime ) )
48+
print '''Simulation speed = %s''' % ( self.simSpeed )
49+
self.video.readPixels( 0, 0 )
50+
self.depth.readDepth( 0, 0, 1, 50 )
51+
if ( self.frameCount < 10 ):
52+
self.video.write( '''imgs/video-%s.png''' % ( self.frameCount ) )
53+
54+
self.depth.write16BitGrayscale( '''imgs/depth-%s.png''' % ( self.frameCount ) )
55+
56+
57+
breve.AggressorController = AggressorController
58+
59+
60+
# Create an instance of our controller object to initialize the simulation
61+
62+
AggressorController()
63+

Chapter 10/genetic.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
"""
2+
# Example usage
3+
from genetic import *
4+
target = 371
5+
p_count = 100
6+
i_length = 6
7+
i_min = 0
8+
i_max = 100
9+
p = population(p_count, i_length, i_min, i_max)
10+
fitness_history = [grade(p, target),]
11+
for i in xrange(100):
12+
p = evolve(p, target)
13+
fitness_history.append(grade(p, target))
14+
15+
for datum in fitness_history:
16+
print datum
17+
"""
18+
from random import randint, random
19+
from operator import add
20+
21+
def individual(length, min, max):
22+
'Create a member of the population.'
23+
return [ randint(min,max) for x in xrange(length) ]
24+
25+
def population(count, length, min, max):
26+
"""
27+
Create a number of individuals (i.e. a population).
28+
29+
count: the number of individuals in the population
30+
length: the number of values per individual
31+
min: the minimum possible value in an individual's list of values
32+
max: the maximum possible value in an individual's list of values
33+
34+
"""
35+
return [ individual(length, min, max) for x in xrange(count) ]
36+
37+
def fitness(individual, target):
38+
"""
39+
Determine the fitness of an individual. Higher is better.
40+
41+
individual: the individual to evaluate
42+
target: the target number individuals are aiming for
43+
"""
44+
sum = reduce(add, individual, 0)
45+
return abs(target-sum)
46+
47+
def grade(pop, target):
48+
'Find average fitness for a population.'
49+
summed = reduce(add, (fitness(x, target) for x in pop))
50+
return summed / (len(pop) * 1.0)
51+
52+
def evolve(pop, target, retain=0.2, random_select=0.05, mutate=0.01):
53+
graded = [ (fitness(x, target), x) for x in pop]
54+
graded = [ x[1] for x in sorted(graded)]
55+
retain_length = int(len(graded)*retain)
56+
parents = graded[:retain_length]
57+
# randomly add other individuals to
58+
# promote genetic diversity
59+
for individual in graded[retain_length:]:
60+
if random_select > random():
61+
parents.append(individual)
62+
# mutate some individuals
63+
for individual in parents:
64+
if mutate > random():
65+
pos_to_mutate = randint(0, len(individual)-1)
66+
# this mutation is not ideal, because it
67+
# restricts the range of possible values,
68+
# but the function is unaware of the min/max
69+
# values used to create the individuals,
70+
individual[pos_to_mutate] = randint(
71+
min(individual), max(individual))
72+
# crossover parents to create children
73+
parents_length = len(parents)
74+
desired_length = len(pop) - parents_length
75+
children = []
76+
while len(children) < desired_length:
77+
male = randint(0, parents_length-1)
78+
female = randint(0, parents_length-1)
79+
if male != female:
80+
male = parents[male]
81+
female = parents[female]
82+
half = len(male) / 2
83+
child = male[:half] + female[half:]
84+
children.append(child)
85+
parents.extend(children)
86+
return parents

Chapter 11/firstVehicle.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import breve
2+
3+
class Controller(breve.BraitenbergControl):
4+
def __init__(self):
5+
breve.BraitenbergControl.__init__(self)
6+
self.vehicle = None
7+
self.leftSensor = None
8+
self.rightSensor = None
9+
self.leftWheel = None
10+
self.rightWheel = None
11+
self.simSpeed = 0
12+
self.light = None
13+
Controller.init(self)
14+
15+
def init(self):
16+
self.light = breve.createInstances(breve.BraitenbergLight, 1)
17+
self.light.move(breve.vector(10, 1, 0))
18+
self.vehicle = breve.createInstances(breve.BraitenbergVehicle,1)
19+
self.watch(self.vehicle)
20+
self.vehicle.move( breve.vector(0, 2, 18)) self.leftWheel = self.vehicle.addWheel(breve.vector(-0.500000,0,-1.500000)) self.rightWheel = self.vehicle.addWheel( breve.vector(-0.500000,0,1.500000)) self.leftWheel.setNaturalVelocity(0.000000) self.rightWheel.setNaturalVelocity(0.000000)
21+
self.rightSensor = self.vehicle.addSensor(breve.vector(2.000000, 0.400000, 1.500000)) self.leftSensor = self.vehicle.addSensor( breve.vector(2.000000, 0.400000, -1.500000 ) ) self.leftSensor.link(self.rightWheel) self.rightSensor.link(self.leftWheel) self.leftSensor.setBias(15.000000) self.rightSensor.setBias(15.000000)
22+
23+
def iterate(self):
24+
breve.BraitenbergControl.iterate(self)
25+
26+
breve.Controller = Controller
27+
28+
Controller()

Chapter 11/secondVehicle.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import breve
2+
3+
class Controller(breve.BraitenbergControl):
4+
def __init__(self):
5+
breve.BraitenbergControl.__init__(self)
6+
self.vehicle = None
7+
self.leftSensor = None
8+
self.rightSensor = None
9+
self.leftWheel = None
10+
self.rightWheel = None
11+
self.simSpeed = 0
12+
self.light = None
13+
Controller.init(self)
14+
15+
def init(self):
16+
17+
self.light = breve.createInstances(breve.BraitenbergLight, 1)
18+
self.light.move(breve.vector(10, 1, 0))
19+
self.vehicle = breve.createInstances(breve.BraitenbergVehicle,1)
20+
self.watch(self.vehicle)
21+
self.vehicle.move( breve.vector(0, 2, 18)) self.leftWheel = self.vehicle.addWheel(breve.vector(-0.500000,0,-1.500000)) self.rightWheel = self.vehicle.addWheel( breve.vector(-0.500000,0,1.500000)) self.leftWheel.setNaturalVelocity(0.500000) self.rightWheel.setNaturalVelocity(1.000000)
22+
self.rightSensor = self.vehicle.addSensor(breve.vector(2.000000, 0.400000, 1.500000)) self.leftSensor = self.vehicle.addSensor( breve.vector(2.000000, 0.400000, -1.500000 ) ) self.leftSensor.link(self.rightWheel) self.rightSensor.link(self.leftWheel) self.leftSensor.setBias(15.000000) self.rightSensor.setBias(15.000000)
23+
self.startTime = self.getRealTime()
24+
25+
def iterate(self):
26+
breve.BraitenbergControl.iterate(self)
27+
self.simSpeed = (self.getTime()/(self.getRealTime()- self.startTime)) print '''Simulation speed = %s''' % ( self.simSpeed )
28+
29+
breve.Controller = Controller
30+
31+
Controller()

Chapter 11/subsumption.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
import RPi.GPIO as GPIOimport timeimport threadingimport numpy as np# next two libraries must be installed IAW appendix instructionsimport Adafruit_GPIO.SPI as SPIimport Adafruit_MCP3008class Behavior(): global pwmL, pwmR, distance1, distance2 # use the BCM pin numbers GPIO.setmode(GPIO.BCM) # setup the motor control pins GPIO.setup(18, GPIO.OUT) GPIO.setup(19, GPIO.OUT) pwmL = GPIO.PWM(18,20) # pin 18 is left wheel pwm pwmR = GPIO.PWM(19,20) # pin 19 is right wheel pwm # must 'start' the motors with 0 rotation speeds pwmL.start(2.8) pwmR.start(2.8)class Controller(): def __init__(self): self.behaviors = [] self.wait_object = threading.Event() self.active_behavior_index = None self.running = True #self.return_when_no_action = return_when_no_action #self.callback = lambda x: 0 def add(self, behavior): self.behaviors.append(behavior) def remove(self, index): old_behavior = self.behaviors[index] del self.behaviors[index] if self.active_behavior_index == index: # stop the old one if the new one overrides it old_behavior.suppress() self.active_behavior_index = None def update(self, behavior, index): old_behavior = self.behaviors[index] self.behaviors[index] = behavior if self.active_behavior_index == index: # stop the old one if the new one overrides it old_behavior.suppress() def step(self): behavior = self.find_next_active_behavior() if behavior is not None: self.behaviors[behavior].action() return True return False def find_next_active_behavior(self): for priority, behavior in enumerate(self.behaviors): active = behavior.takeControl() if active == True: activeIndex = priority print 'index = ', activeIndex time.sleep(2) return activeIndex def find_and_set_new_active_behavior(self): new_behavior_priority = self.find_next_active_behavior() if self.active_behavior_index is None or self.active_behavior_index > new_behavior_priority: if self.active_behavior_index is not None: self.behaviors[self.active_behavior_index].suppress() self.active_behavior_index = new_behavior_priority print 'priority = ', self.active_behavior_index # Callback to tell something it changed the active behavior if anything is interested# self.callback(self.active_behavior_index) def start(self): # run the action methods self.running = True self.find_and_set_new_active_behavior() # force do it ourselves once to find the right one thread = threading.Thread(name="Continuous behavior checker", target=self.continuously_find_new_active_behavior, args=()) thread.daemon = True thread.start() while self.running: if self.active_behavior_index is not None: running_behavior = self.active_behavior_index self.behaviors[running_behavior].action() if running_behavior == self.active_behavior_index: self.active_behavior_index = None self.find_and_set_new_active_behavior()## elif self.return_when_no_action:# break #Nothing more to do, so we are shutting down self.running = False# def start(self, run_in_thread=False):# if run_in_thread:# thread = threading.Thread(name="Subsumption Thread",# target=self._start, args=())# thread.daemon = True# thread.start()# else:# self.start() def stop(self): self._running = False self.behaviors[self.active_behavior_index].suppress() def continuously_find_new_active_behavior(self): while self.running: self.find_and_set_new_active_behavior() def __str__(self): return str(self.behaviors)class NormalBehavior(Behavior): def takeControl(self): return True def action(self): # drive forward pwmL.ChangeDutyCycle(3.6) pwmR.ChangeDutyCycle(2.2) def suppress(self): # all stop pwmL.ChangeDutyCycle(2.6) pwmR.ChangeDutyCycle(2.6)class AvoidObstacle(Behavior): def takeControl(self): #self.distance1 = distance1 #self.distance2 = distance2 if self.distance1 <= 25.4 or self.distance2 <= 25.4: return True else: return False def action(self): # drive backward pwmL.ChangeDutyCycle(2.2) pwmR.ChangeDutyCycle(3.6) time.sleep(1.5) # turn right pwmL.ChangeDutyCycle(3.6) pwmR.ChangeDutyCycle(2.6) time.sleep(0.3) # stop pwmL.ChangeDutyCycle(2.6) pwmR.ChangeDutyCycle(2.6) def suppress(self): # all stop pwmL.ChangeDutyCycle(2.6) pwmR.ChangeDutyCycle(2.6) def setDistances(self, dest1, dest2): self.distance1 = dest1 self.distance2 = dest2class StopRobot(Behavior): global voltage critical_voltage = 6 def takeControl(self): if voltage < critical_voltage: return True else: return False def action(self): # drive forward pwmL.ChangeDutyCycle(3.6) pwmR.ChangeDutyCycle(2.2) def suppress(self): # all stop pwmL.ChangeDutyCycle(2.6) pwmR.ChangeDutyCycle(2.6)class testBBR(): def __init__(self): # instantiate objects self.nb = NormalBehavior() self.oa = AvoidObstacle() self.control = Controller() # setup the behaviors array by priority; last-in = highest self.control.add(self.nb) self.control.add(self.oa) # initialize distances distance1 = 50 distance2 = 50 self.oa.setDistances(distance1, distance2) # activate the behaviors self.control.start() threshold = 25.4 #10 inches # use the BCM pin numbers GPIO.setmode(GPIO.BCM) # ultrasonic sensor pins self.TRIG1 = 23 # an output self.ECHO1 = 24 # an input self.TRIG2 = 25 # an output self.ECHO2 = 27 # an input # set the output pins GPIO.setup(self.TRIG1, GPIO.OUT) GPIO.setup(self.TRIG2, GPIO.OUT) # set the input pins GPIO.setup(self.ECHO1, GPIO.IN) GPIO.setup(self.ECHO2, GPIO.IN) # initialize sensors GPIO.output(self.TRIG1, GPIO.LOW) GPIO.output(self.TRIG2, GPIO.LOW) time.sleep(1) # Hardware SPI configuration: SPI_PORT = 0 SPI_DEVICE = 0 self.mcp = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE)) def run(self): # forever loop while True: # sensor 1 reading GPIO.output(self.TRIG1, GPIO.HIGH) time.sleep(0.000010) GPIO.output(self.TRIG1, GPIO.LOW) # following code detects the time duration for the echo pulse while GPIO.input(self.ECHO1) == 0: pulse_start = time.time() while GPIO.input(self.ECHO1) == 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start # distance calculation distance1 = pulse_duration * 17150 # round distance to two decimal points distance1 = round(distance1, 2) time.sleep(0.1) # ensure that sensor 1 is quiet # sensor 2 reading GPIO.output(self.TRIG2, GPIO.HIGH) time.sleep(0.000010) GPIO.output(self.TRIG2, GPIO.LOW) # following code detects the time duration for the echo pulse while GPIO.input(self.ECHO2) == 0: pulse_start = time.time() while GPIO.input(self.ECHO2) == 1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start # distance calculation distance2 = pulse_duration * 17150 # round distance to two decimal points distance2 = round(distance2, 2) time.sleep(0.1) # ensure that sensor 2 is quiet self.oa.setDistances(distance1, distance2) count0 = self.mcp.read_adc(0) # approximation given 1023 = 7.5V voltage = count0 / 100 self.control.find_and_set_new_active_behavior() print 'distance1 = ', distance1 print print 'distance2 = ', distance2 print print 'voltage = ', voltage print time.sleep(5)# instantiate an instance of testBBRbbr = testBBR()# run itbbr.run()

Chapter 11/thirdVehicle.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import breve
2+
3+
class Controller(breve.BraitenbergControl):
4+
def __init__(self):
5+
breve.BraitenbergControl.__init__(self)
6+
self.vehicle = None
7+
self.leftSensor = None
8+
self.rightSensor = None
9+
self.leftWheel = None
10+
self.rightWheel = None
11+
self.simSpeed = 0
12+
self.light = None
13+
Controller.init(self)
14+
15+
def init(self):
16+
self.n = 0
17+
while ( self.n < 10 ):
18+
breve.createInstances( breve.BraitenbergLight, 1 ).move( breve.vector( ( 20 * breve.breveInternalFunctionFinder.sin( self, ( ( self.n * 6.280000 ) / 10 ) ) ), 1, ( 20 * breve.breveInternalFunctionFinder.cos( self, ( ( self.n * 6.280000 ) / 10 ) ) ) ) )
19+
self.n = ( self.n + 1 )
20+
#self.light = breve.createInstances(breve.BraitenbergLight, 1)
21+
#self.light.move(breve.vector(10, 1, 0))
22+
self.vehicle = breve.createInstances(breve.BraitenbergVehicle,1)
23+
self.watch(self.vehicle)
24+
self.vehicle.move( breve.vector(0, 2, 18)) self.leftWheel = self.vehicle.addWheel(breve.vector(-0.500000,0,-1.500000)) self.rightWheel = self.vehicle.addWheel( breve.vector(-0.500000,0,1.500000)) self.leftWheel.setNaturalVelocity(0.000000) self.rightWheel.setNaturalVelocity(0.000000)
25+
self.rightSensor = self.vehicle.addSensor(breve.vector(2.000000, 0.400000, 1.500000)) self.leftSensor = self.vehicle.addSensor( breve.vector(2.000000, 0.400000, -1.500000 ) ) self.leftSensor.link(self.rightWheel) self.rightSensor.link(self.leftWheel) self.leftSensor.setBias(15.000000) self.rightSensor.setBias(15.000000)
26+
self.startTime = self.getRealTime()
27+
28+
def iterate(self):
29+
breve.BraitenbergControl.iterate(self)
30+
self.simSpeed = (self.getTime()/(self.getRealTime()- self.startTime)) print '''Simulation speed = %s''' % ( self.simSpeed )
31+
32+
breve.Controller = Controller
33+
34+
Controller()

0 commit comments

Comments
 (0)