Вы находитесь на странице: 1из 133

Natalie Downe [cs1njd@bath.ac.

uk]

Signed Declaration

Title:   Refinement of Reynolds' flocking rules in a distributed behavioural model
to better reflect the Semi­adversarial interaction between sheep and sheepdogs
Submitted by: Natalie Jane Downe

Copyright
Attention is drawn to the fact that copyright of this thesis rests with its author.
The Intellectual Property Rights of the products produced as part of the project
belong to the University of Bath (please see 
    http://
   www.bath.ac.uk
   /ordinances/#intelprop
   ).
This copy of the thesis has been supplied on condition that anyone who consults
it is understood to recognise that its copyright rests with its author and that no
quotation from the thesis and no information derived from it may be published
without the prior written consent of the author.

Declaration
This dissertation is submitted to the University of Bath in accordance with the
requirements of the degree of Bachelor of Science in the Department of Computer
Science.
No portion of the work in this dissertation has been submitted in support of an
application for any other degree or qualification of this or any other university or
institute of learning.
Except where specifically acknowledged, it is the work of the author.

Signed:                                                       

This thesis may be made available for consultation within the University Library
and   may   be   photocopied   or   lent   to   other   libraries   for   the   purposes   of
consultation.

Signed:                                                       

Signed Declaration Page 1 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Acknowledgements

Firstly   I   would   like   to   thank   my   project   supervisor   Dr.   Clare   Willis   for   the
invaluable help and guidance given throughout. I would also like to thank Aled
Owen for kindly allowing me to visit and interview him in the initial stages of this
project.
Thank you to everyone who proofread this dissertation and to those who helped
with my research  by completing questionnaires. Last, but not  least, a heartfelt
thanks to all my friends and family, who have helped support me through this
year. 

Acknowledgements Page 2 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Abstract

Nature   has   always   been   a   source   of   inspiration   and   intrigue   to   the   worlds   of
simulation, animation and modelling. This dissertation builds on the fundamental
work developed by as Craig Reynolds [1987 and 1999] in distributed behavioural
modelling   and   emergence   of   flocking   behaviour   through   three   simple   rules;  it
takes   a   look   at   the   relatively   under­studied   world   of   simulating   sheep   and
sheepdog   interaction.   This   project   attempts   to   answer   the   question   “how   can
previous work into the use of the distributed behavioural model with Reynolds'
three flocking rules  be refined further to adapt to the semi­adversarial [Hebert et
al   2003]   environment   with   sheep   and   sheepdogs”.   This   will   be   investigated
through   observation   in   the   field   and   through   qualitative   questionnaires,
interviews and critique of existing systems. This project develops the theories and
requirements underlying a simulation implemented using a multi agent system
consisting of both reactive and hybrid agent with shepherds as the primary users. 

Abstract Page 3 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Contents
Signed Declaration..................................................................................................1
Copyright............................................................................................................1
Declaration.........................................................................................................1
Acknowledgements.................................................................................................2
Abstract...................................................................................................................3
1. Introduction........................................................................................................8
1.1) Problem Description...................................................................................8
1.2) Aims............................................................................................................9
1.3) Project Framework....................................................................................10
Summary..........................................................................................................11
2. Background Literature......................................................................................12
Introduction.....................................................................................................12
2.1) History of Related Work in Computing.....................................................12
2.1.1) Reynolds and the three flocking rules...............................................12
2.1.2) Other Steering behaviour..................................................................13
2.1.3) History of Autonomous Agents.........................................................13
2.1.4) Approaches to Agent Composition....................................................14
2.2) Flocking as a Social Behaviour.................................................................14
2.4) Sheep and Sheepdog behaviour................................................................15
2.5) Comparison of Existing Systems...............................................................18
2.5.1) Reynolds' implementation of bird flocking.......................................18
2.5.2) Autonomous characters in Entertainment.........................................18
2.5.3) Similar modelling systems ...............................................................19
Summary..........................................................................................................20
3. Objectives and Requirements............................................................................21
Introduction.....................................................................................................21
3.1) General Objectives....................................................................................21
3.2) Scope........................................................................................................21
3.3) Requirements Gathering Process..............................................................22
3.4) Requirements Specification......................................................................24
3.4.1) Functional Requirements..................................................................24
3.4.2) Non­functional Requirements...........................................................25

Abstract Page 4 of 133
Natalie Downe [cs1njd@bath.ac.uk]

3.6) Test Plan...................................................................................................26
Summary..........................................................................................................27
4. Detailed Background Research.........................................................................28
Introduction.....................................................................................................28
4.1) Sheep Behaviour.......................................................................................28
4.1.1) Sheep at Rest....................................................................................28
4.1.2) Under 'Attack'....................................................................................28
4.1.3) Tentative Rest...................................................................................29
4.1.4) Dominant Sheep................................................................................29
4.2) Sheepdog Behaviour.................................................................................30
4.2.1) Taming the Predatory Instincts.........................................................30
4.2.2) Directing the dog..............................................................................30
4.3) Sheepdog Trials .......................................................................................31
4.3.1) The Trial Course................................................................................31
4.3.2) Trial Scoring......................................................................................32
4.3.3) Intended trial Structure.....................................................................32
4.3.4) Other points to note..........................................................................33
Summary..........................................................................................................33
5. Application of Research and Agent Design.......................................................34
Introduction.....................................................................................................34
5.1) Class Hierarchy.........................................................................................34
5.2) Detailed Sheep Agent Design....................................................................34
5.2.1) Considerations when designing sheep Agent....................................35
5.2.2) Sheep Agent Architecture..................................................................41
5.3) Detailed Sheepdog Agent Design..............................................................44
5.3.1) Commands from shepherd................................................................45
5.3.2) Sheepdog Agent Architecture............................................................46
Summary..........................................................................................................47
6. Implementation of Design.................................................................................48
Introduction.....................................................................................................48
6.1) Technology considerations.......................................................................48
6.1.1) Alternative options............................................................................48
6.1.2) Resulting Choice: Mason...................................................................50
6.2) Further Implementation Highlights..........................................................51
6.2.1) Interface design.................................................................................51

Abstract Page 5 of 133
Natalie Downe [cs1njd@bath.ac.uk]

6.2.2) GUI controller...................................................................................53
6.2.3) Flock model architecture...................................................................54
6.2.4) Animal Superclass.............................................................................56
6.2.5) Sheep Agent......................................................................................58
6.2.6) Sheepdog Agent................................................................................65
Summary..........................................................................................................65
7. Conclusion and Evaluation...............................................................................66
7.1) Conclusions drawn ...................................................................................66
7.2) Approach and Functional Evaluation........................................................68
7.2.1) Functional Evaluation.......................................................................68
7.2.2) Methodologies and Approach Evaluation..........................................69
7.2.3) Project Achievements........................................................................70
7.2.4) Personal Project Critique...................................................................70
7.3) Further Work: Building on this Project.....................................................70
7.3.1) Implementation aspects to be improved ..........................................71
7.3.2) Areas of further research...................................................................71
7.3.3) Future testing plans...........................................................................72
7.4) Final word.................................................................................................72
References and Bibliography ................................................................................73
Further Information: References......................................................................75
Image accreditation .........................................................................................76
Appendix A: Screen­shots.....................................................................................77
Screen­shot at Start.....................................................................................77
Screen­shot at time 11.................................................................................77
Screen­shot at time 19.................................................................................78
Screen­shot at time 45.................................................................................78
Appendix B: Further Information..........................................................................81
B1) Questionnaire............................................................................................81
B1.1)  email  sent to  working  sheepdog  mailing  list  and  the Border  Collie
interest list...................................................................................................81
B1.2) Responses...........................................................................................84
B2) Report from Field research .......................................................................93
B2.1) Introduction.......................................................................................93
B2.2 trialling vs. General shepherding.........................................................93
B2.3) Shedding in general shepherding.......................................................94

Abstract Page 6 of 133
Natalie Downe [cs1njd@bath.ac.uk]

B2.4) Training with 2 dogs..........................................................................95
B2.5) Importance of the shepherd ..............................................................95
B2.6) Issues when controlling the sheep.....................................................96
B2.7) Dominant sheep.................................................................................97
B2.8) sheepdogs and Training.....................................................................98
Notes............................................................................................................99
Appendix C: Source code....................................................................................100
C1) SheepFlockWithUI.java............................................................................100
C2) Flock.java.................................................................................................104
C3) Animal.java..............................................................................................112
C4) Sheep.java...............................................................................................116
C5) Dog.java...................................................................................................131

Abstract Page 7 of 133
Natalie Downe [cs1njd@bath.ac.uk]

1. Introduction

1.1) Problem Description


Nature   has   always   been   a   source   of   inspiration   and   intrigue   to   the   worlds   of
simulation, animation and modelling. No situation has captured the imagination
more so than that of the flocking of birds, schooling of fish and the herding of
land mammals. 
In comparison to the others one particularly interesting area has not been studied
in nearly as much detail as it warrants  ­ the flocking of sheep and other land
mammals. 
This project sets out to virtually replicate the collective social behaviour of sheep
and explore  the relationship   of  the  flock  to  a  sheepdog.  The overall  aim  is  to
generate a realistic simulation representing a sheepdog trial.
This   problem   is   particularly   interesting   when   the   aspect   of   external   control   is
considered. The dog, although a predator to the sheep, in fact builds up an almost
inexplicable   'working   relationship'   with   the   flock,   with   the   sheep   occasionally
feeling relaxed enough to feed on grass while the dog is still in relatively close
proximity. 
Specifically the relationship between a dog and its flock can be defined as semi­
adversarial [Hebert et al 2003]; this is the situation where one party contributes
no   action   either   to   hinder   or   help   the   other's   intentions.   An   example   of   an
opposite   (adversarial)   situation   would   be   the   traditional   predator   prey
simulation,   where   the   prey   actively   avoid   the   predator   in   the   interest   of   self
preservation. 
Before   the   theories   on   semi   adversarial   behaviour   can   be   developed,   it   is
important for this study  to model the flocking of sheep. The most  noteworthy
research in the area of flocking was from Reynolds [1987] who developed the
idea of emergent behaviour in groups.
The emergent behaviour theory is based around the idea that simple rules applied
to the individual can, when combined with other individuals following their own
or   the   same   set,   result   in   complex   group   behaviour.   It   has   been   said   that
emergence can appear like “structure emerging from apparent chaos” [Johnson
2001].
Reynolds   [1987]   devised   three   very   simple   rules   that   when   applied   to   a
distributed system of agents will result in flock­like tendencies. The three main
flocking rules are:
Cohesion  –  Each   individual   analyses   the  average   position  of   its   neighbours
and calculates the vector needed to move to that point from where it is now,
this results in the flock staying together.

1. Introduction Page 8 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Separation   –  The   preservation   of   personal   space   of   the   individual   is


maintained by calculating each unit vector back from every other individual.
The sum of these unit vectors is the resulting force from separation.
Alignment – Ensuring the flock travels in the same direction and at the same
speed,   the   direction   vectors   of   each   of   the   surrounding   neighbours   are
averaged to obtain a general flock direction.  
Once   the   resulting   forces   from   each   of   the   rules   has   been   obtained,   each   is
multiplied by a weighting that affects the behaviour of the flock.
The above flocking rules have been almost exhaustively extrapolated into various
programming languages for use with the simulation of birds and schools of fish.
Quite naturally these animals have comparatively different flocking behaviours to
land mammals such as sheep. 
In addition to this, with the introduction of the sheepdog, a completely different
scenario arises; the flocking rules are still applicable, but they now need to be
combined with other composite behaviours on the behalf of both the sheep and
the sheepdog. As mentioned earlier this behaviour is very different to that found
in traditional predator­prey simulations.
Being   a   relatively   unexplored   subject,   there   are   few   attempts   to   solve   this   or
similar problems. The one system to have come close, was an attempt by Jerrolyn
A. Hebert, Michael V. Doran and Charles H. Brown [2003] at the creation of a
robotic 'sheepdog' to herd ducks. The main aim of this experiment was to produce
a robotic sheepdog which would be capable of acting independently to bring the
sheep around. In addition to this the project aimed to produce the groundwork
for   their   later   sheepdog   project.   This   meant   the   project   covers   none   of   the
unnecessary behaviour on behalf of the dog.
There are a few other simulations produced by similar projects, these, as well as
various   flocking   approaches,   are   covered   in   more   detail   in   the   Background
Literature section [chapter 2].

1.2) Aims
The primary aim of this project is to investigate the specifics needed to implement
Reynolds' [1987] algorithm with regards to Sheep and sheepdogs. In the process
of investigation a realistic graphical representation will be created, with a view to
modelling a sheepdog trial. The physical result of the system will be determined
in more detail in the requirements gathering section. 
This project will truly test the authors abilities, as prior to the beginning of the
project she was unaware of any of the computational theories related to flocking,
nor the complexities of working dogs with sheep. Therefore an incidental result of
the project, the author hopes to increase her domain knowledge and abilities with
the technologies used.

1. Introduction Page 9 of 133
Natalie Downe [cs1njd@bath.ac.uk]

1.3) Project Framework


This project is structured to facilitate understanding of the concepts involved and
to help with traceability of any conclusions and requirements determined.
The  framework for the document to follow includes:
2. Background Literature – This chapter forms a basis for all that is to come, it
looks at the history of related work in computing as well as the more domain
specific issues regarding sheep and sheepdogs. A critical appraisal of previous
systems is performed with an eye to elicit further requirements based on their
shortcomings.  The chapter then relates the research and background reading
to this project and concludes.
3. Objectives and Requirements –  The requirements gathering stage is vital to
ensure that the system is going to suit the needs of the users. This  chapter
looks at the general objectives of the project, the scope then analyses various
methods used in gathering requirements for this project include a field trip to
Wales [see Appendix B2] Questionnaires and interviews as well as analysis of
existing systems. The requirements are then analysed in detail and listed in a
requirements specification
4. Detailed Background Research – This chapter looks at in detail at the subject
area  that  was touched  upon in  the literature review.  Further information  is
researched through the literature covered in chapter 2 and comparisons  are
made to observation.
5. Application of Research and Agent Design – An overall structure design for
class   hierarchy   is   presented.   A   detailed   look   at   the   requirements   follow,   in
which the design considerations for each agent are looked at and and planed
out in detail. The mathematical grounding for the project is then analysed, and
the agent design is formed.
6. Implementation of Design – The design and Implementation section analysis
the   technological   choices   for   implementation   and   chooses   the   most
appropriate   according   to   various   criteria,  then   follows   an   Implementation
Walk­through where all the important parts of the implementation are covered
(see the Source code in Appendix C) Results of testing are looked at.
7. Conclusion and Evaluation –  The methods and processes of the project are
summarised and the findings presented. An evaluation of the project precedes
details of further work that could be accomplished building on the findings of
this Dissertation.
Appendix A – Screen shots of resulting system
Appendix B: 
1. B1 –  Questionnaires sent to the working sheepdog mailing list and the
Border collie general interest mailing list.
2. B2 –  Report from Interview and field trip to visit Aled Owen in North

1. Introduction Page 10 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Wales [November 2004]
Appendix C – Source code

Summary
In this chapter we have covered the description of the problem to be solved and
the   aims   the   project   hopes   to   achieve.   The   Document   will   now   follow   the
framework set out above and continue with the project's Background research.
In the next chapter we look at the groundwork that will form the foundations for
study and perform a critical analysis of similar work in this area.

1. Introduction Page 11 of 133
Natalie Downe [cs1njd@bath.ac.uk]

2. Background Literature

Introduction
The   social   formations   of   animals   such   as   fish,   land   mammals   and   crowds   of
people   have   long   been   a   common   subject   computer   modelling.   Capturing   this
behaviour fully involves information from a wide­ranging selection of disciplines
such as: Biology, Zoology Robotics, Physics, Artificial Intelligence and Computer
Science itself.
Animals are said to be in a flock or herd with one another when their movements
are   directly   influenced   by   the   majority   of   their   neighbours   and   not   through
planning or coordination on behalf of the individual.

2.1) History of Related Work in Computing


2.1.1) Reynolds and the three flocking rules
The main pioneering effort towards the modelling and simulation of flocks was by
Craig   Reynolds,   in   a   paper   [Reynolds   1987]   presented   at   the   SIGGRAPH   87
conference.
This   work   differed   from   previous   research   in   the   field,   in   that   instead   of
attempting   to   simulate   the   whole   flock   and   every   action   therein,   each   flock
member   was   provided   with   a   simple   set   of   instructions.   Based   on   these
instructions, the individual flock members act independently according to their
unique view on the world.
Reynolds [1987] defines the composition of an Autonomous Character well in his
paper.   An   Autonomous   Character   is   a   “type   of   autonomous   agent   for   use   in
computer animation and interactive media such as games and Virtual reality …
autonomous characters are sometimes called non­player characters”.
The paper then goes on to split the distributed behavioural model of these agents
into three separate layers 
1.Action Selection – the strategy, goals and planning part of behaviour,
the motivation and the whys of the agent behaviour. 
2.Steering Behaviour – The dividing of the goal into sub goals that the
agent is trying to achieve, the what.
3.Locomotion – how the agent moves, whether it is physical in the case
of a robot, or virtual for computer graphics.
The   decomposition   of   the   main   goal   into   sub   goals   forms   a   number   of
manageable objectives that can be completed using simple behavioural rules, e.g.

2. Background Literature Page 12 of 133
Natalie Downe [cs1njd@bath.ac.uk]

avoid objects, find food etc. 
The   simple   rules   allowing   for   interaction   with   other   members   of   the   flock
following   principles   of  Collision   Avoidance,  Velocity  matching  and  Flock
centring  otherwise referred to as  Avoidance,  Separation  and  Cohesion. These
combine   together   with   other   flock   members   to   produce   complex   emergent
behaviour: Flocking [Reynolds 1987].

2.1.2) Other Steering behaviour


Other   steering   behaviour   explained   in   the   Reynolds   Steering   behaviour   paper
[1999] include:
Seek and Flee – to steer toward or away from a stationary target.
Pursuit and Evasion – identical to the above but the target is moving,
a certain amount of prediction is required.
Offset pursuit – Like a flyby, where the aim is not to reach the target
but to go close.
Arrival – slowing down to approach the target far away.
Obstacle  avoidance  –  keeps   an  eye  out   on   the   objects   in  its   view
point (using bounding spheres for irregular shapes) adjusting the path
to avoid collisions
Wander  –  A  way   of   generating   random   steering   similar  to   explore
and forage, used to create the realism of random movement
Path following – moving along a path, relating to wall following
Flow field following – to align the direction of individual characters.
Unaligned   collision   avoidance   –  keeping   characters   moving
arbitrarily   away   from   each   other,   a   kind   of   pre­emptive   collision
avoidance.
Choosing the behaviour to perform can be firstly either deliberative or reactive,
i.e. the agent can react instinctively or deliberately (calculating consequences).
Secondly the forces from the various calculations from the agent can either be
prioritised to calculate overall driving force, or summed with a weighting.

2.1.3) History of Autonomous Agents


Autonomous Agents by name may be a relatively new concept to the world of
computer science however, as Reynolds [1987] points out there is research work
from other fields relating indirectly, as far back as the 1940’s and 1950’s. 
Although agents are related to many areas, such as studies into Social Sciences
Economics or Game theory, the study of Multi­agent systems does not fit nicely
into any of these and many believe it belongs to its own independent discipline
[Wooldridge 1966].

2. Background Literature Page 13 of 133
Natalie Downe [cs1njd@bath.ac.uk]

2.1.4) Approaches to Agent Composition


Similar agent composition techniques, as used by Reynolds [1997] but to a much
more   complex   and   integrated   level,   have   been   used   and   developed   by   Steve
Grand   [2001]   in  the   implementation   of   the   computer   game   'Creatures'.   These
Creatures function independently situated in an environment, each creature has
within them a two level system to produce their behaviour. Grand asserts that
although the perception impulses are not real life, the reactions to them are. 
The two level system involves having both a direct method of computation (the
neurones in the 'creatures' brain, related to reasoning) and an indirect / diffused
one  (with  regards  to   the  actual  biochemistry  and instinct).   Programming  each
individual agent this way ensures that they are acting to their own rules, as a
result emergent behaviour can even be seen here. Grand's method also takes into
account evolution in the chemical processes. 
As a basis system for development in this project this is perhaps more complex
than   is   necessary   to   simulate   sheep   and   sheepdog   behaviour.   However   if   the
system was implemented this way it would be a relatively simple process to then
bring in supplementary information, such as personality of the sheep and dog or
more complex elements like the weather, and make them a fundamental part of
the system.
There are various different other ways of representing the Sheep and sheepdogs
in representations such as Reactive and Hybrid Agents, these will be discussed in
more detail in the Design and Implementation section.

2.2) Flocking as a Social Behaviour


Flocks are mainly formed from selfish motives, an individuals self preservation
instinct   is,   after   all,   what   keeps   it   alive   and   allows   it   to   progress   in   the
reproductive   cycle.     Evolution   has   worked   this   way   for   longer   than   humanly
possible to find out. We know that flocks work as a self preservation mechanism
for the survival of the race as a whole by the pure fact that the race of whichever
flocking animals we are looking at are all living and the race as a whole is not
dwindling slowly in numbers.
Self defence mechanisms of animals are not always as well designed however. As
an aside,  the Tennessee Fainting Goat [IFGA 1999] has been so selectively bred
from a very small number of ancestors, it has now developed a genetic problem
that has led to it being used to protect flocks of other livestock such as sheep from
predators such as wolves and foxes. 
The Goat, when frightened has the unfortunate disorder that forces its muscles to
relax  suddenly,   causing  it   to  fall  over.   When  put   in  a  flock  of   sheep   or  other
cattle, when danger comes the goat will 'faint' and be eaten by the predator hence
saving the rest of the flock by giving them enough time to escape.
Without the use of the Tennessee Fainting Goat however, flocks are still beneficial

2. Background Literature Page 14 of 133
Natalie Downe [cs1njd@bath.ac.uk]

to the individual flock member. Wikipedia [Wikipedia: Flock 2005] states that the
self   preservation   technique   for   flock   members   works   through   the   theory   of
dilution; even if the predator attacks the flock, then because there are so many
individuals, the victim is less likely to be any one animal in particular.
The nature and formation of bird flocks has been studied in great detail, it was
after all the inspiration for the Boids ('Birds' said in a Texan accent). Birds have
additional reasons for flocking other than self preservation. 
Birds   that   migrate   to   warmer   climes   in   the   colder
months   of   the   year   travel   as   a   group,   generally
forming   the   commonly   seen   V   formation.   There   are
many speculations as to why birds form such a pattern
when flying [Andersson et al. 2003]
Insects   again   have   their   own   reasons   for   forming
flocks   or   swarms.   In   insect   colonies   and   perhaps   in
other   groups   of   social   animals   as   well,   there   are   a
group of animals that belong to a specific group with a predetermined set of tasks
it has to perform. 
Ants in particular have this clear division of labour and task allocation [Bonabeau
et al 1999], each individual animal does not know why it does what it does, the
task decided is decided for the duration of that creatures life by the queen, the
culmination of what we commonly think of as the 'hive mind'. 
The queen organises and selects individuals for the different tasks that have then
to last them the duration of their lives. The use of these specific roles is easily
seen when the complex  emergent  behaviour  of  activities  such as  nest building
foraging and the task of finding collecting and transporting food.
Land   mammals   including   livestock   and   wild   animals   such   as   the   Ox   or   the
Gazelle, in comparison to the Swarm  intelligence of the insect world, lack the
structure and role refinement that Ants or Bees have. Instead the primary reason
for the group dynamics is now to ensure the continuation of the species. 
Should  there be  an  attack  from   a predator,  the  flagging  creatures  such as  the
elderly or infirm get eaten. This ensures that the healthy creatures survive and the
race continues to prosper.
Sheep, having been bred not to fear, but to respect the sheepdogs' control, have
led to the refinement of their flocking behaviour to the point where they can be
steered for direction without causing them to run away in fear of their lives. This
is   evidently   a   very   unique   and   specialised   form   of   flocking   worthy   of   further
investigation.

2.4) Sheep and Sheepdog behaviour


Sheep   and   sheepdog   interaction   represents   an   interesting   yet   so   far   relatively
untapped field of study. There has however, been some research into the use of

2. Background Literature Page 15 of 133
Natalie Downe [cs1njd@bath.ac.uk]

