based model. a new revision of can be illustrated with the ... · sfsm, which appears in a...

21
"What I learned from the Artificial Stock Market" Paul E. Johnson [email protected] Dept. of Political Science University of Kansas Lawrence, Kansas 66045 November 5, 2001 Abstract The Santa Fe Artificial Stock Market is a well known agent based model. A new revision of the code (ASM 2.2) is now available. This essay describes some of the changes that were made in the code base and also presents some important lessons for agent based modelers that can be illustrated with the code. Since the code is available on the internet, it is hoped that this discussion and the code base it represents will be helpful to people who are planning projects in the field of agent based modeling. Acknowledgements: I would like to thank the ASM research team for making this code available. I would especially like to thank Blake LeBaron, who has answered quite a few questions about the details of this big set of code, and Brandon Weber, who did the detail work to release ASM 2.0. All errors are my responsibility alone.

Upload: others

Post on 21-May-2020

4 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

"What I learnedfrom theArtificial StockMarket"

PaulE. [email protected]

Dept.of PoliticalScienceUniversityof Kansas

Lawrence,Kansas66045

November5, 2001

Abstract

TheSantaFeArtificial StockMarketis a well knownagent� basedmodel. A newrevisionof

thecode(ASM � 2.2) is now available.Thisessaydescribessomeof thechangesthatwere

madein thecodebaseandalsopresentssomeimportantlessonsfor agent� basedmodelersthat

canbeillustratedwith thecode. Sincethecodeis availableon theinternet,it is hopedthat

thisdiscussionandthecodebaseit representswill behelpful to peoplewhoareplanning

projectsin thefield of agent� basedmodeling.

Acknowledgements:I would like to thanktheASM researchteamfor makingthiscode

available. I wouldespeciallylike to thankBlakeLeBaron,who hasansweredquitea few

questionsaboutthedetailsof this big setof code,andBrandonWeber,whodid thedetail

work to releaseASM � 2.0. All errorsaremy responsibilityalone.

Page 2: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

Thereis plentyof talk thesedaysabout"agent� basedmodeling"in socialscience,but

preciouslittle of it helpswith theactualdetailsof designingsucha modelandwriting code

for it. Thisessayexploressomeconclusionsthatwerereachedwhile workingon arevisionof

thecodefor theSantaFeArtificial StockMarket(ASM) modelthatwasmadefamousin a

verywidely citedarticleby R.G.Palmer,W. Brian Arthur, JohnH. Holland,BlakeLeBaron,

andPaulTaylor (1994). TheASM wasoneof thefirst projectsto demonstratethepotential

of agent� basedmodelsfor theexplorationof theoriesof decentralized,individualistic,and

boundedlyrationalbehavior. It hassparkeda smallcottageindustryof researchon artificial

stockmarkets(seeLeBaron,2000).

Thisessayexplorespracticalissuesthatanyprospectivemodel� builderwill confront.

Theseissuesareof generalimportance,not just to peoplewho wantto write aboutstock

marketsor useaparticularprogramminglibrary. Theoverallmessageis thatmodelsshould

bedesignedasseparate,independentlyfunctionalpiecesof code(objects),andthatsome

guidelinescanbefollowed to improvereadabilityandreduceunintendedconsequences

(bugs).

I don't write from theperspectiveof a computerscientistwho arriveson thesceneto

tell thesocialscientistwhatsheoughtto do. Quitethecontrary. I ama socialscientistby

training. WhenI startedlearningabouttheSwarmSimulationSystem(Minar, Burkhart,

Langton,Askenazi,1996)in 1997, I did notknow a greatdealaboutobject� oriented

programmingor agent� basedmodeling. For me,therewasa hand� in � handdevelopmentof

computingskills alongwith a comprehensionof agent� basedmodeling. I suspectit will be

thesamefor manysocialscientistswhoaredrawnto thegeneralappealandclaimsabout

agent� basedmodeling.

Backgroundon theStockMarketCodeBase

