SWARMSARA: AN ARTIFICIAL LIFE APPROACH TO BUDDHIST LAND RESOURCE MANAGEMENT By Alex Turner A thesis submitted in partial fulfillment of the requirements for the degree of Master of Science (Land Resources/Institute for Environmental Studies) at the UNIVERSITY OF WISCONSIN – MADISON 2001

i University of Wisconsin--Madison Abstract SWARMSARA: AN ARTIFICIAL LIFE APPROACH TO BUDDHIST LAND RESOURCE MANAGEMENT by Alex Turner Chairperson of the Supervisory Committee: Professor Robert O. Ray Institute for Environmental Studies A thesis presented on Swarmsara, a computational model of the life process based in Buddhist epistemology for the purpose of developing high technology methods of indigenous land resource management. The thesis justifies and explains an implementation of this idea in the computer language Java, drawing on materials from a number of traditions and disciplines. The part of Buddhism implemented is the basic idea that the kleshas (afflictive emotions), together with karma (action and its consequences), produce samsara (the world of suffering as we perceive it).

Possible applications of the simulation include GIS-driven

indigenous land-use planning and preservation, fostering bottom-up development and education in Buddhist Asia, as well as providing the beginnings of a means for testing the basic hypothesis of Buddhism. The thesis concludes with a discussion of future directions for the algorithm and its implementations.

ii TABLE OF CONTENTS

Table of Contents................................................................................................................ ii List of Figures ...................................................................................................................... v List of Tables....................................................................................................................... vi Acknowledgments.............................................................................................................vii Preface.................................................................................................................................. ix Chapter I: Introduction...................................................................................................... 1 Modeling Buddhist Epistemology ............................................................................ 2 Cultural Survival and Environmental Protection................................................... 3 Potential Uses of the Model....................................................................................... 3 Implications for Western Science ............................................................................. 4 Testing the Buddhist Hypothesis.............................................................................. 5 Rodney Brooks, the Buddha, and the Body............................................................ 6 Description of Current Version of Swarmsara....................................................... 7 Algorithm Development as Active Listening ......................................................... 8 Chapter II: Statement of the Problem............................................................................. 9 Religion and Ecology................................................................................................... 9 Significance to Environmental Studies ..................................................................10 Beauty, Nature and Buddhism.................................................................................10 Tibetan Government in Exile and INEB..............................................................11 Buddhist Universities, Monastic Colleges and Women’s Knowledge .............11 Towards Artificial Life ..............................................................................................12 Avoiding Pseudo-science..........................................................................................13 The Sociological Perspective....................................................................................14 The Yoke of Capitalism ............................................................................................15 Is Nature Samsaric? ...................................................................................................16 Different Versions of Time......................................................................................17 Post-modern Buddhism, Consumer Culture and Marxist Materialism ...........18 Buddhist Critiques of Marxism ...............................................................................18 The Buddhist Explanation for World Problems..................................................19 Asking the Unanswerable Questions for Practical Reasons ..............................20 The Limitations of Reflexivity .................................................................................21 Chapter III: Algorithms ...................................................................................................23 Universes as Algorithms ...........................................................................................23 Evolving Universes....................................................................................................24 The Dalai Lama’s Cosmology..................................................................................27 The Wheel of Life ......................................................................................................31 Samsara’s Algorithm..................................................................................................34 Karma and Perception ..............................................................................................34

iii The Samsaric Experience .........................................................................................36 The Actual Design of Swarmsara ...........................................................................36 Implementation of Kleshas......................................................................................37 Implementation of Karma........................................................................................40 Emergent Avalanche?................................................................................................41 Chapter IV: Kleshas..........................................................................................................43 The Mother Culture...................................................................................................43 Ecofeminist Development Work............................................................................43 Deconstruction East and West................................................................................44 Ayurvedic Medicine ...................................................................................................45 The Humors................................................................................................................46 Chapter V: Karma.............................................................................................................52 Definition ....................................................................................................................52 Etymology and Cognates..........................................................................................54 Karma and Memes.....................................................................................................55 Ecosystems of Karmas..............................................................................................56 Karmic Fitness Landscapes......................................................................................57 Caveats .........................................................................................................................58 Karma in Swarmsara..................................................................................................59 Pratitya-Samutpada and Subsumption Robotics..................................................59 Buddhism as Bottom-Up..........................................................................................61 Chapter VI: Artificial Life................................................................................................63 Von Neumann Machines and Emergence ............................................................63 The Lambda Point .....................................................................................................64 Gnarl and Knots in the Grain .................................................................................65 Genetics Algorithms and Building blocks.............................................................66 Sumbsumption Robotics ..........................................................................................68 Models and Metaphors .............................................................................................69 Subsumption and Mode Switching.........................................................................69 Subsumption and Mode Switching in Swarmsara................................................70 The Meaning of the Pig ............................................................................................70 Hinges Between Emotions.......................................................................................71 Definition of Life and the Wisdom of Doing A-Life Research........................72 Heuristics of Ecological Restoration and A-Life Research................................73 Constructivism............................................................................................................74 Debate about the Definition of Life.......................................................................74 Chapter VII: Results .........................................................................................................76 Some Swarmsara Runs..............................................................................................77 The Critical Role of Karma......................................................................................87 Karma and Ignorance................................................................................................88 Test of First and Second Noble Truths.................................................................90 Connection of Buddhism and Ayurvedic Medicine ............................................91

iv Proof of Concept .......................................................................................................91 The Emergence of Conversation............................................................................92 Swarmsara Itself .........................................................................................................94 Chapter VIII: Future Directions ....................................................................................95 Karmic fitness landscapes.........................................................................................95 Sub-Peaks of the Karmic Fitness Landscape........................................................98 The Emergence of Cooperation .............................................................................99 Buddhist GIS ............................................................................................................100 Contribution to Chaos and Complexity Theory ................................................102 The Life Assignment ...............................................................................................103 Chapter IX: Conclusion .................................................................................................105 Restatement of the Problem ..................................................................................105 Swarmsara as a Move in Consequentialist Debate.............................................106 Swarmsara as a Constructivist Educational Tool...............................................107 Critique of Negative Emphasis in Swarmsara ....................................................108 Practical Resources for Further Development...................................................109 A Final Word ............................................................................................................109 Works Cited......................................................................................................................111 Appendix A: Glossary ....................................................................................................120 Appendix B: Suggested Reading...................................................................................124 Appendix C: Selected Web Links about Artificial Life and Complexity ..............132 Appendix D: A User’s Guide to Swarmsara ..............................................................135 Introduction ..............................................................................................................135 Control Panel ............................................................................................................135 Swarmsara Window .................................................................................................137 Cell Statistics Window.............................................................................................139 Afflictive Emotions Window.................................................................................140 Avg Food & Percent Happy Window .................................................................141 Appendix E: Java Code..................................................................................................142 Introduction ..............................................................................................................142 GNU License............................................................................................................142 Swarmsara.java..........................................................................................................149 SimCell.java ...............................................................................................................166 SimBug.java ...............................................................................................................167 Imprint.java ...............................................................................................................170 SwarmsaraPop.java ..................................................................................................173 SwarmsaraControl.java............................................................................................178 EmoGraph.java ........................................................................................................194 EmoGraphPop.java.................................................................................................200 RealTimeGraph.java ................................................................................................202 GraphPop.java..........................................................................................................208 Index..................................................................................................................................210

v LIST OF FIGURES

Number Page 1. Self-reproducing Inflationary Universes.........................................................23 2. Lee Smolin’s evolving universes.......................................................................26 3. The Wheel of Life...............................................................................................32 4. The Inner Circle ..................................................................................................33 5. Populating the Karmic Template.....................................................................40 6. Karmic Restrictions on Perception .................................................................41 7. Karmic Avalanche...............................................................................................42 8. The Lambda Point..............................................................................................64 9. Genetic Crossover ..............................................................................................67 10. The Beginning of Ignorance.............................................................................77 11. Attraction Emerges.............................................................................................78 12. Aversion and Drop in Perceived Happiness .................................................79 13. Attraction Peaks ..................................................................................................80 14. A Solitary Agent ..................................................................................................81 15. Solitary Agent at About 200,000 Time Steps.................................................82 16. Eighty Agents with Smoother Graph Lines ..................................................83 17. Karma Turned Off .............................................................................................84 18. An Attempt to Force Interesting Behavior without Karma.......................85 19. More Non-Karmic Flat Lines...........................................................................86 20. Two Agents with Karma Off and Forced Emotions...................................87 21. Control Panel.....................................................................................................135 22. Swarmsara Window..........................................................................................138 23. Cell Statistics Window......................................................................................139 24. Afflictive Emotions Window..........................................................................140 25. Avg Food & Percent Happy Window ..........................................................141

vi LIST OF TABLES

Number Page 1. Ignorance/laziness/delusion ............................................................................37 2. Attraction/approach ..........................................................................................38 3. Aversion/avoidance ...........................................................................................39 4. The Humors.........................................................................................................48

vii ACKNOWLEDGMENTS

The author wishes to express sincere appreciation to Professors Ray, Griffeath and Elder for their assistance in the preparation of this manuscript. In Buddhism, tolerance and patience are deemed high virtues, and Professor Ray in particular has exhibited a great deal of both in helping me through this process. In addition, special thanks to Amy Neidrich who gave me the moral support and enthusiastic encouragement I needed while implementing Swarmsara and doing much of the research behind its design. A year later, without the questioning, clear understanding and interest of Julie Drexler, I would not have completed a written draft. This project would never have been begun without the guidance of Professor James Skrentny, who recognized the importance of my ideas and gave me a special assignment in his Java programming class to get me past the first step. Professor Lin Compton also helped me find the courage to pursue such an unusual line of inquiry. Thanks also to all who use the GNU license to share the wealth of knowledge recorded in software, especially Chris Langton and the other developers of the Swarm simulation system, and Leigh Brookshaw, whose Java classes are behind the real time graphs in Swarmsara. Completing this project would have been impossible without the forbearance of many kind people at the Wisconsin Department of Natural Resources, in particular Dale Ziege, who let me shift my hours to half time when needed, and made a promotion contingent upon completion of the work, thus finally forcing the flower. Capital City Fitness helped keep body and mind strong throughout this process. Their slogan “feed your mind some body” is very much in the spirit of Buddhism and subsumption robotics. My mother Edie has provided crucial emotional and financial support at many stages. If as the Buddhists say, all sentient beings have been one’s mother in past lives, and all mothers are like this one, then my debt to the universe is very great indeed.

viii Several Buddhist knowledge holders also inspired this work. Ko Zarni, the noted Burmese dissident, egged me into making the case for the comparability of Buddhism and Darwinian evolutionary biology during a long overnight car ride back from an activist conference in Virginia. Sensei John Daido Loori planted many karmic predispositions during the course of the intensive Zen training I received under his care now long ago. Tan Santikaro Bikkhu provided much useful feedback from a Theravadan perspective. But I must reserve my deepest thanks, as ever, for Sharpa Rinpoche, whose quiet unflagging support over the years, and whose diamond-clear advice over the course of this endeavor, have changed my life in a host of ways, most of which are too simple and true for me to comprehend.

ix PREFACE

The following pages have little to do with the Buddhist tradition, or even the author’s limited personal experience of Buddhism. They are merely an attempt to justify the implementation of a neat idea the author was unfortunate enough to wake up with one morning. The idea was very simple: it would be interesting to attempt a computational model of the Buddhist description of Samsara, and such a model should be within scope, because it could be done with integers. I have since learned my use of integers is one of the major and unnecessary flaws in the system, but the model is working, and that problem is easy to fix. It is very much the intention of this work to leave such exercises to the readers, whom I hope will include programmers from the various Buddhist schools trying to bring their methodologies into the future context. Please consult the glossary in Appendix A for ad hoc definitions of technical terms as they are used herein. Although I searched extensively for work in a similar vein, I could not find anything close enough to warrant a literature review in the standard sense. Instead, this work cites sources from many disciplines to make its points. Where possible within the constraints of the font correct diacritical marks have been added to foreign words, but no special effort has been made in this regard. The last section of this work will sketch out some of the ideas and suggestions about directions the development of Swarmsara might take. It is offered as a toolkit for those ready to deconstruct the future of an illusion. The source code of the implementation is also available in the appendices, for the same reason. My only request is those using these ideas do so with some attempt at altruistic motivation.

1 Chapter 1

INTRODUCTION Although wishing to be rid of misery, They run towards misery itself. Although wishing to have happiness, Like an enemy they ignorantly destroy it. --Shantideva Recent articles in the Chronicle of Higher Education espouse a Buddhist approach to learning, even a close comparison of Buddhism and ecology (Barash 2001, Johnson 2001). Several books have been written on the subject (Badiner 1990, Tucker 1997). These works tend to focus on the interconnectedness emphasized in both approaches to reality. They tend to look at life in a holistic rather than a reductionistic manner, and generally they do not try to apply Buddhist technical epistemology to biological questions. At His Holiness the Dalai Lama’s request, one of his monks designed a three dimensional computer animation of a complex Tantric visualization involving differently shaped mandalas representing the four elements (Chogyen 1992), but even this does not address the algorithmic nature of the Buddhist description. Trends in artificial intelligence, psychology and neurology indicate the pathways from emotions to thought run largely one way, starting with the emotions (Pinker 1999, Graybiel 1998). If this is so, intelligence must be understood in this light. Experiments in computer science produce lifelike processes under a wide variety of conditions (Levy 1992). For researchers and philosophers considering these

2 results, life is neither a function of mind nor of matter, but rather an information process, an algorithm independent of substrate (Dennett 1995, 45-60; Dawkins 1987, 47-49, Sloman 1978, 105). If life is both an algorithm and mind is based on the emotions, it is therefore very important to consider the emotions as an information process. Modeling Buddhist Epistemology The Buddhist tradition has been taking this approach for thousands of years, producing the Abhidharma, perhaps the world's most complex psychology of the emotions (Chauduri 1976, Kongtrul 1995, Ganguly 1994). This psychology is rooted in a cycle of three "primary" emotions, often translated as greed, anger and ignorance, which generate each other in turn. As the Buddhist publisher Sidney Piburn explained to me, these can be considered more abstractly as attraction, aversion and indifference, a simple “physics” of agency.

The