robotics and animal behaviour [Hebert et al. 2003] in this area, where the theory
of semi­adversarial behaviour was first developed. 
The   aforementioned   paper   discusses   the   robotic   implementation   of   Reynolds’
“Boids” [1987] using sheep as the subject vehicles. The paper states that it differs
from   Reynolds   by   placing   the   simulation   in   a   Semi   ­Adversarial   environment
[Hebert et al. 2003].
A   Semi­Adversarial   environment   involves   at   least   two   main   groups   of   agents,
where one group (in this case, the sheep) neither hinders nor assists the other
group   with   their   goals.   Had   this   been   a   traditional   Predator­Prey   behaviour
environment (though perhaps with different animals than sheep as the prey), it
could   be   considered   to   be   adversarial,   the   prey   do   their   best   to   hinder   the
predator from catching them. 
In addition to the environment being Semi­Adversarial, it can also be described as
inaccessible,   non­deterministic,   continuous,   and   dynamic   [Wooldridge   1966].
This   meaning   that   any   particular   sheep   does   not   know   everything   about   its
counterparts, no set action has a determinable outcome, there are an unlimited
number   of   actions   and   results   of   the   environment   and   the   environment   could
possibly be changed by elements outside the dog or sheep’s control, e.g. rain or
one of the sheep getting nervous scattering etc.
The traditional predator / prey environment has been well studied, though this
situation does not directly influence this project as it is set in the semi­adversarial
environment   of   sheepdog   trialling,   studies   in   this   area   will   still   be   taken   into
consideration.
The studies undertaken in the Hebert et al.
paper   [2003]   do   not   fully   cover   the
interaction   between   sheep   and   sheepdog,
partly   due   to   using   a   ‘predator’   with   the
intention   of   eating   the   sheep.   The
behavioural priorities do not illustrate the
comfort   sheep   can   feel   around   a   dog,
causing   them   to   occasionally   stop   and
forage   for   food,   this   they   would   not   do
when being hunted for real. 
In avoiding predators this project discusses
a   flight   zone   [see   below,   figures   1­3],   any   predators   outside   which   are   not
deemed to be directly dangerous. This information was confirmed in an informal
interview with Mr Aled Owen [Owen 2004].

To understand this, however, we need to realise that there are two main types of
sheep: Heavy sheep and Light sheep [Owen 2004] . Heavy sheep have evolved on
the lowland planes and will take a lot more encouragement from a dog before
they   move   (a   flight­zone   distance   of   about   10   yards).   In   contrast   to   this   the

2. Background Literature Page 16 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Highland (light) sheep have a flight zone of about 30 yards. 
In the majority of cases the sheep will move if the predator gets within this flight
zone. However, heavy sheep are less inclined to move and have the tendency to
turn and  face   the  predator  to   stare  it   out  instead.   Light  sheep   are a  lot  more
skittish and will only turn to face the predator if they have become tired or out of
breath. Herding a mother sheep in the flock also increases the likelihood that it
will turn and defend the flock rather than let the predator reach its offspring. 
The position of the dog in relation to the sheep’s flight zone will determine the
reaction of the sheep. There is an area within the zone in which the dog can enter
to drive the sheep forward [Figure 1], without them panicking and fleeing into
seemingly   random   directions,   or   turning   to   stand   up   to   the   dog   [Figure   2].
However, it has to be noted that if the dog does not enter the flight zone at all,
the sheep will feel no threat and proceed to graze almost as normal [figure 3]

Dog

Dog

Dog
Figure 1 Figure 3

Figure 2

The overall flight zone of a flock is the inner boundary to the area in which all the
neighbouring sheep feel safe, if one sheep is alerted to the danger of a predator,
as with ants [Bonabeau E et al. 1999] through use of pheromones the whole flock
becomes aware [Delgado­Mata 2004]. The outer circle of the flight zone indicates
the fading of the sphere of influence. 
This project will concentrate on the use of Reynolds' [1987] flocking algorithms

2. Background Literature Page 17 of 133
Natalie Downe [cs1njd@bath.ac.uk]

in the research area of sheep and how they can be altered to better reflect real
life. Further analysis continues throughout the dissertation.

2.5) Comparison of Existing Systems


2.5.1) Reynolds' implementation of bird flocking
Reynolds' rules for flocking will form the groundwork for this project, however,
the main criticism of the pure algorithm devised by Reynolds with regards to its
usefulness   in   this   project   is   that   being   designed   for   birds,   there   will   be   a
significant amount of alteration needed to apply it to sheep. In the basic flocking
algorithm there is also no consideration of the predator prey situation. 
Another   consideration   to   add   to   this   is   that   other   than   through   the   'random'
element   and   the   adjusting   to   fit   with   the   neighbours,   there   is   no   method   for
changing the flocking parameters. With sheep their speed and cohesion will be
considerably   more   when   they   are   under   threat   than   when   they   are   merely
grazing.
In addition to implementing the main flocking rules set forth in the 1987 paper,
Reynolds   put   forth   further   theories   on   the   use   of   spatial   reasoning   in   agents
[1999]. These again cannot be implemented directly but through careful analysis
(to be discussed in the design and implementation section) can be specialised for
the semi adversarial situation with sheep.
There have been many direct and partial implementations of the Boids algorithm
designed for both birds and fish, but scarce few have looked at its application to
land mammals.

2.5.2) Autonomous characters in Entertainment


Some of the most recent and by far the most advanced application of the flocking
ideals is to be seen in the world of film and computer games.
The most advanced work done on emergent behaviour to date was in the film
'Lord of The Rings' [Koeppel 2001] where, for the scenes of hundreds of Orc's
fighting   in   'Helms   Deep'   the   film   animation   team   developed   their   own
programming language, Massive [2001] [Merrill 2004] to model the behaviour
and   animation   of   the   creatures   which   were   in   fact   developed   as   autonomous
agents. 
The justification given by the team on the Lord of The Rings film for developing
individual   actions   for  each   Orc  was   that   it   would   eliminate   the   'disconcerting'
effect that comes from copy and pasting extras onto the scene, as in 'Gladiator'
[Koeppel 2001].
One   of   the   offsets   of   using   emergent   behaviour   is   just   that,   the   behaviour   is
emerging   and   it   can   sometimes   be   impossible   to   predict   the   exact   result   of   a
situation. Knoeppel observers “Jackson and Regelous watched as several thousand

2. Background Literature Page 18 of 133
Natalie Downe [cs1njd@bath.ac.uk]

characters   fought   like   hell   while,   in   the   background,   a   small   contingent   of


combatants seemed to think better of it and run away. They weren't programmed
to do this. It just happened. "It was spooky," Jackson said”.
Other films  to  achieve realistic or  semi  realistic  results  using the  properties  of
emergent   behaviour   and   in   some   cases   flocking   were  the   penguins   in  batman
returns 1992, and the Wilder beasts in the Lion King 1994.
Flocking is an important area of research due to its wide ranging applications,
especially   in   replicating   realism   the   film   and   entertainment   industry.   These
applications   mentioned   above   however   impressive   are   not   suitable   application
environments   for   a   basis   of   this   project   as   a   large   part   of   their   use   is   in   the
graphical area and as such prove too complex for the application needed here.
In  addition   to   the   close   implementation   of   Reynolds'   [1987]   flocking   method,
there  is a  computer  game  implemented  in flash  [Lewis  2004] the most  recent
version of which can be found at http://www.david­lewis.com/sg3/index.php.
This simulation is provided purely as a game and is not intended to accurately
simulate   sheep   movements.   The   current
version   builds   upon   the   original   [Lewis
2001]   where   the   sheep   had   no   flocking
tendencies   and   would   purely   avoid   the
mouse cursor acting as a sheepdog.
The   new   version   [Image   2.3a]   has   the
sheep flocking when at rest and not under
the influence of the dog.
Sheep   however,   when   left   alone   and   not
under   threat   do   not   exhibit   flocking
behaviours   as   strongly   as   when   chased
Image 2.3a:   [See Appendix B2]. A very loose flock is
http://www.david­lewis.com/sg3/index.php [David Lewis]
formed   when   the   sheep   are   purely
grazing   and   the   real   flocking   tendencies   appear   when   threatened.   In   this
simulation   the   sheep   also   form   too   close   a   flock   when   left   alone,   there   is   no
apparent Separation force leaving the opportunity open for the sheep to appear
'on top of each other'.

2.5.3) Similar modelling systems


The closest simulation related to aims of this project can be found in the Robotic
sheepdog project [Hebert et al 2003]. A simulation was built of the sheep and
sheepdog in order to then design a robotic sheepdog. Using a simulation first to
ensure that the program controlling the robotic dog would be able to control the
sheep like a real sheepdog. 
Hebert et al [2003] examines the priorities for a herd of sheep and concludes the
following:

2. Background Literature Page 19 of 133
Natalie Downe [cs1njd@bath.ac.uk]

1. Move away from predators  – to “run away from any dogs” maintaining
the sheep’s own personal safety.
2. Stay   in   the   herd  –  Once   the   presence   of   the   dog   as   a   threat   has   been
eliminated the sheep will then check that they are in a herd.
3. Foraging instinct  ­ If the sheep is safe from predators and within the herd,
then it is free to forage for grass
However   through   observation   it   has   been   noticed   that   these   seemingly   simple
priorities   may   well   be   more   complex.   This   will   be   explored   further   in   the
Requirements   gathering   and   Design   sections.   Another   point   to   note   about   the
Robotic sheepdog project Hebert et al [2003] is that it was actually modelled on
the flocking behaviour of ducks. It was mentioned in interview with Aled Owen
[Owen 2004] that ducks flock much differently to sheep and that training a dog
to flock ducks can disadvantage it when trying to flock sheep. 
The   publication   of   Hebert   et   al.   [2003]   begins   to   illustrate   this   link   between
reality   and   simulation   with   respect   to   sheep.   Hebert   et   al   aims   to   produce
simulation of sheep and sheepdogs; however their main direction is toward the
use of physical robots  and  the furtherance of knowledge in robotics.
One last system that was investigated implied another untapped research area. A
video   of   a   welsh   sheepdog   trial   [S4C   2004]   was   kindly   sent   by   one   of   the
shepherds   who   responded   to   the   questionnaires   [Appendix   B1.2.2].   In   this
program a 'simulation' was used as a visual aid to show what the sheepdog should
be ideally doing throughout the particular trial course. 
The system was not so much of a simulation of the trial as the sheep exhibited no
flocking behaviour and it had the feel that it was animated and not generated by
any   sort   of   distributed   behaviour   model.   However   this   does   reveal   another
potential niche area where such a system as the one planned could be used.

Summary
There are many ideas that can be built upon from the results of previous work in
related areas, having reviewed the main background material this project intends
to use a distributed behavioural model together with the flocking rules from Craig
Reynolds' paper [1987]. 
This information will be combined with personal observations in Wales [Appendix
B2] of sheep,  how they move together and how they interact with sheepdogs,
together with the insights gained from 'A way of life', a book by H Glyn Jones and
Barbara   Collins   [1987]   to   obtain   a   realistic   representation   of   Sheep   and
sheepdogs. Further in­depth study of the relation between real life and literature
will be explored in the requirements gathering stage of the project and expanded
upon in the Design and Implementation section.

2. Background Literature Page 20 of 133
Natalie Downe [cs1njd@bath.ac.uk]

3. Objectives and Requirements

Introduction
In the last chapter we covered the theoretical groundwork for this project, the
history of the understanding in flocking, some of its application toward sheep and
sheepdogs   as   well   as   the   uses   in   the   Computer   Science   and   Entertainment
industries.
Having   also   looked   at   previous   systems   and   ascertained   their   strengths'   and
weaknesses' we can better formulate a set of requirements for a system that will
build upon these and further the overall domain understanding.

3.1) General Objectives


The primary aim of the project is to investigate how the Reynolds [1987] flocking
algorithms   can   be   altered   to   reflect   the   controlled   semi­adversarial   controlled
predator prey environment of the interaction between sheep and sheepdogs. 
By building on the prior research from Reynolds and others, this project hopes to
develop   their  theories  and   investigate   the   complex   behaviour   surrounding
sheepdogs and their ability  to limit  their natural predator instincts in order to
control a flock of sheep to the will of a shepherd.
However, before the system can be developed, it is necessary to investigate the
various  technological  foundations  of the theory.  Any technological  solution  will
need to facilitate the use of rapid prototyping and the ability to produce a project
that is easily deployable.
The   physical   result   of   this   project   will   be   to   produce   a   realistic   graphical
representation   of   sheep   and   their   interaction   with   sheepdogs   using   rules   for
emergent behaviour. 

3.2) Scope
Throughout this Dissertation a number of assumptions have been made. Unless
otherwise stated, the type of sheep investigated will be female Hill sheep only and
all sheepdogs will be Border Collies.
The physical  influence of the shepherd is  deemed out of scope.  Therefore any
trial element where body language from the shepherd would have been given to a
sheepdog   will   also   be   out   of   scope   for   this   project.   This   includes   Penning
Shedding and Singling. 
There are many factors that affect the flocking nature of the sheep, such things as
the specific breed of sheep, the weather, length of fleece and the season, not to

3. Objectives and Requirements Page 21 of 133
Natalie Downe [cs1njd@bath.ac.uk]

mention nerves and personality of all agents involved, the sheep, sheepdog and
shepherd  included; all these are out  of  scope  for  this  project.  The doggedness
(experience of the sheep with the course) is also not considered. Dogs may not
grip the sheep as is decreed for sheepdog trials [Appendix B2]

3.3) Requirements Gathering Process


The initial stages of the requirements gathering process looked at similar systems
see how they could be improved [refer back to section 2.5]. Through analysing
these   alternative   solutions,   their   strengths   and   weaknesses   and   where   in   the
domain   these   systems   were   positioned,   it   was   possible   to   observe   areas   that
needed further development.
In conclusion to the analysis of currently existing systems it would appear that
there is a gap in the simulation market in the following areas:
1. Programs   where   the   simulation   reflects   fully   the   semi­adversarial
situation   with   sheepdogs,   the   research   in   predator   prey   environments
focus on survival and the prey try their best to hinder the hunt from the
predators.
2. Simulations where the dog can be controlled in a similar way to real life.
This should be similar with the exception that commands will be given
through a program interface instead of whistles and body language in the
field.
3. None   of   the   simulations   around   aim   their   target   users   at   shepherds,
presently all the simulations available exist purely for technical interest
and advancement in the knowledge base of computer agents and artificial
intelligence.
The main technique used to ascertain the requirements  for this  project  was  to
adopt a user­centred approach [Preece 2002]. This involved contacting potential
users early on and keeping them involved with the design process.
Early on in the project the author contacted a world champion shepherd, Mr Aled
Owen,   who   was   kindly   allowed   for   a   days   research   field   trip.   For   a   detailed
account of the results of the interviews and ethnographic observations please take
a moment to consult Appendix B2.
A greater insight to the realism needed in the simulation was gained through this
study, allowing for further alteration and refinement of the established flocking
rules from Reynolds. Aled Owen mentioned that the use of system such as the one
in development would be useful as a training tool or as a fun demonstration in
visitors   to   his   shepherd   training   centre   [http://www.aled­owen­
sheepdogs.co.uk/].
Another step in the analysis of requirements from the user­centric point of view
was to analyse what shepherds thought they could gain from the intended system
and to refine the system requirements from the results.

3. Objectives and Requirements Page 22 of 133
Natalie Downe [cs1njd@bath.ac.uk]

The Questionnaire in Appendix B1 was sent to the working sheepdog mailing list
and the border collie general interest list. Nine responses were forthcoming, and
it was from this that the following could be determined:
The majority of respondents stated that they would find such a system
useful as a demo to show to friends and family if it was realistic. The
primary   justification   for   this   was   that   it   would   be   a   good   way   of
showing   those   who   had   never   been,   what   trialling   was   about   as   it
alleviates   the   problem   of   bad   weather.   It   is   preferable   to   attempt
understanding   of   trial   specifics   indoors   in   the   warm   as   opposed   to
outside in gale force winds with bad visibility [B1.2.6) response Six].
One questionnaire response [B1.2.6) response Six] suggested that such
a a simulation would be of use to recruit young shepherds into trialling. 
It was mentioned that depending on the quality of the resulting system
of this project, it could be used in collaboration with the International
sheepdog   Society   [IDSS]   as   a   training   aid   for   young   shepherds.   The
majority of respondents had used videos, books or interactive media of
some sort to assist learning. This implies that there my well be a niece
for a training system of the sort proposed.
Other suggested uses included a visual guide to enhance the theory and
reinforce concepts from books on the subject, a tool to get the basics of
trialling if the user already had prior experience of working a dog as
well as the use on a hand­held device for training 'in the field' so to
speak.
Realism   was   considered   a   high   priority   by   those   that   responded,   the
system   would   be   of   little   use   to   them   if   they   were   not   convinced   it
represented sheep and sheepdogs.
Only   one   respondent   said   that   the   system   would   be   of   little   use   in
training people intending to complete in sheepdog trials. respondent Six
stated   that   the   weather   and   other   factors   such   as   nerves   were   too
unpredictable   to  model   effectively   as   this  was   what   made   every  trial
different.
There was also concern [B1.2.9) response Nine] that the system would
not   reach   an   older   and   more   rural   population   because   the   usability
would be too difficult.
Taking   these   considerations   on   board   the   primary   aim   now   is   to   ensure   the
system portrays an accurate representation. Over the forthcoming sections of this
dissertation,   investigations   will   be   made   into   the   movements   and   behavioural
patterns of sheep with the intention  of  analysing the changes and refinements
that need to be made to be basic flocking algorithm for it to be deemed realistic
by the shepherds who deal with sheep on a day to day basis. 

3. Objectives and Requirements Page 23 of 133
Natalie Downe [cs1njd@bath.ac.uk]

3.4) Requirements Specification


Using   all   the   information   gathered   to   date,   from   the   above   requirements
gathering and through an intensive literature review of the existing research in
the area it is possible to develop a list of requirements for a system. 
These requirements are analysed in more detail in chapters 4 and 5.

3.4.1) Functional Requirements


1 Show a visual simulation of the different agents.
 1.1 It should be possible to view the simulation in 'real time' on the screen
 1.2 The individual sheep should be recognisably different to the dog agent.
 1.3 It should be possible to see the direction of each individual agent
 1.4 The speed of the agent should be recognisable by the magnitude (length)
of its direction vector.

2 Realistic Sheep Behaviour


 2.1 Sheep flocking behaviour ­ Model the behaviour of a sheep flock through
flocking rules applied to all individual sheep agents (Distributed behaviour
model)   –   Using   Reynolds   [1987]   rules   and   observation   information
[Appendix B2]
 2.1.1 Cohesion
 2.1.2 Alignment
 2.1.3 Separation
 2.1.4 Random – this has been added into the other three rules to cover for
all the elements out of scope that can affect the sheep behaviour, such as
weather and nerves.
 2.2 Every sheep should have a sphere around them, events in which, they are
influenced by, the 'flight zone'
 2.3 Model   the   sheep  behaviour  with   respect   to   the   sheepdog   (for   a   more
detailed   look   at   this   requirement   set   please   refer   to   the   Subsumption
architecture situated in section 5.2.2] 
 2.3.1 Dog avoidance ­  The sheep should, if a dog is present in their flight
zone, move away from the dog.
 2.3.2 Tentative rest state ­ Model the behaviour when there was a previous
threat and it has been removed.
 2.3.2.1 The sheep should first continue on its current momentum and
slow down gradually if there is still no sheepdog threat.

3. Objectives and Requirements Page 24 of 133
Natalie Downe [cs1njd@bath.ac.uk]

 2.3.2.2 After slowing down gradually the the sheep should wait around
for either the dogs next move or to determine the coast is clear.
 2.3.2.3 Once   assured   that   the   surroundings   are   safe,   the   sheep   then
begins its default foraging pattern [SRC 2004].
 2.3.3 Recreate   the   situation   brought   about   through  pheromones  in   the
sheep when invoked through fear. Other sheep should 'know' if a sheep
in their neighbourhood detects a dog.
 2.4 Model the behaviour of sheep when there is currently no threat. The sheep
should   Increase   their   separation   and   decrease   alignment   and   cohesion,
randomness will also increase as now the sheep is foraging for food.
 2.5 The simulation should also model the dominant sheep theory [Cobb 2005.
The scope of this project only covers female sheep, however as has been
determined, motherhood brings out a rebellious streak in the nature of an
otherwise calm ewe.

3 Realistically Model the behaviour of a sheepdog


 3.1 Take user input as to the intended plan for the dog, e.g. come­bye etc.. To
be   an   accurate   simulation   of   this   however,   the   dog   will   need   to   be
controlled in a similar way to how it would in real life. This means in turn
that there will be some level of unpredictability in the relationship between
user   input   in   the   form   of   commands   to   the   dog   and   the   actions   taken
thereafter depending on the experience of the dog.
 3.2 The dog should be able to interpret if the sheep are moving in the right
direction and adjust course appropriately.
 3.3 The dog should be able to determine if a sheep is dominant standing up to
the dogs authority, and choose from a number of scenarios that will deal
with such a situation
 3.4 The dog  should  be able  to  react  to  general changes  on the part  of the
sheep.

4 trial Requirements
 4.1 The view should simulate a basic trial course 
 4.2 It should be possible to time the game.

3.4.2) Non-functional Requirements


5 Ease of Deployment
 5.1 The   Simulation   should   facilitate   use   through   ease   of   installation   and
initiation, for example a web based applet, so location of the simulation is
through a web browser.
 5.2 All initiating environment variables should default to a usable state and it

3. Objectives and Requirements Page 25 of 133
Natalie Downe [cs1njd@bath.ac.uk]

should be possible to play immediately on load.

6 Cross Platform
 6.1 The System should work on various different platforms, 
 6.1.1 Operating systems:
 6.1.1.1 Windows 98+, 
 6.1.1.2 Ubuntu Linux,  
 6.1.1.3 Mac OSX
 6.1.2 Web Browsers:
 6.1.2.1 Internet Explorer 6+
 6.1.2.2 Mozilla 1.98+ and Firefox 1.0+
 6.1.2.3 Opera 7+

7 Usable
Note: a large majority of the user interface may be unchangeable depending on
the Agent based modelling system chosen.
 8  The system should be able to accommodate those who are not familiar with
computers, expert computer users and the range in between. Clear instructions
should be provided to the user.
 9  Although the system is primarily aimed at those with background knowledge
in the area of shepherding, the system should also accommodate those who
are new to the area and facilitate its use as a training tool. There will need to
be an explanation of the terminology used and the general ideas behind the
correct way to herd sheep near to the simulation
 10 The system should accommodate expert users (experienced shepherds)
 10.1 Realism, The project should build upon current information and studies
in the field of emergent behaviour, in addition to studies collected through
observation.   The   simulation   should   produce   output   that   is   a   realistic
representation to a user trained in the area of shepherding
 10.2 Any language used in the simulation should fit the same language and
terminology as the subject area of shepherding [Preece 2002].

3.6) Test Plan


The testing for most of the above requirements can be determined through visual
analysis of screen shots. Please see Appendix A for screen shots.

3. Objectives and Requirements Page 26 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Summary
This chapter has looked at what is expected to be produced as a result of this
project, the scope and general project objectives have been identified. After this,
an  investigation   was   made   into   the   various   requirements   gathering   techniques
used, leading to a requirements specification. 
Building on this chapter is the detailed background research, this differers from
the   literature   review   in   the   way   in   which   it   relies   heavily   on   the   authors
observation   and   the   comparisons   of   this   to   the   existing   flocking   techniques
researched in the Background literature section [Chapter 2].

3. Objectives and Requirements Page 27 of 133
Natalie Downe [cs1njd@bath.ac.uk]

4. Detailed Background Research

Introduction
The   theoretical   groundwork   for   this   project   has   now   been   researched   in   the
Background   Literature   chapter   [2]   and   the   resulting   requirements   have   been
analysed  in  the  previous  chapter   [4].   Here  the   intention   is   now   to   take  those
requirements, especially the realism related aspect, and build upon the current
work by investigating what happens in real life, mainly through observation of
sheepdog   trials   [“one  man   and  his   dog”  2004]  [S4C   2004],   interviews   [Owen
2004] [Appendix B1] and personal observation in the field [Appendix B2].

4.1) Sheep Behaviour


Sheep are relatively docile creatures, they have been bred throughout  multiple
generations for their docility, control, quality of wool and meat. Keeping sheep is
a way of life for shepherds, trialling is a way in which they can demonstrate in a
regulated and comparative manner that they and their dog are good at what they
do every day.

4.1.1) Sheep at Rest


Sheep are sociable creatures and although that there is some reason to believe
[Cobb   2005]   that   increased   domestication   has   reduced   their   natural   instincts,
there is much evidence to show that their instincts are still strong in places.
Through observation [Appendix B2] the natural state for a sheep is graze in a
loose flock, when there is no danger surrounding, it will walk for a few paces
pause to eat grass and move off in a random direction roughly towards the way it
was previously going.  
The slow moving sheep follow the flocking rules set out by Reynolds [1987] but
in a very loose cohesion and with little alignment. 

4.1.2) Under 'Attack'