TheSwarmDevelopmentGroup(http://www.swarm.org)makesavailablea setof working

1

Page 3: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

codeexamplesfor theSwarmSimulationSystem.In additionto thosesupportedmodels,

therearemanymodelscontributedby theusercommunity. Thesecontributedmodelswere

historicallykeptin anftp directoryunderthelabel"anarchy." Userswho wouldventureinto

theanarchywould find somesimple,interestingmodels,andsomeverycomplicated,hard� to�

understandmodels.

TheASM codebaseis oneof thedifficult ones.Theoriginalmodelwaswritten in the

languageObjective� C for theNext operatingsystem.Thepassingof theNextoperating

systemmadeacasualtyof theoriginal stockmarketmodel. Thereis, however,a packageof

codeavailableunderthename"sfsm,"which is ascloseto theoriginal codeaswe arelikely

to get. Thesfsmcodeis theessenceof theoriginalmodel,exceptthatthegraphicalinterface

whichreliedon theNext librarieshasbeenremoved.With only slight modificationto work

aroundsomeconflictsdueto changesin theGNU C library, thesfsmcodecanbecompiled

with a currentversionof gcc(theGnuCompilerCollection;http://www.gnu.

org/directory/gcc.html).

A glancethroughthesfsmcoderevealsthat,althoughit is written in Objective C, it is

in factordinaryC thatis doingmostof thework. (Objective C is a supersetof ordinaryC, so

anythingthatcanbedonein a C programcanbehousedinsideanObjective� C programas

well.) Theimportanceof thedistinctionis in theextentto which anobject � oriented

frameworkis used.Thesfsmis object� orientedto theextentthatthesignificantactorsin the

modelarehousedin separatefiles andwhenthesimulationruns,objectsbuilt from those

classesareinstantiated.Thedesignon themacrolevel is excellent,separatingthe

functionalityof thecomponentsinto clearlydemarcatedcontainers.Onefinds files to

describethebehaviorof stockinvestors(mostimportantly,thebitstringforecastingagent:

bfagent),thedividendgenerator(dividend),a specialistwho managesthemarket(speclist),a

world objectthatcollectsdataandmakesit availableto agentswhenasked(world), and

2

Page 4: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

variousotherclassesthatorchestratetheinteractionof theseclasses.However,insidethese

largishfiles, thedesignis decidedlymorelike C thanObjective C. Eachbitstringforecasting

agentmaintainsa populationof forecastsandtriesto perfectthemovertime,but eachforecast

is not keptasaseparateobject. Rather,thereareplentyof instancesof dynamicmemory

allocationandpointerusage.

Variousmembersof theoriginalASM team,alongwith staffmembersandaninternat

theSantaFeInstitute,setto thetaskof revisingthesfsmmodelto run with theSwarm

libraries. Thereareanumberof benefitsto doingthis. First,Swarmprovidesasetof well �

testedroutinesfor thingsasmundaneasrandomnumbergenerationandschedulingof agent

actions.Second,Swarmhasa built � in graphicalinterface,includinggraphingcapabilities.

Sincethegraphicalinterfacewaslost with thedemiseof theNextsystem,this wasan

importantconsideration.In orderto put thesfsmcodeinto a Swarmframework,a significant

amountof work wasrequiredto createthestandardmulti � levelSwarmsimulationin whicha

top level swarmobjectobserveseventsandcreatesgraphs,while amiddlelevel modelSwarm

managestheactualcreationandinteractionof thesubstantivelyimportantactorsin themodel.

During1998and1999,a preliminaryversionof theSwarmASM wasavailablein the

"anarchy"ftp directory. SinceI wasa relativeneophytein theworld of Swarm,I lookedon

thecodein a stateof wonderandamazement.I couldnot imaginehowall of this detailcould

possiblyfit togetherinto a coherentpattern. I wasconstantlyaskingpeoplein theSwarm

communityaboutthestatusof thatcodebecauseI wantedto seeabig, socialsciencemodel

thatusedSwarm. Manyof theSwarmcodeexamplesareaboutbugsandotherecological

critters.Therewerenot asmanyexamplesthatdealtwith socialscienceresearch.I thought

theASM couldserveanimportanteducationalrole.

In April, 2000,theSantaFeInstituteannouncedthereleaseof ASM � 2.0. ASM � 2.0

packageincludesthreeelements. First, thereis a copyof theObjective� C versioncalled

3

Page 5: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

sfsm,which appearsin a directorycalledASM_OBJC. Second,thereis theSwarmversion,

whichappearsin thedirectorycalledASM � 2.0. Third, thereis aMicrosoft Worddocument

by BrandonWeber,who wasthethepersonmostcloselyin contactwith theactualcodingof

therevisionof theartificial stockmarket. Theseparateelementsof thatreleaseareavailable

(ftp://ftp.santafe.edu/pub/swarm/src/users� contrib/anarchy/ASM/).

During thesemesterof theASM � 2.0release,I wasteachingagraduateseminaron

agent� basedmodeling.I waseagerto refermy students,manyof whomwerein financeand

economics,to theASM code. By thattime,my codingskills hadimprovedquitea bit (I was

anauthorof theSwarm User Guide (JohnsonandLancaster,2000)andhadwrittenseveral

workingexamplemodels).After reviewingtheASM � 2.0release,I wasableto seethatsome

changescouldbemadeto makethis codeeasierto readandmodify. Somepartsof thecode

wereneedlesslycomplicatedandthereweremanydetailsthatweredifficult to explainto

students.

Perhapsnot theleastof my concernswasthatthecode,asdistributed,hadsomekind

of mistakein it thatcausedthedynamicbehaviorof themodelto deviatefrom theexpected

pattern,thepatternonewould expectfrom thedescriptionof themodelin Palmer,etal., or

from runsof thesfsmmodel. In Figure1, thereis a"screenshot"of a run of theASM � 2.0

code. Notethatin thebottompanel,themarketpricegoeslow andsaysfar belowtherisk

neutralprice. Onewould expectthepriceduringthesimulationto morecloselymirror the

risk neutralprice.

I decidedto startanopeninitiative to reviseandupdatetheASM codebase,not only

to find thesourceof thatproblem,butalsoto enhancethecodeasa teachingexampleandas

anillustrationof thepossibilitiesof theSwarmtoolkit. Thereis anabsolutelygreatresource

for opensourcecodedevelopmentknownasSourceforge.Sponsoredby VA Linux,

Sourceforgeofferswebpagesandcoderepositories(usingCVS,theconcurrentversion

4

Page 6: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

system)to peoplewhowantto developcodethatis opento inspectionandfreeusage.The

Sourceforgeadministratorsgrantedmy applicationfor theArtStkMkt projectanda page

calledhttp://ArtStkMkt.sourceforge.net.Peoplewhowantto readaboutthestatusof the

revisionsor checkoutcodefrom theCVS archivecanvisit thatsite.

After workingon theASM codefor slightly morethanoneyear,I haveannouncedthe

releaseof ASM � 2.2,a significantrevision/enhancement/clarificationof theASM � 2.0code

base.This releasesignalstheintroductionof severalnewclasses,thesimplificationof the

usageof Swarm'sschedulingfacilities,anda radicalsimplificationandredesignof thecode

thatgovernstheway thebitstringforecastingagentsbehave.Midway throughtherevisions,

the"bug" illustratedin Figure1 wasdiscoveredandexterminated.In Figure2, onecanfind

ascreenshotof thecorrectedmodelthatwasrununderthesameconditions.

In thisessay,theintentionis not to give a comprehensivereviewof all thechanges

thatoccurredin theASM code. Rather,usingtheASM revisionasanexample,thereare

somegeneralpointsto bemadeaboutthemodel� writing experience.Peoplewho are

interestedin thedetailsof therevisionarefreeto checkout thecodefrom theCVS archive

andusethefacilities of thecvsprogramto trackthroughtheexacthistoryof therevisions.

OntheArtStkMkt website,thereis anhtml versionof thedocumentationfor thenewversion,

which includesanoverviewof themodelanddetaileddocumentationon all of theclasses.

Thecodeincludesa ChangelogandtheREADME file insidethedistributioncontains

periodicupdates.Onecanalsolook at theperiodiccode patchesthathavebeenissuedwhich

includetheexactchangesneededto movefrom oneeditionto another.

Lessonsto takeawayfrom theASM experience

Thecommentshereareorganizedin orderof decreasinggenerality. Theintentionis

to speakto issuesthatwill affectall kindsof agent� basedmodelingprojects,not justmodels

of stockmarkets.HavingtheASM codehandyfor reference,however,givesussomething

5

Page 7: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

concreteto talk about.

Theoverallmessageis thatobject � orientation is good. Wherepossible,models

shouldbedesignedsothattheyarecomposedof separate,isolatedpiecesthatfit togetherin

understandableways. Thismakesit easierto extendmodels,to find bugs,andto

communicatewith oneanother.In severalof thespecificsto beexplainedbelow,it is also

arguedthattheisolationandconfinementof calculationswithin particularobjects, functions,

or methodsis important. Globalvariablesarebadandshouldbeavoided.

Hint #1.Replacestructswith objects.

A C structis a groupof variables.An objectis alsoagroupof variables,calledinstance

variables,but it hasanadditionalcapability. An objectis createdasaninstanceof a class,

andbecauseit is derivedfrom a class,thenanobjectcanexecutemethods.(Thetermmethod

is theobject� orientedterminologyfor a function.) In additionto storingvaluesinsidean

object,onecanalsotell anobjectto makecalculations.This is a wayof "hiding" a lot of

work andgettingit donein a dependableway insideseparateobjects.

In theASM � 2.0code,thebuyingandsellingof stocksis doneby theBFagentclass

(BF standsfor bitstringforecasting).Theheaderfile BFagent.hdeclarestwo largestructs,

BF_fcast andBFparams. In ASM � 2.2,severalclasseswerecreatedto containtheinformation

andthesestructswereremoved.Thestruct BF_fast wasreplacedwith theobjectBFCast.

TheBFCast objectis quitea complicatedthingbecauseit doesthework of takingcertain

piecesof theworld into accountandthenformulatinga newforecastof thestock'sprice. That

work wassocomplicated,in fact, thatanothersmallerclass,calledBitVector, wascreatedto

handlethelowestlevel detailsof keepingrecordson thebits of information. Similarly, the

structBFparams wasreplacedwith aclassBFParams.

As anexampleof thesimplificationthatcomeswhenobjectsareintroduced,consider

thecodein ASM � 2.0'sfile BFagent.m.Whena forecast(in this case,apointerto a struct

6

Page 8: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

namedfptr) is to beupdated,thevalueis explicitly calculatedby retrievingsomevaluesfrom

theparametersstruct(pp) andfptr itself:

fptr � >specfactor= 1.0/(1.0+ pp� >bitcost*fptr� >specificity);

All of this calculationcanbedoneinsidetheobjectitself by a methodcalleupdateSpecfactor.

Then,wheneveronewantsthatcalculationto takeplace,onetells theforecastto do the

calculation. In Objective� C, thatlookslike:

[aForecastupdateSpecfactor];

If datamustbeupdatedin severaldifferentplaces,this methodcanbecalledin eachplace.

Any changesneededin theupdatingprocedurecanbetakencareof insidetheforecast

object'supdateSpecfactor method,ratherthanin severalpartsof BFagent.

Perhapsthemostimportantexampleof introducingclassesto isolatecalculationsis

theBitVector class.Thebitstringforecastobjects(instancesof BFCast) monitorup to 80

dichotomousvariablesin thestockmarketworld. Thesebits in theworld indicatethatthe

priceis risingor declining,or thatthemovingaverageof dividendsis risingor declining,and

soforth. Eachforecastcanmonitorsomeor all of thesebits,andsoeachforecasthasto

maintaina recordof which bits it is monitoring. This is donein ASM � 2.0with explicit bit

mathin thefile BFagent.m.(A "bit" is a0 or 1 value.Everyintegerhasa representationin

binary(base 2) format,a stringof 0'sand1's. Hence,eachintegercancompactlystorea lot

of bits.) Thatmakesthecodeextremelydifficult to read,evenif oneenjoysbit operations

(andI don't). In ASM ! 2.2,bit mathhasbeenconfinedto theBitVector class,andeachof the

forecastobjectsis createdwith aBitVector instanceinsideit. Changesto theBitVector values

aredonethroughaninterfacewith meaningful(comparativelyspeaking,at least)method

names. TheBFagentsneverneedto preciselymodify theindividual bitsbecauseall of that

detailis hiddeninsidetheimplementationof theBFCast andBitVector classes.

Hint #2.Keepthescopeof all variablesassmallaspossible.

7

Page 9: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

This is astandardpieceof adviceto studentsof programming(KernighanandPike,

1999,p. 104),but it is easyto misstheimportanceof it. Scopeis theareain which a variable

is visible. A globalvariableis visible throughoutaprogram,aninstancevariableis visible

within anobject,anda local variableis visible within a methodonly. Whenanobjectis

small,thereis someconveniencein keepinga singleinstancevariable,thevalueof which can

beeasilyaccessedby severaldifferentmethods,eitherfor readingor writing. Theproblemis

that,astheclassgrows,thenonemaymakemistakesthataccidentallychangethevalueof

thatvariable. Programsthatusevariableswith largescopearederisivelycalled"spaghetti

code"becausea"yank" ononestrandcanhaveunexpectedimplicationsthroughout.

Insteadof usinga singlevariablethatis accessedin severalmethods,it is oftenbetter

to revisethemethodssothattheytakeexplicit argumentsandexplicitly returnvalues,without

relyingoneasyaccessto variablesfrom a higherscope.In theASM " 2.2,for example,there

aresignificantchangesin themethodsthatcontroltheway theagentsconductthegenetic

algorithmthatoptimizestheir forecasts.For instance,thefunctiondeclaredin ASM # 2.0 like

so:

staticvoid Generalize(structBF_fcast*fcast)

assumesit hasaccessto aglobalvariablecalledavstrength. To preventthepossibilitythatthe

valueof avstrengthmightbeaccidentallyalteredsomewhere,theGeneralizemethodof

ASM # 2.2nowtakesasoneof its inputargumentsthevalueof avstrength:

# (void) Generalize:list AvgStrength:(double)avgstrength

Usingthis approach,thereis no longeraneedfor a globalvariableavstrength.

Oneof the risky practicesthatis fairly widespreadthroughouttheASM codeis the

useof staticvariables.A staticvariablein Objective$ C is a variablethatis sharedby all

instancesof a class. It is a usefulapproachif therereally is a singlevaluethatis supposedto

beavailablefor all instancesof a class. However,sometimesstaticvariablesareusedfor

8

Page 10: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

convenience,sayfor "workspace"calculations.Theusageof staticvariablesis inspiredby

thedesireto savememory,sinceroomfor only a singlepieceof memoryis needed.If there

arethousandsof instancesof aclass,thesavingsof memorycanbesignificant,andevenon a

newcomputerfor which memoryis cheap,thesavingsmightbeworthwhile. But this is not

withoutdanger.Any instanceof theclasscanchangethevalueof a staticvariable,andin a

complicatedsimulation,onecancreateveryhard% to% find bugsby usingstaticvariables.

Manyof thechangesthathavebeenmadein ASM & 2.2werenot responsesto

problems,but ratherstepsto preventfutureaccidentsor to resolvestudentquestionsbefore

theyarise. For example,in theASMObserverSwarm.hfile, therewasaninstancevariable:

double*position;

Thispointsto a locationin memorywhich is allocatedin ASMObserverSwarm.m.The

initializationcreatedapermanent,dynamicallyallocatedpieceof memorylike so:

position= xcalloc(numagents,sizeof(double));

Thatpieceof memoryis usedduringeachiterationin theupdateHistos method,wherethe

holdingsof theagentsarecollectedinto thatarrayandthenpassedalongto a chartingobject

thattheauthorsreferto asahistogram(but it ratherappearsto beabarchart).

In ASM ' 2.2,theinstancevariableposition is eliminated,asis theneedto dynamically

allocatememory. Instead,it is possibleto rewritetheupdateHistos methodwith a localarray

positions which is createdto hold informationfrom justasmanyagentsasarecurrentlyin the

model'slist of agents.First thenumberof agentsis retrieved,thentheposition arrayis

created.

int numagents= [[asmModelSwarmgetAgentList]getCount];

doubleposition[numagents];

Theadvantageof this approachis not just thatit keepsthescopeto theabsoluteminimumand

avoidstheuseof dynamicallyallocatedmemory,but it alsomeansthatthechartobjectcanbe

9

Page 11: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

usedto chartthefortunesof anagentlist whichchangesin sizeduringthesimulation. In

ASM ( 2.0,thereis no flexibility to accommodatechangein thenumberof agents.

Hint #3. Useacollectionslibrary.

A collectionis acontainer,a “thing” thatcanhaveobjectsaddedto it andremoved

from it. TheJavalanguageis distributedwith a largelibrary of collections,rangingfrom flat

(unordered)lists to sortedsets. TheC, C++,andObjective) C languagesarenotdistributed

with collectionslibraries,but therearecollectionslibrariesthatcanbeusedwith these

languages.A goodopensourcecollectionslibrary for C canbefoundin theglib package

(http://www.gtk.org).For C++, thereis theStandardTemplateLibrary andfor Objective* C

modelstheSwarmtoolkit hasa collectionslibrary (or onecouldalsousetherecentlyreleased

GNUsteptoolkit: http://www.GNUstep.org).

If onedoesnot wantto usea collectionslibrary, thenwhat? A look at theASM + 2.0

codewill giveanexampleof thealternative:usedynamicallyallocatedmemoryandpointer

math. (Readerswho donot nowaboutmemoryallocationin C mightconsultoneof the

standardtexts,suchas(KernighanandRitchie,1988,or Kochan,1994)). In Kochan(1994,p.

255),thereis a presentationdescribinghowonecancreatea linked list in thestylethatis used

in ASM , 2.0. A C structis usedto containtheinformationabouta “thing,” andonepieceof

informationin thestructis apointerto thenext“thing” in thecollection. As long asonehas

accessto onestruct,thenonecanalwaysfind thenextone.

Theexplicit usageof structsandmemorypointersis not somuchwrongasit is prone

to error. To correctlymakeaseriesof calculations,onefor eachstruct, a sequenceof

relativelydetailedstepsmustbetaken. In C, thereis no warningif onegrabsanincorrect

segmentof memorywhile conductingsuchanexercise.

Usinga containerlibrary, themaintenanceandtraversalof collectionsis converted

into a simpler,morereliableprocess.If onehasanobject,insertingit into thecollection

10

Page 12: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

usuallyrequiresa simplecommandlike "add" or "put." All of thecollectionslibrariesthatI

haveseenincludea standardsetof toolsfor steppingthroughthecollectionwith aniterator.

In Swarm,theinteratorfor acollectionis oftencalledan"index," andonesimplyasksa

containerto createanindexwith a begin statementandtheneachsuccessiveelementof the

collectionis foundby askingtheindexfor the "next" element.

In Table1, onecanfind acomparisonof thetwo approachesto maintainingaset

forecasts.In theleft, codefrom ASM - 2.0 is presented,which showsthedynamicallocation

of achunkof memory (enoughto holdpointersto numfcasts structs),andthena for loopover

thestructssetstheir initial values.After thearrayof structsis set,thenthis exampleshows

howonecantraverseovertheelementsin orderto computetheaverageof a variablecalled

specificity.

On theright sideof Table1, themoreobject. orientedversionof this exerciseis shown

from ASM . 2.2. Insteadof treatingtheelementsasstructs,theelementsarenow objectsfrom

theclassBFCast. Thecreationandinitializationof thoseobjectsis segregatedinto a method

in Bfagent calledcreateNewForecast, andanytimea newforecastis needed,thatmethodis

used.Following thatapproacheliminatestherisk thatonemight forgetto setall of the

numericalvaluescorrectlywhendoingtheinitialization in themiddleof theothermethods,as

is doneon theleft handside. On theright handside,onecanseethattheobjectsareput into a

collectioncalledfcastList, andwhenit is time to computeaveragespecificity,aniterator

objectcalledindex is obtainedfrom thefcastList, andthena looprepeatedlyasksfor thenext

elementof thelist.

Themainpoint of thissectionis thatstoringobjectsinto a collectionis easierandless

error/ pronethantheotherway. Thereis anotherpoint to recommendit, however. It would

bea bit difficult to addnewforecastobjectsif theold approachwerefollowed. Theamount

of memoryallocatedis fixed, andsocreatingmore"headroom"in thecollectionwould

11

Page 13: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

requirefurtherexplicit work to allocatememory. Doing thatwould significantlycomplicate

thepointermaththatis usedto transversethecollection. On theotherhand,mostcollections

librarieswill makeit easyto increasethesizeof a collection. A list classwill simply grow

wheneveranobjectis added.In theTable1 example,aSwarmArray collectionis used,

mostlybecausetheretrievalof specificitemsis fasterwith thanclassthanin anunstructured

list. But theSwarmArray hasa methodwhich allowsit to beresized.Of course,thesame

work getsdoneif oneuseseitherapproach.Thedifferenceis that,in thelatterapproachthe

work is doneautomatically,insidethe(hidden!)confinesof acollectionslibrary. Thework is

donein awell 0 tested,multipurposecollectionslibrary, ratherthanin themiddleof a

substantiveapplication. This freestheuserfrom a significantamountof detailedwork.

Hint #4.Think aboutparametermanagement.

TheSwarmSimulationSystemhasfeaturesin it for creatingobjectsandsettingtheir initial

valuesto particularparametervalues.Theinputparametersarekeptin separatefiles, eitherin

LISP formator theNationalCenterfor SupercomputingApplication's (NCSA)HDF5 data

format(http://hdf.ncsa.uiuc.edu/index.html).In ASM 1 2.2,theLISP approachhasbeentaken,

andthedefaultsettingsfor themodelarein a text file calledasm.scm. (Theextension.scm

refersto theSchemelanguage,animplementationof LISP.)

Onepoint of emphasisis to separatetheadjustmentof parametervaluesfrom the

editingof thecodeitself. If thenumericalvaluesof theparametersareburiedinsidea file that

includesC code,thenit is somewhatinconvenientto dig in, find values,andadjustthem.

Furthermore,onemustrecompilethemodelin orderto run it. It is muchnicerto edit a

separateparameterfile andrun themodelagainwithout recompiling.

Thenewparameterclassesin ASM 2 2.2areBFParamsandASMModelParams.The

BFParamsclasscontainsthedefaultsettingsthatgovernthecreationof bitstringforecasting

agentsandthebitstringforecaststhemselves.Eachagentmaintainsmanyforecasts,

12

Page 14: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

repeatedlycomparingtheirquality in predictingthestockprice. Whenanobjectis created

from theBFCastclass,theBfagent'smethodcreateNewForecast is responsiblefor reading

valuesof of theBFParamsobjectandsettingthemin thenewforecast.Becauseof this

object3 orienteddesign,it is possibleto allow changesin BFParamsovertime,possibly

reflectingtheexperienceof theagent.

Anotherbig changein ASM 4 2.2 is theseparateparameterclassfor theoverallmodel,

ASMModelParams.This affordsasignificantsimplificationof themaintenanceof thecode.

This is sobecauseSwarmmodelsaretypically written to runeitherin thegraphical(GUI)

modeor in abatchmode(withoutanyGUI interaction).Themodelitself is supposedto be

thesame,of course,but thetop level objectwhich managesthesimulationwill differ. In the

GUI version,for example,thetop level classis calledASMObserverSwarm,while in the

batch/noninteractiveversionit is calledASMBatchSwarm.BecausetheASMModelParams

arebrokenoff into aseparateclass,theneitherof thesetop level modelscanaccessthesame

setof parameters.

In ASM 5 2.2,all parametermanagementchoresaregatheredtogetherunderthe

umbrellaof theParametersclass. Parametersis subclassedfrom SwarmsArguments_cclass,

andtheendresultof that is thatSwarm'sdefaultobjectarguments is customizedto fit the

application.Whena simulationmodelbegins,thefirst thing thathappensis thecreationof a

Parametersobject,andwhenit is created,it spawnsinstancesof ASMModelParamsand

BFParams,sothosevaluesarereadywhentheotherobjectsarecreated.

Thinkingaheadto theendof theproject,whenonewantsto runa modeloverandover

again,or exploretheimpactof changesin conditions,it is importantto notethatthe

Parametersclasscanalsohandlecommandline parameters.Whenthemodelruns,the

commandline optionsaresorted,andtheparameterobjectscanbetold to adjusttheir settings.

If a programis ableto acceptcommandline parameters,thenthereareeasy

13

Page 15: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

approachesthatcanbeusedto generatemanyrunsof themodel. Themostsophisticated

approachof which I amawareis TedBelding'sDroneprogram(http://Drone.sourceforge.net),

whichhashigh poweredcapabilitiesto manageparametersweepsanddistributejobsacross

networks.Dronerelieson theExpectpackage,andwehavehadsometroublebuilding that

for MS Windowssystems(butnot onUnix/Linux), soI preparedaPerlscriptthatcanrun

parametersweepsaswell (http://lark.cc.ukans.

edu/~pauljohn/Swarm/MySwarmCode/replicator.pl),but it will not distributejobsarounda

networktheway Dronecan.

Hint #5.Considerstrategiesfor dataoutput.

In thepast,I haveusedC andthestandardmethodsof creatingoutputfiles in text

format. This is convenientandthereis alwaysconfidencethattheresultswill beusefulacross

avarietyof programs.In theASM 6 2.0Output class,onecanfind thecodethatcausesa

simulationto write plainasciivaluesinto a file. This is oneof theapproachesillustratedin

ASM 7 2.2. Thefile's nameis stampedwith thetime anddate. Model runsin batchmodewill

automaticallyturn7 on thedatawriting facilities,but runsin thegraphicalinterfacewill not

write dataunlesstheuserpushesa buttonthatturnson datawriting.

Therearesomeshortcomingsto rawtext output,however,oneof which is thelack of

precisionin real8 valuednumbers.MarcusDanielsof theSantaFeInstituteandtheSwarm

DevelopmentGrouphasintegratedtheNationalCenterfor SupercomputingApplication's

HDF5dataformatinto Swarm,sothatdatacanbesavedin a compressedformatthatretains

precision.Mr. Danielshasalsowrittencodeto supportHDF5usagefor thefreesoftware

statisticalprogramR (IhakaandGentleman,1996;seehttp://www.R9 project.org), which is

free,opensource,increasinglyconvenient,highpowered,andfun9 to9 usetool for creating

graphsandestimatingmodels.OnecangenerateHDF5 files from a Swarmsimulation,read

theminto R, analyzethedata,andoutputthedatain otherformatsif desired.

14

Page 16: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

In ASM : 2.2,thesecapabilitieshavebeenput to use. In orderto takeadvantageof

them,however,oneneedsa fairly neweditionof Swarm,eitheradevelopmentsnapshotof

Swarmfrom July,2001or later,or a releaseversionof Swarm; 2.2. Therearetwo kindsof

hdf5outputthatcanbesavedin ASM < 2.2. First, thereis a smallHDF5 file that includesthe

time< seriesof thevariablesprice, dividend, andvolume. Thatfile is createdthroughSwarm's

EZGraphclass,which is typically usedto showgraphson thescreen,but in this caseit saves

valuesinto a file ratherthanon thescreen.

Theotherkind of outputthattheSwarmlibrariescangenerateis typically called

"serialization" information. Serializationmeanstheability to savethestateof anobjectinto

a file andthen,at a futuretime, re= createthesameobject.(Peoplewho write computergames

have,of course,masteredtheartof serialization.)Swarmcanoutputthecontentsof whole

objectsin eithera LISP formator HDF5. In ASM > 2.2,wearenot interestedin a full

serialization,though,andwecansavesometime/storagespaceby only savinga shallowcopy

of thevariousobjects.A shallowcopyrecordsthevariablesinsideanobject,butnot the

objectsthatit haswithin it. In ASM ? 2.2,thedefaultcodewill write out aLISP formattedtext

file thatincludesthedataof theSpecialistobjectandtheWorld object. At theendof a run,

oneshouldseefiles like:

output.dataWed_Oct_24_11_30_18_2001

swarmDataArchiveWed_Oct_24_11_30_18_2001.scm

hdfGraphWed_Oct_24_11_30_18_2001.hdf

If, insteadof theLISP formattedswarmDataArchivefile, onewantsHDF5formattedoutput,

it canbedonewith eithera C preprocessorflag or anobviouschangein thefile Output.m.

Theusageof theLISParchiverin this examplesignificantlyslowsdownthespeedwith

which themodelrunsbecauseit archivesa greatdealof information,muchof which is not

15

Page 17: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

needed.

Conclusion

While workingon theASM code,severalissuesaboutmodel@ buildingandprogramming

cameinto focus. It is betterto encapsulateinformationandretrieveit whennecessarythanit

is to leaveinformationsitting aboutwhereit canbeaccidentallyaltered. It is betterto use

containerclassesthanto do mathwith pointers. It is a goodideato designasimulationmodel

with aneyetowardtheendproduct,bothin termsof exploringparametercombinationsand

dataoutput.

All of theseobservationsflow togetherinto thecontentionthatobject A oriented

modeling is good. Or, perhapsin themorecynicalstyleof WinstonChurchill, "ObjectB

orientedcodingis the'worst' form of modelB building, exceptall thoseothersthathavebeen

tried from time to time." Onecanreadilycriticize thestatusof ASM B 2.2becausethereare

thingsthatcouldbefurtherisolatedinto specificclassesof their own. Therearecasesin

which thescopeof somevariablescouldbemadesmaller. I havestoppedat this stagefor a

releasebecausethechangeshavebeenquitesubstantial,andfurtherrevisionis likely to

requiremoresignificantbreaksin theconceptualalignmentof thecode. I hopethatpeople

whowantto learnaboutSwarmin particular,or agentC basedmodelingin general,might

benefitfrom acomparisonof thevariousversionsof theArtificial StockMarket.

16

Page 18: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

References

Johnson,PaulE, andAlex Lancaster.2000.The Swarm User Guide. Http://www.santafe.edu/projects/swarm/swarmdocs/userbook/userbook.html

Ihaka,Ross,andRobertGentleman.1996. R: A languagefor dataanalysisandgraphics.Journal of Computational and Graphical Statistics. 5(3):299D 314

Kernighan,BrianW. andRobPike.1999.The Practice of Programming. Reading,MA:AddisonD Wesley.

Kernighan,BrianW. andDennisW. Ritchie.1988.The C Programming Language.EnglewoodCliffs: PrenticeHall.

Kochan,StephenG. 1994.Programming in ANSI C, RevisedEdition. Indianapolis,IN:SAMSPublishing.

LeBaron,Blake.2000.Agentbasedcomputationalfinance:Suggestedreadingsandearlyresearch,Journalof EconomicDynamicsandControl,24:679E 702.

Minar, Nelson,RogerBurkhart,ChrisLangton,andManorAskenazi.1996.TheSwarmSimulationSystem:A toolkit for buildingmulti F agentsimulations. SantaFeInstituteWorkingPaper96F 06F 042,SantaFe,NM. (availableathttp://www.swarm.org/archive/overview.ps)

Palmer,R.G,W. Brian Arthur, JohnH. Holland,BlakeLeBaron,andPaulTaylor.1994.Artificial economiclife: a simplemodelof a stockmarket.Physica D 75:264G 274.

17

Page 19: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

Table1CollectionsUsagein ASM G 2.0andASM G 2.2

//ExampleCodefrom ASM G 2.0(BFagent.m):// Declareapointerto spacefor BF_fcaststructstructBF_fcast*fcast;// Allocatememoryfor forecasts

fcast= calloc(pG >numfcasts,sizeof(structBF_fcast));if(!fcast)printf(“Therewasanerrorallocatingspace

for fcast.”);

structBF_fcast*fptr, *topfptr;

// Initialize theforecaststopfptr= fcast+ pH >numfcasts;for (fptr = fcast;fptr < topfptr; fptr++){fptr H >forecast= 0.0;fptr H >lforecast= global_mean;fptr H >count= 0;fptr H >lastactive= 1;fptr H >specificity= 0;fptr H >next= fptr H >lnext= NULL;

/* Allocatespacefor this forecast’sconditionsout of totalallocation*/

fptr H >conditions= conditions;conditions+= condwords;

/* Initialise all conditionsto don't care/cond= fptr I >conditions;for (word = 0; word < condwords;word+)cond[word]= 0;

/* Add nonI zerobitsasspecifiedbyprobabilities*/

if(fptr!=fcast) /* protectrule0 */

/* Computeaveragespecificity*/specificity= 0;for (fptr = fcast;fptr < topfptr; fptr++){specificity+= fptr J >specificity;

}avspecificity= ((double)specificity)/pJ

>numfcasts;}

//ASM J 2.2equivalent://CreateArray to hold forecastobjectsfcastList=[Arraycreate:[self getZone]

setCount:numfcasts];

// CreateForecastobjects,addto fcastList// The“know nothing” forecastis first[fcastListatOffset:0 put: [self

createNewForecast]];//createrestof forecastswith randomconditionsfor ( i = 1; i < numfcasts;i++){id aForecast=[self createNewForecast];

//initialize[self setConditionsRandomly:aForecast];[fcastListatOffset:i put:aForecast];}

/* Computeaveragespecificity*/

index= [ fcastListbegin:[self getZone]];for ( aForecast= [indexnext];

[indexgetLoc]== Member;aForecast= [index next] )

{sumspecificity+= [aForecast

getSpecificity];}

avspecificity=(double) sumspecificity/(double)

numfcasts;[indexdrop];

}

18

Page 20: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

Figure1Screenshotof ASM K 2.0

19

Page 21: based model. A new revision of can be illustrated with the ... · sfsm, which appears in a directory called ASM_OBJC. Second, there is the Swarm version, which appears in the directory

Figure2Screenshotof ASM K 2.2

20