Buddhists say these emotions, known together as the kleshas, coupled with karma, the information process governing cause and effect, produce the deluded projection of the cyclic world of misery as we know it, Samsara (Rhys Davids and Stede 1921-1925, III 20). This description begs a computational approach, and indeed it is possible to create a model of this reflexive interaction using tools developed for the study of artificial life, and to use this model to test whether the Buddhist version of life makes sense, and whether the emotional pattern it contains has the consequences it outlines. The first version of this model, created using the computer language Java, can be run from a web page (http://www.execpc.com/~alturner/java/Swarmsara.html) and uses a raster grid for its spatial structure. This means that it can be made to be compatible with Geographical Information Systems (GIS), which use raster grids for many of their layers. In other words, Swarmsara is a method for

3 modeling the life process based on Buddhist principles that could be used for land resource management. Cultural Survival and Environmental Protection Such a project has implications for the care of the environment in many respects. Several Buddhist countries, notably Thailand, are coming to a modern environmental awareness (INEB 2000). Thailand is learning from the negative experience of allowing the world economic system to encourage its less ethical citizens to cooperate with multinational corporations in the destruction of its ecosystems (Sivaraksa 1992). Countries like Burma and Tibet await the day when they can cast off their current oppression and get on with the business of repairing the destruction wreaked by military regimes, and their legitimate leaders have already solicited the help of environmentalists in planning their futures (Gyatso 1990).

But Buddhists, although more resistant than most societies to

the intoxications of western materialism, are still frighteningly quick to substitute Pizza Huts for Buddhist temples as the centers of their cultural life. Modern Tibetans, disappointed by their long exile and finally safe in America, replace their Buddhist altars with giant screen color TVs. Potential Uses of the Model It is my hope that developing a tool that can be used to produce realistic spatial models for ecosystem management using Buddhist methods at its core would help slow down the catastrophic destruction of Asian nature. I also hope it would inspire a few in the new generation of Buddhists to respect their indigenous traditions more deeply and not cast them aside with quite as much impatience as some of them do now. Beyond that, it is my fondest hope that my work might inspire programmers in countries like Burma, Thailand and Tibet to go much further than this author can towards creating a system that matches the life process as described by Buddhism, and even perhaps the biological life

4 process itself. I was very encouraged by the response from faculty and students at a Chaos and Complex Systems seminar here at UW-Madison after presenting the system and its justifications. Suggestions were made from every angle: a physicist wanted it to be more deterministic so he could search for strange attractors, psychologists wanted more complexity and detailed rules of karmic interaction, and a biologist wanted it to fit her vocabulary for studying the behavior of slime molds. In other words, Swarmsara, like a stem cell, could grow in many directions, and this fertility bodes well for its chances of crossing the cultural gap to the indigenous Buddhist tradition. Implications for Western Science Swarmsara has implications for many fields of inquiry. Physics in this century has profited again and again by using the traditions of eastern thought to spark insight into otherwise unexplainable phenomena. This is not to suggest eastern thought is valid in scientific terms, but that it often explores perspectives on phenomena closed for too long to the channeled western mindset.

Trained

scientists use its insights to break free of their own conceptual constraints enough to take their established methods into new domains, such as quantum mechanics (Zukav 1979). If Eastern thought proved so useful for Physics, might it not spark equally important insights in evolutionary biology and cognitive psychology? Also, the model has promise, were it to be augmented with a genetic algorithm such that agents could “learn” from their past karma, to serve as a means for studying the emergence of cooperation. Since Robert Axelrod’s groundbreaking work on the subject, the Prisoner’s Dilemma has become a key paradigm in several fields such as Government Studies (Axelrod 1984, Kosumas 2000). Government theorists in Buddhist countries seeking to make the leap once again from the arthashastra of real politique to the ethical government of King Asoka (Tambiah 1976, 27) might find the implications of that future version of Swarmsara very interesting indeed.

5 Testing the Buddhist Hypothesis The model can also be used to test the Buddhist hypothesis. Buddhism claims that life is perceived as dissatisfactory due to the afflictive emotions. These come in many permutations, but at their core is a cycle of three primary emotions, often called greed, anger and ignorance or more abstractly, attraction, aversion and indifference. The Buddhist system can thus be understood to be based on a physics of agency. An agent can be drawn towards, repelled by, or resist being influenced by an object. Put another way, an agent likes, dislikes, or doesn’t care about an object. According to Buddhism these emotions run in a cycle. Filtered through the theories of roboticist Rodney Brooks, this cycle can be seen as subsumptive.

Subsumption at its crudest means that agents try the easiest

solution first, and work their way up through a hierarchy of more expensive strategies until a problem is solved (Brooks 1995, 58-61). In this light, an agent starts by conserving its energy, resisting change when it doesn’t seem necessary. This strategy leads to the unwanted consequence of being inappropriately resistant when change is needed, at which time the agent has to develop attraction to overcome the built-up inertia. By the time attraction is strong enough to overcome the laziness however, it is also a big enough distortion that it necessitates the invocation of an aversion response to escape from objects of attraction that cause problems. But when an agent runs away from everything, it cannot survive either, so the increase of aversion subsequently requires the agent to increase its resistance to change in order to stay near desired objects. Thus the cycle perpetuates and elaborates itself. These reactions distort the evaluation of the object, and these distortions have consequences. One consequence is the agent gets information imprints in its memory that come to fruition when the agent meets similar circumstances in the future. The Buddhists call this karma. Another consequence is that since the

6 agent is living in a strategically distorted worldview, it has little chance of meeting its internally defined optimal conditions. It would be absurd to suggest a simple computer model like the one proposed here could decide for well and good whether Buddhism is right or not. But as it turns out, it was within the scope of this project to set up attributes for the agents that measure whether they perceive themselves to be experiencing their desired conditions, and to gather and graph these data in a way that might spur further study. Indeed, this project was inspired in no small part by an existing application offered by the designers of the Swarm Simulation System called Heatbugs, which shows whether the agents consider themselves within the happy range between being too hot and too cold (Swarm 2001). Rodney Brooks, the Buddha, and the Body There are several major strands in the study of artificial life. Rodney Brooks and his colleagues at MIT (Steels and Brooks 1995) are pursuing one of the most interesting of these, the idea of “subsumption” robotics. “Good old fashioned artificial intelligence” (GOFAI) tried to model intelligence as a process of perception -> planning -> action and has succeeded in producing only the most ponderous of working models. Brooks looked instead at the behavior of simple agents such as insects, and changed this to action -> perception -> planning. In this scheme actions subsume each other as simpler solutions fail, until only as a last resort would an agent use such an expensive process as planning to solve a problem. One might say, cognition is the last refuge of the robot. Brooks says cognition arises from the seamless coupling of motor motion and perception. Incidentally, Brooks and the Buddha make the same radical breakthrough relative to the fields from which they emerged: they both insist that the body must come first. This is clear from the Anapanasati Sutta, which describes the Buddha’s personal meditation (Buddhadasa 1988a,45), in which the practitioner starts with

7 meditation on the body, then moves to the emotions, which have been conditioned by calming the body, then to mental states, which are conditioned by the emotions, and finally the dharmas, or object-truths, which are apparent only when the mental states are pacified. Antonio Damasio, expanding on some points made by William James, argues similarly for the body -> emotion relationship (1994, 125-163). Description of Current Version of Swarmsara As broached earlier, taking these ideas I noticed the Buddhist cycle of the emotions is a subsumption process, and modeled it accordingly. Laziness is easiest, attraction kicks in when laziness fails as a strategy, and aversion takes over when desire fails to meet resource needs, thus triggering a greater urge for laziness as aversion takes the agent away from resources. The model as it currently stands is written into the framework of a Java 1.3 applet and can be viewed at http://www.execpc.com/~alturner/java/Swarmsara.html . It includes original methods for generating resizable raster grids, a control panel and real time graphs, classes that instantiate empty cells and cells occupied by agents, and methods for changing the agents’ emotions individually based on their perceived experience of their surroundings. A key component is a “karma” attribute of cells, in the current implementation produced at random by the agents as they go about their business, and which the agents perceive subsequently as a resource.

Although attraction and aversion increase and

decrease and can be implemented as simple integer scales, ignorance (avidiya) is subtler, being a denial of perception. Therefore this project models instead one of the immediate consequences of ignorance, laziness, which according to Sharpa Rinpoche does accumulate and decrease. Ignorance proper is more an emergent property of the system, as karma reflexively affects perception, and the agents

8 find them caught in the situation succinctly described by Nietzsche with reference to painters: “He likes/ What he can paint” (Gombrich 1977, 75). The model itself is the meat of the project. This Masters thesis does not attempt to adapt the model to GIS, but the author knows enough about GIS to know this is possible in the long run. The bulk of the work for this thesis was just getting the program designed and running, and a large fraction of what follows will just be a description of the program and the design choices I made. However, perhaps more important is the Future Directions section, in which a number of suggestions are made regarding potential applications and extensions of the project. Algorithm Development as Active Listening This project is intended merely as an act of active listening, specifically, a kind of risk taking. In the counseling session, one of the most effective tactics is to take a stab in the dark at what the speaker feels and means by something. Then if you are right, it is very validating, and if you are wrong, it gives the speaker a chance to clarify and correct the situation. If anything, it is better to be wrong, for that reason. The point of this project is to inspire the Buddhist tradition into defining itself in the most modern terms, because I think it can, and should, because its values are much more environmentally benign than what I observed in Asia to be its take on the western myth of scientific modernity that is attempting to replace it (Horkheimer and Adorno 1982, 6). I believe Buddhism really does understand the relationship of selfishness to cooperation, and all that to the biosphere. Even were Buddhism a completely erroneous worldview, its cultures and traditions have perforce become integrated into the landscape, and exist as “keystone species” removable only at our greatest peril.

9 Chapter 2

STATEMENT OF THE PROBLEM Buddhism purports to diagnose the cause of suffering in the world, and prescribe a cure. On May 12, 2000 India’s billionth baby was born, and meanwhile three new giant icebergs calved off Antarctica (Whitehouse 2000), making six that spring alone. If Buddhism can do what it claims, it should be able to stop such trends and bring the world back to a sustainable equilibrium. Religion and Ecology This project intends to broach the subject of whether Buddhism can be used for ecosystem management in ways not yet considered. The general conclusion of the albeit-biased participants of the Human Values and the Environment conference at UW Madison in 1992, across the many religions there represented, including Buddhism, was that the environmental problem caused by religion was not that religion advocates environmental destruction, because almost universally it does not, and in fact advocates environmental stewardship, but rather that its adherents were not religious enough (Thurman 1992, 26).

As the muslim

participant pointed out, the modern American environmental movement took as its immediate precursor works produced by thinkers elaborating the natural philosophy of Islam (Nasr 1992, 47). And despite recent actions by Israeli settlers, the one thing forbidden in the Old Testament when even the destruction of cities such as Jericho was permitted was the uprooting of trees (Berman 1992, 9). So have Buddhists fully considered how their own natural philosophy might be used to better understand environmental change and destruction caused by the forces it works so hard to model? Until now the option available has been to

10 apply the Buddhist teachings to the body and mind of the individual and concomitantly to some extent to the structure of society, thus producing motivation and awareness in the world that can diminish suffering and unwholesome behavior. In very recent years tools of computer science have become available that allow us to put some of these descriptions and approaches to a new kind of test. Does the cycle of the emotions together with the process of ethical cause and effect really produce a life-like system? Do the agents caught in this system really find it impossible to be satisfied? Can such a system be applied to real-world problems like containing urban sprawl or predicting the spread of weedy species across a landscape? Significance to Environmental Studies This is significant to the field of Environmental Studies because Asia along with the rest of the world is in the midst of a severe ecological crisis, which is threatening the survival of life as we know it (Wilson 1992, 191) and needs all the tools possible to attack the problem. Indigenous knowledge systems of human cultural groups are keystone species of ecosystems; so one important means of forestalling the collapse is by bolstering and validating traditional structures and practices.

But pre-modern peoples, even those with rich and sophisticated

histories such as those who inherited the Buddhist tradition, tend to be easily entranced by the lures of Western mass culture. Could this momentum be turned against itself, in the style of yoga, the martial arts, and Buddhist philosophical debate, by presenting in the highest technological terms their own traditional systems back to them, in the form of the materials for making tools for managing the harm done by modernization? Beauty, Nature and Buddhism Survey data, at least in Wisconsin (Barman, 1997), indicate humans value scenic beauty very highly. E.O. Wilson has broached a debate within the sciences about

11 the sociobiological underpinnings of our sense of beauty in landscapes (1992, 350).

Buddhists argue this appreciation of nature is very basic in people

(Buddhadasa 1986, 129-142) and doesn’t go away until it is finally transcended for the only thing better, lasting peace, and even then the great Buddhist teachers seem prone to live close to the land and its occupants (Buddhadasa 2001). Buddhist art, particularly some of the schools of Japanese brush painting, have exhibited an exquisite appreciation of nature. Tibetan laws prior to the Chinese invasion banned hunting, and Darcy Richardson has argued that the old Tibetan kings imported Buddhism because they needed justification for imposing a more sustainable environmental regime in their frail mountain ecosystem.

Thus,

encouraging renewed respect for Buddhism among its adherents fosters a view that is potentially ecologically sound, perhaps much more so than the empty shell of Western materialism so virulent around the world. Tibetan Government in Exile and INEB Two specific groups that might apply future versions of this system are the Tibetan Government in Exile and the International Network of Engaged Buddhists. (INEB), both of which already use high technology to maintain the ancient tradition they represent (INEB 2000). A project involving the Swarmsara application as a touchstone could in fact have as its major effect the transfer of high technology to these groups, but packaged in such a way that for once it might do more good than harm. In other words, even if Swarmsara never finds a specific application, it could still do good as a medium of communication, a way to get resources to those best suited to apply them. Buddhist Universities, Monastic Colleges and Women’s Knowledge Established Buddhist research institutions like Chulalongkorn University in Bangkok, or the concordant monastic colleges there might be good venues for carrying the research forward. So might the remnant monastic colleges of the

12 Tibetan Buddhist world sphere, such as Sera-je and Loseling. However, as in most societies, the real bearers of the indigenous knowledge tradition are the women (Warren 1992). This paper will try to suggest there is reason to believe the underlying knowledge system Buddhism builds upon is couched in metaphors more typical of a woman’s way of life, suggesting the insights and intuitions given structure by later conquerors were originally generated around the cooking fires of women. Tibet and Burma are strongly matrilineal, Thailand also although less so (Wyatt 1984), which may be why these cultures are capable of supporting large monastic communities. The elected leader of Burma, Daw Aung San Suu Kyi, is a Buddhist woman, and the head of the GIS section of the Tibetan Government in Exile, at least as of 1993, is also female. So perhaps the non-linear, reflexive approach to land use problem solving I am offering will appeal to and be taken up by the strong female forces of these societies. Towards Artificial Life On another front, the fields of chaos theory and artificial life are still in their infancy despite having passed their initial hype peaks, and could use the support an army of Buddhistically inclined scientists could lend, extending the tradition already strong in other sciences of borrowing from Eastern thought (Capra 2000). The problem Swarmsara addresses in this context is simply “what is life”. Tom Ray, the first scientist to design a truly open evolutionary system, approaches this with some humor, pointing out that his definition is typical of evolutionary biologists like himself, whereas other researchers offer definitions illustrative of the biases of their own fields (1995, 180). Most such definitions, for instance Rudy Rucker’s, include biological facts such as death and sex (Rucker 1993, 1120). But although Buddhism is almost too much about death, it argues a karmic continuum is beginningless, and that selection occurs in terms of an individual’s interaction with its own karma rather than through the culling of generations. Models like Rucker’s and Ray’s are hard to dispute, but if an interesting life

13 process can be implemented without such components as sex and death, it deepens this fundamental scientific question in a potentially important way. Avoiding Pseudo-science Since artificial life programs are constrained by the dictates of computer logic, they are afforded at least the possibility of protection against straying into the distasteful realms of pseudo-science. The last thing this project would wish would be to merit an entry in the online Skeptic’s Dictionary (www.skepdic.com). Claims of Buddhism’s affinity with science are frequent enough (Buddhadasa 1988b, 7), and founded in a wonderful scripture, the Kalama Sutta, which says Kalama Sutta 1.Do not believe just because it is a tradition maintained by oral repetition. 2.Do not believe just because it is an unbroken succession of practice. 3.Do not believe merely because it is hearsay. 4.Do not believe just because it is in the scriptures. 5.Do not believe just because it fits with one's point of view. 6.Do not believe just because it is correct on the ground of metaphysical theories. 7.Do not believe just because it appeals to one's consideration. 8.Do not believe just because it agrees with one's opinions and theories. 9.Do not believe just because the speaker appears believable. 10.Do not believe just because the speaker is our teacher. Kalamas, whenever you realize by yourselves that these are unwholesome, harmful or are condemned by wise people, and whoever fully undertake or observe them,

14 they will lead to uselessness or suffering, you should abandon them. Kalamas, whenever you realize by yourselves that these are wholesome, unharmful or are admired by wise people, and whoever fully undertake or observe them, they will lead to usefulness or happiness, you should undertake them. (Gautama 1997) But it should be easy to maintain the distinction between the differing methods of empirical verification practiced by the two domains of ideas.

Indeed,

comparisons of these methods have become fashionable in recent years, such as at conferences between His Holiness the Dalai Lama and cognitive psychologists, and the fine points of these proceedings can serve as guidance for experimenters seeking the edges and overlaps between the traditions (Gyatso 1991). The Sociological Perspective Perhaps Ajarn Buddhadasa Bikkhu, the giant of Thai Buddhist thought in the twentieth century, put it best: An ancient proverb which is rarely heard goes, “You must ignite the house fire in order to receive the forest fire.” Elders taught their children that they should burn an area around their huts in order to prevent forest fires from burning down their dwellings. If small countries like our own have a dictatorial dhammic socialist form of government it will be like burning the area around the house in order to protect us from the forest fire. The forest fire can be compared to violent forms of socialism or to capitalism both of which encompass the world today. A dictatorial dhammic socialism will protect us from being victimized by either capitalism or violent forms of proletarian revolution. (1986, 100)

Tan Ajarn’s use of the term “dictatorial dhammic socialism” is deliberately provocative here.

At the time he was trying to provide political cover for his

15 allies in the progressive community from the anti-communist military, by making the argument that Buddhism is socialistic too, by way of its integration into nature (Santikaro 1999), so it should not be assumed that because someone advocates a communal approach that they are from the “radical” latter-day Western socialists (Buddhadasa 1988, 104). Although the threat of communism is abated, the threat of capitalism remains (Soros 1997). The philosopher and master of financial arbitrage Georges Soros compares capitalism to a fire that would have served its purpose had it stayed in the fireplace, but thanks to people wanting too much of a good thing, now it is burning down the whole house. In general, Swarmsara aspires to be part of Buddhadasa’s back fire, an expression of the intuition about the element “fire” in its dynamic relationship to the factors in the Buddhist version of the life equation, and thus a way to preserve some small ring of safety from the forces that rage out of control. The Yoke of Capitalism This idea of a backfire is in the ancient spirit which the Aryan conquerors of India called Yoga, referring by way of its Indo-European root “yeug” (Morris 1981, 1550) to the metaphor of the animal yoke, after its indigenous practitioners used it on them. The idea is to “join” with the opponent, turning the imbalance in the opponent’s momentum into an opportunity, introducing gently the negative consequences of their actions founded in delusion. If it could serve to soften even that primordial motorcycle gang the Aryans, perhaps it can work against the new even harder and more insidious invaders in their suits and their ties. Much has been written lately about “boardroom Buddhism” (Thurman 1999-2000). If Swarmsara serves to increase the cachet of a world view founded in altruism among the gifted but trapped and exploited members of the cultural elite, such that like many through the centuries they renounce the world they have conquered, and work to better the real world instead, and perhaps this is a good thing too.

16 Is Nature Samsaric? What is to be gained by modeling the unenlightened life process? Buddhadasa seems to imply that pre-human nature’s balance is a good model for the enlightened state, whereas Swarmsara tries to show distortions in perception at the microbial level. According to Buddhist scriptures, our problems began when someone got the idea of stockpiling grains and other food, causing shortages for others. [compare Rousseau’s Social Contract] Once supplies began to be hoarded, problems of unequal distribution and access arose. The problems multiplied over time. Leaders of groups of people would be in charge of stockpiling supplies for the group, and fighting among the groups was inevitable. Even when primitive humans inhabited forests, some people or groups began to take more than they needed for themselves. To maintain control over society and to limit kilesa, laws and moral systems developed. Nature would have each of us use no more than we actually need. For years people have failed to heed the way of Nature, competing with one another to take as much as they could, causing the problems that we live with to this day. If we were to take only what is enough, none of these problems would exist, because then people would not be taking advantage of others and oppressing them. The question, then, is how much is enough? There is no set rule. It varies according to the time, place, and situation. These days it seems that nothing is ever enough. There is a Buddhist saying, ‘Even two entire mountains of gold are not enough to satisfy the desires of a single person.’ (1986, 61)

Pressed on the subject, perhaps Tan Ajarn would have acknowledged the imbalance he describes is not unique to humans.

Certainly other Buddhist

17 teachers put it that way. Humans, through their habit of hoarding, have only made the distortion more frequent and pervasive. It is as if with the Marxian exchange process (Marx 1976) we have started Samsara/evolution over again, this time at the world’s expense, using the world as consumable substrate rather than constraining context. Conversely, given the time scale of nature, natural systems tend to settle into an emergent cooperation. Weedy species in this light are only those displaced by human activity, or performing the critical service of stirring the pot, the occasional defectors in Axelrod’s prisoner’s dilemma game (1984). Different Versions of Time Indeed, another objective of this type of experimentation is to zero in on the problems entailed in different versions of time, as John Holland has pointed out in his speculations about modeling the dynamics of forest restoration in Michigan (Holland 1995, 162-164). Buddhism has much to say about the nature of time, and much could be done towards articulating a Buddhist take on Paul Virilio’s slogan “speed is violence” (1986). Time and energy are also of course intimately related, as Einstein showed with his equation E=MC2. Buddhism includes a detailed examination of different types of internal energy via the humoral trope of prana, or energy winds, and the methods for controlling them (Clifford 1984). Buddhists would argue that advertising thrives by exciting these winds in people, but if people can become sufficiently aware, they can decide which level of energy is really in their best interests, and as it were, take the wind out of the sails of the destructive consumer culture. The Swarmsara simulation offers this field of study as well, albeit in an extremely rudimentary form, in the attraction mode triggered by the malfunction of ignorance/laziness/delusion.

18 Post-modern Buddhism, Consumer Culture and Marxist Materialism In this way Buddhism is post-modern in the sense articulated by Charles Olson, the great American poet of the 1950s Black Mountain College school of poetics (Olson 1966). He distinguished humanism and energy. Buddhism is very much about recognizing the impersonal nature of the energies in our bodies, so as to diminish their negative effects by not feeding into them. Olson said the post war world was “mu-sick” (Olson 1975, 3), playing off the root from the Greek of both music and myth. He took the commercial jingle as the myth of his times, and he did not like it. Indeed, one of the most brilliant and most futile lines of critique in 20th Century thought was dedicated to analyzing and trying to stop the advertising culture. Books like Captains of Consciousness, Dialectic of Enlightment, One Dimensional Man, Culture of Narcissism and more recently Toxic Sludge is Good for You sought to shed light on this collective nightmare, but generally from a Marxist or Marxian perspective.

Many attempts have been made to combine Marxism and

Buddhism, but usually to ill effect, such as U Nu’s Burma, which led to the takeover by Ne Win’s brutal dictatorship in 1962 (Lintner 1990, 14). Even His Holiness the Dalai Lama is deeply sympathetic with the moral agenda of Marxism, and has confessed to being inspired to come up with his most important concept, universal responsibility, by childhood singing of the Internationale (Gyatso, 1999-2000, 7). Buddhist Critiques of Marxism More interesting to me are critiques of Marxism from the Buddhist perspective, such as the view Carl Springer admitted he shared with me that Marx went too far in his rejection of Hegel, and thus started too far down the road of formation, at the stage when person and commodity are already articulated, thus missing the power of advertising to manipulate our perceptions of need and value. Springer

19 was speaking with reference to a section in Chögyam Trungpa Rinpoche’s Cutting Through Spiritual Materialism, which helped inspire this work, in which the process of the formation of aggregates composing the ego is described in a wonderfully subsumptive way (121-133).

Thus Marxian critiques of the history of the

influence of advertising fail because they lack tools for approaching historically significant epistemological distortions, tools abundant in the Buddhist tradition, relying instead on recourse to some obscured essential human goodness, and offering no methods beyond social control for ameliorating the affliction. Marxism to be sure works at a level Buddhism has been perhaps to politick to address in its long cozy relationship with military and royal power. To survive the coming period massive change of the kind Marxism contemplates and Buddhism usually does not is probably necessary. Perhaps Buddhism could address some of the questions of the relationship of resources to propaganda output driving modern societies into less and less sustainable practices. Ideally, an approach like Swarmsara could show the effects of these distortions geographically, for instance modeling the scenarios for different types of urban sprawl in different political climates. The Buddhist Explanation for World Problems Why, as Buddhism claims, does the illusion of the inherent existence of personhood lead to so much suffering? The Swarmsara simulation attempts a crude demonstration of how this works, how adaptive distortions of perception cycle beyond control. It is reasonable enough for an agent to weight its locus of control, even to put a membrane around its precious resources, to develop locomotion, and subsequently perception, even the problem-solving activity of cognition, but all these developments come with a cost. Each extension into the design space of possibility (Dennett 1995, 101f) comes with a commitment to that one direction, a limitation that exposes the agent to potential disharmony. Jacques Derrida called this the “violence of the letter” (1995, 124-128), the

20 shameful assertion of being in the face of the cosmic void, the vast exclusion of all non-being from the inner circle of the particular. Buddhism, particularly the philosophy of the Hua Yen (Totality) school, extending Dharmakirti’s apoha (differentiation) theory, which states at its simplest, A = not not A, has covered this topic in depth (Chang 1981). It has been said that the eight hundred year history of the apoha theory is the longest of any idea in philosophy. Derrida’s “differance” can be seen in this light as little more than a latter day revival of this ancient idea, and indeed, Derrida has expressed strong interest in Buddhist thought. Once this convenient but harmfully reductive assumption that persons and phenomena exist inherently and independently is in place, in order to continue functioning an agent (in Buddhist terminology, a sentient being) must create compensatory distortions such as attraction and aversion, which spin up into all the texture and complexity of the world sphere as it is perceived, along with a host of subtle and not so subtle afflictive emotions and distorted consciousnesses. This integrated but unhappy process is illustrated by the icon of the Wheel of Life, found in the entranceways of all Tibetan and many other Buddhist monasteries and centers, pictured here as figure 3 in the chapter on algorithms. Swarmsara is a crude attempt to put this wheel in motion. Asking the Unanswerable Questions for Practical Reasons Hannah Arendt said it is by asking the unanswerable questions that we generate the answerable ones (Babcock-Abrahams 1984).

Recent press releases by

scientists pursuing the illusive mass-bestowing Higgs Boson, the last undetected and perhaps the most important of the subatomic particles, point out that the weirder and more abstract the discovery, the more profound its impact on society (Whitehouse 1999). It might not be true that anything useful can be made from

21 the eventual science of the Higgs, or from, as it were, splitting the Buddhist spiritual atom as Swarmsara attempts to do, but the potential is great enough it would be selfish not to try. The Limitations of Reflexivity A major component of the problem this project confronts is immediately reflexive. However altruistic this work is in theory, the worker involved is far from enlightened, and without a great deal of effort on the part of the reader to take this into account, there is a danger the ideas contained herein will only serve to hasten the coming of the long-prophesied age of the “Counterfeit Dharma” (Kato 1978, 373). True expression of Buddhist thought requires a combination of scholarly rigor and meditative insight both lacking in this case. However, the Buddhist critical tradition has adopted such measures as tying tomes of false doctrine to the tails of dogs to be dragged through the dirt (Pabongkha 1993, 69), so probably it can protect itself against clumsy sullies such as this might turn out to be.

To paraphrase an ecological metaphor taken from the Zen tradition, I

only wish the waters of the Wisconsin River were enough to wash my words from your ears. Despite the viability of the Swarmsara model, it is far from established that Buddhism is amenable to a computational approach, even in its critique of the habitual reductionism of deluded creatures, let alone in terms of any of the higher orders of meaning, which it claims to help us discover. Philosophers of computer science have objected strenuously to modeling emotion using numbers (Sloman 1978, 268) although they were not discussing the simple approach/avoidance patterns here called attraction and aversion, but rather the more complex human emotions Buddhism makes a point of distinguishing from their abstract bases, except in texts for the general reader. Thus Swarmsara is breaking envelopes left and right, a clear case of Derrida’s shamefully violent letter, and only the most sympathetic of Buddhist

22 philosophers could forgive the enterprise of starting Samsara over again, when all efforts over the centuries have been bent towards ending it.

23 Chapter 3

ALGORITHMS

Universes as Algorithms

Figure 1 Self-reproducing Inflationary Universes. Andrei Linde and Dimitri Linde, Stanford University.

24 Life, it has been said, is an algorithm independent of substrate (Dennett 1995, 4660). An algorithm is an input/output process. Life is not an essence given authority by some inherently existent higher mind. It is whatever works at the time, the slow accretion of potential energy into memory and information, until cumulative selection can start to ascend the fitness landscape, itself a nascent collective life form billowing through reflexivity further and further from its base in some generated set of rules, themselves probably selected by the slow gears of evolution.

Indeed, recent advances in quantum cosmology strongly suggest

universes themselves are subject to one or many selection processes (Linde 1991, Guth 1991, Benford 1999). Evolving Universes Consider for example figure 1, taken from a recent computer simulation of selfreproducing universes emerging from a false vacuum. In this scenario, Andrei Linde envisions an evolutionary positive feedback loop in which universes prone to rapidly produce more universes prone to inflation tend to proliferate (Linde 1990, 25-28). The strange thing though is our particular universe is not of that type. Although recent studies suggest our universe may be on the cusp of tipping over into inflation (Linde 1998), it has persisted for billions of years in relatively stable form. Allen Guth’s research indicates that with a theory of quantum gravity, and with energies and technologies far beyond anything conceivable today, it should be possible, by way of quantum tunneling, to create universes in a laboratory from artificially manufactured false vacuums (Guth 1991, Farhi 1990, Benford 1999). Guth and Linde are two of the most highly respected scientists working today, so their speculations, however far beyond the constraints of pure empiricism, should not be taken lightly. In effect they have shown that this universe may have a navel, in the form of the false vacuum that gave rise to our big bang, and reproductive organs, in the form of the hypothetical technology that could be used for producing further universes. Just as finding a watch on a

25 barren moon is a sure sign life has been there, this strongly suggests our universe is the product of an evolutionary process, that it is an algorithm started with input and capable of producing output. And it is also interesting that there may well be a high threshold for our universe to be capable of reproduction. If so, it may also be true that only advanced technological civilizations can reproduce this type of universe. In other words, universes like this could be the domestic animals of the intelligences that come to inhabit them, and subject to the more directed evolutionary rules to which Darwin dedicated the less heralded portion of his life’s work, those governing the breeding practices of farmers and gardeners. This would explain nicely and simply why our universe is so exquisitely tuned for producing intelligent life, without recourse to theology. And like the origin of the eye, however primordially, this lineage of self-reproducing universes could have come about by easy stages, gradually separating away from the more violent highly inflationary realms, first producing patchy life, then more sustained but still ephemeral varieties, finally the great civilizations capable of producing nearly perfectly tuned new universes. This might have happened in a way similar to Cairn-Smith’s theory of life’s origin, in which simple but easily-started replication processes in clay came to support organic chemistry as an adaptation, eventually to be supplanted by it like the removed scaffolding used for creating an arch (Dennett 1995, 157-158). In fact, as Lee Smolin points out in his similar theory about black holes being the driving force of self-replicating universes, it should be possible to gather observational data to test such hypotheses (Smolin 1997, 301327). It should be possible through sophisticated simulations to determine what a universe perfectly tuned for life would be like, in terms of certain variations in the standard cosmological model.

Then applying principles of ecology and

perhaps even running simulations, it should be possible to get an estimate of the range of variation from this optimum condition tolerable for a given universe type. In Smolin’s scenario, the prediction would be that our universe would be

26 almost but not quite perfectly tuned for producing black holes of a certain kind, because evolutionary processes tend to be sub-optimum. But if our universe was produced by an artificial process by agents in a previous universe, it might be as perfectly tuned as their science could make it, or perhaps, even more interestingly, it might be off kilter just enough for that to inscribe a signature or message for the benefit of the agents coming to awareness in their creation, like the brand on a cow.

Figure 2: Lee Smolin’s evolving universes: original caption says “a possible fitness landscape for cosmology on a two dimensional slice of the space of parameters of the standard model. The altitude of the landscape is proportional to the number of black holes a ‘universe’ with each values of the parameters will produce. The cats represent a population of ‘universes’ after a number of ‘generations.’” (Smolin 1997, 99)

27 The Dalai Lama’s Cosmology The strange thing is there are indications His Holiness the Dalai Lama seems to think about universe-creation in a comparable way. When questioned directly on the subject, he said the following: Q: Interest in the discoveries of modern astrophysics and the "Big bang" theory reveal both a great fascination in the cosmos and a probing interrogation by members of our generation into their origins, their destiny and the meaning of their existence. The "Big bang" theory has had a significant impact on our way of looking at matter and nature; it has introduced considerable conceptual innovations. The formation of the structures of the universe, which function in interdependence, and which new research continues to reveal, is a seemingly endless source of wonder. Like all spiritual traditions, Buddhism conveys a cosmogonic myth. And yet Buddhism rejects the idea of creation. Why? Most Western scientists think that life and consciousness are a magnificent result of the universe's material evolution, and yet they know neither how nor why matter emerged in such a way as to fulfill the conditions necessary to engender life and consciousness. What they do know is that these conditions are very strict, yet have nevertheless been fulfilled in our universe in an astonishing way. You have a very different point of view on this subject. Would you therefore speak to us about consciousness in its relation to matter and the universe? A: Why is there no creation possible in Buddhism? It has been said that one cannot find living beings at the becoming of the universe for the essential reason that causes have no beginning. If there were a beginning to the universe, there would also have to be a beginning to consciousness. If we accepted a beginning to consciousness, we would also have to accept that its cause has a beginning, a sudden cause which would have instantly produced consciousness; this would lead

28 to a great many other questions. If consciousness had arisen without cause, or from a permanent cause, that cause would have to exist on a permanent basis, always, or not exist at all, ever. The fact that a phenomenon exists intermittently proves that it depends on causes and conditions. When all the conditions are met, the phenomenon is produced. When those conditions are absent or incomplete, the phenomenon does not appear. As causes have no beginning and stretch back to infinity, the same thing must apply for living beings. Creation is therefore not possible. Let us now consider a particular phenomenon, a glacier for example: it does indeed have a beginning. How was it created? The outside world appears as a result of the acts of sentient beings who use this world. These acts, or karmas, in turn originate in the intentions and motivations of those beings who have not yet taken control of their minds. The "creator of the world," basically, is the mind. In the Sutras, the mind is described as an agent. It is said that consciousness has no beginning, but we must distinguish here between gross consciousness and subtle consciousness. Many gross consciousnesses appear as dependents of the physical aggregates, of the body. This is evident when you consider the different neurons and the functioning of the brain, but just because physical conditions are met does not mean that this is enough to produce a perception. In order for a perception which will have the faculty to reflect and know an object to arise, it must have a consubstantial cause. The fundamental consubstantial cause, of the same substance as its result, will in this case be the subtle consciousness. It is this same consciousness or subtle mind which penetrates the parental cells at the moment of conception. The subtle mind can have no beginning. If it had one, the mind would have to be born of something that is not the mind. According to the Kalacakra Tantra, one would have to return to the particles of space to find the fundamental consubstantial causes of the external physical world as well as of the

29 bodies of sentient beings. Buddhist cosmology establishes the cycle of a universe in the following way: first there is a period of formation, then a period where the universe endures, then another during which it is destroyed, followed by a period of void before the formation of a new universe. During this void, the particles of space subsist, and from these particles the new universe will be formed. It is in these particles of space that we find the fundamental consubstantial cause of the entire physical world. If we wish to describe the formation of the universe and the physical bodies of beings, all we need do is analyse and comprehend the way in which the natural potential of different chemical and other elements constituting that universe was able to take shape from these space particles. It is on the basis of the specific potential of those particles that the structure of this universe and of the bodies of the beings present therein have come about. But from the moment the elements making up the world begin to set off different experiences of suffering and happiness among sentient beings, we must introduce the notion of karma - that is, positive and negative acts committed and accumulated in the past. It is difficult to determine where the natural expression of the potential of physical elements ends and the effect of karma -- in other words, the result of our past acts -- begins. If you wonder what the relation might be between karma and this external environment formed by natural laws, it is time to explain what karma is. Karma means, first of all, action. We distinguish one type of karma which is of a mental nature, a mental factor of volition or intention. There also exist physical and oral karmas. To understand the connection between these physical, oral, or mental karmas and the material world, we must refer to the tantric texts. The Kalacakra Tantra in particular explains that in our bodies there are to be found, at gross, subtle, and extremely subtle levels, the five elements which make up the substance of the external world. It is therefore in this context, I believe, that we must envision the connection between our

30 physical, oral, and mental karmas, and the external elements. (Gyatso 1996) It should be noted His Holiness puts an emphasis on the primordial continuity of mind, usually anathema to hard scientists. Although this problem is critical to the long-term effort to relate Buddhism, or part of Buddhism at least, and science, it is incorporated into the algorithm of the Swarmsara simulation in a specific way, and is not addressed as such. Buddhist philosophical schools give differing weight to the primacy of mind, and many doctoral dissertations are written on the subject, the consideration of which would comprise a much larger study than the present one. In brief, the point of the above argument is that current cosmology calls into question the primacy of physics over evolution, and in so doing, opens the door to a much larger role of agent-based processes in reality in general. If we accept a very weak definition of sentience as wanting to happy and not to be unhappy, while Mind with a capital M is an open space beyond the physical substrate seamlessly coupled with an ontological voidness of inherent existence, then we can proceed without, hopefully, angering the protectors of science or Buddhism overmuch.

31 The Wheel of Life The above suggests the evolutionary life process can be considered independent of its biological substrate, a perception supported by innumerable experiments in artificial life, particularly Tom Ray’s famous Tierra simulation. It also suggests Buddhism has something like an evolutionary cosmology of its own, and indeed, it looks something like this:

32

Figure 3: The Wheel of Life (Khorlo)

33 This icon, known as the Wheel of Life, is found in most Tibetan Buddhist meditation halls. It portrays the six realms, or universe types, surrounding the inner engine of the three primary afflictive emotions, in the clutches of Yama, the Unsympathetic Lord of Death, or in other words, if you will, Darwin.

The

central driving principle of the whole thing is the subject of this thesis, the three primary kleshas and their relationship to karma, so they bear closer examination:

Figure 4 The Inner Circle

The pig symbolizes the lazy deludedness arising from ontological ignorance, the rooster symbolizes attraction, and the snake symbolizes aversion. They are biting each other’s tails to symbolize how they trigger each other in turn. I will have

34 much more to say about these basic emotional reactions later, but for now, they serve as introduction to a description of the Swarmsara algorithm as such. Samsara’s Algorithm An early Buddhist scripture says, simply, “kamma [karma] and passions [Pali: kilesa, Sanskrit: klesha] are the cause of Samsara” (Rhys Davids and Stede 19211925, III 20). Swarmsara is an attempt to implement this simple model using currently available tools, specifically those available through the object-oriented computer language Java.

It is important to realize that despite their evocative

symbolic representations, the kleshas can be understood to be abstract and simple. Although they give rise to complex human emotions like context-specific anger, a microbe is capable of experiencing them.

They are almost at the level of

Newton’s laws of motion. An agent might be indifferent to an object, it might be drawn towards an object, or it might be repelled by an object. In biology these last two are usually called approach and avoidance, and these terms would be suitably applied here as well, the only reason why not being the evolution of the project and the intended audience of computer scientists from Buddhist cultural areas. Note that these simple ways of an agent relating to its surroundings call for a spatial model, perhaps due to the original relationship of the kleshas to the elements and the mandala, to be discussed later. Karma and Perception Karma is the law of cause and effect, and it too can be understood as a simple information process, that is, whenever an agent performs an action, it leaves a mark in the world, but also an imprint on an internal template which goes with it, such that when suitable external conditions are encountered, the imprint comes to fruition, causing the agent to experience some kind of delayed consequence. Karma arises only when the agent is ruled by a klesha (Sunthorn 1976, 76). Also

35 an agent can only experience events, positive of negative, it has the previous karmic predisposition to perceive. This is similar to Nietzsche’s famous ‘All Nature faithfully’ – But by what feint Can Nature be subdued to art’s constraint? Her smallest fragment is still infinite! And so he paints but what he likes in it. What does he like? He likes/what he can paint! (Gombrich 1977, 75) which has had a huge impact on post-modern critical theory, for instance in the work of Gombrich (1977) and Fish (1980). Probably karma and the kleshas are to be understood as two aspects of the same thing, but it is useful to model them as separate categories, as they are in Buddhism and in Swarmsara. To get a sense of their relationship, consider “When a man’s deeds, O bhikkhus, are performed through covetousness...are performed through hatred...are performed through infatuation, arise from infatuation, are conditioned by infatuation, originate in infatuation, wherever he may be born, there those deeds ripen, and wherever they ripen, there he experiences the fruition of those deeds, be it in the present life, or in some subsequent one. (Anguttara-Nikaya Ekanipata, 20/473/171-172)” (Sunthorn 1976, 76) and “When a man’s deeds, O bhikkhus, are performed without covetousness...are performed without hatred...are performed without infatuation, originate without infatuation, then, inasmuch as infatuation is gone, those deeds are abandoned, uprooted, made as if a topless palmyra-tree, and become non-existent and not liable to spring up again in the future. (Anguttara-Nikaya Tikanipata, 20/473/171-172)” (Sunthorn 1976, 76)

36 which are the Buddha’s own words, from the original Pali Canon.

In the

Swarmsara implementation this comes into play in that agents that do not have distorted emotional states do not accumulate karma. The Samsaric Experience Samsara is the whole afflicted world system in the clutches of Yama, portrayed in figure 3 above. More simply, it is what happens when agents driven by kleshas and karma interact. The unhappy consequence, according to Buddhism, is that they are perpetually dissatisfied. Note that this diagnosis (in the humoral medical sense, to be discussed later) also could well be a testable hypothesis. The Actual Design of Swarmsara I woke up one morning sure it would be possible to model the kleshas using integers and a simple spatial metaphor. I chose to use the classic Von Neumann neighborhood for the perceivable world of an individual agent, in other words, the tic-tac-toe board composed of a center and eight square cells around it. For simplicity’s sake, the agents live in a toroidal (wrap around) raster grid landscape. Agents can be affected by each other’s actions in the landscape, but do not otherwise interact, except in that they occasionally displace each other, since only one agent can occupy a cell at a time. This could of course be implemented differently. The agents do not die or reproduce, because their substrate is the big timescale of beginningless reincarnations of a mental/karmic continuum as described above by His Holiness. Death obviously is important in Buddhism, but it seemed interesting to challenge the common assumption that death is key to the life process per se, and must be included in an artificial life simulation. More on this later.

37 Implementation of Kleshas The simulation starts with the agents moving around, unaffected by emotions or karma, producing and consuming resources at random. Because they do not have emotions, they do not produce karma, and this is rooted in Buddhist doctrine as mentioned above. Then when they enter a cell where they find an amount of resources, i.e. produced karma, above a threshold that can be adjusted by the experimenter, it causes the agent to acquire a unit of “ignorance”, more properly termed delusion, or laziness. This causes the agent to weight its current cell as more valuable than it really is by that amount, as below, where the agent has accumulated ignorance over 40 time steps. This means it thinks its current cell is worth 85 rather than the 45 of its substrate, and will choose to stay put even though in reality there is a more valuable cell, the one containing 70, in its neighborhood. Table 1: Ignorance/laziness/delusion

20

1

4

70

45 + 40

22

22

23

44

38 This is a reasonable survival strategy, within limits, because it is good not to expend energy when one does not have to, and if experience indicates there are enough resources locally, it is foolish to move. However, this strategy will start to backfire once it gets exaggerated enough. Therefore, when an agent goes over a certain threshold of accumulated ignorance, and its real resources are below a threshold, attraction (approach) starts to kick in, causing the agent to weight the surrounding cells as more valuable than they really are. Table 2: Attraction/approach

20+20

1+20

4+20

70+20

45 + 40

22+20

22+20

23+20

44+20

Now the agent can behave more appropriately, going to the more valuable cell, even though it thinks it is worth 90 rather than its actual 70. This strategy too starts to fail as attraction grows too strong, and then aversion (avoidance) is triggered.

39

Table 3: Aversion/avoidance

20+20

1+20

4+20

-95

-95

-95

70+20

45 + 40

22+20 -95

-95

22+20

23+20

44+20

-95

-95

-95

This causes the agent to run away from the least valuable cell in the neighborhood, when aversion is strong enough to outweigh attraction and ignorance/delusion/laziness. And when presumably high-cost aversion gets too strong, it triggers more ignorance in turn. In the implementation some other things happen, such as ignorance decreasing when attraction is triggered, but this is the gist of it.

40 Implementation of Karma

Karma 20+20 -95

1+20 -95

4+20 -95

70+20 -95

45+40

22+20 -95 12

22+20 -95

23+20 -95

44+20 -95

34 22 12 12 33 44

Figure 5: Populating the Karmic Template

When an agent adds resources to its current cell, this action is recorded in a template, implemented as a hash table to take advantage of that data structure’s rapid retrieval capabilities. In this example, the agent has added twelve units of resources to its cell, such that on the next time step the cell will have 45+12(resources extracted). Note that the hash table is composed of integer objects, so there can be more than one instance of a twelve in the table. This is important for future versions of the simulation, since karma should be conserved.

41

Karma 20+20 -95

1+20 -95

4+20 -95

70+20 -95

45+40

22+20 -95

22+20 -95

23+20 -95

44+20 -95

34 22 12 12 33 44

Figure 6: Karmic Restrictions on Perception

Karma affects the agent by determining which cells it is able to see. It can only see cells that have numbers found in its existing list of past actions. This reflexive blindness is actually much closer to what the Buddhists mean by Avidya (“not seeing”), the cause of all other problems, than the laziness portrayed by the pig in the wheel of life. This emerged during the implementation of the simulation and is one of the most important results of this project. Emergent Avalanche? Another result of this is emergent behavior similar to what complexity theorists call avalanche. It occurs when a system is blocked from change at the local level, but ripe for it more generally.

In Swarmsara, this can happen due to a

combination of circumstances, such as cells being occupied by other agents, or the agent not having suitable karma to move into its local neighborhood. By the time the logjam breaks, it has built up a long list of karmic objects and can move freely for some time. This effect is observable during runs of the simulation.

42

Avalanche 20+20 -95

1+20 -95

4+20 -95

70+20 -95

45+40

22+20 -95

22+20 -95

23+20 -95

44+20 -95

34 67 12 12 33 23

Figure 7: Karmic Avalanche

In the example the agent cannot move to any adjacent location because it does not have the karma to perceive anything outside itself in its neighborhood.

43 Chapter 4

KLESHAS The Mother Culture This project is intended to be an exercise in the defense of indigenous knowledge. Buddhism is a modern religion, created by a conquering patriarchal people. But Buddhism arose from many factors, not just the military ideology of the Aryans. Theory has it that the Aryans did not know yoga, and had to be taught by the preexisting inhabitants of India, as evinced by the dialogs in the Upanishads where a kshastriya of the warrior caste, son of an indigenous mother, has to lecture a purebred Brahmin priest about these matters (Campbell 1968, 201-206). The Buddha himself was a kshastriya, an interbred warrior king, and not a pure Aryan. Put another way, the symbol system built on the metaphor of the chariot came from the fathers, while the spatial metaphor of the mandala, used incidentally for structuring administration (Tambiah 1976 102-122; Childers 1909, 309) came from the more indigenous mother culture. The mandala theory divides reality into five primary components, and successive associated powers of two, for instance the thirty-seven (1 + 4 + 32) ministers of Burma (Tambiah 1976 109), the 1024 arms of the Thousand Armed Chenrezig (one kilobyte!) or that quintessential example, the five elements. Thus, arguably, the theory of the elements came from the Neolithic mother culture. Ecofeminist Development Work To do indigenous-knowledge-based development work successfully, it is critical to work with women. They are the bearers of the tradition, the reciters of “old wives’ tales”, those who often must do the physical drudgework most closely

44 related to the land. But in this modern late-patriarchal era their voices are too often ignored.

In one case related by the eco-feminist Karen Warren,

development experts tried to get local people to use solar stoves, for all kinds of good reasons, working with the local people (of the wrong gender), but for some reason the women were not using the stoves. When finally asked why, they explained that it was far too hot to cook in the midday sun in that climate (Warren 1992, 35). Deconstruction East and West For soteriological reasons Buddhism goes to great lengths to deconstruct all the categories it posits, and the elements are not exempted (Nagarjuna 1975, 70-71). Although science has long since supplanted humoral medicine and the physics of the elements, the root metaphor, like a prairie remnant, continues to pervade our culture. Every time someone is said to have a sense of humor, or to be cool, they are talking humoral medicine, and indeed, our sense of resignation about the immutability of human nature has everything to do with this fossil system of thought. If Buddhism is right, the mind will do everything it can to bolster its sense of its own permanence, even at the expense of hope. If sense of humor means a resigned attitude towards life based in a recognition of our susceptibility to emotional distortion, we would do well to recall that the theory also originally came with some suggested cures. For example, if the theory is right, it should be possible to “cool” inflamed humors, to achieve what Buddhists call Nirodho, or Nirvana, a cooling or quenching of the passions, or that quality of cool that the OED says hipsters in the 1950s associated with the non-attachment of a Zen monk (OED 1991). More subtly, the great works of literature of the western tradition, notably Shakespeare, are steeped in humoral medicine. Shakespeare’s characters have distinct “humorous” emotional profiles, and in some cases the association is explicit, as in the case of As You Like It’s Melancholy Jacques, who might well have been a figure for the bard himself. Freud looked to Shakespeare

45 for inspiration (Lupton and Reinhard 1993), so this means the influence of this non-scientific tradition runs through the discipline of psychology as well, and we would do well to be more aware of its graces and pitfalls. The strategy of ontological deconstruction as practiced in western post-structuralism and ancient Indian thought is to look for hidden assumptions driving social thought, to uproot their absolutist or nihilist aspects, and to return them “under erasure” (Derrida 1978). The humoral tradition is an ideal subject for this approach, not least because it continues especially in Asia to have a huge influence on practical political thought (Tambiah 1976, 102-112; Lintner 1990, 91). But not just in Asia -- even the state capitol of Madison, Wisconsin is constructed in the centered, four-sided design of the mandala, as inherited from ancient European culture. Ayurvedic Medicine A case in point is the revival of Ayurvedic medicine that occurred in India during the independence movement from Britain (Foster 1994, 9). Part of the colonial strategy was (and is, unfortunately) to argue that a local culture is not civilized enough to be modern, and that therefore they needed supervision from the colonial power, by gunboat if and when missionary attempts fail (Curtin 2000). India has been invaded many times, and the soul of India resurrects by remembering its origin, more or less successfully. It never quite got rid of the Aryan gods, but it managed to promote a few of its own, e.g. Shiva and Kali, into the pantheon, much as Venus and Bacchus re-emerged in the western context (Ovid 1958, 100-107). In the case of the Buddha, it is not insignificant that the Aryan gods that had vowed to protect him on the night of his enlightenment all ran for it when the demon army showed up, but the Earth Goddess stayed to protect him and drove the army off in a great flood of water wrung from her hair, composed of the boundless offerings to the land the Buddha had made in his previous lives whenever performing a virtuous deed (Thurman 1992, 23). During the independence movement, Indian scholars rediscovered the Ayurvedic

46 tradition, and asserted that it was arguably more ancient than the Greek Hippocratic humoral tradition, and that therefore the British had no right to rule them, since as the originators of such a great tradition, India was clearly worthy of self-rule (Foster 1994, 9).

This is proof positive that the strategy of bolstering

this very kind of indigenous knowledge can have serious historical and political implications.

However, India went on to establish 91 Ayurvedic universities

where extra-scientific practices are taught (Upada 1975, 64-65), and Hindu nationalists are now among the more extreme groups in the world. Again, although a powerful strategy, we must be careful to consider the consequences of working with indigenous knowledge like this and to proceed as best we can, under erasure. The Humors So how do the humors work, and how do they relate to Buddhism? According to Terry Clifford, the Four Noble Truths of Buddhism, the Buddha’s first teaching and Buddhism’s most central doctrine, are phrased in the format of an Ayurvedic diagnosis and prescription (1984, 38-39). The Buddha, Clifford says, was himself interested in Ayurveda, many Ayurvedic physicians were Buddhists and Ayurvedic medicine flourished under the early Buddhist kings (1984, 35). The Buddha is often described as a physician, as in Clifford’s quote of Heinrich Zimmer’s quote of H.D. Thoreau’s translation of the Lotus Sutra: The Buddhist medicinal analogy is clearly stated in the Sutra entitled Lotus of the Good Law, in which the Buddha said In this comparison, the Tathagata must be regarded as a great physician; and all beings must be regarded as blinded by error, like the man born blind. Affection, hatred, error, and the sixty-two false doctrines are [the humors] wind, bile, phlegm. (Thoreau’s translation) (Clifford 1984, 39)

47 But Buddhism can never leave categories alone.

The great Pandit Acharya

Nagarjuna tackled the subject of the elements explicitly in his Precious Garland: 358 The senses and their objects are regarded As being composed of the elements, Since the individual elements Are unreal, so too are those objects. 359 If each element is different It follows that there could be fire without fuel, If mixed they would be characterless And this is true of the other elements. 360 Because the elements are unreal in both These ways so too is composition, Because composition is unreal So too in fact are forms (1975, 70-71). Although there are four physical elements, wind, fire, water and earth, J. Filliozat explains only the first three are important to medicine, because the earth is associated with less volatile substances like bone (1964, 28). But the first three as expressed as the three humoral imbalances (tridosa in the Sanskrit) work in dynamic relationship to each other, while at the same time being ascribed as causes for specific maladies with no doubt varying degrees of accuracy.

48

Table 4: The Humors (after Clifford 1984, 92-93)

Humor (Tib. nyes-pa; Skt. dosha, lit Production encouraged by “fault”) WIND/AIR (tib. rlung; “lung”; Skt. vayu)

Desire, attachment and lust; etc.

BILE (Tib. mkhris-pa, “tripa”; Skt. pitta)

Anger, hatred and aversion; etc.

PHLEGM (Tib. bad-kan, “bekan”; Skt. Spiritual ignorance and physical sloth; etc. kapha)

The humor wind, prana, is associated, not surprisingly, with the element of air, and with the emotional impulse of attraction (skt: raga). Fire is associated with the two kinds of bile, and the emotion of aversion (skt: dresha), while water is associated with phlegm, and the emotion of spiritual ignorance (skt: avidya). In the Buddhist emphasis the kleshas (emotions) cause the humors. As Clifford (1984) puts it All the thousands of kleshas can be condensed into the so-called ‘three poisons’ – confusion, attachment and aversion, which all arise from fundamental ignorance or unawareness. (6) and The three humoral constituents of the body are understood to have evolved from the three primary faults or obscurations of the mind: phlegm from ignorance, air from craving, and bile from hatred. (8)

49 But clearly this might be a latter-day a priori imposition, similar to the way metaphors are sanitized and then reintroduced in the process of governance (Judge 1991). Tibetan medicine as a living tradition, of which Clifford is a practitioner, was introduced into Tibet not by way of the Ayurvedic tradition but from a Greek doctor named Galenos much later, then retrofitted with the Buddhist doctrine and the Ayurvedic texts which had found their way into the Tangyur, part of the Tibetan Buddhist canon (Clifford 1984, 38, 53). However, according to Clifford, Zimmer emphasizes that from the outset the tridosa were about “not just airy, bilious and mucous matter found in the bodies but three principles of life-energy” (1984, 52) so the intuition that the idea must be rooted in merely physical processes may be a false one. Scholars of the tradition describe some of the ways in which the humors condition each other, and the capacity of the wind element/humor to condition the other forms is key to the central Buddhist practice of Anapanasati as taught by the great modern Buddhist saint Ajarn Buddhadasa and by the original Buddha as his own personal practice (Buddhadasa 1988a, v). As Filliozat says, “pneumatology … dominates the physiology of Ayurveda” (1964, 170). Buddhadasa emphasizes the interconnectedness of the elements: The elements (earth, sky, atmosphere) of a suitable and happy life cannot exist independently. They must exist relative to one another. Looking at this assertion at greater depth, if only the earth element exists, how will it be useful? There must also be elements of water, fire, air, and spirit (vinnana). If they interrelate well, there will be a balance in nature among human beings, animals, trees, earth, water. Anything which exists in a proper condition has everything in balance. (1986, 104-105) It is clear these are not static categories. But a line from a Tibetan Buddhist tantra is even more revealing: “The wind moves, the fire blazes, the substances

50 inside the skull cup melt and boil” (Phabongkha 1990, 35). In this case, the elements are visualized as reality source mandalas, holding up the skull cup in which foul substances representing the worldly condition are transformed into nectar. Note first the interaction between the elements, as part of a dynamic whole.

Of course this visualization, although taking place in a void, does not

take place in a void, because it is meant to affect the body through the evocative power of its symbols. So it is saying it is possible to transform the body/mind through careful management of the balance of the humors. Note also, that the metaphor involved is one of cooking. The tantra in question, that of Yamantaka, comes from very ancient origins. Buffalo-headed Yamantaka sports an array of Neolithic ritual implements and weapons, and is clearly a Buddhist version of the bull god that was renamed Shiva and Dionysus, the consort of the Goddess. Buddhadasa, in the modern era, uses the heated liquid metaphor explicitly: The pre-dawn is an especially suitable time for thinking, discussing, and investigating things clearly because the mind is very clear and open at this time. By late morning, however, the teacup begins to fill up. Then, we go and mix some alcohol in with the tea and it really starts to boil. It overflows, making everything chaotic and confused. When our teacups overflow, we argue so loudly that it can be heard from a kilometer away. Now, our teacups have not yet filled to overflowing, the mind is still subtle and clear. When our teacups are not yet brimming, we are able to discuss, examine, and investigate things in a subtle and deep way because our minds are still calm and quiet (1999). Returning to the true holders of indigenous knowledge, women, who would be more likely to create a world system and a view of how the body works based on the metaphor of cooking? In any case, the metaphor involves what science now calls phase change, and which is one of the most important aspects of complexity theory.

51 So Ayurveda medicine is significant to this project in several ways. It has played a role in the history of India at two important junctures, as a major motive force and inspiration for Buddhism, and as a motive force for the Indian independence movement from Britain.

Also, it bears noting the continuing influence of

humoral categories on our thinking, and a strategy of ontological deconstruction taking off from Acharya Nagarjuna’s and Derrida’s is suggested. The kleshas, derived from the three active elements, are a major component of the Swarmsara simulation. If it is true they are rooted in the Neolithic mother culture, working with them has the potential to serve as a bridge between indigenous knowledge and high technology.

52 Chapter 5

KARMA Definition Half of the ancient formulation stated in the early Pali as “kamma and passions are the cause of samsara” and much later by the Twentieth Century Tibetan master Kyabje Pabongkha Rinpoche as “Owing to karma and delusion, the aggregates are formed” adding “samsara is one’s continuum of rebirth into the contaminated aggregates” (Pabongkha 1993, 474) is that idea of karma. Karma is cause and effect. In Buddhism this happens at the mental, ethical level as well as at the purely material level, the skanda (aggregate) called sukh (form), the other four skandas being heaps of mental objects crowned by consciousnesses, similar in spirit to the scientific view of the brain developing in layers associated with progressively more sophisticated animals (Damasio 1995, 125-163). The American Heritage Dictionary defines karma as kar·ma ... n. 1. Hinduism & Buddhism. The sum and the consequences of a person’s actions during the successive phases of his existence, regarded as determining his destiny. 2. Fate; destiny. [Sanskrit karman (nominative karma), act, deed, work, from karoti, he makes, he does. See kwer-1 in Appendix.*] (1981, 715) To be sure, in common usage karma means something like fate, or aura, but in technical Buddhism the term gets much more precise applications. Laws of karma and various kinds of karma are described with a care reminiscent of Newton’s laws of motion (Phabongkha 1993, 429-470). Indeed, among the core doctrines of Buddhism karma is considered one of the most difficult to

53 understand from an experiential or rational level. His Holiness the Dalai Lama goes so far as to argue that for most people, since karma is so hard to grasp, practitioners should extend it a provisional faith based on the reliability of other aspects of the Buddha’s teaching, a Buddhist version of Coleridge’s willing suspension of disbelief (Gyatso 1988, 69-72). At the same time, one of the main debates in modern Buddhism is over whether karma is a key component of Buddhist religion, with scholars like Steven Batchelor coming down on the side of dispensing with it, while Robert Thurman, otherwise thoroughly modern, arguing that if you don’t believe in karma you are not Buddhist at all (Buddhism in America 1998). To complicate matters, great philosophers like Acharya Nagarjuna and yogis like the Dzog Chen masters question the very existence of karmic cause and effect. Acharya Nagurjuna takes apart the phases of the moment and shows how it is impossible for them to connect together if they exist in the way they are characterized (Nagarjuna 1986, 95-105). To get a sense of how powerful a deconstruction this is, note that the three stages of the moment, beginning, middle and end, together with their assumed propensity to make a next moment, pretty well describes the basic algorithmic process. Nagarjuna is saying algorithms don’t happen in anything like the way we think. To simplify matters, Sharpa Rinpoche, himself an eminent scholar of Tibetan Buddhism, explains to me that karma is merely an information process. When an agent performs an action, the world is affected, but at the same time a “dry seed” is imprinted on the agent’s mental continuum, which comes to fruition later, when appropriate external circumstances are encountered. complex and subject to external influences.

This ripening is

For instance at early stages it is

possible to eradicate a karma entirely, and later to mitigate it. In a famous story, Angulimala, a follower of the Buddha who had murdered 99 people at the behest of his previous teacher, was caught and beaten to a pulp by the families of his victims. The story goes because he was practicing Buddhism he lived through the

54 ordeal, when otherwise he would have been killed by his karma coming back in this rather direct way (Silacara 1953). The law of karma is often stated as “good actions produce good results, and bad actions produce bad results”, but it should be understood that good in Buddhism is defined as something more like sustainability and bad as something more like dissipation. Buddhism being a vast and internally contradictory tradition, this of course is merely one take on the meanings involved. To further intuit what is meant by karma it is interesting to consider the origin of the word, and what might be suggested by its cognates in English. Etymology and Cognates The the American Heritage Dictionary says the Indo-european root of karma is kwer, meaning, “to make, to do: kwer-1. To make. 1 Sanskrit kr, to make, do: PRAKRIT, SANSKRIT. 2 Suffixed form *kwer-or with dissimilated form *kwel-or in Greek pelor monster (perhaps that which does harm); PELORIA. 3. Sufffixed form *kwer-esin Greek teras, monster: TERATOID. 4. Suffixed form *kwer-mn- in Sanskrit karman, act, deed: KARMA. (1981, 1525) Note that it has only a handful of cognates in English: pe·lo·ri·a ...n. Botany. Unusual regularity in the form of a flower that is normally irregular. [New Latin, from Greek peloros, monstrous, from pelor, monster, prodigy. See kwer-1 in Appendix.*] (1981, 968) ter·a·toid ...adj. Like a monster, monstrous. [New Latin teras (stem terat-) abnormality, from Greek, monster (see kwer-1 in Appendix*) + -OID.] (1981, 1327) ter·a·tol·o·gy ...n. The biological study of the production, development, anatomy, and classification of

55 monsters. [Greek teras (stem terat-), marvel, monster (see teratoid) + LOGY.] (1981, 1327) ter·a·to·ma ...n., a tumor consisting of independent germ cells. [New Latin : Greek teras (stem terat-), monster (see teratoid) + OMA.] (1981, 1328) What could be implied by the fact that the only words in English related to karma all mean something monstrous? At the risk of over reading, this brings to mind Ron Silliman’s (1987) ideas about Frankenstein’s Monster as an image for the literary creation, based on Freud and Hoffman’s imagery as well as of course Shelley’s.

Advanced practices in Buddhism entail substituting an often-

monstrous (but divine) self-image for the habitual one, and Yama, the god gripping the Wheel of Life, is clearly a monster. Some lamas such as Khenpo Könchog Gyaltsen Rinpoche use the phrase “inveterate negative propensities” to describe the deep-seated karmic habits we must overcome. In other words, we have karmic habits that almost have a life of their own, that survive over long periods of time. Karma and Memes Beyond the obvious comparison to Jung’s idea of autonomous complexes, this is reminiscent of Dawkins’ and Dennett’s theory of memetics (Dennett 1995, 341370), the idea that ideas can take on a kind of parasitic life of their own, reproducing themselves either to the benefit or at the expense of their hosts. Consider the WWI soldier going over the top of the trench, for God and country. In other words, the theory of karma is akin to the theory of genetics and its extensions in Neo-Darwinian evolutionary biology. And what is a monster but an automaton, and what is artificial life but the theory of self-reproducing automata developed by John Von Neumann back in the 1940s?

56 Ecosystems of Karmas This might work in a way like Stuart Kauffman’s ideas about the emergence of input/output processes in any sufficiently complex primordial soup (Levy 1992, 134-137). Some karmic acts occur once, come to fruition, and are gone. But others are so attuned that they become habitual, like the act of smoking a cigarette, or committing a murder. Even though murder has horrendous karmic repercussions, it also leads the agent into contexts, like prison or an underground lifestyle, where it becomes more likely to occur again. And the likeable addictions are even more insidious, those based in various manifestations of the klesha here called attraction.

Indeed, the Buddhists call attraction the near enemy, and

aversion the far enemy. It is much easier to fight aversion because it is not a pleasant emotion, while the habits of attraction, like buying a new car, which only later leads to bills and other more subtly painful shifts in lifestyle, present themselves as friends. This is why the Second Noble Truth of Buddhism is often stated as “suffering is caused by desire”. Although the ignorance of self-grasping is the root cause, and the suffering due to acts of aversion is often more acute, the problems of desire are the hard ones to fight, because it goes so much against our grain to do so. In one particularly elegant path of meditation, Anapanasati, which is held to have been the personal practice of the Buddha himself, worldly desires are conquered not by suppressing them or analyzing them, but by refining the experience of pleasure into something very sweet and simple and slow, a regime in which the coarser habitual pleasures and their karmas cannot compete or survive. I mention this to frame a further point about the ecological quality of how karma works. Consider the sleeping sharks of Yucatan. These fish rest on the ocean floor, over fresh water vents, where they can survive, but their adventitious parasites cannot (Cousteau 1975). What if meditation is a similar exercise, a way to subject one’s parasitic memes, those habits of mind and body that use up our resources at our expense, to a regime where they must fall away?

57 Indeed, it is a common subjective experience of meditators on the second or third day of a retreat to feel a dropping away of shriveled dead forms. As the Buddhist rock star David Byrne put it “on the first day, we had everything we could hold/ ooh and then we let it fall/ And on the second day, there was nothing else left to do/ ooh what a day that was” (Byrne 1981). This also relates to complexity.

The routine of everyday life, without awareness, is like a

corrugated fractal landscape where thought forms can easily hide and proliferate. From the human perspective, a tree’s bark looks rough, but more or less like a surface. But to a beetle, that same bark is an endless fractal landscape of much greater circumference, with many places to hide (Wilson 1992, 208-210). Perhaps the conscious mind is like the distance view of that bark, where all seems well but it is not, while meditation is like smoothing the bark of the tree, so the beetles of the brow are flushed out. Karmic Fitness Landscapes This view of an agent’s karma as a thriving ecosystem gives rise to a similar idea, one critical to the future of the Swarmsara simulation, that is, the karmic fitness landscape. This will be discussed at greater length in a later section, but in short, the argument is an agent’s karmas exist in a range of adaptiveness to the individual and the circumstances of the individual. Over beginningless time, an individual’s character develops as an “ecosystem” of these competing karmic habits. With the dawning of human awareness, which is, if Tibetan Buddhism is to be believed, an extremely rare and lucky event dependent on great acts of altruism in previous existences, it becomes possible to extend this adaptiveness through awareness of the karmic process itself.

The human then has the

opportunity to develop much more sustainable, cooperative forms, despite all the other problems concomitant with our increased susceptibility to infection by adventitious memes, such as religion, or political ideology, or the habit of using the word “like” in meaningless pairs, as is happening all around me in the café

58 where I write. That particular parasite seems to thrive on the insecurity of a youth culture that needs extravagant tags (Holland 1995, 12-15), so fragmented its participants have to keep crying out “like, like (me), for I am one of you who uses this trope, an act of abnegation of the shameful indicative for none of us have earned the right to certainty, and those who think they have are not one of us, and I will charm you with a story couched in a metaphorical, subjunctive mood, like, like.” It is almost enough to make one believe in spandrels (Dennett 1996, 267-282). Caveats All this is not to claim karma is not a problematic notion from the modern perspective. Karma is based upon an extraordinary claim, for which there is no extraordinary evidence, i.e., that cause and effect are conserved and come to fruition later in time by virtue of agents having a karmic template called the alayavijnana, a term usually translated as “store-house consciousness”. This is similar to Jung’s collective unconscious (although according the Jungian tibetologist Jeffrey Hopkins, if Buddhism has a theory of the unconscious, he cannot find it), or Freud’s id, and is similarly unproven. Proving the reality of karma through logic is a favorite task of the most brilliant scholastic monks, but such treatises are generally beyond the scope of all but their authors, as they ruefully admit. Those from the Western tradition, inheritors of Aquinus’ logical proofs of the existence of God, would be hard-pressed not to be properly skeptical of such scholarly exercises. So it is not the intention here to try to convince the reader of the scientific or even provisional reality of karma, but merely to explore some of its possible ramifications in terms to which it is not usually subjected.

59 Karma in Swarmsara Nor does the implementation of karma in the Swarmsara simulation come close to doing even the author’s understanding of it justice. On the contrary, like everything else in the program, the simulation of karma is a deliberate oversimplification, in the interests of creating a working prototype, and to leave room for others to expand and elaborate on the work, since it was always intended as a tutelary device, an opening to debate, and never as a final proof of anything. As the simulation stands, the agents are incapable of learning from their past karma, but this is based on Sharpa Rinpoche’s remark to me that a microbe would produce karma, but be incapable of learning from it or controlling it. Within all these constraints the model does succeed in capturing the basic process of agents affecting their world, but also carrying the consequences of those actions around with them until a future external circumstance triggers the fruition. The fact that karma does not start until the agents are driven by afflictive emotions also has doctrinal justification as quoted in the chapter on kleshas. Indeed, it is important to understand that in some sense the kleshas and karma are two sides of the same coin, two aspects of an illusory system based on a false assumption, both perched on an untenable ontological basis, existing only in reflexive dependence on each other. Pratitya-Samutpada and Subsumption Robotics This reflexive cycle is carefully articulated in Buddhism, as pratitya-samutpada, inter-dependent co-arising, the other side of the coin to the emptiness of inherent existence. Most current thinking about the relationship of Buddhism and ecology focus on the more benign level of this process as mentioned in the Introduction, but at the unenlightened level instead of it being the wonderful justification for the liberating necessity of compassion, it is a chain that traps us in a cycle of unbearable suffering. Modeling it may be beyond the capabilities of computers, and it is not central to the theme of this paper, but since it details the relationship

60 of karma and the kleshas in a way standard in Buddhism since the very beginning, following is the Encyclopedia Britannica’s description of the process: pratitya-samutpada (Sanskrit: "origination by dependence"), Pali Paticcasamuppada, the chain, or law, of dependent origination, or the chain of causation--a fundamental concept of Buddhism describing the causes of pain and the course of events that lead a being through rebirth, old age, and death. Existence is seen as an interrelated flux of phenomenal events, material and psychical, without any real, permanent, independent existence of their own. These events happen in a series, one interrelating group of events producing another. The series is usually described as a chain of 12 links (Sanskrit nidanas, "causes"), though some texts abridge these to 10, 9, 5, or 3. The first two stages are related to the past (or previous life) and explain the present, the next eight belong to the present, and the last two represent the future as determined by the past and what is happening in the present. The series consists of: (1) ignorance (Sanskrit: avidya; Pali: avijja), specifically ignorance of the Four Noble Truths, of the nature of man, of transmigration, and of nirvana; which leads to (2) faulty thought constructions about reality (samskara/sankhara). These in turn provide the structure of (3) knowledge (vijñana/viññana), the object of which is (4) name and form--i.e., the principle of individual identity (namarupa) and the sensory perception of an object--which are accomplished through (5) the six domains (sadayatana)-i.e., the five senses and their objects--and the mind as the coordinating organ of sense impressions. The presence of objects and senses leads to (6) contact (sparsa/phassa) between the two, which provides (7) sensation (vedana). Because this sensation is agreeable, it gives rise to (8) thirst (trsna/tanha) and in turn to (9) grasping (upadana), as of sexual partners. This sets in

61 motion (10) the process of becoming (bhava), which fructifies in (11) birth (jati) of the individual and hence to (12) old age and death (jara-marana). The formula is repeated frequently in early Buddhist texts, either in direct order (anuloma) as above, in reverse order (pratiloma), or in negative order (e.g., "What is it that brings about the cessation of death? The cessation of birth"). Gautama Buddha is said to have reflected on the series just prior to his enlightenment, and a right understanding of the causes of pain and the cycle of rebirth leads to emancipation from the chain's bondage. The formula led to much discussion within the various schools of early Buddhism. Later, it came to be pictured as the outer rim of the wheel of becoming (bhavacakra), frequently reproduced in Tibetan painting. (“Pratityasamutpada” 1999-2000) Note that this too takes the form of a cyclic subsumption process, in which states trigger each other in turn. Buddhism as Bottom-Up So another hypothesis emerging from this paper is that Buddhist thought, despite what appear to be many top-down a priori assumptions, such as the conservation of karma, includes in critical places an approach similar to that of the latest bottom-up subsumption robotics.

And again, this is critical in terms of

ecologically sustainable development, if it is true, as much evidence indicates, that bottom-up, indigenous knowledge-based approaches have better chances of success. It is helpful if the indigenous knowledge system in question shares this insight. In the case of Buddhism, this is far from un-problematic, because in the crucible of Asian history many authoritarian forms have crept in, and the debate rages to this day about whether Buddhism is intrinsically authoritarian or

62 egalitarian in nature (Tricycle.com 2001, Damtsig 2001). Clearly, this author would be in the camp supporting the latter idea.

63 Chapter 6

ARTIFICIAL LIFE Complexity theory has many branches, and it is beyond the scope of this work to cover them all, or even enough of them to adequately explain the ways in which Swarmsara interacts with that discipline. However, in order to understand the relevance of some facets of Swarmsara’s design, it is helpful to consider some recent advances in robotics and artificial life. Von Neumann Machines and Emergence The field of artificial life sprang almost fully formed from the mind of the great twentieth century mathematician John Von Neumann, as his last major project before his death (Von Neumann 1966). He recorded the mathematics behind what is now called a Von Neumann machine, an abstract automaton capable of building self-reproducing copies of itself. His model entailed a complex of components each capable of subsisting in a multitude of states. Many decades later, in the late 1980s, Christopher Langton succeeded in implementing a simplified version of the Von Neumann machine as a cellular automaton in his Apple computer, and immediately was surprised by the tendency of his creatures to form larger structures as they spread across the screen, behaving like simple coral animals forming a reef (Levy 1992, 93-107). This unexpected behavior became the paradigm for the holy grail of artificial life experimentation, what is called emergent behavior, and it remains a hotly contested topic, as many still argue computer programs are not truly capable of behaving in unexpected ways, except in so far as their designers are not paying close attention (Steels 1995, 89-96).

64 The Lambda Point Langton remains an adherent of the importance of emergence, and beyond that, of the importance of climbing the slope towards the point of highest complexity. About this lambda point, alluded to previously, Steven Levy commented “life lives there” (1992, 110).

Chris Langton’s Lambda Point

0.0

λ

1.0

Figure 8: The Lambda Point (after Levy 1992, 100)

For instance, in the range between ice and water vapor, just before the boiling point, water is still liquid, but full of a variety of interacting types of turbulence, such that it has much greater capacity for carrying information, and that is the lambda point for water. At this stage in the research it is premature to do more than suggest the correlation, but it does seem that the humoral approach to human health and transformation inherited by Buddhism is about this point too. Also, in the larger Buddhist cosmology, within the six realms of existence

65 illustrated in figure 3 the human realm is said to be the best for liberation, because although we lack the freedom of the formless realms of the gods, we are not trapped in the rigidly controlled levels of the lower beings like animals, hungry ghosts and hell beings. In other words, we have freedom but also pressure, like water coming to a boil, like all processes high up on the lambda point. Gnarl and Knots in the Grain Rudy Rucker is not only one of the great theorists and implementers of artificial life, but also a noted science fiction novelist. Two of the “petaflop” robots in his novel Wetware are infatuated with behaving like 1950s Beatniks (Rucker 1988, 34). So it would not be surprising if Rucker’s usage of the term “gnarl” to symbolize the kind of complexity found at the lambda point were inspired by the following passage from an interview with one of the original Dharma Bums, Gary Snyder: That reminds me of the Japanese word for song, bushi or fushi, which means a whorl in the grain. It means in English what we call a knot, like a knot in a board. It’s a very interesting sense of song – like the grain flows along and then there’s a turbulence that whorls, and that’s what they call a song. It’s an intensification of the flow at a certain point that creates a turbulence of its own, but then the flow continues again. That’s parallel to what Black Elk says in Black Elk Speaks talking of the Plains Indian view of physical nature: that trees, animals, mountains are in some sense individualized turbulence patterns, specific turbulence patterns of the energy flow that manifest themselves temporarily as discrete items, playing specific roles and then flowing back in again. (Snyder 1980, 44) It should be noted that Snyder has been a Zen Buddhist monk for many of the years of his life. I was struck by this passage and Rucker’s description because one of the points that first made me intensely interested in Buddhism was made

66 by the narrator of a TV show back in the 1970s, as the scene jumped from waves in colored oil to footage of an old Zen archer hitting a small target tied by a string to an awning flapping in the wind. The narrator said something like “the great unsolved problem of classical physics is the problem of turbulence. But this Zen archer does not seem to be phased by that” (Eyre 1977).

Examining the

etymology of the word in Buddhism for the First Noble Truth, Dukkha, usually translated as “suffering,” we discover a very interesting thing: it comes from a root metaphor having to do with broken chariot axles and bumpy chariot tracks. Its cognates in English are words like “duality” and “two”. Rhys Davids and Stede (1921-1925) of the Pali text society point out that dukkha usually comes paired with sukha (IV, 160), or bliss, which was originally associated with a smooth road (VII 175). First, this is obviously a binary opposition of the Aryan conquerors as they trundled their way across the Hindu Kush and down into the Gangetic plain. In Buddhism, it gets picked up as something to be transcended. In Anapanasati for instance, dukkha is first escaped into a healing bath of sukha, but then that too is left behind as too much of an encumbrance, until the dukkha of momentary existence itself is confronted and dealt with, in a series of penetrating insights, resulting in an openness to the teachings of nature, and eventual liberation. The Mahayanists say, similarly, at the ultimate level samsara is nirvana, seeing deeply into things as they are is the path to peace, not escaping into oneness, but into non-duality instead (Buddhadasa 1988a). Consider that fractals are measures of roughness. Genetics Algorithms and Building blocks Buddhist theory has something very important in common with the branch of genetics inspired by artificial life modeling, and with the branch of robotics inspired by insect behavior. This idea is from the children’s culture of building blocks.

67 John Holland, in a sense the Brahma of computer science since he was the first person ever to receive a PhD in that field, is also widely considered the “father of genetic algorithms” (Dennett 1995, 212). He chose to approach the problem of optimization by looking at how natural evolution tackles the same problem. In so doing, taking a heuristic, constructivist approach, he happened across a basic fact of genetics overlooked by biologists: The driving force of evolution is not point mutation, which are usually repaired by specialized maintenance proteins, but genetic crossover, in which strands of DNA run into each other and switch halves.

Figure 9: Genetic Crossover

68 This is powerful because it means whole traits are reshuffled, more often than not without damage. It is similar to the mechanism of sexual genetic exchange, but happens at a more fundamental level and is found even in the simplest life forms, even among the strands of RNA injected into bacteria by viruses.

Holland

realized that this kind of reshuffling was how life forms recombine successful traits so as to continually optimize their adaptations to their fitness landscapes. Notice also here the idea of the hinge, much discussed by Jacques Derrida in his post-structuralist ontology (1978, 65), the idea that the key to being is not something solid, but the point of change, of breakage. Note also that this approach to optimization is very much bottom up, and even has been criticized for being too much so by the adherents of the evolutionary computation approach, who believe in using tuned finite state machines to solve problems rather than Holland’s Complex Adaptive Systems (CAS) (Fogel 1995). Buddhism breaks life into a multitude of categories. If science is ready to consider life in terms of chunky building blocks of traits, perhaps Buddhism’s huge toolkit of existing ones might be of interest to science. Sumbsumption Robotics The other new field where building blocks are important is the subsumption robotics of Rodney Brooks and Luc Steels (Steels and Brooks 1995). Subsumption is another simple, elegant idea that eluded those reluctant to take a constructivist approach, the practitioners of what Brooks scornfully refers to as “GOFAI” – good old-fashioned artificial intelligence. Brooks argues, with the Buddha, that you have to start with embodiment. He says the old school tried a model with the structure perception-> planning -> action which apart from being agonizingly slow in execution is not how life does things at all. Instead, he says an agent starts out acting, then has to develop perception to deal with the actions, and perhaps as a last resort tries the incredibly expensive and complex activity of planning. In other words, cognition is the last refuge of the robot. Put another

69 way, he says cognition arises from the seamless coupling of motor motion and perception. To be sure, this is a different description from that offered by Buddhism in such doctrines as the twelve interdependent links of causation (Niddanas), but this should not discourage researchers from considering the niddanas as an intriguing metaphor for modeling subsumption hierarchies. Models and Metaphors Indeed, part of the point of this entire exercise is to challenge the idea, with Anthony Judge (1991), that it is possible or honest to divorce the model from the metaphor.

In Judge’s critique of the process, taking the United Nations’

treatment of the idea of sustainable development as an example, he shows how an idea comes into the system as a metaphor, and thus full of life, then is stripped down to an abstract model, then is sold back to the public using entirely different metaphorical trapping, thus rendering it anemic and incomprehensible.

In a

sense, the metaphor is the body of the model, and the model should be capable of moving the body around, if it is to be anything more than a way of keeping people busy. Thus this work is more overt than it might be about its roots in a religious tradition, and if it is to serve a useful function, it must do so in the terms of the Buddhist metaphor, and for the body politic of the culture from whence it came. Making this more challenging, Buddhism is already a legitimating abstraction from an earlier, richer tradition, as discussed previously in the section on Ayurvedic medicine, so one must look deep into Buddhism to find its intuitions about homeostasis and phase change in the real world, but it is there, expressed in metaphorical form, especially in the Tibetan tantras. Subsumption and Mode Switching Subsumption is the process of trying progressively more expensive solutions to problems in an ascending hierarchy, and that also entails mode switching. For instance, when walking to the store, one is in a simple walking mode, but if one

70 realizes one has forgotten ones’ wallet, one instantly switches into a very different way of allocating energy (Varela 1995, 14). Varela relates how biologists have discovered that the neurological machinery for mode switching is extremely simple, optimized, and conserved across the animal kingdom, as basic to being a living agent on this planet as the segmentation process of the early embryo, or melanin (1995, 16). It strikes me that this mode switching is part and parcel to the basic genetic strategy (or math) of working with building blocks. Each mode can be considered a building block, and there are no doubt many fascinating experiments to try to discover correlations between variations in observed subsumption hierarchies and genetic variation, particularly variation caused by crossover in simple animals. Subsumption and Mode Switching in Swarmsara Swarmsara works from the assumption that emotional mode switching in Buddhism is a subsumption process, because it is described that way often enough in the literature, and the picture at the center of the standard “Wheel of Life” tankha painting found in most Buddhist centers strongly implies subsumption. It should be said however that Sharpa Rinpoche, one of the most educated Tibetan scholars, insists that the typical arrangement of the three animals is not correct, that the rooster and the snake are more properly portrayed emerging from the pig’s mouth. The Meaning of the Pig In Brooks’ terms, this is like saying acting on lack of perception gives rise to attraction and aversion equally, and should always be understood as the driving force of the whole mess, whereas the more typical arrangement of the pig (ignorance) biting the rooster (attraction) biting the snake (aversion) biting the pig in turn implies a more equally weighted arrangement of the emotions, without an identification of the real culprit. The problem here has much to do with what the

71 pig represents exactly. Santikaro Bikkhu, an American monk and scholar of the Theravada tradition, the main translator into English of the work of Ajaarn Buddhadasa Bikkhu, agrees with Sharpa Tulku’s view. He says the pig represents the emotion of delusion rather than the pure willful refusal to see called in Sanskrit “Avidya”. Swarmsara takes the low road on this issue, modeling the emotion represented by the pig as more like laziness, since another Buddhist teacher described it as such, but an emergent trait of the system is more like true Avidya, and this may be one of the most important results of the experiment. Hinges Between Emotions Then also, there is the intriguing question of what the hinge between the emotions might be like in Buddhist terms, especially since one branch of the Buddhist tradition has explored an idea very similar to Derrida’s differance and the western philosophical idea of hermeneutic interpretation for thousands of years. This school of thought, started by Dharmakirti and known as apoha theory, argues that all objects available to us are the result of a differentiation process in which the object is seen to be not what it is not, yet at the same time we take it to simply exist on its own apart from this complex perception process. And this is another line of research:

How might the formation of building blocks driving the

evolutionary process come as a mixed blessing, when the blocks become perceived, perhaps even at the biochemical level, as opaque unified entities, not themselves composed of smaller pieces. This opacity is critical also in modern computer program design, and is in that context known as information hiding, in which an object or process can see only the parts of another object or process it needs to see, thus protecting complex, weirdly optimized underlying structures from disruptive manipulation.

In other words, the very tools used for

constructing the Swarmsara system are already starting to express the same flaws endemic in the life process that, if you believe the Buddhists, give rise to the problem of suffering as an unwanted consequence. In this light, that critical

72 building block of object-oriented programming is just another manifestation of the deluded process that grips all beings, since for utilitarian reasons it reifies the unity and independence of the myth of the object. For programmers in real life of course, more often than not the day-to-day work entails contacting the designer of the now opaque object and asking to see the underlying code so that it can be made to work in a new situation for which it is not adapted. And in this sense programming is not so different from a typical meditation on emptiness, in which the meditator ponders a seemingly unified object like a table, breaking it down into its constituent parts, and breaking down those parts in turn, until no table can be found, and it becomes possible to glimpse the illusory nature of our lived reality. Definition of Life and the Wisdom of Doing A-Life Research If people have heard of artificial life research outside the field, it is usually through the Terminator movies, or other such scary treatments. Indeed, Tom Ray, designer of a breakthrough artificial life system that turned into a complex many-specied ecosystem overnight, has warned that we must take these misgivings seriously (Ray, 1995). There is real danger in letting any life process run out of control. As Rudy Rucker and Gregory Benford point out in their brilliant science fiction (Rucker is a professor of Mathematics, Benford of Physics) constraints such as the Azimov Rules of Robotics might be the first things to go in an evolving system. As Rodney Brooks says, humankind might be distinguished as the first species to create its own successor, and in a similar droll vein, life from Earth may well explore and populate the universe, but it probably won’t be biological life (Brooks 1997).

For instance, a common scenario for

terraforming other planets entails sending a seed factory of self-reproducing robots first to spread across the planet and tame it for us. But by the time they are done, why would they want to share, especially since obedience would not be a conserved trait on that wild frontier?

73 Swarmsara, like Buddhism, is intended as much as a critique of the life process as a celebration of it. It purports to show that agents from their earliest adaptations trap themselves in a cycle, which leaves them perpetually dissatisfied. Like sentient beings, all they do is seek comfort and avoid discomfort, but since it is not trivial to grasp the means for doing this consistently, their very efforts propel them into a reflexive subjectivity where happiness is very far away. Heuristics of Ecological Restoration and A-Life Research Ecological restoration projects have as a consequence the recognition among their participants that the construction of nature is an enormous amount of work. Restorationists do not get the giddy attitude that since you can put nature back together you can wreck it willy-nilly, as was proposed in the first Bush administration’s “No Net Loss” plan for mitigating destruction of wetlands (“Mitigation Scam”, 2000).

Bush thought that it would be fine to destroy a

wetland so long as another wetland of comparable value were restored nearby. But restorationists knew that to do that they would have to disturb a third wetland to get the species, and also that wetland restoration is almost never more than partially successful. Their constructivist, heuristic approach taught them a real humility about what goes into simple wild nature, a humility the top down leaders had no hope of learning. So one of the points of doing artificial life research, especially from the Buddhist perspective, but also in general, is to learn some grim facts about what it means to be alive, or to argue otherwise if such is one’s bent. This plays out also in terms of eventual applications of the work. It could be used for modeling the spread of an aggressive invasive exotic species across a landscape, or what is likely to happen to the country of Tibet under the heel of short sighted occupying army, or the spread of urban sprawl from Buddhist cities under different ideological conditions. For in a sense, what Swarmsara is getting at is that even the most

74 primitive life-processes have a sort of ideology, a method of perceiving the world through a lens or a filter that strategically distorts all it comes across. And the argument is this is almost unavoidable, with possible rare exceptions, and refusal to see this negative consequence of the reflexive life process will only cause more suffering, as Georges Soros (1997) warns about the ideological adherents of free market capitalism and naïve socialism alike. The use of a system like Swarmsara is not to make the beginnings of a ghastly Terminator robot, but to terminate our endemic confidence in the most misleading and parasitic part of our own life process. Constructivism Mitchell Resnick’s (1995) article on constructivism in a-life robotics as an educational tool struck a chord, because it is also in the spirit of ecological restoration and Buddhism. Interestingly, he quotes the phrase found on Richard Feynman’s blackboard on the day of his death: “What I cannot create, I do not understand” (232). This must be an echo of Decartes’ opponent Battista Vico, who put forward, as the founder of restoration ecology William Jordan III relates, after Collingwood, “the doctrine that verum et factum convertuntur: that is, the condition of being able to know anything truly, to understand it as opposed to merely perceiving it, is that the knower himself should have made it.” (Jordan et. al. 1987, 11) So one of the objectives of good a-life design is to provide enough controls that the user can play with it and make it their own. Such also may be the value of offering a prototype like Swarmsara to the world, ready for reverse engineering. Debate about the Definition of Life Tom Ray is also a lively participant, along with Rudy Rucker and many others, in the ongoing debate about the minimal definition of the life process. He wryly acknowledges that researchers tend to define life in the terms of their particular

75 disciplines (Ray 1995, 180). Most a-life experimenters retain some of the basic components of the biological life process that spring to their eye, particularly sex and death.

When Professor Steve Skrentny was inspired in 1998 to ask his

graduate students to design an artificial life assignment for his 302 class, he asked them to come up with a predator-prey cycle. But although such cycles are usually stable in nature, it is notoriously difficult to implement them as computer simulations, with some exceptions (Durrett 2001), and the attempt had to be abandoned. This gravitation to preconceptions leads to fascinating discoveries, as in this case, but it is also important to challenge, and Swarmsara attempts to do that, since it does not include any apparent generational turnover or exchange of genetic information. In a future design and implementation the reflexive karma system would include a learning algorithm similar in style perhaps to typical genetic algorithms, but the agents, as far as karma is concerned, are immortal and separate from each other. They affect each other only by affecting their collective landscape. Of course much of Buddhism is concerned with the interactions of individuals, but this is aside from the challenge to the idea that a living community must have certain kinds of interactions and outcomes to be viable as life. To be sure, many a-life programs such as Boids get very interesting results by looking at a specific part of the life process, in that case flocking behavior (Levy 1992, 76-82). But it is important for one blind person to call out their belief about the nature of the elephant to the others so that none will become too attached to their own limited interpretation. Swarmsara asks the question, are death and sex critical to the life process, or just manifestations of a more basic, simpler formulation? Sex is a formalization of the building block strategy (Dennett 1995, 323), and death is, if the Buddhists are to be believed, found forty times in the time it takes to snap ones’ fingers. In Swarmsara’s terms, every time step is a little death, and both sex and death are elaborated manifestations of Derrida’s hinge, the Buddha’s emptiness.

76 Chapter 7

RESULTS The Swarmsara simulation purports to demonstrate the viability of a constructivist computational approach to uniting Buddhism and Biology for the sake of cultural survival and ecosystem management. This paper does not claim Buddhism or the emotions are truly amenable to such reduction, merely that such reduction nevertheless results in artificial behavior life-like enough to warrant further study. Sloman argued early in the computer age that reducing emotions to numbers is wrong-headed from the outset (1978, 268). However, what the Buddhists mean by klesha and what people usually mean by emotion are different things. The simplicity of the kleshas invites a simplistic approach, but this does not mean the approach taken here in any way approximates the way Buddhism models their functioning. It is critical to bear in mind Swarmsara is only inspired by Buddhist ideas. It does not represent them, even in the weak protestant sense popular in critical theory. However, Swarmara may be thought of as a metonym for a much grander project, perhaps the first sail on the horizon of a ship of ideas and experiments leading to a continent of new discoveries, a folly in the best sense, and that may be the most important result coming from the project. It is a proof of concept that the extremely technical descriptions found in Buddhist texts can be explored using the means of post-modern science. (I refer to Steven Toulmin’s (1982) usage of the term here, meaning science with values, science beyond nonparticipatory pseudo-objectivity, in the spirit of ecological restoration or humanist anthropology, science that takes responsibility for its role in the world).

77 This section is a review of the implications of the Swarmsara project. First it presents some examples of Swarmsara runs, with comments, then some further analysis. The section on future directions following will suggest some more structured experiments and studies that might be done now that a basic framework has been established. Some Swarmsara Runs Following are some examples of output from the Swarmsara simulation as it currently stands. The control panel and windows are described in Appendix D.

Figure 10: The Beginning of Ignorance

At 1365 time steps of a run with default parameters and random seed 5, some agents are developing ignorance, as represented by the green colored cells. The

78 other afflictive emotions have yet to emerge. The reader should observe the same results with this random seed setting and similar software and hardware.

Figure 11: Attraction Emerges

At 7376 time steps, some of the agents are predominantly desirous, making them turn blue in color. Note that this causes them to leave valuable resources behind, as shown by the lighter gray cells near the blue agents. Note also that the average perceived happiness (purple line in upper graph) has started to drop.

79

Figure 12: Aversion and Drop in Perceived Happiness

After 28517 time steps, average perceived happiness has dropped to 50%, even though average resources (yellow line in upper graph) have generally increased. Agents such as the purple, aversive one in the lower left center find themselves trapped in rich areas which they are unable to perceive. This is an atypical run in that aversion took a long time to start. Note also that agent number 5 is not happy even though it should be happy according to its own criteria.

80

Figure 13: Attraction Peaks

Somewhere around 37,000 time steps attraction peaks at 255. This is due to attraction being the middle emotion between ignorance and aversion. maximum attraction is determined by the “threshold” parameter.

The When

attraction, triggered by ignorance greater than 255, is itself at 255, the effect is passed on immediately to aversion. In this sense aversion is dependent on ignorance almost as directly as aversion, like the variation on the three animals metaphor in which both the rooster and the snake emerge from the pig’s mouth. Note the continuing trend of increasing perceived unhappiness despite increasing resources. Yet agent 20, aqua blue in the figure, is happy when it should not be because it is ruled by ignorance, probably produced as a result of inappropriate aversion. As aversion increases, it starts to produce more ignorance, so this complicates the perceived happiness and average resources in the system, as agents start staying in resource rich areas again. Samsara still has its inducements,

81 even if only for the lucky few. Note also that there are far fewer unemotional agents in the system now, so the emotional ones are increasingly likely to get stuck and stay stuck longer. Unemotional agents are not blinded by karma and select the best cell in their neighborhood, thus freeing the emotional ones.

Figure 14: A Solitary Agent

Running the system with a single agent reveals more starkly the relationship between the ignorance threshold and the onset of attraction. Attraction can increase only when ignorance is greater than 255. When attraction is at 255, ignorance transforms directly into aversion. resources once aversion enters the equation.

Observe also the large increase in

82

Figure 15: Solitary Agent at About 200,000 Time Steps

In this run, aversion reaches 255 at about 100,000 time steps. At that stage, when ignorance peaks over 255 it creates a positive feedback and serves to increase itself, but there is enough pressure from other factors such as leveling (although still not stable) resource availability to prevent this from becoming a runaway loop.

83

Figure 16: Eighty Agents with Smoother Graph Lines

As would be expected, larger numbers of agents produce smoother graph lines. This of course is subject for statistical study. Forcing the lines to level out would help to reveal any real attractors that might be in the system.

84

Figure 17: Karma Turned Off

The above screen shows what happens with normal settings when karma is turned off, meaning the agents do not accumulate karma and their perception is not limited by karma. Note that although ignorance shows on the graph, it is at a power of –3, in other words, nothing much is happening.

85

Figure 18: An Attempt to Force Interesting Behavior without Karma

86

Figure 19: More Non-Karmic Flat Lines

It is possible with sufficient adjustment of parameters to induce attraction and aversion in a karma-less system, but only as simple flat slopes. The agents become distinctly unhappy because all they can feel is attraction or aversion, never the dull comfort of ignorance.

87

Figure 20: Two Agents with Karma Off and Forced Emotions

The above figure perhaps explains part of what is going on. The agents are too good at moving to cells where there are resources. They are not blinded by karma, so they never create a trail of resources. Without karma, the landscape does not form. The fact ignorance must be virtually turned off for anything at all to happen is also interesting. We are returned once more to the critical and interesting question of the relationship of ignorance and karma. The Critical Role of Karma When I set out to do this project, learning a computer programming language and modeling the cycle of the emotions seemed more than enough to tackle. Thanks to a key interaction with Sharpa Rinpoche, my ambition expanded and I decided to take on karma as well. It is a good thing I did, because without the karma module, nothing much happens in the simulation.

To be sure, if

88 Swarmsara had been built without karma it would have been tweaked to do something interesting anyway, but as it stands, the case is clear. The reader can examine

this

by

running

the

simulation

from

the

web

(http://www.execpc.com/~alturner/java/Swarmsara.html), and clicking the “Use Karma” option on the control panel before a run, thus turning off karma’s influence over perception. Without karmic blinkers, the agents tend not to develop kleshas, remaining largely invisible, ignorance dissipating in a few time steps. Whether this is artificial or not, it is a fascinating and unexpected result, which tends to support that early Buddhist hypothesis “kamma and passions are the cause of Samsara” (Rhys Davids and Stede 1921-1925, III 20). The kleshas alone are not enough. Karma and Ignorance A lot of the work of structured programming is done at the beginning, in the phase known as “establishing requirements” (Lewis and Loftus 1998, 413). This usually entails a series of discussions with the future users of the program, and with those holding knowledge about the business process to be modeled. Indeed, such interviewing requires skills similar to the anthropologist or counseling psychologist, to draw out salient facts much better incorporated from the beginning than discovered later, although such unwanted surprises happen all too often unless official documents are created to protect the programmer from the evolving ambitions of the users, as they finally bring their minds to bear on the project in later stages.

As has been mentioned before, the klesha called

“ignorance” in much of the simulation and this discussion is not really the same thing as the “not seeing” of avidya. Authorities in both the Theravadan and Mahayana traditions who were kind enough to entertain my ideas agree that a better term in this context for the emotion represented in the Wheel of Life painting might be laziness, or delusion. The simulation continues to use the term

89 “ignorance” partly because it has not been recompiled, and partly because ignorance is also used in a more general, metonymic sense, to mean that range of obscurations stemming from avidya.

However, while in the same discussion in

which he brought up this complexity, Sharpa Rinpoche also defined karma as an information process, and offered that a microbe would not be able to control its karmic behavior, such that the simulation would not have to model learning from karma, at least at this stage. This conversation helped to establish several of the parameters governing the design of the simulation, but it also begged the question, what then is ignorance exactly, and how does it relate to karma? After getting the simulation working and using the karma function to govern what the agents are able to see, it hit me that this involuntary blindness based on willful past actions is much closer to what is meant by avidya. It is similar to Nietzsche’s famous “he likes/what he can paint” (Gombrich 1977, 75), in other words, “we see what our karma born from our kleshas allows us to see”. However, since having kleshas at all is itself a karmic act, the reflexivity in the process knows no bounds.

I took these ideas resulting from building and observing the simulation

back to Sharpa Rinpoche, and he acknowledged a relationship between karma and avidya in Buddhist doctrine that I had never picked up on before attempting my constructivist model. And this relationship has tantalizing similarities to Rodney Brooks’ approach to robotics via working from embodiment and subsumption. It is an exploration of the relationship of perception and action at a highly practical level. Think of the behavior of ants and their pheromone trails, a favorite subject of a-life modelers. From this perspective, life can be considered to be a giant karmic pheromone trail of inveterate negative propensities, a world made real through habit, and no more substantial than that, with many possibilities left unexplored because our habitual karma has led us along only tried and true paths.

90 Swarmsara opened up this line of inquiry, and that opening is one of its most important results. Future versions could be tuned to hone in on the sensitive relationship between action and perception when every action has a conserved consequence affecting perception. Test of First and Second Noble Truths Swarmsara was set up to test the first and second noble truths of Buddhism. As stated earlier, these are 1) life is dissatisfactory (broken, bumpy, dual) and 2) this problem has a cause, that being the cycle of afflictive emotions together with karma. The Buddha presented this as a formal Ayurvedic medical diagnosis, in other words, as scientifically as he could (Clifford 1984, 38-39). Two thousand five hundred years later, it seems high time someone set out to test his hypothesis. Within the scope of this project it was enough to set up a process in which the agents perceive themselves to be increasingly unhappy as the simulation progresses. The real time graphs of the implementation show a line tracking average perceived happiness, and indeed, that line drops as simulation runs progress.