When the sheep is under attack however, it's behaviour changes dramatically and
its   priority   is   now   to   run   away   from   the   threat,   its   second   instinct   is   now   to
remain in the flock.
It  is  the   exploitation   of   the  sheep's   natural   gregarious   instincts   that   proves   so
effective in the control of sheep. Although this sheep­sheepdog interaction may
seem like a traditional predator prey situation, it differs in the way that the sheep
react around dogs that they trust [Jones 1987][Appendix B2].
Having been nurtured through generations of selective breeding and evolution it

4. Detailed Background Research Page 28 of 133
Natalie Downe [cs1njd@bath.ac.uk]

is now possible for the 'fear' reaction of the predator influence to be used to direct
the sheep without distressing them unnecessarily.
It has  recently  been  ascertained  that  sheep  like some other flocking   creatures,
have the facility to communicate their fear to their flock mates using pheromones
and   chemical   communication   [Delgado­Mata   2004]   The   paper   presenting   this
idea built upon the fundamental research by Minsky [1985] who first recognised
the importance of emotion in Artificial intelligence. 
Another important theory to understand about sheep avoidance of the sheepdog
is the theory of the flight zone. There are some [Cobb 2005] who suggest that the
flight zone is around the sheep at all times and is purely enlarged by the presence
of the dog or another threat where it then enlarges. However through observation
and interviews with Aled Owen [Appendix B2] it was discussed that although the
sheep are always aware of its neighbouring sheep and of bumping into them, that
they actually have a separate flight zone acting as a sphere of influence in which
the sheep will remain comfortable if there is no potential threat inside.
This observation follows nicely with Reynolds' theory of flocking [1987] where
the rules apply to each individual sheep and have little or nothing to do with the
sphere of influence (Flight zone) with avoiding predators.
It is important to note that this dissertation will be focussing mainly on hill sheep
[Appendix B2] as this was the variety studied with Aled Owen. The hill sheep are
flightier than their more subdued heavier cousins of the lowlands. The hill sheep
have less cohesion and a larger flight zone than the Lowland sheep.

4.1.3) Tentative Rest


Once the sheep are at rest from influence from the dog, it is observed that once
they have slowed down to a stop, some time is passed before they relax again
[Owen 2004] the actual effect of this depends on a number of sheep, the nerves
of the dog, the weather and many other factors.
Once the sheep have relaxed however, it is not unknown for the sheep to graze
casually   whilst   waiting   for   the   dog   to   make   its   next   move   [S4C   2004],   this
behaviour   you   would   not   find   in   flocks   or   herds   of   other   animals   in   similar
situations for example, Wilder­beasts. 

4.1.4) Dominant Sheep


It has also been noted that the natural instincts in female sheep are extremely
visible  just after they have given birth [Cobb 2005]. A Ewe that is normally shy
and afraid of the dogs will become aggressive in nature and develop a tendency
to   become   aggressive   toward   the   dog   while   they   have   a   lamb   to   defend
[Appendix B2]. In addition to this it has been noticed [Owen 2004] that male
sheep are far more likely to be rowdy and dominant than females.

4. Detailed Background Research Page 29 of 133
Natalie Downe [cs1njd@bath.ac.uk]

4.2) Sheepdog Behaviour


The sheepdog agent is by far the more complex of the two agent types, the agent
has to not only be able to react instinctively to various situations with the sheep,
but also to be able to take the instruction from the shepherd and translate this
into the corresponding required movement.

4.2.1) Taming the Predatory Instincts


The predatory nature that makes the sheepdog a particularly useful assistant in
rounding up and controlling sheep, is also the instinct that has to be kept in check
right from birth. 
If the dog does not control its instinct in general shepherding this is a problem
because the sheep may get injured as a result. However,  if the dog looses the
control   and   'grips'   [bites]   the   sheep   in   a   sheepdog   trial,   this   could   lead   to
disqualification.
There are times however, where it is necessary for a dog to grip the sheep [Owen
2004 and see Appendix B2] (in general shepherding only). With one dominant
sheep in a flock a sheepdog has to give the sheep 'the eye', this is where the dog
stares at the sheep till it can gain its trust at which point the sheep will continue
with a further respect for the dog. Only the Border Collie has really managed this.
At a point where there are more than one dominant sheep [Wikipedia:herd 2005]
it can become necessary [Owen 2004] for the dog to   bite the most forthright
sheep to demand its respect. Once this is achieved the sheep will become more
passive to encouragement from the dog.

4.2.2) Directing the dog


A   shepherd   directs   the   dog   in   a   number   of   ways,   by   far   the   most   important
method is the commands which he gives the dog, this can be performed through
either whistles or voice key words. 
The second but almost equally valuable method is to supplement the commands
given to the dog with body language from the shepherd [see section in Appendix
B2] The sheepdog can normally 'guess' that the shepherd wants the sheep to be
brought   to   him   so   this   is   what   the   dog   will   do   if   given   no   instruction.   Hand
signals and facing direction are the most important ways in which the shepherd
interacts physically with the dog.
The shepherd can also act as a 'weak sheepdog', exhibiting some control over the
sheep and swapping places with the dog when the sheep begin to take advantage
[Jones et al 1987]. 
Training of the dog is guided through trust and partnership between it and the
handler. This partnership includes [Bartlett 1979] the learning of the commands
through play and through direction, sometimes training aids such as a lead or a
stick are used gently. 

4. Detailed Background Research Page 30 of 133
Natalie Downe [cs1njd@bath.ac.uk]

The physical direction of the dog is out of scope for this project, it would make an
interesting   future   study   to   include   the   physical   influence   of   the   shepherd   and
perhaps also the audience members near the pitch as this also has an influence on
the sheep and the sheepdog's nerves.

4.3) Sheepdog Trials


A   sheepdog   trial   is   designed   to   test   both   the   sheepdog   and   the   control   the
shepherd has over it. The shepherd generally stands at a fixed post in the field
and without moving from the post, has to give signals to the dog allowing it to
manoeuvre the sheep through the course.
At the end of the course, the sheep then need to be led into a pen [penning] and
at this point it is necessary for the shepherd to assist the dog somewhat and to
close the gate once the sheep are through.

4.3.1) The Trial Course


Although all trial courses vary regionally and by skill level, there are elements
that make up the building blocks of any trial layout [Nicklass et al 2004].
Outrun – When the handler who is standing at the post, sends their dog away
toward the sheep.
Lift – The dog has reached the outside of the sheep's flight zone and begins to
move and accelerate very slowly. This has the effect of moving the sheep in a
forward direction.
Fetch – The process in which the dog goes on the outrun, lifts the sheep from
behind then drives them forward back toward the handler, normally through
fetch gates.
Drive – Having completed the fetch of the sheep the dog can then ease away
back   from  the  sheep,   move  in  a   wide   circle  180  degrees  and   then   lifts   the
sheep   in   the   direction   away   from   the   handler.   The   sheep   are   then   driven
around the course by the dog.
Crossdrive  –  Once  over  the  first  drive  gates,  the  sheep  can  then  be driven
across the course to the second drive gates.
Double Gather –  It is sometimes the case at open trials that dogs once they
have   gathered   one   set   of   sheep   will   then   need   to   turn   back   and   collect   a
second set to join the first.
Look Back –  The set point in a double gather where the dog needs to turn
back and look for more sheep to collect. An advanced double gather would
indicate in which direction the sheep lay.
Shed –  This is a very difficult process  and the shepherd has to move away
from their post and use themselves as a weak sheepdog in order to split the
sheep. Shedding normally happens after a drive, arriving in a shedding ring

4. Detailed Background Research Page 31 of 133
Natalie Downe [cs1njd@bath.ac.uk]

where dog and handler sort out and separate a number of sheep, normally the
sheep to be separated will be marked and need to step out of the ring for the
sheepdog to then continue on with the course.
Single – At open trials, it is sometimes common for the dog to be required to
separate out one sheep from the rest of the flock.
Pen – Penning is normally the last stage in the trial where the sheep are driven
towards the enclosure and the shepherd will then move in to assist the dog in
the task completion.
Some of the above elements however have been deemed out of scope, primarily
for the reason that the physical influence of the shepherd on the dog 

4.3.2) Trial Scoring


Scoring of sheepdog trials is done in a similar way to ice­skating and some other
sports; the dogs are marked out of a set amount for each area and aspect of the
course then marks are taken off for mistakes.
The   standard   for   scoring   in   trials   all   over   the   world   is   taken   from   the
International Sheepdog Society [IDSS]. Different trials will have various weights
set for all of the different areas of the trial.

4.3.3) Intended trial Structure


The intended trial structure will be very simple, below is a drawing to illustrate a
very simple trial situation without any of the elements considered out of scope
because   of   the   physical   influence   needed   from   the   shepherd,   e.g.   penning
shedding and singling.

Sheep 
Start

Gate One

Gate Two

Sheep 
 End
Dog

4. Detailed Background Research Page 32 of 133
Natalie Downe [cs1njd@bath.ac.uk]

The above is purely an example of a trial field that could be used in the system.
Ideally there would be a number to choose from as different levels to keep the
user   entertained   and   challenged.   Each   would   have   a   way   of   judging   success
against various factors such as the outrun, lift, drive etc.
Naturally real sheepdog trials are a lot more complex than this, however for a
simulation this is adequate, a more complex trial simulation with a double gather
could   also   be   used   as   well   as   variations   on   the   above   theme.   For   more
information on the structure and layout of sheepdog trials please consult “A way
of life” by H Glyn Jones and Barbara Collins [1987].

4.3.4) Other points to note


The other thing note in the design of the agents is the doggedness of the sheep has
also   been   considered   out   of   out   of   scope   because   in   a   trial   situation   each
shepherd is given a new set of sheep who are not used to the track.

Summary
This   chapter   builds   upon   information   in   the   Background   Literature   section   by
incorporating observations and specifics about sheep and sheepdogs.
Using   the   findings   from   the   project   so   far,   this   dissertation   now   goes   on   to
explore   the   design   for   the   system.   Looking   at   the   project   in   a   behavioural
modelling mindset both the dog and the sheep will be designed as agents in a
situated environment.

4. Detailed Background Research Page 33 of 133
Natalie Downe [cs1njd@bath.ac.uk]

5. Application of Research and Agent Design

Introduction
Having   looked   now   in   more   detail   at   the   background   surrounding   the  project
both the existing literature and theories and how the subjects behave in the wild,
and at the detailed requirements needed to ensure a realistic simulation that fits
the   needs   of   the   user,   we   can   now   go   on   and   look   at   the   design   for   the
implementation of these requirements in more detail.
This chapter looks at the overall intended class hierarchy and then the design of
the sheep and sheepdog agents. 

5.1) Class Hierarchy


Below is the intended class hierarchy of the system, all methods that are common
to   both   the   Sheep   and   the   Dog   will   be   placed   in   animal.   One   possible
implementation of the Dominant sheep could be to have a class Dominant Sheep
extending   Sheep.java   that   would   then   have   the   various   extra   functionality   for
standing up against the dog.

Animal.java
Animal.java is the 
super class for 
Dog and Sheep. 

Sheep.java Dog.java

5.2) Detailed Sheep Agent Design


Using the distributed behavioural model for flock formation set out by Reynolds
[1987] we now consider the sheep and the dog to be situated agents interacting
in an environment.
Sheep are intelligent creatures only ranking beneath pigs, and at the same level
as   cattle.   Despite   this   however,   their   primary   instincts   toward   their   situated
environment are their main driving force. As a result it is now possible to view the
sheep as 'Reactive Agents' [Wooldridge 1966]. 

5. Application of Research and Agent Design Page 34 of 133
Natalie Downe [cs1njd@bath.ac.uk]

5.2.1) Considerations when designing sheep Agent


Building   upon   knowledge   gained   in   the   Background   studies   [Chapter   2],   the
Requirements Gathering stage [3.1.1] and the field studies in Wales [Appendix
B2]   we  now  look  in  more  detail  at  the  specific  elements  that   will  need  to  be
considered and planned for when designing the sheep agent.
Referring to Section 2.5.3, in the analysis of similar systems, the publication of
Hebert  et al.  [2003]  was  looked  at,  it  illustrates  this  link  between  reality  and
simulation  with  respect  to  sheep  and proposes  the  following  priority  of  action
selection for an individual flock member:
1. Move   away   from   predators  –   to   “run   away   from   any   dogs”   self
preservation logic, maintaining the sheep’s own personal safety.
2. Stay   in   the   herd  –  Once   the   presence   of   the   dog   as   a   threat   has   been
eliminated the sheep will then check that they are in a herd.
3. Foraging instinct  ­ If the sheep is safe from predators and within the herd,
then it is free to forage for grass
However, from observation [Appendix B2][One man and his dog 2004] and from
Jones [2004] it is clear to see that this is not precisely what happens in the wild. 
Although the sheep scatter under some circumstances, the default reaction is to
stay together in a herd over that of moving away from the predator. This project
suggests that although the above order of action selection preference is correct,
the actual implementation needs further consideration. 
It is the hypothesis of this study that the distance from the sheep, the current
speed and direction of the dog, with respect to the sheep's flight zone (mentioned
above) have a great influence on the actual strength and weighting of the flocking
properties themselves.
1. Move away from predator – Mainly making use of the evasion behaviour
set down by Reynolds [1999] the sheep’s main priority is to stay safe, it does
this through staying in the herd and moving in the opposite direction of the
predator. 
Dog
Dog 
direction
 yDiff
Sheep a
xDiff
Sheep's new 
direction (grey) is 
directly away 
from sheepdog

5. Application of Research and Agent Design Page 35 of 133
Natalie Downe [cs1njd@bath.ac.uk]

To obtain angle a, simple trigonometry needs to be performed: 
a = tan-1(yDiff / xDiff)
The xDiff and yDiff can easily be calculated using the agents' coordinates.
There will need to be a method in each agent to allow the other to know what
position it is at. This is essential for all the calculations.
Now  that   angle  a  has  been  obtained   (in  radians)   to   get  the new  direction
vector for the sheep this has to be converted. This is very dependant on the
geometry of the Agent Based Modelling system chosen.
The direction of the sheep having been calculated as radians and as  a unit
vector,   the   speed   (magnitude   of   direction   vector)   remains   similar   to   its
existing speed.
This said, in this project it is hypothesised that depending on how far and how
fast the sheep move is proportional to the position and the velocity of the dog
with regards to the flight zone of the sheep flock as a whole. 
Therefore as the dog gets closer to the sheep not only do they move away,
they  also  adjust  their  speed  to  that  of  the  dog.  If the dog slows  down  the
sheep will still evade at a constant pace until the sheep is out of their flight
zone, at which point they will slow to a halt but remain alert. 
Should the dog speed up however, the sheep will attempt to match the speed,
but it has also to be considered that the sheep, once tired, will be more likely
to turn and confront the dog, more likely still if they are a 'dominant' sheep to
begin with.
Referring to figure 2 in section 2.4 this states that the sheep will scatter if the
dog comes too close. Although this remains true, before the state of the sheep
can get to this level of panic if there is a slow and gradual increase in speed
causing the sheep to continue to flock only faster.
The diagram below, uses the length of arrows to simulate the speed at which
the agent is travelling. Note, here the dog is speeding up gradually and the
sheep are not travelling directly away from it because there are other factors
to be considered.

5. Application of Research and Agent Design Page 36 of 133
Natalie Downe [cs1njd@bath.ac.uk]

The flight zone increases with the size of the flock. However in order for the
flight zone of the sheep flock to change with regards to the amount of sheep
[From observation and Owen 2004], it is necessary to implement the theory of
pheromones and chemical communication as set out in the paper by Delgado­
Mata [2004]. 
To implement the communication between the sheep, the best way is to have
a 'fear level' set for each sheep that is then accessible (through a Java getter)
to its flock mates. The following could then be analysed
If I [as the current sheep] have a dog in the vicinity of my flight zone I set
my fear variable on and use the Java setter for all other sheep in my flight
zone and  reset  their  fear variable  too  and reset  the fear  variable if that
particular sheep detects a danger.
If I have my fear switch on then check my neighbours, if none of the sheep
in my vicinity have their fear variable set then reset mine to off.
If I do not detect a dog around wait one cycle, if dog still not around switch
my fear off.
2.  Stay   in   herd  –   making   use   of   the   3   flocking   behaviours   for   automated
characters   [Reynolds   1987].   Each   of   these   three   rules   have   their   resulting
forces calculated and then are added together with a weight   for each.  The
weight will be a variable set in the flock class that can be reset by any sheep
and will then be used by all others. 
The sum of the forces once  calculated  is  fractioned  to a small percent  and
added to the current direction vector so that it does not appear the sheep are
turning too sharply.
a.  Cohesion  – moving toward the centre of its neighbours. The way this
rule   operates   is   that   the   sheep   looks   at   all   the   sheep   within   its
neighbourhood   (flight   zone)   obtains   the   average   of   their   positions   and
calculates the vector that would lead it toward that point.

5. Application of Research and Agent Design Page 37 of 133
Natalie Downe [cs1njd@bath.ac.uk]

The above diagram shows the resulting vector to be from the sheep to the
blue circle. This is then multiplied by the cohesion factor (weighting) and
added to the sum of the other resulting forces. which itself is then weighted
and added to the current direction vector. The sheep's present position plus
this direction vector leads it to the next stage along.
An   important   point   to   note   as   recognised   in   the   Background   reading
[Chapter   2]   and   from   observation   [Appendix   B2]   is   that  the   cohesion
belonging to sheep is a lot stronger than that of birds and that when there
are no predators around the bird flocking is still similar, with sheep this
changes to a loose formation if the flock is not in danger.

5. Application of Research and Agent Design Page 38 of 133
Natalie Downe [cs1njd@bath.ac.uk]

b.  Separation  –   moving   to   create   equal   space   with   the   surrounding


neighbours. When neighbouring flock mates get to close, it is necessary to
move away to maintain the flock structure.

In the above diagram all the unit vectors representing the vector from each
of the other sheep back to the sheep in question are calculated, these unit
vectors are then summed and this is produced as the resulting force from
this method.
Although   separation   may   seem   like   just   the   opposite   of   cohesion,   it   is
deceptive as the result is entirely dependant on how  many sheep are used
for calculation. Whereas calculating the average for the neighbouring sheep
is not dependant on the number of surrounding flock­mates.

5. Application of Research and Agent Design Page 39 of 133
Natalie Downe [cs1njd@bath.ac.uk]

c. Alignment – Aligning the direction and speed [velocity] with that of its
neighbours. To ensure that the sheep are travelling not only in a similar
direction but a similar speed.

The current sheep (again in blue) looks at all the sheep around it and
averages their speed and direction vectors to get the resulting force.
3. Foraging instinct – once it is deemed safe, the sheep is then free to eat.
The   foraging   instinct   comes   about   when   the   state   of   the  sheep   is   at   its
initial and relaxed state. When there are no dogs around to be a potential
threat,   the   sheep   have   but   one   interest:   the   pursuit   of   food.   Being
herbivores with an ample food supply there is little danger of missing out
of food, and as a result the sheep do not need to compete with each other
for the 'best grass' and are therefore are more relaxed in their movements.
This feeling combined  with the  natural and instinctive tendencies of the
sheep   to   remain   in   a   flock   for   security   reasons   means   that   the   sheep
wander in a random pattern, following loosely the flocking rules of staying
within a comfortable distance of the other sheep (larger than usual) but
with little or no alignment influence between the them and more influence
from the random factor.
If you were to map out the tracks of the individual sheep on a field over
time   it   would   result   in   a   field   where   most   areas   had   been   covered   by
different sheep at one point or another. The rate at which they move is
relatively random, the sheep will stop for a short amount of time and then
move on.
It should also be noted however, that there is some period of tentative fear

5. Application of Research and Agent Design Page 40 of 133
Natalie Downe [cs1njd@bath.ac.uk]

of   the   sheep   where   the   dog   has   just   left,   this   is   where   the   sheep   will
continue on their current momentum for a period before slowing to a stop
and standing close together for a short while until the situation is deemed
completely   safe,   at   which   point   they   will   continue   with   the   afore
mentioned foraging pattern.
Another point to note is the mention[Owen 2004] that larger flocks are easier to
control   that   smaller   flocks.   This   goes   against   the   traditional   explanation   of
cohesion mentioned above and there will have to be some factor of multiplication
to represent the number in the flock

5.2.2) Sheep Agent Architecture


Having established the sheep agent as a   reactive agent, it is now necessary to
devise   the   appropriate   architecture   for   this.   Various   options   include   the
Subsumption   architecture,   PENGI,   Situated   automata   and   the   agent   network
architecture [Wooldridge 1966]
After   due   consideration,   it   was   decided   that   a   loose   implementation   if   the
Subsumption architecture was the best choice as it dealt nicely with the issue of
prioritising tasks for execution internal to the agent based on information about
its situated environment.
The Subsumption   architecture is  the  brain­child  of  Rodney  Brooks   [1985] and
describes the agent a layered structure of rules. The rules placed on the bottom
gain higher priority than those above.
The idea follows that the lower rules will consist of instinctive behaviour such as
stay in flock or avoid sheepdog, further up the sheep priority (lower preference)
the rules such as graze or move in a random  direction  forward  will guide the
sheep as to the expected behaviour if say for example there is no dog and they are
in the flock.
The diagram opposite [ reference the
Agent diagram]   represents   the   see   and
action   functions   within   the   reactive
agent   and   how   this   relates   to   the
See Act
environment. 
Before   we   establish   the   detailed
nature of the Sheep agent it is first
Environment necessary   to   define   the   information
that   each   sheep   'knows'   these   can
easily  be related to  variables  in the
program.
Per sheep: 
– The individual sheep number which acts as an identifier
– The current direction (as a vector and in radians) it is heading in

5. Application of Research and Agent Design Page 41 of 133
Natalie Downe [cs1njd@bath.ac.uk]

– Whether it is dominant or not 
– If the sheep is afraid 
Ascertained from the flock details:
– The Flight zone radius, this remains constant throughout the simulation
– The   cohesion,   alignment   and   separation   factors   (weights).   As   well   as   a
randomness force.
– The flock itself on which operations such as getting the neighbouring sheep
and determining the proximity of the dog.
Referring   back   to   the   above   diagram   of   the   sheep   architecture   there   are   two
different interactions with the surrounding environment  see  and  act. The 'see'
abilities of the sheep include:
The  ability  to   identify   the neighbouring   sheep   and  to   retrieve data   such  as
their position and direction
The   use   of   their   360   degree   peripheral   vision   [Cobb   2005]   in   order   to
determine if there is a dog nearby and how close it is.
The 'act' functionality of each sheep is as follows:
Move in a Random direction if they hit the side of the field ideally this would
be reflective of the angle of incidence which the sheep had come to the fence.
Calculate the influence of alignment of direction with the other sheep.
Calculate the amount of cohesion needed to stay in flock.
Calculate the separation needed not to bump into its fellow flock mates
Avoid the dog at all costs
Sum the four influencing factors above to find resulting direction vector and
move there. 
The rules, when placed in the Subsumption architecture take a situation and map
it onto an action to take on the environment. For the sheep Agent these rules take
on the following formation (note the lower rules have higher priority):

5. Application of Research and Agent Design Page 42 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Situation ­­­>  Action


6. If 'true' ­­­>  Stop to eat grass for a random
amount of time 
5. If eating grass and have finished ­­­> Move a random short distance (until
eating grass found good grass) forward in a
random direction ranging about 20
  degrees in the current direction
4. If no dog in or close by flight zone ­­­> 1. cohesion: Ensure that I am in the
flock, as noted above this will also
have to be dependant on the
number of individuals in the flock.
2. alignment: Am I travelling at the
right speed and direction?
3. separation: Ensure no imminent
collisions with flock mates 
4. Reset Separation alignment and
cohesion factors to base rate (low)
If I have my fear switch on then check
my neighbours, if none of the sheep in
my vicinity have their fear variable set
then reset mine to off.
3. If there is no dog in or close by the ­­­> continue with current momentum but
flight zone but there was a short slowing down, when slowed to a halt,
while ago slowly turn part way to face the
opposite way you were running and
wait.
wait one cycle, if dog still not around
switch fear variable off.

5. Application of Research and Agent Design Page 43 of 133
Natalie Downe [cs1njd@bath.ac.uk]

2. If detect dog and it is within or ­­­>  Multiply cohesion and alignment


near flight zone distance factors by ¼ * the speed of the dog
[from observation of sheep, this to be
used as a starting point and one of
the aims of the project is to make the
simulation realistic]
Multiply speed by the speed of the
dog 
Run away linearly from dog (or if
there are more than one dogs directly
away from the average pursuance
vector)
set the 'fear' variable on, and use the
Java setter for all other sheep in the
flight zone and reset their fear
variable to on as well.
1. If detect an obstacle in the path ­­­> Move away from obstacle using the
rules covered in depth by Reynolds
[1999]

