04 TpLab V2.07

04 TpLab V2.07 preview image

1 collaborator

121210_portrait_of_garvin Garvin Boyle (Author)

Tags

biophysical economics 

Tagged by Garvin Boyle about 2 years ago

ecological economics 

Tagged by Garvin Boyle about 2 years ago

maximum power principle 

Tagged by Garvin Boyle about 2 years ago

sustainability 

Tagged by Garvin Boyle about 2 years ago

sustainable economics 

Tagged by Garvin Boyle about 2 years ago

Model group Sustainability | Visible to everyone | Changeable by group members (Sustainability)
Model was written in NetLogo 5.0.5 • Viewed 289 times • Downloaded 9 times • Run 0 times
Download the '04 TpLab V2.07' modelDownload this modelEmbed this model

Do you have questions or comments about this model? Ask them here! (You'll first need to log in.)


Info tab cannot be displayed because of an encoding error

Comments and Questions

Please start the discussion about this model! (You'll first need to log in.)

Click to Run Model

;;-----------------------------------------------------------------------------|
;; SECTION A – AUTHOR IDENTIFICATION AND CODE ABSTRACT
;;-----------------------------------------------------------------------------|
;;
;; File Name: TpLab_V2.07.nlogo
;; By Orrery Software
;; Dated: 2017-03-13
;; Author contact:
;;   Garvin H Boyle
;;   orrery@rogers.com
;;   http://orrery-software.webs.com

;; As the author, I welcome questions, discussion of issues and suggestions
;;   for improvements.

;;-----------------------------------------------------------------------------|
;; This TpLab app is a laboratory in which students can study aspects 
;;   of the phenomenon of Teleological Pruning (TP) as described in my 
;;   associated diary notes.

;; In this model, nrg arrives in a steady stream from the Sun and is captured
;;   in plants that produce fruit, which appears randomly in dales in the 
;;   forest.  Nomadic seekers roaming the forest according to their own 
;;   heuristic strategy seek the dales currently having food, and harvest it.
;;   The strategies start as ineffective bland heuristics, and evolve to be 
;;   much more sophisticated. In the most simple scenario, all actions are 
;;   instinctive.

;; But an ability to have beliefs influence behaviour is built into the genes,
;;   and belief systems evolve within the society.  These teleological belief
;;   systems can over-rule instinctual behaviour and stubbornly resist the
;;   need to change.  What happens to seekers that hold beliefs too tightly?
;;   Can the seekers of fruit become seekers of wisdom?  What happens to 
;;   societies that share a dilectic across multiple belief systems?

;;-----------------------------------------------------------------------------|
;; SECTION B – INITIAL DECLARATIONS OF GLOBALS AND BREEDS
;;-----------------------------------------------------------------------------|
;;
;;-----------------------------------------------------------------------------|
;; This program was developed on NetLogo Version 5.0.5
;;

;;-----------------------------------------------------------------------------|
;; code-determined global variables
globals
[
  ;; The version should be coded in this global variable to be included in
  ;;   output files.
  gs-Version
  
  ;; Note: Some global variables are declared inside of switches, sliders and 
  ;;   choosers when the interface is constructed and are not declared here.
  ;;   For the sake of clarity and completeness, they are noted here.
  
  ;; There are several uses of global variables:
  ;;  - Toggles (switches), and choosers which enable or disable features;
  ;;  - Numbers (in variables or sliders) which act as parameters;
  ;;  - Numbers (in variables) which collect data.
  ;;
  ;; Those marked as 'native Boolean' have values of true or false.
  ;; Those marked as 'numeric Boolean' have values of 1 or 0.
   
  ;;---------------------
  ;; MODELING ENVIRONMENT
  ;;---------------------
  
  ;; Assumed “Model Settings” on startup
  ;; horizontal wrap: on
  ;; vertical wrap: on
  ;; location of origin: centre
  ;; patch size: 5 pixels
  ;;-------------------------------------------------------------------------|
  ;; Implicit global variables due to model settings – patch locations
  ;; min-pxcor  -40
  ;; max-pxcor   40
  ;; min-pycor  -40
  ;; max-pycor   40
  
  ;;----------------------------
  ;; SCENARIO SELECTION CONTROLS
  ;;----------------------------
  
  ;; gs-scenario         ;; Chooser, string converts to a scenario number
  g-scenario-number      ;; scenario no., 0, 1 or 2; interp. of gs-scenario
  ;; Glogal enumeration variables - There are 3 scenarios possible.
  ge-scenario-0-beliefs  ;; scenario 0
  ge-scenario-8-beliefs  ;; scenario 1
  ge-scenario-8-shares   ;; scenario 2
  ge-scenario-n-tribes   ;; scenario 3
  
  ;; To halt a scenario at a pre-determined tick.
  ;; g-halt-at-tick      ;; Has it's own input box

  ;; Initialize the Pseudo Random Number Generator (PRNG).
  ;; g-use-this-seed     ;; Slider [1,1,100,7]

  ;;-----------------------------------------------
  ;; BIOPHYSICAL SUB-SYSTEM CONTROLS AND PARAMETERS
  ;;-----------------------------------------------

  ;; Biophyscial life function parameters, seekers.
  ;; g-c2-dat-parm  ;; The death age threshold
  ;; g-c2-det-parm  ;; The death nrg threshold
  ;; g-c2-rat-parm  ;; The reproductive age threshold
  ;; g-c2-ret-parm  ;; The reproductive nrg threshold
  ;; g-c2-epm-parm  ;; The nrg per move
  ;; g-c2-epa-parm  ;; The maximum nrg an agent may hold
  
  ;; The global list of possible heading deltas for moves.
  gl-heading-list  ;; List of heading deltas.
  gl-index-list    ;; List of numbers 0-7 in order
  gl-base-factors  ;; List of factors, used to mutate bases
  gl-colour-list   ;; List of colours, for agents and graphs
  
  ;; Nrg control variables
  ;; g-sun-nrg-per-tick    ;; Nrg arriving per tick [1000,40,12000,6000]
  ;; g-nrg-per-block       ;; Nrg deposited per Dale [1,1,100,40]
  ;; g-prob-of-deposit     ;; Prob nrg will be deposited [0,.001,1,.1]
  ;; g-heuristic-delta  ;; Amount added to heuristic on success [0,.001,2,1]
  ;; g-prob-of-genetic-mutation ;; As it says [0,.001,1,.1]
  ;; g-dt-for-eroi      ;; Delta time, used for EROI [40,40,400,40]

  ;; Nrg accounting variables
  g-nrg-in-sunshine     ;; Nrg held in the sunshine, to be placed as fruit.
  g-nrg-in-fruit        ;; Nrg held in the fruit.
  gl-nrg-by-belief      ;; Nrg held, seekers, by belief (a list of 8 numbers).
  g-total-nrg-in-system ;; Total nrg in the system.
  gl-nrg-by-tribe       ;; Nrg held, seekers, by tribe (a list of 10 numbers)
  
  ;; Nrg in Sunshine takeup accounting variables
  g-sun-takeup-maximum   ;; Maximum possible, = [empty-cells]x[size-of-deposit]
  g-sun-takeup-expected  ;; Expected, = [Max]x[prob-of-deposit] 
  g-sun-takeup-actual    ;; As measured

  ;; Biophyscial life function parameters, seekers.
  ;; g-no-of-tribes      ;; seekers, per belief type, at startup [1,1,100,5]
  ;; g-c1-belief-value   ;; Default value [0,.1,3,2]

  ;; Global enumeration (ge-) codes for cause of death.
  ge-cod-none
  ge-cod-hunger
  ge-cod-fission
  ge-cod-oldage

  ;; List to hold counts of cause of death.
  gl-causes-of-death-per-tick
  gl-causes-of-death-cumulative

  ;;-------------------------------------
  ;; END OF MODEL PARAMETERS AND CONTROLS
  ;;-------------------------------------
  
  ;;-------------------------------------
  ;; DATA COLLECTION AND DISPLAY CONTROLS
  ;;-------------------------------------
  
  ;; The following global variables are not model controls or paramaters, 
  ;;   but, rather, are variables used to collect data about the model 
  ;;   for display in the user interface, in some fashion (monitors or plots),
  ;;   or used to manage all of the debug routines and output.
  
  ;; Global enumeration (ge-) codes.
  ge-sinktype-discard   ;; Discarded sunlight
  ge-sinktype-move-EPM  ;; Seekers EPM
  ge-sinktype-die-DET   ;; Remaining nrg of seeker on death.
  ge-sinktype-die-DAT   ;; Remaining nrg of seeker on death.

  ;; SYSTEM-WIDE AGGREGATES
  ;; System of nrg sinks.
  gl-sinks-per-tick
  gl-sinks-cumulative

  ;;---------------------------------------------------------------------------|
  ;; The following agent sets, counts and averages are for data collection 
  ;;   and display in monitors and plots.
  
  ;; Global counts
  g-no-of-patches          ;; count of all patches
  g-no-of-dales            ;; count of all dales with fruit
  gl-no-of-seekers         ;; count of all seekers; list
  g-no-of-seekers          ;; count of all seekers
  g-no-with-this-belief    ;; count of those with this belief.
  
  ;; Global EROI/ETA system-wide calculations.
  g-sys-nrg-returned      ;; Total nrg returned within delta T.
  g-sys-nrg-invested      ;; Total nrg invested within delta T.
  g-sys-nrg-income        ;; Total nrg income (flowing) within delta T.
  gl-sys-nrg-returned     ;; List of changes.
  gl-sys-nrg-invested     ;; List of changes.
  g-sys-eroi              ;; System-wide EROI, per tick (=B/C).
  g-sys-eta               ;; System-wide ETA, per tick  =(B/I).

  ;; Averages for seekers
  g-ave-age               ;; age of seekers
  g-ave-nrg               ;; nrg of seekers
  g-ind-min-eroi          ;; min eroi of individual seekers = (B/C)
  g-ind-ave-eroi          ;; ave eroi of individual seekers = (B/C)
  g-ind-max-eroi          ;; max eroi of individual seekers = (B/C)
  g-ind-min-eta           ;; min eta of individual seekers  = (B/I)
  g-ind-ave-eta           ;; ave eta of individual seekers  = (B/I)
  g-ind-max-eta           ;; max eta of individual seekers  = (B/I)

  g-ave-C1-b0             ;; c1, base character, gene-0
  g-ave-C1-b1             ;; c1, base character, gene-1
  g-ave-C1-b2             ;; c1, base character, gene-2
  g-ave-C1-b3             ;; c1, base character, gene-3
  g-ave-C1-b4             ;; c1, base character, gene-4
  g-ave-C1-b5             ;; c1, base character, gene-5
  g-ave-C1-b6             ;; c1, base character, gene-6
  g-ave-C1-b7             ;; c1, base character, gene-7

  g-ave-C1-g0             ;; c1, genotypic character, gene-0
  g-ave-C1-g1             ;; c1, genotypic character, gene-1
  g-ave-C1-g2             ;; c1, genotypic character, gene-2
  g-ave-C1-g3             ;; c1, genotypic character, gene-3
  g-ave-C1-g4             ;; c1, genotypic character, gene-4
  g-ave-C1-g5             ;; c1, genotypic character, gene-5
  g-ave-C1-g6             ;; c1, genotypic character, gene-6
  g-ave-C1-g7             ;; c1, genotypic character, gene-7

  g-ave-C1-l0             ;; c1, learned character, gene-0
  g-ave-C1-l1             ;; c1, learned character, gene-1
  g-ave-C1-l2             ;; c1, learned character, gene-2
  g-ave-C1-l3             ;; c1, learned character, gene-3
  g-ave-C1-l4             ;; c1, learned character, gene-4
  g-ave-C1-l5             ;; c1, learnedores character, gene-5
  g-ave-C1-l6             ;; c1, learned character, gene-6
  g-ave-C1-l7             ;; c1, learned character, gene-7

  g-ave-C1-s0             ;; c1, strength character, gene-0
  g-ave-C1-s1             ;; c1, strength character, gene-1
  g-ave-C1-s2             ;; c1, strength character, gene-2
  g-ave-C1-s3             ;; c1, strength character, gene-3
  g-ave-C1-s4             ;; c1, strength character, gene-4
  g-ave-C1-s5             ;; c1, strength character, gene-5
  g-ave-C1-s6             ;; c1, strength character, gene-6
  g-ave-C1-s7             ;; c1, strength character, gene-7

  g-ave-C1-p0             ;; c1, phenotypic character, gene-0
  g-ave-C1-p1             ;; c1, phenotypic character, gene-1
  g-ave-C1-p2             ;; c1, phenotypic character, gene-2
  g-ave-C1-p3             ;; c1, phenotypic character, gene-3
  g-ave-C1-p4             ;; c1, phenotypic character, gene-4
  g-ave-C1-p5             ;; c1, phenotypic character, gene-5
  g-ave-C1-p6             ;; c1, phenotypic character, gene-6
  g-ave-C1-p7             ;; c1, phenotypic character, gene-7

  ;; SWITCHES - These are declared in the switch itself, and so are 
  ;;   commented out here.  They are all native Booleans, having values of
  ;;   true or false.
  ;; gb-plot-data              ;; Enables plotting

  ;; Other - built-in or declared implicitly in plot interface items
  ;; See each plot design dialogue.

  ;;---------------
  ;; DEBUG CONTROLS
  ;;---------------
  
  gb-debug-on                 ;; Numeric Boolean, opens debug log file, 0 or 1.
  gs-debug-status             ;; for monitor, '1 (On)' or '0 (Off)', 
  ;; gs-debug-step-chooser    ;; Chooser, used with gb-debug-flow-on
  gb-debug-flow-on            ;; Numeric Boolean, in association with chooser, 
  gs-log-file-name            ;; name of the debug log file
                              ;;   opens flow to log file
]

  ;;-------------------------------------
  ;; DEFINING PATCHES AND BREEDS
  ;;-------------------------------------
  
;;-----------------------------------------------------------------------------|
;; Attributes of patches
patches-own 
[
  ;; BUILT-IN ATTRIBUTES 
  ;; pxcor        ;; min-pxcor <= pxcor < max-pxcor
  ;; pycor        ;; min-pxcor <= pxcor < max-pxcor 
  ;; pcolor       ;; color of this patch ( 0 <= color < 140 ) 
  ;; plabel       ;; label of this patch
  ;; plabel-color ;; color of this patch's label ( 0 <= label-color < 140 ) 
   
  ;; TpLab-DETERMINED ATTRIBUTES
  fruit
]

;;-----------------------------------------------------------------------------|
;; Attributes of links
;; nil
;; I don't understand links and did not use any.

;;-----------------------------------------------------------------------------|
;; Turtles and breeds
breed [ seekers seeker ]

;;-----------------------------------------------------------------------------|
;; Attributes of seekers
seekers-own 
[
  ;; BUILT-IN ATTRIBUTES
  ;; who         ;; fixed id number
  ;; breed       ;; to which breed this turtle belongs [seeker]
  ;; heading     ;; 0 <= heading < 360, 0 = north
  ;; xcor        ;; min-pxcor <= xcor < max-pxcor
  ;; ycor        ;; min-pxcor <= xcor < max-pxcor
  ;; size        ;; size relative to a patch, default is 1
  ;; shape       ;; a shape chosen from the shape library
  ;; color       ;; color of this turtle ( 0 <= color < 140 )
  ;; pen-mode    ;; "up" or "down"
  ;; pen-size    ;; in pixels
  ;; hidden?     ;; true or false
  ;; label       ;; label of this turtle
  ;; label-color ;; color of this turtle's label ( 0 <= label-color < 140 )
  
  ;; USER-DETERMINED ATTRIBUTES
  ;; The chromosome 1 (c1) genes are used to distinguish behaviours.
  c1-bases    ;; c1 - list of 8 [B]ases for genes (P=B^(G+L))
  c1-genes    ;; c1 - list of 8 heading delta [G]enes
  c1-learn    ;; c1 - list of 8 [L]earned beliefs
  c1-stren    ;; c1 - list of 8 [S]trengths
  c1-pheno    ;; c1 - list of 8 [P]henotypic characters
  belief-affiliation ;; The belief (0-7) held by this agent.
  tribal-affiliation ;; the social affiliation of the seeker.
  
  ;; The chromosome 2 (C2) genes are static in this model.
  DAT         ;; Death Age Threshold.
  DET         ;; Death Energy Threshold.
  RAT         ;; Reproductive Age Threshold.
  RET         ;; Reproductive Energy Threshold.
  EPM         ;; Energy Per Move.
  EPA         ;; Maximum Energy Per Agent.
  
  ;; Other variable characteritics.
  mas-who              ;; serial number of parent agent.
  age                  ;; age of the agent in ticks
  nrg                  ;; nrg in this agent
  cause-of-death       ;; for statistical purposes
  b-is-ready-to-move      ;; 0 = no; 1 = ready to move
  b-is-ready-to-reproduce ;; mature (in age) and healthy (in nrg)
  b-is-ready-to-die       ;; old (in age) or starved (in nrg)
  
  ;; Variables for calculating personal EROI and ETA.
  nrg-returned         ;; Numerator of EROI - an aggregate = Benefits of (B/C)
  nrg-invested         ;; Denominator of EROI - an aggregate = Costs of (B/C)
  nrg-income           ;; Denominator of ETA  - an aggregate = Income of (B/I)
  eroi                 ;; Nrg returned on nrg invested = (B/C)
  eta                  ;; Nrg efficiency = (B/I) where Income = (B+C)
  l-er                 ;; A list of delta ERs
  l-ei                 ;; A list of delta EIs
  counter-eroi         ;; For tracking time up to delta T.
]

;;-----------------------------------------------------------------------------|
;; SECTION C – INITIALIZATION OR SETUP PROCEDURE( S )
;;-----------------------------------------------------------------------------|

;;-----------------------------------------------------------------------------|
;; The 'autostart' startup routine

to startup
  ;; This routine is to be executed by the observer.

  ;; The manual describes this routine as follows:
  ;; This procedure, if it exists, will be called when a model is first loaded
  ;;   in the NetLogo application.  Startup does not run when a model is run 
  ;;   headless from the command line, or by parallel BehaviorSpace.

  ;; On loading the model, the debug feature is always off.
  set gb-debug-on 0
  set gs-debug-status "0 (Off)"
  
  ;; On loading the model, the model, the choosers, switches and sliders are
  ;;   always reset to the values that are known to work by here invoking 
  ;;   the f-reset-default-parameters routine.  Only the chooser
  ;;   for the scenario is not reset.  The last saved 
  ;;   selection of scenario will therefore be persistant.  This allows the 
  ;;  'Reset Defaults' button to NOT reset the scenario number, but to reset 
  ;;  correct parameters for the scenario.
  f-reset-default-parameters

  ;; Run the setup routine to initialize other globals.
  setup
end 

;;-----------------------------------------------------------------------------|
;; Reset the default values for the interface-declared items.

to f-reset-default-parameters 
  ;; The observer executes this routine.

  ;; Switches, sliders and choosers implicitly declare global variables.  The
  ;;   values in these variables are parameters for the model, and many 
  ;;   combinations of those parameters are not sustainable.  However, the
  ;;   values in those user interface devices are stored with the model and
  ;;   are persistant across a save/load action.  The default values must
  ;;   be reset on load, or available to a user as a parameter set.  The
  ;;   purpose of this routine is to store at least one viable set of 
  ;;   parameter values.
  
  ;; DO NOT re-initialize the gs-scenario chooser.  The selected scenario
  ;;   is intended to be persistent, and not subject to a default setting.
  
  ;; Initialize the Pseudo Random Number Generator (PRNG).
  set g-use-this-seed 7          ;; [1,1,100,7]
  
  set gb-plot-data true          ;; Turn plotting on.
   
  ;;-----------------------------------------------
  ;; BIOPHYSICAL SUB-SYSTEM CONTROLS AND PARAMETERS
  ;;-----------------------------------------------

  ;; Slider range settings are shown as (Min,Inc,Max,Default)
  set g-no-of-tribes          10 ;; [1,1,100,5]
  set g-c1-belief-value        2 ;; [0,.1,3,2]
  set g-sun-nrg-per-tick    6000 ;; [1000,40,12000,6000] 
  set g-nrg-per-deposit       40 ;; [1,1,100,40]
  set g-prob-of-deposit      0.1 ;; [0,.001,1,.1]
  set g-prob-of-mutation     0.5 ;; [0,.001,1,.5]
  set g-dt-for-eroi           40 ;; [40,40,400,40]
  set g-gene-to-adjust         0 ;; [0,1,7,0]

  ;; Static chromosome 2 (C2) biophysical controls - borrowed from PSoup model.
  set g-c2-dat-parm        1600  ;; [100,10,3200,1600]
  set g-c2-det-parm           4  ;; [4,4,40,4]
  set g-c2-rat-parm         800  ;; [50,10,3200,800]
  set g-c2-ret-parm        1000  ;; [200,1,1600,1000]
  set g-c2-epm-parm           4  ;; [1,1,40,4]
  set g-c2-epa-parm        1600  ;; [1600,100,3000,1600]
  
  ;; End of f-reset-default-parameters
end 

;;-----------------------------------------------------------------------------|
;; The setup button(s)

to setup
  ;; This routine is to be executed by the observer.

  ;; NOTE: The contents of switches, sliders, and choosers seem to be 
  ;;   immune to these 'clear' commands.
  clear-ticks
  clear-turtles
  clear-patches
  clear-drawing
  clear-all-plots
  clear-output
  ;; clear-globals   ;; Suppressed to make gb-debug-on value persistent.
  ;; NOTE: Instead of 'clear-globals', you must ensure all globals are 
  ;;   initialized properly in 'setup'.
  
  ;; import-drawing "01-B OrrSW.jpg"
  
  ;; Set the nrg (encoded in the variable fruit) in all of the patches to zero.
  ask patches
  [
    set fruit 0
    set pcolor brown
  ]
  
  ;; The version should be coded in this global variable to be included in
  ;;   output files.
  set gs-Version "TpLab_V2.07" 

  ;; Debug features may be off or on depending on history.
  ;;   - Perhaps 'setup' was called by 'to startup'.
  ;;   - Perhaps 'setup' was called during a 'BehaviorSpace' run.
  ;;   - Perhaps 'setup' was called by a user-pushed 'setup' button.
  ;; Setup needs to handle some quasi-persistant values correctly regardless of
  ;;   the history.  For gb-debug-on, in particular, I want it to be 
  ;;   persistant so I can have debug output from the 'setup' routine routed
  ;;   to the debug log file, or to the command centre.
  
  ;; 'startup' automatically sets gb-debug-on to 0 when the application is first
  ;;   loaded.  I want to be able to (A) toggle debug on, then, (B) press 
  ;;   'setup' and watch the debug output of the 'setup' command.  The 
  ;;   gb-debug-on must be persistant through the above 'clear' commands.  The 
  ;;   debug log file name and status, however, should not be persistent and 
  ;;   must be reset when setup runs, if appropriate.
  ifelse ( gb-debug-on = 1 )
  [
    ;; Debug is on due to user setting, so file name and status should be 
    ;;   reset.  I do this by turning the feature off then on.
    ;; First toggle it off, closing any remnant log file, if needed.
    f-toggle-debug
    ;; Then toggle it back on, opening a new time-stamped log file.
    f-toggle-debug
  ]
  ;; else
  [
    ;; Debug is off, possibly due to startup execution, possibly due to user 
    ;;   choice.
    ;; Ensure associated variables have compatible settings.
    set gb-debug-on 0              ;; Redundant but ensures consistency.
    set gs-debug-status "0 (Off)"  ;; Redundant but ensures consistency.
    set gb-debug-flow-on 0         ;; Step-specific flow is off.
    file-close-all                 ;; Close the debug log file.
    set gs-log-file-name "dummyname"
  ]
  
  ;; Now, do the standard check that is done at the start of each debuggable 
  ;;   routine.  This must follow the clear commands, which reset everything 
  ;;   except globals, switches, sliders and choosers.
  if( gb-debug-on = 1 )
  [
    ifelse( ( gs-debug-step-chooser = "all" ) or ( gs-debug-step-chooser = "setup" ) )
    [ set gb-debug-flow-on 1 LOG-TO-FILE "" LOG-TO-FILE word "Do-setup: Debug on; tick = " 0 ]
    [ set gb-debug-flow-on 0 ]
  ]

  ;; g-use-this-seed comes from a slider, and is persistant during setup.
  ;; However it is NOT persistent in a 'reset-defaults' call.
  random-seed g-use-this-seed      ;; Tells the PRNG to use this seed.
  
  ;; Establish the list of allowed headings, each 45 degrees from the last.
  ;;   These are the possible deltas that will be added to the current heading
  ;;   based on which of the 8 genes is expressed during a move.
  set gl-heading-list [ 0 45 90 135 180 225 270 315 ] 
  set gl-index-list   [ 0 1 2 3 4 5 6 7 ] 

  ;; The factors used to mutate the base values of the genes need to be 
  ;;   calculated.
  let prime-list [ 7 11 13 17 ]
  let factor-list ( map [ 1 + ( 1 / ? ) ] prime-list )
  let inverse-list ( map [ 1 - ( 1 / ? ) ] prime-list )
  set gl-base-factors ( sentence factor-list inverse-list )

  ;; Identify one colour for each possible value of preferred index.
  set gl-colour-list  [ 65 56 96 26 15 24 84 54 ]
  
  ;; Glogal enumeration variables - There are 4 scenarios possible.
  set ge-scenario-0-beliefs 0  ;; society not affected by beliefs
  set ge-scenario-8-beliefs 1  ;; society with 8 belief systems
  set ge-scenario-8-shares  2  ;; wisdom shared within belief system
  set ge-scenario-n-tribes  3  ;; wisdom also shared within familial group
  ;; Use the input from the chooser gs-scenario to invoke the selected scenario.
  f-set-scenario-number
  
  ;; For debugging the setup procedure, log the values of the globals.
  LOG-TO-FILE ( word "  Do-set: Scenario number    - " g-scenario-number ) 
  LOG-TO-FILE ( word "  Do-set: Scenario name      - " gs-scenario )
  LOG-TO-FILE ( word "  Do-set: Random seed        - " g-use-this-seed )

  ;; Declare values of hidden declarations from sliders.
  LOG-TO-FILE ( word "  Do-set: g-no-of-tribes     - " g-no-of-tribes )
  LOG-TO-FILE ( word "  Do-set: g-c1-belief-value  - " g-c1-belief-value )
  LOG-TO-FILE ( word "  Do-set: g-sun-nrg-per-tick - " g-sun-nrg-per-tick )
  LOG-TO-FILE ( word "  Do-set: g-nrg-per-deposit  - " g-nrg-per-deposit )
  LOG-TO-FILE ( word "  Do-set: g-prob-of-deposit  - " g-prob-of-deposit )
  LOG-TO-FILE ( word "  Do-set: g-prob-of-mutation - " g-prob-of-mutation )
  LOG-TO-FILE ( word "  Do-set: g-dt-for-eroi      - " g-dt-for-eroi )

  ;; Nrg accounting variables
  set g-nrg-in-sunshine     0 ;; Nrg held in the sunshine, to be placed as fruit.
  set g-nrg-in-fruit        0 ;; Nrg held in the fruit.
  set gl-nrg-by-belief  ( n-values  8 [0] ) ;; Nrg held, by belief affiliation.
  set g-total-nrg-in-system 0 ;; Nrg in the system.
  set gl-nrg-by-tribe   ( n-values 10 [0] ) ;; Nrg held, by tribal affiliation.
  
  ;; Nrg in Sunshine takeup accounting variables
  set g-sun-takeup-maximum   0 ;; = [empty-cells]x[size-of-deposit]
  set g-sun-takeup-expected  0 ;; = [Max]x[prob-of-deposit] 
  set g-sun-takeup-actual    0 ;; As measured

  ;; Global enumeration (ge-) codes for cause of death.
  set ge-cod-none     0
  set ge-cod-hunger   1
  set ge-cod-fission  2
  set ge-cod-oldage   3
  
  ;; List to hold counts of cause of death.
  set gl-causes-of-death-per-tick   ( n-values 4 [0] )
  set gl-causes-of-death-cumulative ( n-values 4 [0] )

  ;; Global enumeration (ge-) codes for sinktype.
  set ge-sinktype-discard     0 ;; Discarded sunlight
  set ge-sinktype-move-EPM    1 ;; Seeker EPM
  set ge-sinktype-die-DET     2 ;; Remaining nrg of seeker on death.
  set ge-sinktype-die-DAT     3 ;; Remaining nrg of seeker on death.
  
  ;; System of nrg sinks.
  set gl-sinks-per-tick   ( n-values 4 [0] )
  set gl-sinks-cumulative ( n-values 4 [0] )

  ;; Global EROI system-wide calculations.
  set g-sys-nrg-returned    0 ;; Total nrg returned within delta T.
  set g-sys-nrg-invested    0 ;; Total nrg invested within delta T.
  set g-sys-nrg-income      0 ;; Total nrg income within delta T.
  set gl-sys-nrg-returned  [] ;; List of changes.
  set gl-sys-nrg-invested  [] ;; List of changes.
  set g-sys-eroi          1.0 ;; System-wide EROI, per tick = (B/C).
  set g-sys-eta           0.5 ;; System-wide ETA, per tick  = (B/I).

  ;;---------------------------------------------------------------------------|
  ;; The following agent sets, counts and averages are for data collection 
  ;;   and display in monitors and plots.
  
  ;; Counts
  set g-no-of-patches          0 ;; count of all patches
  set g-no-of-dales            0 ;; count of all dales with fruit
  ;; Counts of all seekers, by belief-affiliation.
  set gl-no-of-seekers [ 0 0 0 0 0 0 0 0 ] 
  set g-no-of-seekers          0 ;; counts of all seekers
  set g-no-with-this-belief    0 ;; count of those with this belief.


  ;; Averages for seekers
  set g-ave-age      0        ;; age of seekers
  set g-ave-nrg      0        ;; nrg of seekers
  set g-ind-min-eroi 1.0      ;; min individual eroi of seekers = (B/C)
  set g-ind-ave-eroi 1.0      ;; ave individual eroi of seekers = (B/C)
  set g-ind-max-eroi 1.0      ;; max individual eroi of seekers = (B/C)
  set g-ind-min-eta  0.5      ;; min individual eta of seekers = (B/I)
  set g-ind-ave-eta  0.5      ;; ave individual eta of seekers = (B/I)
  set g-ind-max-eta  0.5      ;; max individual eta of seekers = (B/I)

  set g-ave-C1-b0   0         ;; c1, base character, gene-0
  set g-ave-C1-b1   0         ;; c1, base character, gene-1
  set g-ave-C1-b2   0         ;; c1, base character, gene-2
  set g-ave-C1-b3   0         ;; c1, base character, gene-3
  set g-ave-C1-b4   0         ;; c1, base character, gene-4
  set g-ave-C1-b5   0         ;; c1, base character, gene-5
  set g-ave-C1-b6   0         ;; c1, base character, gene-6
  set g-ave-C1-b7   0         ;; c1, base character, gene-7

  set g-ave-C1-g0   0         ;; c1, genotypic character, gene-0
  set g-ave-C1-g1   0         ;; c1, genotypic character, gene-1
  set g-ave-C1-g2   0         ;; c1, genotypic character, gene-2
  set g-ave-C1-g3   0         ;; c1, genotypic character, gene-3
  set g-ave-C1-g4   0         ;; c1, genotypic character, gene-4
  set g-ave-C1-g5   0         ;; c1, genotypic character, gene-5
  set g-ave-C1-g6   0         ;; c1, genotypic character, gene-6
  set g-ave-C1-g7   0         ;; c1, genotypic character, gene-7

  set g-ave-C1-l0   0         ;; c1, learned character, gene-0
  set g-ave-C1-l1   0         ;; c1, learned character, gene-1
  set g-ave-C1-l2   0         ;; c1, learned character, gene-2
  set g-ave-C1-l3   0         ;; c1, learned character, gene-3
  set g-ave-C1-l4   0         ;; c1, learned character, gene-4
  set g-ave-C1-l5   0         ;; c1, learned character, gene-5
  set g-ave-C1-l6   0         ;; c1, learned character, gene-6
  set g-ave-C1-l7   0         ;; c1, learned character, gene-7

  set g-ave-C1-s0   0         ;; c1, strength character, gene-0
  set g-ave-C1-s1   0         ;; c1, strength character, gene-1
  set g-ave-C1-s2   0         ;; c1, strength character, gene-2
  set g-ave-C1-s3   0         ;; c1, strength character, gene-3
  set g-ave-C1-s4   0         ;; c1, strength character, gene-4
  set g-ave-C1-s5   0         ;; c1, strength character, gene-5
  set g-ave-C1-s6   0         ;; c1, strength character, gene-6
  set g-ave-C1-s7   0         ;; c1, strength character, gene-7

  set g-ave-C1-p0   0         ;; c1, phenotypic character, gene-0
  set g-ave-C1-p1   0         ;; c1, phenotypic character, gene-1
  set g-ave-C1-p2   0         ;; c1, phenotypic character, gene-2
  set g-ave-C1-p3   0         ;; c1, phenotypic character, gene-3
  set g-ave-C1-p4   0         ;; c1, phenotypic character, gene-4
  set g-ave-C1-p5   0         ;; c1, phenotypic character, gene-5
  set g-ave-C1-p6   0         ;; c1, phenotypic character, gene-6
  set g-ave-C1-p7   0         ;; c1, phenotypic character, gene-7

  ;; For debugging the debug feature!!!  Suppressed now.
  ;; show ( word "SETUP: Debug Is " gb-debug-on )
  ;; show ( word "SETUP: Debug Status Is " gs-debug-status )
  ;; show ( word "SETUP: Step Chooser Is " gs-debug-step-chooser )
  ;; show ( word "SETUP: Flow Control Is " gb-debug-flow-on )

  set-default-shape seekers  "arrow" ;; pulled from shapes library

  ask patches 
  [ 
    set pcolor brown
  ]
   
  reset-ticks ;; restarts tick counter, runs setup commands within plots
  set gb-plot-data true ;; Enables all plotting calls.
  
  ;; Initialize the seekers.
  ;; This differs for each scenario.
  ;; Injects nrg, and establishes belief systems.
  f-initialize-seekers
  
  ;; This call must follow 'reset-ticks' and initialization of seekers.
  f-update-aggregates  ;; Totals and averages.
 
  ;; Clears unwanted zeros in plots.
  clear-all-plots
  setup-plots
  
  ;; Debug controls
  ;; Boolean, in association with chooser, turns debug LOG-TO-FILE on/off
  set gb-debug-flow-on 0 
  ;; Input variable to set a tick for stopping.
  set g-halt-at-tick -1  

  Set g-nrg-in-fruit ( sum [fruit] of patches )
  ;; ASSERT ( frb-nrg-accounts-are-all-valid ) 
  ;;   ( "Do-set: Nrg accounts invalid." ) -1
  LOG-TO-FILE "  Do-set: procedure completed" 

  ;; end of to-setup
end 

;;-----------------------------------------------------------------------------|
;; Set the scenario number using the input from the chooser.

to f-set-scenario-number
  ;; This routine is to be executed by the observer.

  set g-scenario-number ge-scenario-0-beliefs  ;; default

  if( gs-scenario = "Society With 0 Beliefs" )
    [ set g-scenario-number ge-scenario-0-beliefs ]

  if( gs-scenario = "Society With 8 Beliefs" )
    [ set g-scenario-number ge-scenario-8-beliefs ]

  if( gs-scenario = "Society With Wisdom Sharing" )
    [ set g-scenario-number ge-scenario-8-shares ]

  if( gs-scenario = "Society With Tribal Bonds" )
    [ set g-scenario-number ge-scenario-n-tribes ]

  ;; End f-set-scenario-number
end 

;;-----------------------------------------------------------------------------|
;; Initialize a population of seekers.

to f-initialize-seekers
  ;; This routine is to be executed by the observer.

  ;; Load nrg into the sunshine, for setup.
  set g-nrg-in-sunshine g-sun-nrg-per-tick
  set g-total-nrg-in-system ( g-total-nrg-in-system + g-nrg-in-sunshine )
  
  ;; Record maximum possible Sunshine takeup rate data.
  let empty-cells ( count patches with [fruit = 0] )
  set g-sun-takeup-maximum ( empty-cells * g-nrg-per-deposit )
  ;; Record expected Sunshine takeup rate data.
  set g-sun-takeup-expected ( g-sun-takeup-maximum * g-prob-of-deposit )

  ;; I want a population of each type of preferred gene.
  ;; Although I have allocated an amount of energy for this, I do not stop
  ;;   initializing new agents if/when it runs out.  I simply record the
  ;;   over-draw as a negative in the appropriate sink
  
  if( g-scenario-number = ge-scenario-0-beliefs )
    [ f-initialize-0-beliefs-society ]
  if( g-scenario-number = ge-scenario-8-beliefs )
    [ f-initialize-8-beliefs-society ]
  if( g-scenario-number = ge-scenario-8-shares )
    [ f-initialize-wisdom-sharing ] 
  if( g-scenario-number = ge-scenario-n-tribes )
    [ f-initialize-tribal-sharing ]

  ;; Place more energy into patches.
  ask patches
  [
    set fruit g-nrg-per-deposit
    set g-total-nrg-in-system ( g-total-nrg-in-system + g-nrg-per-deposit )
    set pcolor green
  ]

  ;; Record the actual Sunshine takeup rate data.
  set g-sun-takeup-actual 0
  
  ;; Put the rest of the Sunshine into the sink.
  set g-total-nrg-in-system ( g-total-nrg-in-system - g-sun-nrg-per-tick )
  f-store-data-in-sink ge-sinktype-discard g-nrg-in-sunshine
  
  ;; End of f-initialize-seekers
end 

;;-----------------------------------------------------------------------------|
;; Initialize a society characterized by 0 belief systems.

to f-initialize-0-beliefs-society
  ;; This routine is to be executed by the observer.

  ;; In this scenario, we create 8 populations of seekers which are all
  ;;   identical except for location and heading.  None are affected 
  ;;   by any belief affiliation.  This is identical to the 8-beliefs society
  ;;   initialization, except the slider g-c1-belief-value is ignored.
  
  foreach gl-index-list  ;; 8 genes.
  [
    create-seekers g-no-of-tribes 
    [ 
      f-initialize-new-seeker 
    
      ;; In this scenario, seekers have a belief affiliation but it 
      ;;   is de-activated due to the value of the belief being set 
      ;;   to zero.
      
      ;; Identify the belief affiliation.
      set belief-affiliation 0
      ;; This is set to zero, but it not used.  All seekers have a
      ;;   preferred gene of zero, but the associated belief value is 
      ;;   also zero so it has no effect.
      
      ;; Set the heading as one of the 8 allowed headings.
      set heading ( item ( random 8 ) gl-heading-list )

      set color ( item belief-affiliation gl-colour-list )
      set age ( RAT / 2 ) ;; Age is halfway to mature.
      set nrg ( EPA ) ;; Nrg is at max.
      ;; All start with same age and nrg level to avoid bias.
      
      ;; Update the energy statistics.
      let nrg-was ( item belief-affiliation gl-nrg-by-belief )
      let nrg-is-now ( nrg-was + nrg )
      set gl-nrg-by-belief 
        ( replace-item belief-affiliation gl-nrg-by-belief nrg-is-now )
      LOG-TO-FILE ( word "  Do-set: gl-nrg-by-belief - " gl-nrg-by-belief )
      set g-nrg-in-sunshine ( g-nrg-in-sunshine - nrg )
      
      ;; Genetic and belief characters.
      set c1-bases [ 2 2 2 2 2 2 2 2 ]  ;; 8 unbiased genes
      set c1-genes [ 0 0 0 0 0 0 0 0 ]  ;; 8 unbiased genes
      set c1-learn [ 0 0 0 0 0 0 0 0 ]  ;; 8 unbiased beliefs
      
      ;; IGNORE THE g-c1-belief-value SLIDER.  Leave the beliefs unbiased.
      ;; Agent has an enhanced preference to exercise gene ?.
      ;; set c1-learn 
      ;;   ( replace-item ? c1-learn g-c1-belief-value ) ;; Biased beliefs
      
      ;; Calculate the strengths and phenotypic characters.
      f-find-strens-n-phenos
      
      LOG-TO-FILE ( word "  Do-set: C1-bases - " c1-bases )
      LOG-TO-FILE ( word "  Do-set: C1-genes - " c1-genes )
      LOG-TO-FILE ( word "  Do-set: c1-learn - " c1-learn )
      LOG-TO-FILE ( word "  Do-set: c1-stren - " c1-stren )
      LOG-TO-FILE ( word "  Do-set: c1-pheno - " c1-pheno )

      ;; Move each agent to a random point.
      setxy random-xcor random-ycor

    ]  ;; End of create.
  ]  ;; End of foreach

  ;; End of f-initialize-0-beliefs-society
end 

;;-----------------------------------------------------------------------------|
;; Calculate the strengths and phenotypic values.

to f-find-strens-n-phenos
  ;; This routine is to be executed by a seeker.

  ;; It uses the second example of the map feature.
  ;; Examples of the map feature.
  ;; show (map + [1 2 3] [2 4 6])
  ;; => [3 6 9]
  ;; show (map [?1 + ?2 = ?3] 
  ;;           [1 2 3] 
  ;;           [2 4 6] 
  ;;           [3 5 9])
  ;; => [true false true]
    
  ;; Compute the strength as S=B^(G+L).
  set c1-stren ( map [?1 ^ ( ?2 + ?3 )] 
                     c1-bases 
                     c1-genes 
                     c1-learn )
  ;; Compute the phenotypic character as Pi=100*(Si/sum(Si)).
  set c1-pheno 
    ( map [?1 * ?2 / ?3] 
          ( n-values 8 [100] ) 
          c1-stren 
          ( n-values 8 [sum c1-stren] ) )
  ;; End of f-find-strens-n-phenos
end 

;;-----------------------------------------------------------------------------|
;; Initialize a society characterized by 8 beliefs.

to f-initialize-8-beliefs-society
  ;; This routine is to be executed by the observer.

  ;; In this scenario, we create 8 populations of seekers which are all
  ;;   identical except for (a) location and heading; and (b) belief 
  ;;   affiliation.  There are 8 different belief affiliations, one for each
  ;;   compound gene in chromosome #1 (C1).  Each has their belief value
  ;;   set as per the slider g-c1-belief-value.
  
  foreach gl-index-list  ;; 8 genes.
  [
    create-seekers g-no-of-tribes 
    [ 
      f-initialize-new-seeker 
    
      ;; Identify the preferred heading-delta.
      set belief-affiliation ?
      
      ;; Set the heading as one of the 8 allowed headings.
      set heading ( item ( random 8 ) gl-heading-list )

      set color ( item ? gl-colour-list )
      set age ( RAT / 2 ) ;; Age is halfway to mature.
      set nrg ( EPA ) ;; Nrg is at max.
      ;; All start with same age and nrg level to avoid bias.
      
      ;; Update the energy statistics.
      let nrg-was ( item ? gl-nrg-by-belief )
      let nrg-is-now ( nrg-was + nrg )
      set gl-nrg-by-belief ( replace-item ? gl-nrg-by-belief nrg-is-now )
      LOG-TO-FILE ( word "  Do-set: gl-nrg-by-belief - " gl-nrg-by-belief )
      set g-nrg-in-sunshine ( g-nrg-in-sunshine - nrg )
      
      ;; Genetic and belief characters.
      set c1-bases [ 2 2 2 2 2 2 2 2 ]  ;; 8 unbiased genes
      set c1-genes [ 0 0 0 0 0 0 0 0 ]  ;; 8 unbiased genes
      set c1-learn [ 0 0 0 0 0 0 0 0 ]  ;; 8 unbiased beliefs
      ;; Agent has an enhanced preference to exercise gene ?.
      set c1-learn 
      ( replace-item ? c1-learn g-c1-belief-value )  ;; Biased beliefs

      ;; Calculate the strengths and phenotypic characters.
      f-find-strens-n-phenos
      
      LOG-TO-FILE ( word "  Do-set: C1-bases - " c1-bases )
      LOG-TO-FILE ( word "  Do-set: C1-genes - " c1-genes )
      LOG-TO-FILE ( word "  Do-set: c1-learn - " c1-learn )
      LOG-TO-FILE ( word "  Do-set: c1-stren - " c1-stren )
      LOG-TO-FILE ( word "  Do-set: c1-pheno - " c1-pheno )

      ;; Move each agent to a random point.
      setxy random-xcor random-ycor

    ]  ;; End of create.
  ]  ;; End of foreach
  
  ;; End of f-initialize-8-beliefs-society
end 

;;-----------------------------------------------------------------------------|
;; Initialize a society characterized by 8 beliefs with wisdom sharing.

to f-initialize-wisdom-sharing
  ;; This routine is to be executed by the observer.

  ;; This will be an 8-beliefs society, similar to the previous scenario,
  ;;   but with the ability of junior seekers to get wisdom from their
  ;;   elders who share the same belief system.  
  ;; When two seekers having the same belief affiliation 
  ;;   occupy the same cell, a seeker may have wisdom about
  ;;   that belief transferred from the eldest such seeker, called
  ;;   the local guru.
  ;; Wisdom is transferred during the 'do-feed' step.
  
  ;; The seekers are no different from those in an 8-beliefs society.
  f-initialize-8-beliefs-society
  
  ;; End of f-initialize-wisdom-sharing
end 

;;-----------------------------------------------------------------------------|
;; Initialize a society characterized by 8 belief systems.

to f-initialize-tribal-sharing
  ;; This routine is to be executed by the observer.

  ;; In this scenario, we create a number of tribes of seekers.  Each
  ;;   tribe consists of eight seekers having the full range of belief
  ;;   affiliations.
  
  let no-of-belieftypes 8
  let tribe-no 0
  let belief-no  0
  
  while [ tribe-no < g-no-of-tribes ]
  [
    LOG-TO-FILE ( WORD "  Do-set: Tribal affiliation - " tribe-no )
    set belief-no 0
    while [ belief-no < no-of-belieftypes ]
    [
      LOG-TO-FILE
        ( WORD "  Do-set: (Tribe, Belief)   - (" tribe-no ", " belief-no ")" )
      
      create-seekers 1
      [
        f-initialize-new-seeker
        
        ;; Identify the belief affiliation.
        set belief-affiliation belief-no
        ;; Set the heading as one of the 8 allowed headings.
        set heading ( item ( random 8 ) gl-heading-list )
        ;; Set the tribe number.
        set tribal-affiliation tribe-no

        set color ( item belief-no gl-colour-list )
        set age ( RAT / 2 ) ;; Age is halfway to mature.
        set nrg ( EPA ) ;; Nrg is at max.
        ;; All start with same age and nrg level to avoid bias.
      
        ;; Update the energy statistics.
        let nrg-was ( item belief-no gl-nrg-by-belief )
        let nrg-is-now ( nrg-was + nrg )
        set gl-nrg-by-belief 
          ( replace-item belief-no gl-nrg-by-belief nrg-is-now )
        LOG-TO-FILE ( word "  Do-set: gl-nrg-by-belief - " gl-nrg-by-belief )
        set g-nrg-in-sunshine ( g-nrg-in-sunshine - nrg )
      
        ;; Genetic and belief characters.
        set c1-bases [ 2 2 2 2 2 2 2 2 ]  ;; 8 unbiased genes
        set c1-genes [ 0 0 0 0 0 0 0 0 ]  ;; 8 unbiased genes
        set c1-learn [ 0 0 0 0 0 0 0 0 ]  ;; 8 unbiased beliefs
        ;; Agent has an enhanced preference to exercise gene belief-no.
        set c1-learn 
          ( replace-item belief-no c1-learn g-c1-belief-value ) ;; Biased beliefs

        ;; Calculate the strengths and phenotypic characters.
        f-find-strens-n-phenos
      
        LOG-TO-FILE ( word "  Do-set: C1-bases - " c1-bases )
        LOG-TO-FILE ( word "  Do-set: C1-genes - " c1-genes )
        LOG-TO-FILE ( word "  Do-set: c1-learn - " c1-learn )
        LOG-TO-FILE ( word "  Do-set: c1-stren - " c1-stren )
        LOG-TO-FILE ( word "  Do-set: c1-pheno - " c1-pheno )

        ;; Move each agent to a random point.
        setxy random-xcor random-ycor
      ]
      set belief-no ( belief-no + 1 )
    ]
    set tribe-no ( tribe-no + 1 )
  ]
  
  ;; End of f-initialize-tribal-sharing
end 

;;-----------------------------------------------------------------------------|
;; Initialize a society characterized by 8 belief systems.

to f-impose-belief-affiliation
  ;; This routine is to be executed by the observer.

  ;; This routine will impose a belief affiliation on roughly 1/2 of the 
  ;;   current population of seekers.  The gene affected by this imposition 
  ;;   is determined by the slider g-belief-to-adjust.  The magnitude of the
  ;;   belief is determined by the slider g-c1-belief-value.
  
  ;; It can be called by the "Impose This Belief Affiliation" button at 
  ;;   any time during any scenario.
  
  let selector 0
  ask seekers
  [
    ifelse ( selector = 0 )
    [
      ;; This seeker has been selected to have its belief affiliation adjusted.
      ;; The gene adjusted is determined by g-gene-to-adjust
      let adjustment g-c1-belief-value
      let target g-gene-to-adjust
      set c1-learn ( replace-item target c1-learn adjustment )
      set belief-affiliation g-gene-to-adjust
      
      set selector 1
    ]  ;; End if selector = 0
    ;; Else selector = 1
    [
      ;; This seeker will not have its belief affiliation adjusted.
      ;; No action required, other than resetting the selector.
      
      set selector 0
    ]  ;; End else if selector = 1
  ]
  f-update-aggregates
  
  ;; End of f-impose-belief-affiliation
end 

;;-----------------------------------------------------------------------------|
;; Initialize a single seeker.

to f-initialize-new-seeker
  ;; This routine is to be executed by a seeker.

  ;; BUILT-IN ATTRIBUTES
  ;; who         ;; set automatically
  ;; heading     ;; direction of motion
  ;; xcor        ;; min-pxcor <= xcor < max-pxcor
  ;; ycor        ;; min-pxcor <= xcor < max-pxcor
  ;; pen-mode    ;; "up" or "down"
  ;; pen-size    ;; in pixels
  ;; size        ;; size relative to a patch, default is 1

  ;; USER-DETERMINED ATTRIBUTES
  ;; These two are re-initialized specifically for some scenarios.
  set belief-affiliation 0
  set tribal-affiliation 0
  
  ;; The biophysical body function genes are static in this model.
  ;; Load chromosome 2 with the parameters from sliders.
  set DAT g-c2-dat-parm
  set DET g-c2-det-parm
  set RAT g-c2-rat-parm
  set RET g-c2-ret-parm
  set EPM g-c2-epm-parm
  set EPA g-c2-epa-parm

  ;; Associated with seeker dynamics.
  set mas-who -1                 ;; serial number of parent seeker.
  ;; age and nrg are set in group initialization routine.
  set cause-of-death ge-cod-none ;; for statistical purposes.

  ;; Set the logic trigger flags.
  set b-is-ready-to-move      1 ;; i.e. true
  set b-is-ready-to-reproduce 0 ;; i.e. false
  set b-is-ready-to-die       0 ;; i.e. false
  
  ;; Variables for calculating individual EROI and ETA.
  set nrg-returned g-dt-for-eroi ;; Numerator of EROI - an aggregate
  set nrg-invested g-dt-for-eroi ;; Denominator of EROI - an aggregate
  set nrg-income ( nrg-returned + nrg-invested )
  set eroi              1.0 ;; Nrg returned on nrg invested = (B/C)
  set eta               0.5 ;; individual efficiency        = (B/I)
  set l-er ( n-values g-dt-for-eroi [1] ) ;; Delta ERs = B of B/C
  set l-ei ( n-values g-dt-for-eroi [1] ) ;; Delta EIs = C of B/C
  set counter-eroi g-dt-for-eroi ;; For tracking time up to delta T.

  ;; end f-initialize-new-seeker
end 

;;-----------------------------------------------------------------------------|
;; SECTION D – GO OR MAIN-LOOP PROCEDURE( S )
;;-----------------------------------------------------------------------------|

;;-----------------------------------------------------------------------------|
;; The go button

to go
  ;; This routine is to be executed by the observer.

  ;; Stop codes:
  ;; All stop decisions must be here in the 'go' procedure, as it causes an
  ;;   exit from the current procdure only.

  if( g-halt-at-tick = ticks  ) 
  [
    set g-halt-at-tick -1
    stop
  ]
  
  let b-should-stop-now false
  if( count turtles <= 0 ) [ set b-should-stop-now true ]
  if( b-should-stop-now = true )
  [
    stop
  ]

  ;; MANUAL CHANGE FOR DEBUG
  ;; If needed, each check for validity can be enabled between steps.
  ;; They have been suppressed (turned into comments) for the sake 
  ;;   of speed of execution, but can be re-enabled if a bug has 
  ;;   somehow been re-introduced.
  ;; A single call to the validity check has been left active inside of the
  ;;   Do-Post-Tick step.  If it flags a problem, re-activate these to
  ;;   narrow down where the problem starts.
  
  ;; Major steps or functions, done once per tick, in order of execution.
  do-pre-tick
  ;; if( frb-agents-are-all-valid = false ) 
  ;;   [ LOG-TO-FILE ( word "Agents failed validity test: Do-pre-tick." ) ]

  do-energize
  ;; if( frb-agents-are-all-valid = false ) 
  ;;   [ LOG-TO-FILE ( word "Agents failed validity test: Do-energize." ) ]

  do-move
  ;; if( frb-agents-are-all-valid = false ) 
  ;;   [ LOG-TO-FILE ( word "Agents failed validity test: Do-move." ) ]

  do-feed
  ;; if( frb-agents-are-all-valid = false ) 
  ;;   [ LOG-TO-FILE ( word "Agents failed validity test: do-feed." ) ]

  do-reproduce
  ;; if( frb-agents-are-all-valid = false ) 
  ;;   [ LOG-TO-FILE ( word "Agents failed validity test: Do-reproduce." ) ]

  do-die
  ;; if( frb-agents-are-all-valid = false ) 
  ;;   [ LOG-TO-FILE ( word "Agents failed validity test: Do-die." ) ]

  do-post-tick
  ;; if( frb-agents-are-all-valid = false ) 
  ;;   [ LOG-TO-FILE ( word "Agents failed validity test: Do-post-tick." ) ]
end 

;;-----------------------------------------------------------------------------|
;; D1 - do-pre-tick procedure( s )
;;-----------------------------------------------------------------------------|

to do-pre-tick
  ;; This routine is to be executed by the observer.
  
  if( gb-debug-on = 1 )
  [
    ifelse( ( gs-debug-step-chooser = "all" ) or ( gs-debug-step-chooser = "pre-tick" ) )
    [ set gb-debug-flow-on 1 LOG-TO-FILE "" LOG-TO-FILE word "Do-pre-tick: Debug on.; tick = " ticks ]
    [ set gb-debug-flow-on 0 ]
  ]
  
  ;; Enter all commands that need to be done before a tick begins.
  ;; Supressed. f-update-aggregates
  
  ;; Advance the tick counter by 1 tick.
  ifelse( gb-plot-data = true )
  [
    ;; Advance the ticks by one and update the plots.
    tick
    ;; 'tick' is exactly the same as 'update-plots' except that the tick counter 
    ;;   is incremented before the plot commands are executed.
    
  ]
  ;; else
  [
    ;; Advance ticks by one but do not update the plots.
    tick-advance 1
  ]
  ;; End else

  ;; Once the data is plotted, the per-tick counts can be cleared.
  ;; List to hold counts of cause of death.
  set gl-causes-of-death-per-tick   ( n-values 6 [0] )

  ;; Global EROI system-wide calculations.
  ifelse( length gl-sys-nrg-returned <= g-dt-for-eroi )
  [
    ;; Append a zero for new data.
    set gl-sys-nrg-returned ( lput 0 gl-sys-nrg-returned ) ;; List of changes.
    set gl-sys-nrg-invested ( lput 0 gl-sys-nrg-invested ) ;; List of changes.
  ]
  ;; Else
  [
    ;; Remove old data
    set gl-sys-nrg-returned ( butfirst gl-sys-nrg-returned ) ;; List of changes.
    set gl-sys-nrg-invested ( butfirst gl-sys-nrg-invested ) ;; List of changes.
    ;; Append a zero for new data.
    set gl-sys-nrg-returned ( lput 0 gl-sys-nrg-returned ) ;; List of changes.
    set gl-sys-nrg-invested ( lput 0 gl-sys-nrg-invested ) ;; List of changes.
  ]

  ;; Reset the scenario number, in case the chooser has been changed.
  f-set-scenario-number
  
  ;; Clear the per-tick data for energy sinks.
  ;; This call must happen before the seeker population is stabilized.
  set gl-sinks-per-tick ( n-values 4 [0] )
  
  ask seekers [ set age ( age + 1 ) ]
  LOG-TO-FILE ( word "  Do-pre-tick: Seekers aged." )

  LOG-TO-FILE ( word "  Do-pre-tick: Halt at tick - " g-halt-at-tick  ) 
  LOG-TO-FILE ( word "  Do-pre-tick: Current tick - " ticks ) 

  LOG-TO-FILE "  Do-pre-tick: Routine completed."
end 


;;-----------------------------------------------------------------------------|
;; D2 – do-energize procedure(s)
;;-----------------------------------------------------------------------------|

to do-energize
  ;; This routine is to be executed by the observer.
  
  if( gb-debug-on = 1 )
  [
    ifelse( ( gs-debug-step-chooser = "all" ) or ( gs-debug-step-chooser = "energize" ) )
    [ set gb-debug-flow-on 1 LOG-TO-FILE "" LOG-TO-FILE word "Do-energize: Debug on; tick = " ticks ]
    [ set gb-debug-flow-on 0 ]
  ]
  
  ;; The Sun radiates a fixed amount of energy per tick into the system.
  set g-nrg-in-sunshine ( g-nrg-in-sunshine + g-sun-nrg-per-tick )
  set g-total-nrg-in-system ( g-total-nrg-in-system + g-sun-nrg-per-tick )
  
  ;; Record maximum possible Sunshine takeup rate data.
  let empty-cells ( count patches with [fruit = 0] )
  set g-sun-takeup-maximum ( empty-cells * g-nrg-per-deposit )
  ;; Record expected Sunshine takeup rate data.
  set g-sun-takeup-expected ( g-sun-takeup-maximum * g-prob-of-deposit )

  ;; Make a list of the patches that are without fruit (without nrg)
  let empty-patch-list ( patches with [fruit = 0] )

  ;; Use the probability of deposit to determine if fruit is added.
  ask empty-patch-list
  [
    let random-number ( random 100000 )
    let threshold ( 100000 * g-prob-of-deposit )
    if ( ( random-number <= threshold ) and 
         ( g-nrg-in-sunshine > g-nrg-per-deposit ) )
    [
      set fruit ( fruit + g-nrg-per-deposit )
      set pcolor green
      ;; Record in system nrg accounts
      set g-nrg-in-fruit  ( g-nrg-in-fruit  + g-nrg-per-deposit )
      set g-nrg-in-sunshine ( g-nrg-in-sunshine - g-nrg-per-deposit )
    ]
  ]
  
  ;; Record actual Sunshine takeup rate data.
  set g-sun-takeup-actual ( g-sun-nrg-per-tick - g-nrg-in-sunshine )

  ;; Discard any remaining energy that has not been absorbed by plants.
  f-store-data-in-sink ge-sinktype-discard g-nrg-in-sunshine
  set g-total-nrg-in-system ( g-total-nrg-in-system - g-nrg-in-sunshine )
  set g-nrg-in-sunshine 0
      
  ;; Supressed. f-update-aggregates

  LOG-TO-FILE "  Do-energize: procedure completed"
end 

;;-----------------------------------------------------------------------------|
;; D3 – do-move procedure(s)
;;-----------------------------------------------------------------------------|

to do-move
  ;; This routine is to be executed by the observer.
  
  if( gb-debug-on = 1 )
  [
    ifelse( ( gs-debug-step-chooser = "all" ) or ( gs-debug-step-chooser = "move" ) )
    [ set gb-debug-flow-on 1 LOG-TO-FILE "" LOG-TO-FILE word "Do-move: Debug on; tick = " ticks ]
    [ set gb-debug-flow-on 0 ]
  ]
  
  ;; The seekers move.
  ask seekers
  [
    if( b-is-ready-to-move = 1 )
    [
      f-seeker-moves
    ]  ;; End if( b-is-ready-to-move = 1 )
  ]  ;; End ask seekers

  ;; Supressed. f-update-aggregates

  LOG-TO-FILE "  Do-move: procedure completed"
end 

;;-----------------------------------------------------------------------------|
;; A seeker moves according to genes and heuristics.

to f-seeker-moves
  ;; This routine is to be executed by a seeker.

  ;; When a seeker moves it expends energy out of its pool of nrg.
  ;; Determine if this seeker has sufficient nrg to move.
  ifelse ( nrg >= EPM )
  [
    ;; Establish a heading.
    f-seeker-sets-heading
    
    ;; Step forward
    forward 1
    
    ;; Expend the nrg to the sink.
    f-store-data-in-sink ge-sinktype-move-EPM EPM
    set nrg ( nrg - EPM )
    
    ;; Record the expenditure in the stats.
    let sum-was ( item belief-affiliation gl-nrg-by-belief )
    let sum-is-now ( sum-was - EPM )
    set gl-nrg-by-belief 
      ( replace-item belief-affiliation gl-nrg-by-belief sum-is-now )
    set g-total-nrg-in-system ( g-total-nrg-in-system - EPM )

    ;; Record the expenditure in the EROI variables
    f-record-ei-for-eroi EPM
    
    set b-is-ready-to-move 1
    ;; set b-is-ready-to-die 0
  ] 
  ;; Else
  [
    ;; The seeker is marked for death, and nrg is removed.
    ;; It will die and be removed when do-die is executed.    
    f-store-data-in-sink ge-sinktype-move-EPM nrg
    let sum-was ( item belief-affiliation gl-nrg-by-belief )
    let sum-is-now ( sum-was - nrg )
    set gl-nrg-by-belief 
      ( replace-item belief-affiliation gl-nrg-by-belief sum-is-now )
    set g-total-nrg-in-system ( g-total-nrg-in-system - nrg )

    ;; Record the expenditure in the EROI variables
    f-record-ei-for-eroi nrg
    
    set nrg 0 
    set cause-of-death ge-cod-hunger
    set b-is-ready-to-move 0
    set b-is-ready-to-die 1
  ]
  ;; End else

  LOG-TO-FILE ( word "  Do-move: S(heading,nrg,move-flag,die-flag) - (" 
    heading "," 
    floor nrg "," 
    b-is-ready-to-move"," 
    b-is-ready-to-die ")" )
  
  ;; End of f-seeker-moves  
end 

;;-----------------------------------------------------------------------------|
;; A seeker sets a heading using c1-pheno.

to f-seeker-sets-heading
  ;; This routine is to be executed by a seeker.

    ;; The agent will consult its phenotypic characters, to determine the
    ;;   best direction for the next heading.  It is blind, and cannot sense
    ;;   other agents, or patches of fruit.  So the only guidance it has is
    ;;   the genetic information received from its mother, or from the social
    ;;   wisdom learned via its belief and tribal affiliations.
    
    ;; Take note of the current heading.
    let old-heading heading
    
    ;; DECIDE HOW MUCH TO TURN AS DELTA-HEADING.
    ;; Add up the indicators.
    let sum-of-phenos ( round ( sum c1-pheno ) )
    LOG-TO-FILE ( word "  Do-move: Phenos          - " c1-pheno )
    LOG-TO-FILE ( word "  Do-move: Summed Phenos   - " sum-of-phenos )
    ;; Each pheno is derived from genes plus learnings.  The size of
    ;;   the pheno creates a proportional target interval in the sum.  
    ;;   Choose an interval (i.e. choose a pheno) by getting a random number.
    let random-number ( random-float sum-of-phenos )
    LOG-TO-FILE ( word "  Do-move: Random Number   - " random-number )
    ;; The random-number must fall between two sequential pheno aggregates.
    ;; E.g if the random-number is 50%, and the first two pheno numbers 
    ;;   are 13% and 25% (+=38%) then that sum is less than 50%.  If the 
    ;;   next pheno is 20%, then the aggregate is 58%, which is bigger 
    ;;   than 50%.  So it falls between the 2nd and 3rd aggregate of the 
    ;;   phenos.  The third interval then is selected "randomly" with 
    ;;   probability determined by its relative size, among all phenos.
    ;;   Due to zero-based indexing, the correct index is 3-1 = 2.

    let counter 0
    let good-index -1
    let this-pheno 0
    let this-sum 0
    let next-sum 0
    while [ counter < 8 ]  ;; Do not overshoot
    [
      LOG-TO-FILE ( word "  Do-move: Counter         - " counter )
      set this-pheno ( item counter c1-pheno )
      LOG-TO-FILE ( word "  Do-move: This sum        - " this-sum )
      LOG-TO-FILE ( word "  Do-move: Pheno           - " this-pheno )
      set next-sum ( this-pheno + this-sum )
      LOG-TO-FILE ( word "  Do-move: Next sum        - " next-sum )
      if ( ( random-number >= this-sum ) and 
           ( random-number < next-sum  ) )
      [
        set good-index counter
        LOG-TO-FILE ( word "  Do-move: Selected gene   - " good-index )
      ]
      set this-sum next-sum
      set counter ( counter + 1 )
    ]
    let heading-delta ( item good-index gl-heading-list )
    LOG-TO-FILE ( word "  Do-move: Old heading     - " heading )

    ;; Set the new heading
    set heading ( heading + heading-delta )
    LOG-TO-FILE ( word "  Do-move: New heading     - " heading )
  
  ;; End of f-seeker-sets-heading  
end 

;;-----------------------------------------------------------------------------|
;; Store data in the lists of sinks.

to f-store-data-in-sink [ sinktype value ]
  ;; This routine is to be executed by anyone.
  
  ;; Record it in the per-tick list.
  let old-value ( item sinktype gl-sinks-per-tick )
  let new-value ( old-value + value )
  set gl-sinks-per-tick ( replace-item sinktype gl-sinks-per-tick new-value )

  ;; Record it in the cumulative list.
  set old-value ( item sinktype gl-sinks-cumulative )
  set new-value ( old-value + value )
  set gl-sinks-cumulative 
    ( replace-item sinktype gl-sinks-cumulative new-value )

  ;; end of f-store-data-in-sink
end 

;;-----------------------------------------------------------------------------|
;; Increment the count in the lists of causes of death.

to f-increment-cod-list [ breedtype codtype ]
  ;; This routine is to be executed by anyone.
  
  ;; Record it in the per-tick list.
  let old-count ( item codtype gl-causes-of-death-per-tick )
  let new-count ( old-count + 1 )
  set gl-causes-of-death-per-tick 
    ( replace-item codtype gl-causes-of-death-per-tick new-count )
    
  ;; Record it in the cumulative list.
  set old-count ( item codtype gl-causes-of-death-cumulative )
  set new-count ( old-count + 1 )
  set gl-causes-of-death-cumulative 
    ( replace-item codtype gl-causes-of-death-cumulative new-count )

  ;; End of f-increment-cod-list
end 

;;-----------------------------------------------------------------------------|
;; Record the 'energy invested' component of EROI calculation.

to f-record-ei-for-eroi [eroi-ei]
  ;; This routine is to be executed by a seeker.
  
  ;; NOTE: EROI is ER/EI, that is Benefits over Costs, or (B/C).
  ;;       ETA is ER/(ER+EI), that is Benefits over Income, or (B/I).
  
  ;; LOG-TO-FILE ( word "  Do-move: Counter-eroi - " counter-eroi )
  ;; LOG-TO-FILE ( word "  Do-move: Nrg-returned - " nrg-returned )
  ;; LOG-TO-FILE ( word "  Do-move: Nrg-invested - " nrg-invested )
  ;; LOG-TO-FILE ( word "  Do-move: Nrg-income   - " nrg-income )
  ;; LOG-TO-FILE ( word "  Do-move: L-er         - " l-er )
  ;; LOG-TO-FILE ( word "  Do-move: L-ei         - " l-ei )
  
  LOG-TO-FILE ( word "  Do-move: g-sys-ei was    - " gl-sys-nrg-invested )
  ;; First, record it in the system-wide data.
  let last-index ( ( length gl-sys-nrg-invested ) - 1 )
  let old-value ( last gl-sys-nrg-invested )
  let new-value ( old-value + eroi-ei )
  set gl-sys-nrg-invested 
    ( replace-item last-index gl-sys-nrg-invested new-value )
  LOG-TO-FILE ( word "  Do-move: g-sys-ei is now - " gl-sys-nrg-invested )
  
  ;; Check to determine whether we are only appending data to the list,
  ;;   or we are dropping old data and appending new data.
  ifelse ( counter-eroi < g-dt-for-eroi )
  [
    ;; Case of appending new data only.
    ;; Increment the counter - done only in move-related function.
    set counter-eroi ( counter-eroi + 1 )
    ;; Append new entry to last of l-ei.
    set l-ei ( lput eroi-ei l-ei )
    ;; Append a place-holder zero to l-er.
    set l-er ( lput 0 l-er )
  ]
  ;; Else
  [
    ;; Case of dropping/appending data
    ;; Remove oldest entry.
    set l-ei ( butfirst l-ei )
    ;; Append new entry to last of l-ei
    set l-ei ( lput eroi-ei l-ei )
    
    ;; Adjust l-er, removing oldest and appending a place-holder zero.
    ;; Remove oldest entry.
    set l-er ( butfirst l-er )
    ;; Append zero to last of l-er
    set l-er ( lput 0 l-er )
  ]  ;; End else dropping/appending

  ;; Re-calculate the seekers stats.
  set nrg-invested ( sum l-ei )
  set nrg-income ( nrg-returned + nrg-invested )
  set eroi 0
  if (nrg-invested > 0) [ set eroi ( nrg-returned / nrg-invested ) ]
  set eta 0
  if (nrg-income > 0) [ set eta ( nrg-returned / nrg-income ) ]
  
  ;; LOG-TO-FILE ( word "  Do-move: Counter-eroi - " counter-eroi )
  ;; LOG-TO-FILE ( word "  Do-move: Nrg-returned - " nrg-returned )
  ;; LOG-TO-FILE ( word "  Do-move: Nrg-invested - " nrg-invested )
  ;; LOG-TO-FILE ( word "  Do-move: Nrg-income   - " nrg-income )
  ;; LOG-TO-FILE ( word "  Do-move: L-er         - " l-er )
  ;; LOG-TO-FILE ( word "  Do-move: L-ei         - " l-ei )
  
  ;; End of f-record-ei-for-eroi
end 

;;-----------------------------------------------------------------------------|
;; D4 – do-feed procedure(s)
;;-----------------------------------------------------------------------------|

to do-feed
  ;; This routine is to be executed by the observer.
  
  if( gb-debug-on = 1 )
  [
    ifelse( ( gs-debug-step-chooser = "all" ) or ( gs-debug-step-chooser = "feed" ) )
    [ set gb-debug-flow-on 1 LOG-TO-FILE "" LOG-TO-FILE word "Do-feed: Debug on; tick = " ticks ]
    [ set gb-debug-flow-on 0 ]
  ]
  
  ;; Agents feed on fruit found in patches.
  ask seekers
  [
    let this-patch patch-here  ;; handle to the patch under the seeker.
    let nrg-available ( [fruit] of this-patch )
    if ( ( nrg < ( EPA - g-nrg-per-deposit ) ) and 
         ( nrg-available > 0 ) )
    [
      ;; Case of there is food to eat.
      ;; Seeker eats.
      set nrg ( nrg + nrg-available )
      let sum-was ( item belief-affiliation gl-nrg-by-belief )
      let sum-is-now ( sum-was + nrg-available )
      set gl-nrg-by-belief 
        ( replace-item belief-affiliation gl-nrg-by-belief sum-is-now )
      f-record-er-for-eroi nrg-available
      ask this-patch
      [
        set fruit 0
        set g-nrg-in-fruit ( g-nrg-in-fruit - nrg-available )
        set pcolor brown
      ]
    ]
    
    ;; A seeker checks for a local guru with similar belief affiliation.
    f-seek-guru-wisdom
    
    ;; A seeker checks for a local tribal elder of the same tribal affiliation.
    f-seek-tribal-wisdom
  ]  ;; End of ask seekers.
  
  ;; Supressed. f-update-aggregates

  LOG-TO-FILE "  Do-feed: procedure completed"
  
  ;; End Do-feed procedure.
end 

;;-----------------------------------------------------------------------------|
;; Check if a guru exists locally, and seek a wisdom transfer.

to f-seek-guru-wisdom
  ;; This routine is to be executed by a seeker.
  
  ;; Do this routine for scenarios 2 and 3 only.
  if( g-scenario-number > 1 )
  [
    ;; Case of scenarios 2 and 3.
    ;; Unpack and rename needed characters
    let mywho   who
    let mypatch patch-here
    let myage   age
    let mybelief  belief-affiliation
      
    ;; Select a local guru.
    let belief-elders ( seekers with 
      [ ( who != mywho ) and
        ( patch-here = mypatch ) and
        ( belief-affiliation = mybelief ) and
        ( age >= myage ) ] )

    if( ( count belief-elders ) > 0 )
    [ 
      ;; Case of guru exists.
      LOG-TO-FILE ( word "  Do-feed: wXFer - SEEKING GURU'S WISDOM" ) 
      LOG-TO-FILE ( word "  Do-feed: wXFer - Elders             - " 
        ( [who] of belief-elders ) )
      let maxage ( max [age] of belief-elders )
      let guru ( one-of ( belief-elders with [age = maxage] ) )
      LOG-TO-FILE ( word "  Do-feed: wXFer - Guru found         - " guru )
      LOG-TO-FILE ( word "  Do-feed: wXFer - Belief affiliation - " mybelief ) 
      ;; I estimate that, at steady state, only 1 in ten seekers will 
      ;;   ever experience enlightenment by this routine.
    
      ;; Perform the transfer of wisdom.
      ;;   It is assumed that, since the guru has lived longer, his belief
      ;; has been tested more.  Since the guru is still alive
      ;; that level of belief is to be emulated.
      let mylevel ( item mybelief c1-learn )
      let gurulevel 0
      ask guru [ set gurulevel ( item mybelief c1-learn ) ]
      let level-delta ( ( gurulevel - mylevel ) / 2 )
      let mynewlevel ( mylevel + level-delta )
      set c1-learn ( replace-item mybelief c1-learn mynewlevel )
      LOG-TO-FILE ( word "  Do-feed: wXFer - MyOldLevel - " mylevel 
                                  ", GuruLevel - " gurulevel 
                                  ", LevelDelta - " level-delta 
                                  ", MyNewLevel - " mynewlevel )
    ]  ;; End if guru exists
  ]  ;; End if scenario > 1
  
  ;; End of f-seek-guru-wisdom
end 

;;-----------------------------------------------------------------------------|
;; Check if a tribal elder exists locally, and seek a wisdom transfer.

to f-seek-tribal-wisdom
  ;; This routine is to be executed by a seeker.
  
  ;; Do this routine for scenario 3 only.
  if( g-scenario-number > 2 )
  [
    ;; Case of scenario 3.
    ;; Unpack and rename needed characters
    let mywho   who
    let mypatch patch-here
    let myage   age
    let mytribe tribal-affiliation
      
    ;; Select a local tribal elder.
    let tribal-elders ( seekers with 
      [ ( who != mywho ) and
        ( patch-here = mypatch ) and
        ( tribal-affiliation = mytribe ) and
        ( age >= myage ) ] )
    
    if( ( count tribal-elders ) > 0 )
    [ 
      ;; Case of tribal elder exists.
      LOG-TO-FILE ( word "  Do-feed: wXFer - SEEKING TRIBAL WISDOM" ) 
      LOG-TO-FILE ( word "  Do-feed: wXFer - Tribal elders      - " 
        ( [who] of tribal-elders ) )
      let maxage ( max [age] of tribal-elders )
      let tribal-elder ( one-of ( tribal-elders with [age = maxage] ) )
      LOG-TO-FILE ( word "  Do-feed: wXFer - Teacher found      - " tribal-elder )
        
      ;; Transfer from the tribal elder to the seeker.
      let target-gene ( [belief-affiliation] of tribal-elder )
      LOG-TO-FILE ( word "  Do-feed: wXFer - Belief affiliation - " target-gene )
      let mylevel ( item target-gene c1-learn )
      let elderlevel 0
      ask tribal-elder [ set elderlevel ( item target-gene c1-learn ) ]
      let level-delta ( ( elderlevel - mylevel ) / 2 )
      let mynewlevel ( mylevel + level-delta )
      set c1-learn ( replace-item target-gene c1-learn mynewlevel )
      LOG-TO-FILE ( word "  Do-feed: wXFer - MyOldLevel - " mylevel 
                                  ", ElderLevel - " elderlevel 
                                  ", LevelDelta - " level-delta 
                                  ", MyNewLevel - " mynewlevel )
    ]  ;; End case of elder exists
  ]  ;; End Scenario 3 special processing for tribal connections.
  
  ;; End of f-seek-Tribal-wisdom
end 

;;-----------------------------------------------------------------------------|
;; Record the 'energy returned' component of EROI calculation.

to f-record-er-for-eroi [eroi-er]
  ;; This routine is to be executed by a seeker.
  
  ;; NOTE: EROI is ER/EI, that is Benefits over Costs, or (B/C).
  ;;       ETA is ER/(ER+EI), that is Benefits over Income, or (B/I).
  
  ;; LOG-TO-FILE ( word "  Do-feed: Counter-eroi - " counter-eroi )
  ;; LOG-TO-FILE ( word "  Do-feed: Nrg-returned - " nrg-returned )
  ;; LOG-TO-FILE ( word "  Do-feed: Nrg-invested - " nrg-invested )
  ;; LOG-TO-FILE ( word "  Do-feed: Nrg-income   - " nrg-income )
  ;; LOG-TO-FILE ( word "  Do-feed: L-er         - " l-er )
  ;; LOG-TO-FILE ( word "  Do-feed: L-ei         - " l-ei )
  
  ;; LOG-TO-FILE ( word "  Do-move: g-sys-er was    - " gl-sys-nrg-returned )
  ;; First, record it in the system-wide data.
  let last-index ( ( length gl-sys-nrg-returned ) - 1 )
  let old-value ( last gl-sys-nrg-returned )
  let new-value ( old-value + eroi-er )
  set gl-sys-nrg-returned 
    ( replace-item last-index gl-sys-nrg-returned new-value )
  ;; LOG-TO-FILE ( word "  Do-move: g-sys-er is now - " gl-sys-nrg-returned )
  
  ;; This routine is called by Do-feed.
  ;; The associated routine f-record-er-for-eroi is called by Do-move.
  ;; The two routines work together to calculate EROI.  
  ;; DO NOT increment the counter here - done only in move-related function.
  ;; set counter-eroi ( counter-eroi + 1 )
  ;; Remove the place-holder zero, put there in the move-related routine.
  set l-er ( butlast l-er )
  ;; Append new entry to last of l-er.
  set l-er ( lput eroi-er l-er )

  ;; Re-calculate the seekers stats.
  set nrg-returned ( sum l-er )
  set nrg-income ( nrg-returned + nrg-invested )
  set eroi 0
  if (nrg-invested > 0) [ set eroi ( nrg-returned / nrg-invested ) ]
  set eta 0
  if (nrg-income > 0) [ set eta ( nrg-returned / nrg-income ) ]
  
  ;; LOG-TO-FILE ( word "  Do-feed: Counter-eroi - " counter-eroi )
  ;; LOG-TO-FILE ( word "  Do-feed: Nrg-returned - " nrg-returned )
  ;; LOG-TO-FILE ( word "  Do-feed: Nrg-invested - " nrg-invested )
  ;; LOG-TO-FILE ( word "  Do-feed: Nrg-income   - " nrg-income )
  ;; LOG-TO-FILE ( word "  Do-feed: L-er         - " l-er )
  ;; LOG-TO-FILE ( word "  Do-feed: L-ei         - " l-ei )
  
  ;; End of f-record-er-for-eroi
end 

;;-----------------------------------------------------------------------------|
;; D5 – do-reproduce procedure(s)
;;-----------------------------------------------------------------------------|

to do-reproduce
  ;; This routine is to be executed by the observer.
  
  if( gb-debug-on = 1 )
  [
    ifelse( ( gs-debug-step-chooser = "all" ) or ( gs-debug-step-chooser = "reproduce" ) )
    [ set gb-debug-flow-on 1 LOG-TO-FILE "" LOG-TO-FILE word "Do-rep: Debug on; tick = " ticks ]
    [ set gb-debug-flow-on 0 ]
  ]
  
  ask seekers
  [
    f-set-seeker-repro-flag
    f-reproduce-seeker-by-fission
  ]
  
  ;; Supressed. f-update-aggregates

  LOG-TO-FILE "  Do-rep: procedure completed"
end 

;;-----------------------------------------------------------------------------|
;; f-set-seeker-repro-flag

to f-set-seeker-repro-flag
  ;; This routine is to be executed by a seeker.
  
  set b-is-ready-to-reproduce 1        ;; i.e. true is the default.
  if( nrg < RET )
    [ set b-is-ready-to-reproduce 0 ]  ;; i.e. false due to lack of health.
  
  if( age < RAT )
    [ set b-is-ready-to-reproduce 0 ]  ;; i.e. false due to lack of maturity.
  
  if( b-is-ready-to-reproduce = 1 )
  [
    LOG-TO-FILE 
      ( word "  Do-rep: S(age,nrg,rep-flag) - (" 
        age "," floor nrg  "," b-is-ready-to-reproduce ")" )
  ]
    
  ;; End f-set-seeker-repro-flag
end 

;;-----------------------------------------------------------------------------|
;; A seeker reproduces via fission, one mother having two daughters.

to f-reproduce-seeker-by-fission
  ;; This routine is to be executed by a seeker.
  
  if( b-is-ready-to-reproduce = 1 )   ;; 1 = true
  [
    LOG-TO-FILE ( word "  Do-rep: seeker Ma - " who )

    let mother self
    let mothers-who who
    let mothers-patch patch-here

    let first-share-of-nrg floor( nrg / 2 )
    let second-share-of-nrg ( nrg - first-share-of-nrg )
  
    let daughter-count 0
    ask mothers-patch
    [
      sprout-seekers 2
      [
        set daughter-count ( daughter-count + 1 )
        LOG-TO-FILE ( word "  Do-rep: seeker D" daughter-count " - " who )
        f-initialize-new-seeker
        set color ( [color] of mother )
        
        ;; Copy the C1 genetic/learned material.
        set c1-bases ( [c1-bases] of mother )
        set c1-genes ( [c1-genes] of mother )
        set c1-learn ( [c1-learn] of mother )
        set c1-stren ( [c1-stren] of mother )
        set c1-pheno ( [c1-pheno] of mother )
        set belief-affiliation ( [belief-affiliation] of mother )
        set tribal-affiliation ( [tribal-affiliation] of mother )
        

        ;; C2 genes are static.
        set DAT ( [DAT] of mother )
        set DET ( [DET] of mother )
        set RAT ( [RAT] of mother )
        set RET ( [RET] of mother )
        set EPM ( [EPM] of mother )
        set EPA ( [EPA] of mother )
        
        ;; Note the mother of this daughter.
        set mas-who ( [who] of mother )
        set age 0

        ifelse ( daughter-count = 1 )
        [ set nrg first-share-of-nrg ]
        [ set nrg second-share-of-nrg ]
        
        set cause-of-death          0
        set b-is-ready-to-move      1
        set b-is-ready-to-reproduce 0
        set b-is-ready-to-die       0
        
        ;; Variables for calculating individual EROI and ETA.
        ;; All inherited from mother.
        set nrg-returned ( [nrg-returned] of mother )
        set nrg-invested ( [nrg-invested] of mother )
        set nrg-income   ( [nrg-income] of mother )
        set eroi         ( [eroi] of mother )
        set eta          ( [eta]  of mother )
        set l-er         ( [l-er] of mother )
        set l-ei         ( [l-ei] of mother )
        set counter-eroi ( [counter-eroi] of mother )

        f-mutate-new-seeker
      ]
    ]
    
    ;; Set the cause of death for the mother.
    set cause-of-death ge-cod-fission
    ;; The mother disappears after fission, leaving two daughters.
    ;; Death actually occurs in the Do-die step.
    
  ]

  ;; End f-reproduce-seeker-by-fission
end 

;;-----------------------------------------------------------------------------|
;; A new seeker mutates, changing the genetic basis of strategies.

to f-mutate-new-seeker
  ;; This routine is to be executed by a seeker.
  
  ;; Decide if a genetic mutation is to happen.
  let random-number ( random-float 1 )
  let threshold ( g-prob-of-mutation )
  LOG-TO-FILE 
    ( word "  Do-rep: PreMut (RN, TH)    - (" random-number ", " threshold ")" )
  if ( random-number <= threshold )
  [
    ;; Case of mutation to be done.
    LOG-TO-FILE ( word "  Do-rep: PreMut c1-bases    - " c1-bases )
    LOG-TO-FILE ( word "  Do-rep: PreMut c1-genes    - " c1-genes )
    LOG-TO-FILE ( word "  Do-rep: PreMut c1-learn    - " c1-learn )
    LOG-TO-FILE ( word "  Do-rep: PreMut c1-stren    - " c1-stren )
    LOG-TO-FILE ( word "  Do-rep: PreMut c1-pheno    - " c1-pheno )

    ;; Select the gene to be mutated.  These genes control 
    ;;   the search strategy.
    let gene-to-be-mutated ( random 8 )
    LOG-TO-FILE ( word "  Do-rep: Target gene #      - " gene-to-be-mutated )
    
    ;; Mutate the gene base.
    let oldbase ( item gene-to-be-mutated c1-bases )
    LOG-TO-FILE ( word "  Do-rep: Old base value     - " oldbase )
    ;; Choose a factor for the base.
    let base-factor ( item (random 8) gl-base-factors )
    ;; Mutate it
    let newbase ( oldbase * base-factor )
    LOG-TO-FILE ( word "  Do-rep: Factor             - " base-factor )
    set c1-bases ( replace-item gene-to-be-mutated c1-bases newbase )
    LOG-TO-FILE ( word "  Do-rep: New base value     - " newbase )
    
    ;; Mutate the gene.  The gene value is an integer of either sign.
    let oldgene ( item gene-to-be-mutated c1-genes )
    LOG-TO-FILE ( word "  Do-rep: Old gene value     - " oldgene )
    ;; Decide whether it will increase or decrease in value.
    let delta ( -1 + ( 2 * ( random 2 ) ) )  ;; Either a -1 or a 1.
    LOG-TO-FILE ( word "  Do-rep: Delta              - " delta )
    let newgene ( oldgene + delta )
    set c1-genes ( replace-item gene-to-be-mutated c1-genes newgene )
    LOG-TO-FILE ( word "  Do-rep: New gene value     - " newgene )

    ;; The belief values do not mutate here.

    ;; Calculate the strengths and phenotypic characters.
    f-find-strens-n-phenos
      
    LOG-TO-FILE ( word "  Do-rep: AftMut c1-bases    - " c1-bases )
    LOG-TO-FILE ( word "  Do-rep: AftMut c1-genes    - " c1-genes )
    LOG-TO-FILE ( word "  Do-rep: AftMut c1-learn    - " c1-learn )
    LOG-TO-FILE ( word "  Do-rep: AftMut c1-stren    - " c1-stren )
    LOG-TO-FILE ( word "  Do-rep: AftMut c1-pheno    - " c1-pheno )
  ]
  
  ;; Belief values do not alter in scenarios 0 and 1.
  if( g-scenario-number > 1 )
  [ 
    ;; Decide if a shift of belief value is to happen.
    set random-number ( random-float 1 )
    set threshold ( g-prob-of-belief-drift )
    LOG-TO-FILE 
      ( word "  Do-rep: PreAlt (RN, TH)    - (" random-number ", " threshold ")" )
    if ( random-number <= threshold )
    [
      ;; Case of belief drift to be done.
      LOG-TO-FILE ( word "  Do-rep: PreAlt c1-bases    - " c1-bases )
      LOG-TO-FILE ( word "  Do-rep: PreAlt c1-genes    - " c1-genes )
      LOG-TO-FILE ( word "  Do-rep: PreAlt c1-learn    - " c1-learn )
      LOG-TO-FILE ( word "  Do-rep: PreAlt c1-stren    - " c1-stren )
      LOG-TO-FILE ( word "  Do-rep: PreAlt c1-pheno    - " c1-pheno )

      ;; Alter the belief.  The belief value is an integer 
      ;;   of either sign.
      let myoldbelief ( item belief-affiliation c1-learn )
      LOG-TO-FILE ( word "  Do-rep: Belief Affiliation - " belief-affiliation )
      LOG-TO-FILE ( word "  Do-rep: Old belief value   - " myoldbelief )
      ;; Decide whether it will increase or decrease in value.
      let delta ( -1 + ( 2 * ( random 2 ) ) )  ;; Either -1 or 1.
      LOG-TO-FILE ( word "  Do-rep: Delta              - " delta )
      let mynewbelief ( myoldbelief + delta )
      LOG-TO-FILE ( word "  Do-rep: New belief value   - " mynewbelief )
      set c1-learn ( replace-item belief-affiliation c1-learn mynewbelief )

      ;; Calculate the strengths and phenotypic characters.
      f-find-strens-n-phenos
      
      LOG-TO-FILE ( word "  Do-rep: AftAlt c1-bases    - " c1-bases )
      LOG-TO-FILE ( word "  Do-rep: AftAlt c1-genes    - " c1-genes )
      LOG-TO-FILE ( word "  Do-rep: AftAlt c1-learn    - " c1-learn )
      LOG-TO-FILE ( word "  Do-rep: AftAlt c1-stren    - " c1-stren )
      LOG-TO-FILE ( word "  Do-rep: AftAlt c1-pheno    - " c1-pheno )
    ]
  ]
  
  ;; End of f-mutate-new-seeker
end 
  
;;-----------------------------------------------------------------------------|
;; D6 – do-die procedure(s)
;;-----------------------------------------------------------------------------|

to do-die
  ;; This routine is to be executed by the observer.
  
  if( gb-debug-on = 1 )
  [
    ifelse( ( gs-debug-step-chooser = "all" ) or ( gs-debug-step-chooser = "die" ) )
    [ set gb-debug-flow-on 1 LOG-TO-FILE "" LOG-TO-FILE word "Do-die: Debug on; tick = " ticks ]
    [ set gb-debug-flow-on 0 ]
  ]
  
  if( ( count seekers ) > 0 )
  [
    ask seekers
    [
      f-set-seeker-death-flag
      f-seeker-dies
    ]
  ]
  
  ;; Supressed. f-update-aggregates

  LOG-TO-FILE "  Do-die: procedure completed"
end 

;;-----------------------------------------------------------------------------|
;; f-set-seeker-death-flag

to f-set-seeker-death-flag
  ;; This routine is to be executed by a seeker.
  
  set b-is-ready-to-die 0        ;; i.e. false, default.

  ;; If a cause of death has already been noted, it dies.
  ifelse( cause-of-death > ge-cod-none )
  [
    ;; A cause of death has been previously flagged.
    ;; This is either due to hunger (in do-move) or fission (in do-repro).
    ;; In both cases nrg has been stripped out already.
    ;; In the cases of DET and DAT, the flag is not yet set, 
    ;;   and the nrg remains.
    set b-is-ready-to-die 1 
  ]
  ;; Else
  [
    ;; No cause of death has been set yet.  Check basic vital signs.
    if( nrg <= DET )  ;; Death Energy Threshold.
    [ 
      set b-is-ready-to-die 1 
      set cause-of-death ge-cod-hunger 
      f-store-data-in-sink ge-sinktype-die-det nrg
      let sum-was ( item belief-affiliation gl-nrg-by-belief )
      let sum-is-now ( sum-was - nrg )
      set gl-nrg-by-belief 
        ( replace-item belief-affiliation gl-nrg-by-belief sum-is-now )
      set g-total-nrg-in-system ( g-total-nrg-in-system - nrg )
      set nrg 0
    ]
    
    if( age > DAT )   ;; Death Age Threshold.
    [ 
      set b-is-ready-to-die 1 
      set cause-of-death ge-cod-oldage 
      f-store-data-in-sink ge-sinktype-die-dat nrg
      let sum-was ( item belief-affiliation gl-nrg-by-belief )
      let sum-is-now ( sum-was - nrg )
      set gl-nrg-by-belief 
        ( replace-item belief-affiliation gl-nrg-by-belief sum-is-now )
      set g-total-nrg-in-system ( g-total-nrg-in-system - nrg )
      set nrg 0
    ]
  ]

  if( b-is-ready-to-die = 1 )
  [
    LOG-TO-FILE ( WORD "  Do-die: S(age,nrg,cod) - ("
      age "," 
      nrg "," 
      cause-of-death ")" )
  ]
  
  ;; End f-set-seeker-death-flag
end 

;;-----------------------------------------------------------------------------|
;; f-seeker-dies

to f-seeker-dies
  ;; This routine is to be executed by a seeker.
  
  if( b-is-ready-to-die = 1 )
  [
    ;; Nrg was stripped out in do-move step.
    ;; However, nrg may exist for those who die of old age.
    f-increment-cod-list breed cause-of-death
    die  ;; The seeker disappears from the system.    
  ]

  ;; End f-seeker-dies
end 

;;-----------------------------------------------------------------------------|
;; D7 - do-post-tick procedure(s)
;;-----------------------------------------------------------------------------|

to do-post-tick
  ;; This routine is to be executed by the observer.
   
  if( gb-debug-on = 1 )
  [
    ifelse( ( gs-debug-step-chooser = "all" ) or ( gs-debug-step-chooser = "post-tick" ) )
    [ set gb-debug-flow-on 1  LOG-TO-FILE "" LOG-TO-FILE word "Do-Post-tick: Debug on; tick = " ticks ]
    [ set gb-debug-flow-on 0 ]
  ]
  
  ;; MANUAL CHANGE FOR DEBUG.
  ;; This is a call to a debug routine which could be suppressed if all is okay.
  ;; This is one of a group of such calls, most of which are between steps in 
  ;;   the 'Go' routine.  They are suppressed there, but can be enabled again.
  ;; I have decided to leave this one active, for now.
  ;; It checks all agents, every tick, to ensure that all values are greater than
  ;;   or equal to zero.  
  if( frb-agents-are-all-valid = false ) 
    [ LOG-TO-FILE ( word "  Do-post-tick: Agents failed validity test." ) ]
  
  ;; Global EROI system-wide calculations.
  set g-sys-nrg-returned 
    ( sum gl-sys-nrg-returned ) ;; Total nrg returned within delta T.
  set g-sys-nrg-invested 
    ( sum gl-sys-nrg-invested ) ;; Total nrg invested within delta T.
  set g-sys-nrg-income ( g-sys-nrg-returned + g-sys-nrg-invested )
  set g-sys-eroi 0 ;; System-wide EROI, per tick.
  if( g-sys-nrg-invested != 0 ) 
    [ set g-sys-eroi ( g-sys-nrg-returned / g-sys-nrg-invested ) ]
  set g-sys-eta 0 ;; System-wide ETA, per tick.
  if( g-sys-nrg-income != 0 ) 
    [ set g-sys-eta ( g-sys-nrg-returned / g-sys-nrg-income ) ]

  ;; Update the aggregates for display in the monitors.
  f-update-aggregates

  display

  LOG-TO-FILE "  Do-post-tick: procedure completed."
end 

;;-----------------------------------------------------------------------------|
;; SECTION E – DRAWING AND MAINTENANCE PROCEDURE(S)
;;-----------------------------------------------------------------------------|

;;-----------------------------------------------------------------------------|
;; Update the values of global aggregate numbers.

to f-update-aggregates
  ;; This routine is to be executed by the observer.

  ;; Although this is a display-only routine, it may implicitly call the 
  ;;   PRNG and so may have an effect on the trajectory of the model.  In a 
  ;;   standard 'go' run it is called only once per tick, before graphs are 
  ;;   updated.  If you use the one-step debug buttons, it is called once 
  ;;   after each step, so debug runs that use those buttons will not 
  ;;   replicate a real run.
  
  ;;---------------------------------------------------------------------------|
  ;; The following agent sets, counts and averages are for data collection 
  ;;   and display in monitors and plots.
  
  ;; Counts
  set g-no-of-patches ( count patches )
  foreach gl-index-list
  [
    set gl-no-of-seekers 
    ( replace-item ? gl-no-of-seekers 
      ( count seekers with [belief-affiliation = ?] ) ) 
  ]
  set g-no-of-seekers ( sum gl-no-of-seekers )
  ;; For the 8-beliefs society, track those with targeted belief affiliation.
  set g-no-with-this-belief 
    ( count seekers with [belief-affiliation = g-gene-to-adjust] )
  
  ;; Averages - seekers
  ifelse( 0 = ( count seekers ) )
  [
    set g-ave-age      0        ;; age of seekers
    set g-ave-nrg      0        ;; nrg of seekers
    set g-ind-min-eroi 1        ;; eroi of seekers
    set g-ind-ave-eroi 1        ;; eroi of seekers
    set g-ind-max-eroi 1        ;; eroi of seekers
    set g-ind-min-eta  0.5      ;; eta of seekers
    set g-ind-ave-eta  0.5      ;; eta of seekers
    set g-ind-max-eta  0.5      ;; eta of seekers

    set g-ave-C1-b0   0         ;; c1, base character, gene-0
    set g-ave-C1-b1   0         ;; c1, base character, gene-1
    set g-ave-C1-b2   0         ;; c1, base character, gene-2
    set g-ave-C1-b3   0         ;; c1, base character, gene-3
    set g-ave-C1-b4   0         ;; c1, base character, gene-4
    set g-ave-C1-b5   0         ;; c1, base character, gene-5
    set g-ave-C1-b6   0         ;; c1, base character, gene-6
    set g-ave-C1-b7   0         ;; c1, base character, gene-7
 
    set g-ave-C1-g0   0         ;; c1, genotypic character, gene-0
    set g-ave-C1-g1   0         ;; c1, genotypic character, gene-1
    set g-ave-C1-g2   0         ;; c1, genotypic character, gene-2
    set g-ave-C1-g3   0         ;; c1, genotypic character, gene-3
    set g-ave-C1-g4   0         ;; c1, genotypic character, gene-4
    set g-ave-C1-g5   0         ;; c1, genotypic character, gene-5
    set g-ave-C1-g6   0         ;; c1, genotypic character, gene-6
    set g-ave-C1-g7   0         ;; c1, genotypic character, gene-7
 
    set g-ave-C1-l0   0         ;; c1, learned character, gene-0
    set g-ave-C1-l1   0         ;; c1, learned character, gene-1
    set g-ave-C1-l2   0         ;; c1, learned character, gene-2
    set g-ave-C1-l3   0         ;; c1, learned character, gene-3
    set g-ave-C1-l4   0         ;; c1, learned character, gene-4
    set g-ave-C1-l5   0         ;; c1, learned character, gene-5
    set g-ave-C1-l6   0         ;; c1, learned character, gene-6
    set g-ave-C1-l7   0         ;; c1, learned character, gene-7

    set g-ave-C1-s0   0         ;; c1, strength character, gene-0
    set g-ave-C1-s1   0         ;; c1, strength character, gene-1
    set g-ave-C1-s2   0         ;; c1, strength character, gene-2
    set g-ave-C1-s3   0         ;; c1, strength character, gene-3
    set g-ave-C1-s4   0         ;; c1, strength character, gene-4
    set g-ave-C1-s5   0         ;; c1, strength character, gene-5
    set g-ave-C1-s6   0         ;; c1, strength character, gene-6
    set g-ave-C1-s7   0         ;; c1, strength character, gene-7

    set g-ave-C1-p0   0         ;; c1, phenotypic character, gene-0
    set g-ave-C1-p1   0         ;; c1, phenotypic character, gene-1
    set g-ave-C1-p2   0         ;; c1, phenotypic character, gene-2
    set g-ave-C1-p3   0         ;; c1, phenotypic character, gene-3
    set g-ave-C1-p4   0         ;; c1, phenotypic character, gene-4
    set g-ave-C1-p5   0         ;; c1, phenotypic character, gene-5
    set g-ave-C1-p6   0         ;; c1, phenotypic character, gene-6
    set g-ave-C1-p7   0         ;; c1, phenotypic character, gene-7
    
    set gl-nrg-by-tribe [ 0 0 0 0 0 0 0 0 0 0 ] ;; Max of 10 tribes
  ]
  ;; Else
  [
    set g-ave-age   ( sum [age] of seekers ) / g-no-of-seekers
    set g-ave-nrg   ( sum [nrg] of seekers ) / g-no-of-seekers
    set g-ind-min-eroi  ( min [eroi] of seekers )
    set g-ind-ave-eroi  ( sum [eroi] of seekers ) / g-no-of-seekers
    set g-ind-max-eroi  ( max [eroi] of seekers )
    set g-ind-min-eta  ( min [eta] of seekers )
    set g-ind-ave-eta  ( sum [eta] of seekers ) / g-no-of-seekers
    set g-ind-max-eta  ( max [eta] of seekers )

    set g-ave-C1-b0 ( f-compute-C1-bases-average 0 )
    set g-ave-C1-b1 ( f-compute-C1-bases-average 1 )
    set g-ave-C1-b2 ( f-compute-C1-bases-average 2 )
    set g-ave-C1-b3 ( f-compute-C1-bases-average 3 )
    set g-ave-C1-b4 ( f-compute-C1-bases-average 4 )
    set g-ave-C1-b5 ( f-compute-C1-bases-average 5 )
    set g-ave-C1-b6 ( f-compute-C1-bases-average 6 )
    set g-ave-C1-b7 ( f-compute-C1-bases-average 7 )

    set g-ave-C1-g0 ( f-compute-C1-genes-average 0 )
    set g-ave-C1-g1 ( f-compute-C1-genes-average 1 )
    set g-ave-C1-g2 ( f-compute-C1-genes-average 2 )
    set g-ave-C1-g3 ( f-compute-C1-genes-average 3 )
    set g-ave-C1-g4 ( f-compute-C1-genes-average 4 )
    set g-ave-C1-g5 ( f-compute-C1-genes-average 5 )
    set g-ave-C1-g6 ( f-compute-C1-genes-average 6 )
    set g-ave-C1-g7 ( f-compute-C1-genes-average 7 )

    set g-ave-C1-l0 ( f-compute-c1-learn-average 0 )
    set g-ave-C1-l1 ( f-compute-c1-learn-average 1 )
    set g-ave-C1-l2 ( f-compute-c1-learn-average 2 )
    set g-ave-C1-l3 ( f-compute-c1-learn-average 3 )
    set g-ave-C1-l4 ( f-compute-c1-learn-average 4 )
    set g-ave-C1-l5 ( f-compute-c1-learn-average 5 )
    set g-ave-C1-l6 ( f-compute-c1-learn-average 6 )
    set g-ave-C1-l7 ( f-compute-c1-learn-average 7 )

    set g-ave-C1-s0 ( f-compute-c1-stren-average 0 )
    set g-ave-C1-s1 ( f-compute-c1-stren-average 1 )
    set g-ave-C1-s2 ( f-compute-c1-stren-average 2 )
    set g-ave-C1-s3 ( f-compute-c1-stren-average 3 )
    set g-ave-C1-s4 ( f-compute-c1-stren-average 4 )
    set g-ave-C1-s5 ( f-compute-c1-stren-average 5 )
    set g-ave-C1-s6 ( f-compute-c1-stren-average 6 )
    set g-ave-C1-s7 ( f-compute-c1-stren-average 7 )

    set g-ave-C1-p0 ( f-compute-c1-pheno-average 0 )
    set g-ave-C1-p1 ( f-compute-c1-pheno-average 1 )
    set g-ave-C1-p2 ( f-compute-c1-pheno-average 2 )
    set g-ave-C1-p3 ( f-compute-c1-pheno-average 3 )
    set g-ave-C1-p4 ( f-compute-c1-pheno-average 4 )
    set g-ave-C1-p5 ( f-compute-c1-pheno-average 5 )
    set g-ave-C1-p6 ( f-compute-c1-pheno-average 6 )
    set g-ave-C1-p7 ( f-compute-c1-pheno-average 7 )
    
    ;; Make a list of existing tribal-affiliation numbers.,
    let tribe-list ( sort remove-duplicates ( [tribal-affiliation] of seekers ) )
    
    set gl-nrg-by-tribe [ 0 0 0 0 0 0 0 0 0 0 ] ;; Max of 10 tribes
    foreach tribe-list
    [
      let total-nrg ( sum [nrg] of seekers with [tribal-affiliation = ?] )
      set gl-nrg-by-tribe 
        ( replace-item ? gl-nrg-by-tribe total-nrg )
    ]
  ]
  ;; End else

  
;;-----------------------------------------------------------------------------|
  ;; To ensure that the PRNG is called whether or not plots are displayed, the
  ;;   calculations needed for any histogram plots which invoke the PRNG
  ;;   implicitly should be carried out here where they will happen every tick.

;;-----------------------------------------------------------------------------|
  ;; Setup for Plot "AAAAAA"
  
  ;; This log entry may come from any step during debug operations.  
  LOG-TO-FILE "  Do-update: All aggregates updated."  

  ;; End of f-update-aggregates
end 

;;-----------------------------------------------------------------------------|
;; Compute an average for C1-bases, by preferred gene type.

to-report f-compute-C1-bases-average [ gene-to-check ]
  ;; This routine is to be executed by the observer.
  let count-of-seekers ( count seekers )
  let appropriate-sum ( sum ( [item gene-to-check c1-bases] of seekers ) )
  let answer 0
  if ( count-of-seekers > 0 ) 
    [ set answer ( appropriate-sum / count-of-seekers ) ]
  ;; LOG-TO-FILE ( word "  Do-update: g# - " gene-to-check ", ave [B] - " answer ) 
  
  report answer
  
  ;; End of f-compute-C1-bases-average
end 

;;-----------------------------------------------------------------------------|
;; Compute an average for C1-genes, by preferred gene type.

to-report f-compute-C1-genes-average [ gene-to-check ]
  ;; This routine is to be executed by the observer.
  let count-of-seekers ( count seekers )
  let appropriate-sum ( sum ( [item gene-to-check c1-genes] of seekers ) )
  let answer 0
  if ( count-of-seekers > 0 ) 
    [ set answer ( appropriate-sum / count-of-seekers ) ]
  ;; LOG-TO-FILE ( word "  Do-update: g# - " gene-to-check ", ave [G] - " answer ) 
  
  report answer
  
  ;; End of f-compute-C1-genes-average
end 

;;-----------------------------------------------------------------------------|
;; Compute an average for c1-learn, by preferred gene type.

to-report f-compute-c1-learn-average [ gene-to-check ]
  ;; This routine is to be executed by the observer.
  let count-of-seekers ( count seekers )
  let appropriate-sum ( sum ( [item gene-to-check c1-learn] of seekers ) )
  let answer 0
  if ( count-of-seekers > 0 ) 
    [ set answer ( appropriate-sum / count-of-seekers ) ]
  ;; LOG-TO-FILE ( word "  Do-update: g# - " gene-to-check ", ave [M] - " answer ) 
  
  report answer
  
  ;; End of f-compute-c1-learn-average
end 

;;-----------------------------------------------------------------------------|
;; Compute an average for c1-stren, by preferred gene type.

to-report f-compute-c1-stren-average [ gene-to-check ]
  ;; This routine is to be executed by the observer.
  let count-of-seekers ( count seekers )
  let appropriate-sum ( sum ( [item gene-to-check c1-stren] of seekers ) )
  let answer 0
  if ( count-of-seekers > 0 ) 
    [ set answer ( appropriate-sum / count-of-seekers ) ]
  ;; LOG-TO-FILE ( word "  Do-update: g# - " gene-to-check ", ave [S] - " answer ) 
  
  report answer
  
  ;; End of f-compute-c1-stren-average
end 

;;-----------------------------------------------------------------------------|
;; Compute an average for c1-pheno, by preferred gene type.

to-report f-compute-c1-pheno-average [ gene-to-check ]
  ;; This routine is to be executed by the observer.
  let count-of-seekers ( count seekers )
  let appropriate-sum ( sum ( [item gene-to-check c1-pheno] of seekers ) )
  let answer 0
  if ( count-of-seekers > 0 ) 
    [ set answer ( appropriate-sum / count-of-seekers ) ]
  ;; LOG-TO-FILE ( word "  Do-update: g# - " gene-to-check ", ave [P] - " answer ) 
  
  report answer
  
  ;; End of f-compute-c1-pheno-average
end 

;;--------------------------
;; DATA CAPTURE TO CSV FILES
;;--------------------------

;;-----------------------------------------------------------------------------|
;; Record the data is several selected plots to CSV files

to f-record-selected-plots
  ;; This routine is to be executed by the observer.
  
  ;; The template for the export command is:
  ;; export-plot plotname filename

  ;; Get a common timestamp for all plots.
  let timestamp fr-get-time-stamp
  
  ;; Plot 01
  let plotname "Nrg - By Belief Affiliation"
  let plot-filename 
    ( word timestamp 
           "_Sc" g-scenario-number 
           "_Se" g-use-this-seed 
           "_Pl01_NBBA.CSV" )
  export-plot plotname plot-filename
  
  ;; Plot 02
  set plotname "Nrg - By Tribal Affiliation"
  set plot-filename 
    ( word timestamp 
           "_Sc" g-scenario-number 
           "_Se" g-use-this-seed 
           "_Pl02_NBTA.CSV" )
  export-plot plotname plot-filename
  
  ;; Plot 03
  set plotname "[B]ase Values By Gene #"
  set plot-filename 
    ( word timestamp 
           "_Sc" g-scenario-number 
           "_Se" g-use-this-seed 
           "_Pl03_BVBG.CSV" )
  export-plot plotname plot-filename
  
  ;; Plot 04
  set plotname "[G]ene Values By Gene #"
  set plot-filename 
    ( word timestamp 
           "_Sc" g-scenario-number 
           "_Se" g-use-this-seed 
           "_Pl04_GVBG.CSV" )
  export-plot plotname plot-filename
  
  ;; Plot 05
  set plotname "[L]earned Beliefs By Gene #"
  set plot-filename 
    ( word timestamp 
           "_Sc" g-scenario-number 
           "_Se" g-use-this-seed 
           "_Pl05_LVBG.CSV" )
  export-plot plotname plot-filename
  
  ;; Plot 06
  set plotname "[S]trengths By Gene #"
  set plot-filename 
    ( word timestamp 
           "_Sc" g-scenario-number 
           "_Se" g-use-this-seed 
           "_Pl06_SVBG.CSV" )
  export-plot plotname plot-filename
  
  ;; Plot 06
  set plotname "[P]henotype Values By Gene #"
  set plot-filename 
    ( word timestamp 
           "_Sc" g-scenario-number 
           "_Se" g-use-this-seed 
           "_Pl07_PVBG.CSV" )
  export-plot plotname plot-filename
  
  ;; End f-record-selected-plots
end 

;;-----------------------------------------------------------------------------|
;; Construct a time stamp for a file name for data in CSV format.

to-report fr-get-time-stamp
  ;; This routine is to be executed by the observer.
  ;;
  ;; Date-string format "01:19:36.685 PM 19-Sep-2002"
  let date-string date-and-time
  let time-stamp ""
  ;; Append the year as yy.
  set time-stamp word time-stamp ( substring date-string 25 27 )
  ;; Append the month as Mmm.
  set time-stamp word time-stamp fr-convert-mmm-mm ( substring date-string 19 22 )
  ;; Append the day as dd.
  set time-stamp word time-stamp ( substring date-string 16 18 )
  ;; Append a dash.
  set time-stamp word time-stamp "_"

  ;; Append the hour as hh.
  set time-stamp word time-stamp fr-convert1224 ( substring date-string 0 2 ) ( substring date-string 13 15 )
  ;; Append the minute as mm.
  set time-stamp word time-stamp ( substring date-string 3 5 )
  ;; Append the second as ss.
  set time-stamp word time-stamp ( substring date-string 6 8 )

  report time-stamp
  ;; End fr-get-time-stamp
end 

;;-----------------------------------------------------------------------------|
;; DEBUG AND DEBUG LOG FILE MANAGEMENT FUNCTIONS
;;-----------------------------------------------------------------------------|

;;-----------------------------------------------------------------------------|
;; Open a log file for debug output.

to f-open-log-file
  ;; This routine is to be executed by the observer.
  
  ;; Ensure previous log file is closed.
  if ( is-string? gs-log-file-name )
  [
    if ( file-exists? gs-log-file-name )
    [
      file-close-all
    ]
  ]
  
  ;; Date-string format "01:19:36.685 PM 19-Sep-2002"
  let date-string date-and-time
  set gs-log-file-name "TpLab_Log_"
  ;; Append the year as yy.
  set gs-log-file-name word gs-log-file-name ( substring date-string 25 27 )
  ;; Append the month as Mmm.
  set gs-log-file-name word gs-log-file-name fr-convert-mmm-mm ( substring date-string 19 22 )
  ;; Append the day as dd.
  set gs-log-file-name word gs-log-file-name ( substring date-string 16 18 )
  ;; Append a dash.
  set gs-log-file-name word gs-log-file-name "_"

  ;; Append the hour as hh.
  set gs-log-file-name word gs-log-file-name fr-convert1224 ( substring date-string 0 2 ) ( substring date-string 13 15 )
  ;; Append the minute as mm.
  set gs-log-file-name word gs-log-file-name ( substring date-string 3 5 )
  ;; Append the second as ss.
  set gs-log-file-name word gs-log-file-name ( substring date-string 6 8 )
  ;; Append the .txt extension.
  set gs-log-file-name word gs-log-file-name ".txt"

  file-open gs-log-file-name
  file-show "Log File for a TpLab (NetLogo) Model."
  file-show word "File Name: " gs-log-file-name
  file-show word "File opened at:" date-and-time
  file-show ""
  
  ;; Send a message directly to the command centre.
  ifelse ( file-exists? gs-log-file-name )
  [
    show word gs-log-file-name " opened."
  ]
  [
    show word gs-log-file-name " not opened."
  ]
end 

;;-----------------------------------------------------------------------------|
;; Convert month in text form to digital form.

to-report fr-convert-mmm-mm [ mmm ]
  ;; This routine is to be executed by the observer.
  ;; It converts a string in the form mmm ( alpha text ) to the form mm ( digit-text ).
  
  let mm "00"
  if( mmm = "Jan" ) [ set mm "01" ]
  if( mmm = "Feb" ) [ set mm "02" ]
  if( mmm = "Mar" ) [ set mm "03" ]
  if( mmm = "Apr" ) [ set mm "04" ]
  if( mmm = "May" ) [ set mm "05" ]
  if( mmm = "Jun" ) [ set mm "06" ]
  if( mmm = "Jul" ) [ set mm "07" ]
  if( mmm = "Aug" ) [ set mm "08" ]
  if( mmm = "SeP" ) [ set mm "09" ]
  if( mmm = "Oct" ) [ set mm "10" ]
  if( mmm = "Nov" ) [ set mm "11" ]
  if( mmm = "Dec" ) [ set mm "12" ]
  report mm
end 

;;-----------------------------------------------------------------------------|
;; Convert hour in 12 format to 24 hour format.

to-report fr-convert1224 [ hh ampm ]
  ;; This routine is to be executed by the observer.
  ;; It converts a string in 12 hour format to 24 hour format.
  
  let hour read-from-string hh
  if( ampm = "PM" ) [ set hour ( hour + 12 ) ]
  
  let dd ( word "00" hour )
  let d2 last dd
  set dd but-last dd
  let d1 last dd
  set dd ( word d1 d2 )
  report dd
end 

;;-----------------------------------------------------------------------------|
;; Close a log file for debug output.

to f-close-log-file
  ;; This routine is to be executed by the observer.
  
  let b-filename-exists 0
  if ( is-string? gs-log-file-name ) 
  [
    if ( file-exists? gs-log-file-name )
    [
      set b-filename-exists 1
    ]
  ] 

  ifelse( b-filename-exists = 1 )
  [
    ;; Ensure the file is selected.
    file-open gs-log-file-name
      
    ;; Stanp it.
    LOG-TO-FILE word "File closed at: " date-and-time
      
    ;; Flush the buffers.
    file-flush 
      
    ;; Close it.
    file-close-all
      
    ;; Note sent to command centre.
    show word gs-log-file-name " closed."
    
    ;; Revert to dummy name.
    set gs-log-file-name "dummyname"
  ]
  [
    if( gs-log-file-name = "dummyname" )
      [ show "No log file is open.  Cannot close it." ]
  ]
end 

;;-----------------------------------------------------------------------------|
;; Select an already opened log file.

to f-select-log-file
  ;; This routine is to be executed by the observer.
  
  ifelse ( file-exists? gs-log-file-name )
  [
    ;; Ensure the file is selected.
    file-open gs-log-file-name
    
    ;; Ensure it is open for writing.
    LOG-TO-FILE ""
    LOG-TO-FILE "SELECTED"    
  ]
  [
    show word gs-log-file-name " is not open.  Cannot select it."
  ]
end 

;;-----------------------------------------------------------------------------|
;; Change the debug mode from on to off, or vice versa.

to f-toggle-debug
  ;; This routine is to be executed by the observer, and is activated by a 
  ;;   button.
  
  ifelse( gb-debug-on = 1 )
  [
    ;; Debug is On, turn it Off.
    ;; Close the file before turning debug logging off.
    f-close-log-file
    set gs-debug-status "0 (Off)"  ;; This appears in the monitor.
    set gb-debug-on 0              ;; But this controls the debug feature.
  ]
  [
    ;; Debug is Off, turn it On.
    set gs-debug-status "1 (On)"   ;; This appears in the monitor.
    set gb-debug-on 1              ;; But this controls the debug feature.
    ;; The switches, if needed, are reset manually by the user.
    ;; Open the log file after turning debug logging on.
    f-open-log-file
  ]
end 

;;-----------------------------------------------------------------------------|
;; 'Show' a string in a debug log.

to LOG-TO-FILE [ log-this-string ]
  ;; This routine may be executed by observer or seeker.
  ;; It should be invoked as a debug routine only, and would not be used for 
  ;;    normal output.  It sends output to the debug log file, or, optionally,
  ;;    also to the command centre.
  
  ;; gb-debug-on is a global Boolean and has value 1 (true) or 0 (false).
  if( gb-debug-on = 1 )
  [
    ;; gb-debug-flow-on is declared as a global Boolean variable, and its value 
    ;;   is 0 ( false ) or 1 ( true ) and is set on or off at the beginning of each 
    ;;   function ( each do-step ).  It is controlled by the chooser that selects 'all' 
    ;;   or a specific do-function.
    ;; 
    ;; When it is 'on' you can assume the debug log file exists and is open for
    ;;   write.
    
    if( gb-debug-flow-on = 1 )
    [
      file-show log-this-string
      show log-this-string
    ] 
  ]
end 

;;-----------------------------------------------------------------------------|
;; This replicates the effect of an 'ASSERTION' in C++

to ASSERT [ error-test error-string error-who ]
;; This routine can be run by observer or seeker.

if( error-test = false )
[
  show ( word error-test " " error-string " " error-who )
  ;; Cause a run-time error and display a message.
  error ( word "Agent: " error-who " - " error-string )
]
end 


;;-----------------------------------------------------------------------------|
;; Check whether the nrg accounts are all valid.

to-report frb-nrg-accounts-are-all-valid 
;; This routine can be run by the observer.

  let b-accounts-are-all-valid 1
  
  if( gb-debug-on = 1 )
  [
    ;; Do the check only if debug is on.
    let temp-nrg-in-seekers  ( sum [nrg] of seekers )
    let temp-nrg-in-fruit    ( sum [fruit] of patches )
    let temp-nrg-in-sunshine g-nrg-in-sunshine
    
    let temp-total-nrg ( temp-nrg-in-seekers +
      temp-nrg-in-fruit +
      temp-nrg-in-sunshine )
    
    if (temp-nrg-in-seekers != ( sum gl-nrg-by-belief ) )
    [ 
      set b-accounts-are-all-valid 0 
      LOG-TO-FILE ( word 
        "S-nrg-check: SB:" temp-nrg-in-seekers 
        ", IS:" ( sum gl-nrg-by-belief ) )    
    ]
    
    if (temp-nrg-in-fruit != g-nrg-in-fruit )
    [ 
      set b-accounts-are-all-valid 0 
      LOG-TO-FILE ( word 
        "F-nrg-check: SB:" temp-nrg-in-fruit 
        ", IS:" g-nrg-in-fruit )    
    ]
    
    if (temp-total-nrg != g-total-nrg-in-system )
    [ 
      set b-accounts-are-all-valid 0 
      LOG-TO-FILE ( word 
        "T-nrg-check: SB:" temp-total-nrg 
        ", IS:" g-total-nrg-in-system )    
    ]
  ]
  
  report b-accounts-are-all-valid
  
  ;; End of frb-nrg-accounts-are-all-valid
end 

;;-----------------------------------------------------------------------------|
;; Check whether the agents are all valid.

to-report frb-agents-are-all-valid 
;; This routine can be run by the observer.

  let b-agents-are-all-valid true
  
  if( gb-debug-on = 1 )
  [
    ;; Do the check only if debug is on.
    
    ;; Check the seekers.
    ask seekers
    [
      if( frb-seeker-is-valid = false ) [ set b-agents-are-all-valid false ]
    ]
  ]
  
  report b-agents-are-all-valid
  
  ;; End of frb-agents-are-all-valid
end 

;;-----------------------------------------------------------------------------|
;; Check whether a seeker is valid.

to-report frb-seeker-is-valid 
;; This routine can be run by a seeker.

  let b-seeker-is-valid true
  
  report b-seeker-is-valid
  
  ;; End of frb-seeker-is-valid
end 

There is only one version of this model, created about 2 years ago by Garvin Boyle.

Attached files

File Type Description Last updated
04 TpLab V2.07.png preview Preview for '04 TpLab V2.07' about 2 years ago, by Garvin Boyle Download
141129 NTF - NetLogo Stds for OrrerySW R2.pdf pdf Prepared standards for Orrery Software for NetLogo projects. about 2 years ago, by Garvin Boyle Download
160702 03 PPT MPP in Sustainable Society R8.pptx pdf A presentation at ISEE 2017 on the nature of the MPP and its role in economics. about 2 years ago, by Garvin Boyle Download
170219 NTF Reconciling Eco n Sci R5.pdf pdf A proposal on how to reconcile science and economics (draft). about 2 years ago, by Garvin Boyle Download
170322 NTF TpLab Change Log R2.07.pdf pdf The most recent change diary. about 2 years ago, by Garvin Boyle Download

This model does not have any ancestors.

This model does not have any descendants.