This is valid, in that when agents are ruled by attraction and

aversion rather than the laziness stemming from deluded contentment they can be said to be unhappy by definition. It might be argued that it is tautological, even disingenuous, but that might well be the Buddha’s point.

If you allow

yourself to be ruled by dissatisfaction, you will be unhappy. Sometimes the most obvious facts have to be stated directly lest they be overlooked, especially when they strike close to home. However, also, agents do not start out with strong attraction and aversion, these develop as consequences of the indulgence in laziness born of the hardening of identification with the current location. This process of formation and its consequences are less self-evident, and more important to study and analyze.

Many fields, from evolutionary biology to

political economy, might benefit from a more mathematical approach to early

91 stages of the relationship of an agent to its surroundings, and experiments with the Samsara theory might well yield such an approach. Swarmsara’s graphs are presented only to suggest the possibility of more refined study. They show signs of complexity, but a good deal of further development would be required to isolate any true signs of it, such as attractors. Connection of Buddhism and Ayurvedic Medicine Although the historical relationship of Buddhism and Ayurvedic medicine is well known in some circles, such as the Tibetan medical community, it is not common knowledge even among most Buddhists, and this author came across it fairly late in the current project. It is of particular significance here because Ayurveda was so important to the Indian national movement, thus indicating the very concepts in play have historical and political power, the kind of power needed to make inroads into the destructive trends engendered by modernization. If a return to Ayurveda helped to throw off the colonial yoke, perhaps it could also serve to mitigate environmental destruction. Proof of Concept In an important respect, this project was a test of whether someone with little background in math or computer science could manage to create an artificial life simulation. Basic artificial life projects are given as assignments in second year computer science classes, but few development workers in Buddhist Asia are trained as programmers. To be sure, there are many thousands of people with solid Buddhist backgrounds now working at the top level of the Information Technology industry. Most people however do not think of relating the old-time religion of their incense-filled temples with the tools and methods of their bleeding edge high tech jobs. It seemed useful to at least establish that an attempt to do so might have an interesting outcome. High technology is a very powerful