Based on the above rules it is now possible use these as priorities to create the
sheep Agent. 

5.3) Detailed Sheepdog Agent Design


The  predatory   nature   of   animals   in   the   wild   can   vary   greatly   from   species   to
species   as   they   utilise   their   particular   characteristics   for   hunting   their   prey.
Sheepdogs use a combination of their speed, intelligence and sense of smell.
In order for the sheepdog to control a flock of sheep under the command of a
shepherd, it has to firstly have the ability to take the instructions given to it and
follow them through, but also to observe the body language from the shepherd. It
has been mentioned previously that the body language of the shepherd is out of
scope for this project, but none the less is still an important factor in how the
sheepdog knows how to control the sheep.
In  addition   to  given  and observed   commands,   the  dog  also   has  to  be  suitably
reactive to the movements of the surrounding sheep and whether or not they are
heading in roughly the right direction. Should the sheep be heading in a direction
unfavourable   to   the   plan   of   the   dog   its   course   will   need   to   be   readjusted   to
accommodate for this. It is for this reason that it was decided to implement the
sheepdog agent as a Hybrid of a reactive and planning architecture [Wooldridge
1966].

5. Application of Research and Agent Design Page 44 of 133
Natalie Downe [cs1njd@bath.ac.uk]

5.3.1) Commands from shepherd


The Dog obtains its short term plans from the shepherd mainly by the way of
instructional calls or whistles depending on the experience of the dog. Covered
briefly in chapter 4 here we look at the commands in more detail, commands
come from Nickless et al. [2004].
"Away"   or   "Away   to   Me"   means   to   move   in   an   anticlockwise
direction, with a relitavely straight outrun.
"Come­Bye" Opposite to Away, this means for the dog to move in a
clockwise direction (come by the hands of the clock [Owen 2004]
all directions are relative to the sheepdog's point of view
"Get Back"or "Get Out" encourages the dog to keep further away
than it is, backing off and and giving the sheep more room
"In Here" used when shedding in conjunction with body language
to indicate a gap in the sheep that could be used to separate them.
"Lie Down" means a  variety of things from  Stop,  lie down,  slow
down or just to stand still the intelligent Border Collies will be able
to tell which one the handler means.
"Look   Back"   when   a   'Double   gather]   (see   detailed   trial
requirements) implies to the dog that there is another set of sheep
elsewhere. The advanced look back also indicates the direction
"Stand"­ Stand still ­ the dog must stop but remain on its feet
"Take Time" Slow down
"That'll do" an end command, return directly to the handler
"There" Stop flanking and move straight towards the sheep ready
for a drive.
"Walk Up" to move straight towards the sheep

5. Application of Research and Agent Design Page 45 of 133
Natalie Downe [cs1njd@bath.ac.uk]

5.3.2) Sheepdog Agent Architecture


The implementation of the dog agent will not deal with the artificial intelligence
needed for the dog to coordinate the sheep to the intended position as this project
concentrates more on the  sheep' interaction with the dog. The area of artificial
intelligence   to   make   a   purely   automatic   sheepdog   has   been   covered   by   the
Robotic sheepdog Project [Hebert et al 2003].
The sheepdog model considered by this dissertation is consistent with a hybrid
Agent, dealing with both the sheepdogs reactive nature and the planning element
that   when   given   a   command   by   the   shepherd   knows   how   to   implement   this
command in more detail.

Agent

See Perceive Decide Act

Environment

As with the sheep agent it is possible to divide this up into its constituent parts:
See
– Receive   commands   from   shepherd,   either   by   voice   or   whistle,   in   this
simulation however input will be from the keyboard, with various keys
giving the commands, possibly utilising the arrow keys to ensure novice
users are also able to do this.
– receive   information   about   their   environment   such   as   the   position   and
direction of the nearby sheep and whether there are any obstacles in the
path or not.
Perceive
– Perceive deals with the processing of visual data and reasoning aspects
about the environment from that, for example deciding if the sheep are
moving in the intended direction would be one of the important elements
to consider here.
– Are any of the sheep exhibiting dominant behavioural patterns? 
– Take the input given by the shepherd and apply that to current position
and direction – do not act on it just yet however look at the command
and Perceive the intended direction from that. 
Decide

5. Application of Research and Agent Design Page 46 of 133
Natalie Downe [cs1njd@bath.ac.uk]

– Decide takes the perceptions about the environment and maps them onto
an   action.   Therefore   for   whichever   command   that   was   given,   map   the
intended direction perceived to the current direction.
– If any  of  the sheep  are exhibiting  dominant  tendencies,  look  at all the
possible coping strategies and decide between them.
Act
– If  any   action   decision   has   been  made  this   is   the  area  where  it   will  be
implemented.
If the dog follows the above architecture and implements especially the steering
behaviours   for   obstacle   avoidance   and   pursuit   then   this   will   emulate   a   rough
approximation  of  a sheepdog.  However the Border Collie  and  the sheepdog  in
general is a very complex creature and far more research will need to be carried
out to do it justice.

Summary
This   project   has   now   covered   the   background   literature   and   related   specific
research, the above chapter used this to design one possible implementation of
the sheep and sheepdog agents. 
The   next   chapter   goes   into   these   designs   in   more   detail   after   choosing   an
appropriate   implementation   technology.   There   will   then   be   a   system   walk
through consisting of the highlights of implementation. Source code of the project
can be found at the back of the project in Appendix C.

5. Application of Research and Agent Design Page 47 of 133
Natalie Downe [cs1njd@bath.ac.uk]

6. Implementation of Design

Introduction
The   previous   chapter   built   on   the   knowledge   gathered   from   investigations,
research and background reading by presenting designs for the two agent types.
This   chapter   relates   to   the   implementation   of   these   designs,   it   considers   the
various technology options that had to be decided upon before the project could
be developed, and the reasons for the final choice.
After this the implementation highlights are looked at in detail with regards to
the flow of the system, and the system testing results are covered. 
The resulting simulation will be included on the accompanying disk if attached to
this   project,   otherwise   the   simulation   is   also   available   on­line   at:
http://www.bath.ac.uk/~cs1njd/demo.html.

6.1) Technology considerations


Before any specific project development decisions can be made, it is essential to
look in more detail at the various options available for implementation, as this
will have a dramatic effect on the design itself.

6.1.1) Alternative options


The   following   technology   choices   were   evaluated   with   regards   to   the
requirements set out in chapter 3 as well as their ease of use and their alignment
with the authors mental model. 

6.1.1.1) Swarm
The   first   implementation   solution   to   be   investigated   was   Swarm,   originally
developed   at   the     Santa  Fe  Institute,     [Wildberger  1996]   [Minar  et   al   1996]
SWARM was the first widely used agent based modelling system. 
SWARM was initially developed as tool to aid “researchers in the study of agent
based   models.”[Swarm   Wiki].   It   then   evolved   rapidly   into   the   simulation
environment   of   today.   The   environment   itself   consists   of   a   large   download   of
libraries. Its structure is designed to host many agents over concurrent computers,
and as a result has a lot of unnecessary features which adds considerably to its
complexity. 
In   addition   to   the   above,   with   regards   to   the  deployability  requirement
[Requirement 5] the users would be required to download and install the large
set of libraries. This in itself makes SWARM an inadequate choice for a simulation
base.

6. Implementation of Design Page 48 of 133
Natalie Downe [cs1njd@bath.ac.uk]

6.1.1.2) Breve
Breve [Klein 2002] is similar to swarm but also attempts to simulate continuous
time   and   3D   space.   The   environment   is   controlled   using   'Steve'   a   specially
designed programming language based on objective C and Perl. Steve is relatively
easy   to   learn   and   in   comparison   to   Java   based   environments   is   very   fast   to
achieve visible results.
Although   easy   to   get   an   initial   visualisation,   understanding   the   underlying
functionality and the complex libraries involved is comparatively  difficult.
A number of interesting projects have been developed using Breve, including a
virtual   simulation   of   the   Harry   Potter   game  Quidditch,   and   an   interesting
adaptation of the flocking algorithm to simulate learning behaviour in flocks of
birds searching for food sources [Spector et al 2003].
Despite   the   core   language   being   a   relatively   simple   language   to   learn,   after
extensive testing of this solution it was deemed that the underlying architecture
of the API (Applications Programming Interface) was overly complex.

6.1.1.3) MASON
MASON [Balan et al. 2003] (Multi Agent Simulator of Neighbourhoods) aims at
integrating   the   Cross   Pollination”   of   disciplines   such   as   Artificial   inelegance,
Social sciences and robotics. Like BREVE it is also BASED on a variant of SWARM.
One of the greatest advantages of MASON is that it is highly modular and as a
result is not too large a system. 
MASON aims its facilities at the intersection between most multi agent system
domains and not the union between them all, as a result MASON is “Intentionally
simple but highly flexible” [Balan et al. 2003]. For these reasons and helped by
the   author's   prior   knowledge   of   Java,   this   made   MASON   the   natural   choice.
Further justification of this decision follows in section 6.1.2.

6.1.1.4) Python and PyGame


http://www.pygame.org/ PyGame is a collection of  python modules designed for
the implementation of games. PyGame is highly portable and also has intuitive
use of user input. Although a highly usable base language (python) this system
unfortunately does not easily facilitate the use of agent oriented design.

6.1.1.5) Processing
Processing  is an environment   which is  exceedingly   usable,  it  was  designed  for
artists   with   little   or   no   programming   ability.   The   resulting   simulations   are
invariably visually pleasing. However at the time of analysis this environment was
s in Alpha release and as a result was not yet fully supported.

6.1.1.6) Programming the simulation from 'scratch'


Programming  the project  entirely  from   'scratch'   with  no library's   or simulation

6. Implementation of Design Page 49 of 133
Natalie Downe [cs1njd@bath.ac.uk]

environments was also considered as an option. 
There were a number of  languages  that   were  suitable to this  large task,  Java,
C++ and Python. The primary reason this was not the solution that was chosen
was   that   it   would   not   have   been   utilising   the   knowledge   that   was   already
understood about agent environments.
By   building   on   the   work   of   others   it   is   possible   to   refine   and   improve   upon
existing   knowledge   and   develop   a   project   that   goes   beyond   this.   Ignoring   the
existing   research   ensures   a   project   that   covers   a   lot   of   the   same   ground   that
previous projects have.

6.1.2) Resulting Choice: Mason


The previous section covered the main reasons for choosing MASON as the agent
based simulation environment. These included:
The modular approach of MASON 
How   the   libraries   take   an   intersection   of   functionality   needed   by   different
modelling domains
The author's prior knowledge of Java
Another   striking   reason   as   to   why   MASON   is   better   than   some   of   the   other
choices looked at relates to one of the most interesting features of MASON; as an
API is that it positively encourages the use of the Model View Controller paradigm
[GAMMA et al 2000]. Mason simulations have the ability to run with or without a
corresponding GUI. 
This forces the designer to think in terms of what elements of the program are
purely  visual  and which  relate  to the simulation.  MASON  does not  implement
strict MVC as there is no controller.
As   a   consequence   there   is   now   a   definite   file   structure   needed   for   the
implementation.   The   System   Architecture   diagram   below   builds   on   the   class
diagram from before.

The SheepFlockWithUI object calls the 
Flock object, the simulation works because 
SheepFlockWithUI.java they both reference the same underlying 
data model: a continuous2D object

Flock.java Animal.java
Flock.java instantiates the sheep  Animal.java is the 
and dog depending on how many  super class for 
are specified in the class variable  Dog and Sheep. 
(changeable by the user)

Sheep.java Dog.java

System Architecture Diagram

6. Implementation of Design Page 50 of 133
Natalie Downe [cs1njd@bath.ac.uk]

This perspective is very useful for the implementation of this project as it easily
facilitates the use of agent objects that are called from the Flock.Java file

6.1.2.1) Geometry of Mason


An understanding of the geometry of MASON starts with a general understanding
of the direction and zero coordinate of the object used to represent the agents'
positions.
The   simulation   is   held   in   a  continuous2d  data   type   which   is   then   easily
incorporated with the 'view' of SheepFlockWithUI.java using the MASON libraries.
Below is a diagram that represents the basic geometry of MASON

+ N
(0,0)

0 radians
+

In Java, all the angle calculations are in radians and MASON displays 0 radians to
be due East. the coordinate (0,0) is at the top left and positive axes stretch east
and south.

6.2) Further Implementation Highlights


What follows is a brief walk through of the implementation of the system in the
respective   order   of   how   the   objects   are   created   and   called.   Referring   back   to
Gamma   et   al.   [2000]   and   Balan   et   al   [2003].   We   also   recall   that   Mason
encourages the use of the Model View Controller.  Starting with the view of the
interface the walk­through works down to the underlying model of the flock and
the agents it calls.

6.2.1) Interface design


Referring   back   to   the   requirements,   it   was   stated   that   the   system   should   be
portable and easily deployed [requirement 5] it was decided that the system be
finally deployed as an applet. This would mean that the system could be sent to
users as purely a link. In order for the system to be usable by the target audience
however   some   consideration   would   need   to   be   put   into   a   user   guide   that
explained in clear detail with screen shots how to install Java onto their machine.

6. Implementation of Design Page 51 of 133
Natalie Downe [cs1njd@bath.ac.uk]

The Java applet is launched through a button that  also brings in not only the
simulation but all the supporting mason code:

This launches a pop­up Java selection box:

The   contents   of   the   drop   down   options   are   specified   in   the


sim/display/simulation.classes file as follows:

# Fully qualified class name of graphical start-up class


uk.co.natbat.sheep.SheepFlockWithUI
ONLY

This ensures that the user can only select from the drop down list and also that
the only option in the list is this program.
When   started,   the   program   pops   up   two   windows.   The   first   is   the   simulation
window in which all the movement of the sheep and dogs will occur in, this also
has the basis for extra functionality such as the ability to record the simulation as
a Quicktime movie. This leaves definite room for expansion as with a simulation
it is not always possible to recreate the same situation more than once.   Other
functions   of  this   tool  bar   include  the  the   capture  of  a   still  image  and  various
resizing options.

A lot of the mason interface comes as standard with the mason package. Part of
the inherent MASON functionality is the ability to display the public variables of
the containing flock object as adjustable fields in the default mason interface.
There are two 'control panels' in the second 'set­up' window that appears  as a
result of selecting and starting the simulation:

6. Implementation of Design Page 52 of 133
Natalie Downe [cs1njd@bath.ac.uk]

The   screen   shot   on   the   left   controls   the   various   public   variables   available   for
change in the  model, updating them and clicking on the update button should
change   the   variables   in   the   program   and   therefore   alter   the   effect   of   the
simulation. The  console  screen displays  the available base options, most  users
will not need to look at these.

6.2.2) GUI controller


The GUI Controller is the main file used to view the simulation, it is possible to
run the system without it because of the inherent functionality of MASON and
their model view controller implementation.
The GUI controller (SheepFlockWithUI.java) extends GUIState and as such has a
number of methods that need to be overridden. It initiates all the relevant class
variables   such   as   the  Display2D  which   is   the   visual   representation   of   the
Continuous2D  object   used   to   store   objects   situated   at   coordinates   (where   a
coordinate is a Double2D, a pair of doubles)
Other variables such as the size and colour of the sheep and dog are initiated and
set to pale grey for the sheep and black for the dog. The background colour is
white.
The init() method of this class takes a controller object and passes this up to the
constructor of the super class GUI state. it then sets up the display window the
title, the colour etc. and then registers this with the controller setting it to visible.
The explicit constructor of the class initiates the flock from the superclass using

6. Implementation of Design Page 53 of 133
Natalie Downe [cs1njd@bath.ac.uk]

the current time  in milliseconds  as  a random  seed.  This  method  then sets  the


simulation Continuous2D object to be the representation from the Flock class.

public SheepFlockWithUI() {
super(new Flock(System.currentTimeMillis()));
simulation = ((Flock)this.state).getSimulation();
}

 There is also an explict contrrucor that takes a state and passes this back to the
superclass.   
The Main method calls the above constructor and then initiates the console.
Then   follows   a   number   of   boiler­plate   methods,   mainly   getters   and   setters,
(getSimulationInspectedObject(),    getName(),    getInfo(),   load(SimState
state) )
The important part of this class commences in the start method which is called on
the  initiation  of  the start   button.  This  sets   uo the portrayals  needed  and then
resets thhe displayer and repaints the simulation.
Setting   up   of   the   portrayals   is   done   in   the  setupPortrayals()  method,   this
determines what the agent lookslike on screeen.

sheepFlockPortrayal.setPortrayalForClass(Sheep.class, new
sim.portrayal.simple.OvalPortrayal2D(sheepColour, sheepSize));

sheepFlockPortrayal.setPortrayalForClass(Dog.class, new
sim.portrayal.simple.OvalPortrayal2D(dogColour, sheepSize));
        
Following this are two more boiler­plate methods, finish and quit, these call the
corresponding methods in GUI state. [for screen shots please see Appendix A.]

6.2.3) Flock model architecture


The Flock.java is the underlying model of the system, it is this that initiates the
sheep and sheepdogs. Flock.java extends SimState.
Firstly   a   number   of   of   private   class   variables   as   decided   in   the   design   and
application of research section. These variables include (but are not limited to)
the width, height, number of sheep, the probability of a dominant sheep, their
flight zone radius and their initial speed. Dog variables  include the number of
dog, set to 1 initially and the speed. The flock vector weighting for the various
different elements; cohesion, alignment and separation are also set here.
The start method is called every time the start button on the interface is pressed,
and as such, since the simulation can be paused and started again it is best to

6. Implementation of Design Page 54 of 133
Natalie Downe [cs1njd@bath.ac.uk]

leave this inherited method as is.
The   constructor   for   the   flock   takes   a   long   seed   (called   by   the
SheepFlockWithUI.java   file   with   the  current  time   in  milliseconds).   It   is   in  this
method that the continuous2D object is initialised. In the system, other than the
representation of this object in the display file there is only one copy to avoid
duplication.

simulation = new Continuous2D(bucketSize, simulationWidth,


simulationHeight);

The sheep   are  initialised   and   it  is   calculated   depending   on  the  probability   set
previously, whether or not this particular sheep will be dominant or not.

// initiate the desired amount of sheep


for(int sheepNum = 1; sheepNum <= numSheep; sheepNum++) {
System.out.println("F: initiating sheep number " + sheepNum
+ " of " + numSheep);
// decide if this sheep will be a dominant sheep
Random randomNumberGenerator = new Random
(System.currentTimeMillis());
int randNum = randomNumberGenerator.nextInt(100);
boolean dominant = false;
if(randNum < (100 * probOfDominantSheep)) {
dominant = true;
}
// initiate sheep
Sheep sheep = new Sheep(this, dominant, sheepNum);
simulation.setObjectLocation(sheep, sheep.getPosition());
schedule.scheduleRepeating(sheep);
}

A similar method is used for initiating the number of dogs.
The main method then controls the more detailed part of setting the agents to
repeat and making sure that any threads are finished up
As  mentioned   previously   the  continuous2D  object   is   only   stored   in   the   Flock
class, this means that to set the position of an animal the animal calls the set
position method with itself and its intended positions as arguments.
The   rest   of   the   class   consists   of   various   getters   and   setters   for   the   private
variables, as is generally considered good practice in the implementation of Java
projects.

6. Implementation of Design Page 55 of 133
Natalie Downe [cs1njd@bath.ac.uk]

6.2.4) Animal Superclass


The aim of the animal superclass is to place the functionality needed by both the
sheep and the sheepdog agents.
The first  method  takes  a  direction  in radians   and converts  to  a unit  vector to
allow for easier calculation when it comes to using vectors. Please refer back to
the diagram of MASON architecture earlier in this chapter. The code bellow is
well comented and as sucn needs no further explanation.

public Double2D radiansToVector(double radians) {

// local variables
double vectorX;
double vectorY;

// check for slim possibility that radians is negative


if(radians < 0) {
throwError("Unable to calculate unit vector from
radians, 'radians' equals zero!");
}

if(radians >= (1.5 * Math.PI)) {


// sheep pointing between north and east (including
due east and due north)
if(radians == (1.5 * Math.PI)) {
// due North
vectorX = 0.0;
vectorY = -1.0;
} else if(radians == (2 * Math.PI)) {
// due East
vectorX = 1.0;
vectorY = 0.0;
} else {
// between North and east
vectorX = Math.abs(Math.sin((Math.PI * 2) -
radians));
vectorY = (-1) * (Math.abs(Math.cos((Math.PI * 2)
- radians)));
}
} else if(radians >= Math.PI) {

6. Implementation of Design Page 56 of 133
Natalie Downe [cs1njd@bath.ac.uk]

// sheep pointing between west and north (including


due west)
if(radians == Math.PI) {
// due West
vectorX = -1.0;
vectorY = 0.0;
} else {
// between West and North
vectorX = (-1) * (Math.abs(Math.sin(radians -
Math.PI)));
vectorY = (-1) * (Math.abs(Math.cos(radians -
Math.PI)));
}
} else if(radians >= (Math.PI / 2)) {
// sheep pointing between south and west (including
due south)
if(radians == (Math.PI / 2)) {
// due South
vectorX = 0.0;
vectorY = 1.0;
} else {
// between south and west
vectorX = (-1) * (Math.abs(Math.sin(Math.PI -
radians)));
vectorY = Math.abs(Math.cos(Math.PI - radians));
}
} else {
// sheep pointing between east and south (including
due east)
if(radians == 0) {
// due East
vectorX = 1.0;
vectorY = 0.0;
} else {
// between east and south
vectorX = Math.abs(Math.sin(radians));
vectorY = Math.abs(Math.cos(radians));
}
}

6. Implementation of Design Page 57 of 133
Natalie Downe [cs1njd@bath.ac.uk]

// return calculated unit vector


return new Double2D(vectorX, vectorY);
}
   
This   class   also   includes   the   method   that,   given   two   coordinates   (Double2D
objects)   calculates   the   vector   to   travel   from   the   first   to   the   second.   This   is
especially useful when calculating the Separation, Cohesion and dog avoidance.
The use of this and other such small generic methods increaces the modularity of
the code, making it easier to maintain.

protected Double2D vectorDifference(Double2D fromPosition,


Double2D toPosition) {
return new Double2D(toPosition.getX() - fromPosition.getX
(), toPosition.getY() - fromPosition.getY());
}
   
As well as these functional methods, two others were included to save the author
time   when   it   came   to   debugging   the   program   and   also   to   tidy   up   the   error
messages.
Error code:

public void throwError(String errorMessage) {


System.out.println("died: '"+errorMessage+"'");
throw new RuntimeException("died: '"+errorMessage+"'");
}
Debug code:

protected void debug(String debugMessage){


System.out.println(": "+debugMessage);
}
These   methods   are   then   overridden   in   the   sheep   and   dog   classes   to   send   the
animal identification number to the console.

6.2.5) Sheep Agent


The sheep agent is where the code gets really interesting, although not all of the
requirements were implemented, it still shows a fully functional working variant
of the Reynolds' [1987] rules 
 The sheep agent implements  Steppable so that it is possible for its position to be
analysed every step. for the use in this project it is best to think of every step as a
frame in a film.

6. Implementation of Design Page 58 of 133
Natalie Downe [cs1njd@bath.ac.uk]

To start with in the sheep class we have the class variables including (but not
limited   t)   a   local   copy   of   the   weighting   factors   of   cohesion   separation   and
alignment,   this   is   future   proofing   for   when   the   Subsumption   architecture
mentioned   in   the   previous   chapter   is   implemented   and   the   weights   need   to
change accordingly for each flock member. 
Other   details   soted   include   the   current   direction   in   radians   (needed   for   the
portrayals   to   implement   the   view)   and   the   current   direction   as   a   vector,   to
simplify the arithmetic.
The constructor of this class takes the flock  as  a flock object,  a sheep number
which will become the unique sheep identifier and whether the sheep is dominant
or not. The main thing the constructor does is populate the initiated variables
with information from the calling class, using getters and setters.
A   secondary   result   of   the   constructor   os   the   generating   of   the   sheep's   initial
random position and direction:
// generate random initial position ensureing that it is
posetive
double positionX = Math.abs(Math.random() *
containingFlock.getSimulationWidth());
double positionY = Math.abs(Math.random() *
containingFlock.getSimulationHeight());

// setting the new position


position = new Double2D(positionX, positionY);

// set the sheep facing a random direction


directionRadians = Math.PI * 2.0 * Math.random();

// calculating direction vector from this


directionVector = radiansToVector(directionRadians);

