Академический Документы
Профессиональный Документы
Культура Документы
uk]
Signed Declaration
Title: Refinement of Reynolds' flocking rules in a distributed behavioural model
to better reflect the Semiadversarial 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 understudied 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 semiadversarial [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) Nonfunctional 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: Screenshots.....................................................................................77
Screenshot at Start.....................................................................................77
Screenshot at time 11.................................................................................77
Screenshot at time 19.................................................................................78
Screenshot 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. Introduction Page 8 of 133
Natalie Downe [cs1njd@bath.ac.uk]
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. 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 wideranging 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. 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. Background Literature Page 13 of 133
Natalie Downe [cs1njd@bath.ac.uk]
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. 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 semiadversarial 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 SemiAdversarial 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 PredatorPrey 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 SemiAdversarial, it can also be described as
inaccessible, nondeterministic, 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 semiadversarial
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 13], 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 flightzone 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 [DelgadoMata 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. Background Literature Page 18 of 133
Natalie Downe [cs1njd@bath.ac.uk]
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 indepth 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]
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.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. 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 handheld 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. 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.
4 trial Requirements
4.1 The view should simulate a basic trial course
4.2 It should be possible to time the game.
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. 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]
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. 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 [DelgadoMata 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. Detailed Background Research Page 29 of 133
Natalie Downe [cs1njd@bath.ac.uk]
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. 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
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].
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]
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.
Animal.java
Animal.java is the
super class for
Dog and Sheep.
Sheep.java Dog.java
5. Application of Research and Agent Design Page 34 of 133
Natalie Downe [cs1njd@bath.ac.uk]
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]
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 flockmates.
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. 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]
5. Application of Research and Agent Design Page 43 of 133
Natalie Downe [cs1njd@bath.ac.uk]
Based on the above rules it is now possible use these as priorities to create the
sheep Agent.
5. Application of Research and Agent Design Page 44 of 133
Natalie Downe [cs1njd@bath.ac.uk]
5. Application of Research and Agent Design Page 45 of 133
Natalie Downe [cs1njd@bath.ac.uk]
Agent
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 online at:
http://www.bath.ac.uk/~cs1njd/demo.html.
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.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. 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.
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
+ 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. 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 popup Java selection box:
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 'setup' 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. Implementation of Design Page 53 of 133
Natalie Downe [cs1njd@bath.ac.uk]
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 boilerplate 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 boilerplate methods, finish and quit, these call the
corresponding methods in GUI state. [for screen shots please see Appendix A.]
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.
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.
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]
// local variables
double vectorX;
double vectorY;
6. Implementation of Design Page 56 of 133
Natalie Downe [cs1njd@bath.ac.uk]
6. Implementation of Design Page 57 of 133
Natalie Downe [cs1njd@bath.ac.uk]
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());
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]
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.
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 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 [DelgadoMata 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. 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 plugin,
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. Conclusion and Evaluation Page 69 of 133
Natalie Downe [cs1njd@bath.ac.uk]
Aiming at a nontechnical 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. Conclusion and Evaluation Page 70 of 133
Natalie Downe [cs1njd@bath.ac.uk]
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. Conclusion and Evaluation Page 72 of 133
Natalie Downe [cs1njd@bath.ac.uk]
AOYAGI, M., NARNATAME A (2003) “Massive individual based simulation:
forming and reforming of flocking behaviours” National defence academy,
Japan
BALAN, G., CIOFFIREVILLA, C., LUKE, S., PANAIT, L., PAUS, S., (2003)
“Mason: A Java MultiAgent Simulation Library” [online], 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” [online] Massachusetts Institute of Technology, Artificial Intelligence
Laboratory.
Available from:
https://dspace.mit.edu/bitstream/1721.1/6432/2/AIM864.pdf
COBB, R., (2005) “An Introduction to Sheep Behaviour” [online], 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
DELGADOMATA, C., (2004) “Characterising Emotion Signalling and Affected
Group Behaviour in Virtual Mammals” [online], Manchester: University of
Salford, Available from:
http://ceurws.org/Vol97/IVEVAFinal_S2_04.pdf
[Accessed: 15 November 2004]
ELLIOT, E., KIEL, L. D., (2004) “AgentBased Modeling in the Social and
Behavioural Sciences” Published in Nonlinear 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 ObjectOriented
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” [online], 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” [online], 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 [online] Available from:
http://www.davidlewis.com/sg3/index.php
LEWIS, D., (2001), Sheepgame v1 [online] 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 ” [online]
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” [online] Available
from: http://www.workingsheepdog.co.uk/sheepdogtraining
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
HumanComputer 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 2534.
References and Bibliography Page 74 of 133
Natalie Downe [cs1njd@bath.ac.uk]
REYNOLDS, C. W., (1999). “Steering Behaviours For Autonomous Characters”
[online], 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”[online]
Proceedings of the Genetic and Evolutionary Computation Conference
(GECCO2003). Berlin: SpringerVerlag. pp. 6173.
Editors: In E. CantuPaz, 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/spectorgecco2003.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 161168.
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
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 'AttributionNonCommercialNoDerivs' 2.0 licence.
[http://flickr.com/photos/candl/8066163/]
Page 19 – Screen shot from 'Sheepgame', developed by David Lewis:
[http://www.davidlewis.com/sg3/index.php]
Pages 17 and 98 – Drawing of sheep used in diagrams, by Jens Pagotto.
[http://islandthree.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 screenshots can be found at:~
http://www.flickr.com/photos/nataliedowne/tags/dissertation/
Screen-shot at Start
Screen-shot at time 11
Appendix A: Screenshots Page 77 of 133
Natalie Downe [cs1njd@bath.ac.uk]
Screen-shot at time 19
Screen-shot at time 45
Appendix A: Screenshots Page 78 of 133
Natalie Downe [cs1njd@bath.ac.uk]
Appendix A: Screenshots Page 79 of 133
Natalie Downe [cs1njd@bath.ac.uk]
Appendix A: Screenshots Page 80 of 133
Natalie Downe [cs1njd@bath.ac.uk]
B1) Questionnaire
B1.1) email sent to working sheepdog mailing list and
the Border Collie interest list
Hello,
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
> 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 parttime 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
> 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
> 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 workingsheepdog 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)
> 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]
> 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
> 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.
> 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 galeforce 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
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
> 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
> 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]
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.
4
1 3
Dog
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.
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.
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
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.
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]
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 {
Appendix C: Source code Page 100 of 133
Natalie Downe [cs1njd@bath.ac.uk]
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);
display.setBackdrop(backgroundColour);
displayFrame.setTitle("Natalie Downe: Final Year
Project");
}
Appendix C: Source code Page 101 of 133
Natalie Downe [cs1njd@bath.ac.uk]
// initiating console
Console c = new Console(sheepFlock);
c.setVisible(true);
}
Appendix C: Source code Page 102 of 133
Natalie Downe [cs1njd@bath.ac.uk]
setupPortrayals();
// reschedule the displayer
display.reset();
display.repaint();
}
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
Appendix C: Source code Page 104 of 133
Natalie Downe [cs1njd@bath.ac.uk]
// dog variables
public int numDogs = 1;
Appendix C: Source code Page 105 of 133
Natalie Downe [cs1njd@bath.ac.uk]
// 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");
}
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
}
Appendix C: Source code Page 107 of 133
Natalie Downe [cs1njd@bath.ac.uk]
Appendix C: Source code Page 108 of 133
Natalie Downe [cs1njd@bath.ac.uk]
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]
Appendix C: Source code Page 111 of 133
Natalie Downe [cs1njd@bath.ac.uk]
C3) Animal.java
/**
Appendix C: Source code Page 112 of 133
Natalie Downe [cs1njd@bath.ac.uk]
package uk.co.natbat.sheep;
import sim.engine.SimState;
import sim.engine.Steppable;
import sim.util.Bag;
import sim.util.Double2D;
// local variables
double vectorX;
double vectorY;
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));
}
}
/**
* 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;
// flock details
private Flock containingFlock;
private double flightZoneRadius;
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();
Appendix C: Source code Page 117 of 133
Natalie Downe [cs1njd@bath.ac.uk]
/**
* 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());
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");
}*/
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) {
Appendix C: Source code Page 120 of 133
Natalie Downe [cs1njd@bath.ac.uk]
try {
// looking at current sheep
currentSheep = (Sheep)
tempNeighbours.get(i);
if(currentSheep.getSheepNum() ==
sheepNum){
debug("looking at self in
sepparation");
continue;
}
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();
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;
}
Appendix C: Source code Page 123 of 133
Natalie Downe [cs1njd@bath.ac.uk]
/**
* 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;
Appendix C: Source code Page 124 of 133
Natalie Downe [cs1njd@bath.ac.uk]
} else {
// the bag is null or empty so return zero
scaledCohesionVector = new Double2D(0.0, 0.0);
}
/**
* 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) {
Appendix C: Source code Page 125 of 133
Natalie Downe [cs1njd@bath.ac.uk]
/**
* 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]
/**
* 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]
// local variables
double vectorX;
double vectorY;
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));
}
}
/**
* 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]
/**
* 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);
}
/**
* @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;
/**
* @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;
/**
* @see sim.portrayal.Oriented2D#orientation2D()
*/
public double orientation2D() {
return directionRadians;
}
}
Appendix C: Source code Page 133 of 133