92 force, but since it is a technology, for many it is bereft of ethical content or concern. If a job as a programmer enables ones’ family to own an environmentdestroying but comfortable SUV, caught for most of the day in some Asian city’s traffic jams, that is enough. But it is my belief no one, least of all those capable of writing computer programs, can escape the nagging sense of the absurd unless they do their part to develop solutions to global problems. Swarmsara shows it is possible to develop Buddhistic spatial simulations.

From a spatial

implementation to a geographical, fully applied one is a big step, but a traversable one. For the sake of the long-term survival of Asia, it is an exploration we would be remiss to neglect. The Emergence of Conversation The holy grail of artificial life is emergence, enough so the term is subject of continuing debate. Some go as far as to say computer behavior is surprising only to those who have not sufficiently comprehended the consequences of their own design (Steels 1995, 89-96).

Swarmsara as it stands shows only the weakest,

most rudimentary types of emergence, such as the avalanche situation mentioned in the Algorithm section, and the tendency of resources to increase as afflictive emotions increase, since increasingly agitated agents tend to abandon good locations for bad.

Much more interesting patterns might be possible given

improvements to be discussed in the next section, but there is a present result which bears mentioning, even though it is one held in common by every experiment and study, that is, the project has stirred up some discourse on the Internet. Website logs show the system has been visited and run by people, presumably mostly Buddhist, from all over the world. This is due primarily to the posting of the address of the system on the web by Than Santikaro Bikkhu, the translator of Ajaan Buddhadasa mentioned several times earlier here.

93 Another observer remarked that what emerges from the simulation are metaphors. There may be no real world correlation with the tendency of agitated agents to abandon their resources, but it is an interesting question to ask, and one which might well lead to empirical results.

Indeed, it is a question with direct

consequences for ecological conservation, and many, such as participants in the Voluntary Simplicity movement, already act on the intuition that less may be more. But what is the message of this epiphenomenon in the simulation runs? Could one not also argue that the difference is similar to the difference between nomadic and sedentary tribes, i.e., the difference between modern and Neanderthal humans, as suggested by recent evidence?

The paleontological

record seems to suggest that modern humans had a huge advantage because they migrated, thus meeting other migrating groups, and facilitating the spread of technologies and ideas, while avoiding putting too much pressure on any one part of the land, while the older Neanderthals tended to stay in unmoving villages, thus isolating themselves and limiting their resources. So then the question is, is there a differing emotional regime among nomads as opposed to settled folk? Bruce Chatwin in his Songlines (1987) made much of the nomadic origins of the human species, and how that might have been critical to the development of abstract language. People needed to have names for landmarks not seen every day, but only during stages of the migratory route.

The Buddha too was

peripatetic, and depended on participation in a society that supported that activity for the development of his homeless community. Is there an Ayurvedic analysis of this aspect of the non-attached life, and what might it have to do with the wandering microbes of the Swarmsara simulation?

And how might we adjust

our behavior to be more sustainable and conducive to development of enlightened attitudes, in terms of how we are impelled to travel across the land? Is there a way to do it more cleanly than in an ignorance-heavy SUV? A discipline of artificial life theorists is to restrain themselves from reading too

94 much into the behavior of their simulations, but the emergence of metaphors and questions remains a happy result. Swarmsara Itself The final result of this project is the Swarmsara simulation itself, and its public domain code. The source code was inspired by the Objective-C code for the Santa Fe Institute’s Swarm Simulation System. At the time the implementation was done, no Java version of Swarm was available, but at this writing similar, more robust versions have been done by other workers.

Therefore, those

wishing to expand on this work might be well served to investigate these resources, such as those developed by the designers of the Gecko system, and the continuing development of Swarm itself. Nonetheless, the algorithm and logic developed for Swarmsara is offered for use under the GNU license to any who care to make the effort. In most places the code is well documented and all but the classes for the real time graphs, created by Leigh Brookshaw, are included as an appendix. The simulation as it stands comes with a control panel, and many aspects of its runs can be adjusted in a manner similar to classic Swarm examples such as Heatbugs. Even in its current form, the simulation can be quite entertaining, and can be used to demonstrate the possibility the Buddha might have been right about suffering and its cause. At this writing it remains publicly available at http://www.execpc.com/~alturner/java/Swarmsara.html .

95 Chapter 8

FUTURE DIRECTIONS Perhaps more important to a project like this one than current results are the directions for future research it suggests.

Mention has been made throughout

this document of these possibilities. The two main ones are what is called here the “karmic fitness landscape” and the development of a land modeling application akin to Yale’s Gecko (2001) system. Of interest also are versions of the algorithm and implementation better suited to the search for attractors and other traits of complexity, as well as considerations of how development of the system might be transferred into more “indigenous” hands, e.g. by packaging it as an assignment in a computer science class in an Asian university. Karmic fitness landscapes “Up the hill backwards, it’ll be alright” -- David Bowie, Zen Buddhist rock star Most artificial life simulations, particularly varieties of the genetic algorithm, emphasize death together with Darwinian generational selection as the engine of optimization (Holland 1995, 122-126; Rucker 1993, 11-20; Ray 1995, 180-182). But Swarmsara’s agents do not die. In the current simulation, which is set up to demonstrate the possibility of showing the increase of dissatisfaction as the kleshas and karma do their work, they do not learn or significantly evolve, either. Their emotional and karmic profiles change and they affect each other reflexively by changing their effects on the landscape in the course of a run, but they do not change their basic strategies beyond going through a preset sequence of mode

96 switches based on perceptions of conditions.

However, Buddhism in the

positive is about awareness, and the ability to learn from karma thanks to awareness. In Buddhism all consciousness is consciousness of. There is no mind without an object of mind, and no object without an observer. The problem of the tree falling in the forest is solved by recourse to an omniscient Buddha mind underlying all, the Jewel Mirror Samadhi (Ryokai 1999). That most basic mind takes as its object sunyata, the non-affirming negative that makes all things possible, the complete lack of any kind of hindering inherent existence, despite our deeply held, primordial conviction to the contrary. In Buddhism all minds are compound phenomena, accumulations of mental aggregates, which manifest as various kinds of mental factors, one might say, ecosystems of mental factors. This is where evolution is very much alive in Buddhism. Over vast stretches of time, agents develop more or less adaptive methods of adjusting their karma and mental factors, to strive for more or less sustainable goals. One might say the weak definition of awareness in Buddhism is merely the ability to adjust karma according to some information process, to gravitate towards perceived comfort and away from perceived discomfort. To be sure, many Buddhists hold to a version of the doctrine that puts Mind first, or even Mind Only (e.g. the Chittamatrins) but since Buddhism is by its nature wide open to interpretation, their conviction right or wrong should not impede the present study. Information is potential energy, potential energy is difference, difference is differentiation, and differentiation is the English translation of the Sanskrit apoha, Dharmakirti’s core doctrine the Mind Only schools use to assert their position, since how can you have differentiation without mind? Whatever the reality, those drawn to this view are often those prone to conservative, top-down political agendas, since Mind with a capital M is authority incarnate. Again, it seems enough to assert with His Holiness the Dalai Lama and Acharya Shantideva something much simpler, that objects and agents seek ease, to roll downhill, to

97 seek happiness and avoid suffering, but to be unskillful, even contrary, in how they go about getting it. To put it even more simply, evolution is intelligence. Consider again the graphic from Lee Smolin’s Life in the Cosmos shown in figure 2. It shows a fitness landscape for universes based on conceivable variations in the standard model. This kind of fitness landscape, with peaks for alignments of traits that are adaptive and so on is used often in evolutionary biology, to model any kind of range of variation subjected to evolutionary processes. But without generations and death, in a model of the world where agents are born alone, live alone, and die alone, and have existed over beginningless time, where would such change take place? Perhaps Darwinism could be applied to the karma/kleshas feedback loop. There might be such a thing as karmic hill climbing, similar to the adaptive hill climbing of ecological modeling. Perhaps agents over time and with extraordinary luck finally learn how to adjust their karma so as to improve their future. Sharpa Rinpoche says that a microbe would not be able to control its karmic output, as a human can. Buddhists for millenia have pondered the difference between humans and animals, as evinced by Zen’s great Koan A monk asked Joshu, “Does a dog have the Buddhanature or not?” Josh replied, “Mu!” (Yamada 1990, 11) According to the Mahayana Buddhist tradition of which Zen is a part, the Buddha said all sentient beings down to the smallest ants have the Buddha nature (Tathagatagarbha). But Joshu’s “Mu!” means no, or not, or nothingness. This is understood to mean that Buddha Nature is an essenceless lack of essence, an inner openness that makes all things possible, including Buddhahood for dogs, or better, there is no dog or human in Buddhahood. You can’t have something that

98 is the non-existent negation of a non-existent, however important it is. But the question remains, why can humans get enlightened and dogs can’t? The point drives to the heart of reality and the student hasn’t really asked the question until he or she is completely dumbstruck by it, and the ego shell bursts open. Short of that it also points out the strange fact that humans have enough control of their karma to chose to live in a way divorced from the cycle of suffering illustrated in the Swarmsara simulation. Thus an improvement to Swarmsara might be a way for the agents to learn karmically how to avoid the causes of suffering and to seek the causes of happiness. The methods of evolutionary computation and genetic algorithms might well have an indispensable role to play. It would be interesting to explore with Buddhist scholars some of the subtler aspects of karmic interplay to see if such lines of thought have already been opened in the vast and wellarticulated Buddhist tradition. Such inquiry is already touched on in catechisms like Kyabje Pabongkha’s (1993) version of the Lam Rim, so it must certainly exist in much greater depth as well. Sub-Peaks of the Karmic Fitness Landscape Perhaps Buddhist enlightenment is the ultimate peak of the karmic fitness landscape, but it would contain many sub-peaks as well. As long as an agent is ruled by the ignorance of self-grasping, its actions must evolve with regard to that salient fact.

As in Swarmsara, such ignorance and its concomitant laziness

necessitates attraction, and that necessitates aversion. Agents that are capable of these compensations will in the short run do better than those that just suffer with no reaction. But also, agents put resources into their environment, and they take them out, and all that is recorded in their Alayavijnana, their storehouse consciousness, the Buddhist equivalent of Freud’s Id, where all karmic imprints wait like seeds for their eventual growth and ripening. If they just take resources out, they will experience short term happiness, but long term deprivation, whereas if they add to their environment, not only will they have more in the

99 future, other agents will prosper as well, in complicated ways, that might often backfire. It would not take much for many alignments of adaptive traits around many peaks to emerge, for agents to start conserving preferable traits, even if always under the terrible shadow of ignorance and in the grip of the illusion of death.

And this use of the word “shadow” is not un-self-conscious—the way

ignorance limits perception and defines the fitness landscape might be version of Carl Jung’s (1963) shadow of the self, and attempts to detect the functioning of this in the system might produce results of great interest. With the right sensors and statistics these adaptations could be measured and recorded, and variations in the evolving evolutionary strategies could be examined for qualitative differences, to see if anything like the simpler mental aggregates such as sensations and impulses, and even types of “consciousness” could be detected. The Emergence of Cooperation The highest mind in Buddhism is called Bodhicitta, literally the awakening mind, the mind of Enlightenment (Shantideva 1981). It is a mind of pure altruism, a commitment to personal growth solely for the benefit of others, born of awareness of the beauty and suffering of the world, and the confidence that liberation is possible based on penetrating ontological analysis. A hot topic nowadays in game theory and many related fields such as government studies is the emergence of cooperation among selfish agents. Robert Axelrod (1984) of Michigan University wrote the paradigmatic book on the subject, and interestingly enough, he is a colleague of John Holland, widely recognized as the founder of genetic algorithm theory.

Axelrod’s model is built around the

Prisoner’s Dilemma game, in which two agents, both of which on any one time step can win more points by betraying the other, choose to cooperate by and large if they have a sense of future consequences.

Humans and artificial life

agents gravitate to similar strategies, but pure game theory produces a different

100 one.

More complex versions of the game are applied to the interactions of

nations in spheres of influence, with some nations taking leading roles, and others trying free rider strategies, and so on (Kosumas 2000). A major arena for the application of Swarmsara might be towards modeling the emergence of cooperation and even ethics among selfish, samsaric agents, and the gradual emergence of versions of altruism among them. South Asian history faults between the followers of the Arthashastra, the Macheavellian-like strategies of ancient India, and the model of the righteous Buddhist king Asoka (Tambiah 1976, 27). Although lip service is paid to the idea of ethical government in the style of Asoka and in Thailand his successor King Ramkanghaing (Sivaraksa 1992) more often foreign ministries gravitate to the Western, Arthashastra-like real politique models that seemed necessary for survival during the colonial period, that seem to force them to sell or destroy all that was good and whole in their societies in the process. These Buddhist governments might be open to more benign approaches if they could see the way to them, and perhaps future versions of Swarmsara could help light the way. Buddhist GIS From the beginning of this project, due to the author’s environmental studies background, Swarmsara has been developed with an eventual integration into Geographical Information Systems in mind. Over the several years it took to learn programming languages and apply them to the algorithm, the Swarm Simulation System which served as a starting point for Swarmsara has attracted a corps of GIS programmers, and Swarm itself has been ported in a robust way from its original Objective-C to Java, the language used for Swarmsara. Probably the object wrappers needed for packaging Swarm-like Java classes for a GIScompatible framework already exist. This does not mean it would be a trivial task to adopt Swarmsara for a more applied setting. Many performance and design

101 issues would need to be resolved. Also, there remains the fascinating question of how to define value in a simulation of a real world landscape, and how the agents might maneuver in that context. Buddhism provides a well-articulated theory of subjective/objective value (thai: kha) that surely would serve as a basis, implemented perhaps in terms of the emergent strategies of the genetic algorithm version of Swarmsara (Buddhadasa 1986, 124-142). So agents could be told to start out being selfish about strip mall development, or road building, with different constituencies reacting from different relative levels of enlightenment and time scale. John Holland has suggested a similar application of his Echo simulation system with regards to studying the history of Civilian Conservation Corps and their interaction with the trees they planted in the nineteen thirties (1995, 162-163).

The developers of the Gecko system at Yale, working from

Holland’s ideas, would be of invaluable help in this regard, as would other researchers such as those behind the project to model hypothetical Anasazi cultural life using the Swarm Simulation System (Gecko 2001, Carr 1997). Scenarios could be constructed such as a study of differing patterns of deforestation in Thailand based on differing levels of free trade ideology, or variations in adult education of Buddhist monks about land resource issues, or what happens when indigenous knowledge itself is encouraged, and the villagers and monks are the ones doing the modeling, using increasingly Buddhist and increasingly accurate computational tools, as much as any model might so serve. Alternatively, The Tibetan Government in Exile might apply a GIS descendant of Swarmsara to the problem of modeling exploitation of their occupied country by the Chinese military. They could take such scenarios to world forums where they could argue on those grounds for more sustainable policies, to slow down desertification, the slaughter of wildlife and so on. Consequentialist reasoning is basic to Buddhist thought, so showing the negative consequences of deluded Chinese policy should be a natural move for the Tibetans. The fact that they

102 would be working with their own knowledge system, if it could be made to apply, would help them sustain it into the technological future, and thus to sustain their evolved, relatively benign, relationship with the land. Contribution to Chaos and Complexity Theory After the presentation of Swarmsara at the Chaos and Complex Systems Seminar in the Fall of 2000 at UW-Madison, the physicist Professor Clint Sprott suggested that for it to be useful as the kind of research tool he needed, the system would need to be stripped of as many random numbers as possible, and that it should be un-discretized, that is, where integers are used, real numbers should be used instead. That way, a physicist could look for sensitive dependence on initial conditions, and the strange attractors that are their stock in trade. He would like to be able to make minute changes to the settings in the control panel and watch runs to see the range of their variation. The simulation as it stands includes the ability to set a random seed, but other changes would be required such as eliminating the use of that seed to eliminate bias or to set the amount of produced karma. Creating such a stripped down version of the system would not be a major undertaking, but developing the methodologies for analyzing the results might be, and better reporting mechanisms such as serialized state logs (meaning printouts to files) for each agent would be required. In the conversation after the presentation, social scientists wanted the simulation to become more complex and phenomenological, with better-structured rules for how karmic actions might affect the agents. A biologist wanted the terminology adjusted to better fit the jargon used for describing the behavior of slime molds. Meanwhile a colleague at the author’s workplace at the State of Wisconsin, a geophysicist with expertise in the analysis of earthquakes and tsunamis, suggested applying black box control theory and Fourier Transforms to the output data, to search for hidden patterns there.

103 All of these are worthy and exciting directions for the project, and validate its role as a stem-cell-like prototype, meant for use by others. The Life Assignment Second year computer science students are often assigned the task of creating an implementation of Conway’s Game of Life. Conway is a mathematician who created simple rules in the same Von Neumann neighborhood used by Swarmsara and most cellular automata.

His simulation has intrigued many

researchers since, and because it is so visually entertaining, for years it was a favored screensaver on UNIX workstations. When I told my old Oracle SQL instructor about this project at a Java Users Group, he teased me about it, assuming it was as simple as the Conway model, and that this was no subject for a Masters thesis. Be that as it may, when Conway first came up with his idea, before computing power was readily available, entire math departments devoted large amounts of floor space to playing out the consequences of his runs, with black and white tiles, and Conway’s class was able to prove it was possible to create a Turing machine, that is, a universal computer, in the space of the simulation (Levy 1992, 58-60). The first functioning Von Neumann machines, or self-reproducing automata, created by Chris Langton, were also simple cellular automata (Levy 1992, 97-103). And this project would never have been properly begun if Professor Steve Skrentny of the UW Computer Science department had not been kind enough to ask me to start it as a special assignment for his class. Therefore the suggestion is, in order to remind computer science students of the relevance of the ancient ideas behind Swarmsara to the modern world, and to inspire them to develop them in new directions, perhaps the simplest approach would be to make the implementation of the algorithm an assignment in first or second year computer science, in universities in Asia. Clearly the current Java implementation, despite a number of tricks to optimize it detailed in the code

104 included in the appendix, is too slow. Either most of the Java should be moved to the server side, or the implementation should be done in a better-optimized language like C++, or even Swarm’s old Objective-C. Nor is there a reason why the basic algorithm of the cycle of emotions reflexively interacting with karmic cause and effect should be confined to Von Neumann neighborhood or any of the other constraints imposed by the design choices I have made.

105 Chapter 9

CONCLUSION The thesis of this project is that a computational approach to modeling life from interpretations of Buddhist principles is worth exploring. It does not try to claim Buddhism is true, or that the implementation here is more than remotely similar to Buddhism as such. Nor is the existing implementation complete even in its own terms, let alone in terms of the quantum leaps it would have to take to hope to climb towards the Lambda point of the ultimate fitness landscape of complexity. However, it does work, and it does suggest many new approaches to a host of basic questions, and as such, was work worth doing. Restatement of the Problem To refresh the mind of the reader, the basic idea was to attempt a computational implementation of the idea expressed in Buddhism as “kamma and passions [kilesa] are the cause of Samsara” (Rhys Davids and Stede 1921-1925, III 20). This idea is set in the context of ecosystem collapse in Asia as bad as the anywhere in the world, with several of the major Buddhist countries already deforested, and the others well on their way (Weiner 1999, Bleeker 1999). As a consequence floods ravage their countrysides (Maryknoll 2000), and we can only thank the march of progress for protecting their victims from coming to believe in an autonomous vengeful god in such circumstances, as must have happened in ancient Mesopotamia after similar environmental destruction, when the Ziggurats were constructed. However, that same march is driven by the most destructive myth of all, the myth of science, which destroys all other myths in its path (Horkheimer and Adorno 1982, 6). This author does not dispute the assertion

106 that freeing humans from superstition is a well-intentioned act, but as Grechen Schoff was fond of remarking, in ecology you can never do just one thing. Those superstitions are often symbols supporting sustainable ways of life. If a village dedicates its energy to planning a religious festival, it is energy not spent pressuring the land for more production than it can sustainably deliver. Religions are the flywheels of cultures, and cultures are the keystone species of the landscapes they inhabit.

Perhaps before the arrival of humans everywhere but

Africa the mega fauna were much better off, but that damage was done long ago, and the settled descendents of those early destroyers have perforce learned to live in better harmony with the land. The European expansion is having a similar destructive affect around the world, and it is the responsibility of thinking people on both sides of this wave to do whatever can be done to mitigate its impacts. Asian societies can be particularly resistant to infection with the memes of modernization, since it is easy for them to recognize that what they already have is often superior, but this is far from universally true. According to the anthropologist Peter Metcalf, in Burma there is a temple with a diamond set in its roof, and on moonlit nights the custom is to circumambulate it in little groups, having quiet conversations, taking particular joy in the moments when they are lucky enough to walk through the pools of diamond moonlight. Yet the ex-CEO of PepsiCo Corporation, Christopher Sinclair is famous for having had the temerity to remark that by forcing his product in that traumatized country he was offering its people a “something that is a little bit special” (“Victories” 2000). Everyone wants to be like the conqueror, and multinational corporations have every reason to foster this impulse, so they can sell their products, and serve the expanding ambitions of their countries of origin. Swarmsara as a Move in Consequentialist Debate In this context, Swarmsara is almost as cynical as it probably is futile. But Yoga , a cognate of the English “yoke”, along with the martial arts and Indo-Tibetan

107 philosophical debate, means to join with the opponent, to introduce the opponent to its own unwanted consequences (Skt: prasanga). The idea is to inject a meme into the Buddhist and scientific culture that might serve as an inoculation against the destruction of the precious Buddhist knowledge system and its ability to care for the land, using as a vector, that very fascination with the modern that makes so many so vulnerable. Perhaps the message is really a protest against the easy confidence many have that delivering technology to developing societies is bound to help them. Perhaps Swarmsara is trying to say; the sensitivity needed to offer development assistance that does not do more harm than good is beyond the abilities of mere mortals like this writer, or of typical NGO workers. Having said that, the hope remains that through the collective efforts of people with Buddhist backgrounds, or otherwise, working with these nascent ideas, a more altruistic, ethical approach to land resource planning might emerge in Buddhist Asia, that could at least slow down the destruction taking place. It is said somewhere in the Buddhist tradition that in our current degenerated era, the Kaliyuga, keeping even a single precept has more karmic merit than keeping all of them in easier times (Atisha 2000).

So any effort in the direction of

environmental preservation, however shamefully inadequate, must surely be worth attempting. If it ends up doing more harm than good, it will at least be in the good company of most approaches to the problems of development. Swarmsara as a Constructivist Educational Tool The Swarmsara implementation is intended as a constructivist educational tool, meant to inspire the user to further inquiry into the ideas behind it. It includes a control panel with many settings adjustable by the user, and is easily accessible from the author’s website on the Internet.

As mentioned earlier a monk in

Thailand posted that address in a public forum, and since then it has received visits from around the world. The presentation at the Chaos and Complex

108 Systems seminar was packed, and many people came up to ask questions afterwards. However, despite the web visits, and other passing interest, so far it has not generated the kind of sustained interest it would need to serve its intended purpose of opening new fields of inquiry. The interest is a bit like a run of Conway’s Game of Life, intense for a short while, but quickly devolving into repetition and stasis. One interesting exception to this trend is an interlocutor who has yet to see the simulation itself, but has only heard about its theoretical underpinnings, and on that basis seems to have a sustained interest. This may indicate the implementation is failing to do justice to the ideas behind it, and its real take off as a subject of discourse might have to wait until the agents are able to learn from their conditions.

It may also be true that the ideas expressed and

implemented here, however original, are only of passing interest at best. If this means real Buddhism is far more interesting than anything that can be canned inside a computer, this is not an undesirable result. Critique of Negative Emphasis in Swarmsara Or it may be the Swarmsara project as it stands takes too negative an approach to Buddhism. Tibetan Buddhist texts do not have titles like “Your mind is like a swarm of hungry fish” or “As you are, it is impossible to be happy”. Rather, they are titled Kindly Bent to Ease Us or The Precious Garland or Song of the Jewel Mirror Samadhi. One Tibetan friend implored me to model the positive side as well. This author, as a Darwinian skeptic, is certainly more open to the deconstructive, negative side of Buddhism than that which describes endless pure lands full of enlightened beings. But it is clear from the doctrine that in order to be liberated; one must first grasp the causes of suffering. Only in so doing can there be any genuine hope that since sufferings are caused, they can also be stopped, and only with that well-founded hope can one scale the slopes of that far peak in the fitness landscape, the one pointing to altruism and not selfishness. So rather than being a project in starting samsara over again, Swarmsara is intended as a warning

109 that the life process from the beginning manufactures distortion and delusion, and is not to be trusted. That is the reason we must study it and learn its ways, so that we might finally start to shift our role in its reflexive complexity, towards a happier, more benign outcome. Practical Resources for Further Development Practically speaking, in order to continue learning the computer languages needed to do this project, and without funding, I took a job at the Wisconsin Department of Natural Resources as a programmer. It remains my hope that someday I can take the experience and knowledge I am accumulating in my increasingly critical role there as an Oracle web database and GIS developer and use it to help re-emerging Buddhist nations like Burma and Tibet to create sound institutions for ecological management and cleanup.

By the time this

opportunity emerges, if it ever does, I have reason to believe I will be well equipped to serve as a vector for the right kind of technology transfer. The creation of a large project for the application of the Swarmsara approach could actually be feasible were conditions to ripen and shift only slightly. A Final Word One of the several long grueling days of mantra-like repetitious bibliography formatting that came at the end of this project, I staggered out numbly for a walk to watch the sunset over Madison’s Lake Mendota. As I sat on a rock looking over the water, the endless play of wind and water and fire did its work, melting and opening my mind in a thousand whispered metaphors. It struck me as sensation returned that this work has been neglectful of Buddhism’s emphasis on nature as teacher, although to be sure that topic is well served by many others. Then a few other thoughts came, I remembered how important it had been to me to make a point about the highest stage of Anapanasati, patinissagganupassi, which means throwing it all back to nature (Buddhadasa 1988a, 88). In other words, it

110 could be said, for the Buddhists, enlightenment is just recognizing one’s infinite debt to nature and finally responding to that recognition. This work is dedicated to the preservation and development of the Buddhist tradition, so it may continue in its mission of saving all sentient beings, and perhaps even a cellular automaton or two, from suffering.

111 WORKS CITED

Atisha, Palden. 2000. “Advice from Atisha,” trans. under Geshe Wangyal. Accessed May 1, 2001. . Axelrod, Robert. 1984. The Evolution of Cooperation. New York: Basic Books. Babcock-Abrahams, Barbara. 1984. “Arrange Me into Disorder: Fragments and Reflections on Ritual Clowning.” Rite, Drama, Spectacle: Rehersals Toward a Theory of Cultural Performance, ed. By John MacAloon. Philadelphia: Institue for the Study of Huamn Issues, pp. 102-128. Badiner, Allan Hunt, ed. 1990. Dharma Gaia: A Harvest of Essays in Buddhism and Ecology. Berkeley: Parallax Press. Barash, David P. 2001. “Buddhism and the ‘Subversive Science’.” Chronicle of Higher Education, February 23. Barman, Todd J. 1997. Scenic Beauty and Travel Behavior: The Effect of Visual Preference on Stated Travel Route Preference. Thesis, UW Madison. Benford, Gregory. 1999. COSM. New York: Avon Eos. Berman, Saul J. 1992. “Jewish Environmental Values: The Dynamic Tension Between Nature and Human Needs.” Human Values and the Environment

: Conference Proceedings. Madison, WI: Wisconsin Academy of Sciences, Arts and Letters, pp 811. Bleeker, Marco. 1999. “The Speed of Deforestation.” Accessed May 1, 2001. . Bowie, David. 1980. “Up the Hill Backwards.” Scary Monsters (and Supercreeps). RCA. Audio LP. Brooks, Rodney A. 1995. “Intelligence Without Reason.” The Artificial Life Route to Artificial Intelligence: Building Embodied, Situated Agents, ed. by Luc Steels and Rodney Brooks. Hillsdale, New Jersey: Lawrence Erlbaum Associates. Brooks, Rodney A. 1997. Fast, Cheap and Out of Control. Sony Pictures Classics. 82 min. Accessed May 1, 2001 . Buddhadasa, Bhikkhu. 1986. Dhammic Socialism. Trans. and ed. Donald K. Swearer. Bangkok: Thai Inter-Religious Commission for Development. Buddhadasa, Bhikkhu. 1988a. Anapanasati: Mindfulness With Breathing: Unveiling the Secrets of Life: A Manual for Serious Beginners, trans. Santikaro

112 Bikkhu. Bangkok: Dhamma Study/ Practice Group. Buddhadasa, Bhikkhu. 1988b. Key to Natural Truth. Bangkok: The Dhamma Study and Practice Group. Buddhadasa, Bhikkhu. 2001. “Remembering the Hornbill.” Suan Mokkh: Evolution/Liberation. Feb. Accessed May 1, 2001. . Buddhadasa, Bhikkhu.1999. “Conserving the Inner Ecology,” trans. Santikaro Bikkhu.. Suan Mokkhabalarama: Evolution/Liberation. Accessed 21 Oct. 2000. . Buddhism in America: The Official Record of the Landmark Conference on the Future of Buddhist Meditative Practices in the West, Boston, January 17-19, 1997, comp. by.Al Rapaport, ed. By Brian D. Hotchkiss. 1998. Rutland VT: Charles E. Tuttle. Byrne, David. 1981. The Complete Score from the Broadway Production of “The Catherine Wheel,” choreographed by Twyla Tharp. Campbell, Joseph. 1968. The Masks of God: Oriental Mythology. New York: The Viking Press. Capra, Fritjof. 2000. The Tao of Physics: An Exploration of the Parallels Between Modern Physics and Eastern Mysticism, 4th Ed, updated. Boston: Shambhala.