The   step   function   is   the   most   important   function   in   the   class   as   it   brings   in
together all the various different forces from alignment cohesion and separation
and eventually will incorporate the other relevant factors too. The step function is
calculated on every frame and the new position of the agent set.
The important highlight of this function is as follows:
// calculate cohesion alignment and avoidance
Double2D cohesionVector = cohesion(neighbours);
Double2D seperationVector = separation(neighbours);
Double2D alignmentVector = alignment(neighbours);
Calculate   avoidance   cohesion   alignment   and   separation   influence   on   direction

6. Implementation of Design Page 59 of 133
Natalie Downe [cs1njd@bath.ac.uk]

vector
newDirectionVectorX += cohesionVector.getX() +
seperationVector.getX() + alignmentVector.getX();
newDirectionVectorY += cohesionVector.getY() +
seperationVector.getY() + alignmentVector.getY();
    
Calculating the new position:
newPositionX = position.getX() + (newDirectionVectorX *
containingFlock.getSheepSpeed());
newPositionY = position.getY() + (newDirectionVectorY *
containingFlock.getSheepSpeed());
    
Setting the new position:
newPosition = new Double2D(newPositionX, newPositionY);
    
Ensure that both coordinates are on screen:
if((newPositionX >= 0.0) && (newPositionY >= 0.0) &&
(newPositionX <= containingFlock.getSimulationWidth()) &&
(newPositionY <= containingFlock.getSimulationHeight())) {
// both coordinates are on the screen
position = newPosition;
} else {
// future work implement random angle with respect to angle
of incedance
directionVector = radiansToVector(Math.PI * 2.0 *
Math.random());
}
    
Update new position on screen
containingFlock.setSheepLocation(this, position);

Moving on from here, the next function covers the ability to 'see the environment'
[chapter 5] and to obtain all the sheep within its sphere of influence – the flight
zone. With the method getNearSheep() the argument given is the flight zone of
the sheep (the current position of the sheep being looked at is already in a class
variable.   This   method  returns  a  bag   of  sheep,  this  is   one  of  MASON's  specific
ways of grouping objects and functions similarly to an array. This function just

6. Implementation of Design Page 60 of 133
Natalie Downe [cs1njd@bath.ac.uk]

pits   the   arguments   into   this   other   inherent   MASON   method


getObjectsWithinDistance(Double2D position, double distance, boolean toroidal,
boolean nonPointObjects, Bag result)
The separation,   alignment   and   cohesion  rules  function   very  much   in   a  similar
method to the one described in chapter 5.

Allignment
public Double2D alignment(Bag neighbours) {
debug("inside alignment method");
double resultingX = 0.0;
double resultingY = 0.0;
if((neighbours != null) && (neighbours.size() > 0)) {
// creating a copy of neighbours so that we dont
alter it
Bag tempNeighbours = new Bag(neighbours);
int numNeighbouringSheep = neighbours.size();
Sheep currentSheep;
for(int i = 0; i < numNeighbouringSheep; i++) {
try {
// looking at current sheep
currentSheep = (Sheep)tempNeighbours.get
(i);
if(currentSheep.getSheepNum() ==
sheepNum){
debug("looking at self in
sepparation");
continue;
}
// for every sheep get the direction and
add it to a running total
if(currentSheep.getDirectionVector() !
= null) {
resultingX +=
currentSheep.getDirectionVector().getX();
resultingY +=
currentSheep.getDirectionVector().getY();
}
} catch(ClassCastException
clastCastException) {
// have caught dog not sheep
continue;

6. Implementation of Design Page 61 of 133
Natalie Downe [cs1njd@bath.ac.uk]

}
}
// average out the calculated vector and
multiply by the alignment factor sent in flock.java
resultingX = (resultingX /
numNeighbouringSheep) * alignmentFactor;
resultingY = (resultingY /
numNeighbouringSheep) * alignmentFactor;
}
return new Double2D(resultingX, resultingY);
}

Separation
The separation rule, takes a bag of neighbouring sheep and  retuns the vector that
would lead away from the neighbours that are too close, it calculates the vector
away from each of the neighbouring sheep and scales this and then adds the unit
component of this vector to a running total returning the scaled version of this to
reflect the separation factor set in flock.
public Double2D separation(Bag neighbours) {
double resultingX = 0.0;
double resultingY = 0.0;
Double2D average;
Double2D vectorDifference;
double magnitude;
int numNeighbouringSheep = neighbours.size();
if((neighbours != null) && (neighbours.size() > 0)) {
// create copy of the current neighbours bag
Bag tempNeighbours = new Bag(neighbours);
Sheep currentSheep;
for(int i = 0; i < numNeighbouringSheep; i++) {
try{
// set the next sheep to be the next item
currentSheep = (Sheep)tempNeighbours.get(i);
if(currentSheep.getSheepNum() == sheepNum){
debug("looking at self in sepparation");
continue;
}
// calculate distance and average position

6. Implementation of Design Page 62 of 133
Natalie Downe [cs1njd@bath.ac.uk]

magnitude = Math.abs(currentSheep.getPosition
().distance(position));
// calculate return vector
vectorDifference = vectorDifference
(currentSheep.getPosition(), position);
// calculate unit vector and add to cumulitive
total
resultingX += (vectorDifference.getX() /
magnitude);
resultingY += (vectorDifference.getY() /
magnitude);
} catch(ClassCastException clastCastException) {
continue;
}
}
// calculate the resulting vector as a unit
vector scaled by the separation factor
resultingX = (resultingX * separationFactor);
resultingY = (resultingY * separationFactor);
//resultingX = (resultingX / (Math.abs
(position.distance(resultingX, resultingY)))) *
separationFactor;
//resultingY = (resultingY / (Math.abs
(position.distance(resultingX, resultingY)))) *
separationFactor;
}
// return calculated average
average = new Double2D(resultingX, resultingY);
return average;
}

Cohesion
Cohesion   rule,   takes   a   bag   of   neighbouring   sheep   and     retuns   the  vector   that
would lead toward the center of the flock, scaled to reflect the cohesion factor set
in flocks
public Double2D cohesion(Bag neighbours) {
Double2D cohesionVector;
Double2D scaledCohesionVector;
if((neighbours != null) && (neighbours.size() > 0)) {
// creating a copy of neighbours so that we

6. Implementation of Design Page 63 of 133
Natalie Downe [cs1njd@bath.ac.uk]

dont alter it
Bag tempNeighbours = new Bag(neighbours);
// calculate initial cohesion vector from
average positions of neighbours
cohesionVector = vectorDifference(position,
getAveragePosition(tempNeighbours));
// multiply calculated cohesion by the cohesion
factor specified in Flock
scaledCohesionVector = new Double2D
((cohesionVector.getX() * cohesionFactor), (cohesionVector.getY
() * cohesionFactor));
} else {
// the bag is null or empty so return zero
scaledCohesionVector = new Double2D(0.0, 0.0);
}
return scaledCohesionVector;
}
The following is used by the cohesion method to find the average position of a
bag of sheep
public Double2D getAveragePosition(Bag neighbours) {
// check that we havnt been given an empty bag
if((neighbours == null) || (neighbours.size()
<= 0)) {
throwError("Trying to calculate the average
position of an empty bag");
}
// create replicate so as not to alter original
Bag tempNeighbours = new Bag(neighbours);
double averagePositionX = 0.0;
double averagePositionY = 0.0;
int numNeighbouringSheep = tempNeighbours.size
();
Sheep currentSheep;
// go through each of the neighbouring sheep
and add position to running total
for(int i = 0; i < numNeighbouringSheep; i++) {
// set the next sheep to be the next item
try {
currentSheep = (Sheep)
tempNeighbours.get(i);

6. Implementation of Design Page 64 of 133
Natalie Downe [cs1njd@bath.ac.uk]

averagePositionX +=
(currentSheep.getPosition().getX());
averagePositionY +=
(currentSheep.getPosition().getY());
} catch(ClassCastException
clastCastException) {
// catching dog
continue;
}
}
// calculate average point
return new Double2D((averagePositionX /
numNeighbouringSheep), (averagePositionY /
numNeighbouringSheep));
}
The remainder of the class consists of the overridden methods for throwing an
error, debugging as well as all the getters and setters needed.

6.2.6) Sheepdog Agent


At the current state of implementation the Sheepdog moves in a random direction
at a constant speed till it comes across the field border where it changes direction
and moves off again. The level of detail in design of the system in Chapter 5 is
such that little re­analysis of the sheepdog would be need to be done in order to 

Summary
The above chapter shows how the core Reynolds rules [1987] were implemented
with a groundwork for further improvements as set out in Chapter 5.
The next  chapter   summarises   the  work  and   findings   of   the   whole   project   and
attempts to provide an unbiased critique as to its success.

6. Implementation of Design Page 65 of 133
Natalie Downe [cs1njd@bath.ac.uk]

7. Conclusion and Evaluation

7.1) Conclusions drawn


At   the   start   of   the   project   the   area   looked   at   was   diverse,   ranging   in   subject
matter   from   flocking   with   different   life   forms,   theories   on   the   hive   mind   and
predator   prey   interaction.   As   the   project   continued   and   the   research   in   the
Background Literature section [Chapter 2] was analysed, so the areas for possible
further   study   narrowed.   Eventually   it   became   clear   that   there   was   a   research
niche in the re­engineering of the flocking algorithms with the intent to model the
real life behaviour of sheep with sheepdogs.
Similar   exiting   systems   were   looked   at   and   questionnaires   were   sent   out   to
shepherds   all   over   the   world,   and   as   a   result,   another   area   of   previously
unexplored   territory   surfaced;   that   of   a   system   aimed   not   purely   at   the
furtherance   of   research   in   the  area  but   at   a   usable   system   for  shepherds   who
wished to either show the key elements in sheepdog trialling to friends and family
or to train shepherds who already had experience with working dogs but were yet
to compete in a trial environment [Chapter 3].
The key requirement of the system mentioned above however, was determined
that it had to be realistic to be of any use. This requirement leads back to the first
project  direction of the refinement of Reynolds' [1987] flocking algorithms  for
distributed agents to match the behaviour of sheep and sheepdogs.
Intensive  research  was   performed   through   analysing   literature   in   the   area   of
shepherding   such   as   'A   way   of   Life'   [Jones   et   al   1987]   and   others,   also   by
watching and analysing videos of sheepdog trials [S4C 2004][“one man and his
dog” 2004], further theories developed into how precisely to alter and utilise the
existing domain knowledge for application in this area [Chapter 4].
By far the most valuable insight into the changes needed however was obtained
through   personal   observation,   visiting   Mr   Aled   Owen   in   North   Wales   [Owen
2004][Appendix B2].  The information  gathered during the authors  visit  to  the
sheepdog training centre there has been utilised and referred to throughout the
project.
Information gathered from these valuable studies enabled the detailed design and
application of this research [Chapter 5]. Here, the main theories of this project
are developed and analysed with the intent of implementation.
The primary theories deduced within this dissertation and applied to the flocking
rules [Reynolds 1987] are as follows:
The flight­zone of the sheep is very important and essential to
succeeding in a realistic simulation. This is the zone considered
the   'sphere   of   influence   of   the   sheep'   it   is   used   for   the

7. Conclusion and Evaluation Page 66 of 133
Natalie Downe [cs1njd@bath.ac.uk]

neighbourhood of sheep considered to be its direct flock mates
as well as the distance at which the sheep is quite happy to have
the dog at. Any closer and depending on the speed of the dog,
the   sheep   will   tighten   its   flocking   tendencies   and   move   away
from the predator in the methods analysed in chapter 5. 
The   sheep   follow   a   reactive   agent   pattern   that   is   best
implemented using the Subsumption architecture [Brooks 1985]
A larger flock of sheep is easier to control than a smaller one. 
The position and speed of the sheepdog with respect to the flight
zone of the flock in general is important for determining how
fast the sheep will move away.
There are two different types of sheep that have to be modelled
if a full system was to be implemented: Light (hill raised) sheep,
and heavy (lowland born) sheep. These two types of sheep have
different characteristics, especially with regards to the radius of
their flight zone.
Dominant sheep are not unheard of and occasionally there will
be one or two dominant sheep in a flock (especially if they have
recently   given  birth).   Dominant   sheep  are  more   likely  to   stop
and   confront   a   dog   and   occasionally   be   physically   aggressive
toward it than the other flock members.
Tiredness can lead any sheep to become aggressive and turn to
face   the   dog.   Lowland   sheep   are  more   likely   to   become   tired
from running. The dog has to consider how fast it is making the
sheep move so as not to over exert them.
Pheromones and communication are also factors in the way the
sheep move, if one sheep can see a dog and the others cannot,
the remainder of the flock is quickly alerted to its presence, and
there has already been considerable research to show that this is
done   using  pheromones   as   a   communication   method   between
the sheep [Delgado­Mata 2004]. This behaviour especially can
not   be   modelled   by   the   flocking   rules   of   the   distributed
behavioural model alone. [Reynolds 1987]
If the dog is outside of the flock's flight zone, the sheep do not
commence avoidance, they neither help or hinder the efforts of
the   sheepdog,   this   is   called   a   semi   adversarial   environment
[Hebert et al 2003]
The sheepdog is a very complex predator, especially the methods
employed by the border collie, such as giving the sheep the eye
and dropping to the ground. Considerably more research would
be needed to analyse in detail the techniques needed to do this
creature justice.

7. Conclusion and Evaluation Page 67 of 133
Natalie Downe [cs1njd@bath.ac.uk]

The implementation section in Chapter 6 covers a detailed walk through of the
system implementation. Not all the requirements in Chapter 3 were implemented,
leaving the project as a proof of concept prototype for theories developed in the
project research.
The project concludes that the area covered is an interesting domain worthy of
future work. The response to the primary project question is that purely altering
the  work   of   Reynolds   [1987][1999]   will   not   lead   to   an   accurate   and   realistic
representation of sheep and sheepdogs.

7.2) Approach and Functional Evaluation


7.2.1) Functional Evaluation
As mentioned in the above section, not all of the requirements listed in chapter
three   have   been   implemented.   A   description   of   the   system's   current   features
follows.
1) Simulation
The simulation displays the agents in a visibly distinct manner, the sheep are
displayed as grey circles and the dog as a same sized black circle. At the time
of hand­in it was not possible to view the agents direction or speed visibly.
2) Sheep Behaviour
The cohesion, alignment and separation of the sheep is all fully functional and
the summation relates to the weighting defined in the Flock class.
The flight zone of each individual sheep is implemented and works.
Currently the sheep has no reaction to the sheepdog, this is left as an exercise
to the interested reader.
3) Sheepdog 
The sheepdog is displayed on the screen and is initiated in a random direction
because   the   part   of   the   system   where   the   user   input   was   taken   was   not
implemented,   an   approximation   of   the   movements   has   been   simplified   to
continue in a straight line until it hits the field edge at which point it skips that
step and changed to another random direction. 
In this simulation the dog is used merely to demonstrate the sheep's reaction.
4) Trialling 
The   game   is   timed,   however   none   of   the   other   trial   requirements   are
implemented.
5) Deployment.
The   simulation   is   available   as   a   web   applet,   this   makes   it   infinitely   more
deployable than having a stand alone application because in tat case the user

7. Conclusion and Evaluation Page 68 of 133
Natalie Downe [cs1njd@bath.ac.uk]

would   have  to   install   MASON   and   Java   and   then   try   to   get  the  simulation
working. 
With an applet admittedly the user does still have to install a Java plug­in,
however, this is a relatively simple operation and with a comprehensive install
document it should be accessible to all users.
All environment variables are set up in such a way that it is in a usable state
without altering any through the control panel.
6) Cross Platform considerations.
The system as an applet was tested on multiple Operating systems and web
browsers and deemed successful.
7) Usability
Further and intensive usability tests would have to be performed to evaluate
this requirement fully. Clear instructions are provided to the user and future
work   for   this   area   also   consists   of   a   document   for   novice   /   non   shepherds
describing the main principles of herding, this would facilitate further its use
as a training tool. 
To   accommodate   the   experienced   shepherds,   where   possible   the   correct
terminology has been used.

7.2.2) Methodologies and Approach Evaluation


The primary methodology used in the development of this system was the user
centred approach mentioned in Preece [2001]. For delivering a system that the
user is satisfied with, this is a very effective method. 
Ensuring the  users  are  involved  from   the very  beginning  not  only  aids   system
acceptance but ensures the system fits their needs better than if the developer had
only contacted them at each release of the requirements.
However, the use of this method invariably involves many iterations, spiralling
into a product where the user is satisfied with its functionality and usability. This
can be time consuming, in addition it can be difficult to gain access to the users
for the long time periods needed for this kind of approach.
The model view controller paradigm that was implemented with mason worked
well, sing this Agent based modelling system however there was no real choice as
to use it or not. Even though it was not a full implementation of the MVC the
resulting   framework   was   clear   and   understandable,   different   views   could   be
swapped in should the need arise, for example to insert a 3D visualisation instead
of the current Ariel 2D view, would be relatively simple thanks to this.
The   use   of   MASON   as   the   underlying   architecture   of   the   system   had   its
advantages   because   of   the   simple   and   flexible   application   [see   beginning   of
chapter   6].   However   it   would   have   been   a   further   improvement   had   the
visulaisation of the agents been more artistic. 

7. Conclusion and Evaluation Page 69 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Aiming at a non­technical audience it is invariably the 'looks' of the system that
count, one of the reasons why the Sheepgame has been so popular [Lewis, 2001
and 2003]. Perhaps now that 'Processing' has moved to a beta release it would be
an interesting development to the project to implement in this language and to
concentrate   further   on   the   usability   of   the   system   now   that   the   realism   and
adaption of existing flocking algorithms has been covered.

7.2.3) Project Achievements


From the Aims set out in the project introduction [Chapter 1], the primary aim of
this project was to investigate particular changes and refinements needed to apply
to Reynolds' [1987] algorithm with regards to Sheep and sheepdogs. 
Through   extensive   observation   and   research   the   project   has   succeeded   in
analysing and designing a solid basis for future implementations of the sheep and
sheepdog   environment   [see   detailed   conclusions   above].   Although   not   all   the
intended requirements have been met, the design and application of research is to
a sufficient level, that the interested reader could take the current specifications
and   without   too   much   further   refinement   could   implement   the   remainder   as
intended.

7.2.4) Personal Project Critique


Taken from the Aims in the project introduction, it was stated that the project
would truly test the authors abilities. I believe this to be entirely correct, I found
this project an exciting challenge, it was quite aside from any other project done
throughout my academic and professional career. 
As was mentioned in the dissertation to the project, prior to its start I had never
done anything remotely similar and was unaware of any of the computational
theories related to flocking, or the complexities of working dogs with sheep.
Throughout   the   process   of   this   dissertation,   I   believe   I   have   learnt   about   the
subject area in detail. The observations I have made build upon the work and
research in the existing knowledge domain and pave the way for future research.
One thing that would ensure the increased application of the work done here,
would   be   to   complete   further   observations   and   asses   the   repeatability   and
reliability of the conclusions drawn.
As  an  incidental  result  of   the project,   I also  believe  I  have increased  my   Java
ability and learnt some of the intricacies involved in writing a Dissertation.

7.3) Further Work: Building on this Project


This project intends to serve as a proof of concept to the interested reader who
wishes to build on the findings in this report and further improve the resulting
system.   A   number   of   areas   are   suggested   where   either   further   research,
implementation of testing would be beneficial to improve the final result.

7. Conclusion and Evaluation Page 70 of 133
Natalie Downe [cs1njd@bath.ac.uk]

7.3.1) Implementation aspects to be improved


Unfortunately not all the requirements were implemented, however as mentioned
previously, a lot of the design is detailed enough that some of these requirements
could be implemented without much hassle.
Looking  at the areas of  implementation that have yet  to be completed,  please
refer back to the requirements document in chapter 3, the requirements regarding
the sheepdog and its behaviour, the sheep's interaction with the dog is also not
fully completed. However the design in chapter 5 is  enough for most  of these
requirements to be implemented without further analysis.
The trial requiments were also left as an exercise to the interested reader. [see
chapter 3]. Other elements of implemetation that could be explored is the flight
zone of the flock and how it ioncreaces with the number of members in that flock.
Also the theory [Owen 2004] that a larger flock is easier to control than a smaller
one.
The  random  factor  in  all  aspects   of  the  simulation   should  also   be  explored  in
more detail.
Portability could be an issue to address, there may be scope for other devices such
as   hand­held   PCs,   not   an   essential   requirement   but   one   of   the   Questionnaires
mentioned this may be s useful feature. 
Dominant   sheep   choices   for   situations   where   the   dog   is   confronted.
Implementation of the theory of the dog making the sheep speed up the closer it
gets to them.  Further refinement of the fear theory and development of a scale
rather than a switch to detect the dog would be an interesting idea. 
Intensive   study   into   the   other   'steering   behaviour'   rules   from   Reynolds   [1999]
should   be   looked   at,   especially   with   regards   to   obstacle   avodance   and   field
boundarys.

7.3.2) Areas of further research


Further   research   would   be   needed   in   order   to   determine   a   better   and   more
realistic system. Research such as:
The type of of dog and how likely it is to give 'the eye' or use other forms  of
intimidation experience on the sheep, the effects of instinct and obedience on the
behaviour of the dog when around the sheep.
The extent to which pheromones have an influence on the behaviour of the sheep.
Another interesting area would be to note if the dog could pick up the smell of
fear from the sheep. 
One further thing that has to be considered in the development of this project is
the learning capabilities of the dogs and sheep. In order to accurately simulate
the model over time the sheepdog has to learn the best way of manoeuvring the
sheep with the smallest amount  of stress caused to the sheep,  sheep may also

7. Conclusion and Evaluation Page 71 of 133
Natalie Downe [cs1njd@bath.ac.uk]

have a limited learning capability.
The   program   could   also   act   as   an   interactive   tool   for   research   into   flocking
techniques of sheep in various different environments, for example the effect of
terrain   or  temperature,   and   the   differences   between   different   breeds   and   wild
sheep could also be investigated.

7.3.3) Future testing plans


Intensive usability testing on both Shepherds  and non­shepherds  would ensure
the systems applicability in the field, whether or not it would be useful.
Once the system is complete, white box testing could be used to analyse if the
code does what it intends to.
Black box testing could also be used to analyse the behaviour of the system.

7.4) Final word


In conclusion it can be said that it is primarily due to the ambitious nature of the
project requirements that the implementation of the system was not completed. 
However,   extensive   research   was   carried   out   throughout   the   project   and   as   a
result,   some   interesting   findings   have   been   found,   these   were   covered   in   the
conclusion above in addition as was an overview of the answer of the project's
main question  “How can the traditional flocking rules of the Reynolds distributed
behavioural model be refined, to reflect the Semi­adversarial environment of sheep
and sheepdogs?”
A critical analysis of the methodologies and approaches used has been provided
and further work to build on this project has been identified. The findings of this
dissertation could be used as  a basis  for a more 'system­development'  oriented
approach of a similar idea.

7. Conclusion and Evaluation Page 72 of 133
Natalie Downe [cs1njd@bath.ac.uk]

References and Bibliography

AOYAGI, M.,  NARNATAME A (2003) “Massive individual based simulation:
forming and reforming of flocking behaviours” National defence academy,
Japan 
BALAN, G., CIOFFI­REVILLA, C., LUKE, S., PANAIT, L., PAUS, S., (2003)
“Mason: A Java Multi­Agent Simulation Library” [on­line], Fairfax: George
Mason University, In proceedings from the Agent 2003 Conference.
Available from:
http://cs.gmu.edu/~eclab/projects/mason/publications/Agent2003.pdf
[Accessed: 4 January 2005]
BARTLETT, M., (1979) “A novice look at Puppy Aptitude Testing” published in
Pure Bred Dogs, American Kennel Gazette.
BONABEAU, E., DORIGO, M., THERAULAZ, G., (1999). “Swarm Intelligence:
From Natural to Artificial Systems” New York: Oxford University Press
BROOKS, R. A., (1985) “A robust layered control system for a multi layered
robot” [on­line] Massachusetts Institute of Technology, Artificial Intelligence
Laboratory. 
Available from:
https://dspace.mit.edu/bitstream/1721.1/6432/2/AIM­864.pdf 
COBB, R., (2005) “An Introduction to Sheep Behaviour” [on­line], Illinois: Illini
SheepNet, Available from:
http://www.traill.uiuc.edu//sheepnet/paperDisplay.cfm?ContentID=1
[Accessed: 4 January 2005]
DIX, A., FINLAY, J., ABOWD, G. D., BEALE, R., (2004) “Human Computer
Interaction” third edition, Harlow, Essex: Prentice Hall
DELGADO­MATA, C., (2004) “Characterising Emotion Signalling and Affected
Group Behaviour in Virtual Mammals” [on­line], Manchester: University of
Salford, Available from: 
http://ceur­ws.org/Vol­97/IVEVAFinal_S2_04.pdf   
[Accessed: 15 November 2004]
ELLIOT, E., KIEL, L. D., (2004) “Agent­Based Modeling in the Social and
Behavioural Sciences” Published in Non­linear Dynamics, Psychology and
Life Sciences, Vol 8 Number 2. 
Publisher: The Society for Chaos Theory in Psychology & Life Sciences 
GRAND, S,. (2000). “Creation life and how to make it.” Massachusetts: Harvard
GAMMA et al (2000) Design Paterns: Elements of Reusable Object­Oriented
Software, Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides –
Addison Wesley Professional computing series foreword by grady booch

References and Bibliography  Page 73 of 133
Natalie Downe [cs1njd@bath.ac.uk]

University Press
HEBERT, A. J., DORAN, M. V., BROWN, C. H., (2003). “Simulation of Animal
Behaviours Using Robotic Agents” [on­line], Alabama: University of South
Alabama, Available from:
http://www.cis.usouthal.edu/~doran/public/pdfs/Simulation%20of%
20Animal%20Behaviors%20Using%20Robotic%20Agents.pdf 
[Accessed: 10 November 2004]
KLEIN, J,. (2002) “BREVE: a 3D Environment for the simulation of Decentralised
Systems and Artificial Life” [on­line], Sweden and Amherst: Chalmers
University of Technology, Goeteborg University and Hampshire College,
Available from: 
http://www.spiderland.com/breve  
[Accessed: 4 January 2005]
JOHNSON, S., (2001) “Emergence: The connected lives of ants brains cities and
software” Allen Lane, The Penguin Press
JONES, H. G., COLLINS, B. C., (1897). “A Way of Life: sheepdog Training,
Handling and trialling.” Ipswich: Farming Press Limited.  
LEWIS, D., (2004), Sheepgame v3 [on­line] Available from: 
http://www.david­lewis.com/sg3/index.php 
LEWIS, D., (2001), Sheepgame v1 [on­line] Available from:
http://www.sheepgame.co.uk/
MINAR, N., BERKHART, R., LANGTON, C., ASKENAZI, M., (1996), “The swarm
simulation system: a toolkit for building multi agent simulations ” [on­line]
Available from: http://www.swarm.org/archive/overview.ps 
[Accessed: 12 April 2005]
MINSKY, M., (1985) The Society of Mind, New York: Simon and Schuster
NICKLESS, A., WATSON, G,. (2004), “The working sheepdog” [on­line] Available
from: http://www.workingsheepdog.co.uk/sheepdog­training­
terminology.htm 
[Accessed: 12 April 2005]
PARTRIDGE, D., (1986) “Artificial Intelligence: Applications in the future of
software engineering” John Wiley & Sons (page 91)
PREECE, J., ROGERS, Y., SHARP, H., (2002) “Interaction Design: Beyond
Human­Computer Interaction”, New York: John Wiley & Sons, Inc. 
OWEN, A., (2004) Personal communication, North Wales: 2 November 2004 
[see Appendix B2]  
REYNOLDS, C. W., (1987). “Flocks, Herds and Schools: A Distributed
Behavioural Model.” Computer Graphics SIGGRAPH '87, Volume 21(4),
Pages 25­34.

References and Bibliography  Page 74 of 133
Natalie Downe [cs1njd@bath.ac.uk]

REYNOLDS, C. W., (1999). “Steering Behaviours For Autonomous Characters”
[on­line], California: Sony Computer Entertainment America, Computer
Graphics SIGGRAPH 99, 
Available from: http://act­
r.psy.cmu.edu/people/douglass/Douglass/Agents/PDF/Steering_Behaviors.p
df  [Accessed: 21 November 2004]
S4C (2004) Video, Filmed in Bala, Wales, by Cynhrchiad for Teesgop on the S4C
channel. Video of the “Treialon cwn defaio Rhyngwlaool” sheepdog trials
2004.
SPECTOR, L., KLEIN, J., PERRY, C., FEINSTEIN, M. (2003) “Emergence of
Collective Behaviour in Evolving Populations of Flying Agents”[on­line]
Proceedings of the Genetic and Evolutionary Computation Conference
(GECCO­2003). Berlin: Springer­Verlag. pp. 61­73. 
Editors: In E. Cantu­Paz, J.A. Foster, K. Deb, L.D. Davis, R. Roy, U.­M. O'Reilly,
H.­G. Beyer, R. Standish, G. Kendall, S. Wilson, M. Harman, J. Wegener, D.
Dasgupta. M.A. Potter, A.C. Schultz, K.A. Dowsland, N. Jonoska, J. Miller
Available from http://hampshire.edu/lspector/pubs/spector­gecco2003.pdf
[Accessed on 12 April 2005]
TAUBE, M,. (1961). “Computers and Common Sense: The Myth of Thinking
Machines.” New York: Columbia University Press.
WILDBERGER, A. M., (1996) “Introduction & overview of ‘Artificial Life’ –
Evolving Intelligent Agents for Modelling and Simulation.” Proceedings of
the 1996 Winter Simulation Conference, ed. J. M. Charnes, D. J. Morrice, D.
T. Brunner, and J. J. Swain, Pages 161­168.
WOOLDRIDGE, M., (1966) “An Introduction to Multi Agent Systems.” 2nd
Edition (2002), West Sussex: John Wiley & Sons Ltd.
“One man and his Dog” (2004), Video, London: filmed in Holker Hall, Grange
over Sands, Cumbria, on 24th/25th July 2004

Further Information: References


http://www.usbcha.com/Rules.htm ­ sanctioning body for sheepdog trials
throughout the United States
http://www.swarm.org/wiki/Introduction_to_Swarm Information on the SWARM
simulation environment
http://www.faintinggoat.com/ International Fainting Goat Association IFGA 1999
http://www.isds.org.uk/  International Sheepdog Society
http://en.wikipedia.org/wiki/Flock  Wikipedia, the on­line encyclopaedia.
http://www.beheco.oupjournals.org/cgi/reprint/15/1/158  Kin   selection   and
reciprocity   in   flight   formation?   2003   Malte   Andersson   and   Johan   Wallander

References and Bibliography  Page 75 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Department of Zoology, Göteborg University, Box 463, SE 405 30 Gothenburg, Sweden
http://www.popsci.com/popsci/science/article/0,20967,390918,00.html  Dan   Koeppel
2001 Massive Attack
http://www.massivesoftware.com/index.html  Massive technology solutions
Massive 2001
http://www.findarticles.com/p/articles/mi_m0PAM/is_139/ai_112861526
Where's massive? Past, present and future for the Lord of the Rings' crowd
software Metro Magazine,  Wntr, 2004  by Miles Merrill
http://beheco.oupjournals.org/cgi/reprint/15/1/158.pdf flock formation in
Vshape on desktop

Image accreditation
Page 15 – Photo of Birds flocking, taken by Chris and is available under the
Creative Commons 'Attribution­NonCommercial­NoDerivs' 2.0 licence.
[http://flickr.com/photos/candl/8066163/]
Page 19 – Screen shot from 'Sheepgame', developed by David Lewis:
[http://www.david­lewis.com/sg3/index.php]
Pages 17 and 98 – Drawing of sheep used in diagrams, by Jens Pagotto. 
[http://island­three.net/]
[All remaining images were taken by the Author]

References and Bibliography  Page 76 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Appendix A: Screen-shots

Further screen­shots can be found at:~
http://www.flickr.com/photos/nataliedowne/tags/dissertation/

Screen-shot at Start

Screen-shot at time 11

Appendix A: Screen­shots Page 77 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Screen-shot at time 19

Screen-shot at time 45

Appendix A: Screen­shots Page 78 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Appendix A: Screen­shots Page 79 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Appendix A: Screen­shots Page 80 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Appendix B: Further Information

B1) Questionnaire
B1.1) email sent to working sheepdog mailing list and
the Border Collie interest list

Hello,

My   name   is   Natalie   Downe   and   I   am   a   final   year   computer   scientist   at   Bath


University. My degree project is making a simulation of the flocking behaviour of
sheep with a sheepdog in a trialling situation, and I am looking for people who
would not mind filling in a short questionnaire.

The aim of the project, other than just making the simulation the possibility of
using this as a training tool for potential shepherds or as a demo tool to show
people who do not have the facilities, the basics of shepherding in a sheepdog
trial.

The simulation is currently in development and will, once completed be an aerial
view of a basic trial course (not including penning) with some sheep and a dog.
The dog will take input from the user similar to how the sheepdog is controlled in
a trial.

I   have   done   a   lot   of   research   into   the   behaviour   of   sheep   and   sheepdogs,
including spending some time in Wales at the invitation of Mr Aled Owen who
kindly let me watch him training sheepdogs and herding sheep and helped me
with my research. So with any luck the simulation will be reasonably realistic.

I am currently looking for people to fill in a short  questionnaire on your own
experience learning to compete in trials and for opinions as to whether you think
the sort of project demo / training tool would be useful to you or people you
know.

I would very much appreciate it if you could fill in the below questionnaire and
send it back to me at natalie@natbat.co.uk, any responses will greatly help me
with  my   research.  If  you  have  any  further  questions   please   do  not  hesitate  to
contact me. 

Kind Regards,
Natalie

Appendix B: Further Information Page 81 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Appendix B: Further Information Page 82 of 133
Natalie Downe [cs1njd@bath.ac.uk]

***************************** Questionnaire *****************************

1) How did you get involved in sheepdog trialling? 
   (please delete as appropriate, you can choose more than one)
a) "I was involved in shepherding from a young age"
b) "trialling was why I got involved with shepherding"
c) "I had a friend who had done trialling and got me involved"
d) "It was something I always wanted to do"
e) "I went to a sheepdog trial and it looked like fun"
f) other (please state): 

2) How did you learn how to compete in sheepdog trials 
   (please delete as appropriate, you can choose more than one)
a) Taught by friend / family member
b) Self Taught
c) Observation
c) Books
d) Videos
e) computer based media (e.g. CD ROM or websites) 
           please state details of media its key features 
           (e.g. demonstrations, photos, details of scoring etc.): 

3) If you answered c, d or e to the above question please state authors and 
   titles and details of how it helped you learn:

4) Do you feel that it would have helped you learn to compete in sheepdog trials
   if you had had a computer simulation such as the one mentioned above? 
   (Please state yes or no and then reasons for your answer)

5) If you had access to such a system now, do you feel that you would use it 
   to demonstrate to friends / family what exactly is involved in trialling? 
   (Please state yes or no and then reasons for your answer)

6) Any Further comments

*** Thank you for taking the time to fill in this questionnaire. ***

­ would you mind being contacted to help test the completed system? 
  Yes / No (please delete as appropriate)

­   would   you   like   to   be   sent   a   copy   of   the   report   and   simulation   when   it   is
completed?  
  Yes / No (please delete as appropriate)

************************************************************************

Appendix B: Further Information Page 83 of 133
Natalie Downe [cs1njd@bath.ac.uk]

B1.2) Responses
B1.2.1) Response One

> 1) How did you get involved in sheepdog trialling?
a) "I was involved in shepherding from a  young age

> 2) How did you learn how to compete in sheepdog trials
b) Self Taught

> 4) Do you feel that it would have helped you learn to compete in sheepdog
trials
>   if you had had a computer simulation such as the one mentioned above?
I feel it would help some people when they are starting in trials

> 5) If you had access to such a system now, do you feel that you would use it
>   to demonstrate to friends / family what exactly is involved in trialling?
I would use it to show people as a lot of people do not understand how dogs
work sheep and trialling

> ­ would you mind being contacted to help test the completed system?  
No, please contact me 

> ­ would you like to be sent a copy of the report and simulation when it is
> completed? 
Yes

B1.2.2) Response Two

> 1) How did you get involved in sheepdog trialling?
d) "It was something I always wanted to do"

> 2) How did you learn how to compete in sheepdog trials
c) Books
d) Videos
e) computer based media (e.g. CD ROM or websites)

Going to sheepdog trainers has been the main way I have started but have
also   used   books,   videos   and   the   Smartgroups   facility   as   a   learning   tool.
Videos I find more helpful as obviously more visual for someone like me,
who   has   no   natural   sheep   sense   and   does   not   come   from   a   sheep
background.  I have a degree so can't be completely stupid but learning how
to handle sheep dogs and sheep is definitely the hardest thing I have ever
done!

Appendix B: Further Information Page 84 of 133
Natalie Downe [cs1njd@bath.ac.uk]

> 3) If you answered c, d or e to the above question please state authors and
> titles and details of how it helped you learn:
 
Derek   Scrimgeour   videos   and   DVDs   ­   the   last   one   I   have   found   the   most
useful as shows more of what can go wrong and this is usually what happens
to me! Derek Scrimgeour's book, Julie Simpson's book, Ewe were made for
Me video and Bruce
Engelfield's video, Barbara Carpenter book.
 
Found the Derek Scrimgeour book the most useful book out of the ones I
have.   Have found all the videos quite useful but as I said, the new Derek
Scrimgeour DVD is the one I prefer at the moment.

> 4) Do you feel that it would have helped you learn to compete in sheepdog
trials
> if you had had a computer simulation such as the one mentioned above?
Don't   know   but   the   simulation   on   the   International   sheepdog   trial   TV
programme   was   very   interesting.     I   have   done   agility   in   the   past   and
although I like to learn software programs at work from books, I find I need
to see sheepdog training more visually.

It was a Welsh TV programme that showed a simulation of the trial so that
viewers would understand the course.  It looked a little like Subbuteo as the
sheep,   from   what   I   remember,   seemed   to   glide   sideways.     It   was   S4C   or
whatever is the name of the TV company that films programmes in Wales. 

> 5) If you had access to such a system now, do you feel that you would use it
> to demonstrate to friends / family what exactly is involved in trialling?
Yes ­ would also be interesting to show my students as they cover computer
simulations as part of their exam courses at school.  My part­time hobby is
always a source of interest at school!

> ­ would you mind to being contacted to help test the completed system? 
No ­ I am sure my students at school would love to!

>   would   you   like   to   be   sent   a   copy   of   the   report   and   simulation   when   it   is
completed? 
Yes 

B1.2.3) Response Three

> 1) How did you get involved in sheepdog trialling?
b) "trialling was why I got involved with shepherding"
f)  other  (please  state):   My  daughter  bought  a  Border  Collie  Pup and  we
wanted to train it.

Appendix B: Further Information Page 85 of 133
Natalie Downe [cs1njd@bath.ac.uk]

> 2) How did you learn how to compete in sheepdog trials
b) Self Taught
c) Observation
c) Books
d) Videos

> 3) If you answered c, d or e to the above question please state authors and
>    titles and details of how it helped you learn:  
Nearly  every book written  along  with  videos by Tony Collins,  Glyn Jones,
Mike Hubbard, and especially Martin Penfold

> 4) Do you feel that it would have helped you learn to compete in sheepdog
> trials if you had had a computer simulation such as the one mentioned above?
I really can't answer until I have a better concept of just what it will entail.  I
look forward to the finished product.

> 5) If you had access to such a system now, do you feel that you would use it
>    to demonstrate to friends / family what exactly is involved in trialling?
Yes, providing the content is realistic.

> 6) Any Further comments
I greatly enjoyed my visit to Bath in 2003.  Please give my best to my friends
Aled and Jano Owen when you next speak to them. 

> ­ would you mind to being contacted to help test the completed system? 
No

> ­ would you like to be sent a copy of the report and simulation when it is
> completed? 
Yes 

B1.2.4) Response Four

>  1) How did you get involved in sheepdog trialling?
a) "I was involved in shepherding from a young age"

>  2) How did you learn how to compete in sheepdog trials
a) Taught by friend / family member
b) Self Taught
c) Observation
c) Books
d) Videos

>  3) If you answered c, d or e to the above question please state authors and
>  titles and details of how it helped you learn:
Books and videos help to reinforce a concept that you have come across, ie. a

Appendix B: Further Information Page 86 of 133
Natalie Downe [cs1njd@bath.ac.uk]

certain   part   of   training   a   dog   here   are   many,   the   further   you   get   into
sheepdog   trialling.   The   first   ones  that   I   used   were  Glyn   Jones   books   and
videos

>  4) Do you feel that it would have helped you learn to compete in sheepdog
> trials if you had had a computer simulation such as the one mentioned above?
It's not vital but I would give it a go and then tell you the answer to that.

>  5) If you had access to such a system now, do you feel that you would use it
>  to demonstrate to friends / family what exactly is involved in trialling?
Yes, if it was any good.

>  6) Any Further comments
Please   let   me   know   how   your   research   is   going.   I   am   involved   with   co­
ordinating training within the ISDS and maybe we can use your simulation
to recruit young shepherds who need to learn how to run a dog.

Please   bear   in   mind   that   many   people   on   the   working­sheepdog   list   are
general border collie enthusiasts, they often claim to work their dogs, but it
is often not to the standard found in a sheepdog trial. All I am saying is that
there is a difference. Maybe this does not matter to your work.

>  ­ would you mind being contacted to help test the completed system? 
No I would like to help

>  ­ would you like to be sent a copy of the report and simulation when it is
>  completed? 
Yes  (please delete as appropriate)

B1.2.5) Response Five

> 1) How did you get involved in sheepdog trialling?
b) "trialling was why I got involved with shepherding"
c) "I had a friend who had done trialling and got me involved"
e) "I went to a sheepdog trial and it looked like fun"

> 2) How did you learn how to compete in sheepdog trials
a) Taught by friend
b) Self Taught
c) Observation
c) Books
d) Videos

> 3) If you answered c, d or e to the above question please state authors and
> titles and details of how it helped you learn:
Virgil Holland's book, Colin Gordon's book on judging, G. Jones book. Rural

Appendix B: Further Information Page 87 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Route  Videos,  G. Jones video.  Was able to understand  concepts,  exercises


and see how the dog was supposed to work.

> 4) Do you feel that it would have helped you learn to compete in sheepdog
trials
> if you had had a computer simulation such as the one mentioned above?
Don't know for sure since have never seen one before!

> 5) If you had access to such a system now, do you feel that you would use it
> to demonstrate to friends / family what exactly is involved in trialling?
Yes   ­   it   would   be   interesting   to   show   others   what   it   is   like,   use   as   a
teaching/learning tool.

> 6) Any Further comments
Sounds very interesting.  I'll  look forward  to viewing  the demo and seeing
what it is like!

> ­ would you mind being contacted to help test the completed system? 
Yes

> ­ would you like to be sent a copy of the report  and simulation when it is
completed? 
Yes

B1.2.6) Response Six

> 1) How did you get involved in sheepdog trialling?
c) "I had a friend who had done trialling and got me involved"
e) "I went to a sheepdog trial and it looked like fun"
f) I got very interested in the breed and its work so trialling was the next
stage for me

> 2) How did you learn how to compete in sheepdog trials
a) Taught by friend / family member
c) Observation
c) Books

> 3) If you answered c, d or e to the above question please state authors and
> titles and details of how it helped you learn:
Training sheepdogs ­ Thomas Longton & Barbars Sykes
This book helped me a lot as the training methods were close to the ones I
had been taught

A Way of Life ­ H.Glyn Jones
this book inspired me to learn more about the Border Collie even though I
had owned them for a few years this book got me more involved with the

Appendix B: Further Information Page 88 of 133
Natalie Downe [cs1njd@bath.ac.uk]

working dog.

Talking sheepdogs ­ Derek Scrimgeour
Having had Derek over to give a couple of training courses I really liked his
method of training and this book has helped me alter some of my ways of
training for the better

> 4) Do you feel that it would have helped you learn to compete in sheepdog
trials
> if you had had a computer simulation such as the one mentioned above?
No as when trialling , the sheep are so very different at just about every trial
so   what   with   the   weather   as   a   factor   and   nerves   trialling   conditions   are
never the same.

If all  the different conditions  could  be evaluated on screen  then  maybe a


computer   simulation   might   help   but   there   is   no   better   way   to   gain
experience than a real trial situation.

> 5) If you had access to such a system now, do you feel that you would use it
> to demonstrate to friends / family what exactly is involved in trialling?
Yes ­ to show others just what trialling is about if they have never been able
to get to a trial themselves.

I suppose it is better to sit in the comfort of your own home to show what
trials are really like than to stand out in gale­force winds and torrential rain
when  the person you are trying to show  what trials are cannot really see
what  is going  on  as you are both  shut in the car  unable to see the trials
field!!!

> 6) Any Further comments
I'd like to see a computer simulation but not sure it would help me but am
always willing to give anything a go

> ­ would you mind being contacted to help test the completed system?
No

> ­ would you like to be sent a copy of the report  and simulation when it is
completed? 
Yes

B1.2.7) Response Seven


> 1) How did you get involved in sheepdog trialling?
a) "I was involved in shepherding from a young age"
d) "It was something I always wanted to do"

Appendix B: Further Information Page 89 of 133
Natalie Downe [cs1njd@bath.ac.uk]

> 2) How did you learn how to compete in sheepdog trials
b) Self Taught
c) Observation

I started by having to learn as I went along during every day
work.

> 4) Do you feel that it would have helped you learn to compete in sheepdog
trials
>  if you had had a computer simulation such as the one mentioned above?
Probably Yes it may have helped to learn to compete in a trial but I'm not
sure it would be of much use to someone who had never worked a dog.

> 5) If you had access to such a system now, do you feel that you would use it
>  to demonstrate to friends / family what exactly is involved in trialling?
Yes. I do quite a bit of teaching and think it would be a very useful aid in
putting over a point.

> 6) Any Further comments
One would have to see it before one could really evaluate the usefulness of
such an aid.

> ­ would you mind being contacted to help test the completed system?
No I wouldn't mind.

> ­ would you like to be sent a copy of the report  and simulation when it is
completed?
Yes

B1.2.8) Response Eight

>  1) How did you get involved in sheepdog trialling?
We rescued a Border Collie almost 3 years ago and as she grew she exhibited
her inbred instincts so we contacted a local trainer. We took her up one day
and put her in a pen to see how she'd react around a small flock and she
went right to work, no commands. The trainer offered to buy here then and
there! Instead he's working with us to train her. We've been to a couple local
trials and are really amazed by the work the dogs do, and knowing our dog
is capable of it, we want to train her well enough to trial. 

Now   we   have   two   rescued   Border   Collies   and   will   put   them   both   into
training again this summer. Unfortunately we don't have our own sheep and
working them at the trainer's is season because of the very long nights in the
winter and the spring lambing season.

Appendix B: Further Information Page 90 of 133
Natalie Downe [cs1njd@bath.ac.uk]

>  2) How did you learn how to compete in sheepdog trials
Learning currently. Haven't been in a trial as of yet.

> 4) Do you feel that it would have helped you learn to compete in sheepdog
> trials if you had had a computer simulation such as the one mentioned above?
No. The best learning, to me, is hands on with an excellent trainer.

>  5) If you had access to such a system now, do you feel that you would use
> it to demonstrate to friends / family what exactly is involved in trialling?
A computer based program would be fun to watch, but I'm not sure it would
be a good learning tool. You can't take it onto the field with you in case you
get stuck. The user would have to take the dog off the field, go back in the
house, run the program and scroll through to the area where they're having
problems. Then go back outside and start up again. 

If the   user  had  a  hand  held  device  or  a  small  weather  proof  laptop,   that
might help, but not everyone can afford to do that.  A trainer on the field
with you is much cheaper and offers immediate help and correction while
the user and the dog are still working.
>  ­ would you mind being contacted to help test the completed system?
Yes / No (please delete as appropriate)

>  ­ would you like to be sent a copy of the report and simulation when it is
> completed?
Yes

B1.2.9) Response Nine

> 1) How did you get involved in sheepdog trialling?
e) "I went to a sheepdog trial and it looked like fun"
f) other (please state):   I had seen it demonstrated several times & when I
adopted my first BC, I thought he might enjoy doing it.

> 2) How did you learn how to compete in sheepdog trials
a) Taught by friend / family member

> 4) Do you feel that it would have helped you learn to compete in sheepdog
> trials if you had had a computer simulation such as the one mentioned above?
Yes ­ sometimes I don't know what to do in certain situations and it would be
nice to have already thought them through before the situation arises in the
field.

> 5) If you had access to such a system now, do you feel that you would use it
> to demonstrate to friends / family what exactly is involved in trialling?
Yes ­ I like to share information.

Appendix B: Further Information Page 91 of 133
Natalie Downe [cs1njd@bath.ac.uk]

> 6) Any Further comments
I think this would be useful to any herding trial competitor who is computer
literate.  It may not reach an older or more rural population.

> ­ would you mind being contacted to help test the completed system?
No ­ please do!  Sounds like fun!

> ­ would you like to be sent a copy of the report and simulation when it is
> completed?
Yes please!

Appendix B: Further Information Page 92 of 133
Natalie Downe [cs1njd@bath.ac.uk]

B2) Report from Field research