Carr, Eric;Kohler, Tim; and Van West, Carla. 1997. “SWARM: The Anasazi Village Formation Model.” Santa Fe: The Santa Fe Institute. Accessed May 1, 2001. . Chang, Garma C. C. 1981. Buddhist Teaching of Totality: The Philosophy of Hwa Yen Buddhism. University Park PA: Pennsylvania State University Press. Chatwin, Bruce. 1987. The Songlines. New York: Viking. Chaudhuri, Sukomal. 1976. Analytical Study of the Abhidharmakosa. Calcutta: Sanskrit College. Childers, Robert Caesar. 1909. A Dictionary of the Pali Language. London: Kegan Paul, Trench, Trubner. Chogyen, Pema Losang and Namgyal Monastery. 1992. Exploring the Mandala, VHS Cassette. Ithaca: Cornell University. Clifford, Terry. 1984. Tibetan Buddhist Medicine and Psychiatry: The Diamond Healing. York Beach ME: Samuel Weiser. Collingwood, R.J. 1946 The Idea of History. Oxford: Oxford University Press. Cousteau, Jacques. 1975. “The Sleeping Sharks of Yucatan,” narr. By Joseph Campanella. The Undersea World of Jacques Cousteau. Metromedia Producers Corp. CAV. Curtin, Philip D. 2000.The World and the West: The European Challenge

113 and the Overseas Response in the Age of Empire. Cambridge: Cambridge UP. Damasio, Antonio R. 1994. Descartes’ Error: Emotion, Reason, and the Human Brain. New York: Avon. Damtsig. 2001. Accessed May 1, 2001. . Dawkins, Richard. 1987. The Blind Watchmaker : Why the Evidence of Evolution Reveals a Universe Without Design. New York: Norton. Dennett, Daniel C. 1995. Darwin's Dangerous Idea : Evolution and the Meanings of Life. New York: Simon & Schuster. Derrida, Jacques. 1978. Of Grammatology, trans. by Gayatri Chakravorty Spivak. Baltimore: Johns Hopkins University Press. Durrett, Rick. 2001. Rick Durrett’s Home Page. Accessed April 30, 2001. .. Ewen, Stuart. 1976. Captains of Consciousness: Advertising and the Social Roots of the Consumer Culture. New York: McGraw-Hill. Eyre, Ronald, narr. 1977. “Land of the Disappearing Buddha.” The Long Search , prod.by Peter Montagnon, episode 9. TimeLife Films. VAS, 53 min. Farhi, Edward; Guth, Alan H.; and Guven, Jemal. 1990. “Is it Possible to Create a Universe in the Laboratory by Quantum Tunneling?” Nuclear Physics B, vol. 339. pp. 417-490.

Filliozat, J. 1964. The Classical Doctrine of Indian Medicine: Its Origins and Greek Parallels, trans. by Dev Raj Chanana. Delhi: Munshiram Manoharlal. Fish, Stanley Eugene. 1980. Is There a Text In This Class?: The Authority of Interpretive Communities. Cambridge MA: Harvard UP. Fogel, David B. 1995. Evolutionary Computation: Toward a New Philosophy of Machine Intelligence. New York: IEEE Press. Foster, George M.. 1994. Hippocrates’ Latin American Legacy: Humoral Medicine in the New World. Theory and Practice in Medical Anthropology and International Health, vol. 1. Langhorne, PA: Gordan and Breach. Ganguly, Swati. 1994. Treatise on Groups of Elements: The Abhidharma-Dhatukaya-Padasastra: English Translation of Hsüan-tsang’s Chinese Version Edited with Critical Notes. Delhi: Eastern Book Linkers. Gautama, Buddha. 1997. Kalama Sutta.. Mahasati Association of America. Nov. 8. Accessed May 1, 2001. . Gecko. 2001. Yale University. March 1. Accessed May 1, 2001. . Gombrich, Ernst Hans. 1977. Art and Illusion: A Study in the Psychology of Pictorial Representation. London: Phaidon.

114 Graybiel, A.M. 1998. “The Basal Ganglia and Chunking of Action Repertoires.” Neurobiology of Learning and Memory, vol. 70, pp. 119-136. Guth, Alan H. 1991. “Can a ManMade Universe be Created by Quantum Tunneling without an Initial Singularity?” Physica Scripta, vol. T36. Stockholm: Royal Swedish Academy of Sciences, pp. 237-246. Gyatso, Tenzin, Dalai Lama XIV ; Benson, Herbert; Thurman, Robert A.F.; Goleman, Daniel; Gardner, Howard; et. al. 1991. MindScience: An East-West Dialogue: Proceedings of a Symposium Sponsored by the Mind/Body Medical Institute of Harvard Medical School & New England Deaconess Hospital, and Tibet House New York, ed. by Daniel Goleman and Robert A. F. Thurman. Boston: Wisdom Publications. Gyatso, Tenzin, Dalai Lama XIV. 1988. The Dalai Lama at Harvard: Lectures on the Buddhist Path to Peace, Jeffrey Hopkins, trans. Ithaca NY: Snow Lion Publications. Gyatso, Tenzin, Dalai Lama XIV. 1990. A Policy of Kindness : An Anthology of Writings by and About the Dalai Lama, foreword by Claiborne Pell; compiled and ed. by Sidney Piburn. Ithaca, N.Y.: Snow Lion Publications. Gyatso, Tenzin, Dalai Lama XIV. 1996. Beyond Dogma: The Challenge of the Modern World, trans. by Alison Anderson and Marianne

Dresser. Berkeley: North Atlantic Books. Accessed May 1, 2001. . Gyatso, Tenzin, Dalai Lama XIV. 1999/2000. “The Long Road Home: Robert Thurman Interviews His Holiness The Dalai Lama About the Life and Fate of His Once and Future Homeland.” Civilization: The Magazine of the Library of Congress, vol. 71, Dec./Jan. p. 71. Holland, John H. 1995. Hidden Order : How Adaptation Builds Complexity. Reading, Mass: Addison-Wesley. Horkheimer, Max and Adorno, Theodor W. 1982. Dialectic of Enlightenment, trans. by John Cumming. New York: Continuum. Human Values and the Environment: Conference Proceedings. 1992. Madison, WI: Wisconsin Academy of Sciences, Arts and Letters. International Network of Engaged Buddhists. 2000. Buddhist Peace Fellowship Website. 23 Oct. Accessed May 1, 2001. . Johnson, Charles. 2001. “The Elusive Art of ‘Mindfulness’.” Chronicle of Higher Education, April 13. Jordan, William R. III; Gilpin, Michael E.; and Aber, John D., eds. 1987. Restoration Ecology: A

115 Synthetic Approach to Ecological Research. Cambridge UK: Cambridge University Press. Judge, Anthony. 1991. “Guiding Metaphors and Configuring Choices.” Tools for Critical Choice by Top Decision Makers. Development Administration Division of the United Nations Department of Technical Cooperation for Development. Jung, Carl Gustav. 1963. Memories, Dreams, Reflections, recorded and ed. By Aniela Jaffé, trans. by Richard and Clara Winston. New York: Pantheon Books. Kato, Bunno; Tamura, Yoshiro; and Miyasaka, Kojiro, trans. 1978. The Threefold Lotus Sutra: Innumerable Meanings, The Lotus Flower of the Wonderful Law, and Meditation on the Bodhisattva Universal Virtue, revised by W.E. Soothill, Wilhelm Schiffer, and Pier P. Del Campana. New York: Weatherhill/Kosei. Klon-chen-pa Dri-med-‘od-zer. 1976. Kindly Bent to Ease Us: From the Trilogy of Finding Comfort and Ease, trans. and anno. by Herbert V. Geunther. Emeryville CA: Dharma Publishing. Kongtrul Lodrö Tayé, Jamgön. 1995. Myriad Worlds: Buddhist Cosmology in Abhidharma, Kalachakra, and, Dzog-chen, trans. and ed. by the International Translation Committee of Kunkhyab Choling. Ithaca, N.Y.: Snow Lion Publications.

Kosumas, Wimonkan. 2000. Half a Hegemon: Japan’s Leadership in Southeast Asia. Diss. University of Virginia. Lasch, Christopher. 1979. The Culture of Narcissism: American life in an Age of Diminishing Expectations. New York: Warner Books. Levy, Steven. 1992. Artificial life : The Quest for a New Creation. New York: Pantheon Books. Lewis, John, Loftus, William (Contrib.). 1998. Java Software Solutions : Foundations of Program Design. Reading MA: AddisonWesley. Linde, A.D. 1990. Inflation and Quantum Cosmology, ed. by Robert Brandenberger, Boston: Academic Press. Linde, Andrei. 1998. “The SelfReproducing Inflationary Universe.” Scientific American, March. Lintner, Bertil. 1990. Outrage: Burma’s Struggle for Democracy. London: White Lotus. Lupton, Julia Reinhard and Reinhard, Kenneth. 1993. After Oedipus: Shakespeare in Psychoanalysis. Ithaca: Cornell UP. MacDonell, Arthur Anthony. 1958. A Practical Sanskrit Dicitionary with Transliteration, Accentuation and Etymological Analysis Throughout. Oxford: Oxford University Press. Marcuse, Herbert. 1964. One Dimensional Man. Boston: Beacon Press. Marx, Karl. 1976. Capital : A Critique of Political Economy, intro. by

116 Ernest Mandel ; trans. by Ben Fowkes. Harmondsworth, UK: Penguin. Maryknoll. 2000. “Thailand: Floods Blamed on Deforestation.” Global Concerns. Maryknoll. Accessed May 1, 2000. . “The Mitigation Scam.” 2000. Green Earth Journal: Reports from the Environmental Front. April 27. Accessed April 30, 2001. . Morris, William, ed. 1981. The American Heritage Dictionary of the English Language. Boston: Houghton Mifflin. Nagarjuna, Acharya and Gyatso, Kaysang the Seventh Dalai Lama. 1975. The Precious Garland and the Song of the Four Mindfulnesses, trans. and ed. by Lati Rinpoche, Jeffrey Hopkins and Anne Klein. New York: Harper and Row. Nagarjuna, Acharya. 1986. Master of Wisdom: Writings of the Buddhist Master Nagarjuna, trans and studies by Christian Lindtner. Berkeley: Dharma Publishing. Nasr, Seyyd Hossein. 1992. “The Islamic View of the Environment.” Human Values and the Environment : Conference Proceedings. Madison, WI: Wisconsin Academy of Sciences, Arts and Letters, pp. 47-49.

Olson, Charles. 1966. Selected Writings, ed. By Robert Creeley. New York: New Directions. Olson, Charles. 1975. The Maximus Poems. New York: Jargon/Corinth. Ovid. 1958. The Metamorphoses, trans by Horace Gregory, decorated by Zhenya Gray. New York: TheViking Press. Oxford English Dictionary, 2nd ed, prep. By J.A. Simpson and E.S.C. Weiner. 1991. Oxford: Clarendon Press. Phabongkha, Dechen Nyingpo. 1990. Meditation on Vajrabhairava: The Procedures for Doing the Serviceable Retreat of the Glorious Solitary Hero Vajrabhairava with the Sadhana “Victory Over Evil,” Trans. by Sharpa Tulku and Richard Guard. Dharamsala: Library of Tibetan Works and Archives. Phabongkha, Dechen Nyingpo. 1993. Liberation in the Palm of Your Hand: A Concise Discourse on the Stages of the Path to Enlightenment,ed. by Trijang Rinpoche, trans by Michael Richards. Boston: Wisdom Publications. Pinker, Steven. 1999. “Brain and Behavior: Segment 2” To the Best of Our Knowledge from Wisconsin Public Radio, WPR Program 9711-23-B, hosted by Jim Fleming. Madison WI: WHA, 7 March, hour 2. “Pratitya-samutpada.” 1999-2000. ENCYCLOPÆDIA BRITANNICA. Britannica.com.

117 Accessed Nov 3, 2000. Ray, Thomas S.. 1995. “An Evolutionary Approach to Synthetic Biology: Zen and the Art of Creating Life.” Artificial Life: An Overview, ed. By Christopher G. Langton. Cambridge MA: MIT Press. Resnick, Mitchell. 1995. “Learning About Life.” Artificial Life: An Overview, ed. By Christopher G. Langton. Cambridge MA: MIT Press. Rhys Davids, T.W. and Stede, William, eds. 1921-1925. The Pali Text Society’s Pali-English Dictionary. London: Luzac. Rucker, Rudy. 1988. Wetware. New York: Avon. Rucker, Rudy. 1993. Artificial Life Lab. Corte Madera CA: Waite Group Press. Ryokai, Tozan. 1999. “Song of the Jewel Mirror Samadhi.” San Francisco: San Francisco Zen Center. Accessed May 1, 2001. . Shakespeare, William. 1999. As You Like It, The Works of William Shakespeare, Presented by ELF. Electronic Literature Foundation | JazzEtext Engine. Accessed 21 Oct. 2000. . Shantideva, Acharya. 1981. A Guide to the Bodhisattva’s Way of Life, trans. by Stephen Batchelor.

Dehli: Library of Tibetan Works and Archives. Silacara, Bikkhu. 1953. A Young People’s Life of the Buddha. Singapore. Singapore Buddhist Meditation Center. 1995. Accessed May 1, 2001. Silliman, Ron. 1987. “A 1982 Interview with Ron Silliman.” Alive and Writing: Interviews with American Authors of the 1980s, conducted and ed. By Larry McCaffery and Sinda Gregory. Urbana: U of Illinois P. 1987. Accessed April 29, 2001. . Sivaraksa, Sulak. 1992. Seeds of Peace : A Buddhist Vision for Renewing Society. Berkeley, CA: Parallax Press. Sloman, Aaron. 1978. The Computer Revolution in Philosophy: Philosophy, Science and Models of Mind, Harvester Studies in Cognative Science ed. Margaret A. Boden. Hassocks, Sussex:: The Harvestor Press. Smolin, Lee. 1997. The Life of the Cosmos. New York: Oxford University Press. Snyder, Gary. 1980. The Real Work: Interviews & Talks, 1964-1979, ed. and intro. By Wm. Scott McLean. New York: New Directions. Soros, Georges. 1997. “The Capitalist Threat.” The Atlantic

118 Monthly, vol. 279, No. 2, Feb, pp. 45-58. Accessed April 30, 2001 Stauber, John and Rampton, Sheldon. 1995. Toxic Sludge is Good for You: Lies, Damn Lies, and the Public Relations Industry. Monroe, ME: Common Courage Press. Steels, Luc and Brooks, Rodney A., eds. 1995. The Artificial Life Route to Artificial Intelligence: Building Embodied, Situated Agents. Hillsdale, New Jersey: Lawrence Erlbaum Associates. Steels, Luc. 1995. “The Artificial Life Roots of Artificial Intelligence.” Artificial Life: An Overview, ed. By Christopher G. Langton. Cambridge MA: MIT Press. Sunthorn, Na-Rangsi. 1976. The Buddhist Concepts of Karma and Rebirth. Bangkok: Mahamakut Rajavidyalaya Press. Swarm Development Group,. 2001. Swarm Development Group. Accessed May 1, 2001. . Tambiah, S.J. 1976. World Conqueror and World Renouncer: A Study of Buddhism and Polity in Thailand Against a Historical Background. Cambridge, UK: Cambridge University Press. Thurman, Robert A.F. 1992. “Buddhist Views on the Environmental Crisis.” Human Values and the Environment : Conference Proceedings, Madison,

WI : Wisconsin Academy of Sciences, Arts and Letters, pp. 23-31. Thurman, Robert A.F. 1999-2000. “Boardroom Buddhism.” Civilization: The Magazine of the Library of Congress, vol. 71, Dec./Jan. pp. 61-64. Toulmin, Stephen Edelston. 1982. The Return to Cosmology: Postmodern Science and the Theology of Nature. Berkeley: University of California Press. Tricycle.com: The Buddhist Review. 2001. Accessed April 30, 2001. . Trungpa, Chögyam. 1973. Cutting Through Spiritual Materialism, ed. by John Baker and Marvin Casper, illus. by Glen Eddy. Berkeley: Shambhala. Tucker, Mary Evelyn and Williams, Duncan Ryuken, eds. 1997. Buddhism and Ecology: The Interconnection of Dharma and Deeds. Cambridge MA: Harvard University Press. Udupa, K.N. 1975. The Ayurvedic System of Medicine in India. In Health by the People, K.W. Newell, ed.. Geneva: World Health Organization, pp. 53-69. Varela, Francisco J. 1995. “The ReEnchantment of the Concrete: Some Biological Ingredients for a Nouvelle Cognitive Science” The Artificial Life Route to Artificial Intelligence: Building Embodied, Situated Agents, ed. by Luc Steels and Rodney Brooks. Hillsdale, New Jersey: Lawrence Erlbaum Associates.

119 “Victories!” 2000. Free Burma Coalition. Accessed May 1, 2001. . Virilio, Paul. 1986. Speed and Politics. New York: Semiotexte. Von Neumann, John. 1966. Theory of Self-Reproducing Automata, ed. and completed by Arthur W. Burks. Urbana: University of Illinois Press. Warren, Karen J. 1992. “Taking Empirical Data Seriously: An Ecofeminist Philosophical Perspective.” Human Values and the Environment : Conference Proceedings. Madison, WI: Wisconsin Academy of Sciences, Arts and Letters, pp. 32-39. Weiner, Matt. 1999 “The Story of Pho: The Monk who Ordained Trees.” Seeds of Peace. Bangkok: INEB. Accessed May 1, 2001. . Whitehouse, David. 1999. “Hunting the Higgs.” BBC News | SCI/TECH, March 19.

Accessed April 29, 2001. . Whitehouse, David. 2000. “Three Giant Icebergs Calved in Antarctic.” BBC News | SCI/TECH, May 23. Accessed April 29, 2001. . Wilson, Edward O. 1992. The Diversity of Life, Cambridge, MA: The Belnap Press of Harvard University. Yamada, Koun, trans. 1990. Gateless Gate, 2nd ed. Tucson: University of Arizona Press. Wyatt, David K. 1984. Thailand: A Short History. New Haven: Yale University Press. Zimmer, Heinrich. 1948. Hindu Medicine. Baltimore: The Johns Hopkins Press. Zukav, Gary. 1979. The Dancing Wu Li Masters: An Overview of the New Physics. New York: Morrow.

120 APPENDIX A: GLOSSARY

Abhidharma. The Buddhist canon of epistemological and psychological theory, and the main text therein. Abhidharmakosa. A major text of the Abhidharma. Agent. A term more specifically defined in other works, here, an object capable of making choices. Sentient being. Distinguished from a cellular automaton mainly in terms of degree. Cellular automata can be subject of mathematical theorems, agent-based simulations usually cannot. Algorithm. An information process with input and output. The word comes from Arabic. Artificial Life. Any attempt to model a life process. These are usually implemented as robots or computer simulations. Also, the field of study about these attempts. Ayurvedic Medicine. The ancient humoral medical tradition of India revived during the Indian independence movement. It is similar in many respects to Greek Hippocratic medicine and it is unclear which came first. Bodhisattva. Buddha to be, a being who has vowed to attain enlightenment soley for the purpose of saving all sentient beings from suffering and placing them in bliss. Buddha. An enlightened being who is ready to enter final Nirvana upon death. Cellular Automaton. (CA) A set of rules for local state change, usually interacting with others in a raster landscape. Complex Adaptive System. (CAS) John Holland’s term for a wide range of collective phenomena, from immune systems to economies. Conventional Existence. The real mode of things, as opposed to inherent existence. The world as empty information process. Dosa. Humor. Similar to Klesha, but in the context of Ayurvedic medicine. The three primary dosas are phlegm, bile and wind.

121 Emergence. Unexpected interesting behavior in an artificial life system or game. Enlightenment. In Buddhism, a state of no hindrance to omniscience about how to liberate others. Epistemology. The branch of philosophy concerned with how we know and perceive. Fitness Landscape. An concept in evolutionary biology. A map of traits rated in terms of their adaptiveness. Fitness landscapes are never exact derivatives of the physical landscape, because they are defined in large part by the agents in the landscape adapting to each other reflexively. Genetic Algorithm. A form of logic designed to act like the natural selection process, particularly its methods of information storage and distribution, first proposed by John Holland. Humoral Medicine. The medical system widely spread across the ancient world, and still alive in many places and forms. It entailed a theory of reality based on four or five elements which were associated with organs and processes of the body. Inherent Existence. An impossible mode of existence, in which things are permanent, partless, existing on their own side, etc. According to Buddhists, a deep-seated evolved belief in inherent existence is the ignorance that is the root of suffering. Java®. A modern Object-oriented programming language characterized by being platform-independent. Karma. Action. A theory of cause and effect as an information process. Klesha. Also Kilesa. Obscuration, afflictive emotion. There are many, but Swarmsara implements only the three primary ones, ignorance, attraction and aversion, usually translated at greed, anger and ignorance. Lam Rim. Buddhist catechism of the Gelukpa sect of Tibetan Buddhism. Literally, stages of the path. Mandala. Usually thought of as a circle, it is also in Tibetan Buddhism a castle symbolizing body, speech and mind by its nested walls, built on bases symbolizing the elements. It is also a metaphor for space and power, shared

122 across vast geographical distances, from the Roman influenced design of the State Capital building in Madison Wisconsin to the sand mandalas of the Hopi Indians. It is one of the most ancient and useful symbols in the human repertoire. Metanym. Naming something by one of its parts, the classic example being saying “a sail!” for a ship, when it is first seen on the horizon. Object-Oriented Programming. (OOP) An approach to the design of solutions to problems implemented in computer languages like Java and Objective-C. It entails principles like classes/objects, inheritance and encapsulation to make the programmer’s job easier. A class is a blueprint for an object. An object is an instance of a class. Inheritance is the capability of making new classes which are slight modifications of existing classes, and encapsulation is the ability to hide the details of an object’s functionality, so the user of the object only needs to deal with controls, not wiring. Ontological Deconstruction. A philosophical method meant to uproot misconceptions about the mode of being. Practiced among many others by the Indian Pandit Acharya Nagarjuna and the French critical theorist Jacques Derrida. Pratitya-samutpada. also Paticca-samuppada (Pali). Interdependent co-origination. In its impure form, Samsara, especially the Twelve Links (Niddanas), but also conventional existence in its pure form. Raster. A spatial checkerboard-like grid data structure for representing interactions in two dimensions, or for representing pixel data. Reflexivity. The idea that participants in a system affect the environment of a system. Although obvious, as Georges Soros points out, it is a point lost on proponents of the world’s major ideologies such as communism and capitalism. It is key to understanding CAS and evolutionary fitness landscapes. Samadhi. A state of bliss and healing brought about by dhyana, meditative concentration. Samsara. The world as we perceive it. Cyclic existence. A set of six realms in which beings are reborn and where they suffer from beginningless time. Sentient Being. Agent. An object capable of feeling attraction, aversion and laziness, and subject to karma. In Tibetan, translated as Sem-Jen, “mind having”. Here, the question of existence of mind is not addressed.

123 Sunyata. The voidness of self, inherent existence, existence by way of its own character, etc. Different Buddhist traditions put different emphasis on it, but for many it is critical. Sutra. A Buddhist canonical text. Swarm Simulation System. A library of computer language modules useful for performing artificial life experiments. Swarmsara. The Java applet that is the basis for this thesis. Tantra. A tradition of transformative yogas and rituals probably stemming from the Neolithic, but which were absorbed into Buddhism and Hinduism much later. A text of the Indo-Tibetan canon about such practices. Theravada Buddhism. The last remaining of several schools of so-called Hinayana Buddhism, the Buddhism practiced primarily by monks, that led to the creation of the Abhidharmakosa. Vajrayana. A part of Indo-Tibetan Buddhism originally intended only for the most advanced students but now taught to beginners. Two key aspects are guru devotion and Yidam practice. Von Neumann Neighborhood. In a raster grid, three by three grid of nine cells immediately available to an agent. Yidam. A Tantric tutelary deity, meditation upon which is said to accelerate progress towards spiritual attainment.

124 APPENDIX B: SUGGESTED READING

Aber, John D. and Melillo, Jerry M. 1991. Terrestrial Ecosystems. Philadelphia: Saunders College Publishing. Adleman, Leonard M. 1994. "Molecular Computation of Solutions to Combinatorial Problems." Science, vol. 266, Nov 11, pp. 1021-4. Allen, T.F.H., and Starr, Thomas B. 1982. Hierarchy: Perspectives for Ecological Complexity. Chicago: University of Chicago Press. Arnold, Ken, and Gosling, James. 1999. The Java Programming Language, (Java Series) 2nd ed. Reading Mass: Addison-Wesley. Askins, Robert A., and Julie Zickefoose, Illus. 2000. Restoring North America's Birds: Lessons from Landscape Ecology. New Haven: Yale UP. Austin, J.L. 1975. How To Do Things With Words: The William James Lectures 1955, 2nd ed. Cambridge, Mass: Harvard University Press. Austin, James H. 1999. Zen and the Brain: Toward an Understanding of Meditation and Consciousness. Cambridge Mass: MIT Press. Benford, Gregory. 2000. Eater. New York: Eos. Bray, John R. 1955. The Savanna Vegetation of Wisconsin and an Application of the Concepts Order and Complexity to the Field of

Ecology. Ph.D. Thesis: University of Wisconsin-Madison. Brown, Brian E. 1981. The Buddha Nature: A Study of the Tathagatagarbha and Alayavijnana. New York: Dissertation at Fordham University. Buddhism and Nature: Proceedings of an International Symposium on the Occasion of EXPO 1990. 1991. Tokyo: The International Institute for Buddhist Studies. Bynum, Terrell Ward, and Moor, James H. eds. 1998. The Digital Phoenix : How Computers Are Changing Philosophy. Oxford: Blackwell Publishers. Chekhov, Anton. 1989. Uncle Vanya, adapted by David Mamet, trans. by Vlada Chernomirdik. New York: Grove Press. Chng, Nancy (ed.). 1988. Questioning Development in Southeast Asia. Singapore: Select Books. Conze, Edward; Horner, J. B.; Snellgrove, David; and Waley, Arthur, eds. 1954. Buddhist Texts Through the Ages: Translated from Pali, Sanskrit, Chinese, Tibetan, Japanese and Apabhramsa. New York: Harper & Row. Curtis, John T. 1987. The Vegetation of Wisconsin: An Ordination of Plant Communities. Madison: U of Wisconsin Press. Dandhanin, Mongkul; Kaewsong, Banchorn; et al. 1990. A Research Proposal on Community Forestry in

125 the Northeast, submitted to Professor Saneh Chamrik at the Local Development Institute. Desai, Prakash N. 1989. Health and Medicine in the Hindu Tradition. New York: Crossroad. Dewdney, Christopher. 1978. Spring Trances in the Control Emerald Night. Berkeley: The Figures. Dreyfus, H.L. 1979. What Computers Can't Do: The Limits of Artificial Intelligence, 2nd ed. New York: Harper & Row. Dummer, Tom. 1988. Tibetan Medicine and Other Holistic HealthCare Systems. London: Routledge. Ekachai, Sanisuda. 1993. Behind the Smile: Voices of Thailand. Bangkok: The Post Publishing Co. Floreano, Dario; Nicoud, JeanDaniel; and Mondada, Francesco, eds. 1999. Advances in Artificial Life: European Conference on Artificial Life: 5th European Conference, ECAL'99, Lausanne, Switzerland, September 13-17, 1999 : proceedings, Lecture Notes in Computer Science ; vol. 1674, Lecture Notes in Artificial Intelligence. Berlin: Springer. Forestland for the People: A Forest Village Project in Northeast Thailand. 1988. Bangkok: Food and Agriculture Organization of the United Nations. Givnish, T.J. 1984. “Leaf and canopy adaptations in tropical forests.” Tasks for Vegetation Science, vol. 12, pp.51-84. Gleick, James. 1987. Chaos: Making a New Science. New York: Viking.

Gold, Martin, ed. 1999. The Complete Social Scientist: A Kurt Lewin Reader. Washington, DC: American Psychological Association. Goldstein, Melvyn C. 1989. A History of Modern Tibet, 19131951: the Demise of the Lamaist State. Berkeley: University of California Press. Grunfeld, A. Tom. 1987. The Making of Modern Tibet. London: Zed Books. Guth, Alan H. 1988. “The Birth of the Cosmos.” Origins and Extinctions: Based on a Symposium on Life and the Universe, held at the National Academy of Sciences, Washington, D.C., April 30, 1986, ed. By Donald E. Osterbrock and Peter H. Raven. New Haven: Yale University Press,. Pp. 1-42. Guth, Alan H. 2000. “Genesis: The Sequel.” Natural History, Feb 01, v 109, n 1. New York: American Museum of Natural History, p.77. Gyatso, Tenzin, Dalai Lama XIV. 1990. Freedom in Exile: The Autobiography of the Dalai Lama. New York: HarperCollins. Gyatso, Tenzin, Dalai Lama XIV; Agrawala, S.K.; et. al. 1995. Dialogues on Universal Responsibility and Education Dharamsala, H.P., India: Library of Tibetan Works and Archives. Hall, Justin. 1995. “Buddhadasa's Dhammic Socialism: an Internet Vision.”. 21 Oct. 2000

126 . Head, Suzanne and Heinzman, Robert, eds. Lessons of the Rainforest. San Francisco: Sierra Club Books, 1990. Hedin, Sven Anders. 1917. Southern Tibet: Discoveries in Former Times Compared With My Own Researches in 1906-1908, Stockholm: Lithographic institute of the General staff of the Swedish army. Holland, John H. 1992. Adaptation in Natural and Artificial Systems : An Introductory Analysis with Applications to Biology, Control, and Artificial Intelligence. Cambridge, Mass: MIT Press. Holtzman, Steven R. 1994. Digital Mantras: The Languages of Abstract and Virtual Worlds. Cambridge Mass: MIT Press. IEEE International Workshop on Robot and Human Communication. 1995. Proceedings, 4th IEEE International Workshop on Robot and Human Communication : RO-MAN'95 Tokyo, July 5-7, 1995, Waseda University, Tokyo, Japan. Piscataway, NJ: IEEE. IEEE International Workshop on Robot and Human Communication. 1996. Proceedings: 5th IEEE International Workshop on Robot and Human Communication : RO-MAN'96: November 11-14, 1996, Auditorium, AIST Tsukuba Research Center, Tsukuba, Ibaraki, Japan. Piscataway, NJ: IEEE.

IEEE International Workshop on Robot and Human Communication 1997. Proceedings : 6th IEEE International Workshop on Robot and Human Communication : RO-MAN'97 Sendai : 19 Sept.- 1 Oct., 1997, Tohoku University, Sendai, Japan. Piscataway, NJ: IEEE. International Campaign for Tibet. 1996. A Season to Purge: Religious Repression in Tibet. Washington DC: International Campaign for Tibet. Ishii, Yoneo. 1986. Sangha, State, and Society: Thai Buddhism in History, trans by Peter Hawkes. Monographs of the Center for Southeast Asian Studies Kyoto University. Honolulu: The University of Hawaii Press. Kauffman, Stuart A. 1993. The Origins of Order: Self Organization and Selection in Evolution. New York: Oxford University Press. Koza, John R. 1994. Genetic Programming II : Automatic Discovery of Reusable Programs. Cambridge, Mass: MIT Press. Koza, John R.. 1992. Genetic Programming : On the Programming of Computers by Means of Natural Selection, Cambridge, Mass: MIT Press. Kuhn, Thomas S. 1996. The Structure of Scientific Revolutions, 3rd ed. Chicago: University of Chicago Press. Langton, Christopher G. ed. 1995. Artificial Life: An Overview. Cambridge MA: MIT Press.

127 Langton, Christopher G., ed. 1994. Artificial Life III: Proceedings of the Workshop on Artificial Life Held June, 1992 in Santa Fe, New Mexico, Proceedings Vol. XVII Santa Fe Institute Studies in the Sciences of Complexity. Reading MA: Addison-Wesley. Langton, Christopher G.; Taylor, Charles; Farmer, J. Doyne; Rasmussen, Steen, eds. 1992. Artificial Life II: Proceedings of the Workshop on Artificial Life Held February, 1990 in Santa Fe, New Mexico, Proceedings Vol. X Santa Fe Institute Studies in the Sciences of Complexity. Reading MA: Addison-Wesley. Lemay, Laura; Perkins, Charles L. and Morrison, Michael. 1996. Teach Yourself Java in 21 Days, Professional Reference Edition. Indianapolis: Sams.net. Leslie, Charles. 1992. “Interpretations of Illness: Syncretism in Modern Ayurveda.” Paths to Asian Medical Knowledge, C. Leslie and A. Young, eds. Berkeley: University of California Press. pp. 177-208. Li, Tieh-tseng. 1956. The Historical Status of Tibet. New York: King's Crown Press. Lohmann, Larry. 1990. "Commercial Tree Plantations in Thailand: Deforestation by Any Other Name." The Ecologist, Vol. 20, No. 1, January/February, pp. 917. MacAndrews, Colin and Sien, Chia Lin. 1982. Too Rapid Rural Development: Perceptions and

Perspectives from Southeast Asia. Athens, Ohio: Ohio University Press. Margulis, Lynn. 1981. Symbiosis in Cell Evolution: Life and its Environment on the Early Earth. San Francisco: W. H. Freeman. Margulis, Lynn. 1988. “The Ancient Microcosm of Planet Earth.” Origins and Extinctions: Based on a Symposium on Life and the Universe, held at the National Academy of Sciences, Washington, D.C., April 30, 1986, ed. By Donald E. Osterbrock and Peter H. Raven. New Haven: Yale University Press, pp 1-42. Margulis, Lynn. 1998. Symbiotic planet : A New Look at Evolution. New York: Basic Books. Matthews, Bruce. Craving and Salvation: A Study in Buddhist Soteriology. Ontario: Wilfred Laurier University Press, 1983. McDermott, James Paul. 1984. Development in the Early Buddhist Concept of Kamma/Karma. New Delhi: Munshiram Manoharlal. N´hât Hanh, Thích. 1967. Vietnam: The Lotus In The Sea Of Fire. London: S.C.M. Press. Norbu, Namkhai. 1981. The Necklace of Gzi: A Cultural History of Tibet. Dharamsala, India: Information Office of His Holiness the Dalai Lama. Nyamapfene, K.W. 1983. "Correlation of Traditional Terms and Scientific Knowledge." Zambezia vol. XI, (i).

128 Oldfield, Margery L., and Alcorn, Janis B. 1991. Biodiversity: Culture, Conservation, and Ecodevelopment, Boulder: Westview Press. Packard, Steve. 1988. “Just a Few Oddball Species: Restoration and the Rediscovery of the Tallgrass Savanna.” Restoration & Management Notes, vol.6.1, pp.1322. Packard, Steve. 1993. “Restoring Oak Ecosystems: The Savannas and Wooodlands of the Midwest Are Providing an Arena for an Emerging Debate About the Nature of These Ecosystems.” Restoration & Management Notes, vol. 11.1, pp. 5-16. Padgham, Lin and Taylor, Guy. 1996. “A System for Modelling Agents Having Emotion and Personality.” Intelligent Agent Systems: Theoretical and Practical Issues: Based on a Workshop Held at PRICAI ’96: Lecture Notes in Artificial Intelligence 1209, Subseries of Lecture Notes in Computer Science, Lawrence Cavedon, Anand Rao, Wayne Wobcke, eds. New York: Springer. Panyakul, Vitoon.1992. People Centered Development: The People Forum 1991, 2nd Ed. Bangkok: Local Development Institute. Patt, David. 1992. A Strange Liberation : Tibetan Lives in Chinese Hands. Ithaca, N.Y.: Snow Lion Publications. Phongphit, Seri. 1988. Religion in a Changing Society: Buddhism, Reform, and the Role of Monks in Community Development in

Thailand. Hong Kong: Arena Press. Plotkin, Mark, and Famolare, Lisa, eds. 1992. Sustainable Harvest and Marketing of Rain Forest Products. Island Press, Washington. Proceedings of the Conference on "Forest Resources Crisis in the Third World", 6-8 September 1986. 1987. Penang: Sahabat Alam Malaysia. Resnick, Mitchel. 1994. Turtles, Termites, and Traffic Jams: Explorations in Massively Parallel Microworlds. Cambridge, MA: MIT Press. Richardson, Hugh Edward. 1962. A Short History of Tibet. New York: Dutton. Rinbochay, Lati. 1980. Mind In Tibetan Buddhism: Oral Commentary on Ge-Shay Jam-Bel-Sam-Pel's Presentation of Awareness and Knowledge, Composite of All the Important Points, Opener of the Eye of New Intelligence , trans., ed., and introduced by Elizabeth Napper. London: Rider. River, Jess. 1993. “We must learn to be leaves.” Earth Island Journal vol. 8.4, p. 12. 21 Oct. 2000 . Rogers, Carl R. And Stevens, Barry. 1967. Person to Person: The Problem of Being Human A New Trend in Psychology. Moab, Utah: Real People Press. Rogers, Carl R.. 1961. On Becoming a Person: A Therapist’s View of Psychotherapy. Boston: Houghton Mifflin.