B2.1) Introduction
I made the decision to travel to a working sheepdog farm, in order to get accurate
view   of   the   problem   by   observing   the   situation   first   hand,   instead   of   purely
through books and papers on the subject.
I   was   lucky   enough   to   be   able   to   interview   Mr   Aled   Owen   (from
http://www.aled­owen­sheepdogs.co.uk/).   Aled   is   internationally   renowned   as
one of the major authorities on sheepdogs and shepherding, his accolades include
amongst others:
World sheepdog trials Champion 2002
International sheepdog Society Supreme Champion
1999 & 2000
7 times winner of Welsh Open Championship
8  times   winner  of  North  Wales  sheepdog  Society
Open Championship
Winner of BBC TV 'One Man and his Dog' doubles
title
3 times winner of Welsh National Championship
5 times Welsh Aggregate Champion
I spent the day observing the use of about 10 different dogs of varying abilities, in
both   general   shepherding   purposes   (such   as   separating   the   lame   sheep   for
treatment) and in the training of new dogs. Aled owns and runs a sheepdog and
shepherd training college in north Wales.

B2.2 trialling vs. General shepherding


shepherding has been around for hundreds of years, trialling came about out of a
desire to have some quantifiable measure of a shepherds skill.
The two situations however represent very different  ways  of working with the
sheep. For example in certain situations in the general course of shepherding, it
may be necessary for a dog to grip a sheep to keep it in line, however in trialling
this is illegal and can lead to disqualification. 
The   other   major   difference   between   trialling   and   general   shepherding   is   the
removal   of   any   physical   influences   of   the   shepherd   themselves.   In   general
shepherding practices it is very common to use oneself as a ‘weak sheepdog’ to
add another level of control to the sheep and also as an extra indicator to the dog
(see section 4).
In general, sheepdog trialling is more predictable and, by its very nature there is

Appendix B: Further Information Page 93 of 133
Natalie Downe [cs1njd@bath.ac.uk]

increased regulation than general shepherding. There are varying factors that are
monitored in trialling, for example shape of the field makes a big difference to the
ease of control and manoeuvrability; i.e. with an oddly shaped field it may be
difficult for the dog to get behind the sheep to move them.
Another factor may include the amount of mothers and lambs  in the flock,  as
lambs are more rebellious and determined, and natural instinct leads the mothers
to be protective and harder to move. Mother sheep are more likely to become
dominant and stand up to the dog, male sheep also have this rebellious instinct in
them naturally.
Other   notable   observations   in   general   shepherding   difficulties   that   are   not   as
prominent in trialling include methods to encourage sheep to go through roads,
the main method for this appears to be the dog to bring up the rear sheep, then
the   shepherd   to   walk   in   the   middle   of   the   road   and   herd   to   keep   the   flock
moving.
Sheep can predict where to go under some circumstances which is why after each
person in a trial has had their turn, a new set of sheep are brought in to prevent
the flock becoming ‘dogged’ and just automatically heading toward the gate.
In trialling the sheep and sheepdog are nearly always in sight, however in the
daily life of a shepherd the dog may not actually always be in sight. When this
happens the dog uses its initiative and native herding instincts, to predict where
the farmer wants the sheep, which is mostly back inside the farmers line of sight. 
An interesting fact to note is that a dog whistle can carry over half a mile, the dog
will still respond to this but there will be a time delay so there is some degree of
‘prediction’ on the part of the farmer as to when to give the signal, accounting for
distance delay.

B2.3) Shedding in general shepherding


Shedding is the process of separating
one sheep or a selection of sheep for
various   different   reasons,   for
example if a sheep is lame and needs
to be treated.

4
1 3
Dog

It   is   a   particularly   difficult   skill   to   perfect,


using   an   ideal   method,   the   shepherd   will
identify a sheep to separate to the dog using Shepherd
body language and direction signals, the dog
then   works   on   getting   this   sheep   on   the Figure B2.3a
outside of the flock. 

Appendix B: Further Information Page 94 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Once on the outside, the dog can then concentrate on the majority of the flock
while the farmer steps between the sheep and the flock, facing the lone sheep.
Both the farmer and the sheepdog then concentrate on both parts of the flock as
they move the lone sheep further from the flock. [At this  point refer to  figure
B2.3a]  for if the sheep move towards  the dog, the dog moves and then keeps
them   in  track   and  moves   back.   The  sheep   are  likely   to   take   advantage   of   the
farmer who is acting as a ‘weak sheepdog’
It is very important  throughout the whole exercise that the shepherd does not
loose sight of either the main flock or the chosen sheep. Even when the dog has
control of the main flock body, the shepherd while tending to the chosen sheep
should never turn his back on the others.

B2.4) Training with 2 dogs


Training with two dogs can sometimes be an advantage, especially if there is a
very large flock, however if the same two dogs get too used to working with each
other, it can disable their ability in the long run, they may become too reliant on
each other and end up becoming left or right handed. If this were to happen, the
dog   is  then  rendered  less   useful  in  the  long  run  as   they   are  now   less  able   to
switch to the other side.
It is sometimes necessary to use two dogs for shepherding, however for the most
part   the   shepherd   generally   acts   as   a   weaker   version   of   the  dog;   keeping   the
sheep in line. The sheep will however take every opportunity to try the shepherd
as they have more respect for the power of the dog
The generally accepted solution to this is for the shepherd to periodically swap
places with the dog and to cooperate as such.

B2.5) Importance of the shepherd


The   main   advantage   of   the   shepherd   being
involved   in   the   rounding   up   or   directing   of
sheep   is   to   direct   the   dog   when   they   are
unsure   instinctively.   The   dog   can   normally
'guess' where the farmer wants the sheep to be
and, if the dog is experienced, how it would go
about getting them there. 
On a number of occasions throughout the time
spent   in  Wales   with   Aled   Owen,   I   witnessed
the dog using its instincts to control the sheep,
in   one   case   the   world   champion   sheepdog
'Bob' was let into a field with about 10 sheep
and instinctively knew that Aled wanted the sheep brought to him. Bob rounded
up the sheep and brought them to the fence where I was standing.
Dogs also respond highly to body language as well as to signalling, for example

Appendix B: Further Information Page 95 of 133
Natalie Downe [cs1njd@bath.ac.uk]

during shedding the farmer can direct using his arms and direction which way he
wishes the dog to go about separating individual sheep. One point to note with
this is that the dog will concentrate on the sheep that the shepherd is facing.
As mentioned previously the shepherd can be used as a sort of 'weak sheepdog'
where  the  dog   is the  strong   control   point  to   the   sheep   and   the  shepherd   will
occasionally cross paths and swap places with the dog to allow the dog to move
some of the sheep and the shepherd will keep the others at bay.
Another point well worth noting relates to the training of sheepdogs from each
other, it is common practice to put different level dogs in a field together with the
sheep in the event that the younger and more inexperienced dogs will learn some
of the tricks of the trade from the more experienced dog. 

B2.6) Issues when controlling the sheep


Sheep flock as with many animals for the primary reason of safety in numbers,
when being chased in the wild their lives are at stake and staying in a flock is
primarily a selfish act. 
The breeds themselves have evolved through both natural selection and selective
breeding to have qualities such as fine wool, good meat and easy control through
flocking. Where these sheep have evolved has a great effect on the nature of their
flock behaviour.
Although Flocking is a natural instinct of sheep, it isn't until the flock is under
threat that the sheep feel the need for safety in numbers. It is a lesser known fact
that   sheep,   like   many   animals,   can   communicate   in  pheromones,   signalling   to
other sheep that they are under threat, causing the flock to cohere together.
From the shepherds point of view, Aled Owen mentioned that an entire flock is
easier to control than a small number, say 5 sheep. 

B2.6.1) Light sheep


Light sheep are those that have been reared on the hills, they are naturally flighty
and will run at a moments notice. 
To understand the types of sheep further we must first take note of the 'flight
zone' of the individual sheep. This  concept  relates to the 'safety bubble' of the
sheep, the zone in which it feels the dog is 'too close'.
The flight zone can be easily explained by the below diagrams. Light sheep have a
large flight zone, of about 30 yards – this means that if the dog comes too close
too fast [Figure B2.6.1b] the sheep will scatter, but just the right distance away at
the edge of the flight zone and moving at a constant speed [Figure B2.6.1a] and
the sheep will move slowly in a forward direction.
Although light sheep run faster and are more skittish, they will still not hesitate to
turn and fight the dog when they get out of breath.

Appendix B: Further Information Page 96 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Dog

Dog

Dog
Figure Figure
B2.6.1a B2.6.1c

Figure
B2.6.1b

B2.7.2) Heavy sheep


Heavy sheep are more likely to stop and stare or even nip at a dog instead of
running, their flight zone is smaller [about 10 yards] having evolved from  the
heavy lowland sheep, it takes them less to get out of breath and their cohesion as
a group is generally stronger than that of the light hill sheep.
Border   collies   are   generally   known   to   be   better   at   gauging   the   flight   zone   or
safety   bubble   of   the   sheep   flock   than   other   dogs   such   as   South   England   and
Scottish dogs.

B2.7) Dominant sheep


Dominant sheep are a problem when herding, dominant sheep can occur for a
number of reasons but it is by no means rare for a sheep to take more initiative
than the rest of its flock mates when confronted with a dog.
The primary reason for dominant sheep is the mothers maternal instinct over its
young, if there are lambs in the flock then the mothers will be naturally protective
and hence more likely to stand up to a sheepdog than it would normally. Also the
number of males in the flock has an effect on this too as male sheep are naturally
more aggressive than female sheep.
The   best   way   for   a   dog   to   handle   the   dominant   sheep   is   to   concentrate   its

Appendix B: Further Information Page 97 of 133
Natalie Downe [cs1njd@bath.ac.uk]

attention onto it and move slowly toward it. Border collies have a particularly
good method for dealing with dominant sheep which appears to gain the sheeps'
trust and respect; it is know generally in the trade as 'the eye'.
The   Eye   is   where   the   dog   will   crouch   down   to   the   ground   and   stare   at   the
intended   sheep   until   it   backs   down   and   becomes   recessive.   A   very   successful
method   which   is   another   reason   why   the   border   collie   makes   such   a   good
sheepdog, other dogs in the same situation may go straight to the sheep and give
them a small nip to gain control.
The border collie my in some cases be justified in nipping [gripping] the sheep, if
there are two dominant sheep in a flock (which in a trial situation is very unlucky
indeed as gripping is not allowed and the shepherd may not leave their post) then
the dog may grip the sheep to shock it into complying while the dog can then
concentrate its attentions on the second offending sheep. 
It is very much an issue of trust, if the sheep do not feel comfortable with the dog
then they are more likely to turn and get aggressive. If the dog panics, the sheep
are also likely to panic and the shepherd will then have to intervene. With two
dominant   sheep   it   can   sometimes   be   advisable   for   the   shepherd   to   help   out
regardless.
The   shepherd   can   help   the   dog   out   as   mentioned
previously,   where  the  farmer   keeps   the   sheep   at   bay   by
acting as a weak sheepdog, and then swapping with the
dog   once   they   have   moved   the   other   sheep   to   a   more
preferable location.

In a badly controlled situation it has been known for two dominant sheep to split
the flock, so some follow one and the others split off. This can be quite difficult to
recover from, though the best plan is to ease off and be patient with the sheep
while the dog regains its hold over them from a wide angle.

B2.8) sheepdogs and Training


At   one   point   in  Wales,   two   puppies
who   had   never   seen   sheep   before,
were let loose in the field with Gwen
(an older and more experienced dog)
and the 6 sheep pictured to the left. 
Although neither dog had seen sheep
before and both were from the same
litter,   each   reacted   very   differently
when they saw the sheep. One ran at
the sheep and demonstrated clear, if
rather over zealous herding instincts. 

Appendix B: Further Information Page 98 of 133
Natalie Downe [cs1njd@bath.ac.uk]

The other sheepdog puppy decided it would be far more fun to herd us spectators
instead. This demonstrates that the extreme differences in personality a dog can
have are partly nature as well as nurture. 
Although the First puppy may appear the best choice for a champion sheepdog,
this is not always the case. With many handlers, it is the energy that is important
as an inherent skill and not the honed instinct. 
A problem with inexperienced dogs, is that the instinct can get them carried away
and they may go that little bit too far and actually try to attack and eat the sheep.
On the  other  hand  dogs  that   are weak   and  nervous   around  the  sheep  will  be
exploited by the flock and not respected as a source of direction and control.

Notes
Some interesting facts to note with regards to shepherding:
The   dogs   all   have   1   syllable
names   to   make   calling   them
easier.
Verbal commands are used for
young   dogs   until   they   have
learnt their meanings then they
are switched to whistles.
The whistle itself can be heard
up to half a mile away even if
the dog is out of sight. In this
case time delay has to be taken
into account.
Recommended sources of information were given as: http://www.isds.org.uk/
http://www.workingsheepdog.org/, The book considered to be the best source
of information for my purposes was 'H Glyn Jones talks to Barbara C Collins'.
It was mentioned in my discussion with Aled Owen, that the system planned for
this project may be of some use in training young shepherds, or as a demo to the
public to simulate a trial situation.
Either way, the signals for the dog and the behaviour of the interaction between
sheep and dog would have to be within a certain degree of realism for the system
to be of any practical use.

Appendix B: Further Information Page 99 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Appendix C: Source code

C1) SheepFlockWithUI.java
/**
* @author Natalie Downe :: natalie@natbat.co.uk
* @see http://www.natbat.co.uk/
*/

package uk.co.natbat.sheep;
import java.awt.Color;
import javax.swing.JFrame;
import sim.display.Console;
import sim.display.Controller;
import sim.display.Display2D;
import sim.display.GUIState;
import sim.engine.SimState;
import sim.field.continuous.Continuous2D;
import sim.portrayal.continuous.ContinuousPortrayal2D;

/**
* Class to combine the flock simulation with the Mason GUI
* @see http://cs.gmu.edu/~eclab/projects/mason/
*/
public class SheepFlockWithUI extends GUIState {

// initialsing mason speific variables


public Display2D display;
public JFrame displayFrame;
ContinuousPortrayal2D sheepFlockPortrayal = new
ContinuousPortrayal2D();
Continuous2D simulation;

// width and height have to be synchronised with Flock.java


public double simulationWidth = 500.00;
public double simulationHeight = 500.00;

// Background colour of dark green

Appendix C: Source code Page 100 of 133
Natalie Downe [cs1njd@bath.ac.uk]

//public Color backgroundColour = new Color(0, 80, 0);


// Background colour of dark green
public Color backgroundColour = new Color(255, 255, 255);
//public Color sheepColour = new Color(159, 113, 80);
public Color sheepColour = new Color(207, 207, 207);
public Color dogColour = new Color(0, 0, 0);
public int sheepSize = 10;
public int dogSize = 6;

public void init(Controller c) {

super.init(c);
Flock flock = (Flock)state;
// set up the display window
display = new Display2D(simulationWidth, simulationHeight,
this, 1);
displayFrame = display.createFrame();
// regester the frame so it appears in the "Display"
list
c.registerFrame(displayFrame);
displayFrame.setVisible(true);

// attach the portrayal we have created


display.attach(sheepFlockPortrayal, "Sheep Flock");

display.setBackdrop(backgroundColour);
displayFrame.setTitle("Natalie Downe: Final Year
Project");
}

// Explicit costructor initiates the flock from the


superclass using time as seed
public SheepFlockWithUI() {
super(new Flock(System.currentTimeMillis()));
simulation = ((Flock)this.state).getSimulation();
}

// Explicit costructor that takes a state


public SheepFlockWithUI(SimState state) {
super(state);

Appendix C: Source code Page 101 of 133
Natalie Downe [cs1njd@bath.ac.uk]

public static void main(String[] args) {


// creating new flock by calling SheepFlockWithUI() with
currentTimeMillis
SheepFlockWithUI sheepFlock = new SheepFlockWithUI();

// initiating console
Console c = new Console(sheepFlock);
c.setVisible(true);
}

// defined in super - allows user to alter preferences in


GUI
public Object getSimulationInspectedObject() {
return state;
}

// getter for the name of the flock


public String getName() {
return "Natalie Downe: Final Year Project";
}

public String getInfo() {


// insert HTML index.html into root directory
return
"<H2>Natalie Downe: Final Year Project</H2>" +
"<p>Program to simulate the flocking of sheep and the
interaction with sheepdogs</p>";
}

// load the simulation


public void load(SimState state) {
super.load(state);
setupPortrayals();
}

// start the simulation


public void start() {
super.start();

Appendix C: Source code Page 102 of 133
Natalie Downe [cs1njd@bath.ac.uk]

setupPortrayals();
// reschedule the displayer
display.reset();
display.repaint();
}

public void setupPortrayals() {

// obstacle portrayal needs no setup here but may in


future
// set the portrayal to look at the simulation set up in
Flock.java
sheepFlockPortrayal.setField(simulation);

// what the entities [sheep and dogs] look like


// may want to change colour of dominant sheep here
later
//sheepFlockPortrayal.setPortrayalForClass(Sheep.class,
new sim.portrayal.simple.RectanglePortrayal2D(Color.white));
sheepFlockPortrayal.setPortrayalForClass(Sheep.class,
new sim.portrayal.simple.OvalPortrayal2D(sheepColour,
sheepSize));
sheepFlockPortrayal.setPortrayalForClass(Dog.class, new
sim.portrayal.simple.OvalPortrayal2D(dogColour, sheepSize));

public void finish() {


super.finish();
}

// quit the simulation


public void quit() {
super.quit();
if (displayFrame != null) {
displayFrame.dispose();
}
displayFrame = null;
display = null;
}

Appendix C: Source code Page 103 of 133
Natalie Downe [cs1njd@bath.ac.uk]

C2) Flock.java
/**
* @author Natalie Downe :: natalie@natbat.co.uk
* @see http://www.natbat.co.uk/
*/

package uk.co.natbat.sheep;
import java.util.Random;
import sim.engine.Schedule;
import sim.engine.SimState;
import sim.field.continuous.Continuous2D;
import sim.util.Double2D;

/**
* Controls the generation of the simulation
*/
public class Flock extends SimState {

// simulation variables
public double scaleFactor = 4.0; // eg 4: 4m = 1cm
// width and height have to be syncronised with
SheepFlockWithUI.java
private static Continuous2D simulation;
private double simulationWidth = 500.00;
private double simulationHeight = 500.00;
private double bucketSize = 50; //
file:///home/nat/Desktop/Programs/mason9/docs/classdocs/sim/fiel
d/continuous/Continuous2D.html

// sheep flock variables


public int numSheep = 30;
public double probOfDominantSheep = 0.1; // mother or male
sheep
// change to something sensible
public double flightZoneRadius = 40.0; // measured in

Appendix C: Source code Page 104 of 133
Natalie Downe [cs1njd@bath.ac.uk]

'meters' drawn at 1 centimeter for 'scaleFactor' number of


meters
public double sheepSpeed = 0.2; //0.015; //0.2; // max
speed - measured in kilometers per hour - 1kmph = 28 centimeters
per second then scaled
public double doggedness = 1.0; // range from 1-10 where 1
is new sheep and 10 is well used/trained sheep

// dog variables
public int numDogs = 1;

// flock vector variables


// these are all set at 1 currently but will need to be
changed to reflect reaserch
public double cohesion = 0.3;
public double alignment = 2.0;
public double separation = 1.0;
public double consistency = 1.0;
public double randomness = 1.0;

public void start() {


System.out.println("F: start() - entering start
method");
}

// generates a flock using random number from given seed


public Flock(long seed) {
super(new ec.util.MersenneTwisterFast(seed), new
Schedule(1));
System.out.println("F: entering constructor that takes a
long seed");
// initiate the simulation environment where the
objects will be added
simulation = new Continuous2D(bucketSize,
simulationWidth, simulationHeight);

// initiate the desired ammount of sheep


for(int sheepNum = 1; sheepNum <= numSheep;
sheepNum++) {
System.out.println("F: initiating sheep number "
+ sheepNum + " of " + numSheep);

Appendix C: Source code Page 105 of 133
Natalie Downe [cs1njd@bath.ac.uk]

// decide if this sheep will be a dominant


sheep
Random randomNumberGenerator = new Random
(System.currentTimeMillis());
int randNum = randomNumberGenerator.nextInt
(100);
boolean dominant = false;
if(randNum < (100 * probOfDominantSheep)) {
dominant = true;
System.out.println("F: dominant");
} else {
System.out.println("F: not dominant");
}

// initiate sheep
Sheep sheep = new Sheep(this, dominant,
sheepNum);
System.out.println("F: sheep initiated");
simulation.setObjectLocation(sheep,
sheep.getPosition());
System.out.println("F: setting the location in
the flock class");
schedule.scheduleRepeating(sheep);
System.out.println("F: sheep set to repeat");
}

// initiate the desired ammount of dogs


// system designed for one dog more than one dog
interaction working together
for(int dogNum = 1; dogNum <= numDogs; dogNum++) {
System.out.println("F: initiating dog");
Dog dog = new Dog(this, dogNum);
schedule.scheduleRepeating(dog);
}
System.out.println("F: finished initiating dog");

public static void main(String[] args) {


System.out.println("F: entering main method");

Appendix C: Source code Page 106 of 133
Natalie Downe [cs1njd@bath.ac.uk]

//doLoop(Flock.class, args);
Flock flock = new Flock(System.currentTimeMillis());
flock.start();
long steps;
do {
if (!flock.schedule.step(flock))
break;
steps = flock.schedule.getSteps();
if (steps % 500 == 0)
System.out.println("Steps: " + steps + " Time: "
+ flock.schedule.time());
}
while(steps < 5000);
flock.finish();
System.exit(0); // make sure any threads finish up
}

// set up inheritance and have one method instead of these


two
/*public void setAnimalLocation(Animal thisAnimal, Double2D
position) {
simulation.setObjectLocation(thisAnimal, position);
}*/
// Set location of current sheep in continuous 2D
public void setSheepLocation(Sheep thisSheep, Double2D
position) {
simulation.setObjectLocation(thisSheep, position);
}
// Set location of current sheep in continuous 2D
public void setDogLocation(Dog thisDog, Double2D position)
{
simulation.setObjectLocation(thisDog, position);
}

// Eclipse generated Getters and Setters for private class


variables
/**
* @return Returns the simulation.
*/

Appendix C: Source code Page 107 of 133
Natalie Downe [cs1njd@bath.ac.uk]

public Continuous2D getSimulation() {


return simulation;
}
/**
* @param simulation The simulation to set.
*/
public void setSimulation(Continuous2D simulationGiven) {
Flock.simulation = simulationGiven;
}
/**
* @return Returns the doggedness.
*/
public double getDoggedness() {
return doggedness;
}
/**
* @param doggedness The doggedness to set.
*/
public void setDoggedness(double doggedness) {
this.doggedness = doggedness;
}
/**
* @return Returns the flightZoneRadius.
*/
public double getFlightZoneRadius() {
return flightZoneRadius;
}
/**
* @param flightZoneRadius The flightZoneRadius to set.
*/
public void setFlightZoneRadius(double flightZoneRadius) {
this.flightZoneRadius = flightZoneRadius;
}
/**
* @return Returns the simulationHeight.
*/
public double getSimulationHeight() {
return simulationHeight;
}
/**

Appendix C: Source code Page 108 of 133
Natalie Downe [cs1njd@bath.ac.uk]

* @param simulationHeight The simulationHeight to set.


*/
public void setSimulationHeight(double simulationHeight) {
this.simulationHeight = simulationHeight;
}
/**
* @return Returns the simulationWidth.
*/
public double getSimulationWidth() {
return simulationWidth;
}
/**
* @param simulationWidth The simulationWidth to set.
*/
public void setSimulationWidth(double simulationWidth) {
this.simulationWidth = simulationWidth;
}
/**
* @return Returns the avoidance.
*/
public double getAlignment() {
return alignment;
}
/**
* @return Returns the cohesion.
*/
public double getCohesion() {
return cohesion;
}
/**
* @return Returns the consistency.
*/
public double getConsistency() {
return consistency;
}
/**
* @return Returns the numDogs.
*/
public int getNumDogs() {
return numDogs;

Appendix C: Source code Page 109 of 133
Natalie Downe [cs1njd@bath.ac.uk]

}
/**
* @return Returns the numSheep.
*/
public int getNumSheep() {
return numSheep;
}
/**
* @return Returns the randomness.
*/
public double getRandomness() {
return randomness;
}
/**
* @return Returns the sheepSpeed.
*/
public double getSheepSpeed() {
return sheepSpeed;
}
/**
* @return Returns the separation.
*/
public double getSeparation() {
return separation;
}
/**
* @return Returns the bucketSize. - size of the
discrezation of the continuous2D
*/
public double getBucketSize() {
return bucketSize;
}
/**
* @param bucketSize The bucketSize to set. - size of the
discrezation of the continuous2D
*/
public void setBucketSize(double bucketSize) {
this.bucketSize = bucketSize;
}
/**

Appendix C: Source code Page 110 of 133
Natalie Downe [cs1njd@bath.ac.uk]

* @return Returns the probOfDominantSheep.


*/
public double getProbOfDominantSheep() {
return probOfDominantSheep;
}
/**
* @param probOfDominantSheep The probOfDominantSheep to
set.
*/
public void setProbOfDominantSheep(double
probOfDominantSheep) {
this.probOfDominantSheep = probOfDominantSheep;
}
/**
* @return Returns the scaleFactor.
*/
public double getScaleFactor() {
return scaleFactor;
}
/**
* @param scaleFactor The scaleFactor to set.
*/
public void setScaleFactor(double scaleFactor) {
this.scaleFactor = scaleFactor;
}
/**
* @param alignment The alignment to set.
*/
public void setAlignment(double alignment) {
this.alignment = alignment;
}
/**
* @param cohesion The cohesion to set.
*/
public void setCohesion(double cohesion) {
this.cohesion = cohesion;
}
/**
* @param consistency The consistency to set.
*/

Appendix C: Source code Page 111 of 133
Natalie Downe [cs1njd@bath.ac.uk]

public void setConsistency(double consistency) {


this.consistency = consistency;
}
/**
* @param numDogs The numDogs to set.
*/
public void setNumDogs(int numDogs) {
this.numDogs = numDogs;
}
/**
* @param numSheep The numSheep to set.
*/
public void setNumSheep(int numSheep) {
this.numSheep = numSheep;
}
/**
* @param randomness The randomness to set.
*/
public void setRandomness(double randomness) {
this.randomness = randomness;
}
/**
* @param separation The separation to set.
*/
public void setSeparation(double separation) {
this.separation = separation;
}
/**
* @param sheepSpeed The sheepSpeed to set.
*/
public void setSheepSpeed(double sheepSpeed) {
this.sheepSpeed = sheepSpeed;
}
}

C3) Animal.java
/**

Appendix C: Source code Page 112 of 133
Natalie Downe [cs1njd@bath.ac.uk]

* @author Natalie Downe :: natalie@natbat.co.uk


* @see http://www.natbat.co.uk/
*/

package uk.co.natbat.sheep;
import sim.engine.SimState;
import sim.engine.Steppable;
import sim.util.Bag;
import sim.util.Double2D;

public class Animal {


/**
* Takes a direction in radians and converts to a unit vector
to allow for easyer calculation
* assumes: Top-left of screen = (0,0) <- through testing
* Down and right = posetive <- through
testing
* East (right) = 0 radians <- common
assumption
*
* @param radians
* @return
*/
public Double2D radiansToVector(double radians) {

// local variables
double vectorX;
double vectorY;

// check for slim possibility that radians is negative


if(radians < 0) {
throwError("Unable to calculate unit vector from
radians, 'radians' equals zero!");
}

if(radians >= (1.5 * Math.PI)) {


// sheep pointing between north and east (including
due east and due north)
if(radians == (1.5 * Math.PI)) {
// due North

Appendix C: Source code Page 113 of 133
Natalie Downe [cs1njd@bath.ac.uk]

vectorX = 0.0;
vectorY = -1.0;
} else if(radians == (2 * Math.PI)) {
// due East
vectorX = 1.0;
vectorY = 0.0;
} else {
// between North and east
vectorX = Math.abs(Math.sin((Math.PI * 2) -
radians));
vectorY = (-1) * (Math.abs(Math.cos((Math.PI * 2)
- radians)));
}
} else if(radians >= Math.PI) {
// sheep pointing between west and north (including
due west)
if(radians == Math.PI) {
// due West
vectorX = -1.0;
vectorY = 0.0;
} else {
// between West and North
vectorX = (-1) * (Math.abs(Math.sin(radians -
Math.PI)));
vectorY = (-1) * (Math.abs(Math.cos(radians -
Math.PI)));
}
} else if(radians >= (Math.PI / 2)) {
// sheep pointing between south and west (including
due south)
if(radians == (Math.PI / 2)) {
// due South
vectorX = 0.0;
vectorY = 1.0;
} else {
// between south and west
vectorX = (-1) * (Math.abs(Math.sin(Math.PI -
radians)));
vectorY = Math.abs(Math.cos(Math.PI - radians));
}

Appendix C: Source code Page 114 of 133
Natalie Downe [cs1njd@bath.ac.uk]

} else {
// sheep pointing between east and south (including
due east)
if(radians == 0) {
// due East
vectorX = 1.0;
vectorY = 0.0;
} else {
// between east and south
vectorX = Math.abs(Math.sin(radians));
vectorY = Math.abs(Math.cos(radians));
}
}

// return calculated unit vector


return new Double2D(vectorX, vectorY);
}

/**
* Given two points calculates the vector to travel from the
first to the second
*
* @param Double2D fromPosition
* @param Double2D toPosition
* @return Double2D vector difference
*/
protected Double2D vectorDifference(Double2D fromPosition,
Double2D toPosition) {
return new Double2D(toPosition.getX() - fromPosition.getX
(), toPosition.getY() - fromPosition.getY());
}

/**
* stops the program running and throws the error with the
error message given
*
* @param errorMessage - String, what went wrong in the
program
*/
public void throwError(String errorMessage) {

Appendix C: Source code Page 115 of 133
Natalie Downe [cs1njd@bath.ac.uk]

System.out.println("died: '"+errorMessage+"'");
throw new RuntimeException("died: '"+errorMessage+"'");
}

/**
* prints out a message complete with the sheep number - less
typing!
* @param debugMessage - String, what is going on in the
program
*/
protected void debug(String debugMessage){
System.out.println(": "+debugMessage);
}
}

C4) Sheep.java
/**
* @author Natalie Downe :: natalie@natbat.co.uk
* @see http://www.natbat.co.uk/
*/

package uk.co.natbat.sheep;
import sim.engine.SimState;
import sim.engine.Steppable;
import sim.util.Bag;
import sim.util.Double2D;

public class Sheep implements Steppable,


sim.portrayal.Oriented2D {

// flock details
private Flock containingFlock;
private double flightZoneRadius;

// flock behaviour variables


private double cohesionFactor;
private double alignmentFactor;
private double separationFactor;

Appendix C: Source code Page 116 of 133
Natalie Downe [cs1njd@bath.ac.uk]

// sheep details
private int sheepNum;
private Double2D position; // (0,0) as defined by mason is
the top left of the screen left & up = negative
private Double2D directionVector;
private double directionRadians;

/**
* Sheep constructor takes the flock as a flock object, a
sheep number and whether the sheep is dominant or not
*
* @param Flock initContainingFlock
* @param boolean initDominantSheep
* @param int generatedSheepNum
*/
public Sheep(Flock initContainingFlock, boolean
initDominantSheep, int generatedSheepNum) {

// populating variables
containingFlock = initContainingFlock;
cohesionFactor = containingFlock.getCohesion();
alignmentFactor = containingFlock.getAlignment();
separationFactor = containingFlock.getSeparation();
sheepNum = generatedSheepNum;
flightZoneRadius =
containingFlock.getFlightZoneRadius();

// generate random initial position ensureing that it


is posetive
double positionX = Math.abs(Math.random() *
containingFlock.getSimulationWidth());
double positionY = Math.abs(Math.random() *
containingFlock.getSimulationHeight());

// setting the new position


position = new Double2D(positionX, positionY);

// set the sheep facing a random direction


directionRadians = Math.PI * 2.0 * Math.random();

Appendix C: Source code Page 117 of 133
Natalie Downe [cs1njd@bath.ac.uk]

// calculating direction vector from this


directionVector = radiansToVector(directionRadians);
}

/**
* every step of the process what happenes to the sheep
* @see sim.engine.Steppable#step(sim.engine.SimState)
*/
public void step(SimState state) {

// local variables
Double2D newPosition;
double newPositionX;
double newPositionY;
Double2D newDirectionVector;
double newDirectionVectorX = directionVector.getX();
double newDirectionVectorY = directionVector.getY();
Bag neighbours = getNearSheep
(containingFlock.getFlightZoneRadius());

// calculate cohesion alignment and avoidance


Double2D cohesionVector = cohesion(neighbours);
Double2D seperationVector = separation(neighbours);
Double2D alignmentVector = alignment(neighbours);

// calculate avoidance cohesion alignment and


separation influence on direction vector
newDirectionVectorX += cohesionVector.getX() +
seperationVector.getX() + alignmentVector.getX();
newDirectionVectorY += cohesionVector.getY() +
seperationVector.getY() + alignmentVector.getY();

// new position if there are no dogs/ other threat


arround
// uncomment when implemented dog surround logic with
if statements, if there is no dog
//newDirectionVectorX = directionVector.getX();
newDirectionVectorY = directionVector.getY();
//newPositionX = position.getX() +

Appendix C: Source code Page 118 of 133
Natalie Downe [cs1njd@bath.ac.uk]

(directionVector.getX() * containingFlock.getSheepSpeed());
//newPositionY = position.getY() +
(directionVector.getY() * containingFlock.getSheepSpeed());
// otherwise there is infleuce from flocking
variables calculated above and the speed is faster
/*try {
// again if there are no dogs arround the sheep will
pause for a random amount of time
this.wait((long)(Math.random() * 20));
} catch (InterruptedException e) {
e.printStackTrace();
throwError("wait [sheep eating grass when no threat]
was interupted");
}*/

newPositionX = position.getX() + (newDirectionVectorX *


containingFlock.getSheepSpeed());
newPositionY = position.getY() + (newDirectionVectorY *
containingFlock.getSheepSpeed());

// calculate radians and update class variable

newPosition = new Double2D(newPositionX, newPositionY);

// test for real values of the intended new position


coodrdinate
if((newPositionX >= 0.0) && (newPositionY >= 0.0) &&
(newPositionX <= containingFlock.getSimulationWidth()) &&
(newPositionY <= containingFlock.getSimulationHeight())) {
// both coordinates are on the screen
position = newPosition;
} else {
// implement random angle with respect to angle of
incedance
directionVector = radiansToVector(Math.PI * 2.0 *
Math.random());
}

// update new position on screen


containingFlock.setSheepLocation(this, position);

Appendix C: Source code Page 119 of 133
Natalie Downe [cs1njd@bath.ac.uk]

/**
* Given the flight zone of the sheep work out all the
neighbouring sheep and return in a bag
* using: Bag getObjectsWithinDistance(Double2D position,
double distance, boolean toroidal, boolean nonPointObjects, Bag
result)
*
* @param flightZoneRadius
* @return Bag of near sheep
*/
public Bag getNearSheep(double flightZoneRadius) {
return containingFlock.getSimulation().
getObjectsWithinDistance(position, flightZoneRadius, true,
true);
}

/**
* Separation rule, takes a bag of neighbouring sheep and
* retuns the vector that would lead away from the
neighbous that are too close
*
* calculates the vector away from each of the neighbouring
sheeps,
* scales this and then adds the unit component of this
vector to a running total
* returning the scaled version of this to reflect the
separation factor set in flock.
*
* @param Bag neighbours
* @return Double2D scaledCohesionVector
*/
public Double2D alignment(Bag neighbours) {

debug("inside alignment method");

double resultingX = 0.0;


double resultingY = 0.0;

Appendix C: Source code Page 120 of 133
Natalie Downe [cs1njd@bath.ac.uk]

if((neighbours != null) && (neighbours.size() > 0)) {

// creating a copy of neighbours so that we


dont alter it
Bag tempNeighbours = new Bag(neighbours);
int numNeighbouringSheep = neighbours.size();
Sheep currentSheep;

for(int i = 0; i < numNeighbouringSheep; i++) {

try {
// looking at current sheep
currentSheep = (Sheep)
tempNeighbours.get(i);

if(currentSheep.getSheepNum() ==
sheepNum){
debug("looking at self in
sepparation");
continue;
}

// for every sheep get the direction


and add it to a running total
if(currentSheep.getDirectionVector
() != null) {
resultingX +=
currentSheep.getDirectionVector().getX();
resultingY +=
currentSheep.getDirectionVector().getY();
}
} catch(ClassCastException
clastCastException) {
// have caught dog not sheep
continue;
}
}
// average out the calculated vector and
multiply by the alignment factor sent in flock.java
resultingX = (resultingX /
numNeighbouringSheep) * alignmentFactor;

Appendix C: Source code Page 121 of 133
Natalie Downe [cs1njd@bath.ac.uk]

resultingY = (resultingY /
numNeighbouringSheep) * alignmentFactor;
}
return new Double2D(resultingX, resultingY);
}

/**
* Separation rule, takes a bag of neighbouring sheep and
* retuns the vector that would lead away from the
neighbous that are too close
*
* calculates the vector away from each of the neighbouring
sheeps,
* scales this and then adds the unit component of this
vector to a running total
* returning the scaled version of this to reflect the
separation factor set in flock.
*
* @param Bag neighbours
* @return Double2D scaledCohesionVector
*/
public Double2D separation(Bag neighbours) {
double resultingX = 0.0;
double resultingY = 0.0;
Double2D average;
Double2D vectorDifference;
double magnitude;
int numNeighbouringSheep = neighbours.size();

if((neighbours != null) && (neighbours.size() > 0)) {

// create copy of the current neighbors bag in


order to presrve
Bag tempNeighbours = new Bag(neighbours);
Sheep currentSheep;

for(int i = 0; i < numNeighbouringSheep; i++) {

try{
// set the next sheep to be the next

Appendix C: Source code Page 122 of 133
Natalie Downe [cs1njd@bath.ac.uk]

item
currentSheep = (Sheep)
tempNeighbours.get(i);

if(currentSheep.getSheepNum() ==
sheepNum){
debug("looking at self in
sepparation");
continue;
}

// calculate distance between us and


average position
magnitude = Math.abs
(currentSheep.getPosition().distance(position));

// calculate vector from the sheep


back to where i am
vectorDifference = vectorDifference
(currentSheep.getPosition(), position);

debug("\n magnitude "+magnitude);


debug("Vector difference.getX() =
"+vectorDifference.getX());
debug("Vector difference.getY() =
"+vectorDifference.getY());
debug("Unit vector X = "+
(vectorDifference.getX() / magnitude));
debug("Unit vector Y = "+
(vectorDifference.getY() / magnitude)+"\n");

// calculate unit vector and add to


cumulitive total
resultingX += (vectorDifference.getX
() / magnitude);
resultingY += (vectorDifference.getY
() / magnitude);
} catch(ClassCastException
clastCastException) {
continue;
}

Appendix C: Source code Page 123 of 133
Natalie Downe [cs1njd@bath.ac.uk]

// calculate the resulting vector as a unit


vector scaled by the separation factor
resultingX = (resultingX * separationFactor);
resultingY = (resultingY * separationFactor);
//resultingX = (resultingX / (Math.abs
(position.distance(resultingX, resultingY)))) *
separationFactor;
//resultingY = (resultingY / (Math.abs
(position.distance(resultingX, resultingY)))) *
separationFactor;
}

// return calculated average


average = new Double2D(resultingX, resultingY);
return average;
}

/**
* Cohesion rule, takes a bag of neighbouring sheep and
* retuns the vector that would lead toward the center of
the flock,
* scaled to reflect the cohesion factor set in flock
*
* @param Bag neighbours
* @return Double2D scaledCohesionVector
*/
public Double2D cohesion(Bag neighbours) {

Double2D cohesionVector;
Double2D scaledCohesionVector;

if((neighbours != null) && (neighbours.size() > 0)) {

// creating a copy of neighbours so that we


dont alter it
Bag tempNeighbours = new Bag(neighbours);

Appendix C: Source code Page 124 of 133
Natalie Downe [cs1njd@bath.ac.uk]

// calculate initial cohesion vector from


average positions of neighbours
cohesionVector = vectorDifference(position,
getAveragePosition(tempNeighbours));

// multiply calculated cohesion by the cohesion


factor specified in Flock
scaledCohesionVector = new Double2D
((cohesionVector.getX() * cohesionFactor), (cohesionVector.getY
() * cohesionFactor));

} else {
// the bag is null or empty so return zero
scaledCohesionVector = new Double2D(0.0, 0.0);
}

//cohesionVector = cohesionVector * cohesionFactor;


return scaledCohesionVector;
}

/**
* Given a Bag of neighbouring sheep calculates the
average position of the surrounding sheep
*
* @param Bag neighbours - calculated through
getNearSheep
* @return Double2D average - the average positon as a
Double2D object
*/
public Double2D getAveragePosition(Bag neighbours) {

// check that we havnt been given an empty bag


if((neighbours == null) || (neighbours.size()
<= 0)) {
throwError("Trying to calculate the average
position of an empty bag");
}

// create replicate so as not to alter original


Bag tempNeighbours = new Bag(neighbours);

Appendix C: Source code Page 125 of 133
Natalie Downe [cs1njd@bath.ac.uk]

double averagePositionX = 0.0;


double averagePositionY = 0.0;
int numNeighbouringSheep = tempNeighbours.size
();
Sheep currentSheep;

// go through each of the neighboring sheep and


add position to running total
for(int i = 0; i < numNeighbouringSheep; i++) {
// put in code to check if the current item
is infact a dog!
// set the next sheep to be the next item
try {
currentSheep = (Sheep)
tempNeighbours.get(i);
averagePositionX +=
(currentSheep.getPosition().getX());
averagePositionY +=
(currentSheep.getPosition().getY());
} catch(ClassCastException
clastCastException) {
// catching dog
continue;
}
}

// calculate average point


return new Double2D((averagePositionX /
numNeighbouringSheep), (averagePositionY /
numNeighbouringSheep));
}

/**
* stops the program running and throws the error with the
error message given
* overrides method from Animal to display sheep number
*
* @param errorMessage - String, what went wrong in the
program
*/
// uncomment when other code moved to animal

Appendix C: Source code Page 126 of 133
Natalie Downe [cs1njd@bath.ac.uk]

/*protected void throwError(String errorMessage) {


throwError("Sheep #"+sheepNum+" died: "+errorMessage);
}*/

/**
* prints out a message complete with the sheep number -
less typing!
* overrides method from Animal to display sheep number
*
* @param debugMessage - String, what is going on in the
program
*/
/*protected void debug(String debugMessage){
debug("Sheep #"+sheepNum+": "+debugMessage);
}*/

/**
* returns the direction the sheep is currently facing in
radians
* essential method to be over-ridden from interface
* @see sim.portrayal.Oriented2D#orientation2D()
*/
public double orientation2D() {
return directionRadians;
}

// to go in Animal
/**
* Takes a direction in radians and converts to a unit vector
to allow for easyer calculation
* assumes: Top-left of screen = (0,0) <- through testing
* Down and right = posetive <- through
testing
* East (right) = 0 radians <- common
assumption
*
* @param radians
* @return
*/

Appendix C: Source code Page 127 of 133
Natalie Downe [cs1njd@bath.ac.uk]

protected Double2D radiansToVector(double radians) {

// local variables
double vectorX;
double vectorY;

// check for slim possibility that radians is negative


if(radians < 0) {
throwError("Unable to calculate unit vector from
radians, 'radians' equals zero!");
}

if(radians >= (1.5 * Math.PI)) {


// sheep pointing between north and east (including
due east and due north)
if(radians == (1.5 * Math.PI)) {
// due North
vectorX = 0.0;
vectorY = -1.0;
} else if(radians == (2 * Math.PI)) {
// due East
vectorX = 1.0;
vectorY = 0.0;
} else {
// between North and east
vectorX = Math.abs(Math.sin((Math.PI * 2) -
radians));
vectorY = (-1) * (Math.abs(Math.cos((Math.PI * 2)
- radians)));
}
} else if(radians >= Math.PI) {
// sheep pointing between west and north (including
due west)
if(radians == Math.PI) {
// due West
vectorX = -1.0;
vectorY = 0.0;
} else {
// between West and North
vectorX = (-1) * (Math.abs(Math.sin(radians -

Appendix C: Source code Page 128 of 133
Natalie Downe [cs1njd@bath.ac.uk]

Math.PI)));
vectorY = (-1) * (Math.abs(Math.cos(radians -
Math.PI)));
}
} else if(radians >= (Math.PI / 2)) {
// sheep pointing between south and west (including
due south)
if(radians == (Math.PI / 2)) {
// due South
vectorX = 0.0;
vectorY = 1.0;
} else {
// between south and west
vectorX = (-1) * (Math.abs(Math.sin(Math.PI -
radians)));
vectorY = Math.abs(Math.cos(Math.PI - radians));
}
} else {
// sheep pointing between east and south (including
due east)
if(radians == 0) {
// due East
vectorX = 1.0;
vectorY = 0.0;
} else {
// between east and south
vectorX = Math.abs(Math.sin(radians));
vectorY = Math.abs(Math.cos(radians));
}
}

// return calculated unit vector


return new Double2D(vectorX, vectorY);
}

/**
* Given two points calculates the vector to travel from the
first to the second
*
* @param Double2D fromPosition

Appendix C: Source code Page 129 of 133
Natalie Downe [cs1njd@bath.ac.uk]

* @param Double2D toPosition


* @return Double2D vector difference
*/
protected Double2D vectorDifference(Double2D fromPosition,
Double2D toPosition) {
return new Double2D(toPosition.getX() - fromPosition.getX
(), toPosition.getY() - fromPosition.getY());
}

/**
* stops the program running and throws the error with the
error message given
*
* @param errorMessage - String, what went wrong in the
program
*/
protected void throwError(String errorMessage) {
System.out.println("died: '"+errorMessage+"'");
throw new RuntimeException("died: '"+errorMessage+"'");
}

/**
* prints out a message complete with the sheep number - less
typing!
* @param debugMessage - String, what is going on in the
program
*/
protected void debug(String debugMessage){
System.out.println(": "+debugMessage);
}

/* ------------------- Getters and Setters


------------------- */

/**
* @return Returns the sheepNum.
*/
public int getSheepNum() {

Appendix C: Source code Page 130 of 133
Natalie Downe [cs1njd@bath.ac.uk]

return sheepNum;
}

/**
* @return Returns the position.
*/
public Double2D getPosition() {
return position;
}

/**
* @return Double2D
*/
private Double2D getDirectionVector() {
return directionVector;
}
}

C5) Dog.java
/**
* @author Natalie Downe :: natalie@natbat.co.uk
* @see http://www.natbat.co.uk/
*/

package uk.co.natbat.sheep;
import sim.engine.SimState;
import sim.engine.Steppable;
import sim.util.Double2D;

/**
*
*/
public class Dog extends Animal implements Steppable,
sim.portrayal.Oriented2D {

// Simulation details
private Flock containingFlock;

Appendix C: Source code Page 131 of 133
Natalie Downe [cs1njd@bath.ac.uk]

// dog details
private int dogNum;
private Double2D position; // (0,0) as defined by mason is
the top left of the screen left & up = negative
private Double2D directionVector;
private double directionRadians;

/**
* constructor takes the flock as a flock object and the
dog number
*
* @param Flock initContainingFlock
* @param int generatedDogNum
*/
public Dog(Flock initContainingFlock, int initDogNum) {

// populating variables
containingFlock = initContainingFlock;
dogNum = initDogNum;

// generate random initial position ensureing that it


is posetive
double positionX = Math.abs(Math.random() *
containingFlock.getSimulationWidth());
double positionY = Math.abs(Math.random() *
containingFlock.getSimulationHeight());

// setting the new position


position = new Double2D(positionX, positionY);

// set the sheep facing a random direction


directionRadians = Math.PI * 2.0 * Math.random();

// calculating direction vector from this


directionVector = radiansToVector(directionRadians);
}

/**
* @see sim.engine.Steppable#step(sim.engine.SimState)

Appendix C: Source code Page 132 of 133
Natalie Downe [cs1njd@bath.ac.uk]

*/
public void step(SimState state) {

Double2D newPosition;

double newPositionX = position.getX() +


directionVector.getX();
double newPositionY = position.getY() +
directionVector.getY();
newPosition = new Double2D(newPositionX, newPositionY);

// test for real values of the intended new position


coodrdinate
if((newPositionX >= 0.0) && (newPositionY >= 0.0) &&
(newPositionX <= containingFlock.getSimulationWidth()) &&
(newPositionY <= containingFlock.getSimulationHeight())) {
// both coordinates are on the screen
position = newPosition;
} else {
// off the screen or NaN
// implement random angle with respect to angle of
incedance
directionVector = radiansToVector(Math.PI * 2.0 *
Math.random());
}

// update new position on screen


containingFlock.setDogLocation(this, position);

/**
* @see sim.portrayal.Oriented2D#orientation2D()
*/
public double orientation2D() {
return directionRadians;
}
}

Appendix C: Source code Page 133 of 133

Вам также может понравиться