129 Rogers, Carl R.. 1969. Freedom to Learn. Columbus: Charles E. Merrill Publishing. Rogers, Carl R.. 1977. Carl Rogers on Personal Power. New York: Delacorte Press. Rogers, Carl R.. 1980. A Way of Being. Boston: Houghton Mifflin. Royal Forest Department and Ministry of Agriculture and Cooperatives, Kingdom of Thailand. 1989. Final Report: Thailand Upland Social Forestry Pilot Project: Phase 1, July 1987December 1989, submitted to Ford Foundation, RFD/Ford Grant Number 870-0534. Rumbaugh, James; Blaha, Michael; Premerlani, William; Eddy, Frederick; and Lorenson, William (Contributor). 1991. Object-Oriented Modeling and Design. Englewood Cliffs, NJ: Prentice Hall. Santikaro, Bikkhu. 1999. Dhammic Socialism FAQ. Suan Mokkhabalarama: Evolution/Liberation. Oct. 23, 2000 . Santikaro, Bikkhu. 2000. Dhammic Socialism. Suan Mokkhabalarama: Evolution/Liberation. 4 June . Sanyal, Promaode Kumar. 1964. A Story of Medicine & Pharmacy in India: Pharmacy 2000 Years Ago and After. Calcutta: Shri Amitava Sanyal.

Schmithausen, Lambert. 1991. Plants as Sentient Beings in Earliest Buddhism: The A.L. Basham Lecture for 1989, Canberra: Australian National University. Schmithausen, Lambert. 1991. The Problem of the Sentience of Plants in Earliest Buddhism. Tokyo: The International Institute for Buddhist Studies. Schoenhoff, Doris M., 1993. The Barefoot Expert: The Interface of Computerized Knowledge Systems and Indigenous Knowledge Systems, Contributions to the Study of Computer Science, Number 3. Westport CN: Greenwood Press. Shakabpa, Tsepon W. D. 1967. Tibet, a Political History. New Haven: Yale University Press. Shermer, Michael. 1997. Why People Believe Weird Things: Pseudoscience, Superstition, and Other Confusions of Our Time, foreward by Stephen Jay Gould. New York: W. H. Freeman. Siu, R.G.H. 1957. The Tao of Science: An Essay on Western Knowledge and Eastern Wisdom. Cambridge, MA: MIT Press. Sivaraksa, Sulak. 1988. A Socially Engaged Buddhism. Bangkok: Thai Inter-Religious Commission for Development. Sloman, Aaron and Croucher, Monica. 1981. “Why Robots Will Have Emotions.” Proceedings of the Seventh International Joint Conference on Artificial Intelligence. New York: Springer-Verlag.

130 Snellgrove, David L. and Richardson, Hugh Edward. 1968. A Cultural History of Tibet, New York: F. A. Praeger. Sommerville, Ian. 1996. Software Engineering, 5th Ed. Wokingham, UK: Addison-Wesley. Spiro, Melford, 1982. Buddhism and Society: A Great Tradition and its Burmese Vicissitudes, 2nd Expanded Ed. Berkeley: University of California Press. Suksamran, Somboon. 1977. Political Buddhism in Southeast Asia: The Role of the Sangha in the Modernization of Thailand. Ed. Trevor O. Ling. London: C. Hurst & Co. Suksamran, Somboon. 1993. Buddhism and Political Legitimacy, Chulalongkorn University Research Report Series 2. Bangkok: Chulalongkorn U Printing House. Swearer, Donald K. 1986. Introduction. Dhammic Socialism. By Bikkhu Buddhadasa. Trans. and ed. Donald K. Swearer. Bangkok: Thai Inter-Religious Commission for Development. Tambiah, S.J. 1970. Buddhism and the Spirit Cults in North-East Thailand. Cambridge, UK: Cambridge University Press. Tan-Kim-Yong, Uraivan. 1992. "A Participatory Land-Use Planning as a Sociological Methodology for Natural Resource Management." Resource Management and Development Program.

Taylor, J.L. 1991. "Living on the Rim: Ecology and the Forest Monks in Northeast Thailand." Sojourn: Social Issues in Southeast Asia, vol. 6, Num 1, February. Singapore: The Institute of Southeast Asian Studies, pp. 106-125. The Legal Status of Tibet : Three Studies by Leading Jurists. 1989. Dharamsala, India: Office of Information & International Relations. The Management of Community Forests by Local Organizations. 1992. Ford Foundation. Thoreau, Henry David 1993. Faith in a Seed : The Dispersion of Seeds and Other Late Natural History Writings, ed. by Bradley P. Dean. Washington, D.C.: Island Press/Shearwater Books. Thurman, Robert A. F., trans. 1976. The Holy Teaching of Vimalakirti: A Mahayana Scripture. University Park PA: Pennsylvania State University Press. Toda, Masanao and Higuchi, Kasue. 1994. “Emotion and Social Factors in Communication.” Proceedings : 3rd IEEE International Workshop on Robot and Human Communication : ROMAN'94 Nagoya : 18-20 July, 1994, Nagoya University, Nagoya, Japan. Piscataway, NJ: IEEE. Tulku, Sharpa and Turner, Alex. 1995. “Missing the Point of Buddhism: Old Confusions Resurface in a New Book.” Tibetan Review, vol XXX, No 6, June, pp. 12-15.

131 Tyler, Bert, et. al. 1990-1997. FRACTINT, Vers. 19.6. Computer Software. The Stone Soup Group. DOS. Vyas, C.S. 1991. Buddhist Theory of Perception with Special Reference to Pramana Varttika of Dharmakirti. New Delhi: Navrang. Walt van Praag, Michael C. van. 1987. The Status of Tibet: History, Rights and Prospects in International Law. Boulder: Westview Press. Watson, James D. 1968. The Double Helix: A Personal Account of the

Discovery of the Structure of DNA. New York: New American Library. Weiss, Mark Allen. 1998. Data Structures and Problem Solving Using Java. Reading, MA: AddisonWesley. Werner, Ozwald, and Schoepfle, G. Mark. 1987. Systematic Fieldwork, vols. 1 and 2. Newbury Park: Sage Publications.

132 APPENDIX C: SELECTED WEB LINKS ABOUT ARTIFICIAL LIFE AND COMPLEXITY

A Philosophy of Artificial Life Bibliography Artificial Life Games Homepage Artificial Life Links Artificial Life Online C.O.P.P. Software Flanders Chaos research books 97 Complexity Complexity, Complex Systems and Chaos Theory: @BRINT (tm) CoreLife Creative Optics, Inc. Cybertation index page Directory of /pub/SOFTWARE/biotopia Directory of /pub/robots



Echo Evolutionary Computation IRC Group Gecko Graph Class Library

133 Index for AI: A Modern Approach Index of Objective C information Industrial Technology Institute (ITI)/HOME PAGE Journal of Social And Evolutionary Systems Karl Sims -- Virtual Creatures Loki Madison Chaos and Complex Systems Seminar Marco's Maddening Artificial Life Page Paul Wiegand's Page Politics - Nonlinear Politics Preston Pfarner's Bookmarks Q1.4 - HHGT Evolutionary Computation The Artificial Self-Replication Page (Moshe Sipper) The Echo Project The Primordial Soup Kitchen The Swarm Simulation System Tierra home page Welcome to Zooland!

134 comp.robotics Frequently Asked Questions (FAQ) part 5/5 www.alife.org: ALIFE VI

135 APPENDIX D: A USER’S GUIDE TO SWARMSARA

Introduction Java’s slogan is “write once, run anywhere” but it practice it is more like “write once, debug everywhere.” Swarmsara works fairly reliable on Windows 9* and Windows NT running Netscape 3.5+ or Internet Explorer 5+. It is not known to run on Linux, UNIX or Macintosh computers. Use this program at your own risk. The program has at least one memory leak and tends to run slower after the first run. Reloading it usually clears this problem. As mentioned in the text, it began as a port to Java of the Swarm “canonical example” program Heatbugs for a class assignment. Since that time, other Swarm developers have created robust Java classes, but when this began they were not available. The Control Panel, Swarmsara window and pop-up probe window are all original code. The real time graphs use Leigh Brookshaw’s GNU-licensed graph class libraries in a fairly standard way. The user will want to try out various settings on the control panel to explore different aspects of the system. Note that the Swarmsara and graph windows are resizeable. The windows are set to open in a way convenient for those using 800x600 screen resolution but the user can arrange them as appropriate. Be sure to try clicking with the mouse over the Swarmsara window. Control Panel Like standard Swarm applications, Swarmsara comes with a control panel, where parameters for runs can be set. Runs cannot be modified after they have begun. See the Algorithms section for an explanation of what is going on

Figure 21: Control Panel

136 behind the scenes of the user interface. One of the most important aspects of the simulation, the accumulation of karma as a kind of experiential genetic template, has as of yet no visual representation. •

• •







• • •

Start Swarmsara: This button starts a run and opens the simulation without also opening the graphs. In some situations the graphs do not load well, so this is a useful option, but most users will prefer to utilize the Start Graphs button which starts everything at once. “Start Swarmsara” is greyed after a run begins and clicking on it during a run will have no effect. Stop Swarmsara: The button is greyed and unavailable before a run starts. During a run it can be used to stop a run altogether, as opposed to “Stop Graphs”, which stops the graphs but lets the run continue. Start Graphs: This is the recommended way to start a run because it starts everything. It may not work right the first time when invoked from the web, as a number of files have to be loaded into the browser cache. It may be used more than once during a run, if the graphs have been stopped. Stop Graphs: Using this button once it is activated after a run starts allows the user to end the display of the graphs. It is preferable to using the standard x button on the windows containing the graphs. It may be used whenever the graphs are displayed. It is greyed otherwise. Number of Bugs: This control sets the number of agents (a.k.a. bugs) in a run. Since each agent acquires karma, large numbers of agents will affect performance. It can be interesting to set the number to 1 to isolate other interactions. X Size/ Y Size: The number of cells visible in the toroidal world. This along with number of agents determines population density. Since each side wraps around, for example if an agent goes off the top it will reappear at the bottom, this could be used to study an another aspect of how karmic return might work, by observing the agents encounter a landscape created by them previously. Large X and Y sizes will slow the simulation down considerably. The user can try fast mode in those cases. Ignorance/Attraction/Aversion Threshold: This number is the amount of an emotion that must be built up before an agent starts developing the next emotion. Happiness Threshold: This number is the amount of produced karma, a.k.a. food the agent perceives to be in its current cell for it to deem itself happy. This perception is distorted by emotion. Use Karma: This toggle produces one of the most interesting results in the simulation. It switches whether the agents accumulate karma and find their perception limited by it subsequently. With it on, the agents go through many phases of interaction. Without it, not much happens. Further study is

137





• •



needed to determine the cause of this, but as mentioned in the paper, it seems to support Buddhist theory. Food Consumed: The amount of produced karma, a.k.a. food, removed from the current cell of an agent in each time step. At the moment, this is set to a single number. In future versions this could be a trait the agents would modify based on their attempts to learn from their experience. Karma Range: The range karmic actions possible, entailing adding a random number of units of produced karma into the landscape within that range, and adding that action into the agent’s storehouse of past karmic imprints with that value. Note that cells may easily acquire amounts of resources outside this range, in which case agents with emotions cannot see them, and they may be entered only by non-emotional agents or accidentally when driven by aversion. This trait might also be subject to alteration from learning in subsequent versions of the simulation. For instance, an agent might learn if it keeps a high range, thus feeding resources into the landscape, it would also find it more likely to enter valuable, happiness-inducing cells. Sleep Time: This setting slows down the time steps, making it easier to observe what happens to the agent from one moment to the next. Use Fast Mode: Due to the way the Java programming language is designed, it is very difficult to control the way the screen repaints itself. This mode uses a more optimized algorithm for processing the agents, their behaviors, and screen painting, but it causes the agents to leave trails, and for some reason messes up the timing, such that even when a random seed is set, runs are different. Use it when you want to experiment with large numbers of agents or large X/Y sizes. Random Seed: Entering a number in this box will set a seed for Java’s random number generator, causing runs to be identical if they have the same seed and all else being equal. This does not work in fast mode.

Swarmsara Window This window displays the running simulation as it evolves reflexively. Runs can be radically different from each other even with the same initial conditions except the random seed. It has not been determined whether this is due to true sensitivity to initial conditions, or is an artifact of the way the system uses random numbers. The window opens in the lower left at the beginning of a run, and at first it is black. In many cases by the time the window opens many timesteps have passed and more activity can be observed, but let us assume otherwise for now. The user will observe rectangles of different shades of grey appear. These shades indicate quantities of produced karma, a.k.a. food, being created. The cells often

138 disappear again because the agents are taking the resources back out of the cell. The agents are black at first, because they have not yet developed emotions. Soon the first signs of ignorance/laziness appear, as cells, actually cells occupied by agents, with increasingly strong shades of green. Observe that these cells move occasionally, but generally try to stay in one location. After a few minutes, some of these agents start to turn blue green, as their attraction (approach) starts to increase and Figure 22: Swamsara Window their laziness drops off. Finally, after a longer period of time, some cells turn white or purple, as their aversion builds up. Behaviors will be different with different initial settings. Clicking the mouse once over the window brings up the Cell Statistics Window. Doubleclicking over the window pauses the run of the simulation. Double-clicking again starts the run again.

139 Cell Statistics Window The Cell Statistics Window is invoked by clicking the mouse over the running Swarmsara window. It shows statistics about the cell or agent (a.k.a. bug) directly under the mouse cursor at the time the mouse is clicked. What is displayed will vary Figure 23: Cell Statistics Window depending on whether the cell is empty or not. The more complicated case of the occupied cell is illustrated here. Note that the image here is from Netscape, whereas the others are from Internet Explorer. The version of Internet Explorer used to create the other images failed to display the statistics screen correctly. Use caution with this product. • Timestep: The number of times the simulation has calculated positions for the agents. This is not necessarily the same as the number of times the screen has repainted the positions. • Avg world food: The average amount of produced karma per cell. • Avg bug food: The average amount of produced karma in cells occupied by agents. • Food: The amount of produced karma in the current cell. When a cell is unoccupied, this show as a shade of grey. When the cell is occupied, the color is determined by the emotional state of the agent. • …for Cell in X,Y: Gives the coordinate of the cell in terms of the dimensions of the Swarmsara world, not the physical location on the screen. • This Cell Contains Bug Number X: The identity of the agent. A future version of the simulation might contain a means of tracking the life history of a particular agent, but by slowing down the run from the control panel, and starting and stopping it with the mouse, it should be possible to track agents from step to step this way. • It has ignorance/attraction/aversion: Current levels of the emotions, as reflected in the agent’s color. • It is happy/unhappy: The agent’s subjective state based on its emotional distortions • It should be/shouldn’t be happy: How the agent should feel based on the objective amount of produced karma in its current cell.

140

Figure 24: Afflictive Emotions Window

Afflictive Emotions Window This, along with the other graph, pops up when the “Start Graphs” button is pressed at the beginning or during a run. The first time the applet is used it may not work correctly. It shows the average emotion levels of all the agents in the current run. Results will vary depending on initial conditions and will vary from run to run unless a random seed is set and fast mode is off. Attempts to extract patterns from these data using Fast Fourier Transforms have so far been unsuccessful. Both graph windows may be resized during runs.

141

Figure 25: Avg Food & Percent Happy Window

Avg Food & Percent Happy Window This window pops up when “Start Graphs” is pressed at the beginning or during a run. It uses a calculation to skip time steps in its display, to make the data more readable over longer runs. It shows that at least within the definitions of the Swarmsara system, the Buddha’s diagnosis and hypothesis framed in the First and Second Noble Truths seems to be correct: Consistently across runs, as agents develop emotional distortions, they become increasingly unhappy, as shown by the purple line above. This happens even as average resources in their world increase, as shown by the yellow line, and even though many of the agents are in objective conditions in which they should be happy, as shown by the cyan line. This result is not surprising, because when an agent is driven by dissatisfaction with their current situation they are by definition unhappy. This point perhaps by virtue of its very simplicity seems to escape most people, and bears emphasis.

142 APPENDIX E: JAVA CODE

Introduction The following code is offered as is. It compiles using Sun Forte and JDK1.3. Included here are some lines generated by the Forte IDE, but not Leigh Brookshaw’s Graph Class Library. That extremely useful tool can be found at Graph Class Library . Electronic copies of the files including compiled bytecode and the graph classes can be downloaded from the author’s website, at http://www.execpc.com/~alturner/java/Swarmsara.zip. Swarmsara can be run directly from the site, from http://www.execpc.com/~alturner/java/Swarmsara.html. GNU License GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave, Cambridge, MA 02139, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid

143 anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License

144 along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,

145

b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.

146 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free

147 Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

148

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.

149 Swarmsara.java /******************************************************************************* ** Copyright (C) 2000 Alex Turner ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *******************************************************************************/ //****************************************************************************** // Swarmsara: a translation of the canonical // Swarm HeatBugs sample program. // by Alex Turner // // ID 34552764551 // // // This applet is based on the Swarm // HeatBugs program. It is a 2D toroidal world // in which a population of agents // seek optimum conditions. This version // has no input controls other than resizing the // applet window and/or changing the variable and // constant values in the source and recompiling. // The program uses // polymorphism, inheritance, hashtables and threading. Some code // was absorbed from an applet which displays color // boxes, some is standard applet stuff, and // some was reworked from the Objective-C // of the Swarm system, but the majority of it is // original for this project. It // throws an error upon termination, but this doesn't // seem to affect functioning. The code has been tested // on Windows95, NT, Linux and the web. //****************************************************************************** //import java.awt.Graphics; //import java.awt.Color; import java.util.*;

150 import java.awt.*; //import java.io.*; public class Swarmsara extends java.applet.Applet implements Runnable { // most of these variables and constants can be tweaked to // get the bugs to do interesting things. //public final int XSIZE = 25, YSIZE =25; protected int XSIZE=25,YSIZE=25,NUM_OF_BUGS=35; private int ignoranceThreshold=255; private int desireThreshold=255; private int aversionThreshold=255; protected int timestep = 0; // to go with number of shades of red. public final int MAXSTATES = 256; protected int karmaRange = 60; private int PAINTSTEP = 30; // numbers for the diffusion formula //private float diffusionConstant = 1.0f, evaporationRate = 0.98f; //public final int NUM_OF_BUGS = 35; // the food the bug exudes. Must be between 0 and 255 //public final static int BUG_FOOD = 200; protected int HAPPINESS_THRESHOLD = 20; protected float avgIgnorance, avgDesire, avgAversion; protected float avgTotalFood; protected float avgBugFood; protected float pctHappy; protected float pctOverHapThreshold; // create the world for this time step protected SimCell[][] lattice; protected SimCell[][] newLattice; // to reduce searchtime //public SimCell[] bugList; protected SimCell[] bugList; // public SimCell[] oldBugList; protected SimCell[] foodList; // start a random object for all kinds of uses. private Random rnd; // = new Random(); private String rndSeed; // a thread for easing animation tasks private volatile Thread runner; // set to true to view graphs, but these don't work very well yet. private boolean useGraph = false;

151 //private boolean fromControlPanel = false; public boolean cellBorders = false; //used in paint() to force full refreshes private int stepCount = 0; protected boolean useKarma = true; protected int foodConsumed = 30; protected int sleepTime = 0; // for repaints when the frame size has changed significantly protected int oldWidth, oldHeight; protected boolean isStopped, useFastMode = false; private String message; public Swarmsara() { NUM_OF_BUGS = 35; XSIZE = 25; YSIZE = 25; } public Swarmsara (int num_of_bugs,int xsize,int ysize, int ignoranceThreshold, int desireThreshold, int aversionThreshold, int happinessThreshold, boolean useKarma, int foodConsumed, int karmaRange, int sleepTime, boolean useFastMode, String rndSeed) { //fromControlPanel = true; this.NUM_OF_BUGS = num_of_bugs; this.XSIZE = xsize; this.YSIZE = ysize; this.ignoranceThreshold = ignoranceThreshold; this.desireThreshold = desireThreshold; this.aversionThreshold = aversionThreshold; this.HAPPINESS_THRESHOLD = happinessThreshold; this.useKarma = useKarma; this.sleepTime = sleepTime; this.useFastMode = useFastMode; this.rndSeed = rndSeed; init(); //start(); , } public void init () { // initialize the lattice of cells. The program employs // polymorphism to manage an array of cells and bugs lattice = new SimCell[XSIZE][YSIZE]; bugList = new SimCell[NUM_OF_BUGS]; //oldBugList = new SimCell[NUM_OF_BUGS]; foodList = new SimCell[NUM_OF_BUGS]; isStopped = false; // start a random object for all kinds of uses.

152 if (rndSeed.equals("random")) rnd = new Random(); else rnd = new Random(Long.parseLong(rndSeed)); for (int x = 0; x < XSIZE; x++) for (int y = 0; y < YSIZE; y++) lattice[x][y] = new SimCell(x,y); // init oldCellSize for paint() oldWidth = getSize().width; oldHeight = getSize().height; PAINTSTEP = (XSIZE + YSIZE); //rnd.setSeed(50); // add some bugs taking care not to pile them // on top of each other boolean isOccupied = false; int count = NUM_OF_BUGS; while (count > 0) { do { int tryX = Math.abs(rnd.nextInt()) % XSIZE; int tryY = Math.abs(rnd.nextInt()) % YSIZE; if (!lattice[tryX][tryY].hasBug()) { // place the bugs in the lattice lattice[tryX][tryY] = new SimBug(tryX,tryY,count); // make an array of references to just the bugs bugList[count-1] = lattice[tryX][tryY]; isOccupied = false; } else isOccupied = true; } while (isOccupied); count--; } //newLattice = diffuse(newLattice); } // method init // for a threaded applet public void start() { if (runner == null) { runner = new Thread(this); runner.start(); isStopped = false; } } //method start public void stop() { runner = null; isStopped = true; } // method stop

153

// the "main" method of the applet public void run() { Thread thisThread = Thread.currentThread(); while (runner == thisThread) { try { thisThread.sleep(sleepTime); } catch (InterruptedException e){ } lattice = moveBugs(futureLattice(/*newLattice*/)); timestep++; if (timestep % 1000 == 500) System.gc(); repaint(); if (useGraph) happyGraph(); //Bug ego = new Bug(); // Bug ego2 = new Bug(); //System.out.println(ego.hashCode()); //try {Thread.sleep(100); } //catch (InterruptedException e) {} } } // method run // paint makes the color boxes that represent food and bugs. public void paint(Graphics g) { int rval, gval, bval; // for setting colors, red, green and blue int cellSizeX, cellSizeY; // finds a good cell size based on the size of the applet window, // which can be reset during the run by the user cellSizeX = getSize().width / (XSIZE + 2); cellSizeY = getSize().height / (YSIZE + 2); //cellSizeY = cellSizeY + 1; //g.drawString(message, 20, this.getHeight()-10); /* String message = "Cell Width: " + cellSizeX; g.drawString(message, 20, 20); String message2 = "Cell Height: " + cellSizeY; g.drawString(message2, 20, 30); String message3 = "Number of Bugs: " + NUM_OF_BUGS; g.drawString(message, 20, this.getHeight()-10); g.drawString(message3, 20, 40); */ // lattice[10][10].setFood(10); //String message4 = "Has Bug: " + lattice[10][10].hasBug(); //g.drawString(message4, 20, 50); // color in the grid, green for lazy bugs, blue for hungry, red for // scared, // gradations of white for food. // paint when resized while running if (timestep != 0) { //oldCellSizeX != cellSizeX || oldCellSizeY != cellSizeY

154 //|| timestep % PAINTSTEP == 1) if (!useFastMode || timestep % PAINTSTEP == 1 || oldWidth != getSize().width || oldHeight != getSize().height) for (int x = cellSizeX; x <= (XSIZE * cellSizeX); x += cellSizeX) for (int y = cellSizeY; y <= (YSIZE * cellSizeY); y += cellSizeY) if (lattice[x/cellSizeX-1][y/cellSizeY-1].hasBug()) { g.setColor(new Color( lattice[x/cellSizeX-1][y/cellSizeY-1].getAversion() < 255? lattice[x/cellSizeX-1][y/cellSizeY-1].getAversion(): 255, lattice[x/cellSizeX-1][y/cellSizeY-1].getIgnorance() < 255? lattice[x/cellSizeX-1][y/cellSizeY-1].getIgnorance(): 255, //0, lattice[x/cellSizeX-1][y/cellSizeY-1].getDesire() < 255? lattice[x/cellSizeX-1][y/cellSizeY-1].getDesire(): 255 // 0 )); if (cellBorders) g.fillRect(x+1, y+1, cellSizeX-1, cellSizeY-1); else g.fillRect(x, y, cellSizeX, cellSizeY); } else { rval = lattice[x/cellSizeX-1][y/cellSizeY-1].getFood(); gval = lattice[x/cellSizeX-1][y/cellSizeY-1].getFood(); bval = lattice[x/cellSizeX-1][y/cellSizeY-1].getFood(); g.setColor(new Color(rval,gval,bval)); if (cellBorders) g.fillRect(x+1, y+1, cellSizeX-1, cellSizeY-1); else g.fillRect(x, y, cellSizeX, cellSizeY); } else { //just the changed boxes -- hopefully for (int i = 0; i < bugList.length; i++) { g.setColor(new Color( bugList[i].getAversion() < 255? bugList[i].getAversion(): 255, bugList[i].getIgnorance() < 255? bugList[i].getIgnorance(): 255, //0, bugList[i].getDesire() < 255? bugList[i].getDesire(): 255 // 0 )); if (cellBorders) g.fillRect((bugList[i].getX() + 1) * cellSizeX + 1,

155 (bugList[i].getY() + 1) * cellSizeY + 1, cellSizeX-1, cellSizeY-1);

else g.fillRect((bugList[i].getX() + 1) * cellSizeX, (bugList[i].getY() + 1) * cellSizeY, cellSizeX, cellSizeY); if (!foodList[i].hasBug()) { g.setColor(new Color (foodList[i].getFood()>=0?foodList[i].getFood():0, foodList[i].getFood()>=0?foodList[i].getFood():0, foodList[i].getFood()>=0?foodList[i].getFood():0)); // g.setColor(new Color(foodList[i].getFood(), // foodList[i].getFood(), // foodList[i].getFood())); if (cellBorders) g.fillRect((foodList[i].getX() + 1) * cellSizeX + 1, (foodList[i].getY() + 1) * cellSizeY + 1, cellSizeX-1, cellSizeY-1); else g.fillRect((foodList[i].getX() + 1) * cellSizeX, (foodList[i].getY() + 1) * cellSizeY, cellSizeX, cellSizeY); } } /*for (int i = 0; i < foodList.length; i++) if (!foodList[i].hasBug()) { g.setColor(new Color (foodList[i].getFood()>=0?foodList[i].getFood():0, foodList[i].getFood()>=0?foodList[i].getFood():0, foodList[i].getFood()>=0?foodList[i].getFood():0)); // g.setColor(new Color(foodList[i].getFood(), // foodList[i].getFood(), // foodList[i].getFood())); if (cellBorders) g.fillRect((foodList[i].getX() + 1) * cellSizeX + 1, (foodList[i].getY() + 1) * cellSizeY + 1, cellSizeX-1, cellSizeY-1); else g.fillRect((foodList[i].getX() + 1) * cellSizeX, (foodList[i].getY() + 1) * cellSizeY, cellSizeX, cellSizeY); } */ } // end else */ // paint for init() } else

156 for (int x = cellSizeX; x <= (XSIZE * cellSizeX); x += cellSizeX) for (int y = cellSizeY; y <= (YSIZE * cellSizeY); y += cellSizeY) { g.setColor(new Color(0,0,0)); if (cellBorders) g.fillRect(x+1, y+1, cellSizeX-1, cellSizeY-1); else g.fillRect(x, y, cellSizeX, cellSizeY); } if (oldWidth != getSize().width || oldHeight != getSize().height) if (stepCount == 0) { stepCount = 3; oldWidth = getSize().width; oldHeight = getSize().height; } else stepCount--; } // method paint // this is overridden to reduce screen flicker public void update (Graphics g) { paint(g); } //********************************************************************* // the diffuse method is based on the Swarm diffuse2d Class. // The formula they give is: // "basic CA diffusion. // newFood = evap (self + k * (nbdavg - self)) // where self is our own food // nbdavg is the appropriately weighted average of our neighbour's food // k is the diffusion constant // evap is the evaporation rate." // It adds food to the next timestep based on the current one. //*********************************************************************** public synchronized SimCell[][] futureLattice (/*SimCell[][] newLattice*/) { // newLattice = new SimCell[XSIZE][YSIZE]; //if (1+1==2 || timestep == 0) { //int xminus1, xplus1, yminus1, yplus1; //boolean firstOrder = false; //SimCell[][] newLattice = new SimCell[XSIZE][YSIZE]; int xminus1, xplus1, yminus1, yplus1; // calculate the avg food in world here float totalFood = 0.0F; if (!useFastMode || timestep == 0 || timestep % PAINTSTEP == 1 || oldWidth != getSize().width || oldHeight != getSize().height) { newLattice = new SimCell[XSIZE][YSIZE]; for (int x = 0; x < XSIZE; x++) for (int y = 0; y < YSIZE; y++) { // make a lattice for the future timestep newLattice[x][y] = new SimCell(x,y);

157 newLattice[x][y].setFood(lattice[x][y].getFood()); totalFood += newLattice[x][y].getFood(); } if (XSIZE*YSIZE != 0) avgTotalFood = totalFood/(XSIZE*YSIZE); } else // do just the bugs and their neighborhoods //newLattice = lattice; for (int count = 0; count < bugList.length;count++) { int bugX = bugList[count].getX(); int bugY = bugList[count].getY(); //int foodX = foodList[count].getX(); //int foodY = foodList[count].getY(); newLattice[bugX][bugY] = new SimCell(bugX,bugY); newLattice[bugX][bugY].setFood(lattice[bugX][bugY].getFood()); //newLattice[foodX][foodY] = new SimCell(foodX,foodY); //newLattice[foodX][foodY].setFood(lattice[foodX][foodY].getFood()); } /* xminus1 = (x + XSIZE - 1) % XSIZE; xplus1 = (x + 1) % XSIZE; yminus1 = (y + YSIZE - 1) % YSIZE; yplus1 = (y + 1) % YSIZE; SimCell[] neighborhood = { lattice[x] [y] , // Center lattice[xminus1][yminus1], // NW lattice[x] [yminus1], // N lattice[xplus1] [yminus1], // NE lattice[xplus1] [y] , // E lattice[xplus1] [yplus1] , // SE lattice[x] [yplus1] , // S lattice[xminus1][yplus1] , // SW lattice[xminus1][y] // W }; for (int i = 0; i < neighborhood.length; ++i) { int hoodX = neighborhood[i].getX(); int hoodY = neighborhood[i].getY(); newLattice[hoodX][hoodY] = new SimCell(hoodX,hoodY); newLattice[hoodX][hoodY].setFood(lattice[hoodX][hoodY].getFood()); } // for } // for */ // else return newLattice; } // method diffuse //************************************************************** // moveBugs updates bug locations. The bugs pick // a new spot that is closest to their optimum temperature // that is not already occupied in the next timestep and // move there, adding their food to diffused food in the cell. //************************************************************** public synchronized SimCell[][] moveBugs(SimCell[][] diffusionProduct) { SimCell[][] newLattice = diffusionProduct; int xminus1, xplus1, yminus1, yplus1;

158 int bestCell, preferredFood, currentFood, newFood, newKarma; int ignorance, desire, aversion; int bugNumber; //for keeping track of individual bugs float happiness = 0.0F; float numOverHapThreshold = 0.0F; int newCellNum; int newX, newY; Hashtable template; Integer imprint; SimCell newCell; boolean isOccupied; int x,y; float totalBugFood = 0.0F; float totalIgnorance = 0.0F; float totalDesire = 0.0F; float totalAversion = 0.0F; //foodList = new SimCell[NUM_OF_BUGS]; for (int count = 0; count < bugList.length;count++) { //for (int x = 0; x < XSIZE; x++) // for (int y = 0; y < YSIZE; y++) { // if (lattice[x][y].hasBug()) { // big if statement to test only bugs not plain cells //System.out.println("Desire: " + lattice[x][y].getDesire()); x = bugList[count].getX(); y = bugList[count].getY(); //foodList[count] = newLattice[x][y]; currentFood = bugList[count].getFood(); totalBugFood += currentFood; //oldBugList[count] = new SimCell(x,y); //oldBugList[count].setFood(bugList[count].getFood()); bugNumber = bugList[count].getBugNumber(); //bugNumber = lattice[x][y].getBugNumber(); //System.out.println("Bug number " + bugNumber); // make it aware of toroidal neighborhood ignorance = bugList[count].getIgnorance(); desire = bugList[count].getDesire(); aversion = bugList[count].getAversion(); if (currentFood > HAPPINESS_THRESHOLD) //happiness++; numOverHapThreshold++; // add to the count of bugs that think they are happy if ((ignorance + currentFood >= desire) && (ignorance + currentFood >= aversion)) happiness++; //newKarma is added at random. Sharpa Rinpoche says a //microbe would create karma at random. Can be anywhere in range //from -256 to 256 or whatever MAXSTATES is.

159 //newKarma = (Math.abs(rnd.nextInt()) % (KARMARANGE * 2)) - KARMARANGE; newKarma = (Math.abs(rnd.nextInt()) % (karmaRange * 2)) - (karmaRange + 1); // pass in the bug's hashtable template = bugList[count].getTemplate(); // The buddhist Pali canon says that agents with no afflictions do not // produce karma. This condition also allows the user to toggle // karma off if (useKarma && (ignorance > 0 || desire > 0 || aversion > 0)) { imprint = new Integer(newKarma); template.put(imprint, imprint); } //System.out.println("New Karma: " + newKarma); //System.out.println(template.get(new Integer(newKarma))); //template.remove(event); // hmm problem here? if (useKarma) { if (template.get(new Integer(currentFood)) != null) { //System.out.println("got some!!!!!!!!!!!!!!!!! " // + template.get(new Integer(lattice[x][y].getFood()))); template.remove(new Integer(currentFood)); bugList[count].setFood(currentFood - foodConsumed); } } else bugList[count].setFood(currentFood - foodConsumed); currentFood = bugList[count].getFood(); newFood = currentFood + newKarma; if (newFood < 0) newFood = 0; if (newFood >= (MAXSTATES - 1)) newFood = MAXSTATES - 1; // stay in range // make it aware of toroidal neighborhood xminus1 = (x + XSIZE - 1) % XSIZE; xplus1 = (x + 1) % XSIZE; yminus1 = (y + YSIZE - 1) % YSIZE; yplus1 = (y + 1) % YSIZE; // set up an array of the eight cell neighborhood // very important that these be in this order so // opposite direction can be determined by // Math.abs(i-4) SimCell[] neighbors = { lattice[xminus1][yminus1], // NW lattice[x] [yminus1], // N lattice[xplus1] [yminus1], // NE lattice[xplus1] [y] , // E lattice[xplus1] [yplus1] , // SE lattice[x] [yplus1] , // S

160 lattice[xminus1][yplus1] , // SW lattice[xminus1][y] // W }; // set a sentinel value bestCell = -10000; // calculate new emotion levels if (currentFood > HAPPINESS_THRESHOLD) { ignorance++; // if (currentFood > 50 && desire > 0) //desire--; } else if (ignorance > 0) { //and current foood < 10 ignorance--; if (ignorance > ignoranceThreshold) { desire++; ignorance--; } if (currentFood <= 50 && desire > desireThreshold) { aversion++; desire--; } if (currentFood <= 0 && aversion > aversionThreshold) { ignorance++; aversion--; } } totalIgnorance += ignorance; totalDesire += desire; totalAversion += aversion; //System.out.println("Current food: " + currentFood); // test if a bug is planning on moving in to the current spot if (!newLattice[x][y].hasBug() && ignorance > 0 // may not need this //&& (template.get(new Integer(lattice[x][y].getFood()))!= null) ){ // start with self so you can test for other bugs nearby without // also finding self bestCell = currentFood + ignorance; } // test the neighbors if there is desire if (desire > 0) for (int i = 0; i < neighbors.length; ++i) // don't want to squish friends if (useKarma) { if (!newLattice[neighbors[i].getX()][neighbors[i].getY()].hasBug() // test for karma && (template.get(new Integer(lattice [neighbors[i].getX()] [neighbors[i].getY()].getFood())) != null) ) if ((neighbors[i].getFood() + desire) > bestCell)

161 bestCell = neighbors[i].getFood() + desire; } else if (!newLattice[neighbors[i].getX()][neighbors[i].getY()].hasBug() // test for karma //&& (template.get(new Integer(lattice //[neighbors[i].getX()] //[neighbors[i].getY()].getFood())) != null) ) if ((neighbors[i].getFood() + desire) > bestCell) bestCell = neighbors[i].getFood() + desire; // test the neighbors if there is aversion // note this needs work, aversion is still like desire if (aversion > 0) for (int i = 0; i < neighbors.length; ++i) // don't want to squish friends // test for bugs in cells *opposite* the cell to be judged if (useKarma) { if (!newLattice[neighbors[Math.abs(i-4)].getX()] [neighbors[Math.abs(i-4)].getY()].hasBug() // test for karma in cell to be judged && (template.get(new Integer(lattice [neighbors[i].getX()] [neighbors[i].getY()].getFood())) != null) ) if (Math.abs(neighbors[i].getFood() - aversion) > bestCell) bestCell = Math.abs(neighbors[i].getFood() - aversion); } else if (!newLattice[neighbors[Math.abs(i-4)].getX()] [neighbors[Math.abs(i-4)].getY()].hasBug() // test for karma in cell to be judged //&& (template.get(new Integer(lattice //[neighbors[i].getX()] //[neighbors[i].getY()].getFood())) != null) ) if (Math.abs(neighbors[i].getFood() - aversion) > bestCell) bestCell = Math.abs(neighbors[i].getFood() - aversion); // stay in current cell if there isn't something better out there //System.out.println("\nbest food: " + bestCell); //System.out.println("ignorance: " + ignorance); //System.out.println("desire: " + desire); //System.out.println("food plus ignorance: "+(currentFood + ignorance)); // ignorance breaks a tie if (!newLattice[x][y].hasBug() && ignorance > 0 && (currentFood + ignorance == bestCell) //&& (template.get(new Integer(lattice[x][y].getFood()))!= null) ){ bugList[count].setProperties(x,y,ignorance,desire,aversion,newFood); newLattice[x][y] = bugList[count];

162 //newLattice[x][y] = new SimBug //(x,y,bugNumber,ignorance,desire,aversion,template); //newLattice[x][y].setFood(newFood); //bugList[count] = newLattice[x][y]; // foodList[count] = newLattice[x][y]; } else { // now make a vector of neighbor cells that have equal food // to prevent bias // this needs work too re aversion Vector candidates = new Vector(); // if (desire > 0 || aversion > 0) for (int i = 0; i < neighbors.length; ++i) { if (useKarma) { if (!newLattice[neighbors[i].getX()][neighbors[i].getY()].hasBug() && desire > 0 && neighbors[i].getFood() + desire == bestCell // this is the test for whether the bug has karma // to move into that cell && (template.get(new Integer(lattice [neighbors[i].getX()] [neighbors[i].getY()].getFood())) != null)) candidates.addElement(neighbors[i]); } else if (!newLattice[neighbors[i].getX()][neighbors[i].getY()].hasBug() && desire > 0 && neighbors[i].getFood() + desire == bestCell // this is the test for whether the bug has karma // to move into that cell //&& (template.get(new Integer(lattice // [neighbors[i].getX()] // [neighbors[i].getY()].getFood())) != null)) ) candidates.addElement(neighbors[i]); // for the aversion test -- adds a bugless neighbor opposite the // the one causing the reaction if (useKarma) { if (!newLattice[neighbors[Math.abs(i-4)].getX()] [neighbors[Math.abs(i-4)].getY()].hasBug() && aversion > 0 && Math.abs(neighbors[i].getFood() - aversion) == bestCell && (template.get(new Integer(lattice [neighbors[i].getX()] [neighbors[i].getY()].getFood())) != null)) candidates.addElement(neighbors[Math.abs(i-4)]); } else if (!newLattice[neighbors[Math.abs(i-4)].getX()] [neighbors[Math.abs(i-4)].getY()].hasBug() && aversion > 0 && Math.abs(neighbors[i].getFood() - aversion) == bestCell // && (template.get(new Integer(lattice // [neighbors[i].getX()]

163 // [neighbors[i].getY()].getFood())) != null) ) candidates.addElement(neighbors[Math.abs(i-4)]);

} //System.out.println(candidates.size()); // initialize newCellNum = -1; // newCell = lattice[x+1][y+1]; // now pick a random cell number from the list of candidates if (candidates.size() > 0) { newCellNum = Math.abs(rnd.nextInt()) % candidates.size(); newCell = (SimCell)candidates.elementAt(newCellNum); } else { //stay in cell if all else fails...including the test following newCell = lattice[x][y]; isOccupied = true; while (isOccupied) { newCellNum = Math.abs(rnd.nextInt()) % neighbors.length; if (!newLattice [neighbors[newCellNum].getX()] [neighbors[newCellNum].getY()].hasBug()){ isOccupied = false; newCell = lattice [neighbors[newCellNum].getX()] [neighbors[newCellNum].getY()]; } } //newCell = lattice //[neighbors[newCellNum].getX()] //[neighbors[newCellNum].getY()]; // try stay in cell if all else fails // but how is this justified? I thought there was // already a test...an or test... /* newCell = lattice[x][y]; if (newLattice[x][y].hasBug()) { //try moving into a neighbor cell at random int i = 0; isOccupied = true; while (isOccupied && i < neighbors.length) { i++; newCellNum = Math.abs(rnd.nextInt()) % (neighbors.length); if (!newLattice [neighbors[newCellNum].getX()] [neighbors[newCellNum].getY()].hasBug()) { isOccupied = false; newCell = lattice [neighbors[newCellNum].getX()] [neighbors[newCellNum].getY()];

164 } } // if the whole neighborhood is full // then choose a spot at random as in init() int tryX=-1,tryY=-1; while (isOccupied){ tryX = Math.abs(rnd.nextInt()) % XSIZE; tryY = Math.abs(rnd.nextInt()) % YSIZE; if (!newLattice[tryX][tryY].hasBug()) { newCell = lattice[tryX][tryY]; isOccupied = false; } // if } // while } */ // if } // else // use cell methods to locate the newLattice cell in question newX = newCell.getX(); newY = newCell.getY(); bugList[count].setProperties(newX,newY,ignorance, desire,aversion,newFood); //newLattice[newX][newY] = new SimBug //(newX,newY,bugNumber,ignorance,desire,aversion,template); //if (!isOccupied) //if isOccupied got triggered, don't subtract for random move //newLattice[newX][newY].setFood(lattice[newX][newY].getFood()); //bugList[count] = newLattice[newX][newY]; //else //newLattice[newX][newY].setFood(lattice[newX][newY].getFood()); // change the old cell back into a Cell with no bug in it. //newFood = newLattice[x][y].getFood(); if (!newLattice[x][y].hasBug()) { //newLattice[x][y] = new SimCell(x,y); //move the to-be-occupied cell object to the //to-be-emptied spot newLattice[x][y] = lattice[newX][newY]; newLattice[x][y].setFood(newFood); newLattice[x][y].setX(x); newLattice[x][y].setY(y); } newLattice[newX][newY] = bugList[count]; // foodList[count] = newLattice[x][y]; } // else foodList[count] = newLattice[x][y]; //System.out.println(); } // for loop avgBugFood = totalBugFood/NUM_OF_BUGS; avgIgnorance = totalIgnorance/NUM_OF_BUGS; avgDesire = totalDesire/NUM_OF_BUGS; avgAversion = totalAversion/NUM_OF_BUGS; pctHappy = 100*happiness/NUM_OF_BUGS;

165 pctOverHapThreshold = 100*numOverHapThreshold/NUM_OF_BUGS; return newLattice; } // method moveBugs //************************************* // happyGraph only half works. // The idea is to show percentage // of bugs that are succeeding in // finding a cell in their optimal // range, as well as showing average // cell temperature where bugs are. // no time left to improve it. //************************************** public void happyGraph() { //new Console(); int count = 0; int findFood = 0; int avgFood; float happiness; for (int x = 0; x < XSIZE; x++) for (int y = 0; y < YSIZE; y++) if (lattice[x][y].hasBug()) { if (lattice[x][y].isHappy()) count++; findFood += lattice[x][y].getFood(); } happiness = (int)(100 * (float)count/NUM_OF_BUGS); avgFood = findFood/NUM_OF_BUGS; System.out.print("Happiness : "); for (int i = 0; i < happiness; ++i) System.out.print("*"); System.out.println(); System.out.print("Average Food: "); for (int i = 0; i < avgFood/3; ++i) System.out.print("*"); System.out.println(); } } // applet Swarmsara

166 SimCell.java //********************************************* // The SimCell class manages food and // location information as well as // serving as the parent for the SimBug class. //********************************************* import java.util.*; public class SimCell { protected int food; protected int x,y; // essential that cells remember their location so // they can report back after being subject to aliasing etc. protected int ignorance, desire, aversion, bugNumber; //used by Bugs only protected Hashtable template; //used by Bugs only public SimCell(int food) { this.food = food; } // constructor SimCell public SimCell(int x,int y) { this.x = x; this.y = y; } // the important constructor public SimCell() { food = 0; } // initialization constructor // getFood is the most called method in the program public int getFood() {return food;} public void setFood(int food) {this.food = food;} public boolean hasBug() {return false;} // overridden as true in Bug class public int getX() {return x;} // indispensible for tracking cells public int getY() {return y;} // especially after aliasing public void setX(int x) {this.x = x;} // I don't think we want to mess with public void setY(int y) {this.y = y;} // this kind of moving, better to transfer // food to new cell. But it is here for now. public boolean isHappy() {return false;} // to override public int getIgnorance() {return ignorance;} //used by Bugs only but here to public int getDesire() {return desire;} // satify polymorphism public int getAversion() {return aversion;} public Hashtable getTemplate() {return template;} public int getBugNumber() {return bugNumber;} public void setProperties(int x, int y, int i, int d, int a, int f) { } } // class SimCell

167 SimBug.java /************************************************************************** ** Copyright (C) 2000 Alex Turner ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. **************************************************************************/ //********************************************* // a cell with a bug in it. Beyond code reuse, // here inheritance is necessary // in order to have an array of bugs and cells //********************************************* import java.util.*; public class SimBug extends SimCell { private boolean happiness; private int highHappyTemp, lowHappyTemp; private static int i = 1; int foodKarma; private Imprint event; //SemJen ego = new SemJen(new Imprint(1,1,i++)); // not used // public SimBug () { // super (); // food += Swarmsara.BUG_FOOD; // } // constructor Bug // initialization constructor here public SimBug (int x, int y, int bugNumber) { super (x,y); this.bugNumber = bugNumber; template = new Hashtable(); // make the hashtable only once per bug } // constructor Bug

168

//new constructor public SimBug (int x, int y, int i, int d, int a, int f) { super (x,y); ignorance = i; desire = d; aversion = a; foodKarma = f; } // constructor Bug //hashtable constructor public SimBug (int x, int y, int b, int i, int d, int a, Hashtable t) { super (x,y); this.bugNumber = b; ignorance = i; desire = d; aversion = a; template = t; // pass in the hashtable modified in moveBug() } // constructor Bug // not used //public Bug (int x, int y, int food) { //super (x,y); //this.food = food + Swarmsara.BUG_FOOD; //} // constructor Bug // not used yet if ever public SimBug (int food, int BUG_FOOD, int highHappyTemp, int lowHappyTemp){ super(food); this.highHappyTemp = highHappyTemp; this.lowHappyTemp = lowHappyTemp; } // constructor Bug // not used yet /* public void setHighHappyTemp(int temp) {highHappyTemp = temp;} // need input masks public void setLowHappyTemp(int temp) {lowHappyTemp = temp;} // to prevent numbers public int getHighHappyTemp() {return highHappyTemp;} // less than 0 or more than 255 public int getLowHappyTemp() {return lowHappyTemp;} // and lows higher than highs */ public void setProperties(int x, int y, int i, int d, int a, int f) { this.x = x; this.y = y; this.ignorance = i; this.desire = d; this.aversion = a;

169 this.food = f; }

// very important accessor, tells whether or not the cell // has a bug in it public boolean hasBug() {return true;} public int getBugNumber() {return bugNumber;} public Hashtable getTemplate() {return template;} // public int addFood() {return food + BUG_FOOD;} // used in happyGraph public boolean isHappy() { //if (food >= Swarmsara.PREFERRED_MIN && food <= //Swarmsara.PREFERRED_MAX) return true; //else //return false; } // method isHappy() } // class Bug

170 Imprint.java /****************************************************************************** ** Copyright (C) 2000 Alex Turner ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *******************************************************************************/ /******************************************************************************* Main Class: SwarmsaraControl.java Author: Alex Turner, [email protected] Date: 4/26/00 Compiler: Forte (JDK 1.3) Platform: Windows95 *******************************************************************************/ /** * Represents a karmic imprint, to be inserted into a bug's karma hashtable * * Bugs: currently only uses the Imprint(int karma) constructor **/ public class Imprint { // only karma is used, its range depends on karmaRange in Swarmsara class // the other variables are still there for possible future use private int desire, anger, ignorance, karma; /** * Constructs an Imprint with the current emotion levels of the bug * (This constructor is not currently in use) * @param desire represents attraction, can be any integer >= 0 * @param anger represents aversion, can be any integer >= 0 * @param ignorance represents laziness, can be any integer >= 0 **/ public Imprint (int desire, int anger, int ignorance) { super(); this.desire = desire; this.anger = anger;

171 this.ignorance = ignorance; } // constructor /** * Constructs a default Imprint * (This constructor is not currently in use) **/ public Imprint () { super(); desire = 0; anger = 0; ignorance = 0; } // constructor /** * Constructs an Imprint from a karmic action of the bug * @param karma is generated in Swarmsara class, based on karmaRange **/ public Imprint (int karma) { super(); this.karma = karma; } // constructor // accessors public int getDesire(){return desire;} public int getAnger(){return anger;} public int getIgnorance(){return ignorance;} public int getKarma() {return karma;} // mutators public void setDesire(int desire) {this.desire = desire;} public void setAnger(int anger) { this.anger = anger;} public void setIgnorance(int ignorance) { this.ignorance = ignorance;} /* private short validate(short emotion) { if (emotion < -10 || emotion > 10) //System.out.println ("complain"); return emotion; // fix this else return emotion; } */ /** * Typical toString override, used for debugging * @return the karma variable as a string **/ public String toString() { //return desire + ", " + anger + ", " + ignorance; return "" + karma;

172 } } // class Imprint

173 SwarmsaraPop.java /* * SwarmsaraPop.java * * Created on April 6, 2000, 11:16 AM */ /************************************************************************** ** Copyright (C) 2000 Alex Turner ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. **************************************************************************/ /** * * @author turnea * @version */ import java.awt.*; import java.awt.event.MouseListener; import java.awt.event.MouseEvent; public class SwarmsaraPop extends java.awt.Frame implements MouseListener { //private int num_of_bugs,xsize,ysize; Swarmsara swarmsara; // = new Swarmsara(num_of_bugs,xsize,ysize); InfoFrame infoWindow = new InfoFrame(); int xsize, ysize; final static String newline = "\n"; /** Creates new form SwarmsaraPop */ public SwarmsaraPop(int num_of_bugs,int xsize,int ysize, int ignoranceThreshold, int desireThreshold, int aversionThreshold, int happinessThreshold, boolean useKarma, int foodConsumed, int karmaRange, int sleepTime, boolean useFastMode, String rndSeed) { initComponents ();

174 this.xsize = xsize; this.ysize = ysize; swarmsara = new Swarmsara(num_of_bugs,xsize,ysize, ignoranceThreshold, desireThreshold, aversionThreshold, happinessThreshold,useKarma,foodConsumed,karmaRange,sleepTime, useFastMode,rndSeed); swarmsara.addMouseListener(this); //swarmsara.setSize(this.getSize().width,this.getSize().height); //infoWindow = new InfoFrame(); infoWindow.setLocation(275,350); infoWindow.setSize(325,225); infoWindow.setTitle("Cell Statistics"); add(swarmsara,BorderLayout.CENTER); //pack (); swarmsara.setVisible(true); //swarmsara.start(); } public void paint(Graphics g) { //g.drawLine(0, 0, getSize().width, getSize().height); //swarmsara.repaint(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the FormEditor. */ private void initComponents () {//GEN-BEGIN:initComponents addContainerListener (new java.awt.event.ContainerAdapter () { public void componentAdded (java.awt.event.ContainerEvent evt) { formComponentAdded (evt); } } ); addWindowListener (new java.awt.event.WindowAdapter () { public void windowClosing (java.awt.event.WindowEvent evt) { exitForm (evt); } } ); }//GEN-END:initComponents private void formComponentAdded (java.awt.event.ContainerEvent evt) {//GENFIRST:event_formComponentAdded // Add your handling code here: }//GEN-LAST:event_formComponentAdded public void mousePressed(MouseEvent e) {

175 //saySomething("Mouse pressed (# of clicks: " // + e.getClickCount() + ")", e); } public void mouseReleased(MouseEvent e) { //saySomething("Mouse released (# of clicks: " // + e.getClickCount() + ")", e); } public void mouseEntered(MouseEvent e) { //saySomething("Mouse entered", e); } public void mouseExited(MouseEvent e) { //saySomething("Mouse exited", e); } public void mouseClicked(MouseEvent e) { int cellSizeX = swarmsara.getSize().width / (xsize + 2); int cellSizeY = swarmsara.getSize().height / (ysize + 2); SimCell statCell = swarmsara.lattice [(e.getX()/cellSizeX)-1] [(e.getY()/cellSizeY)-1]; infoWindow.toFront(); if (e.getClickCount() == 2 && !swarmsara.isStopped) swarmsara.stop(); else if (e.getClickCount() == 2) swarmsara.start(); saySomething(newline + "Mouse clicked (# of clicks: " + e.getClickCount() + ")", e); //infoWindow.textArea.append("SimSizeX: " + swarmsara.getSize().width); //infoWindow.textArea.append(" SimSizeY: " + swarmsara.getSize().height + newline); //infoWindow.textArea.append("Columns: " + xsize); //infoWindow.textArea.append(" Rows: " + ysize + newline); //infoWindow.textArea.append("X click position: " + e.getX()); //infoWindow.textArea.append(" Y click position: " + e.getY() + newline); infoWindow.textArea.append("Timestep: " + swarmsara.timestep + newline); //infoWindow.textArea.append("X cellSize: " + cellSizeX + newline); //infoWindow.textArea.append("Y cellSize: " + cellSizeY + newline); infoWindow.textArea.append("Avg world food: " + swarmsara.avgTotalFood); infoWindow.textArea.append(" Avg bug food: " + swarmsara.avgBugFood + newline); if ( e.getX() < cellSizeX || e.getY() < cellSizeY || e.getX() > cellSizeX + (cellSizeX * xsize) || e.getY() > cellSizeY + (cellSizeY * ysize) ) infoWindow.textArea.append("Outside world boundary " + newline);

176 else { infoWindow.textArea.append("Food: " + statCell.getFood() + " for cell in " + ((e.getX()/cellSizeX)-1) + ", " + ((e.getY()/cellSizeY)-1) + newline); if (statCell.hasBug()) { infoWindow.textArea.append("This cell contains bug number " + statCell.getBugNumber() + newline); infoWindow.textArea.append("It has ignorance: " + statCell.getIgnorance() + newline); infoWindow.textArea.append("It has attraction: " + statCell.getDesire() + newline); infoWindow.textArea.append("It has aversion: " + statCell.getAversion() + newline); if ((statCell.getIgnorance() + statCell.getFood() >= statCell.getDesire()) && (statCell.getIgnorance() + statCell.getFood() >= statCell.getAversion())) infoWindow.textArea.append("It is happy" + newline); else infoWindow.textArea.append("It's not happy" + newline); if (statCell.getFood() > swarmsara.HAPPINESS_THRESHOLD) infoWindow.textArea.append("It should be happy" + newline); else infoWindow.textArea.append("It shouldn't be happy" + newline); } else infoWindow.textArea.append("This cell is free of bugs for now" + newline); } // infoWindow.textArea.append("Free Memory: " + Runtime.getRuntime().freeMemory() + newline); // infoWindow.textArea.append("Food: " // + swarmsara.lattice[2][2].getFood() //+ newline); } void saySomething(String eventDescription, MouseEvent e) { infoWindow.textArea.append(eventDescription + " detected on " + e.getComponent().getClass().getName() + "." + newline); // String message = "test"; //window.setMessage(message); if (!infoWindow.isShowing()) infoWindow.setVisible(true); } /** Exit the Application */ private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm setVisible(false);

177 infoWindow.setVisible(false); }//GEN-LAST:event_exitForm /** * @param args the command line arguments */ // public static void main (String args[]) { // new SwarmsaraPop ().show (); // } // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables } // frame SwarmsaraPop class InfoFrame extends java.awt.Frame { public TextArea textArea = new TextArea(); //String message; public InfoFrame() { initComponents (); //textArea = new TextArea(); textArea.setEditable(false); add(textArea); pack(); } public String SetMessage(String message){return message;} private void initComponents () { addWindowListener (new java.awt.event.WindowAdapter () { public void windowClosing (java.awt.event.WindowEvent evt) { exitForm (evt); } } ); } private void exitForm(java.awt.event.WindowEvent evt) { setVisible(false); } }

178 SwarmsaraControl.java /* * SwarmsaraControl.java * * Created on April 6, 2000, 11:41 AM */ /******************************************************************************* ** Copyright (C) 2000 Alex Turner ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *******************************************************************************/ /******************************************************************************* Program: Swarmsara Author: Alex Turner, [email protected] Date: 4/26/00 Compiler: Forte (JDK 1.3) Platform: Windows95 *******************************************************************************/ /** * * @author turnea * @version */ import java.awt.*; /** * Creates the control panel which lets the user set * parameters and start and stop the runs * * Bugs: Runs tend to get slower so something is wrong in with garbage collection * Random seed does not work in fast mode **/

179 public class SwarmsaraControl extends java.applet.Applet { SwarmsaraPop window; //an instance of Samsara frame that holds the sim GraphPop graphPop; //an instance of the frame that holds the food graph EmoGraphPop emoGraphPop; //an instance of the frame that holds the emotion graph //for controlling the start/stop buttons and sim private boolean simIsRunning = false; //for controlling the start/stop buttons and graphs private boolean graphIsRunning = false; // variables adjustable by user to pass on to the sim: // how many agents in the world, // and the number of cells (not pixels) to represent private int num_of_bugs,xsize,ysize; // the levels the emotions must reach before they trigger the next emotion private int ignoranceThreshold, desireThreshold, aversionThreshold; // how much food a bug must be on top of to consider itself happy // this also triggers ignorance (laziness) private int happinessThreshold; // turns off the imprinting and blocked perception caused by karma private boolean useKarma; // switches to a 1D process in which only the bugs and their // most recent locations are updated. It gets sloppy due to Java's // non-deterministic repaints but can handle much bigger worlds. private boolean useFastMode; // how much food does a bug eat per timestep private int foodConsumed; // what is the variation in the amount of food put in a cell by a bug, // this also affects what gets passed to the karma template in Swarmsara private int karmaRange; // this allows the user to slow down the sim private int sleepTime; // lets the user set a random seed // at this writing it allows duplicate runs in normal mode // but not in fast mode private String rndSeed; /** Initializes the applet SwarmsaraControl */ public void init () { // used by Forte initComponents ();

180

}

// get the default values from the controls, parse where appropriate ysize = Integer.parseInt(txtYSize.getText()); xsize = Integer.parseInt(txtXSize.getText()); num_of_bugs = Integer.parseInt(txtNumOfBugs.getText()); aversionThreshold = Integer.parseInt( txtAversionThreshold.getText()); desireThreshold = Integer.parseInt(txtDesireThreshold.getText()); ignoranceThreshold = Integer.parseInt(txtIgnoranceThreshold.getText()); happinessThreshold = Integer.parseInt(txtHappinessThreshold.getText()); useKarma = cbxUseKarma.getState(); foodConsumed = Integer.parseInt(txtFoodConsumed.getText()); karmaRange = Integer.parseInt(txtKarmaRange.getText()); sleepTime = Integer.parseInt(txtSleepTime.getText()); useFastMode = cbxUseFastMode.getState(); // don't parse this one to leave random default intact rndSeed = txtRndSeed.getText();

/** * separates the controls, generated by Forte **/ public Insets getInsets() { return new Insets(5, 5, 5, 5); } /** This method is called from within the init() method to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the FormEditor. */ private void initComponents () {//GEN-BEGIN:initComponents btnStartSwarmsara = new java.awt.Button (); btnStopSwarmsara = new java.awt.Button (); btnStartGraph = new java.awt.Button (); btnStopGraph = new java.awt.Button (); lblNumOfBugs = new java.awt.Label (); txtNumOfBugs = new java.awt.TextField (); lblXSize = new java.awt.Label (); txtXSize = new java.awt.TextField (); lblYSize = new java.awt.Label (); txtYSize = new java.awt.TextField (); lblIgnoranceThreshold = new java.awt.Label (); txtIgnoranceThreshold = new java.awt.TextField (); lblDesireThreshold = new java.awt.Label (); txtDesireThreshold = new java.awt.TextField (); lblAversionThreshold = new java.awt.Label (); txtAversionThreshold = new java.awt.TextField (); lblHappinessThreshold = new java.awt.Label (); txtHappinessThreshold = new java.awt.TextField (); lblUseKarma = new java.awt.Label (); cbxUseKarma = new java.awt.Checkbox (); lblFoodConsumed = new java.awt.Label ();

181 txtFoodConsumed = new java.awt.TextField (); lblKarmaRange = new java.awt.Label (); txtKarmaRange = new java.awt.TextField (); lblSleepTime = new java.awt.Label (); txtSleepTime = new java.awt.TextField (); lblUseFastMode = new java.awt.Label (); cbxUseFastMode = new java.awt.Checkbox (); lblRndSeed = new java.awt.Label (); txtRndSeed = new java.awt.TextField (); setLayout (new java.awt.GridLayout (15, 2, 5, 5)); setBackground (java.awt.Color.lightGray); btnStartSwarmsara.setFont (new java.awt.Font ("Dialog", 0, 11)); btnStartSwarmsara.setLabel ("Start Swarmsara"); btnStartSwarmsara.setActionCommand ("startSwarmsara"); btnStartSwarmsara.setName ("startSwarmsara"); btnStartSwarmsara.setBackground (java.awt.Color.lightGray); btnStartSwarmsara.setForeground (java.awt.Color.black); btnStartSwarmsara.addMouseListener (new java.awt.event.MouseAdapter () { public void mouseClicked (java.awt.event.MouseEvent evt) { btnStartSwarmsaraMouseClicked (evt); } } ); add (btnStartSwarmsara); btnStopSwarmsara.setFont (new java.awt.Font ("Dialog", 0, 11)); btnStopSwarmsara.setLabel ("Stop Swarmsara"); btnStopSwarmsara.setActionCommand ("stopSwarmsara"); btnStopSwarmsara.setName ("stopSwarmsara"); btnStopSwarmsara.setEnabled (false); btnStopSwarmsara.setBackground (java.awt.Color.lightGray); btnStopSwarmsara.setForeground (java.awt.Color.black); btnStopSwarmsara.addMouseListener (new java.awt.event.MouseAdapter () { public void mouseClicked (java.awt.event.MouseEvent evt) { btnStopSwarmsaraMouseClicked (evt); } } ); add (btnStopSwarmsara); btnStartGraph.setFont (new java.awt.Font ("Dialog", 0, 11)); btnStartGraph.setLabel ("Start Graphs"); btnStartGraph.setName ("startGraph"); btnStartGraph.setBackground (java.awt.Color.lightGray); btnStartGraph.setForeground (java.awt.Color.black); btnStartGraph.addMouseListener (new java.awt.event.MouseAdapter () {

182 public void mouseClicked (java.awt.event.MouseEvent evt) { btnStartGraphMouseClicked (evt); }

} );

add (btnStartGraph); btnStopGraph.setFont (new java.awt.Font ("Dialog", 0, 11)); btnStopGraph.setLabel ("Stop Graphs"); btnStopGraph.setName ("stopGraph"); btnStopGraph.setEnabled (false); btnStopGraph.setBackground (java.awt.Color.lightGray); btnStopGraph.setForeground (java.awt.Color.black); btnStopGraph.addMouseListener (new java.awt.event.MouseAdapter () { public void mouseClicked (java.awt.event.MouseEvent evt) { btnStopGraphMouseClicked (evt); } } ); add (btnStopGraph); lblNumOfBugs.setFont (new java.awt.Font ("Dialog", 0, 11)); lblNumOfBugs.setName ("lblNumOfBugs"); lblNumOfBugs.setBackground (new java.awt.Color (204, 204, 204)); lblNumOfBugs.setForeground (java.awt.Color.black); lblNumOfBugs.setText ("Number of Bugs"); lblNumOfBugs.setAlignment (java.awt.Label.RIGHT); add (lblNumOfBugs); txtNumOfBugs.setBackground (java.awt.Color.white); txtNumOfBugs.setName ("txt_NumOfBugs"); txtNumOfBugs.setFont (new java.awt.Font ("Dialog", 0, 11)); txtNumOfBugs.setForeground (java.awt.Color.black); txtNumOfBugs.setText ("20"); txtNumOfBugs.addTextListener (new java.awt.event.TextListener () { public void textValueChanged (java.awt.event.TextEvent evt) { txtNumOfBugsTextValueChanged (evt); } } ); add (txtNumOfBugs); lblXSize.setFont (new java.awt.Font ("Dialog", 0, 11));

183 lblXSize.setName ("lblXSize"); lblXSize.setBackground (new java.awt.Color (204, 204, 204)); lblXSize.setForeground (java.awt.Color.black); lblXSize.setText ("X Size"); lblXSize.setAlignment (java.awt.Label.RIGHT); add (lblXSize); txtXSize.setBackground (java.awt.Color.white); txtXSize.setName ("txtXSize"); txtXSize.setFont (new java.awt.Font ("Dialog", 0, 11)); txtXSize.setForeground (java.awt.Color.black); txtXSize.setText ("15"); txtXSize.addTextListener (new java.awt.event.TextListener () { public void textValueChanged (java.awt.event.TextEvent evt) { txtXSizeTextValueChanged (evt); } } ); add (txtXSize); lblYSize.setFont (new java.awt.Font ("Dialog", 0, 11)); lblYSize.setName ("lblYSize"); lblYSize.setBackground (new java.awt.Color (204, 204, 204)); lblYSize.setForeground (java.awt.Color.black); lblYSize.setText ("Y Size"); lblYSize.setAlignment (java.awt.Label.RIGHT); add (lblYSize); txtYSize.setBackground (java.awt.Color.white); txtYSize.setName ("txtYSize"); txtYSize.setFont (new java.awt.Font ("Dialog", 0, 11)); txtYSize.setForeground (java.awt.Color.black); txtYSize.setText ("15"); txtYSize.addTextListener (new java.awt.event.TextListener () { public void textValueChanged (java.awt.event.TextEvent evt) { txtYSizeTextValueChanged (evt); } } ); add (txtYSize); lblIgnoranceThreshold.setFont (new java.awt.Font ("Dialog", 0, 11)); lblIgnoranceThreshold.setName ("lblIgnoranceThreshold");

184 lblIgnoranceThreshold.setBackground (new java.awt.Color (204, 204, 204)); lblIgnoranceThreshold.setForeground (java.awt.Color.black); lblIgnoranceThreshold.setText ("Ignorance Threshold"); lblIgnoranceThreshold.setAlignment (java.awt.Label.RIGHT); add (lblIgnoranceThreshold); txtIgnoranceThreshold.setBackground (java.awt.Color.white); txtIgnoranceThreshold.setName ("txtIgnoranceThreshold"); txtIgnoranceThreshold.setFont (new java.awt.Font ("Dialog", 0, 11)); txtIgnoranceThreshold.setForeground (java.awt.Color.black); txtIgnoranceThreshold.setText ("255"); txtIgnoranceThreshold.addTextListener (new java.awt.event.TextListener () { public void textValueChanged (java.awt.event.TextEvent evt) { txtIgnoranceThresholdTextValueChanged (evt); } } ); add (txtIgnoranceThreshold); lblDesireThreshold.setFont (new java.awt.Font ("Dialog", 0, 11)); lblDesireThreshold.setName ("lblDesireThreshold"); lblDesireThreshold.setBackground (new java.awt.Color (204, 204, 204)); lblDesireThreshold.setForeground (java.awt.Color.black); lblDesireThreshold.setText ("Attraction Threshold"); lblDesireThreshold.setAlignment (java.awt.Label.RIGHT); add (lblDesireThreshold); txtDesireThreshold.setBackground (java.awt.Color.white); txtDesireThreshold.setName ("txtDesireThreshold"); txtDesireThreshold.setFont (new java.awt.Font ("Dialog", 0, 11)); txtDesireThreshold.setForeground (java.awt.Color.black); txtDesireThreshold.setText ("255"); txtDesireThreshold.addTextListener (new java.awt.event.TextListener () { public void textValueChanged (java.awt.event.TextEvent evt) { txtDesireThresholdTextValueChanged (evt); } } ); add (txtDesireThreshold); lblAversionThreshold.setFont (new java.awt.Font ("Dialog", 0, 11)); lblAversionThreshold.setName ("lblAversionThreshold"); lblAversionThreshold.setBackground (new java.awt.Color (204, 204, 204));

185 lblAversionThreshold.setForeground (java.awt.Color.black); lblAversionThreshold.setText ("Aversion Threshold"); lblAversionThreshold.setAlignment (java.awt.Label.RIGHT); add (lblAversionThreshold); txtAversionThreshold.setBackground (java.awt.Color.white); txtAversionThreshold.setName ("txtAversionThreshold"); txtAversionThreshold.setFont (new java.awt.Font ("Dialog", 0, 11)); txtAversionThreshold.setForeground (java.awt.Color.black); txtAversionThreshold.setText ("255"); txtAversionThreshold.addTextListener (new java.awt.event.TextListener () { public void textValueChanged (java.awt.event.TextEvent evt) { txtAversionThresholdTextValueChanged (evt); } } ); add (txtAversionThreshold); lblHappinessThreshold.setFont (new java.awt.Font ("Dialog", 0, 11)); lblHappinessThreshold.setName ("lblHappinessThreshold"); lblHappinessThreshold.setBackground (new java.awt.Color (204, 204, 204)); lblHappinessThreshold.setForeground (java.awt.Color.black); lblHappinessThreshold.setText ("Happiness Threshold"); lblHappinessThreshold.setAlignment (java.awt.Label.RIGHT); add (lblHappinessThreshold); txtHappinessThreshold.setBackground (java.awt.Color.white); txtHappinessThreshold.setName ("txtHappinessThreshold"); txtHappinessThreshold.setFont (new java.awt.Font ("Dialog", 0, 11)); txtHappinessThreshold.setForeground (java.awt.Color.black); txtHappinessThreshold.setText ("20"); txtHappinessThreshold.addTextListener (new java.awt.event.TextListener () { public void textValueChanged (java.awt.event.TextEvent evt) { txtHappinessThresholdTextValueChanged (evt); } } ); add (txtHappinessThreshold); lblUseKarma.setFont (new java.awt.Font ("Dialog", 0, 11)); lblUseKarma.setName ("lblUseKarma"); lblUseKarma.setBackground (new java.awt.Color (204, 204, 204)); lblUseKarma.setForeground (java.awt.Color.black);

186 lblUseKarma.setText ("Use Karma"); lblUseKarma.setAlignment (java.awt.Label.RIGHT); add (lblUseKarma); cbxUseKarma.setState (true); cbxUseKarma.setBackground (new java.awt.Color (204, 204, 204)); cbxUseKarma.setName ("cbxUseKarma"); cbxUseKarma.setFont (new java.awt.Font ("Dialog", 0, 11)); cbxUseKarma.setForeground (java.awt.Color.black); cbxUseKarma.addItemListener (new java.awt.event.ItemListener () { public void itemStateChanged (java.awt.event.ItemEvent evt) { cbxUseKarmaItemStateChanged (evt); } } ); add (cbxUseKarma); lblFoodConsumed.setFont (new java.awt.Font ("Dialog", 0, 11)); lblFoodConsumed.setName ("lblFoodConsumed"); lblFoodConsumed.setBackground (new java.awt.Color (204, 204, 204)); lblFoodConsumed.setForeground (java.awt.Color.black); lblFoodConsumed.setText ("Food Consumed"); lblFoodConsumed.setAlignment (java.awt.Label.RIGHT); add (lblFoodConsumed); txtFoodConsumed.setBackground (java.awt.Color.white); txtFoodConsumed.setName ("txtFoodConsumed"); txtFoodConsumed.setFont (new java.awt.Font ("Dialog", 0, 11)); txtFoodConsumed.setForeground (java.awt.Color.black); txtFoodConsumed.setText ("30"); txtFoodConsumed.addTextListener (new java.awt.event.TextListener () { public void textValueChanged (java.awt.event.TextEvent evt) { txtFoodConsumedTextValueChanged (evt); } } ); add (txtFoodConsumed); lblKarmaRange.setFont (new java.awt.Font ("Dialog", 0, 11)); lblKarmaRange.setName ("lblKarmaRange"); lblKarmaRange.setBackground (new java.awt.Color (204, 204, 204)); lblKarmaRange.setForeground (java.awt.Color.black); lblKarmaRange.setText ("Karma Range");

187 lblKarmaRange.setAlignment (java.awt.Label.RIGHT); add (lblKarmaRange); txtKarmaRange.setBackground (java.awt.Color.white); txtKarmaRange.setName ("txtKarmaRange"); txtKarmaRange.setFont (new java.awt.Font ("Dialog", 0, 11)); txtKarmaRange.setForeground (java.awt.Color.black); txtKarmaRange.setText ("60"); txtKarmaRange.addTextListener (new java.awt.event.TextListener () { public void textValueChanged (java.awt.event.TextEvent evt) { txtKarmaRangeTextValueChanged (evt); } } ); add (txtKarmaRange); lblSleepTime.setFont (new java.awt.Font ("Dialog", 0, 11)); lblSleepTime.setName ("lblSleepTime"); lblSleepTime.setBackground (new java.awt.Color (204, 204, 204)); lblSleepTime.setForeground (java.awt.Color.black); lblSleepTime.setText ("Sleep Time"); lblSleepTime.setAlignment (java.awt.Label.RIGHT); add (lblSleepTime); txtSleepTime.setBackground (java.awt.Color.white); txtSleepTime.setName ("txtSleepTime"); txtSleepTime.setFont (new java.awt.Font ("Dialog", 0, 11)); txtSleepTime.setForeground (java.awt.Color.black); txtSleepTime.setText ("0"); txtSleepTime.addTextListener (new java.awt.event.TextListener () { public void textValueChanged (java.awt.event.TextEvent evt) { txtSleepTimeTextValueChanged (evt); } } ); add (txtSleepTime); lblUseFastMode.setFont (new java.awt.Font ("Dialog", 0, 11)); lblUseFastMode.setName ("label12lblUseFastMode"); lblUseFastMode.setBackground (new java.awt.Color (204, 204, 204)); lblUseFastMode.setForeground (java.awt.Color.black); lblUseFastMode.setText ("Use Fast Mode"); lblUseFastMode.setAlignment (java.awt.Label.RIGHT);

188

add (lblUseFastMode); cbxUseFastMode.setBackground (new java.awt.Color (204, 204, 204)); cbxUseFastMode.setName ("cbxUseFastMode"); cbxUseFastMode.setFont (new java.awt.Font ("Dialog", 0, 11)); cbxUseFastMode.setForeground (java.awt.Color.black); cbxUseFastMode.addItemListener (new java.awt.event.ItemListener () { public void itemStateChanged (java.awt.event.ItemEvent evt) { cbxUseFastModeItemStateChanged (evt); } } ); add (cbxUseFastMode); lblRndSeed.setFont (new java.awt.Font ("Abadi MT Condensed Light", 0, 10)); lblRndSeed.setName ("lblRndSeed"); lblRndSeed.setBackground (new java.awt.Color (204, 204, 204)); lblRndSeed.setForeground (java.awt.Color.black); lblRndSeed.setText ("Random Seed"); lblRndSeed.setAlignment (java.awt.Label.RIGHT); add (lblRndSeed); txtRndSeed.setBackground (java.awt.Color.white); txtRndSeed.setName ("txtRndSeed"); txtRndSeed.setFont (new java.awt.Font ("Abadi MT Condensed Light", 0, 10)); txtRndSeed.setForeground (java.awt.Color.black); txtRndSeed.setText ("random"); txtRndSeed.addTextListener (new java.awt.event.TextListener () { public void textValueChanged (java.awt.event.TextEvent evt) { txtRndSeedTextValueChanged (evt); } } ); add (txtRndSeed); }//GEN-END:initComponents /** * picks up changes to the text and adjusts the variable * @param evt A text event in the control **/

189 private void txtRndSeedTextValueChanged (java.awt.event.TextEvent evt) {//GENFIRST:event_txtRndSeedTextValueChanged // Add your handling code here: // this should probably have some validation built in rndSeed = txtRndSeed.getText(); }//GEN-LAST:event_txtRndSeedTextValueChanged /** * on mouse click on Stop Graphs stops the graphs and resets the buttons * @param evt A mouse event in the control **/ private void btnStopGraphMouseClicked (java.awt.event.MouseEvent evt) {//GENFIRST:event_btnStopGraphMouseClicked // Add your handling code here: if (graphIsRunning) { graphPop.graph.stop(); graphPop.graph = null; graphPop.dispose(); emoGraphPop.graph.stop(); emoGraphPop.graph = null; emoGraphPop.dispose(); btnStartGraph.setEnabled(true); btnStopGraph.setEnabled(false); graphIsRunning = false; System.gc(); } }//GEN-LAST:event_btnStopGraphMouseClicked /** * on mouse click on Start Graphs starts the graphs and sim if it not running * and greys the start buttons * @param evt A mouse event in the control **/ private void btnStartGraphMouseClicked (java.awt.event.MouseEvent evt) {//GENFIRST:event_btnStartGraphMouseClicked // Add your handling code here: if (!simIsRunning) { window = new SwarmsaraPop(num_of_bugs,xsize,ysize, ignoranceThreshold, desireThreshold, aversionThreshold, happinessThreshold,useKarma,foodConsumed,karmaRange,sleepTime, useFastMode,rndSeed); window.setLocation(0,300); window.setSize(275,275); window.setTitle("Swarmsara"); window.setVisible(true); btnStartSwarmsara.setEnabled(false); btnStopSwarmsara.setEnabled(true); simIsRunning = true; window.swarmsara.start(); } if (!graphIsRunning) {

190 //try { //Thread.sleep(250); //wait(20000); //} catch(Exception e) { } graphPop = new GraphPop(window.swarmsara); graphPop.setLocation(275,0); graphPop.setSize(525,380); graphPop.setTitle("Food and Happiness"); graphPop.setVisible(true); //try { //Thread.sleep(250); //wait(20000); //} catch(Exception e) { } emoGraphPop = new EmoGraphPop(window.swarmsara); emoGraphPop.setLocation(275,75); emoGraphPop.setSize(525,380); emoGraphPop.setTitle("Emotions"); emoGraphPop.setVisible(true); graphIsRunning = true; btnStartGraph.setEnabled(false); btnStopGraph.setEnabled(true); graphPop.graph.start(); emoGraphPop.graph.start();

} }//GEN-LAST:event_btnStartGraphMouseClicked

private void btnStopSwarmsaraMouseClicked (java.awt.event.MouseEvent evt) {//GENFIRST:event_btnStopSwarmsaraMouseClicked // Add your handling code here: if (simIsRunning) { //window.swarmsara.destroy(); window.swarmsara.stop(); window.swarmsara = null; window.dispose(); simIsRunning = false; btnStartSwarmsara.setEnabled(true); btnStopSwarmsara.setEnabled(false); } if (window.infoWindow.isShowing()) window.infoWindow.dispose(); if (graphIsRunning) { graphPop.graph.stop(); graphPop.graph = null; graphPop.dispose(); emoGraphPop.graph.stop(); emoGraphPop.graph = null; emoGraphPop.dispose(); graphIsRunning = false; btnStartGraph.setEnabled(true); btnStopGraph.setEnabled(false);

191 } System.gc(); // window.hide(); }//GEN-LAST:event_btnStopSwarmsaraMouseClicked private void btnStartSwarmsaraMouseClicked (java.awt.event.MouseEvent evt) {//GENFIRST:event_btnStartSwarmsaraMouseClicked // Add your handling code here: if (!simIsRunning) { window = new SwarmsaraPop(num_of_bugs,xsize,ysize, ignoranceThreshold, desireThreshold, aversionThreshold, happinessThreshold,useKarma,foodConsumed,karmaRange,sleepTime, useFastMode,rndSeed); window.setLocation(0,300); window.setSize(275,275); window.setTitle("Swarmsara"); window.setVisible(true); btnStartSwarmsara.setEnabled(false); btnStopSwarmsara.setEnabled(true); simIsRunning = true; window.swarmsara.setVisible(true); window.swarmsara.start(); } //window.swarmsara.start(); }//GEN-LAST:event_btnStartSwarmsaraMouseClicked private void txtSleepTimeTextValueChanged (java.awt.event.TextEvent evt) {//GENFIRST:event_txtSleepTimeTextValueChanged // Add your handling code here: sleepTime = Integer.parseInt(txtSleepTime.getText()); }//GEN-LAST:event_txtSleepTimeTextValueChanged private void cbxUseFastModeItemStateChanged (java.awt.event.ItemEvent evt) {//GENFIRST:event_cbxUseFastModeItemStateChanged // Add your handling code here: useFastMode = cbxUseFastMode.getState(); }//GEN-LAST:event_cbxUseFastModeItemStateChanged private void txtKarmaRangeTextValueChanged (java.awt.event.TextEvent evt) {//GENFIRST:event_txtKarmaRangeTextValueChanged // Add your handling code here: karmaRange = Integer.parseInt(txtKarmaRange.getText()); }//GEN-LAST:event_txtKarmaRangeTextValueChanged private void txtFoodConsumedTextValueChanged (java.awt.event.TextEvent evt) {//GENFIRST:event_txtFoodConsumedTextValueChanged // Add your handling code here: foodConsumed = Integer.parseInt(txtFoodConsumed.getText()); }//GEN-LAST:event_txtFoodConsumedTextValueChanged

192 private void cbxUseKarmaItemStateChanged (java.awt.event.ItemEvent evt) {//GENFIRST:event_cbxUseKarmaItemStateChanged // Add your handling code here: useKarma = cbxUseKarma.getState(); }//GEN-LAST:event_cbxUseKarmaItemStateChanged private void txtHappinessThresholdTextValueChanged (java.awt.event.TextEvent evt) {//GEN-FIRST:event_txtHappinessThresholdTextValueChanged // Add your handling code here: happinessThreshold = Integer.parseInt(txtHappinessThreshold.getText()); }//GEN-LAST:event_txtHappinessThresholdTextValueChanged private void txtAversionThresholdTextValueChanged (java.awt.event.TextEvent evt) {//GENFIRST:event_txtAversionThresholdTextValueChanged // Add your handling code here: aversionThreshold = Integer.parseInt( txtAversionThreshold.getText()); }//GEN-LAST:event_txtAversionThresholdTextValueChanged private void txtDesireThresholdTextValueChanged (java.awt.event.TextEvent evt) {//GENFIRST:event_txtDesireThresholdTextValueChanged // Add your handling code here: desireThreshold = Integer.parseInt(txtDesireThreshold.getText()); }//GEN-LAST:event_txtDesireThresholdTextValueChanged private void txtIgnoranceThresholdTextValueChanged (java.awt.event.TextEvent evt) {//GENFIRST:event_txtIgnoranceThresholdTextValueChanged // Add your handling code here: ignoranceThreshold = Integer.parseInt(txtIgnoranceThreshold.getText()); }//GEN-LAST:event_txtIgnoranceThresholdTextValueChanged // Stop Graph// Start Graph private void txtYSizeTextValueChanged (java.awt.event.TextEvent evt) {//GENFIRST:event_txtYSizeTextValueChanged // Add your handling code here: ysize = Integer.parseInt(txtYSize.getText()); }//GEN-LAST:event_txtYSizeTextValueChanged private void txtXSizeTextValueChanged (java.awt.event.TextEvent evt) {//GENFIRST:event_txtXSizeTextValueChanged // Add your handling code here: xsize = Integer.parseInt(txtXSize.getText()); }//GEN-LAST:event_txtXSizeTextValueChanged private void txtNumOfBugsTextValueChanged (java.awt.event.TextEvent evt) {//GENFIRST:event_txtNumOfBugsTextValueChanged // Add your handling code here: num_of_bugs = Integer.parseInt(txtNumOfBugs.getText()); }//GEN-LAST:event_txtNumOfBugsTextValueChanged // Stop Swarmsara// Start Swarmsara // Variables declaration - do not modify//GEN-BEGIN:variables private java.awt.Button btnStartSwarmsara;

193 private java.awt.Button btnStopSwarmsara; private java.awt.Button btnStartGraph; private java.awt.Button btnStopGraph; private java.awt.Label lblNumOfBugs; private java.awt.TextField txtNumOfBugs; private java.awt.Label lblXSize; private java.awt.TextField txtXSize; private java.awt.Label lblYSize; private java.awt.TextField txtYSize; private java.awt.Label lblIgnoranceThreshold; private java.awt.TextField txtIgnoranceThreshold; private java.awt.Label lblDesireThreshold; private java.awt.TextField txtDesireThreshold; private java.awt.Label lblAversionThreshold; private java.awt.TextField txtAversionThreshold; private java.awt.Label lblHappinessThreshold; private java.awt.TextField txtHappinessThreshold; private java.awt.Label lblUseKarma; private java.awt.Checkbox cbxUseKarma; private java.awt.Label lblFoodConsumed; private java.awt.TextField txtFoodConsumed; private java.awt.Label lblKarmaRange; private java.awt.TextField txtKarmaRange; private java.awt.Label lblSleepTime; private java.awt.TextField txtSleepTime; private java.awt.Label lblUseFastMode; private java.awt.Checkbox cbxUseFastMode; private java.awt.Label lblRndSeed; private java.awt.TextField txtRndSeed; // End of variables declaration//GEN-END:variables }

194 EmoGraph.java import java.awt.*; import java.applet.*; import java.net.URL; import java.util.*; import graph.*; /************************************************************************* ** ** Applet example2a ** Version 1.0 August 1996 ** ************************************************************************** ** Copyright (C) 1996 Leigh Brookshaw ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ************************************************************************** ** ** This is a simple applet that creates a Scroll Chart using the ** Graph2D class library and double buffering ** *************************************************************************/ // upgraded and adapted by Alex Turner 4/12/00 // modified 4/19/00 ALT public class EmoGraph extends Applet implements Runnable { Graph2D graph; Label title; DataSet data1 = new DataSet(); DataSet data2 = new DataSet(); DataSet data3 = new DataSet(); double minTime; //RTextLine text = new RTextLine(); Axis yaxis_right; Axis xaxis_bottom;

195 Image osi = null; Graphics osg = null; int iwidth = 0; int iheight = 0; Thread runner = null; Random random = new Random(); int count = 0; String st; String mfile; Swarmsara swarmsara; /* ** In milliseconds how often do we want to add a new data point. */ int period = 500; public EmoGraph(String title,String markers,int period,Swarmsara swarmsara) { st = title; mfile = markers; //setDocumentBase("/"); this.period = period; this.swarmsara = swarmsara; init(); } /* ** Maximum number of points to display before scrolling the data */ int maximum = 1000000; URL markersURL; /* ** Initialize the applet. The Parameters passed are the title of the plot ** the marker file to use and the update period in milliseconds */ public void init() { int i; int j; /* ** */

Get the passed parameters

//String st = getParameter("TITLE"); // String mfile = getParameter("MARKERS"); // try { // period = Integer.parseInt(getParameter("PERIOD")); // } // catch (Exception e) { // System.out.println("Frequency parameter not an Integer!"); // } /*

196 ** */

/* ** */

Create the Graph instance and modify the default behaviour graph = new Graph2D(); graph.zerocolor = new Color(0,255,0); graph.borderTop = 50; graph.borderBottom = 50; graph.setDataBackground(Color.black); Create the Title title = new Label(st, Label.CENTER); title.setFont(new Font("TimesRoman",Font.PLAIN,20)); Label legend = new Label ("Green: Avg Ignorance Blue: Avg Attraction Red: Avg Aversion", Label.CENTER); legend.setFont(new Font("TimesRoman",Font.PLAIN,14)); setLayout( new BorderLayout() ); add("North", title); add("Center", graph); add("South", legend);

/* ** */

/* ** */

Load a file containing Marker definitions //System.out.println(getCodeBase()); // System.out.println(getAppletContext()); //System.out.println(mfile); // try { // markersURL = new URL(getDocumentBase(),mfile); //markersURL = new URL("file:///C|/alexweb/thesis/Swarmsara/marker.txt"); // graph.setMarkers(new Markers(markersURL)); // } catch(Exception e) { // System.out.println("Failed to create Marker URL!"); // }

Modify the default Data behaviour data1.linecolor = new Color(255,0,0); //data1.marker = 1; //data1.markercolor = new Color(100,100,255); data2.linecolor = new Color(0,255,0); data3.linecolor = new Color(0,0,255); //data2.marker = 1; // data2.markercolor = new Color(100,100,255);

/* ** ** */

Setup the Axis. Attach it to the Graph2D instance, and attach the data to it. yaxis_right = graph.createAxis(Axis.RIGHT);

197 //yaxis_right.setTitleText("Perception Distortion"); yaxis_right.attachDataSet(data1); yaxis_right.attachDataSet(data2); yaxis_right.attachDataSet(data3); yaxis_right.setLabelFont(new Font("Helvetica",Font.PLAIN,14)); xaxis_bottom = graph.createAxis(Axis.BOTTOM); xaxis_bottom.drawgrid = false; xaxis_bottom.setTitleText("Timesteps"); xaxis_bottom.attachDataSet(data1); xaxis_bottom.attachDataSet(data2); xaxis_bottom.attachDataSet(data3); xaxis_bottom.setLabelFont(new Font("Helvetica",Font.PLAIN,14)); graph.attachDataSet(data1); graph.attachDataSet(data2); graph.attachDataSet(data3); minTime = swarmsara.timestep - 1.0; } // for a threaded applet public void start() { if (runner == null) { runner = new Thread(this); runner.start(); } } //method start public void stop() { runner = null; } // method stop // the "main" method of the applet public void run() { int i =0; double aversionData[] = new double[2]; double ignoranceData[] = new double[2]; double desireData[] = new double[2]; Graphics g; Thread thisThread = Thread.currentThread(); while (runner == thisThread) { try { thisThread.sleep(0); } catch (InterruptedException e){ } count++; if(count >= maximum) data1.delete(0,0);

198 //if(count >= maximum) data2.delete(0,0); //if(count >= maximum) data3.delete(0,0); //data[1] = (2.0*random.nextDouble()-1.0)*50.0; aversionData[1] = swarmsara.avgAversion; //data[2] = swarmsara.avgBugFood; aversionData[0] = swarmsara.timestep; try { data1.append(aversionData,1); } catch (Exception e) { System.out.println("Error appending Data!"); } ignoranceData[1] = swarmsara.avgIgnorance; ignoranceData[0] = swarmsara.timestep; try { data2.append(ignoranceData,1); } catch (Exception e) { System.out.println("Error appending Data!"); } desireData[1] = swarmsara.avgDesire; desireData[0] = swarmsara.timestep; try { data3.append(desireData,1); } catch (Exception e) { System.out.println("Error appending Data!"); } //data2.yaxis.maximum = 150.0; //data2.yaxis.minimum = 0.0; //data1.yaxis.maximum = 150.0; //data1.yaxis.minimum = 0.0; //data3.yaxis.maximum = 150.0; //data3.yaxis.minimum = 0.0; data1.xaxis.minimum = minTime; g = graph.getGraphics(); if( osi == null || iwidth != graph.getSize().width || iheight != graph.getSize().height ) { iwidth = graph.getSize().width; iheight = graph.getSize().height; osi = graph.createImage(iwidth,iheight); osg = osi.getGraphics(); }

199 osg.setColor(this.getBackground()); osg.fillRect(0,0,iwidth,iheight); osg.setColor(g.getColor()); osg.clipRect(0,0,iwidth,iheight); graph.update(osg); g.drawImage(osi,0,0,graph);

try { Thread.sleep(period); } catch(Exception e) { } } } }

200 EmoGraphPop.java /* * EmoGraphPop.java * * Created on April 12, 2000, 1:32 AM */

/** * * @author turnea * @version */ import java.awt.BorderLayout; public class EmoGraphPop extends java.awt.Frame { EmoGraph graph; /** Creates new form GraphPop */ public EmoGraphPop(Swarmsara swarmsara) { graph = new EmoGraph("Afflictive Emotions","marker.txt",250,swarmsara); //graph.setSize(200,150); add (graph,BorderLayout.CENTER); initComponents (); pack (); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the FormEditor. */ private void initComponents () {//GEN-BEGIN:initComponents addWindowListener (new java.awt.event.WindowAdapter () { public void windowClosing (java.awt.event.WindowEvent evt) { exitForm (evt); } } ); }//GEN-END:initComponents /** Exit the Application */ private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm setVisible(false); }//GEN-LAST:event_exitForm /**

201

* @param args the command line arguments */ public static void main (String args[]) { // new GraphPop (window.swarmsara).show (); } // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables }

202 RealTimeGraph.java import java.awt.*; import java.applet.*; import java.net.URL; import java.util.*; import graph.*; /************************************************************************* ** ** Applet example2a ** Version 1.0 August 1996 ** ************************************************************************** ** Copyright (C) 1996 Leigh Brookshaw ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ************************************************************************** ** ** This is a simple applet that creates a Scroll Chart using the ** Graph2D class library and double buffering ** *************************************************************************/ // upgraded and adapted by Alex Turner 4/12/00 public class RealTimeGraph extends Applet implements Runnable { Graph2D graph; Label title; DataSet data1 = new DataSet(); DataSet data2 = new DataSet(); DataSet data3 = new DataSet(); double minTime; Axis yaxis_right; Axis xaxis_bottom; Image osi = null; Graphics osg = null;

203 int iwidth = 0; int iheight = 0; Thread runner = null; Random random = new Random(); int count = 0; String st; String mfile; Swarmsara swarmsara; long sysDate, oldSysDate; int oldTimeStep = 0; /* ** In milliseconds how often do we want to add a new data point. */ int period = 500; public RealTimeGraph (String title,String markers,int period, Swarmsara swarmsara) { st = title; mfile = markers; //setDocumentBase("/"); this.period = period; this.swarmsara = swarmsara; init(); } /* ** Maximum number of points to display before scrolling the data */ int maximum = 1000000; URL markersURL; /* ** Initialize the applet. The Parameters passed are the title of the plot ** the marker file to use and the update period in milliseconds */ public void init() { int i; int j; sysDate = new Date().getTime(); oldSysDate = sysDate; /* ** */

Get the passed parameters //String st = getParameter("TITLE"); // String mfile = getParameter("MARKERS"); // try { // period = Integer.parseInt(getParameter("PERIOD")); // } // catch (Exception e) { // System.out.println("Frequency parameter not an Integer!");

204 // /* ** */

} Create the Graph instance and modify the default behaviour graph = new Graph2D(); graph.zerocolor = new Color(0,255,0); graph.borderTop = 50; graph.borderBottom = 50; graph.setDataBackground(Color.black);

/* ** */

Create the Title

title = new Label(st, Label.CENTER); title.setFont(new Font("TimesRoman",Font.PLAIN,20)); Label legend = new Label ("Yellow: Avg World Food Cyan: % over Happiness Threshold Label.CENTER); legend.setFont(new Font("TimesRoman",Font.PLAIN,14));

Purple: % Happy",

setLayout( new BorderLayout() ); add("North", title); add("Center", graph); add("South", legend); /* ** */

Load a file containing Marker definitions //System.out.println(getCodeBase()); // System.out.println(getAppletContext()); //System.out.println(mfile); // try { // markersURL = new URL(getDocumentBase(),mfile); //markersURL = new URL("file:///C|/alexweb/thesis/Swarmsara/marker.txt"); // graph.setMarkers(new Markers(markersURL)); // } catch(Exception e) { // System.out.println("Failed to create Marker URL!"); // }

/* ** */

Modify the default Data behaviour data1.linecolor = new Color(255,255,0); //data1.marker = 1; //data1.markercolor = new Color(100,100,255); data2.linecolor = new Color(0,255,255); data3.linecolor = new Color(255,0,255); //data2.marker = 1; // data2.markercolor = new Color(100,100,255);

205 /* ** ** */

Setup the Axis. Attach it to the Graph2D instance, and attach the data to it. yaxis_right = graph.createAxis(Axis.RIGHT); yaxis_right.attachDataSet(data1); yaxis_right.attachDataSet(data2); yaxis_right.attachDataSet(data3); yaxis_right.setLabelFont(new Font("Helvetica",Font.PLAIN,14)); xaxis_bottom = graph.createAxis(Axis.BOTTOM); xaxis_bottom.drawgrid = false; xaxis_bottom.setTitleText("Timesteps"); xaxis_bottom.attachDataSet(data1); xaxis_bottom.attachDataSet(data2); xaxis_bottom.attachDataSet(data3); xaxis_bottom.setLabelFont(new Font("Helvetica",Font.PLAIN,14)); graph.attachDataSet(data1); graph.attachDataSet(data2); graph.attachDataSet(data3); //prevents a problem with x axis that causes crashes minTime = swarmsara.timestep - 1.0; } // for a threaded applet public void start() { if (runner == null) { runner = new Thread(this); runner.start(); } } //method start public void stop() { runner = null; } // method stop // the "main" method of the applet public void run() { int i =0; double data[] = new double[2]; double bugData[] = new double[2]; double happiness[] = new double[2]; Graphics g; Thread thisThread = Thread.currentThread(); while (runner == thisThread) { try { thisThread.sleep(0); } catch (InterruptedException e){

206 } count++; if(count >= maximum) data1.delete(0,0); if(count >= maximum) data2.delete(0,0); if(count >= maximum) data3.delete(0,0); //data[1] = (2.0*random.nextDouble()-1.0)*50.0; data[1] = swarmsara.avgTotalFood; //data[2] = swarmsara.avgBugFood; data[0] = swarmsara.timestep; try { data1.append(data,1); } catch (Exception e) { System.out.println("Error appending Data!"); } bugData[1] = swarmsara.pctOverHapThreshold; bugData[0] = swarmsara.timestep; try { data2.append(bugData,1); } catch (Exception e) { System.out.println("Error appending Data!"); } happiness[1] = swarmsara.pctHappy; happiness[0] = swarmsara.timestep; try { data3.append(happiness,1); } catch (Exception e) { System.out.println("Error appending Data!"); } //data2.yaxis.maximum = 150.0; //data2.yaxis.minimum = 0.0; //data1.yaxis.maximum = 150.0; //data1.yaxis.minimum = 0.0; //data3.yaxis.maximum = 150.0; //data3.yaxis.minimum = 0.0; data1.xaxis.minimum = minTime; g = graph.getGraphics(); if( osi == null || iwidth != graph.getSize().width || iheight != graph.getSize().height ) { iwidth = graph.getSize().width; iheight = graph.getSize().height;

207 osi = graph.createImage(iwidth,iheight); osg = osi.getGraphics(); } osg.setColor(this.getBackground()); osg.fillRect(0,0,iwidth,iheight); osg.setColor(g.getColor()); osg.clipRect(0,0,iwidth,iheight); graph.update(osg); g.drawImage(osi,0,0,graph); sysDate = new Date().getTime(); // if (swarmsara.timestep - oldTimeStep != 0) // System.out.println( // (sysDate - oldSysDate) / swarmsara.timestep); // else System.out.println("zero!");

try { //Thread.sleep(period); if (swarmsara.timestep != 0) Thread.sleep( period * ((sysDate - oldSysDate) / swarmsara.timestep)); } catch(Exception e) { } //oldTimeStep = swarmsara.timestep; //oldSysDate = sysDate; } } }

208

GraphPop.java /* * GraphPop.java * * Created on April 12, 2000, 1:32 AM */ /************************************************************************** ** Copyright (C) 2000 Alex Turner ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. **************************************************************************/ /** * * @author turnea * @version */ import java.awt.BorderLayout; public class GraphPop extends java.awt.Frame { RealTimeGraph graph; /** Creates new form GraphPop */ public GraphPop(Swarmsara swarmsara) { graph = new RealTimeGraph("Avg Food & Percent Happy","marker.txt",250,swarmsara); //graph.setSize(200,150); add (graph,BorderLayout.CENTER); initComponents (); pack (); } /** This method is called from within the constructor to

209 * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the FormEditor. */ private void initComponents () {//GEN-BEGIN:initComponents addWindowListener (new java.awt.event.WindowAdapter () { public void windowClosing (java.awt.event.WindowEvent evt) { exitForm (evt); } } ); }//GEN-END:initComponents /** Exit the Application */ private void exitForm(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_exitForm setVisible(false); }//GEN-LAST:event_exitForm /** * @param args the command line arguments */ public static void main (String args[]) { // new GraphPop (window.swarmsara).show (); } // Variables declaration - do not modify//GEN-BEGIN:variables // End of variables declaration//GEN-END:variables }

210 INDEX

A

B

Abhidharma, 2, 113, 115, 120 Abhidharmakosa, 112, 120, 123 Agent, 5, 6, 7, 19, 20, 28, 30, 34, 36, 37, 38, 39, 40, 41, 42, 53, 56, 57, 68, 70, 91, 98, 102, 120, 122, 123, 128, 136, 137, 139, 141 Algorithms, i, 2, 4, 8, 20, 23, 24, 25, 30, 34, 53, 66, 67, 75, 92, 94, 95, 98, 99, 100, 103, 120, 121, 135, 137 Anapanasati, 6, 49, 56, 66, 109, 111 Applications, i, 6, 8, 11, 52, 73, 95, 100, 101, 109, 124, 126, 135, 146, 148, 176, 200, 209 Artificial Life, i, 74, 75, 89, 115, 132, 133, 134

Bodhisattva, 115, 117, 120 Brooks, Rodney, 5, 6, 68, 70, 72, 89, 111, 118 Buddha, 6, 36, 43, 45, 46, 49, 53, 56, 61, 68, 75, 90, 93, 94, 96, 97, 113, 117, 120, 124, 141 Buddhadasa Bikkhu, 6, 11, 13, 14, 15, 16, 49, 50, 66, 71, 92, 101, 109, 111, 112, 125, 130 Buddhadasa, Bikkhu, 6, 11, 13, 14, 15, 16, 49, 50, 66, 71, 92, 101, 109, 111, 112, 125, 130 Buddhism Mahayana, 88, 97, 130 Theravada, 71, 123 Vajrayana, 123 C Campbell, Joseph, 43, 112

Capitalism, 14, 15, 74, 117, 122 Cellular automata, 63, 103, 110, 120 Chaos Theory, 4, 12, 102, 107, 125, 132, 133 Clifford, Terry, 17, 46, 48, 49, 90, 112 Complexity, 4, 20, 41, 50, 57, 63, 64, 65, 89, 91, 95, 102, 105, 109, 114, 124, 127, 132, 133 Constructivism, 67, 68, 73, 74, 76, 89, 107 D Dalai Lama, 1, 3, 14, 18, 27, 30, 53, 96, 114, 116, 125, 127 Darwin, Charles, 25, 33, 113 Darwinism, 97 Dawkins, Richard, 2, 55, 113 Deconstruction, 44, 45, 51, 53, 108, 122

211 Dennett, Daniel, 2, 19, 24, 25, 55, 58, 67, 75, 113 Derrida, Jacques, 19, 20, 21, 45, 51, 68, 71, 75, 113, 122 Development, i, ix, 8, 43, 54, 61, 69, 91, 93, 94, 95, 101, 107, 109, 110, 111, 115, 118, 124, 125, 127, 128, 129, 130 Dharma, 21, 65, 111, 115, 116, 118 Dukkha, 66 E Ecofeminism, 43, 119 Ecological restoration, 17, 73, 74, 76, 114, 128 Evolutionary Biology, viii, 4, 55, 90, 97, 121 F Four Noble Truths, 46, 56, 60, 66, 90, 141

Guth, Alan, 24, 113, 114, 125 H Holland, John, 17, 58, 67, 68, 95, 99, 101, 114, 120, 121, 126 K Karma, i, v, viii, 2, 4, 5, 7, 12, 28, 29, 33, 34, 35, 36, 37, 40, 41, 42, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 75, 87, 88, 89, 90, 95, 97, 98, 102, 104, 107, 118, 121, 122, 127, 136, 137, 139, 158, 159, 160, 161, 162, 170, 171, 179, 186 Karmic fitness landscapes, 57, 95, 98 Kilesas, 16, 34, 105, 121 Kleshas, i, 2, 33, 34, 35, 36, 37, 43, 48, 51, 56, 59, 60, 76, 88, 95, 97, 120, 121

G Geographical Information Systems (GIS), i, 2, 8, 12, 100, 109

L Lama, 1, 14, 18, 27, 53, 96, 114, 116, 125, 127

Lambda Point, v, 64, 65, 105 Langton, Christopher, vii, 63, 103 Levy, Stephen, 1, 56, 63, 64, 75, 103, 115 Linde, Andrei, 23, 24, 115 M Marxism, 17, 18, 115 Memes, 55, 56, 57, 106, 107 Memetics, 55 N Nagarjuna, Acharya, 44, 47, 51, 53, 116, 122 P Pratitya-samutpada, 59, 60, 61, 116, 122 R Ray, Tom, i, vii, 12, 31, 72, 74, 95, 117 Robotics, vii, 6, 59, 61, 63, 66, 68, 72, 74, 89, 126, 129, 130, 134 S Samsara, i, ix, 2, 16, 17, 22, 34, 36, 52,

212 66, 88, 91, 100, 105, 108, 122, 179 Santikaro Bikkhu, viii, 15, 71, 92, 111, 112, 129 Santikaro, Bikkhu, viii, 15, 71, 92, 111, 112, 129 Self-reproducing automata, 55, 103 Sharpa Tulku, viii, 7, 53, 59, 70, 71, 87, 89, 97, 116, 130, 158 Sloman, Aaron, 2, 21, 76, 117, 129 Smolin, Lee, v, 25, 26, 97, 117 Steels, Luc, 6, 63, 68, 92, 111, 118 Subsumption, vii, 5, 6, 7, 59, 61, 68, 69, 70, 89 Swarm Simulation System, vii, 6, 94, 100, 104, 118,

123, 133, 135, 149, 156 Swarmsara, i, vii, ix, 2, 4, 7, 11, 12, 15, 16, 17, 19, 20, 21, 30, 34, 35, 36, 41, 51, 57, 59, 63, 70, 71, 73, 74, 75, 76, 77, 88, 90, 92, 93, 94, 95, 98, 100, 102, 103, 106, 107, 108, 109, 121, 123, 135, 136, 137, 139, 141, 142, 149, 150, 151, 165, 167, 168, 169, 170, 171, 173, 174, 178, 179, 181, 189, 191, 192, 195, 196, 200, 203, 204, 208 T Tantra, 1, 28, 29, 49, 123

Trungpa, Chögyam, 19, 118 Turing Machine, 103 U Universes, v, vii, 23, 24, 26, 27, 29, 33, 72, 97, 113, 114, 115, 125, 127 V Von Neumann Machines, 63, 103 Von Neumann Neighborhood, 123 Von Neumann, John, 36, 55, 63, 103, 104, 119, 123 W Warren, Karen, 12, 44, 119

SWARMSARA: AN ARTIFICIAL LIFE APPROACH TO ...

indigenous land-use planning and preservation, fostering bottom-up development ...... they can cast off their current oppression and get on with the business of .... a cure. On May 12, 2000 India's billionth baby was born, and meanwhile three ...... the word “like” in meaningless pairs, as is happening all around me in the café ...

1MB Sizes 2 Downloads 160 Views

Recommend Documents

Genetic Algorithms and Artificial Life
In the 1950s and 1960s several computer scientists independently studied .... logical arms races, host-parasite co-evolution, symbiosis, and resource ow in ...

Genetic Algorithms and Artificial Life
In the 1950s and 1960s several computer scientists independently studied .... individual learning and species evolution a ect one another (e.g., 1, 2, 13, 37 ... In recent years, algorithms that have been termed \genetic algorithms" have ..... Bedau

Genetic Algorithms and Artificial Life
... in the population. 3. Apply selection and genetic operators (crossover and mutation) to the population to .... an environment|aspects that change too quickly for evolution to track genetically. Although ...... Princeton University Press, Princeto

Genetic Algorithms and Artificial Life
In the 1950s and 1960s several computer scientists independently studied ... ther developed by Holland and his students and colleagues at the University of .... If if the environment is stable so that the best things to learn remain constant, then th

Artificial intelligence: an empirical science
before computers, the only observable examples of intelligence were the minds of living organisms, especially human beings. Now the family of intelligent systems had been joined by a new genus, intelligent computer programs. * E-mail: [email protected]

Artificial intelligence: an empirical science
My initial tasks in this paper are, first, to delimit the boundaries of artificial intelligence, then, to justify calling it a science: is AI science, or is it engineering, or some combination of these? After arguing that it is (at least) a science,

2013 Artificial Life and Robotics.pdf
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. 2013 Artificial ...

An Attempt to Mechanize Sociology by Artificial Intelligence ...
(because of business reasons although technically simple) of the society represented by ... social informatics to investigate applications of sociological theories.

2013 Artificial Life and Robotics.pdf
Page 1 of 11. ORIGINAL ARTICLE. Muscle force distribution for adaptive control of a humanoid. robot arm with redundant bi-articular and mono-articular muscle. mechanism. Haiwei Dong • Nikolaos Mavridis. Received: 7 January 2013 / Accepted: 14 May 2

DOWNLOAD An Interdisciplinary Approach to Early Childhood ...
Education and Care: Perspectives from Australia (Routledge Research in. Early Childhood Education) pdf by Susanne Garvis Full KINDLE ePub. Online.

Micropinion Generation: An Unsupervised Approach to ... - CiteSeerX
unsupervised, it uses a graph data structure that relies on the structural redundancies ..... For example, “Pros: battery, sound; Cons: hard disk, screen”. Since we ...

An Interpersonal Neurobiology Approach to ...
Reproduced with permission of the copyright owner. Further reproduction prohibited without permission. An Interpersonal Neurobiology Approach to Psychotherapy. Daniel J Siegel. Psychiatric Annals; Apr 2006; 36, 4; Psychology Module pg. 248 ...

An Institutionwide Approach to Redesigning Management of ...
rest events occur annually in the United States.1 Despite widespread training ... achieve the highest likelihood of success, the emergency must be identified, and ...

PDF Artificial Intelligence: A Modern Approach
Hall Series in Artificial Intelligence) Full Audiobook Online ... contributing "Artificial Intelligence "author and Professor Sebastian Thrun a Pearson author are ...

An Enhanced Approach to Providing Secure Point-to ...
emerging wireless technology that provides robustness, low power-consumption ..... operation flawless, we have three different options for prior link keys, like wise, .... Applications and the Internet Workshops (SAINT'03),. 2003. [6] Creighton T.