The AHA Model  Revision: 12809
Reference implementation 04 (HEDG02_04)
m_common.f90
Go to the documentation of this file.
1 !> @file m_common.f90
2 !! This module defines common global parameters and objects for the AHA Model.
3 !! It also contains a general overview of the AHA Model in Doxygen notation.
4 !! @author Sergey Budaev <sergey.budaev@uib.no>
5 !! @author Jarl Giske <jarl.giske@uib.no>
6 !! @date 2016-2017
7 
8 !-------------------------------------------------------------------------------
9 ! $Id: m_common.f90 9552 2020-06-06 07:26:50Z sbu062 $
10 !-------------------------------------------------------------------------------
11 
12 ! Note: This is the starting main Doxygen documentation page. It should be
13 ! subdivided using @section @subsection @subsubsection tags rather than
14 ! the Markdown ###-style.
15 
16 !> @mainpage The AHA Model: Evolution of decision making and behaviour
17 !> @section intro_aha_intro Overview of The AHA Model
18 !! This is a large scale simulation model (under development) that implements
19 !! a general **decision-making architecture** in **evolutionary agents**. Each
20 !! agent is programmed as a whole virtual organism including the genome,
21 !! rudimentary physiology, the hormonal system, a cognitive architecture and
22 !! behavioural repertoire. They "live" in a stochastic spatially explicit
23 !! virtual environment with physical gradients, predators and prey. The primary
24 !! aim of the whole modelling machinery is to understand the evolution of
25 !! decision making mechanisms, personality, emotion and behavioural plasticity
26 !! within a realistic ecological framework. An object-oriented approach coupled
27 !! with a highly modular design not only allows to cope with increasing layers
28 !! of complexity inherent in such a model system but also provides a framework
29 !! for the system generalizability to a wide variety of systems. We also use
30 !! a "physical-machine-like" implementation philosophy and a coding standard
31 !! integrating the source code with parallel detailed documentation that
32 !! increases understandability, replicability and reusability of this model
33 !! system.
34 !!
35 !> The cognitive architecture of the organism is based on a set of
36 !! motivational (emotional) systems that serves as a common currency for
37 !! decision making. Then, the decision making is based on **predictive
38 !! assessment** of external and internal stimuli as well as the agent's own
39 !! motivational (emotional) state. The agent makes a subjective assessment
40 !! and selects, from the available repertoire, the behaviour that would reduce
41 !! the expected motivational (emotional) arousal. Thus, decision making is
42 !! based on predicting one's own internal state. As such, the decision-making
43 !! architecture integrates motivation, emotion, and a very simplistic model
44 !! of consciousness.
45 !!
46 !! The **purpose** of the AHA model is to investigate a general framework for
47 !! modelling proximate decision-making and behavior. From this we will
48 !! investigate adaptive goal-directed behaviour that is both guided by the
49 !! external environment and still is endogeneously generated.
50 !!
51 !! Other research topics include individual differences, personality as well
52 !! as consequences of emotion and personality to population ecology.
53 !!
54 !! We think that understanding and modelling complex adaptive behaviour
55 !! requires both extraneous (environmental) factors and stimuli as well as
56 !! endogeneous mechanisms that produce the behaviour. Explicit proximate
57 !! representation of the motivation and emotion systems, self-prediction can
58 !! be an important component in linking environment, genes, physiology,
59 !! behavior, personality and consciousness.
60 !!
61 !! - The AHA! Project Development Pages: http://ahamodel.uib.no
62 !! - Building blocks of the AHA Model: @ref aha_builblocks_main
63 !! - The Cognitive Architecture of the agent: @ref aha_buildblocks_cogn_arch
64 !! .
65 !!
66 !! Fortran is used due to its simplicity and efficiency. For example, check out
67 !! this paper:
68 !! [Why physicists still use Fortran?](http://www.moreisdifferent.com/2015/07/16/why-physicsts-still-use-fortran).
69 !!
70 !! Main features of modern Fortran that are used in the AHA model code
71 !! are briefly outlined in the
72 !! [README_NF](http://ahamodel.uib.no/doxydoc/md__r_e_a_d_m_e__n_f.html) .
73 !!
74 !> @section intro_version Version information
75 !! This is the model version information parsed from the main Subversion
76 !! repository https://svn.uib.no/aha-fortran or Bitbucket Mercurial-based
77 !! repository https://bitbucket.org/ahaproject/hedg2_01 (the latter is
78 !! currently used just as a mirror of the Subversion branch).
79 !! @verbatim
80 !! $Id: m_common.f90 9552 2020-06-06 07:26:50Z sbu062 $
81 !! @endverbatim
82 !! Version information is also saved as two variables that can be passed to
83 !! the logger (see commondata::logger_init()) and outputs and file names:
84 !! - commondata::svn_version_string, full version string as above;
85 !! - commondata::svn_version, version number (hex id).
86 !! .
87 !! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
88 !!
89 !> @section intro_main Working with the Model
90 !! A "Getting Started" introduction is available in the
91 !! [README.md](http://ahamodel.uib.no/doxydoc/md__r_e_a_d_m_e.html) file.
92 !!
93 !> @subsection intro_overview_modules Overview of the AHA Fortran modules
94 !! The Modelling framework is composed of two separate components:
95 !! - [HEDTOOLS](http://ahamodel.uib.no/doc/HEDTOOLS.pdf)
96 !! (also [mirror at bitbucket](https://bitbucket.org/teg_uib/hedtools)),
97 !! modelling utilities and tools implemented as portable Fortran
98 !! modules, not object-oriented, that have general applicability and are
99 !! used for data conversion, output, random number generation and
100 !! execution logging. HEDTOOLS modules are designed such that they can be
101 !! used in many different simulation projects, not only the AHA model;
102 !! - @ref intro_aha_intro "The AHA model", an object oriented evolutionary
103 !! agents simulation framework implementing reusable module components.
104 !! @image html aha_modules.svg "Overview of AHA Fortran modules"
105 !! @image latex aha_modules.eps "Overview of AHA Fortran modules" width=14cm
106 !!
107 !> @subsection intro_running Running the model
108 !! Building and running the mode is based on the GNU Make system.
109 !! - To **build** the model from the source code issue:
110 !! @code{.sh}
111 !! make
112 !! @endcode
113 !! - To build and **run** the model issue this command:
114 !! @code{.sh}
115 !! make run
116 !! @endcode
117 !! - **Delete** all build-related, data and temporary files:
118 !! @code{.sh}
119 !! make distclean
120 !! @endcode
121 !! - Get a quick **help** from the make system:
122 !! @code{.sh}
123 !! make help
124 !! @endcode
125 !! - The compiler can be provided via `FC` variable, e.g.
126 !! @code{.sh}
127 !! make run FC=ifort
128 !! @endcode
129 !! - Building with debug symbols is controlled by setting the `DEBUG` variable.
130 !! @code{.sh}
131 !! make run FC=ifort DEBUG=1
132 !! @endcode
133 !! .
134 !! See @ref Makefile for build configuration. To get more information on GNU
135 !! Make see [AHA Modelling Tools Manual](http://ahamodel.uib.no/doc/ar01s13.html),
136 !! [Using Microsoft Visual Studio](http://ahamodel.uib.no/doc/ar01s14.html) and
137 !! [Using Code::Blocks IDE](http://ahamodel.uib.no/doc/ar01s15.html).
138 !!
139 !> @subsection intro_environ_vars Environment variables
140 !! The model makes use of several environment variables to control
141 !! certain global aspects of the execution. These variables have the `AHA_`
142 !! prefix and are listed below.
143 !! - `AHA_DEBUG=TRUE` sets the @ref intro_debug_mode "debug mode";
144 !! - `AHA_SCREEN=YES` sets logger to write to the standard output in addition
145 !! to the log file;
146 !! - `AHA_DEBUG_PLOTS=YES` enables generation of debug plots;
147 !! - `AHA_ZIP_FILES=YES` enables background compression of big output
148 !! data files;
149 !! - `AHA_CHECK_EXTERNALS=NO` disables checking for external executable
150 !! modules (this is a workaround against Intel Fortran compiler bug).
151 !! .
152 !! They are described in details in the `commondata::system_init()` section.
153 !! **Setting** the environment variable on different platforms:
154 !! **Linux/Unix:**
155 !! @code{.sh}
156 !! export AHA_DEBUG=1
157 !! @endcode
158 !! **Windows:**
159 !! @code{.sh}
160 !! set AHA_DEBUG=1
161 !! @endcode
162 !! **Checking** if the environment variable is set and what is it value
163 !! On Unix/Linux:
164 !! @code{.sh}
165 !! echo $AHA_DEBUG
166 !! @endcode
167 !! On Windows
168 !! @code{.sh}
169 !! echo %AHA_DEBUG%
170 !! @endcode
171 !! To check if any of the above environment variables are set is easy on Linux:
172 !! @code{.sh}
173 !! env | grep AHA_
174 !! @endcode
175 !!
176 !> @subsection intro_debug_mode The DEBUG mode
177 !! The protected global variable `IS_DEBUG` (commondata::is_debug) sets
178 !! up the **debug mode** of execution. The debug mode results in huge
179 !! amount of output and logs that significantly slows down execution.
180 !! Debug mode can be set using the environment variable
181 !! `AHA_DEBUG=1`, `AHA_DEBUG=YES` or `AHA_DEBUG=TRUE`.
182 !> Debug mode can also be set by setting the runtime **command line**
183 !! parameter to `DEBUG`, `DEBUG=1`, `DEBUG=YES` or `DEBUG=TRUE`
184 !! to the model executable, e.g.
185 !! @code{.sh}
186 !! ./MODEL.exe DEBUG
187 !! @endcode
188 !! This runtime command line parameter is automatically set if the model
189 !! is started using the DEBUG variable for the GNU Make:
190 !! @code{.sh}
191 !! make run DEBUG=1
192 !! @endcode
193 !! *Build* Note also that `DEBUG` with make build command
194 !! @code{.sh}
195 !! make DEBUG=1
196 !! @endcode
197 !! will build the executable for the model in the debug mode also. All
198 !! compiler optimisations are turned off (`-O0`), debugger symbols (`-g`) and
199 !! tracebacks are enabled, various compiler error checking options and
200 !! warnings are also enabled, along with extended runtime checks.
201 !!
202 !! Notably, the Intel Fortran compiler enables initialisation of variables
203 !! with the signalling NaNs (`-init=snan`). Any operations on non-initialised
204 !! variable(s) would then result in the runtime crash with traceback, making
205 !! it easier to catch non-initialised variables.
206 !!
207 !! Normal build without setting `DEBUG`, in contrast, enables various compiler
208 !! optimisations making the executable run faster.
209 !! @code{.sh}
210 !! make
211 !! @endcode
212 !! Notably, with the Intel Fortran compiler, the model is built with automatic
213 !! parallelisation (`-parallel`), so whole array operations, `do concurrent`
214 !! and `pure` and `elemental` functions are run in the
215 !! [multi-threaded mode](http://ahamodel.uib.no/intel/hh_goto.htm?index.htm#GUID-29986DD5-C17F-49BB-AC9B-365B077C3909.html)
216 !! whenever the compiler is "sure" that these operations can be safely
217 !! performed.
218 !! See the @ref Makefile for specific compiler and debugging options and the
219 !! [GNU make](http://ahamodel.uib.no/doc/ar01s13.html) for a general overview of
220 !! the system. A overview of Intel Fortran parallel processing options can be
221 !! found
222 !! [here](http://ahamodel.uib.no/intel/hh_goto.htm#GUID-1E91DFFD-D7CD-4AF5-B911-7E5D1CCDBBA5.html)
223 !! and [here](http://ahamodel.uib.no/intel/hh_goto.htm?index.htm#GUID-06B54325-1C5C-41E7-A9CD-0E3A8542DC05.html).
224 !!
225 !! Combining the shell environment variable `AHA_DEBUG` and the `DEBUG` make
226 !! variable allows to control how the model executable is build and run.
227 !! For example, *building* it in *non-debug* mode, i.e. with all the
228 !! optimisations for fast (and possibly multi-threaded) execution:
229 !! @code{.sh}
230 !! make
231 !! @endcode
232 !! can be combined with *running* the model in the *debug* mode:
233 !! @code{.sh}
234 !! export AHA_DEBUG=YES
235 !! make run
236 !! @endcode
237 !! In such a case, the model is built and executed in the "fast" optimised
238 !! and possibly multi-threaded mode, but still prints all the numerous
239 !! debugging outputs into the logger.
240 !!
241 !! The system initialisation procedure commondata::system_init() and
242 !! commondata::logger_init() provide more details on initialisation and
243 !! logging.
244 !!
245 !> @subsection intro_overview_lockfile The lock file
246 !! At the start of the simulation, the program creates an empty **lock file**
247 !! defined by commondata::lock_file. The lock file is created at the end of
248 !! commondata::system_init() and and is deleted by the procedure
249 !! commondata::system_halt().
250 !!
251 !! The lock file indicates that the simulation is (still) running and could be
252 !! used by various scripts, cron jobs etc to make sure the simulation is
253 !! finished. For example, a script can check from time to time if the lock
254 !! file exists and if not, issue a command to zip all data outputs and transfer
255 !! them to a remote analysis server.
256 !!
257 !> @subsection intro_overview_stopfile The stop file
258 !! The stop file is an effective method to terminate the simulation at any
259 !! generation and avoiding any destructive consequences that would be caused,
260 !! for example, by using the `Ctrl+C` keypress or `kill` command. Thus, the
261 !! stop file is a signalling file.
262 !!
263 !! The name of the stop file is defined by the parameter
264 !! commondata::stop_file. This file is checked upon each new generation of
265 !! the Genetic Algorithm in the_evolution::generations_loop_ga()
266 !! (`CHECK_STOP_FILE` block). If this file is found, simulation will not
267 !! proceed to the next generation and will just stop as if it were the last
268 !! generation. All the data are saved as normal.
269 !! @note The stop file can be easily created on Lunux terminal by this command:
270 !! `touch stop_simulation_running.lock`. On Windows, these two command
271 !! can be used for the same purpose:
272 !! `type nul > stop_simulation_running.lock` or
273 !! `copy NUL stop_simulation_running.lock`. The lock file is deleted by
274 !! `make cleandata` command. Note also that once the stop
275 !! file is created in the model running directory, actual stop is not
276 !! immediate: it will be executed only at the next generation, the
277 !! currently running generation is completed to its end as normal.
278 !!
279 !> @subsection intro_overview_files_csv Output numerical data
280 !! Data could be output from the model. The standard format for data output is
281 !! [CSV](http://ahamodel.uib.no/doc/ar01s08.html). Its advantage is that it is
282 !! based on plain text and is human readable nut can be easily imported into
283 !! spreadsheets and statistical packages. The most straightforward use for CSV
284 !! is for vector-based data and two-dimensional matrices, including sets of
285 !! vectors (e.g. 'variables'/columns with 'observations'/rows).
286 !!
287 !! CSV output is based on the [CSV_IO](http://ahamodel.uib.no/doc/ar01s08.html)
288 !! module in [HEDTOOLS](http://ahamodel.uib.no/doc/). There is also an object
289 !! oriented wrapper for CSV_IO: @ref file_io.
290 !!
291 !! The model also includes a few standardised CSV output procedures for saving
292 !! various characteristics for a whole population of agents:
293 !! - the_population::population::save_csv() -- save various condition data;
294 !! - the_population::population::save_genomes_csv() -- save the complete genome
295 !! data of the agents;
296 !! - the_population::population::save_memory_csv() -- save the perceptual and
297 !! emotional memory stacks of the agents;
298 !! - the_population::population::save_movements_csv() -- save the latest
299 !! movement history of the agents.
300 !! - the_population::population::save_behaviour_csv() -- save the behaviour
301 !! history of the agents: successive labels of behaviours executed.
302 !! .
303 !! Additionally, the genetic algorithm subroutine
304 !! the_evolution::generations_loop_ga() implements a sub-procedure
305 !! - @ref generation_stats_record_write() -- produces various generation-wise
306 !! statistics, such as the number of surviving agents, average body mass
307 !! etc.
308 !! .
309 !!
310 !! The following procedures output the properties of the @ref the_environment
311 !! at a particular time step:
312 !! - the_environment::food_resource::save_csv() -- saves all the (stochastic)
313 !! food items that compose the the_environment::food_resource.
314 !! - the_environment::habitat::save_predators_csv --saves all the (possibly
315 !! stochastic) predators that are implemented within the habitat.
316 !! .
317 !!
318 !! @subsection intro_descriptors The Model descriptors
319 !! The model includes several descriptors that can be used for descriptive
320 !! notes on the model.
321 !! - commondata::model_name -- model name: a short name of the model;
322 !! - commondata::model_descr -- model description: a longer, one line
323 !! description of the model;
324 !! - The Model Abstract -- A brief text that can span several lines of text
325 !! and is kept in a separate file with the name defined by the
326 !! commondata::model_abstract_file parameter. If this file is absent,
327 !! model description is used.
328 !! .
329 !! These descriptors can appear in the model logger output and form parts of
330 !! the output data files.
331 !!
332 !! In particular, because the Model Abstract is stored in a separate text file,
333 !! it can contain dynamically updated information, such as the latest version
334 !! control message log output. Subversion and Mercurial commit hooks can be
335 !! used to implement such a functionality.
336 !!
337 !! To append version information (Subversion) to the Model Abstract file
338 !! manually do this:
339 !! @code
340 !! svn log -l1 >> abstract.txt
341 !! @endcode
342 !!
343 !> @subsection intro_style_rules Coding and documenting style
344 !! Using a consistent coding style increases the readability and
345 !! understandability of the program. It is also easier to search and locate
346 !! specific parts. For example, using specific rules for version control
347 !! commit messages make it easier to find specific changes by using regular
348 !! expression syntax. The coding rules for the AHA model are relatively light.
349 !!
350 !> @subsubsection intro_coding_style Fortran coding style
351 !! - Clean, readable and understandable code is much better than "tricky" but
352 !! more computationally efficient code.
353 !! - Obsolete, outdated and non-standard (e.g. vendor extensions) features
354 !! of the Fortran language should *never* be used.
355 !! - Very modern Fortran features (e.g. many F2008 and F2015) not well
356 !! supported by the available compilers should be avoided whenever possible.
357 !! - Portability is crucial: the model should be easy to build and run using
358 !! different compilers, GNU free software *gfortran* is the compiler of
359 !! priority.
360 !! - Frequent checking for errors (and even *possible* errors) is important;
361 !! correct computation has much higher priority than just speed.
362 !! - Use generic programming techniques (e.g. optional arguments, generic
363 !! interfaces) for higher extensibility.
364 !! - Always use explicit `intent` declared for all subroutines and functions.
365 !! - The line length should not exceed 80 characters; use continuation lines
366 !! and indents to make the structure clear.
367 !! - Spaces (not tabs) are used for indentation, standard indent is 2
368 !! characters.
369 !! - Use *lowercase* names for all local and Fortran intrinsic
370 !! objects.
371 !! - Global variables (not constants) should be in "CamelCase".
372 !! - Public or local *constants* (that are not changed) are in
373 !! UPPERCASE.
374 !! - External or library objects, e.g. those from the HEDTOOLS are in
375 !! UPPERCASE
376 !! - Module names are UPPERCASE, class names are UPPERCASE.
377 !! - Spatial objects (`SPATIAL` and `SPATIAL_MOVING`) use
378 !! `position` to *set* spatial position and `location` to
379 !! *get* it.
380 !! - `create` method is used to create and initialise an
381 !! empty object (e.g. `SPATIAL` with missing coordinates),
382 !! should not take other parameters and must be elemental
383 !! (so cannot include calls to random);
384 !! - `make` or `build` method is used to create a working object
385 !! with random initialisation etc.
386 !! .
387 !! See the [AHA Modelling Tools Manual](http://ahamodel.uib.no/doc/) for more
388 !! details (http://ahamodel.uib.no/doc/HEDTOOLS.pdf).
389 !!
390 !! The [README_NF](http://ahamodel.uib.no/doxydoc/md__r_e_a_d_m_e__n_f.html)
391 !! provides a brief outline of the main features of modern Fortran (F2003/2008)
392 !! that are used in the model code.
393 !!
394 !> @subsubsection intro_commit_style Version control style
395 !! - Commit messages noting specific subroutines or functions should
396 !! include the names of these procedures in parentheses:
397 !! @code{.sh}
398 !! svn ci -m "hope function (hope) now accepts arbitrary raw grid arrays"
399 !! @endcode
400 !! - Commit messages chenging only the Doxygen comments should start with
401 !! 'doc:', e.g.
402 !! @code{.sh}
403 !! svn ci -m "doc: still notes render poorly, try top put to return"
404 !! @endcode
405 !! .
406 !> @subsubsection intro_document_style Doxygen self-document style
407 !! - If something is changed in the *code*, the documentation comments
408 !! should also be checked for *correspondence with the code*, Doxygen
409 !! comments should *always* reflect the logic of the code and should
410 !! be never outdated.
411 !! - Document procedure purpose and brief implementation in the
412 !! over-the-procedure header comment block.
413 !! - *Local variables* are **not** in the Doxygen tags unless they
414 !! are very important, then include full paragraph description.
415 !! - Porting and F2008 compatibility notes and warnings are not in
416 !! the Doxygen tags unless they are very important.
417 !! - Unimportant implementation notes can be documented within
418 !! the body of the procedure *without* Doxygen "`!>`" tags. So they
419 !! are never parsed.
420 !! - *Important* implementation details are fully documented in
421 !! Doxygen tags. So they can be rendered if `HIDE_IN_BODY_DOCS` is
422 !! `NO`.
423 !! - Implementation details within the procedure body should be under
424 !! the level 3 headers enclosed in `###`:
425 !! @code
426 !! !> ### Implementation details ###
427 !! @endcode
428 !! - Full Fortran variable object hierarchy for instantiated objects must be
429 !! as normal text, i.e. **not enclosed in reverse single quotes** (as
430 !! verbatim code), because percent sign is not escaped and parsed wrongly
431 !! then:
432 !! @verbatim
433 !! this\%reprfact_decrement_testosterone
434 !! @endverbatim
435 !! not
436 !! @verbatim
437 !! `this\%reprfact_decrement_testosterone`
438 !! @endverbatim
439 !! or
440 !! @verbatim
441 !! this%reprfact_decrement_testosterone
442 !! @endverbatim
443 !! or still
444 !! @verbatim
445 !! `this%reprfact_decrement_testosterone`
446 !! @endverbatim
447 !! as the percent sign disappears in the parsed output.
448 !! - Reference to other subroutines and functions of the code must
449 !! be in the C++ style, referring the class/module in **lowercase**:
450 !! @verbatim
451 !! !! values resulting from executing this behaviour (`reproduce::do_this()`
452 !! !! = the_neurobio::reproduce_do_this() method). This is repeated for
453 !! @endverbatim
454 !! This makes them appear as cross-links in the parsed document.
455 !! - Documenting specific implementation procedure for in-type interface
456 !! name declaration should follow this style (include link to implementation):
457 !! @verbatim
458 !! !> Calculate the Euclidean distance between two spatial objects.
459 !! !! See `the_environment::spatial_distance_3d()`
460 !! procedure, public :: distance => spatial_distance_3d
461 !! @endverbatim
462 !! - Reference to a procedure that is defined within this (being documented)
463 !! procedure (i.e. below `contains`) is using the hanging `::` notation:
464 !! @verbatim
465 !! !! The subjective capture probabilityis calculated by the sub-function
466 !! !! `::subjective_capture_prob()`.
467 !! @endverbatim
468 !! - Documentation sections/subsections/subsubsections with tags are inserted
469 !! like this:
470 !! @verbatim
471 !! !> @subsubsection aha_buildblocks_genome_genome Individual genome
472 !! @endverbatim
473 !! They can be referred to in the documentation text using the tag like this:
474 !! @verbatim
475 !! !> @ref aha_buildblocks_individual "The individual agent" is also ...
476 !! @endverbatim
477 !! - The \@name tag defines an arbitrary **member group** of
478 !! Doxygen objects. Membership range is defined by the \@{ and
479 !! \@} tags. But this does not seem to work within `type`
480 !! definitions to delimiter outer procedure interfaces.
481 !!
482 !> @subsection intro_computation_notes Brief notes on computation
483 !> @subsubsection intro_computation_real Float point computations
484 !! There are many possible quirks and caveats with the real type (float point)
485 !! calculations on the computer. The rules of float point computations deviate
486 !! from the basic arithmetic. The main issue is that real type numbers are
487 !! represented as bits and have finite and limited precision. Furthermore,
488 !! numerical precision can deteriorate due to rounding in computations.
489 !!
490 !! The precision of the float point number representation in Fortran is
491 !! controlled by the kind parameter (e.g. `real(kind=some_number`) ).
492 !!
493 !! **Numerical precision modes**. In the AHA Model, there are two basic
494 !! numerical precision modes:
495 !! - commondata::srp, "Standard Real Precision" for real numbers that is
496 !! normally used for all computations:
497 !! @code
498 !! real(SRP) :: value
499 !! @endcode
500 !! @note Note that commondata::srp precision model should be used in most
501 !! cases.
502 !! - commondata::hrp, "High Real Precision", an extended precision that is used
503 !! in a few cases where commondata::srp is not enough for valid computation
504 !! (insufficient precision or inability to represent huge numbers):
505 !! @code
506 !! real(HRP) :: value
507 !! @endcode
508 !! Parenthetically, there is also an extended precision integer type defined
509 !! by commondata::long parameter.
510 !! .
511 !!
512 !! **Constants.** There is also a useful commondata::zero constant, which sets
513 !! some "minimum distinguishable non-zero" value: it is the smallest real
514 !! number *E* such that @f$ 1 + E > 1 @f$.
515 !!
516 !! The smallest positive real value is defined by the commondata::tiny_srp
517 !! constant. It is used in the definition of the default numerical tolerance
518 !! value for high precision calculations:
519 !! - commondata::tolerance_low_def_srp;
520 !! - commondata::tolerance_low_def_hrp (the same constant for the high
521 !! commondata::hrp precision with commondata::tiny_hrp).
522 !! .
523 !! @note Note that the commondata::tiny_srp and commondata::tiny_hrp values are
524 !! much smaller than the commondata::zero parameter. Also, the default
525 !! tolerance limits commondata::tolerance_low_def_srp and
526 !! commondata::tolerance_low_def_hrp are also much smaller than the
527 !! commondata::zero.
528 !!
529 !! Because the low tolerance based on the commondata::tiny_srp and
530 !! commondata::tiny_hrp may be too small and restrictive in many cases, the
531 !! second set of tolerance limits for low-precision calculations is based on
532 !! the commondata::zero parameter:
533 !! - commondata::tolerance_high_def_srp (commondata::srp real);
534 !! - commondata::tolerance_high_def_hrp (commondata::hrp real).
535 !! .
536 !! @note These high tolerance values should be used as the standard `epsilon`
537 !! in most cases.
538 !!
539 !! The default commondata::srp values of these parameters calculated on an
540 !! x86_64 platform under Linux are (an example only!):
541 !! @verbatim
542 !! ZERO: 1.19209290E-07
543 !! TINY_SRP: 1.17549435E-38
544 !! TOLERANCE_LOW_DEF_SRP: 5.87747175E-38
545 !! TOLERANCE_HIGH_DEF_SRP: 1.19209290E-04
546 !! @endverbatim
547 !! These constants are reported at the start of the logger output.
548 !!
549 !! **Real type equality**. One possible quirk in float point computation
550 !! involves equality comparison, e.g.
551 !! @code
552 !! if ( a == b) then ...
553 !! @endcode
554 !! With real type data `a` and `b`, such a condition can lead to unexpected
555 !! results due to finite precision and even tiny rounding errors: the numbers
556 !! that are deemed *equal* may in fact *differ* by a tiny fraction leading to
557 !! `a == b` condition being `FALSE`.
558 !!
559 !! Instead of the exact comparison, one should test whether the absolute
560 !! difference is smaller than than some predefined @f$ \varepsilon @f$
561 !! tolerance value (in the simplest case):
562 !! @f[ \left | a-b \right | < \varepsilon @f]
563 !! The @f$ \varepsilon @f$ is chosen based on the nature of the data and the
564 !! computational algorithm.
565 !!
566 !! The AHA Model framework includes a specific function for testing
567 !! *approximate equality* of two reals: commondata::float_equal(). With this
568 !! function, correct comparison is:
569 !! @code
570 !! if ( float_equal(a, b, epsilon) ) then ...
571 !! @endcode
572 !! There is also a user defined operator "float equality" `.feq.` that works
573 !! as the commondata::float_equal() function, but uses a fixed default
574 !! `epsilon` equal to the default tolerance commondata::tolerance_low_def_srp
575 !! (or commondata::tolerance_low_def_hrp for high precision). Its benefit is
576 !! that the usage almost coincides with the `==` (`.eq.`) operator usage:
577 !! @code
578 !! if ( a .feq. b) then ...
579 !! @endcode
580 !! See the backend procedures commondata::float_equal_srp_operator() and
581 !! commondata::float_equal_hrp_operator() for details.
582 !! Another similar operator is "approximate equality" `.approx.` has a much
583 !! higher level of tolerance (larger error accepted)
584 !! @code
585 !! if ( a .approx. b) then ...
586 !! @endcode
587 !! See the backend procedures commondata::float_approx_srp_operator() and
588 !! commondata::float_approx_hrp_operator() for details.
589 !!
590 !! There is also a function for testing if a real value is approximately equal
591 !! to zero: commondata::is_near_zero():
592 !! @code
593 !! if ( is_near_zero(a) ) then ! correct equivalent of if ( a == 0.0 )
594 !! @endcode
595 !!
596 !! @subsubsection intro_computation_missing Initialisation undefined constants
597 !! When a variable is created but not yet initialised, its value is
598 !! "undefined". However, it can take some haphazard values depending on the
599 !! compiler and the platform. There are special "initialisation" constants
600 !! defined in @ref commondata that set "missing" or "undefined" variable
601 !! status: commondata::missing (real) and commondata::unknown (integer).
602 !! By default, they are set to an unusual negative number -9999, so that any
603 !! bugs are clearly exposed if a variable inadvertently uses such an
604 !! "undefined" value.
605 !!
606 !! @subsubsection intro_computation_nonpar Nonparametric functions
607 !! The model in many cases makes use of **nonparametric relationships** between
608 !! parameters. This is based on the linear and non-linear interpolation
609 !! procedures implemented in HEDTOOLS:
610 !! [Interpolation routines](http://ahamodel.uib.no/doc/ar01s07.html#_interpolation_linterpol_ddpinterpol_interp_linear_interp_lagrange)
611 !!
612 !! Instead of defining specific function equation linking, say, parameters
613 !! *X* and *Y*: *Y=f(X)*, the relationship is defined by an explicit **grid**
614 !! of *X* and *Y* values without specifying any equation.
615 !!
616 !! In the simplest two-dimensional case, such a grid is defined by two
617 !! parameter arrays, for the *abscissa* and the *ordinate* of the nonparametric
618 !! function. Any values of this function can then be calculated based on a
619 !! nonlinear interpolation. This makes it very easy to specify various
620 !! patterns of relationships even when exact function is unknown or not
621 !! feasible.
622 !!
623 !! An example of such a nonparametric function is
624 !! the_neurobio::gos_global::gos_find().
625 !!
626 !> @subsection intro_webresources_model Links for more information
627 !> **AHA/BEAST Resources:**
628 !> - AHA Model repository mirror on Bitbucket:
629 !! https://bitbucket.org/ahaproject/hedg2_01
630 !! - Full documentation for the AHA Model in PDF:
631 !! http://ahamodel.uib.no/doxydoc/refman.pdf
632 !! - HEDTOOLS repository mirror on Bitbucket:
633 !! https://bitbucket.org/teg_uib/hedtools
634 !! - HEDTOOLS documentation in HTML format: http://ahamodel.uib.no/doc
635 !! - HEDTOOLS documentation as a single PDF file:
636 !! http://ahamodel.uib.no/doc/HEDTOOLS.pdf
637 !! - Development statistics for the model:
638 !! http://ahamodel.uib.no/devstat/dir_branches_budaev_HEDG2_01.html
639 !! - TEG development statistics from Subversion: http://ahamodel.uib.no/devstat
640 !!
641 !> **Tools web resources:**
642 !! - GNU Fortran documentation: https://gcc.gnu.org/onlinedocs/
643 !! (note that the model code targets features of the pre-version 5 because
644 !! of their wider availability in Linux repos.)
645 !! - GNU Fortran 4.9: https://gcc.gnu.org/onlinedocs/gcc-4.9.4/gfortran/
646 !! .
647 !! - Intel Fortran compiler documentation: http://ahamodel.uib.no/intel/
648 !! (note that the model code targets version 17.0)
649 !! - Automatic parallelisation is [here](http://ahamodel.uib.no/intel/index.htm#GUID-06B54325-1C5C-41E7-A9CD-0E3A8542DC05.html)
650 !! .
651 !! - Doxygen documentation: http://www.doxygen.org/
652 !! - Special tags: http://www.stack.nl/~dimitri/doxygen/manual/commands.html
653 !! - Formulas: http://www.stack.nl/~dimitri/doxygen/manual/formulas.html
654 !! .
655 !! - GNU Make: https://www.gnu.org/software/make/
656 !! .
657 !! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
658 !> @section aha_builblocks_main Building blocks of the AHA model
659 !> @subsection aha_buildblocks_environ The environment
660 !! The environment is a full 3D space, that is has the class
661 !! the_environment::spatial as the elementary base primitive. The
662 !! the_environment::spatial is a single object that has *X, Y and Z* (depth)
663 !! coordinates. the_environment::spatial_moving extends the basic
664 !! the_environment::spatial object by allowing it to move. Furthermore,
665 !! the_environment::spatial_moving includes a history stack that records the
666 !! latest history of such a spatial moving object. Examples of spatial moving
667 !! objects can be food items (the_environment::food_item), predators
668 !! (the_environment::predator), and more complex objects composed of several
669 !! the_environment::spatial components like the_environment::environment.
670 !!
671 !! The basic environment where the agents "live" is very simplistic in this
672 !! version of the model. It is just and empty box. The box is delimited by the
673 !! basic environmental container: the_environment::environment class.
674 !! The the_environment::habitat class is the ecological "habitat", an extension
675 !! of the basic the_environment::environment that adds various ecological
676 !! characteristics and objects such as the_environment::food_resource, array
677 !! of the_environment::predator objects etc.
678 !!
679 !! Normally, the movement of the agent is limited to a specific
680 !! the_environment::environment container with its own the_environment::habitat.
681 !! All the habitats that are available for the agents are arranged into a
682 !! single global public array the_environment::global_habitats_available.
683 !!
684 !! @ref aha_buildblocks_individual "The individual agent" is also an extension
685 !! of the the_environment::spatial class: the_environment::spatial →
686 !! the_environment::spatial_moving → the_genome::individual_genome → ... →
687 !! the_population::member_population.
688 !!
689 !! @image html aha_environment_diagr.svg
690 !! @image latex aha_environment_diagr.eps "Environmental objects" width=14cm
691 !! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
692 !!
693 !> @subsection aha_buildblocks_genome The genome structure
694 !! A brief outline of the genetic architecture, defined in the_genome, is
695 !! presented on this scheme.
696 !! - the_genome::gene
697 !! - the_genome::chromosome
698 !! - the_genome::individual_genome
699 !! .
700 !> @subsubsection aha_buildblocks_genome_gene Gene
701 !! The agent has genes (class the_genome::gene) that are arranged into
702 !! chromosomes (class the_genome::chromosome). Each gene also
703 !! includes an arbitrary number of additive components (see the_genome::gene).
704 !! @image html aha_genome_01.svg
705 !! @image latex aha_genome_01.eps "The genome structure" width=14cm
706 !> @subsubsection aha_buildblocks_genome_chromosome Chromosome
707 !! Here is a brief outline of the chromosome structure. The chromosomal
708 !! architecture allows arbitrary ploidity (however haploid is not supported,
709 !! although can be easily added), i.e. agents with diploid and polyploid
710 !! genomes can be implemented. Ploidity is defined by a single parameter
711 !! commondata::chromosome_ploidy.
712 !!
713 !> Correspondence between the genotype and the phenotype (hormones,
714 !! neurobiological modules etc.) is represented by boolean
715 !! **Gene x Phenotype matrices**. Any arbitrary structure can be implemented,
716 !! many traits controlled by a single gene, many genes controlling a specific
717 !! single trait.
718 !! @anchor aha_buildblocks_gp_matrix_intro
719 !! @image html aha_genome_02.svg
720 !! @image latex aha_genome_02.eps "Genotype x phenotype matrix" width=14cm
721 !!
722 !! An example of such a structure is the genetic sex determination:
723 !! commondata::sex_genotype_phenotype.
724 !!
725 !! There is a small utility script `tools\gpmatrix.tcl` that assists in
726 !! automatic production of the Fortran code for such a matrix.
727 !! @image html img_doxygen_gpmat.png "gpmatrix.tcl utility"
728 !! @image latex img_doxygen_gpmat.png "gpmatrix.tcl utility" width=12cm
729 !! @remark Windows distribution for Tcl/Tk language is obtained
730 !! [here](http://www.activestate.com/activetcl)).
731 !!
732 !> @subsubsection aha_buildblocks_genome_genome Individual genome
733 !! The the_genome::individual_genome class defines the basic higher-level
734 !! component properties of the whole organism, such as sex (logical type
735 !! the_genome::individual_genome::sex_is_male), genome size
736 !! (the_genome::individual_genome::genome_size), individual string "name"
737 !! of the agent (the_genome::individual_genome::genome_label) etc.
738 !!
739 !! The the_genome::individual_genome class also includes such type-bound
740 !! procedures as the_genome::individual_genome::lives() that gives the agent
741 !! the "alive" status, the_genome::individual_genome::dies() for making the
742 !! agent "dead". It also has linked procedures implementing genetic crossover
743 !! - the_genome::individual_genome::recombine_random(),
744 !! - the_genome::individual_genome::recombine_partial(),
745 !! - the_genome::individual_genome::crossover().
746 !! .
747 !! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
748 !!
749 !> @subsection aha_buildblocks_individual The individual agent
750 !> The individual agent has a `the_environment::spatial_moving` class as its
751 !! base (but this class is an extension of the simple the_environment::spatial)
752 !! and is then composed of several layers by class extensions.
753 !!
754 !! Each of these main layers that create the individual agent is defined in
755 !! separate Fortran module:
756 !! - genome (the_genome module);
757 !! - hormones (the_hormones module);
758 !! - the body characteristics and condition (the_body);
759 !! - neurobiological architecture (the_neurobio);
760 !! - behaviour architecture (the_behaviour) that builds on the neurobiology;
761 !! - finally, the agent is a member of a population (the_individual and
762 !! the_population::member_population).
763 !! .
764 !!
765 !! @image html aha_individual_class.svg
766 !! @image latex aha_individual_class.eps "The individual class layers" width=14cm
767 !!
768 !! The model code benefits from Fortran intrinsic "elemental" and array-based
769 !! procedures. To initialise a whole population of random agents (with full
770 !! object hierarchy) use the the_population::population::init() method:
771 !! @code
772 !! call generation_one%init(POPSIZE)
773 !! @endcode
774 !! Invocation of the 'init' method calls a whole cascade of various elementary
775 !! object-bound procedures that create the whole population object.
776 !!
777 !! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
778 !! @subsection aha_buildblocks_visrange Localist interactions
779 !! The model is based on (almost) fully proximate and localist philosophy.
780 !! All objects (agents, predators, prey) can obtain information about only
781 !! those objects that in proximity. No one is considered omniscient. Thus,
782 !! objects can only interact locally, e.g. the agent can eat only food items
783 !! that it could see, a predator could only attack agents that are visible to
784 !! it etc.
785 !!
786 !! The distance at which the objects can get information about each other
787 !! is based on the visibility (visual range). Thus, the agents and predators
788 !! are considered to be fully visual creatures that can only sense the world
789 !! with their vision.
790 !!
791 !! Visibility, i.e. the distance from which an object can be detected ("seen")
792 !! depends on the ambient illumination at a specific depth, the area of the
793 !! object, its contrast etc. Visual range is calculated for the different
794 !! kinds of objects using the the_environment::visual_range() backend.
795 !!
796 !! Examples of the visual range are the visibility distance of an agent
797 !! the_body::condition::visibility(), food item
798 !! the_environment::food_item::visibility(), and predator
799 !! the_environment::predator::visibility().
800 !!
801 !! Importantly, the @ref aha_buildblocks_percept "perception" of various
802 !! kinds of environmental objects by the agent uses the
803 !! the_environment::visual_range() calculation engine.
804 !!
805 !! Furthermore, probabilities of stochastic events typically have non-linear
806 !! relationships with the visual range. One example is the probability of
807 !! capture of a food item by the agent. This probability is high in close
808 !! proximity but strongly reduces at the distance equal to the visual range
809 !! limit: the_environment::food_item::capture_probability(). Similarly, the
810 !! risk that the agent is killed by a predator is highest at a small distances
811 !! and significantly reduces at a distance equal to the visibility limit (i.e.
812 !! the maximum distance the predator can see the agent):
813 !! the_neurobio::perception::risk_pred(). A more complex procedure is
814 !! implemented for the probability of successful reproduction:
815 !! the_neurobio::appraisal::probability_reproduction().
816 !!
817 !! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
818 !! @subsection aha_buildblocks_cogn_arch The Cognitive Architecture
819 !! The cognitive architecture of the agent is represented on the scheme below.
820 !! It includes several functional units, "bundles," each representing specific
821 !! motivation or emotion state.
822 !! @note Note that the scheme below includes three such bundles for the states
823 !! *A*, *B*, *C*. For simplicity, there are also only three stimuli
824 !! @f$ S_1, S_2, S_3 @f$ .
825 !!
826 !> @image html aha_global_scheme_neuroresp.svg "General cognitive architecture of the agent"
827 !! @image latex aha_global_scheme_neuroresp.eps "General cognitive architecture of the agent" width=14cm
828 !!
829 !! **General.** The agent perceives the outer and its own inner environment,
830 !! obtaining perception (signal) values. The agent also has several motivation
831 !! (emotional) states, such that only one can be active at any time step of the
832 !! model. Thus, the states compete for this position. The winning motivation
833 !! (emotion) becomes the dominant emotional state of the agent, its Global
834 !! Organismic State. This @ref aha_buildblocks_neurobioflow_gos
835 !! "Global Organismic States" of the agent determines how the agent weights
836 !! different options during its decision making process and therefore
837 !! determines what kind of behaviour (action) it will execute.
838 !!
839 !! **Perception and appraisal.** The agent obtains
840 !! @ref aha_buildblocks_neurobioflow_perc "perceptions" (*P*) from its
841 !! external and internal environments. These perceptions are fed into the
842 !! @ref aha_buildblocks_neurobioflow_appr "Appraisal" modules, separate for
843 !! each of the motivation/emotion state.
844 !!
845 !! Here perception signals are first fed into the
846 !! @ref aha_buildblocks_neuronal_resp "neuronal response functions" (based on
847 !! the sigmoidal function commondata::gamma2gene()). The neuronal response
848 !! function is a function of both the perception signal (*P*) and the
849 !! genome (*G*) of the agent. Perception signal is also distorted by a
850 !! random Gaussian error. Each neuronal response function returns the neuronal
851 !! response (*R*) value.
852 !!
853 !! The neuronal responses *R* for each stimulus are summed for the same
854 !! motivation module to get the *primary motivation* values
855 !! (@f$ M_1 @f$) for this motivational state. These primary motivations can
856 !! then be subjected to genetic or developmental (e.g. age-related)
857 !! **modulation**, resulting in the *final motivation* values (@f$ M_{f} @f$).
858 !! Such modulation could strengthen or weaken the motivation values and
859 !! therefore shift the outcome of competition between the different
860 !! motivational states. In absence of modulation @f$ M_1 = M_{f} @f$.
861 !!
862 !! **Global Organismic State.** Final motivations (@f$ M_{f} @f$) for different
863 !! motivations (emotions) are competing, so that the winning state that is
864 !! characterised by the highest final motivation value becomes the dominant
865 !! emotional state of the agent: its @ref aha_buildblocks_neurobioflow_gos
866 !! "Global Organismic State" at the next time step. Additionally, the final
867 !! motivation value of this state becomes the *GOS arousal* level.
868 !!
869 !! The competition mechanism is complex and dynamic. It depends on the
870 !! current arousal level, such that relatively minor fluctuations in the
871 !! stimuli and their associated motivation values are ignored and do not
872 !! result in switching of the GOS to a different state.
873 !!
874 !! Furthermore, the relative difference (surplus) that the competing motivation
875 !! must have to win competition against the current state depends on the
876 !! current level of GOS arousal. If the current arousal level of the agent is
877 !! relatively low (motivation or emotion is weak), a competing state must
878 !! exceed a relatively higher threshold to win. However, if the current arousal
879 !! level is very high (high motivation or emotion), a competing state can win
880 !! even if it only slightly exceeds the current arousal level. Thus, the
881 !! emotional state of the agent is characterised by a degree of continuity or
882 !! "inertia" and such inetria is lower the higher is the current level of
883 !! arousal. The dynamic threshold mechanism for GOS competition is described
884 !! in details in the_neurobio::gos_find_global_state() procedure documentation
885 !! section.
886 !!
887 !! **Attention focus.** Whenever the agent has a specific Global Organismic
888 !! State, this state also affects the agent's *perception*. All the perception
889 !! inputs that belong to motivations other than the currently dominant (i.e.
890 !! the current GOS) are suppressed by *attention weights*. For example, if the
891 !! motivation *B* is the GOS, all the perception values linked with Motivation
892 !! *A* and *C* are suppressed. The suppression weights are proportional to the
893 !! current GOS arousal of the agent.
894 !!
895 !! Thus, the attention mechanism effectively filters out or "focus" the agent
896 !! on the stimuli that are linked with the current dominant emotional state.
897 !! Moreover, the stronger is the current GOS arousal, the stronger is such
898 !! attention focusing. Attention weight mechanism is described in details in
899 !! the the_neurobio::gos_attention_modulate_weights() procedure section.
900 !!
901 !! **Perception-to-arousal path.** This process, *perception → neuronal
902 !! response → motivation → GOS → arousal* is repeated at each time step of the
903 !! model as the agent acts in (e.g. moves through) its stochastic environment.
904 !! In effect, the dominant motivational and emotional state of the agent
905 !! changes adapting to to the latest changes in the inner and external
906 !! environment.
907 !!
908 !! **Self-predictive decision making**. Furthermore, the same processes (and
909 !! computer code procedures) are also evoked when the agent is *making the
910 !! decision* about what *behavioural action* to choose at each time step.
911 !!
912 !! Basically, the agent predicts what would be its perceptions and, for each
913 !! of the behavioural action available, runs the same process
914 !! (perception → neuronal response → motivation → GOS → arousal) and finally
915 !! selects the behaviour that would result in the lowest predicted GOS arousal.
916 !! Perceptions in this process are predicted from the agent's internal or
917 !! local external environment ("fake" perceptions in the `do_this` method for
918 !! each of the behaviour units). They are also subjected to attention
919 !! suppression, however, attention weights are transferred from the
920 !! agent's own current Global Organismic State by
921 !! the_behaviour::behaviour_base::attention_transfer() method.
922 !!
923 !! Thus, decision making of the agent is based on predicting one's own
924 !! emotional state. The emotional arousal therefore becomes a common currency
925 !! in decision making. See @ref aha_buildblocks_decision
926 !! "Predictive decision making" for more details.
927 !!
928 !! **Goal directed behaviour.** The cognitive architecture implemented in the
929 !! AHA model effectively produces goal-directed behaviour in the agents. The
930 !! "goal" is defined by the evolutionary process, the @ref aha_buildblocks_ga
931 !! "Genetic Algorighm". Specifically , the target "goal" is to survive, grow,
932 !! accumulate energy and reproduce. The agents that do best in this respect
933 !! pass their genes into the next generation.
934 !!
935 !! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
936 !! @subsection aha_buildblocks_ga The Genetic Algorithm
937 !! @subsubsection aha_buildblocks_ga1 Fixed explicit fitness GA
938 !! This version of the Genetic Algorithm (GA) is based on an explicitly
939 !! defined "fitness" value for each individual agent. The evolution then
940 !! optimises agents with respect to this fitness: only agents with high
941 !! fitness values pass their genes into the next generations.
942 !!
943 !! This algorithm for this kind of GA is simple and is implemented in the
944 !! the_evolution::generations_loop_ga() procedure:
945 !! - Initialise the first generation of agents (population) from random
946 !! genomes. This first generation becomes the "parents".
947 !! - Start the main GA generations loop
948 !! - All "parent"-population agents go via the full life cycle
949 !! (with many time steps), the_population::population::lifecycle_step().
950 !! - Fixed fitness is calculated for each individual agent showing how good
951 !! it did during the life cycle by the
952 !! the_individual::individual_agent::fitness_calc() method.
953 !! - All agents are sorted according to their fitness by
954 !! the_population::population::sort_by_fitness().
955 !! - Some number of the "best fitting" agents (i.e. those with the highest
956 !! fitness values) are selected for the new generation: their genomes
957 !! pass to the new "offspring" generation in an unchanged form (i.e.
958 !! this is an *elitism*-based GA algorithm): the_evolution::selection().
959 !! - The rest of the offspring population are obtained from the genomes of
960 !! the best fitting agents, however,
961 !! - parent's genomes randomly exchange their genetic material,
962 !! - the resulting offspring genomes are subject to random mutations.
963 !! .
964 !! These steps are implemented in the_evolution::mate_reproduce().
965 !! - This new offspring population now becomes the "parents". A mechanism
966 !! based on pointer swapping implemented in
967 !! the_evolution::generations_swap() avoids copying big arrays of agents.
968 !! .
969 !! - Finally, the algorithm goes to the next generation loop cycle.
970 !! .
971 !!
972 !! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
973 !> @subsection aha_buildblocks_lifecycle Life cycle of the agent
974 !! @subsubsection aha_buildblocks_life_init Initialisation
975 !! The life cycle of the agent begins with birth. In the first generation of the
976 !! Genetic Algorithm each agent is initialised from a random genome by calling
977 !! the the_individual::individual_agent::init() method. This method evokes a
978 !! cascade of procedures that initialise all levels of the
979 !! @ref aha_buildblocks_individual "individual agent" object hierarchy.
980 !!
981 !! All subsequent generations use pre-existing genomes that are passed from
982 !! the ancestral agents subject to genetic crossover and mutation. The
983 !! the_individual::individual_agent::init() procedure has a logical switch that
984 !! controls if a random genome should be generated.
985 !!
986 !! Because the population of agents is an object (class
987 !! the_population::population), a whole population of agents is initialised
988 !! by the the_population::population::init() method. After the birth, all
989 !! agents get random location within their initial the_environment::habitat
990 !! object by calling the_population::population::scatter_uniform().
991 !!
992 !! @subsubsection aha_buildblocks_life_time Life cycle step
993 !! Then, the agents pass through many time steps (commondata::lifespan).
994 !! At each time step each agent gets internal and environmental
995 !! @ref aha_buildblocks_percept "perceptions". Based on these instantaneous
996 !! perceptions, they obtain their main internal state: the
997 !! @ref aha_neurobio_flow "Global Organismic State" (GOS). Finally, each agent
998 !! must make a decision to execute a single specific
999 !! @ref aha_buildblocks_behaviour "behaviour" depending on its GOS, internal
1000 !! and external environment (@ref aha_buildblocks_percept "perception"). Some
1001 !! examples of such behaviour are eat a food item, approach a conspecific,
1002 !! escape from a predator, move, freeze, migrate to a novel environment,
1003 !! reproduce, etc.
1004 !!
1005 !! Each of the behaviour chosen by the agent has specific consequences and
1006 !! can
1007 !! - affect the agent (e.g. incurs energetic cost, or relocation of the
1008 !! whole agent into a novel environment, the agent is killed if it does not
1009 !! escape a nearby predator),
1010 !! - affect the other agents in proximity (e.g. emigration of an agent could
1011 !! change the risk of predation for other agents by changing the spatial
1012 !! configuration and therefore modifying predation dilution and confusion
1013 !! effects for the agents that remain in place),
1014 !! - affect the external environment (e.g. food item disappears when an agent
1015 !! eat it).
1016 !! .
1017 !!
1018 !! Whenever the agent successfully consumes food items, it grows
1019 !! its mass and length: the_body::condition::mass_grow(),
1020 !! the_body::condition::len_grow().
1021 !! On the other hand, every movement incurs some energetic cost:
1022 !! the_body::condition::cost_swim(). There are also additional costs linked
1023 !! with specific behavioural actions, e.g. food processing cost
1024 !! the_body::condition::food_process_cost() or the cost of successful
1025 !! (the_body::reproduction::reproduction_cost()) or unsuccessful
1026 !! (the_body::reproduction::reproduction_cost_unsuccess()) reproduction.
1027 !!
1028 !! There is also an overall living cost that is subtracted
1029 !! (the_body::condition::subtract_living_cost()). Additionally, digestion
1030 !! occurs by emptying the agent's stomach by a fixed fraction
1031 !! (the_body::condition::stomach_empify() at each time step.
1032 !!
1033 !! @subsubsection aha_buildblocks_life_predation Predation and mortality
1034 !! At each time step, the agent can be subjected by random disastrous events,
1035 !! such as habitat-specific random mortality
1036 !! the_population::population::mortality_habitat() or predatory attacks
1037 !! the_population::population::attacked(). If the predatory attack is
1038 !! successful, the agent the_genome::individual_genome::dies() and cannot
1039 !! normally pass its genome into the next generation.
1040 !!
1041 !! The agents are also checked at various stages of their life cycle for
1042 !! starvation: the_body::condition::starved_death(). If the agent is starved,
1043 !! it also the_genome::individual_genome::dies().
1044 !!
1045 !! Predation risk (the probability of the agent being caught by the predator)
1046 !! is automatically adjusted if the predator can simultaneously perceive
1047 !! several conspecific agents. Depending on the number of such agents in the
1048 !! perceived group and individual distances between the predator and each
1049 !! agent, a predator dilution and confusion effects are calculated (see
1050 !! the_environment::predator::risk_fish_group()). By the way, when the agent
1051 !! makes the decision to approach conspecific in presence of a predator, it
1052 !! also evaluates how many other conspecifics are there and what is
1053 !! the relative distances between the conspecifics and the predator (see
1054 !! the_behaviour::approach_conspec::do_this()). The agent's decision therefore
1055 !! adjusts for the classical "selfish herd" effect.
1056 !!
1057 !! @subsubsection aha_buildblocks_life_compete Food competition
1058 !! Because many agents are dwelling within the same habitat with limited food
1059 !! resource (fixed number of the_environment::food_item objects),
1060 !! they also compete for food. For example, if two agents find themselves near
1061 !! the same food item, one or the other can eat it, whoever is the first to
1062 !! make the decision to the_behaviour::eat_food. If an agent successfully
1063 !! eats such food item, it is marked as the_environment::food_item::eaten and
1064 !! is not available for everyone else.
1065 !!
1066 !! Because the model is @ref aha_buildblocks_visrange "localist" and
1067 !! explicitly implements individual capture of each food item by each agent
1068 !! within spatially explicit habitats, any density- and frequency-dependent
1069 !! effects would appear automatically.
1070 !!
1071 !! @subsubsection aha_buildblocks_life_reprod Reproduction
1072 !! Whenever the agent the_body::reproduction::is_ready_reproduce(), it can
1073 !! make decision to the_behaviour::reproduce at a specific time step.
1074 !! The probability of successful reproduction in specific stochastic conditions
1075 !! is calculated by the_neurobio::appraisal::probability_reproduction(). As a
1076 !! consequence of successful reproduction, some number
1077 !! (the_body::reproduction::offspring_number()) of offspring are produced.
1078 !! How subjective value of reproduction is evaluated by the agent is dictated
1079 !! by the_behaviour::reproduce::do_this().
1080 !!
1081 !! @subsubsection aha_buildblocks_life_select Agent order and competition
1082 !! To avoid systematic biases, the agents make their behavioural choices in a
1083 !! random order (see
1084 !! [PERMUTE_RANDOM()](http://ahamodel.uib.no/doc/ar01s09.html#_random_permutation_permute_random_function)).
1085 !! However, it is also easy to implement any other sorted order,
1086 !! e.g. selecting agents according to their body weight: the body weight
1087 !! then would provide a strong competitive advantage.
1088 !!
1089 !! Any arbitrary order of the agents can be implemented using
1090 !! [array indexing](http://ahamodel.uib.no/doc/ar01s07.html#_subroutines_array_index_and_array_rank)
1091 !! mechanism. See the_population::population::lifecycle_step() for more
1092 !! discussion.
1093 !!
1094 !! @subsubsection aha_buildblocks_life_conclude Concluding remarks
1095 !! The long sequence of such decision makings in a stochastic environment at
1096 !! each time step constitutes the life cycle of the agent. Depending on how
1097 !! well the agent does during its life cycle (e.g. grows and reproduces)
1098 !! determines the chance that its genome passes to the next generation by the
1099 !! Genetic algorithm. Thus, the whole process simulates the behaviour, decision
1100 !! making and evolution.
1101 !!
1102 !! The following sections provide general information about the implementation
1103 !! and the object class hierarchy of the model code.
1104 !!
1105 !> @subsection aha_buildblocks_percept The perception mechanism
1106 !> @subsubsection aha_buildblocks_percept_overview Overview
1107 !! Perception is defined in the the_neurobio::perception class. Perception
1108 !! objects can be of three types:
1109 !! - Internal perception objects, depend on the body.
1110 !! - the_neurobio::percept_stomach
1111 !! - the_neurobio::percept_energy
1112 !! - the_neurobio::percept_age
1113 !! - the_neurobio::percept_reprfact
1114 !! .
1115 !! - Direct environmental perceptions (e.g. light).
1116 !! - the_neurobio::percept_light
1117 !! - the_neurobio::percept_depth
1118 !! .
1119 !! - External spatial perception objects, depend on the visual range.
1120 !! - the_neurobio::percept_food
1121 !! - the_neurobio::percept_predator
1122 !! - the_neurobio::percept_conspecifics
1123 !! .
1124 !! .
1125 !! @image html aha_neurobio_percept.svg
1126 !! @image latex aha_neurobio_percept.eps "Perception objects" width=14cm
1127 !!
1128 !> @subsubsection aha_buildblocks_percept_spatial Spatial perceptions
1129 !! External spatial perception components are truly "localist" and proximate,
1130 !! they get individual environmental objects (e.g. food items, individual
1131 !! conspecifics or predators) dynamically as the agent and the spatial objects
1132 !! move within the model 3D environment. This allows aha_buildblocks_gp_matrix_introto produce very complex
1133 !! environmental structures (e.g. patchy foods with Gaussian scatter). Also,
1134 !! every individual environmental object is perceived only if it is within
1135 !! the specific visual range. This means that, as food items are stochastic
1136 !! (have random Gaussian size), perception of each food item depends on its
1137 !! individually-specific visibility range. The same is true also for
1138 !! conspecifics, predators, etc.
1139 !! @image html img_doxygen_spatial_visrange.svg "Spatial perception"
1140 !! @image latex img_doxygen_spatial_visrange.eps "Spatial perception" width=14cm
1141 !!
1142 !> Selection of the nearest environmental objects that are within the current
1143 !! visual range (the_environment::spatial::neighbours()) is based on partial
1144 !! indexing (spatial segmentation) of potentially huge arrays of different
1145 !! objects (e.g. thousands of individual stochastic food items, each with
1146 !! specific visual range). Partial indexing allows very fast processing of
1147 !! only a subset of spatial objects that are in proximity of the agent (and
1148 !! therefore could fit into the visibility range), ignoring al other, more
1149 !! remote, objects in the same environment.
1150 !!
1151 !> @subsection aha_neurobio_flow From perception to GOS
1152 !! The overview below shows the sequence of the main procedures from perception
1153 !! (the_neurobio::perception class) through the_neurobio::appraisal to the
1154 !! determination of the Global Organismic State (GOS, the_neurobio::gos_global
1155 !! class).
1156 !> @image html aha_neurobio_appraisal.svg
1157 !> @image latex aha_neurobio_appraisal.eps "Appraisal objects" width=14cm
1158 !!
1159 !> @subsubsection aha_buildblocks_neurobioflow_perc Perception
1160 !> **Perception**: first, the agent obtains perceptions from its inner
1161 !! environment (such as age, stomach contents etc), the external environment
1162 !! (e.g. light, depth), as well as spatial perceptions (e.g. food items,
1163 !! conspecifics, predators). These *perception components* are described by
1164 !! the the_neurobio::percept_components_motiv class. Perception
1165 !! components represent a crucial component of each of the *motivational
1166 !! states*. Perceptions are obtained by calling these procedures:
1167 !! - the_neurobio::perception::perceptions_inner() - inner perceptions (an
1168 !! umbrella for several perceptions), these include:
1169 !! - the_neurobio::perception::feel_stomach()
1170 !! - the_neurobio::perception::feel_bodymass()
1171 !! - the_neurobio::perception::feel_energy()
1172 !! - the_neurobio::perception::feel_age()
1173 !! - the_neurobio::perception::feel_repfac()
1174 !! .
1175 !! - the_neurobio::perception::perceptions_environ() - environmental
1176 !! perceptions (an umbrella procedure for several perceptions) including
1177 !! - the_neurobio::perception::feel_light()
1178 !! - the_neurobio::perception::feel_depth()
1179 !! .
1180 !! - the_neurobio::perception::see_food() - get food;
1181 !! - the_neurobio::perception::see_pred() - get predators;
1182 !! - the_neurobio::perception::see_consp() - get conspecifics;
1183 !! .
1184 !! Notably, the spatial perceptions dynamically access stochastic external
1185 !! spatial objects using a fast algorithm based on partial distance ranking
1186 !! of spatial objects, a kind of spatial segmentation. This largely reduces
1187 !! the need to multiply loop across the objects and the agents over many
1188 !! time steps and generations.
1189 !> @subsubsection aha_buildblocks_neurobioflow_appr Appraisal
1190 !> **Appraisal**: perceptions are weighted by the *attention weights* and go
1191 !! into the *neuronal response* function
1192 !! the_genome::individual_genome::neuro_resp(), then summed to get the
1193 !! *primary* motivation value for each of the motivation states.
1194 !!
1195 !! #### Neuronal response function ####
1196 !! The neuronal response function @anchor aha_buildblocks_neuronal_resp has
1197 !! a central role in the model. It links the sensory perception from a specific
1198 !! environmental stimulus *P* (including the inner organism's environment), and
1199 !! the strength of the response to this stimulus (the neuronal response) *R*
1200 !! mediated by the genome. Neuronal response function is based on the sigmoidal
1201 !! equation that is implemented in commondata::gamma2gene() procedure.
1202 !!
1203 !! Note that this function is not based on a mechanistic understanding of the
1204 !! relationship between perception and neuronal response. Lacking such
1205 !! understanding, the genetic algorithm may produce a series of potentially
1206 !! adaptive relationships. Depending upon the allele values of the genes, the
1207 !! function can appear concave, sigmoidal, nearly linear, or convex in
1208 !! the *0 ≤ P ≤1* range. We use a sigmoidal function to avoid total lack of
1209 !! (emotional) interest at very low *P*.
1210 !!
1211 !! #### From neuronal responses to motivations and emotions ####
1212 !! There are currently four motivational states that the agent can have:
1213 !! @anchor aha_buildblocks_gp_motivations
1214 !! - the_neurobio::state_hunger
1215 !! - the_neurobio::state_fear_defence
1216 !! - the_neurobio::state_reproduce
1217 !! .
1218 !! All these motivational states represent extensions of the basic *abstract
1219 !! class* the_neurobio::state_motivation_base that is not used directly.
1220 !!
1221 !! Calculating the *primary* motivational values involves calling these
1222 !! procedures:
1223 !! - the_neurobio::appraisal::motivations_percept_components() -- perceptions
1224 !! are fed into the neuronal response function, obtain perceptual
1225 !! components for each of the above motivational states ;
1226 !! - the_neurobio::appraisal::motivations_primary_calc() -- perception
1227 !! components are fed into this procedure resulting in calculation of
1228 !! *primary* motivations, i.e. values of the above motivational states
1229 !! before they are subjected to any modulation.
1230 !! .
1231 !! These primary motivation values for each of the above four motivation
1232 !! states are subjected to genetic or developmental modulation, resulting
1233 !! in *final* motivation value for each of the motivational states:
1234 !! - the_neurobio::appraisal::modulation();
1235 !! .
1236 !! They are also recorded into the emotional memory stack by calling
1237 !! - the_neurobio::appraisal::motivations_to_memory();
1238 !! .
1239 !> @subsubsection aha_buildblocks_neurobioflow_gos GOS
1240 !! **GOS**: finally, a single *Global Organismic State* (GOS) is determined
1241 !! on the basis of the competition between the final values of all
1242 !! motivational states. GOS is determined in this procedure:
1243 !! - the_neurobio::gos_global::gos_find();
1244 !! - gos_find() also internally calls the attention modulation procedure
1245 !! the_neurobio::gos_global::attention_modulate() that limits attention
1246 !! all perceptions that are "irrelevant" for the current GOS;
1247 !! .
1248 !! .
1249 !! @subsubsection aha_buildblocks_neurobioflow_code Code example
1250 !! The code below is an example of the above steps, from
1251 !! @ref aha_buildblocks_neurobioflow_perc "perception" to @ref
1252 !! aha_buildblocks_neurobioflow_appr "appraisal" and
1253 !! @ref aha_buildblocks_neurobioflow_gos "GOS":
1254 !! @code{.f90}
1255 !! ! Perception:
1256 !! call proto_parents%individual(ind)%perceptions_inner()
1257 !! call proto_parents%individual(ind)%perceptions_environ()
1258 !!
1259 !! call proto_parents%individual(ind)%see_food( food_resource )
1260 !! call proto_parents%individual(ind)%see_consp( proto_parents%individual )
1261 !! call proto_parents%individual(ind)%see_pred( habitat_safe%predators )
1262 !!
1263 !! ! Add perceptions to the memory:
1264 !! call proto_parents%individual(ind)%perception_to_memory()
1265 !!
1266 !! ! Appraisal:
1267 !! call proto_parents%individual(ind)%motivations_percept_components()
1268 !! call proto_parents%individual(ind)%motivations_primary_calc()
1269 !! call proto_parents%individual(ind)%modulation()
1270 !! call proto_parents%individual(ind)%motivations_to_memory()
1271 !!
1272 !! ! GOS:
1273 !! call proto_parents%individual(ind)%gos_find()
1274 !! @endcode
1275 !! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1276 !!
1277 !> @subsection aha_buildblocks_behaviour The behavioural repertoire
1278 !> The *behavioural repertoire* of the agent is composed of several *behaviour
1279 !! units*, which are extensions of the basic the_behaviour::behaviour_base class
1280 !! (this is an abstract class and is not used directly). Thus, each component
1281 !! of the behavioural repertoire is a *separate object* `class` not linked
1282 !! with the *agent* class hierarchy (from the_genome::individual_genome up to
1283 !! the_neurobio::gos_global).
1284 !!
1285 !! However, all the individual components of the behavioural repertoire are
1286 !! collected together in the the_behaviour::behaviour class (that is in the
1287 !! agent class hierarchy). Thus, the behavioural repertoire of the agent is
1288 !! here *constructed* from individual behavioural components.
1289 !!
1290 !! @image html aha_neurobio_behav.svg "Construction of the behaviour"
1291 !! @image latex aha_neurobio_behav.eps "Construction of the behaviour" width=14cm
1292 !!
1293 !> @subsubsection aha_buildblocks_behav_elements Behavioural units
1294 !! Here is the behavioural repertoire of the agent:
1295 !! - the_behaviour::eat_food
1296 !! - the_behaviour::reproduce
1297 !! - the_behaviour::walk_random
1298 !! - the_behaviour::freeze
1299 !! - the_behaviour::escape_dart
1300 !! - the_behaviour::approach
1301 !! - the_behaviour::approach_conspec
1302 !! - the_behaviour::migrate
1303 !! - the_behaviour::go_down_depth
1304 !! - the_behaviour::go_up_depth
1305 !! .
1306 !! The inheritance structure of these behavioural units is shown on the scheme
1307 !! below.
1308 !!
1309 !! @image html aha_neurobio_behaviour.svg "The behaviour repertoire"
1310 !! @image latex aha_neurobio_behaviour.eps "The behaviour repertoire" width=10cm
1311 !!
1312 !! Some of the behaviours involve "movement", i.e. change of the spatial
1313 !! location. Such behaviours are programmed as extensions of the base class
1314 !! the_behaviour::move (this is also an abstract class that is not used
1315 !! directly).
1316 !! - the_behaviour::walk_random
1317 !! - the_behaviour::freeze
1318 !! - the_behaviour::escape_dart
1319 !! - the_behaviour::approach
1320 !! - the_behaviour::approach_conspec (an extension of the_behaviour::approach)
1321 !! - the_behaviour::migrate
1322 !! - the_behaviour::go_down_depth
1323 !! - the_behaviour::go_up_depth
1324 !! .
1325 !! Each of these *movements* can differ by its *distance* or length (although
1326 !! the_behaviour::freeze always has zero distance):
1327 !! the_behaviour::move::distance. Thus, there can be a whole repertoire of
1328 !! each of the above movements, such as Gaussian random walks or vertical
1329 !! migrations with different steps.
1330 !!
1331 !! the_behaviour::eat_food also involves movement but indirectly, so it is not
1332 !! related to the the_behaviour::move base class.
1333 !!
1334 !! Finally, certain behaviours involve specific "target object":
1335 !! - the_behaviour::eat_food
1336 !! - the_behaviour::escape_dart
1337 !! - the_behaviour::approach
1338 !! - the_behaviour::approach_conspec
1339 !! - the_behaviour::migrate
1340 !! .
1341 !! Such a target can be, for example, food items (the_environment::food_item),
1342 !! predators (the_environment::predator), conspecifics
1343 !! (the_neurobio::appraisal) or an environmental container
1344 !! (the_environment::environment).
1345 !!
1346 !! Combinations of several behavioural units with multiple *distances* (for
1347 !! movements) and *targets* creates an additional diversity, complexity and
1348 !! flexibility of the behaviour in the agents.
1349 !!
1350 !> @subsubsection aha_buildblocks_behav_complex Double role of motivation
1351 !! Notably, the the_neurobio::motivation class is included both into the
1352 !! **agent's** the_neurobio::appraisal (motivations) as well as into the
1353 !! **behaviour unit** the_behaviour::behaviour_base (expectancy).
1354 !!
1355 !! Such a complex design composed of separate behavioural units (separate
1356 !! classes although inheritances of the same base the_neurobio::motivation)
1357 !! makes it possible to generate behaviours that:
1358 !! - depend on inputs from the_neurobio::perception of the agent, both
1359 !! "objective" perceptions that flow from the environment and "subjective"
1360 !! perceptions that are internally generated as a part of the subjective
1361 !! evaluation of various possible outcomes of behaviour;
1362 !! - link **perception** to **motivation** both in the agent itself and
1363 !! in each of the behavioural units;
1364 !! - have multiple behaviours with their linked motivational expectancies that
1365 !! are collected (plugged) back into the agent class hierarchy;
1366 !! - so that the agent can compare the motivational expectancies from each
1367 !! of the possible behaviour units, also in response to each of the multiple
1368 !! perception targets (e.g. specific food items, conspecifics and predators);
1369 !! - the agent can select the behaviour (and the specific target) that depends
1370 !! on the expected arousal, for *execution*;
1371 !! - finally, this optimal behaviour is "executed" (with its specific target)
1372 !! by calling its specific `do_` method in the the_behaviour::behaviour class.
1373 !! - exactly the same class data structures and procedure(s) are employed
1374 !! to calculate the motivation values:
1375 !! - for the the_neurobio::appraisal::motivations of the **agent** and
1376 !! - for motivational the_behaviour::behaviour_base::expectancy of the each
1377 !! **behaviour unit**.
1378 !! .
1379 !! .
1380 !!
1381 !! @image html aha_neurobio_motivation.svg
1382 !! @image latex aha_neurobio_motivation.eps "Motivation and behaviour" width=14cm
1383 !!
1384 !! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1385 !> @subsection aha_buildblocks_decision Predictive decision making
1386 !> @subsubsection aha_buildblocks_decis_overview Overview
1387 !! Decision making in the AHA Model is centered around three concepts:
1388 !! - motivation (emotion)
1389 !! - global organismic state (GOS)
1390 !! - expected arousal
1391 !! .
1392 !! The main principle of decision maming is simple. It involves evaluating
1393 !! each of the available behavioural alternative (each behaviour unit with
1394 !! specific parameters and targets) to find those alternative which minimises
1395 !! the expected arousal. This option is then considered the *optimal* behaviour
1396 !! and and is finally *executed*. This is a kind of a "brute force"
1397 !! optimisation mechanism that aims to get the most optimal behavioiral
1398 !! outcome from the agent's knowledge of the local environment and its own
1399 !! internal state.
1400 !!
1401 !! Thus, each agent evaluates the environment in the context and in terms of
1402 !! *its own predicted internal state*. Thie outcome of such a process therefore
1403 !! depends both on the local instantaneous environmental context (depicted by
1404 !! the agent's local perception of food, conspecifics and predators), and the
1405 !! current internal state of the agent (its current motivation, the global
1406 !! organismic state, GOS).
1407 !!
1408 !! The emotional state of the agent represents the common currency, the GOS
1409 !! arousal, for predicting the optimal behaviour: selection of a single action
1410 !! out of numerous available alternatives.
1411 !!
1412 !> @subsubsection aha_buildblocks_decis_behaviour The umbrella class
1413 !! *Selection* and *execution* of the optimal behaviours is implemented in the
1414 !! the_behaviour::behaviour class, which is a pert of the individual agent class
1415 !! hierarchy. The the_behaviour::behaviour class collects all the separate
1416 !! behavioural units ans thereby serves an umbrella construict for the whole
1417 !! behavioural repertoire of the agent. It also includes high level execution
1418 !! procedures for each of the behavioural unit:
1419 !! - the_behaviour::behaviour::do_eat_food_item();
1420 !! - the_behaviour::behaviour::do_reproduce();
1421 !! - the_behaviour::behaviour::do_walk();
1422 !! - the_behaviour::behaviour::do_freeze();
1423 !! - the_behaviour::behaviour::do_escape();
1424 !! - the_behaviour::behaviour::do_approach();
1425 !! - the_behaviour::behaviour::do_migrate();
1426 !! - the_behaviour::behaviour::do_go_down();
1427 !! - the_behaviour::behaviour::do_go_up();
1428 !! .
1429 !! These execution "do_" procedures basically call the "execute" methods for
1430 !! their respective specific behaviour unit (each behaviour unit is implemented
1431 !! as a separate class class, see @ref aha_buildblocks_behav_elements
1432 !! "Behavioural units"). For example,
1433 !! the_behaviour::behaviour::do_eat_food_item() calls
1434 !! the_behaviour::eat_food::execute(). This provides a connection between
1435 !! the the_behaviour::behaviour umbrella class and each of the
1436 !! @ref aha_buildblocks_behav_elements "behavioural units". Furthermore,
1437 !! this connection allows to call a whole cascade of methods to assess and
1438 !! predict possible consequences of executing each of the possible behaviour.
1439 !!
1440 !> @subsubsection aha_buildblocks_decis_do_behave do_behave method
1441 !! The the_behaviour::behaviour class also implements the
1442 !! the_behaviour::behaviour::do_behave() method which provides a unitary
1443 !! interface for the evaluation, selection and execution of the optimal
1444 !! behaviour unit, i.e. the behaviour minimising the expected GOS arousal.
1445 !!
1446 !! The the_behaviour::behaviour::do_behave() method
1447 !! - Evaluates each of the available behavioural alternative given the
1448 !! specific current context (internal and external perception objects).
1449 !! This is implemented by the various lower order `select` procedures
1450 !! within `do_behave()`:
1451 !! - ::eat_food_select();
1452 !! - ::reproduce_select();
1453 !! - ::walk_random_select();
1454 !! - ::freeze_select();
1455 !! - ::escape_dart_select();
1456 !! - ::approach_consp_select();
1457 !! - ::migrate_select();
1458 !! - ::go_down_select();
1459 !! - ::go_up_select().
1460 !! .
1461 !! These `select` procedures calculate the arousal expectancy for each
1462 !! of the behavioural unit. If specific behaviour unit has multiple
1463 !! targets (e.g. several food items or several conspecifics) or parameters
1464 !! (e.g. random walks of different Gaussian length or vertical migrations
1465 !! with different step sizes), each such option is also evaliuated and the
1466 !! optimal one is determined (e.g. the "best" food item, eating which would
1467 !! result in lowest arousal).
1468 !! - Once the expected arousal level is known for each of the behaviours, the
1469 !! procedure determines the one that minimises the GOS arousal overall.
1470 !! - Finally, the behaviour (with specific optimal target or parameters) that
1471 !! would minimise the resulting GOS arousal is executed by calling respective
1472 !! `do_` procedure (e.g. the_behaviour::behaviour::do_eat_food_item() for the
1473 !! optimal food item if feeding was selected as minimising the overall
1474 !! arousal).
1475 !! .
1476 !! This process is schematically depicted in the figure below.
1477 !! @image html img_doxy_predictive.svg "Predictive decision making by minimising expected GOS arousal"
1478 !! @image latex img_doxy_predictive.eps "Predictive decision making by minimising expected GOS arousal" width=14cm
1479 !!
1480 !! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1481 
1482 !-------------------------------------------------------------------------------
1483 !> @brief COMMONDATA -- definitions of global constants and procedures
1484 !> @section commondata_module Commondata module
1485 !> Module **COMMONDATA** is used for defining various global
1486 !! parameters like model name, tags, population size etc.
1487 !! Everything that has global scope and should be passed to many
1488 !! subroutines/functions, should be defined in `COMMONDATA`.
1489 !! It is also safe to include public keyword to declarations.
1490 !! `COMMONDATA` may also include subroutines/functions that have
1491 !! general scope and used by many other modules of the model.
1492 !! ### Accessibility of objects ###
1493 !! By default, all **data objects** in `COMMONDATA` should be accessible to all
1494 !! other modules. However, procedures defined here must have granular access
1495 !! rights, with the generic name declared *public* while specific
1496 !! implementations *private*.
1498 
1499  use, intrinsic :: iso_fortran_env
1500  use base_utils
1501  use logger
1502  use base_random
1503  use base_strings, only : lowercase
1504  use csv_io, only : max_filename, csv_matrix_write, &
1505  csv_file_lines_count, get_free_funit, fs_unlink
1506  use base_strings, only : parse
1507  implicit none
1508 
1509  ! Access note:
1510  ! By default, all **data objects** in COMMONDATA should be accessible to all
1511  ! other modules. However, procedures defined here must have granular access
1512  ! rights, with the generic name *public* while specific implementations
1513  ! *private*.
1514  public
1515 
1516  !.............................................................................
1517  !.............................................................................
1518 
1519  ! Doxygen comments note: The @name tag defines an arbitrary **member group**
1520  ! of Doxygen objects. Membership range is defined by
1521  ! the @{ and @} tags.
1522 
1523  !> @name Precision control for real type and IEEE float math in the model
1524  !! @{
1525 
1526  ! Precision control for real type and IEEE float math in the model
1527  ! ================================================================
1528 
1529  !> Standard precision for real data type. We first define 32, 64 and
1530  !! 128 bit real kinds.
1531  !! @warning `HEDTOOLS` cannot accept precision higher than kind 8 so far.
1532  !! So 128 bit reals are for example only here. Have to implement
1533  !! higher precision `HEDTOOLS` routines if they are really used.
1534  integer, parameter, public :: s_prec_32 = selected_real_kind( 6, 37)
1535  integer, parameter, public :: d_prec_64 = selected_real_kind(15, 307)
1536  integer, parameter, public :: q_prec_128 = selected_real_kind(33, 4931)
1537 
1538  !> @brief Definition of the **standard** real type precision (*SRP*).
1539  !> @details `SRP` is defined as the standard precision that should normally
1540  !! be used for all real variables and constants. **SRP** stands for
1541  !! **Standard Real Precision** (Naming note: const name should be
1542  !! short to not produce too long real definitions, e.g.
1543  !! `real(SRP) :: alpha`).
1544  !! @warning All float (and other) constants should ideally be defined in the
1545  !! definition section of COMMONDATA or another module, **not** in
1546  !! the code. It is for easier maintainability and precision control.
1547  !! @warning **All standard real variables** should be defined as:
1548  !! `real(SRP) :: real_var`.
1549  !! **Literal constants** should normally add `_SRP`: `1.234_SRP`
1550  !! (although it is less crucial).
1551  integer, parameter, public :: srp = s_prec_32
1552 
1553  !> Definition of the **high** real precision (**HRP**). This real type kind
1554  !! is used in pieces where a higher level of FPU precision is required, e.g.
1555  !! to avoid overflow/underflow and similar errors.
1556  integer, parameter, public :: hrp = q_prec_128
1557 
1558  !> In some (perhaps quite rare) cases of exponentiation we may also need huge
1559  !! integers, those in 64 bit would probably be enough. So whenever we need
1560  !! such a big integer, declare it as:
1561  !! @verbatim
1562  !! integer(LONG) :: bignum
1563  !! @endverbatim
1564  !! @warning HEDTOOLS **do not** currently work with these `LONG`
1565  !! kind integers. So they are only for "internal"-calculation use.
1566  !! Alternatively, use the intrinsic function `int` to convert to the
1567  !! default integer type inline before use, e.g.:
1568  !! `TOSTR(int(max_permutations))`.
1569  integer, parameter, public :: long = selected_int_kind(16)
1570 
1571  !> @}
1572 
1573  !.............................................................................
1574  !.............................................................................
1575 
1576  !> @name Accessory parameters
1577  !! @{
1578 
1579  ! Accessory parameters
1580  ! ====================
1581 
1582  !> MODNAME always refers to the name of the current module for use by
1583  !! the LOGGER function LOG_DBG. Note that in the @ref intro_debug_mode
1584  !! "debug mode" (if IS_DEBUG=TRUE) LOGGER should normally produce additional
1585  !! messages that are helpful for debugging and locating possible sources of
1586  !! errors. MODNAME is declared private and is not accessible outside of this
1587  !! module. Each procedure should also have a similar private constant
1588  !! `commondata::procname`.
1589  !! @note `MODNAME` must have the same case as the module name itself and must
1590  !! be enclosed in parentheses, e.g. `"(THE_MODULE)"`.
1591  character(len=*), parameter, private :: modname = "(COMMONDATA)"
1592 
1593  !> PROCNAME is the procedure name for logging and debugging
1594  !! (with `commondata::modname`).
1595  !! @note `PROCNAME` must have the same case as the subroutine itself and must
1596  !! be enclosed in parentheses, e.g. `"(function_or_subroutine_name)"`,
1597  !! so that it is easier to find in the code and easy to search by
1598  !! regex in the long output logs (use parentheses to search).
1599  !! Here is a template to insert into the code (procedure name is to
1600  !! be filled in the parentheses):
1601  !! @code
1602  !! ! PROCNAME is the procedure name for logging and debugging
1603  !! character(len=*), parameter :: PROCNAME = "()"
1604  !! @endcode
1605  character(len=*), parameter, private :: procname = ""
1606 
1607  !> **Subversion** or *Mercurial* revision number (or ID) of the model code.
1608  !! @warning The revision string is **updated automatically** at svn commmit
1609  !! (or hg commit). It is also not fully portable and may **not**
1610  !! auto update if a different version control system is used.
1611  !! Note that *Mercurial* has a **keyword** extension that works
1612  !! similar to Subversion and should auto-update the keywords.
1613  character(len=*), parameter, public :: &
1614  svn_version_string = "$Revision: 9552 $"
1615 
1616  !> **Subversion** or *Mercurial* revision number that is parsed by
1617  !! `commondata::parse_svn_version()`. It is shorter than
1618  !! `commondata::svn_version_string` and does not contain blanks.
1619  !! Therefore, it can be used for building output file names.
1620  !! @note Note that the SVN parse function is called at initialising the
1621  !! log `LOGGER_INIT`, so `SVN_Version` is initialised.
1622  !! @warning `SVN_Version` is a string, version ID in *Subversion* is numeric,
1623  !! but in other version control systems (hg or git) it can be an
1624  !! arbitrary non-numeric hash string.
1625  !! @note Because it has allocatable attribute, its actual length is
1626  !! obtained automatically and no `trim(SVN_Version)` is necessary.
1627  character(len=:), allocatable, protected, public :: svn_version
1628 
1629  !> Safety parameter avoid errors in logical values, so we can now
1630  !! refer to standard Fortran `.TRUE.` and `.FALSE.` as `YES` and `NO`
1631  !! or `TRUE` and `FALSE`
1632  logical, parameter, public :: true=.true., false=.false.
1633  logical, parameter, public :: yes=.true., no=.false.
1634 
1635  !> Some parameters should never be zero or below. In such cases they could
1636  !! be set to some smallest distinguishable non-zero value. Here set as
1637  !! the Fortran intrinsic `epsilon` function, a value that is almost
1638  !! negligible compared to one, i.e. the smallest `real` number *E* such
1639  !! that @f$ 1 + E > 1 @f$. In some cases it is also reasonable to set the
1640  !! tolerance limit to this parameter (see @ref intro_computation_real
1641  !! "Float point computations").
1642  !! @note The value of this parameter computed on a x86_64 Linux platform is
1643  !! `1.19209290E-07`.
1644  real(srp), parameter, public :: zero = epsilon(0.0_srp)
1645 
1646  !> The smallest positive number in the commondata::srp standard real model.
1647  !! @note This parameter is used for definition of numerical tolerance.
1648  !! See @ref intro_computation_real "Float point computations".
1649  !! @note The value of this parameter computed on a x86_64 Linux platform is
1650  !! `1.17549435E-38`.
1651  real(srp), parameter, public :: tiny_srp=tiny(1.0_srp)
1652 
1653  !> The smallest positive number in the commondata::hrp high precision real
1654  !! model. See @ref intro_computation_real "Float point computations".
1655  !! @note This parameter is used for definition of numerical tolerance.
1656  real(hrp), parameter, public :: tiny_hrp=tiny(1.0_hrp)
1657 
1658  !> Lower bound for ::do_sanitise() procedure. This is the lowest value
1659  !! that considered valid.
1660  real(srp), parameter, public :: lo_valid_sanitised = tiny_srp * 10.0_srp
1661 
1662  !> Higher bound for ::do_sanitise() procedure. This is the highest value
1663  !! that considered valid.
1664  real(srp), parameter, public :: hi_valid_sanitised = huge(1.0_srp)/100.0_srp
1665 
1666  !> Default value of *low* tolerance (*high precision*). This is the
1667  !! *standard* commondata::srp precision. See @ref intro_computation_real
1668  !! "Float point computations".
1669  !! @note The value of this parameter computed on a x86_64 Linux platform is
1670  !! `5.87747175E-38`.
1671  real(srp), parameter, public :: tolerance_low_def_srp = tiny_srp * 5.0_srp
1672 
1673  !> Default value of *low* tolerance (*high precision*). This is the *high*
1674  !! commondata::hrp precision. See @ref intro_computation_real
1675  !! "Float point computations".
1676  real(hrp), parameter, public :: tolerance_low_def_hrp = tiny_hrp * 5.0_hrp
1677 
1678  !> Default value of *high* tolerance (*low precision*). This is the
1679  !! *standard* commondata::srp precision real. See @ref intro_computation_real
1680  !! "Float point computations".
1681  !! @note The value of this parameter computed on a x86_64 Linux platform is
1682  !! `1.19209290E-04`.
1683  real(srp), parameter, public :: tolerance_high_def_srp = zero * 1000.0_srp
1684 
1685  !> Default value of *high* tolerance (*low precision*). This is the
1686  !! *high* commondata::hrp precision real. See @ref intro_computation_real
1687  !! "Float point computations".
1688  !! @note The value of this parameter computed on a x86_64 Linux platform is
1689  !! `1.92592994438723585305597794258492732E-0031`.
1690  real(hrp), parameter, public :: tolerance_high_def_hrp = &
1691  epsilon(0.0_hrp) * 1000.0_hrp
1692 
1693  !> Numerical code for *missing* and *invalid* **real type** values.
1694  !! @note We deliberately set an unisually *big negative value* for `MISSING`
1695  !! because it will reveal bugs by clearly strange/invalid negative
1696  !! results that will propagate in calculations.
1697  !! @warning It is **safe** to assign integer `UNKNOWN` constant to a **real**
1698  !! type variable, see the next definition.
1699  real(srp), parameter, public :: missing = -9999.0_srp, invalid = -9999.0_srp
1700 
1701  !> Numerical code for invalid or *missing* **integer** counts.
1702  !! @note It is safe to assign integer `UNKNOWN` to a **real** type variable,
1703  !! e.g. `real(SRP) :: value=UNKNOWN`.
1704  integer, parameter, public :: unknown = -9999
1705 
1706  !> @brief The **PI** number.
1707  !! @details Pi number @f$ \pi = 4.0 \cdot tg(1.0) @f$ `[4.*atan(1.0)]`,
1708  !! numerically equal to (64 bit real)
1709  !! `PI=3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803_Q_PREC_64`.
1710  real(srp), parameter, public :: pi=4.0_srp*atan(1.0_srp)
1711 
1712  !> Standard data file extension for data output is now .csv
1713  character(len=*), parameter, public :: csv=".csv"
1714 
1715  !> Standard file extension for debug and other PostScript plots
1716  character(len=*), parameter, public :: ps=".ps"
1717 
1718  !> Set the standard length of the file name, are 255 characters enough?
1719  !! @warning Do not forget to use `trim()` function to delete trailing
1720  !! spaces from the file name if it is declared as a fixed-length
1721  !! character string.
1722  integer, parameter, public :: filename_length = 255
1723 
1724  !> Logical flag for setting if POSIX direct filesystem procedures are used.
1725  !! These utilities are implemented in HEDTOOLS for standard POSIX C call
1726  !! via the Fortran interface. They should work safer, better and faster
1727  !! than indirect procedure wrappers (e.g. calling `system()`) but are not
1728  !! fully portable and might not work as expected on all systems and
1729  !! compilers.
1730  logical, parameter, public :: use_posix_fs_utils = .true.
1731 
1732  !> The length of standard character string labels. We use labels for various
1733  !! objects, like alleles, perceptual and neural components / bundles etc.
1734  !! For simplicity, they all have the same length. It should be big enough to
1735  !! fit the longest whole label
1736  integer, parameter, public :: label_length = 14
1737 
1738  !> The length of long labels.
1739  integer, parameter, public :: long_label_length = 128
1740 
1741  !> This parameter defines the range of characters that is used for generating
1742  !! random labels, 97:122 corresponds to lowercase Latin letters
1743  integer, parameter, public :: label_cst = 97, label_cen = 122
1744 
1745  !> The name of the lock file. The lock file is created at the start of the
1746  !! simulation and is deleted at the end of the simulation. It can be used to
1747  !! signal that simulation is still ongoing to external utilities and scripts.
1748  !! See @ref intro_overview_lockfile "The lock file".
1749  !! @note Lock file operation uses native Fortran intrinsic `open`
1750  !! statement rather than any higher level procedures like
1751  !! @ref file_io. This is because the file is for signalling
1752  !! only (intended to be empty) and nothing is actually written
1753  !! into it.
1754  character(len=*), parameter :: lock_file = "lock_simulation_running.lock"
1755 
1756  !> This is the unit number that identifies the lock file. The lock file is
1757  !! created at the start of the simulation and is deleted at the end of the
1758  !! simulation. It can be used to signal that simulation is still ongoing to
1759  !! external utilities and scripts.
1760  !! See @ref intro_overview_lockfile "The lock file".
1761  !! @note Lock file operation uses native Fortran intrinsic `open`
1762  !! statement rather than any higher level procedures like
1763  !! @ref file_io. This is because the file is for signalling
1764  !! only (intended to be empty) and nothing is actually written
1765  !! into it.
1766  integer, protected, public :: lock_file_unit
1767 
1768  !> The name of the stop file. The stop file is checked before each new
1769  !! generation of the Genetic Algorithm. If this file is found, simulation
1770  !! does not go to the next generation and just stops.
1771  !! See @ref intro_overview_stopfile "The stop file".
1772  !! @note Stop file operation uses native Fortran intrinsic `open`
1773  !! statement rather than any higher level procedures like
1774  !! @ref file_io. This is because the file is for signalling
1775  !! only (intended to be empty) and nothing is actually read or
1776  !! written.
1777  character(len=*), parameter :: stop_file = "stop_simulation_running.lock"
1778 
1779  !> Runtime platform ID constants. Use these constants for determining the
1780  !! current runtime platform, e.g. `Platform_Running = PLATFORM_WINDOWS`.
1781  !! See `commondata::platform_running`.
1782  integer, parameter, public :: platform_windows = 100
1783  integer, parameter, public :: platform_unix = 111
1784 
1785  !> Global variable that shows what is the current platform. Should use the
1786  !! above platform constants, e.g. `Platform_Running = PLATFORM_WINDOWS`.
1787  !! See `commondata::platform_windows` and `commondata::platform_unix`.
1788  integer, public :: platform_running
1789 
1790  !> There are a few **external programs** which are called from the model code.
1791  !! The name of the **interpolation** program (htintrpl.f90 from HEDTOOLS)
1792  !! executable.
1793  character(len=*), parameter, public :: exec_interpolate = "htintrpl.exe"
1794 
1795  !> The name of the **scatterplot** program (htscatter.f90 from HEDTOOLS)
1796  !! executable.
1797  character(len=*), parameter, public :: exec_scatterplot = "htscatter.exe"
1798 
1799  !> The name of the **histogram** program (hthist.f90 from HEDTOOLS)
1800  !! executable.
1801  character(len=*), parameter, public :: exec_histogram = "hthist.exe"
1802 
1803  !> **Tag prefixes** for the logger system. The log may use tags for
1804  !! some common information pieces, so they are easily found within.
1805  !! The tags are normally set the prefix for the log:
1806  !! 017-01-31 13:33:22 INFO: Saving histogram, data: debug_hist.csv
1807  !! Some common tags are:
1808  !! STAGE STAGE: 2017-01-31 16:03:15 INFO: Generation 7 took 448.3279s.
1809  !! INFO INFO: some information
1810  !! TIMER TIMER: Calculating distances took 0.001 s
1811  !! Tag meaning: @n
1812  !! + **MAJOR** major stages of the simulation, e.g. next generation;
1813  !! + **STAGE** minor stages of the simulation, e.g. time step change;
1814  !! + **INFO** some information about model running;
1815  !! + **WARNING** warnings on possible issues and minor errors;
1816  !! + **ERROR** error reports that do not normally halt running;
1817  !! + **CRITICAL** critical errors that would stop execution;
1818  !! + **TIMER** reports from the timers and stopwatches.
1819  character(len=*), parameter, public :: ltag_major = "IMPORTANT: "
1820  character(len=*), parameter, public :: ltag_stage = "STAGE: "
1821  character(len=*), parameter, public :: ltag_info = "INFO: "
1822  character(len=*), parameter, public :: ltag_warn = "WARNING: "
1823  character(len=*), parameter, public :: ltag_error = "ERROR: "
1824  character(len=*), parameter, public :: ltag_crit = "CRITICAL: "
1825  character(len=*), parameter, public :: ltag_timer = "TIMER: "
1826  character(len=*), parameter, public :: ltag_stats = "STATS: "
1827 
1828  !> @}
1829 
1830  !> @name System-wide fatal errors
1831  !! The description of errors that pertain to the whole system.
1832  !! @{
1833 
1834  !> Error message for **"no automatic intrinsic array allocation"**.
1835  !! Fortran compilers support automatic allocation of arrays on
1836  !! intrinsic assignment. This feature should work by default in
1837  !! GNU gfortran v.4.6 and Intel ifort v.17.0.1. Automatic allocation
1838  !! allows to avoid a possible bug when the number of array elements
1839  !! in the `allocate` statement is not updated when the components of the
1840  !! array are updated in the array constructor.
1841  character(len=*), parameter, public :: error_no_autoalloc = &
1842  "No automatic array allocation"
1843 
1844  !> Error message for **"no automatic determination of the size in parameter"**
1845  !! arrays in the style:
1846  !! @code
1847  !! real(SRP), parameter, dimension(*) :: ARRAY=[ 1.0, 2.0, 3.0, 4.0 ]
1848  !! @endcode
1849  character(len=*), parameter, public :: error_auto_param_arrays = &
1850  "No automatic size in parameter arrays"
1851 
1852  !> Error message **"Cannot allocate array or object"** is issued if
1853  !! an array or an object is checked and turns out to be not allocated while
1854  !! it must be.
1855  character(len=*), parameter, public :: error_allocation_fail = &
1856  "Cannot allocate array or object"
1857 
1858  character(len=*), parameter, public :: error_lock_preexists = &
1859  "Lock file '" // lock_file // "' exists. Is another simulation running?"
1860 
1861  !> @}
1862 
1863  !> @name Stopwatch Timer class
1864  !! Used for execution timing of certain parts of the code.
1865  !! @{
1866 
1867  !> CPU timer container object for debugging and speed/performance control.
1868  !! Arbitrary timers can be instantiated for different parts of the code and
1869  !! also global. Using a specific timer (`stopwatch`) is like this:
1870  !! @code
1871  !! call stopwatch%start("Output all agents data")
1872  !! @endcode
1873  !! to **start** the stopwatch with specific title, then the function
1874  !! @code
1875  !! ... = stopwatch%elapsed()
1876  !! @endcode
1877  !! returns the **elapsed time**. Then, the function stopwatch\%title()
1878  !! outputs the title of this timer. A few other functions build on this
1879  !! simple functionality to provide typical shortcuts: stopwatch\%show()
1880  !! and stopwatch\%log().
1881  !! @note The near-trivial nature of this object makes it ideal for learning
1882  !! how to implement objects in modern Fortran.
1883  type, public :: timer_cpu
1884  !> All object data components private, we should never use them directly.
1885  private
1886  !> Define start time for the stopwatch.
1887  ! @note We need to keep only the start time as raw values coming out
1888  ! of `cpu_time` are machine-dependent
1889  ! @note It does not seem good to move `TIMER_CPU` to *HEDTOOLS* as they
1890  ! are for portability (require only F90) and do not use OO.
1891  ! `TIMER_CPU` uses full OO extensible class implementation so
1892  ! requires *F2003* minimum.
1893  real(srp) :: cpu_time_start
1894  !> Optional title for the stopwatch. Useful if we use many timers and for
1895  !! logger.
1896  ! @warning Not allocatable as deferred character length strings within
1897  ! derived types may not be supported by all recent widespread
1898  ! compilers, e.g. GNU gfortran 4.8.4 does not support it.
1899  character (len=LONG_LABEL_LENGTH) :: cpu_time_title
1900  contains
1901  !> Start the timer object, stopwatch is now ON.
1902  !! See `commondata::timer_cpu_start()`
1903  procedure, public :: start => timer_cpu_start
1904  !> Calculate the time elapsed since the stopwatch subroutine was called
1905  !! for this instance of the timer container object. Can be called several
1906  !! times showing elapsed time since the grand start.
1907  !! See `commondata::timer_cpu_elapsed()`
1908  procedure, public :: elapsed => timer_cpu_elapsed
1909  !> Return the title of the current timer object.
1910  !! See `commondata::timer_cpu_title()`
1911  procedure, public :: title => timer_cpu_title
1912  !> A ready to use in output function that returns a formatted
1913  !! string for a timer combining its title and the elapsed time.
1914  !! See `commondata::timer_cpu_show()`
1915  procedure, public :: show => timer_cpu_show
1916  !> A ready to use shortcut to be used in logger, just adds the TIMER: tag
1917  !! in front of the normal `show`output.
1918  !! See `commondata::timer_cpu_log()`
1919  procedure, public :: log => timer_cpu_log
1920  end type timer_cpu
1921  ! @note Note that all component procedures are private.
1924 
1925  !> @}
1926 
1927  !.............................................................................
1928  !.............................................................................
1929 
1930  !> @name General Parameters
1931  !! @{
1932 
1933  ! General Parameters
1934  ! ==================
1935 
1936  !> Model name for tags, file names etc. Must be very short.
1937  !! See @ref intro_descriptors "Model descriptors".
1938  character (len=*), parameter, public :: model_name = "HEDG2_04"
1939 
1940  !> Model description - a fixed descriptive text, used in text outputs etc.
1941  !! See @ref intro_descriptors "Model descriptors".
1942  character (len=*), parameter, public :: model_descr = &
1943  "AHA, single fear, body size non-genetic."
1944 
1945  !> The name of the file that contains the Model abstract, a short description
1946  !! that can span several lines of text ans is kept in a separate file. The
1947  !! file is read, if it exists, and its contents is logged at the start the
1948  !! simulation.
1949  !! The separate Model Abstract file is useful because it can integrate
1950  !! dynamic information, such as the latest version control log(s) via
1951  !! Subversion or Mercurial hooks mechanism.
1952  !! See @ref intro_descriptors "Model descriptors".
1953  character (len=*), parameter, private :: model_abstract_file = "abstract.txt"
1954 
1955  !> Sets the model in the @ref intro_debug_mode "debug mode" if TRUE. The
1956  !! Debug mode generates huge additional outputs and logs. Also, the logs
1957  !! by default go to the screen (standard output).
1958  !! See `commondata::system_init()` for details.
1959  !! @warning This is a protected variable not fixed parameter. Can be set at
1960  !! start from the command line parameter or environment variable.
1961  !! @note Debug mode can be set in three ways (see `system_init` subroutine):
1962  !! 1. by setting this variable at the initialisation here to TRUE
1963  !! (although this is **not-normal** as requires recompile);
1964  !! 2. by setting the shell environment variable `AHA_DEBUG=1`,
1965  !! `AHA_DEBUG=TRUE` or `AHA_DEBUG=YES`;
1966  !! 3. by setting the command line parameter `DEBUG` when calling this
1967  !! executable program.
1968  !! @warning `IS_DEBUG` can also be declared as a `parameter`, see
1969  !! @ref system_debug_optimise "Compiler optimisation of debug mode"
1970  !! in commondata::system_init() for details.
1971  !! @note `IS_DEBUG` can also be declared as a normal global variable, not
1972  !! "protected" (by removing the `protected` attribute) In such case
1973  !! it could be changed everywhere in the program. A potential
1974  !! benefit is that only a section of the program, e.g. a single
1975  !! function, can then produce extended debugging output. However,
1976  !! this would also make compiler optimisation more difficult and
1977  !! reduce performance. See commondata::system_init() for more
1978  !! discussion.
1979  !! @remark A short discussion on the protected attribute for module variable
1980  !! is at [comp.lang.fortran](https://groups.google.com/forum/#!topic/comp.lang.fortran/K-JkeVFXZMo).
1981  logical, protected, public :: is_debug=.false.
1982  ! DEBUG_COMPILER_OPTIMISE: see 'Compiler optimisation of debug mode'
1983  ! logical, parameter, public :: IS_DEBUG=.FALSE.
1984 
1985  !> This parameter controls if the debug plots are produced. They can be
1986  !! huge number that takes lots of space. Also, debug plots are called as
1987  !! separate processes that can run at the background and easily exceed the
1988  !! system-specific limit on child processes (if run in asynchronous mode).
1989  !! Generation of debug plots can be controlled by the environment variable
1990  !! `AHA_DEBUG_PLOTS`: if it is set to TRUE, 1, or YES, debug plots are
1991  !! enabled. See `commondata::system_init()` for details.
1992  logical, protected, public :: is_plotting=.true.
1993 
1994  !> Sets the model in screen output mode. If TRUE, the logger output goes
1995  !! to the screen (standard output device). Can be manipulated using the
1996  !! environment variable `AHA_SCREEN`. If `AHA_SCREEN` is set to TRUE or 1 or
1997  !! yes, logger screen output is enabled. See `commondata::system_init()` for
1998  !! details.
1999  logical, protected, public :: is_screen_output=.false.
2000 
2001  !> This parameter enables or disables post-processing compression of the
2002  !! data: if TRUE, the data are compressed using the command defined by the
2003  !! commondata::cmd_zip_output string parameter. Note that not all data
2004  !! files are compressed, only potentially big ones are (e.g. agent population
2005  !! data and habitat data).
2006  !! @note Note that each data file is compressed individually. That is,
2007  !! no 'archive' containing multiple files is made.
2008  !! @warning This parameter is by default set to FALSE because calling wrong
2009  !! compression program might hang this program (e.g. if the child
2010  !! process is waiting for data on standard input). Enabling
2011  !! background data compression is normally done by setting the
2012  !! environment variable `AHA_ZIP_FILES=TRUE`.
2013  !! See commondata::system_init() for details.
2014  logical, protected, public :: is_zip_outputs=.false.
2015 
2016  !> This parameter defines if the output files are compressed in the
2017  !! background in the parallel mode or the program should wait for
2018  !! termination of the child zipping process.
2019  logical, parameter, public :: zip_outputs_background=.true.
2020 
2021  !> This parameter defines the compression program that is executed to "zip"
2022  !! the data files if commondata::is_zip_outputs is enabled (TRUE).
2023  !! The normal compression utility is "gzip," that is found on almost any
2024  !! Linux/Unix system. gzip compresses each file individually and by default
2025  !! automatically deletes the original file. The compressed file extension
2026  !! is defined by commondata::zip_file_extenssion. See http://www.gzip.org/.
2027  !! Alternative compressors that are fairly widespread are `bzip2`, `lzma`
2028  !! and `xz`.
2029  character(len=*), parameter, public :: cmd_zip_output = "gzip"
2030 
2031  !> This parameter defines the compressed file extension for the external
2032  !! compression utility defined by the commondata::cmd_zip_output.
2033  character(len=*), parameter, public :: zip_file_extenssion = ".gz"
2034 
2035  !> This parameter defines if all agents data is saved at each time step
2036  !! of the life cycle. See the_evolution::lifecycle_preevol().
2037  !! @warning Saving large amount of data at each time step of the
2038  !! lifecycle is time consuming and will make calculations
2039  !! slower.
2040  logical, parameter, public :: enable_save_agents_each_timestep = .false.
2041 
2042  !> `MMDD` tag, year, month and day, used in file names and outputs.
2043  !! The value of the tag should be obtained only once at the start of
2044  !! the simulation, normally by calling the commondata::tag_mmdd()
2045  !! function at commondata::system_init(). It does not make much sense
2046  !! to generate these data tags on the fly as the simulations can be very
2047  !! long, several days, and so the file tags will be inconsistent.
2048  !! @note MMDD normally has a fixed length 8 as in `20161228`, see
2049  !! commondata::tag_mmdd(). Because it has allocatable attribute,
2050  !! its actual length is obtained automatically and no `trim(MMDD)`
2051  !! is necessary.
2052  character(len=:), allocatable, protected, public :: mmdd
2053 
2054  !> Maximum population size
2055  integer, parameter, public :: popsize = 10000
2056 
2057  !> Maximum number of generations in GA
2058  integer, parameter, public :: generations = 100
2059 
2060  !> The current global **generation number**. This is a global non
2061  !! fixed-parameter variable that is updated in subroutines.
2062  !! @warning There might be no guarantee that it is saved in all subroutines
2064 
2065  !> Number of time steps in the agent's maximum life length
2066  integer, parameter, public :: lifespan = 14000
2067 
2068  !> Number of time steps in the agent's life at the pre-evolution stage.
2069  integer, parameter, public :: preevol_tsteps = 560
2070 
2071  !> Number of time steps in the agent's life at the fixed fitness
2072  !! pre-evolution stage. This parameter **forces** a smaller fixed value
2073  !! that is used for debugging only. Thus, adaptive time steps calculated by
2074  !! the_evolution::preevol_steps_adaptive() are disabled.
2075  !! To enable this fixed time steps, set this parameter
2076  !! commondata::preevol_tsteps_force_debug_enabled to TRUE.
2077  !! @warning This is used for debugging and testing purposes only and should
2078  !! normally be disabled.
2079  integer, parameter, public :: preevol_tsteps_force_debug = 280
2080 
2081  !> This parameter enables the forced smaller fixed number of time steps
2082  !! set by the commondata::preevol_tsteps_force_debug parameter.
2083  !! @warning This is used for debugging and testing purposes only and should
2084  !! normally be disabled, set to **FALSE**.
2085  logical, parameter, public :: preevol_tsteps_force_debug_enabled = .false.
2086 
2087  !> This parameter completely disables predation in the GA life cycle
2088  !! procedure.
2089  !! @warning Can be enabled for debugging purposes only. Normally should be
2090  !! set to **FALSE**.
2091  logical, parameter, public :: lifecycle_predation_disabled_debug = .false.
2092 
2093  !> The current global **time step** of the model. This is a global non
2094  !! fixed-parameter variable that is updated in subroutines.
2096 
2097  !> The current global time frame. Frames are time steps within the time step
2098  !! defined by the commondata::global_time_step_model_current
2099  integer, public :: global_frame_number
2100 
2101  !> Default perception error in the commondata::gamma2gene() neuronal
2102  !! response functions. Note that this parameter defines stochastic error as
2103  !! the Coefficient of Variation (CV).
2104  real(srp), parameter, public :: percept_error_cv_def = 0.01_srp
2105 
2106  !> @}
2107 
2108  !.............................................................................
2109  !.............................................................................
2110 
2111  !> @name Basic agent parameters
2112  !! @{
2113 
2114  ! Basic agent parameters
2115  ! ======================
2116 
2117  !> Minimum body length possible
2118  real(srp), parameter, public :: body_length_min = 0.2_srp
2119 
2120  !> Maximum body length
2121  real(srp), parameter, public :: body_length_max = 100.0_srp
2122 
2123  !> Minimum possible body mass, hard limit.
2124  !! @note Note that body mass is calculated from condition factor and length.
2125  !! = k * l**3
2126  real(srp), parameter, public :: body_mass_min = 0.1_srp
2127 
2128  !> This parameter determines if the agents are initialised at a fixed
2129  !! depth at the initialisation. Agents are normally placed uniformly,
2130  !! the_environment::uniform(), at the initialisation. However, the depth
2131  !! can be fixed. In such a case they are scattered uniformly in the X and Y
2132  !! coordinates but with fixed depth that is set by the
2133  !! commondata::init_agents_depth parameter.
2134  !> @warning The agents can also be initialised with Gaussian depth. This is
2135  !! controlled by the parameter commondata::init_agents_depth_is_gauss.
2136  !! However, this parameter has precedence over Gaussian, so remember
2137  !! to set it FALSE if Gaussian depth initialisation is required.
2138  !! See the_population::member_population::place_uniform().
2139  logical, parameter, public :: init_agents_depth_is_fixed = .false.
2140 
2141  !> This parameter determines if the agents are initialised at a fixed
2142  !! depth at the initialisation. Agents are placed uniformly,
2143  !! the_environment::uniform(), at the initialisation. However, the depth
2144  !! can be a Gaussian value with the
2145  !! - mean set by the commondata::init_agents_depth
2146  !! - CV set by the commondata::init_agents_depth_cv
2147  !! .
2148  !! Such a Gaussian depth patter is switched by this parameter. The other
2149  !! coordinates of the agents, X and Y are then uniform.
2150  !! @warning If Gaussian depth initialisation is required, the parameter
2151  !! commondata::init_agents_depth_is_fixed must be set to FALSE as
2152  !! it has a higher precedence.
2153  !! See the_population::member_population::place_uniform().
2154  logical, parameter, public :: init_agents_depth_is_gauss = .true.
2155 
2156  !> The fixed depth at which the agents are initialised at the start of the
2157  !! simulation. The other coordinates are normally set
2158  !! the_environment::uniform() within the initialisation environment
2159  !! container. See the_population::member_population::place_uniform().
2160  !! @note If the parameter commondata::init_agents_depth_is_fixed is FALSE,
2161  !! then the agents are scattered uniformly in the whole 3D space
2162  !! and this parameter is ignored.
2163  real(srp), parameter, public :: init_agents_depth = 1833.0_srp
2164 
2165  !> This parameter sets the Coefficient of Variation for the Gaussian depth
2166  !! initialisation of the agents that is controlled by
2167  !! commondata::init_agents_depth_is_gauss.
2168  !! See the_population::member_population::place_uniform().
2169  real(srp), parameter, public :: init_agents_depth_cv = 0.2_srp
2170 
2171  !> The energetic cost of reproduction in terms of the agent's body mass
2172  !! loss.
2173  !! @warning This parameter applies to the fixed cost version of the
2174  !! procedure `the_body::reproduction_cost_energy_fix()`.
2175  real(srp), parameter, public :: reproduction_cost_body_mass_fix = 0.2_srp
2176 
2177  !> The component of the energetic cost of reproduction in **males** that is
2178  !! proportional to the total offspring mass. For details see the procedure
2179  !! `the_body::reproduction_cost_energy_dynamic()`.
2180  real(srp), parameter, public :: &
2182 
2183  !> The component of the energetic cost of reproduction in **females** that is
2184  !! proportional to the total offspring mass. For details see the procedure
2185  !! `the_body::reproduction_cost_energy_dynamic()`.
2186  real(srp), parameter, public :: &
2188 
2189  !> The component of the energetic cost of reproduction in **males** that is
2190  !! proportional to the agent's body mass. For details see the procedure
2191  !! `the_body::reproduction_cost_energy_dynamic()`.
2192  real(srp), parameter, public :: &
2194 
2195  !> The component of the energetic cost of reproduction in **females** that is
2196  !! proportional to the agent's body mass. For details see the procedure
2197  !! `the_body::reproduction_cost_energy_dynamic()`.
2198  real(srp), parameter, public :: &
2200 
2201  !> The energetic cost of unsuccessful reproduction in terms of the agent's
2202  !! body mass lost. This is a fraction of the **full cost of reproduction**,
2203  !! that is described by the `REPRODUCTION_COST_BODY_MASS` parameter.
2204  real(srp), parameter, public :: reproduction_cost_unsuccess = 0.1_srp
2205 
2206  !> The array defining the **abscissa** (X) of the nonparametric function
2207  !! curve that defines the relationship between the agent's body mass and
2208  !! the overall mass of all offspring as a fraction of the agent's body mass.
2209  !! @warning Must have the same dimensionality as
2210  !! commondata::reproduct_body_mass_offspr_ordinate.
2211  real(srp), dimension(*), &
2212  parameter, public :: reproduct_body_mass_offspr_abscissa = &
2213  [ body_mass_min, 3.0_srp, 10.5_srp, 12.0_srp ]
2214 
2215  !> The array defining the **ordinate** (Y) of the nonparametric function
2216  !! curve that defines the relationship between the agent's body mass and
2217  !! the overall mass of all offspring as a fraction of the agent's body mass.
2218  !! Plotting command for the interpolator:
2219  !! @verbatim
2220  !! htintrpl.exe [0.1 100 350 400] [0.0 0.1 0.199 0.20] [0] [nonlinear]
2221  !! htintrpl.exe [0.1 3 10.5 12.0] [0.0 0.1 0.199 0.20] [0] [nonlinear]
2222  !! @endverbatim
2223  !! @warning Must have the same dimensionality as
2224  !! commondata::reproduct_body_mass_offspr_abscissa.
2225  real(srp), dimension(*), &
2226  parameter, public :: reproduct_body_mass_offspr_ordinate = &
2227  [ 0.0_srp, 0.1_srp, 0.199_srp, 0.20_srp ]
2228 
2229  !> @}
2230 
2231  !.............................................................................
2232  !.............................................................................
2233 
2234  !> @name Parameters of the environment
2235  !! @{
2236 
2237  ! Parameters of the environment
2238  ! =============================
2239 
2240  !.............................................................................
2241  ! ## General environmental parameters ##
2242 
2243  !> @brief Overall size of the global 3D universe of the model.
2244  !! @details Physical sizes of the 3D "universe" environment for the agents'
2245  !! life. The *minimum* coordinates (`UNIVERSE_MIN_COORD_NOTUSE`)
2246  !! are all zeroes for simplicity. So here set the *maximum*
2247  !! coordinates vector [x,y,z] limiting the maximum environment
2248  !! size: `UNIVERSE_WHOLE_SIZE_NOTUSE`.
2249  !! @warning The dimensionality is only **3** for three-dimensional space.
2250  !! @note Universe has been deprecated in @ref the_evolution module as
2251  !! it has not been used. However, the parameters are still defined
2252  !! as the arrays could be used in definitions of habitats, if found
2253  !! feasible.
2254  real(srp), parameter, dimension(3), public :: universe_min_coord_notuse = &
2255  [0.0_srp, 0.0_srp, 0.0_srp]
2256  real(srp), parameter, dimension(3), public :: universe_whole_size_notuse = &
2257  [20000.0_srp, 10000.0_srp, 3000.0_srp]
2258 
2259  !> Number of days and nights in a lifespan, `DIELCYCLES=500`.
2260  integer, parameter, public :: dielcycles = 100
2261 
2262  !> The size of the history for spatial moving objects, i.e. how many time
2263  !! steps positions to remember in stack arrays.
2264  integer, parameter, public :: history_size_spatial = 50
2265 
2266  !.............................................................................
2267  !.............................................................................
2268  ! ## Parameters of the HABITATs ##
2269 
2270  !> @brief Definition of the habitat spatial limits.
2271  !! @details We define two habitats **within the global universe**
2272  !! (`UNIVERSE_WHOLE_SIZE`) of the model. They are called
2273  !! "The safe" and "The dangerous" habitats and primarily
2274  !! differ in the level of predator risk. The habitats
2275  !! represent two adjacent squares that form a rectangular
2276  !! "universe" (the universe defined by
2277  !! `UNIVERSE_WHOLE_SIZE`).
2278  !! @code
2279  !! 0 10000000 20000000
2280  !! +------------------+-------------------+
2281  !! | | |
2282  !! | | |
2283  !! | Safe habitat | Dangerous |
2284  !! Y | | habitat |
2285  !! | | |
2286  !! | | |
2287  !! | | |
2288  !! | | |
2289  !! | | |
2290  !! 0 +------------------+-------------------+ 20000000
2291  !! X
2292  !! @endcode
2293  !! Safe habitat: 0:1000000 x 0:1000000 x 0:3000 cm (NB: units cm!)
2294  !! @warning The dimensionality is only **3** for three-dimensional space.
2295  real(srp), parameter, dimension(3), public :: &
2296  habitat_safe_min_coord = [0.0_srp, 0.0_srp, 0.0_srp]
2297  real(srp), parameter, dimension(3), public :: &
2298  habitat_safe_max_coord = [10000.0_srp, 10000.0_srp, 3000.0_srp]
2299  !! Dangerous habitat: 10000:20000 x 0:10000 x 0:30
2300  !! @warning The dimensionality is only **3** for three-dimensional space.
2301  real(srp), parameter, dimension(3), public :: &
2302  habitat_danger_min_coord = [10000.0_srp, 0.0_srp, 0.0_srp]
2303  real(srp), parameter, dimension(3), public :: &
2304  habitat_danger_max_coord = [20000.0_srp, 10000.0_srp, 3000.0_srp]
2305 
2306  ! Setting other parameters of the two habitats.
2307 
2308  !> The **number of predators** in the **safe** habitat.
2309  integer, parameter, public :: predators_num_habitat_safe = 100
2310 
2311  !> The **number of predators** in the **dangerous** habitat.
2312  integer, parameter, public :: predators_num_habitat_danger = 500
2313 
2314  !> The **food abundance** in the **safe** habitat.
2315  integer, parameter, public :: food_abundance_habitat_safe = 20000
2316 
2317  !> The **food abundance** in the **dangerous** habitat.
2318  integer, parameter, public :: food_abundance_habitat_danger = 40000
2319 
2320  !. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2321  ! ### Default parameters of all the HABITAT objects. ###
2322 
2323  !> Default level of other mortality risks in the habitat
2324  real(srp), parameter, public :: other_risks_def = 0.01_srp
2325 
2326  !> Habitat-specific mortality risk (not linked with predation) in the
2327  !! **safe** habitat.
2328  real(srp), parameter, public :: other_risks_habitat_safe = 0.01_srp
2329 
2330  !> Habitat-specific mortality risk (not linked with predation) in the
2331  !! **dangerous** habitat.
2332  real(srp), parameter, public :: other_risks_habitat_danger = 0.05_srp
2333 
2334  !> Default level of egg mortality in the habitat
2335  real(srp), parameter, public :: eggmortality_def = 0.01_srp
2336 
2337  !> Default individually-specific mortality risk. It can increase or decrease
2338  !! depending on various factors. The individually-specific mortality risk
2339  !! is normally a Gaussian variable with the variability set by the
2340  !! commondata::individual_mortality_risk_cv.
2341  real(srp), parameter, public :: individual_mortality_risk_def = 0.01_srp
2342 
2343  !> The coefficient of variation for Gaussian stochastic individually-specific
2344  !! mortality risk of the agent.
2345  real(srp), parameter, public :: individual_mortality_risk_cv = 0.05_srp
2346 
2347  !.............................................................................
2348  ! Parameters of the predator attack efficiency. Predators is an array
2349  ! (population of predators) that are initialised with Gaussian random
2350  ! parameters.
2351 
2352  !> The body size of the predator. In this version all predators have the
2353  !! same body size set by this parameter, but can be Gaussian stochastic.
2354  !! Moreover, in such a case predator attack efficiency can depend on
2355  !! the body size, e.g. larger predators are more dangerous.
2356  !! compare to the agents maximum body size `BODY_LENGTH_MAX=100.0`
2357  real(srp), parameter, public :: predator_body_size = 100.0_srp
2358 
2359  !> Mean rate of a single predator attack
2360  real(srp), parameter, public :: predator_attack_rate_default = 0.9_srp
2361 
2362  !> Coefficient of variation for a single predator attack among the
2363  !! whole population of stochastic predators.
2364  real(srp), parameter, public :: predator_attack_rate_cv = 0.1_srp
2365 
2366  !> The probability of capture of a fish agent by a predator at the distance
2367  !! equal to 1/2 of the visual range. For more details see
2368  !! `the_environment::predator_capture_risk_calculate_fish()`.
2369  real(srp), parameter, public :: &
2371 
2372  !> Minimum probability of capture, e.g. at a distance exceeding the visual
2373  !! range. The latter assumes that the predator could detect the agent beyond
2374  !! the visual range and pursue it. For more details see
2375  !! `the_environment::predator_capture_risk_calculate_fish()`.
2376  real(srp), parameter, public :: &
2378 
2379  !> A parameter factor defining the probability of capture of an immobile
2380  !! (freezing) agent by a predator: interpolation ordinate for the distance
2381  !! equal to **0.25 of the visual range**.
2382  !! See `the_environment::predator_capture_risk_calculate_fish()` for details.
2383  real(srp), parameter, public :: predator_attack_capture_prob_frz_50 = 0.10_srp
2384  !> A parameter factor defining the probability of capture of an immobile
2385  !! (freezing) agent by a predator: interpolation ordinate for the distance
2386  !! equal to **0.40 of the visual range**.
2387  !! See `the_environment::predator_capture_risk_calculate_fish()` for details.
2388  real(srp), parameter, public :: predator_attack_capture_prob_frz_75 = 0.01_srp
2389 
2390  !> A logical flag of whether the agents can assess the individual inherent
2391  !! attack rates of the predators. If yes, these inherent individual attack
2392  !! rates are collated into the perception object. If no, the default
2393  !! attack rate set by the commondata::predator_attack_rate_default parameter
2394  !! is used.
2395  logical, parameter, public :: agent_can_assess_predator_attack_rate = .true.
2396 
2397  !> Sets the limit for partial indexing and ranking of **prey agents**
2398  !! in the visual range of the predator. The risk of predation, i.e. the
2399  !! probability of attack and capture of each agent in a group of agents,
2400  !! will be calculated individually for distance-ranked agents only up to
2401  !! this parameter value.
2402  integer, parameter, public :: predator_risk_group_select_index_partial = 20
2403 
2404  !> The array defining the ordinate grid values for the weighting
2405  !! nonparametric function linking the distance rank of the agent within
2406  !! the visual field of the predator and the weighting factor adjusting
2407  !! for predator confusion and predator dilution effects. The grid abscissa
2408  !! is calculated dynamically in the
2409  !! the_environment::predator_capture_risk_calculate_fish_group() procedure.
2410  !! @note Note that the middle value equal to 0.5 results in a linear
2411  !! function.
2412  !!
2413  !! This command produces the function plot:
2414  !! @verbatim
2415  !! htintrpl.exe [1 30 60] [1 0.3 0.0] [1]
2416  !! @endverbatim
2417  real(srp), dimension(*), parameter, public &
2418  :: predator_risk_group_dilution_ordinate = [1.0_srp, 0.3_srp, 0.1_srp]
2419 
2420  !.............................................................................
2421  ! ## Parameters of the food resources ##
2422 
2423  !> Default size of a single food item.
2424  !! @note Note that the maximum stomach capacity of the agent
2425  !! (the_condition::condition::maxstomcap) is 0.15 of the
2426  !! agent body mass (@f$ M_a @f$). So if the average agent mass
2427  !! is 41.0, the maximum capacity is about 6.15.
2428  !! Thus, to get the food item size corresponding to such a mass
2429  !! (food item mass 6.15), the *size* of the food item should be:
2430  !! @f[ s=\sqrt[3]{\frac{3\cdot 0.15 \cdot M_a}{4\pi\rho}} \Rightarrow
2431  !! s=\sqrt[3]{\frac{0.45M_a}{4\pi\rho}} . @f]
2432  !! Calculate: `( 0.45 * 41 / (4 * 3.1415926 * 0.1 ))^(1/3) = 2.45`
2433  !! In reality, it makes sense to make the mean food item size smaller
2434  !! than exactly 0.15 of the maxstomcap to accomodate its Gaussian
2435  !! variability, so more than 50% of items would fit into the stomach.
2436  !! An average food item mass of 0.09 of the agent mass might be better.
2437  !! Calculate: `( 3 * 0,09 * 41 / (4 * 3.1415926 * 0.1 ))^(1/3) = 2.065`
2438  real(srp), parameter, public :: food_item_size_default = 2.1_srp
2439 
2440  !> The above is also the average size of a stochastic Gaussian
2441  !! food items.
2442  real(srp), parameter, public :: food_item_mean_size = food_item_size_default
2443 
2444  !> Coefficient of variation for Gaussian food items.
2445  real(srp), parameter, public :: food_item_size_default_cv = 0.1_srp
2446 
2447  !> The minimum size of a food item. This is the "floor" in case the
2448  !! stochastically generated (e.g. Gaussian) value gets zero or below.
2449  real(srp), parameter, public :: food_item_minimum_size = 1.0_srp
2450 
2451  !> The (physical) density of a single food item. TODO: need to parametrise!
2452  real(srp), parameter, public :: food_item_density = 0.1_srp
2453 
2454  !> The cost of the food item catching, in terms of the **food item mass**
2455  !! (proportional cost). So, if the agent does an unsuccessful attempt to
2456  !! catch a food item, the cost still applies.
2457  real(srp), parameter, public :: food_item_capture_prop_cost = 0.05_srp
2458 
2459  !> The **baseline** probability that the food item is captured.
2460  !! See the_neurobio::food_item_capture_probability_calc().
2461  !! @note Interpolation plot command:
2462  !! `htintrpl.exe [0.0 0.5 1.0] [0.85, 0.68, 0.1]` (0.68=0.85*0.8).
2463  real(srp), parameter, public :: food_item_capture_probability = 0.99_srp
2464 
2465  !> The **minimum** probability of capture a food item, when the item is
2466  !! at a distance equal to the visual range from the predator agent.
2467  real(srp), parameter, public :: food_item_capture_probability_min = 0.1_srp
2468 
2469  !> Subjective error assessing the food item capture probability when
2470  !! assessing the subjective GOS expectancies of food items. The subjective
2471  !! assessment value of the capture probability is equal to the objective
2472  !! value plus random error with the CV equal to this parameter.
2473  real(srp), parameter, public :: &
2475 
2476  !.............................................................................
2477  ! ## Parameters of stochastic movement of food items ##
2478  ! Food items do regular deterministic vertical migrations. Additionally,
2479  ! each of the food item is are also displaced randomly in a Gaussian pattern.
2480 
2481  !> Mean shift parameter for the local random walk movement of food items in
2482  !! the horizontal plane.
2483  real(srp), parameter, public :: food_item_migrate_xy_mean = &
2484  food_item_size_default * 10.0_srp
2485 
2486  !> Mean shift parameter for the local random walk movement of food items in
2487  !! the vertical (depth) plane.
2488  real(srp), parameter, public :: food_item_migrate_depth_mean = &
2489  food_item_size_default * 100.0_srp
2490 
2491  !> Coefficient of variation parameter for the local random walk movement of
2492  !! food items in the horizontal plane.
2493  real(srp), parameter, public :: food_item_migrate_xy_cv = &
2495 
2496  !> Coefficient of variation parameter for the local random walk movement of
2497  !! food items in the vertical (depth) plane.
2498  real(srp), parameter, public :: food_item_migrate_depth_cv = &
2499  0.8_srp
2500 
2501  !.............................................................................
2502  ! ## Visual perception parameters ##
2503  ! Visual perception and range parameters, taken from the old code. They
2504  ! are normally left unchanged. These are used for the **food items / prey**,
2505  ! and may be set separately for the **agent** itself.
2506 
2507  !> Maximum above-surface light intensity at midday, DAYLIGHT=500.0.
2508  !! @note Can be deterministic or stochastic.
2509  real(srp), parameter, public :: daylight=500.0_srp
2510 
2511  !> Flag for stochastic daylight pattern (if TRUE) or deterministic sinusoidal
2512  !! (when FALSE). Check out the next parameter `DAYLIGHT_CV` for variability.
2513  logical, parameter, public :: daylight_stochastic = .true.
2514 
2515  !> Coefficient of variation for stochastic DAYLIGHT,
2516  !! @note if = 0.0 then deterministic sinusoidal daylight pattern is used.
2517  real(srp), parameter, public :: daylight_cv=0.2_srp
2518 
2519  !> Beam attenuation coefficient of water (m-1),BEAMATT = 1.0.
2520  !! @note See `the_environment::visual_range()` and
2521  !! `the_environment::srgetr()` for more details.
2522  real(srp), parameter, public :: beamatt=1.0_srp
2523 
2524  !> Inherent contrast of prey, CONTRAST =1.0.
2525  !! @note See `the_environment::visual_range()` and
2526  !! `the_environment::srgetr()` for more details.
2527  real(srp), parameter, public :: preycontrast_default = 1.0_srp
2528 
2529  !> Area of prey (m2), PREYAREA = 3.E-6.
2530  !! @note See `the_environment::visual_range()` and
2531  !! `the_environment::srgetr()` for more details.
2532  real(srp), parameter, public :: preyarea_default=3.e-6_srp
2533 
2534  !> Dimensionless descriptor of fish eye quality, VISCAP=1.6E6.
2535  !! @note See `the_environment::visual_range()` and
2536  !! `the_environment::srgetr()` for more details.
2537  real(srp), parameter, public :: viscap=1.6e6_srp
2538 
2539  !> Saturation parameter of eye (Ke) (uE m-2 s-1), EYESAT=500.0.
2540  !! @note See `the_environment::visual_range()` and
2541  !! `the_environment::srgetr()` for more details.
2542  real(srp), parameter, public :: eyesat=500.0_srp
2543 
2544  !> Vertical conservation of light, per depth (old code lightdecay=0.2).
2545  !! @note set = 0 if light constant with depth
2546  !! @note Because body size of the agent is set in cm, and the environment
2547  !! size is also in cm, we need to scale depth appropriately, in the old
2548  !! code it was within the range 0:30 m or unitless?, now the range
2549  !! is 0:3000 cm. So the appropriate scaling factor is 0.002.
2550  !! @note wxMaxima quick code for plotting (assuming surface light 500.0):
2551  !! @code
2552  !! wxplot2d( 500.0*exp(-0.002 * D), [D, 0., 3000.] );
2553  !! @endcode
2554  real(srp), parameter, public :: lightdecay = 0.002_srp
2555 
2556  !> @}
2557 
2558  !.............................................................................
2559  !.............................................................................
2560 
2561  !> @name Genetic architecture parameters
2562  !! @{
2563 
2564  ! Genetic architecture parameters
2565  ! ===============================
2566 
2567  ! ## Alleles ##
2568 
2569  ! The following two parameters define the range of possible allele values
2570  !> The minimum possible value of alleles (allele range minimum)
2571  !! See implementation notes on `the_genome::gene::allele_value` component
2572  !! of the `the_genome::gene` derived type and `commondata::alleleconv()` and
2573  !! `commondata::allelescale()` functions.
2574  !! @warning The minimum value should **not** be zero, as it will result in
2575  !! *division by zero* condition in `gamma2gene`, `(P/y)**x`.
2576  integer, parameter, public:: allelerange_min = 1
2577 
2578  !> The maximum possible value of alleles (allele range maximum)
2579  !! See implementation notes on `the_genome::gene::allele_value` component
2580  !! of the `the_genome::gene` derived type and `commondata::alleleconv()` and
2581  !! `commondata::allelescale()` functions.
2582  integer, parameter, public :: allelerange_max = 10000
2583 
2584  !> Conversion parameter that defines the scaling of the integer allele
2585  !! values ::ALLELERANGE_MIN to ALLELERANGE_MAX are converted to ::zero to
2586  !! this parameter value as the maximum. See ::allelescale() for details.
2587  real(srp), parameter, public :: allelescale_max = 20.0_srp
2588 
2589  !> Number of additive allele components
2590  integer, parameter, public :: additive_comps = 3
2591 
2592  ! ## Genes ##
2593 
2594  !> Mutation rate for point allele mutations
2595  real(srp), parameter, public :: mutationrate_point = 0.1_srp
2596 
2597  !> Maximum point mutation rate in the adaptive Fixed Fitness Genetic
2598  !! Algorithm
2599  real(srp), parameter, public :: ga_mutationrate_point_max = 0.25_srp
2600 
2601  !> Mutation rate for point allele mutations, a whole batch of allele
2602  !! components.
2603  real(srp), parameter, public :: mutationrate_batch = 0.05_srp
2604 
2605  !> Maximum batch mutation rate in the adaptive Fixed Fitness Genetic
2606  !! Algorithm
2607  real(srp), parameter, public :: ga_mutationrate_batch_max = 0.1_srp
2608 
2609  !> Mutation rate for chromosome relocation, i.e. probability of a gene
2610  !! moving to a different position on the same chromosome: There are two
2611  !! kinds of relocations, swapping genes between two positions and
2612  !! moving a gene with subsequent shift. So we have two constants for the
2613  !! respective rates
2614  real(srp), parameter, public :: relocation_swap_rate = 0.05_srp
2615  real(srp), parameter, public :: relocation_shift_rate = 0.01_srp
2616 
2617  ! ## Chromosomes ##
2618 
2619  !> The number of chromosomes for the agents.
2620  !! @warning This is the base for setting dimensionality of several other
2621  !! parameter arrays below!
2622  integer, parameter, public :: n_chromosomes = 6
2623 
2624  !> The number of alleles in each of the chromosomes. NOTE: This must be an
2625  !! array (vector) of the size `commondata::n_chromosomes`. We use new
2626  !! Fortran array constructor here to set the array values.
2627  !! @warning The dimensionality of this array must always coincide
2628  !! with `commondata::n_chromosomes`!
2629  integer, parameter, dimension(N_CHROMOSOMES), public :: len_chromosomes = &
2630  [ 6, 5, 12, 12, 12, 12 ]
2631 
2632  !> This parameter defines the maximum number of alleles within the chromosome
2633  !! It *IS NOT* intended to vary freely/independently. Used in definitions
2634  !! of `_GENOTYPE_PHENOTYPE` matrices, equal to the `maxval(LEN_CHROMOSOMES)`.
2635  !! @note This parameter is only used for setting the genotype x phenotype
2636  !! parameter matrices.
2637  !! @warning `maxval(LEN_CHROMOSOMES)` cannot be used for array declaration
2638  !! in many compilers, so should be set manually from values
2639  !! of LEN_CHROMOSOMES above. Or may be a scalar *exceeding*
2640  !! `maxval(LEN_CHROMOSOMES)`, in such case the extra values are
2641  !! padded with `.FALSE.` in `reshape` (see `reshape` in the
2642  !! parameter matricess below).
2643  integer, parameter, public :: max_nalleles = 12
2644 
2645  !> Set the labels of the chromosomes. NOTE, must be an array(vector) ) of
2646  !! the size `commondata::n_chromosomes`. We use new Fortran array constructor
2647  !! here to set the array values.
2648  !! @note Note that the length of the string values in the array declaration
2649  !! below are all the same. Many compilers will issue an error
2650  !! otherwise. Hence, the assignment is arranged vertically.
2651  !! @warning The dimensionality of this array must always coincide
2652  !! with `commondata::n_chromosomes`!
2653  character(len=*), parameter, dimension(N_CHROMOSOMES), public :: &
2654  lab_chromosomes = [ "C_1_SEX ", &
2655  "C_2_BODY", &
2656  "C_3_HORM", &
2657  "C_4_HUNG", &
2658  "C_5_FEAR", &
2659  "C_6_REPR" ]
2660 
2661  !> The ploidy of the chromosome set. Can theoretically be haploid (=1),
2662  !! diploid (=2) or, polyploid (>2).
2663  !! @warning The `gamma2gene` code does not work with *haploid* genotype
2664  !! `commondata::chromosome_ploidy=1`, in such a case there is no
2665  !! need to select random homologous chromosome and it is impossible
2666  !! to set the two parameters of the `gamma2gene` function.
2667  integer, parameter, public ::chromosome_ploidy = 2
2668 
2669  !> The ratio of the genome that inherited from the **mother**. The other part
2670  !! is inherited from the father. See implementation details of the
2671  !! **random independent** genetic recombination procedure
2672  !! `procedures the_genome::individual_genome::recombine()`.
2673  real(srp), parameter, public :: genome_recombination_ratio_mother = 0.8_srp
2674 
2675  !> Boolean 2D matrix that determines the pattern of **fixed** chromosome
2676  !! **crossover**. For each chromosome, the alleles that are marked with the
2677  !! TRUE (YES) values are inherited from the **mother** whereas those marked
2678  !! FALSE (NO) are inherited from the **father**. See implementation details
2679  !! of the **fixed genetic crossover** procedure
2680  !! `procedures the_genome::individual_genome::crossover()`.
2681  !! @note Note that the parameter order is **reversed**: alleles are
2682  !! presented by rows, chromosomes by columns,just as in the
2683  !! genotype x phenotype boolean matrices.
2684  logical, dimension(MAX_NALLELES,N_CHROMOSOMES), parameter,public &
2685  :: genome_crossover_fixed_mother = reshape ( &
2686  ! ............................................................................
2687  [ & ! 1 2 3 4 5 6
2688  !-------------------------
2689  yes,yes,yes,yes,yes,yes, & ! 1
2690  yes,yes,yes,yes,yes,yes, & ! 2
2691  yes,yes,yes,yes,yes,yes, & ! 3
2692  no, no,yes,yes,yes,yes, & ! 4
2693  no, no,yes,yes,yes,yes, & ! 5
2694  no, no,yes,yes,yes,yes, & ! 6
2695  no, no, no, no, no, no, & ! 7
2696  no, no, no, no, no, no, & ! 8
2697  no, no, no, no, no, no, & ! 9
2698  no, no, no, no, no, no, & ! 10
2699  no, no, no, no, no, no, & ! 11
2700  no, no, no, no, no, no ], & ! 12
2701  ! -------------------------
2702  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
2703  [max_nalleles,n_chromosomes],[no],[2,1] )
2704  ! Note: additional reshape params: array shape |pad | order
2705  ! |with| by rows
2706 
2707  ! ## Sex determination ##
2708 
2709  !> Sex ratio for initialising genomes @f[ \frac{N_{males}}{N_{females}} @f]
2710  !! should evolve and change during the evolution
2711  real(srp), parameter, public :: sex_ratio = 0.5_srp
2712 
2713  !> Labels for the sex locus alleles (gene) - vector as we don't need to label
2714  !! individual alleles. `LABEL_LENGTH` is here to avoid a GF warning
2715  character(len=LABEL_LENGTH), parameter :: sexlocus_label="SEX_LOCUS"
2716 
2717  !> Set names of the sexes -- the allele labels
2718  character(len=*), parameter, public :: male="male", female="female"
2719 
2720  !> Sex definition can be implemented differently from all other traits.
2721  !! Here is an example of the **phenotype** x **genotype matrix** code for
2722  !! sex determination:
2723  !! @code
2724  !! !> Sex definition can be implemented differently from all other traits.
2725  !! !! @note Note that the parameter order is **reversed**: alleles are
2726  !! !! presented by rows, chromosomes by columns.
2727  !! logical, dimension(MAX_NALLELES,N_CHROMOSOMES), parameter,public &
2728  !! :: SEX_GENOTYPE_PHENOTYPE = reshape ( &
2729  !! ! .........................................................................
2730  !! [ & ! 1 2 3 4 5 6
2731  !! !-------------------------
2732  !! YES, NO, NO, NO, NO, NO, & ! 1
2733  !! NO, NO, NO, NO, NO, NO, & ! 2
2734  !! NO, NO, NO, NO, NO, NO, & ! 3
2735  !! NO, NO, NO, NO, NO, NO, & ! 4
2736  !! NO, NO, NO, NO, NO, NO, & ! 5
2737  !! NO, NO, NO, NO, NO, NO, & ! 6
2738  !! NO, NO, NO, NO, NO, NO, & ! 7
2739  !! NO, NO, NO, NO, NO, NO, & ! 8
2740  !! NO, NO, NO, NO, NO, NO, & ! 9
2741  !! NO, NO, NO, NO, NO, NO, & ! 10
2742  !! NO, NO, NO, NO, NO, NO, & ! 11
2743  !! NO, NO, NO, NO, NO, NO ], & ! 12
2744  !! ! -------------------------
2745  !! ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
2746  !! [MAX_NALLELES,N_CHROMOSOMES],[NO],[2,1] )
2747  !! ! Note: additional reshape params: array shape |pad | order
2748  !! ! |with| by rows
2749  !! ! ............................................................................
2750  !! @endcode
2751  !! @note Note that the parameter order is **reversed**: alleles are
2752  !! presented by rows, chromosomes by columns.
2753  logical, dimension(MAX_NALLELES,N_CHROMOSOMES), parameter,public &
2754  :: sex_genotype_phenotype = reshape ( &
2755  ! ............................................................................
2756  [ & ! 1 2 3 4 5 6
2757  !-------------------------
2758  yes, no, no, no, no, no, & ! 1
2759  no, no, no, no, no, no, & ! 2
2760  no, no, no, no, no, no, & ! 3
2761  no, no, no, no, no, no, & ! 4
2762  no, no, no, no, no, no, & ! 5
2763  no, no, no, no, no, no, & ! 6
2764  no, no, no, no, no, no, & ! 7
2765  no, no, no, no, no, no, & ! 8
2766  no, no, no, no, no, no, & ! 9
2767  no, no, no, no, no, no, & ! 10
2768  no, no, no, no, no, no, & ! 11
2769  no, no, no, no, no, no ], & ! 12
2770  ! -------------------------
2771  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
2772  [max_nalleles,n_chromosomes],[no],[2,1] )
2773  ! Note: additional reshape params: array shape |pad | order
2774  ! |with| by rows
2775  ! ............................................................................
2776 
2777  !> @}
2778 
2779  !.............................................................................
2780  !.............................................................................
2781 
2782  !> @name Hormonal parameters
2783  !! @{
2784 
2785  ! Hormonal parameters
2786  ! ===================
2787 
2788  !> @brief Genotype x Phenotype matrix for **growth hormone**.
2789  !! @details This two-dimensional array defines the phenotypic structure of the
2790  !! hormone objects, i.e. the correspondence between the gene objects
2791  !! and the trait values (produced by the sigmoid function). That is,
2792  !! which genes on which chromosomes contribute to the pheontypic
2793  !! values of the trait objects. This is a two dimensional array of
2794  !! the `logical` type that defines the allele and chromosome
2795  !! contributes to this specific trait.
2796  !! @note Note that the dimensions of the genetic structure array must fit
2797  !! within the `N_CHROMOSOMES x maxval(LEN_CHROMOSOMES(chrom_nr))`.
2798  !! @note Note that the parameter order is **reversed**: alleles are
2799  !! presented by rows, chromosomes by columns.
2800  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
2801  :: growhorm_genotype_phenotype = reshape ( &
2802  ! ............................................................................
2803  [ & ! 1 2 3 4 5 6
2804  !------------------------
2805  no, no,yes, no, no, no, & ! 1
2806  no, no, no, no, no, no, & ! 2
2807  no, no, no, no, no, no, & ! 3
2808  no, no, no, no, no, no, & ! 4
2809  no, no, no, no, no, no, & ! 5
2810  no, no, no, no, no, no, & ! 6
2811  no, no, no, no, no, no, & ! 7
2812  no, no, no, no, no, no, & ! 8
2813  no, no, no, no, no, no, & ! 9
2814  no, no, no, no, no, no, & ! 10
2815  no, no, no, no, no, no, & ! 11
2816  no, no, no, no, no, no ], & ! 12
2817  ! -------------------------
2818  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
2819  [max_nalleles,n_chromosomes],[no],[2,1] )
2820  ! Note: additional reshape params: array shape |pad | order
2821  ! |with| by rows
2822  ! ............................................................................
2823 
2824  !> Genotype to phenotype gamma2gene initialisation value for **growth
2825  !! hormone**
2826  real(srp), parameter, public :: growhorm_init = 0.5_srp
2827 
2828  !> Genotype to phenotype gamma2gene Gaussian error parameter. This is
2829  !! really the coefficient of variation of the output hormone level with
2830  !! respect to an ideal value (initially 0).
2831  real(srp), parameter, public :: growhorm_gerror_cv = 0.5_srp
2832 
2833  !-----------------------------------------------------------------------------
2834 
2835  !> @brief Genotype x Phenotype matrix for **thyroid**.
2836  !! @details This two-dimensional array defines the phenotypic structure of the
2837  !! hormone objects, i.e. the correspondence between the gene objects
2838  !! and the trait values (produced by the sigmoid function). That is,
2839  !! which genes on which chromosomes contribute to the pheontypic
2840  !! values of the trait objects. This is a two dimensional array of
2841  !! the `logical` type that defines the allele and chromosome
2842  !! contributes to this specific trait.
2843  !! @note Note that the dimensions of the genetic structure array must fit
2844  !! within the `N_CHROMOSOMES x maxval(LEN_CHROMOSOMES(chrom_nr))`.
2845  !! @note Note that the parameter order is **reversed**: alleles are
2846  !! presented by rows, chromosomes by columns.
2847  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
2848  :: thyroid_genotype_phenotype = reshape ( &
2849  ! ............................................................................
2850  [ & ! 1 2 3 4 5 6
2851  !------------------------
2852  no, no, no, no, no, no, & ! 1
2853  no, no,yes, no, no, no, & ! 2
2854  no, no, no, no, no, no, & ! 3
2855  no, no, no, no, no, no, & ! 4
2856  no, no, no, no, no, no, & ! 5
2857  no, no, no, no, no, no, & ! 6
2858  no, no, no, no, no, no, & ! 7
2859  no, no, no, no, no, no, & ! 8
2860  no, no, no, no, no, no, & ! 9
2861  no, no, no, no, no, no, & ! 10
2862  no, no, no, no, no, no, & ! 11
2863  no, no, no, no, no, no ], & ! 12
2864  ! -------------------------
2865  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
2866  [max_nalleles,n_chromosomes],[no],[2,1] )
2867  ! Note: additional reshape params: array shape |pad | order
2868  ! |with| by rows
2869  ! ............................................................................
2870 
2871  !> Genotype to phenotype gamma2gene initialisation value for **thyroid**
2872  real(srp), parameter, public :: thyroid_init = 0.5_srp
2873 
2874  !> Genotype to phenotype gamma2gene Gaussian error parameter. This is
2875  !! really the coefficient of variation of the output hormone level with
2876  !! respect to an ideal value (initially 0).
2877  real(srp), parameter, public :: thyroid_gerror_cv = 0.5_srp
2878 
2879  !-----------------------------------------------------------------------------
2880 
2881  !> @brief Genotype x Phenotype matrix for **adrenaline**
2882  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
2883  :: adrenaline_genotype_phenotype = reshape ( &
2884  ! ............................................................................
2885  [ & ! 1 2 3 4 5 6
2886  !------------------------
2887  no, no, no, no, no, no, & ! 1
2888  no, no, no, no, no, no, & ! 2
2889  no, no,yes, no, no, no, & ! 3
2890  no, no, no, no, no, no, & ! 4
2891  no, no, no, no, no, no, & ! 5
2892  no, no, no, no, no, no, & ! 6
2893  no, no, no, no, no, no, & ! 7
2894  no, no, no, no, no, no, & ! 8
2895  no, no, no, no, no, no, & ! 9
2896  no, no, no, no, no, no, & ! 10
2897  no, no, no, no, no, no, & ! 11
2898  no, no, no, no, no, no ], & ! 12
2899  ! -------------------------
2900  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
2901  [max_nalleles,n_chromosomes],[no],[2,1] )
2902  ! Note: additional reshape params: array shape |pad | order
2903  ! |with| by rows
2904  ! ............................................................................
2905 
2906  !> Genotype to phenotype gamma2gene initialisation value for **adrenaline**
2907  real(srp), parameter, public :: adrenaline_init = 0.5_srp
2908 
2909  !> Genotype to phenotype gamma2gene Gaussian error parameter. This is
2910  !! really the coefficient of variation of the output hormone level with
2911  !! respect to an ideal value (initially 0).
2912  real(srp), parameter, public :: adrenaline_gerror_cv = 0.5_srp
2913 
2914  !-----------------------------------------------------------------------------
2915 
2916  !> @brief Genotype x Phenotype matrix for **cortisol**.
2917  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
2918  :: cortisol_genotype_phenotype = reshape ( &
2919  ! ............................................................................
2920  [ & ! 1 2 3 4 5 6
2921  !------------------------
2922  no, no, no, no, no, no, & ! 1
2923  no, no, no, no, no, no, & ! 2
2924  no, no, no, no, no, no, & ! 3
2925  no, no,yes, no, no, no, & ! 4
2926  no, no, no, no, no, no, & ! 5
2927  no, no, no, no, no, no, & ! 6
2928  no, no, no, no, no, no, & ! 7
2929  no, no, no, no, no, no, & ! 8
2930  no, no, no, no, no, no, & ! 9
2931  no, no, no, no, no, no, & ! 10
2932  no, no, no, no, no, no, & ! 11
2933  no, no, no, no, no, no ], & ! 12
2934  ! -------------------------
2935  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
2936  [max_nalleles,n_chromosomes],[no],[2,1] )
2937  ! Note: additional reshape params: array shape |pad | order
2938  ! |with| by rows
2939  ! ............................................................................
2940 
2941  !> Genotype to phenotype gamma2gene initialisation value for **cortisol**
2942  real(srp), parameter, public :: cortisol_init = 0.5_srp
2943 
2944  !> Genotype to phenotype gamma2gene Gaussian error parameter. This is
2945  !! really the coefficient of variation of the output hormone level with
2946  !! respect to an ideal value (initially 0).
2947  real(srp), parameter, public :: cortisol_gerror_cv = 0.5_srp
2948 
2949  !-----------------------------------------------------------------------------
2950 
2951  !> @brief Genotype x Phenotype matrix for **testosterone**.
2952  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
2953  :: testosterone_genotype_phenotype = reshape ( &
2954  ! ............................................................................
2955  [ & ! 1 2 3 4 5 6
2956  !------------------------
2957  no, no, no, no, no, no, & ! 1
2958  no, no, no, no, no, no, & ! 2
2959  no, no, no, no, no, no, & ! 3
2960  no, no, no, no, no, no, & ! 4
2961  no, no,yes, no, no, no, & ! 5
2962  no, no, no, no, no, no, & ! 6
2963  no, no, no, no, no, no, & ! 7
2964  no, no, no, no, no, no, & ! 8
2965  no, no, no, no, no, no, & ! 9
2966  no, no, no, no, no, no, & ! 10
2967  no, no, no, no, no, no, & ! 11
2968  no, no, no, no, no, no ], & ! 12
2969  ! -------------------------
2970  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
2971  [max_nalleles,n_chromosomes],[no],[2,1] )
2972  ! Note: additional reshape params: array shape |pad | order
2973  ! |with| by rows
2974  ! ............................................................................
2975 
2976  !> Genotype to phenotype gamma2gene initialisation value for **testosterone**
2977  real(srp), parameter, public :: testosterone_init = 0.01_srp
2978 
2979  !> Genotype to phenotype gamma2gene Gaussian error parameter. This is
2980  !! really the coefficient of variation of the output hormone level with
2981  !! respect to an ideal value (initially 0).
2982  real(srp), parameter, public :: testosterone_gerror_cv = 0.5_srp
2983 
2984  !-----------------------------------------------------------------------------
2985 
2986  !> @brief Genotype x Phenotype matrix for ESTROGEN
2987  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
2988  :: estrogen_genotype_phenotype = reshape ( &
2989  ! ............................................................................
2990  [ & ! 1 2 3 4 5 6
2991  !------------------------
2992  no, no, no, no, no, no, & ! 1
2993  no, no, no, no, no, no, & ! 2
2994  no, no, no, no, no, no, & ! 3
2995  no, no, no, no, no, no, & ! 4
2996  no, no, no, no, no, no, & ! 5
2997  no, no,yes, no, no, no, & ! 6
2998  no, no, no, no, no, no, & ! 7
2999  no, no, no, no, no, no, & ! 8
3000  no, no, no, no, no, no, & ! 9
3001  no, no, no, no, no, no, & ! 10
3002  no, no, no, no, no, no, & ! 11
3003  no, no, no, no, no, no ], & ! 12
3004  ! -------------------------
3005  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3006  [max_nalleles,n_chromosomes],[no],[2,1] )
3007  ! Note: additional reshape params: array shape |pad | order
3008  ! |with| by rows
3009  ! ............................................................................
3010 
3011  !> Genotype to phenotype gamma2gene initialisation value for **estrogen**
3012  real(srp), parameter, public :: estrogen_init = 0.01_srp
3013 
3014  !> Genotype to phenotype gamma2gene Gaussian error parameter. This is
3015  !! really the coefficient of variation of the output hormone level with
3016  !! respect to an ideal value (initially 0).
3017  real(srp), parameter, public :: estrogen_gerror_cv = 0.5_srp
3018 
3019  !-----------------------------------------------------------------------------
3020  ! ## Sex steroid increment parameters ##
3021 
3022  !> The number of the latest historical values that are checked for change
3023  !! when setting an increment of the **sex steroid** hormones.
3024  integer, parameter, public :: sex_steroids_check_history = 3
3025 
3026  !- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3027  !> @note Note that these parameters link sex steroid increment
3028  !! with the agent's **age**.
3029 
3030  !> The array defining the **abscissa** (X) of the nonparametric function
3031  !! curve that defines the relationship between the age of the agent
3032  !! and the steroid increment factor for this specific age.
3033  !! @warning The LIFESPAN parameter has to be converted to the real type.
3034  !! @warning All these arrays must have the same dimensionality:
3035  !! - commondata::sex_steroids_increment_factor_age_curve_abscissa
3036  !! - commondata::sex_steroids_increment_factor_age_curve_ordinate
3037  !! - commondata::sex_steroids_increment_factor_len_curve_abscissa
3038  !! - commondata::sex_steroids_increment_factor_len_curve_ordinate
3039  !! .
3040  real(srp), dimension(*), &
3041  parameter, public :: sex_steroids_increment_factor_age_curve_abscissa = &
3042  [ 0.0_srp, real(lifespan, srp)*0.25_srp, real(lifespan, srp) ]
3043 
3044  !> The array defining the **ordinate** (Y) of the nonparametric function
3045  !! curve that defines the relationship between the age of the agent
3046  !! and the steroid increment factor for this specific age.
3047  !! @warning All these arrays must have the same dimensionality:
3048  !! - commondata::sex_steroids_increment_factor_age_curve_abscissa
3049  !! - commondata::sex_steroids_increment_factor_age_curve_ordinate
3050  !! - commondata::sex_steroids_increment_factor_len_curve_abscissa
3051  !! - commondata::sex_steroids_increment_factor_len_curve_ordinate
3052  !! .
3053  real(srp), dimension(*), &
3054  parameter, public :: sex_steroids_increment_factor_age_curve_ordinate = &
3055  [ 0.0_srp, 0.01_srp, 0.1_srp ]
3056 
3057  !- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3058  !> @note Note that these parameters link sex steroid increment
3059  !! with the agent's **body length**.
3060 
3061  !> The array defining the **abscissa** (X) of the nonparametric function
3062  !! curve that defines the relationship between the body length of the agent
3063  !! and the steroid increment factor for this specific length.
3064  !! @warning All these arrays must have the same dimensionality:
3065  !! - commondata::sex_steroids_increment_factor_age_curve_abscissa
3066  !! - commondata::sex_steroids_increment_factor_age_curve_ordinate
3067  !! - commondata::sex_steroids_increment_factor_len_curve_abscissa
3068  !! - commondata::sex_steroids_increment_factor_len_curve_ordinate
3069  !! .
3070  real(srp), dimension(*), &
3071  parameter, public :: sex_steroids_increment_factor_len_curve_abscissa = &
3072  [ 0.0_srp, body_length_max*0.2_srp, body_length_max ]
3073 
3074  !> The array defining the **ordinate** (Y) of the nonparametric function
3075  !! curve that defines the relationship between the body length of the agent
3076  !! and the steroid increment factor for this specific length.
3077  !! @warning All these arrays must have the same dimensionality:
3078  !! - commondata::sex_steroids_increment_factor_age_curve_abscissa
3079  !! - commondata::sex_steroids_increment_factor_age_curve_ordinate
3080  !! - commondata::sex_steroids_increment_factor_len_curve_abscissa
3081  !! - commondata::sex_steroids_increment_factor_len_curve_ordinate
3082  !! .
3083  real(srp), dimension(*), &
3084  parameter, public :: sex_steroids_increment_factor_len_curve_ordinate = &
3085  [ 0.0_srp, 0.01_srp, 0.1_srp ]
3086 
3087  !> @}
3088 
3089  !.............................................................................
3090  !.............................................................................
3091 
3092  !> @name Body parameters, individual physiology and condition
3093  !! @{
3094 
3095  ! Body parameters, individual physiology and condition
3096  ! ====================================================
3097 
3098  !> History stack size for the agent's basic properties, such as body length
3099  !! and body mass. Normally they are saved only for the analysis and currently
3100  !! not used in the perception.
3101  integer, parameter, public :: history_size_agent_prop = 100
3102 
3103  !> Living cost in terms of food consumed. metabolic costs, p
3104  !! roportional to body size
3105  real(srp), parameter, public :: living_cost = 4.0_srp
3106 
3107  !> A minimum body mass increment when any linear growth is possible,
3108  !! in units of the body mass (e.g. 0.05 = 5%)
3109  real(srp), parameter, public :: mass_growth_threshold = 0.0001_srp
3110 
3111  !> Growth exponent linking linear growth and body mass growth. Based on
3112  !! Fulton's condition factor "cube law."
3113  !! @note It is real and can get noninteger values due to nonisometric growth.
3114  real(srp), parameter, public :: linear_growth_exponent = 3.0_srp
3115 
3116  !> The array defining the **abscissa** (X) of the nonparametric function
3117  !! curve that defines the function linking the relationship between the
3118  !! growth hormone and the relative linear growth increment.
3119  !! @warning Note that these are raw values that should go via the gamma2gene
3120  !! fake "guess" calculation version.
3121  !! @warning Must have the same dimensionality as
3122  !! commondata::linear_growth_hormone_increment_factor_curve_ordinate.
3123  real(srp), dimension(*), &
3124  parameter, public :: &
3126  [ 0.0_srp, growhorm_init, growhorm_init*3.0_srp, &
3127  growhorm_init*5.0_srp, growhorm_init*20.0_srp ]
3128 
3129  !> The array defining the **ordinate** (Y) of the nonparametric function
3130  !! curve that defines the function linking the relationship between the
3131  !! growth hormone and the relative linear growth increment.
3132  !! @warning Must have the same dimensionality as
3133  !! commondata::linear_growth_hormone_increment_factor_curve_abscissa.
3134  real(srp), dimension(*), &
3135  parameter, public :: &
3137  [0.0_srp, 0.6_srp, 0.9_srp, 0.98, 1.00_srp]
3138 
3139  !> Set the maximum stomach capacity default value -- fraction of the
3140  !! body mass available for food. Can be overriden in different agent types.
3141  !! Normally 15%
3142  real(srp), parameter, public :: max_stomach_capacity_def = 0.15_srp
3143 
3144  !> @brief Stomach content emptify factor at each step.
3145  !! @details Stomach contents S(t) is emptied by a constant fraction each
3146  !! time step @f[ S_{t} =S_{t+1} \frac{ K }{\Omega } @f],
3147  !! where @f$ K @f$ is the stomach content emptify factor.
3148  real(srp), parameter, public :: stomach_content_emptify_factor = 100.0_srp
3149 
3150  !> Set average stomach capacity at birth/init in units of body weight,
3151  !! @note it is a random Gaussian variable, this just sets the mean value,
3152  !! the next parameter sets coefficient of variation
3153  real(srp), parameter, public :: stomach_content_init = 0.01_srp
3154 
3155  !> Set the coefficient of variation for the stomach capacity at init
3156  real(srp), parameter, public :: stomach_content_init_cv = 0.05_srp
3157 
3158  !> Set the weighting factor parameter of burst swimming cost in terms of
3159  !! the agent body size and the distance expressed in terms of the agent
3160  !! body lengths. In the_body::condition_cost_swimming_burst(), this
3161  !! parameter sets the @f$ \beta @f$ coefficient.
3162  real(srp), parameter, public :: swimming_speed_cost_burst = 0.1e-4_srp
3163 
3164  !> Set the cost of foraging in terms of SMR.
3165  real(srp), parameter, public :: cost_factor_foraging_smr = 0.1e-5_srp
3166 
3167  !-----------------------------------------------------------------------------
3168 
3169  !> @brief The initial value of the **energy reserves** at birth is genetically
3170  !! determined. This is the Genotype x Phenotype matrix for energy
3171  !! reserves.
3172  logical, dimension(MAX_NALLELES,N_CHROMOSOMES), parameter, public &
3173  :: energy_genotype_phenotype = reshape ( &
3174  ! ............................................................................
3175  [ & ! 1 2 3 4 5 6
3176  !------------------------
3177  no, no, no, no, no, no, & ! 1
3178  no, no, no, no, no, no, & ! 2
3179  no, no, no, no, no, no, & ! 3
3180  no, no, no, no, no, no, & ! 4
3181  no, no, no, no, no, no, & ! 5
3182  no, no, no, no, no, no, & ! 6
3183  no, no, no, no, no, no, & ! 7
3184  no, no, no, no, no, no, & ! 8
3185  no, no, no, no, no, no, & ! 9
3186  no, no, no, no, no, no, & ! 10
3187  no, no, no, no, no, no, & ! 11
3188  no, no, no, no, no, no ], & ! 12
3189  ! -------------------------
3190  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3191  [max_nalleles,n_chromosomes],[no],[2,1] )
3192  ! Note: additional reshape params: array shape |pad | order
3193  ! |with| by rows
3194  ! ............................................................................
3195 
3196  !> This is the initial value of the energy reserves, non-genetic mean.
3197  real(srp), parameter, public :: energy_init = 0.18
3198 
3199  !> Genotype to phenotype initialisation, Gaussian error parameter. Coefficient
3200  !! of variation for the `ENERGY_INIT` value
3201  real(srp), parameter, public :: energy_gerror_cv = 0.01
3202 
3203  !-----------------------------------------------------------------------------
3204 
3205  !> @brief The initial value of the body length at birth is genetically
3206  !! determined. This is the Genotype x Phenotype matrix for body length.
3207  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3208  :: body_length_genotype_phenotype = reshape ( &
3209  ! ............................................................................
3210  [ & ! 1 2 3 4 5 6
3211  !------------------------
3212  no, no, no, no, no, no, & ! 1
3213  no, no, no, no, no, no, & ! 2
3214  no, no, no, no, no, no, & ! 3
3215  no, no, no, no, no, no, & ! 4
3216  no, no, no, no, no, no, & ! 5
3217  no, no, no, no, no, no, & ! 6
3218  no, no, no, no, no, no, & ! 7
3219  no, no, no, no, no, no, & ! 8
3220  no, no, no, no, no, no, & ! 9
3221  no, no, no, no, no, no, & ! 10
3222  no, no, no, no, no, no, & ! 11
3223  no, no, no, no, no, no ], & ! 12
3224  ! -------------------------
3225  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3226  [max_nalleles,n_chromosomes],[no],[2,1] )
3227  ! Note: additional reshape params: array shape |pad | order
3228  ! |with| by rows
3229  ! ............................................................................
3230 
3231  !> The initial value of **body length**, the average (gon-genetic).
3232  real(srp), parameter, public :: body_length_init = 2.3_srp
3233 
3234  !> Genotype to phenotype initialisation, Gaussian error parameter. Coefficient
3235  !! of variation for the `BODY_LENGTH_INIT` value
3236  real(srp), parameter, public :: body_length_gerror_cv = 0.1_srp
3237 
3238  !-----------------------------------------------------------------------------
3239 
3240  !> @brief The initial value of the **control unselected** trait. This trait
3241  !! is is genetically determined but is not selected or used. So it
3242  !! can be used to control for random genetic drift. This is the
3243  !! Genotype x Phenotype matrix.
3244  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3245  :: control_unselected_genotype_phenotype = reshape ( &
3246  ! ............................................................................
3247  [ & ! 1 2 3 4 5 6
3248  !------------------------
3249  no, no, no, no, no, no, & ! 1
3250  no, no, no, no, no, no, & ! 2
3251  no,yes, no, no, no, no, & ! 3
3252  no, no, no, no, no, no, & ! 4
3253  no, no, no, no, no, no, & ! 5
3254  no, no, no, no, no, no, & ! 6
3255  no, no, no, no, no, no, & ! 7
3256  no, no, no, no, no, no, & ! 8
3257  no, no, no, no, no, no, & ! 9
3258  no, no, no, no, no, no, & ! 10
3259  no, no, no, no, no, no, & ! 11
3260  no, no, no, no, no, no ], & ! 12
3261  ! -------------------------
3262  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3263  [max_nalleles,n_chromosomes],[no],[2,1] )
3264  ! Note: additional reshape params: array shape |pad | order
3265  ! |with| by rows
3266  ! ............................................................................
3267 
3268  !> The initial value of the **control unselected** trait that goes through
3269  !! the gamma2gene.
3270  real(srp), parameter, public :: control_unselected_init = 0.5_srp
3271 
3272  !> Genotype to phenotype initialisation, Gaussian error parameter. Coefficient
3273  !! of variation for the control unselected trait.
3274  real(srp), parameter, public :: control_unselected_gerror_cv = 0.5_srp
3275 
3276  !-----------------------------------------------------------------------------
3277 
3278  !> @brief The initial value of the standard metabolic rate (SMR) at birth is
3279  !! genetically determined. This is the Genotype x Phenotype matrix
3280  !! for SMR.
3281  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3282  :: smr_genotype_phenotype = reshape ( &
3283  ! ............................................................................
3284  [ & ! 1 2 3 4 5 6
3285  !------------------------
3286  no, no, no, no, no, no, & ! 1
3287  no, no, no, no, no, no, & ! 2
3288  no, no, no, no, no, no, & ! 3
3289  no,yes, no, no, no, no, & ! 4
3290  no, no, no, no, no, no, & ! 5
3291  no, no, no, no, no, no, & ! 6
3292  no, no, no, no, no, no, & ! 7
3293  no, no, no, no, no, no, & ! 8
3294  no, no, no, no, no, no, & ! 9
3295  no, no, no, no, no, no, & ! 10
3296  no, no, no, no, no, no, & ! 11
3297  no, no, no, no, no, no ], & ! 12
3298  ! -------------------------
3299  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3300  [max_nalleles,n_chromosomes],[no],[2,1] )
3301  ! Note: additional reshape params: array shape |pad | order
3302  ! |with| by rows
3303  ! ............................................................................
3304 
3305  !> This is the initial value of SMR that goes through the gamma2gene
3306  real(srp), parameter, public :: smr_init = 0.5_srp
3307 
3308  !> Genotype to phenotype initialisation, Gaussian error parameter. Coefficient
3309  !! of variation for the `SMR_LENGTH_INIT` value
3310  real(srp), parameter, public :: smr_gerror_cv = 0.5_srp
3311 
3312  !> Minimum SMR value, anything lower is not allowed.
3313  real(srp), parameter, public :: smr_min = 0.01_srp
3314 
3315  !> Default swimming cost body mass exponent parameter for **laminar**
3316  !! flow. See doi:10.1242/jeb.01484 (https://dx.doi.org/10.1242/jeb.01484)
3317  !! and the_body::condition_cost_swimming_burst() for details.
3318  real(srp), parameter :: swimming_cost_exponent_laminar = 0.5_srp
3319 
3320  !> Default swimming cost body mass exponent parameter for **turbulent**
3321  !! flow. See doi:10.1242/jeb.01484 (https://dx.doi.org/10.1242/jeb.01484)
3322  !! and the_body::condition_cost_swimming_burst() for details.
3323  real(srp), parameter :: swimming_cost_exponent_turbulent = 0.6_srp
3324 
3325  !> This parameter defines the cost of the buoyancy-based locomotion as a
3326  !! fraction of normal laminar flow propulsion for lowering downwards.
3327  real(srp), parameter, public :: swimming_cost_factor_buoyancy_down = 0.01_srp
3328 
3329  !> This parameter defines the cost of the buoyancy-based locomotion as a
3330  !! fraction of normal laminar flow propulsion for lowering downwards.
3331  !! @note Note that the relative cost of buoyancy-based swimming up is
3332  !! higher than down because gas secretion is more slow and demanding
3333  !! than absorption.
3334  real(srp), parameter, public :: swimming_cost_factor_buoyancy_up = 0.1_srp
3335 
3336 
3337  !> @}
3338 
3339  !.............................................................................
3340  !.............................................................................
3341 
3342  !> @name Parameters of the neurobiological architecture
3343  !! @{
3344 
3345  ! Parameters of the neurobiological architecture
3346  ! ==============================================
3347 
3348  ! ## Perception ##
3349 
3350  !. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3351  ! ### Parameters of food objects/items **perception** ###
3352 
3353  !> Sets the limit for partial indexing and ranking of **food items** in
3354  !! the visual range of the agents.
3355  !! @note Calculating the distances between the agent and food items
3356  !! may be very slow if the number of food items is large (and
3357  !! every agent should do this repeatedly!!!). So we use partial
3358  !! indexing, we need only small number of neighbouring food
3359  !! items anyway.
3360  integer, parameter, public :: food_select_items_index_partial = 20
3361 
3362  !> Sets the limit for partial indexing and ranking of **conspecifics**
3363  !! in the visual range of the agent.
3364  integer, parameter, public :: consp_select_items_index_partial = 20
3365 
3366  !> Sets the limit for partial indexing and ranking of **predators**
3367  !! in the visual range of the agent.
3368  integer, parameter, public :: pred_select_items_index_partial = 20
3369 
3370  !> Inherent contrast of the **agent**, It is used in determining
3371  !! the visual range of an agent in perception of conspecifics, and also
3372  !! for assessing the agent's detectability by predator. Default Contrast of
3373  !! food items is set separately.
3374  real(srp), parameter, public :: individual_visual_contrast_default = 1.0_srp
3375 
3376  !> Sets the size of the perception memory stack.
3377  integer, parameter, public :: history_size_perception = history_size_spatial
3378 
3379  !.............................................................................
3380 
3381  ! ## Appraisal ##
3382 
3383  !.............................................................................
3384 
3385  !> Sets the size of the emotional state memory stack.
3386  integer, parameter, public :: history_size_motivation = history_size_spatial
3387 
3388  !.............................................................................
3389  ! ### Parameters for the HUNGER motivational state ###
3390 
3391  !-----------------------------------------------------------------------------
3392  !> The genotype structure for **light** perception effects on **hunger**
3393  !! that goes via gamma2gene perception to neuronal response.
3394  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3395  :: light_hunger_genotype_neuronal = reshape ( &
3396  ! ............................................................................
3397  [ & ! 1 2 3 4 5 6
3398  !------------------------
3399  no, no, no,yes, no, no, & ! 1
3400  no, no, no, no, no, no, & ! 2
3401  no, no, no, no, no, no, & ! 3
3402  no, no, no, no, no, no, & ! 4
3403  no, no, no, no, no, no, & ! 5
3404  no, no, no, no, no, no, & ! 6
3405  no, no, no, no, no, no, & ! 7
3406  no, no, no, no, no, no, & ! 8
3407  no, no, no, no, no, no, & ! 9
3408  no, no, no, no, no, no, & ! 10
3409  no, no, no, no, no, no, & ! 11
3410  no, no, no, no, no, no ], & ! 12
3411  ! -------------------------
3412  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3413  [max_nalleles,n_chromosomes],[no],[2,1] )
3414  ! Note: additional reshape params: array shape |pad | order
3415  ! |with| by rows
3416  ! ............................................................................
3417 
3418  !> Gaussian perception error parameter (cv) for **light** perception
3419  !! effects on **hunger**.
3420  real(srp), parameter, public :: &
3422 
3423  !-----------------------------------------------------------------------------
3424  !> The genotype structure for **depth** perception effects on **hunger**
3425  !! that goes via gamma2gene perception to neuronal response.
3426  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3427  :: depth_hunger_genotype_neuronal = reshape ( &
3428  ! ............................................................................
3429  [ & ! 1 2 3 4 5 6
3430  !------------------------
3431  no, no, no, no, no, no, & ! 1
3432  no, no, no,yes, no, no, & ! 2
3433  no, no, no, no, no, no, & ! 3
3434  no, no, no, no, no, no, & ! 4
3435  no, no, no, no, no, no, & ! 5
3436  no, no, no, no, no, no, & ! 6
3437  no, no, no, no, no, no, & ! 7
3438  no, no, no, no, no, no, & ! 8
3439  no, no, no, no, no, no, & ! 9
3440  no, no, no, no, no, no, & ! 10
3441  no, no, no, no, no, no, & ! 11
3442  no, no, no, no, no, no ], & ! 12
3443  ! -------------------------
3444  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3445  [max_nalleles,n_chromosomes],[no],[2,1] )
3446  ! Note: additional reshape params: array shape |pad | order
3447  ! |with| by rows
3448  ! ............................................................................
3449 
3450  !> Gaussian perception error parameter (cv) for **depth** perception
3451  !! effects on **hunger**.
3452  real(srp), parameter, public :: &
3454 
3455  !-----------------------------------------------------------------------------
3456  !> The genotype structure for **food items count** perception effects on
3457  !! **hunger** that goes via gamma2gene perception to neuronal response.
3458  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3459  :: foodcount_hunger_genotype_neuronal = reshape ( &
3460  ! ............................................................................
3461  [ & ! 1 2 3 4 5 6
3462  !------------------------
3463  no, no, no, no, no, no, & ! 1
3464  no, no, no, no, no, no, & ! 2
3465  no, no, no,yes, no, no, & ! 3
3466  no, no, no, no, no, no, & ! 4
3467  no, no, no, no, no, no, & ! 5
3468  no, no, no, no, no, no, & ! 6
3469  no, no, no, no, no, no, & ! 7
3470  no, no, no, no, no, no, & ! 8
3471  no, no, no, no, no, no, & ! 9
3472  no, no, no, no, no, no, & ! 10
3473  no, no, no, no, no, no, & ! 11
3474  no, no, no, no, no, no ], & ! 12
3475  ! -------------------------
3476  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3477  [max_nalleles,n_chromosomes],[no],[2,1] )
3478  ! Note: additional reshape params: array shape |pad | order
3479  ! |with| by rows
3480  ! ............................................................................
3481 
3482  !> Gaussian perception error parameter (cv) for **food items count**
3483  !! perception effects on **hunger**.
3484  real(srp), parameter, public :: &
3486 
3487  !-----------------------------------------------------------------------------
3488  !> The genotype structure for **food items count** perception effects on
3489  !! **hunger** that goes via gamma2gene perception to neuronal response.
3490  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3491  :: food_mem_hunger_genotype_neuronal = reshape ( &
3492  ! ............................................................................
3493  [ & ! 1 2 3 4 5 6
3494  !------------------------
3495  no, no, no, no, no, no, & ! 1
3496  no, no, no, no, no, no, & ! 2
3497  no, no, no, no, no, no, & ! 3
3498  no, no, no,yes, no, no, & ! 4
3499  no, no, no, no, no, no, & ! 5
3500  no, no, no, no, no, no, & ! 6
3501  no, no, no, no, no, no, & ! 7
3502  no, no, no, no, no, no, & ! 8
3503  no, no, no, no, no, no, & ! 9
3504  no, no, no, no, no, no, & ! 10
3505  no, no, no, no, no, no, & ! 11
3506  no, no, no, no, no, no ], & ! 12
3507  ! -------------------------
3508  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3509  [max_nalleles,n_chromosomes],[no],[2,1] )
3510  ! Note: additional reshape params: array shape |pad | order
3511  ! |with| by rows
3512  ! ............................................................................
3513 
3514  !> Gaussian perception error parameter (cv) for **food items count**
3515  !! perception effects on **hunger**.
3516  real(srp), parameter, public :: &
3518 
3519  !-----------------------------------------------------------------------------
3520  !> The genotype structure for **conspecifics number** perception effects on
3521  !! **hunger** that goes via gamma2gene perception to neuronal response.
3522  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3523  :: conspcount_hunger_genotype_neuronal = reshape ( &
3524  ! ............................................................................
3525  [ & ! 1 2 3 4 5 6
3526  !------------------------
3527  no, no, no, no, no, no, & ! 1
3528  no, no, no, no, no, no, & ! 2
3529  no, no, no, no, no, no, & ! 3
3530  no, no, no, no, no, no, & ! 4
3531  no, no, no,yes, no, no, & ! 5
3532  no, no, no, no, no, no, & ! 6
3533  no, no, no, no, no, no, & ! 7
3534  no, no, no, no, no, no, & ! 8
3535  no, no, no, no, no, no, & ! 9
3536  no, no, no, no, no, no, & ! 10
3537  no, no, no, no, no, no, & ! 11
3538  no, no, no, no, no, no ], & ! 12
3539  ! -------------------------
3540  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3541  [max_nalleles,n_chromosomes],[no],[2,1] )
3542  ! Note: additional reshape params: array shape |pad | order
3543  ! |with| by rows
3544  ! ............................................................................
3545 
3546  !> Gaussian perception error parameter (cv) for **conspecifics number count**
3547  !! perception effects on **hunger**.
3548  real(srp), parameter, public :: &
3550 
3551  !-----------------------------------------------------------------------------
3552  !> The genotype structure for **direct predation** perception effects on
3553  !! **hunger** that goes via gamma2gene perception to neuronal response.
3554  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3555  :: pred_direct_hunger_genotype_neuronal = reshape ( &
3556  ! ............................................................................
3557  [ & ! 1 2 3 4 5 6
3558  !------------------------
3559  no, no, no, no, no, no, & ! 1
3560  no, no, no, no, no, no, & ! 2
3561  no, no, no, no, no, no, & ! 3
3562  no, no, no, no, no, no, & ! 4
3563  no, no, no, no, no, no, & ! 5
3564  no, no, no,yes, no, no, & ! 6
3565  no, no, no, no, no, no, & ! 7
3566  no, no, no, no, no, no, & ! 8
3567  no, no, no, no, no, no, & ! 9
3568  no, no, no, no, no, no, & ! 10
3569  no, no, no, no, no, no, & ! 11
3570  no, no, no, no, no, no ], & ! 12
3571  ! -------------------------
3572  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3573  [max_nalleles,n_chromosomes],[no],[2,1] )
3574  ! Note: additional reshape params: array shape |pad | order
3575  ! |with| by rows
3576  ! ............................................................................
3577 
3578  !> Gaussian perception error parameter (cv) for **direct predation**
3579  !! perception effects on **hunger**.
3580  real(srp), parameter, public :: &
3582 
3583  !-----------------------------------------------------------------------------
3584  !> The genotype structure for **mean predator number** perception effects on
3585  !! **hunger** that goes via gamma2gene perception to neuronal response.
3586  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3588  ! ............................................................................
3589  [ & ! 1 2 3 4 5 6
3590  !------------------------
3591  no, no, no, no, no, no, & ! 1
3592  no, no, no, no, no, no, & ! 2
3593  no, no, no, no, no, no, & ! 3
3594  no, no, no, no, no, no, & ! 4
3595  no, no, no, no, no, no, & ! 5
3596  no, no, no, no, no, no, & ! 6
3597  no, no, no,yes, no, no, & ! 7
3598  no, no, no, no, no, no, & ! 8
3599  no, no, no, no, no, no, & ! 9
3600  no, no, no, no, no, no, & ! 10
3601  no, no, no, no, no, no, & ! 11
3602  no, no, no, no, no, no ], & ! 12
3603  ! -------------------------
3604  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3605  [max_nalleles,n_chromosomes],[no],[2,1] )
3606  ! Note: additional reshape params: array shape |pad | order
3607  ! |with| by rows
3608  ! ............................................................................
3609 
3610  !> Gaussian perception error parameter (cv) for **mean predator number**
3611  !! perception effects on **hunger**.
3612  real(srp), parameter, public :: &
3614 
3615  !> The weight of the immediately seen predators over those in the perceptual
3616  !! memory stack. Those in the memory then have this weight in the predation
3617  !! risk estimate: `1-PREDATION_RISK_WEIGHT_IMMEDIATE`.
3618  !! See the_neurobio::predation_risk_backend().
3619  !! @note Note that this parameter also works in appraisal functions for the
3620  !! fear state neuronal respones components.
3621  real(srp), parameter, public :: predation_risk_weight_immediate = 0.7
3622 
3623  !> The length of the perceptual memory window that is taken into account and
3624  !! weighted against the currently seen number of predators when calculating
3625  !! the motivation value.
3626  !! @note Note that the total memory window is `HISTORY_SIZE_PERCEPTION`.
3627  integer, parameter, public :: predation_risk_weight_memory_window = &
3628  nint(history_size_perception / 2.0) !! Here set to 1/2 of total.
3629 
3630  !-----------------------------------------------------------------------------
3631  !> The genotype structure for **stomach** perception effects on **hunger**
3632  !! that goes via gamma2gene perception to neuronal response.
3633  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3634  :: stom_hunger_genotype_neuronal = reshape ( &
3635  ! ............................................................................
3636  [ & ! 1 2 3 4 5 6
3637  !------------------------
3638  no, no, no, no, no, no, & ! 1
3639  no, no, no, no, no, no, & ! 2
3640  no, no, no, no, no, no, & ! 3
3641  no, no, no, no, no, no, & ! 4
3642  no, no, no, no, no, no, & ! 5
3643  no, no, no, no, no, no, & ! 6
3644  no, no, no, no, no, no, & ! 7
3645  no, no, no,yes, no, no, & ! 8
3646  no, no, no, no, no, no, & ! 9
3647  no, no, no, no, no, no, & ! 10
3648  no, no, no, no, no, no, & ! 11
3649  no, no, no, no, no, no ], & ! 12
3650  ! -------------------------
3651  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3652  [max_nalleles,n_chromosomes],[no],[2,1] )
3653  ! Note: additional reshape params: array shape |pad | order
3654  ! |with| by rows
3655  ! ............................................................................
3656 
3657  !> Gaussian perception error parameter (cv) for **stomach** perception
3658  !! effects on **hunger**.
3659  real(srp), parameter, public :: &
3661 
3662  !-----------------------------------------------------------------------------
3663  !> The genotype structure for **body mass** perception effects on **hunger**
3664  !! that goes via gamma2gene perception to neuronal response.
3665  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3666  :: bodymass_hunger_genotype_neuronal = reshape ( &
3667  ! ............................................................................
3668  [ & ! 1 2 3 4 5 6
3669  !------------------------
3670  no, no, no, no, no, no, & ! 1
3671  no, no, no, no, no, no, & ! 2
3672  no, no, no, no, no, no, & ! 3
3673  no, no, no, no, no, no, & ! 4
3674  no, no, no, no, no, no, & ! 5
3675  no, no, no, no, no, no, & ! 6
3676  no, no, no, no, no, no, & ! 7
3677  no, no, no, no, no, no, & ! 8
3678  no, no, no,yes, no, no, & ! 9
3679  no, no, no, no, no, no, & ! 10
3680  no, no, no, no, no, no, & ! 11
3681  no, no, no, no, no, no ], & ! 12
3682  ! -------------------------
3683  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3684  [max_nalleles,n_chromosomes],[no],[2,1] )
3685  ! Note: additional reshape params: array shape |pad | order
3686  ! |with| by rows
3687  ! ............................................................................
3688 
3689  !> Gaussian perception error parameter (cv) for **body mass** perception
3690  !! effects on **hunger**.
3691  real(srp), parameter, public :: &
3693 
3694  !-----------------------------------------------------------------------------
3695  !> The genotype structure for **energy reserves** perception effects on
3696  !! **hunger** that goes via gamma2gene perception to neuronal response.
3697  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3698  :: energy_hunger_genotype_neuronal = reshape ( &
3699  ! ............................................................................
3700  [ & ! 1 2 3 4 5 6
3701  !------------------------
3702  no, no, no, no, no, no, & ! 1
3703  no, no, no, no, no, no, & ! 2
3704  no, no, no, no, no, no, & ! 3
3705  no, no, no, no, no, no, & ! 4
3706  no, no, no, no, no, no, & ! 5
3707  no, no, no, no, no, no, & ! 6
3708  no, no, no, no, no, no, & ! 7
3709  no, no, no, no, no, no, & ! 8
3710  no, no, no, no, no, no, & ! 9
3711  no, no, no,yes, no, no, & ! 10
3712  no, no, no, no, no, no, & ! 11
3713  no, no, no, no, no, no ], & ! 12
3714  ! -------------------------
3715  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3716  [max_nalleles,n_chromosomes],[no],[2,1] )
3717  ! Note: additional reshape params: array shape |pad | order
3718  ! |with| by rows
3719  ! ............................................................................
3720 
3721  !> Gaussian perception error parameter (cv) for **energy reserves** perception
3722  !! effects on **hunger**.
3723  real(srp), parameter, public :: &
3725 
3726  !-----------------------------------------------------------------------------
3727  !> The genotype structure for **age** perception effects on
3728  !! **hunger** that goes via gamma2gene perception to neuronal response.
3729  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3730  :: age_hunger_genotype_neuronal = reshape ( &
3731  ! ............................................................................
3732  [ & ! 1 2 3 4 5 6
3733  !------------------------
3734  no, no, no, no, no, no, & ! 1
3735  no, no, no, no, no, no, & ! 2
3736  no, no, no, no, no, no, & ! 3
3737  no, no, no, no, no, no, & ! 4
3738  no, no, no, no, no, no, & ! 5
3739  no, no, no, no, no, no, & ! 6
3740  no, no, no, no, no, no, & ! 7
3741  no, no, no, no, no, no, & ! 8
3742  no, no, no, no, no, no, & ! 9
3743  no, no, no, no, no, no, & ! 10
3744  no, no, no,yes, no, no, & ! 11
3745  no, no, no, no, no, no ], & ! 12
3746  ! -------------------------
3747  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3748  [max_nalleles,n_chromosomes],[no],[2,1] )
3749  ! Note: additional reshape params: array shape |pad | order
3750  ! |with| by rows
3751  ! ............................................................................
3752 
3753  !> Gaussian perception error parameter (cv) for **age** perception
3754  !! effects on **hunger**.
3755  real(srp), parameter, public :: &
3757 
3758  !-----------------------------------------------------------------------------
3759  !> The genotype structure for **reproductive factor** perception effects on
3760  !! **hunger** that goes via gamma2gene perception to neuronal response.
3761  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3762  :: reprfac_hunger_genotype_neuronal = reshape ( &
3763  ! ............................................................................
3764  [ & ! 1 2 3 4 5 6
3765  !------------------------
3766  no, no, no, no, no, no, & ! 1
3767  no, no, no, no, no, no, & ! 2
3768  no, no, no, no, no, no, & ! 3
3769  no, no, no, no, no, no, & ! 4
3770  no, no, no, no, no, no, & ! 5
3771  no, no, no, no, no, no, & ! 6
3772  no, no, no, no, no, no, & ! 7
3773  no, no, no, no, no, no, & ! 8
3774  no, no, no, no, no, no, & ! 9
3775  no, no, no, no, no, no, & ! 10
3776  no, no, no, no, no, no, & ! 11
3777  no, no, no,yes, no, no ], & ! 12
3778  ! -------------------------
3779  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3780  [max_nalleles,n_chromosomes],[no],[2,1] )
3781  ! Note: additional reshape params: array shape |pad | order
3782  ! |with| by rows
3783  ! ............................................................................
3784 
3785  !> Gaussian perception error parameter (cv) for **reproductive factor**
3786  !! perception effects on **hunger**.
3787  real(srp), parameter, public :: &
3789 
3790  !.............................................................................
3791  ! ### Parameters for the FEAR motivational state ###
3792 
3793  !-----------------------------------------------------------------------------
3794  !> The genotype structure for **light** perception effects on
3795  !! **fear state** that goes via gamma2gene perception to neuronal
3796  !! response.
3797  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3798  :: light_actv_avoid_genotype_neuronal = reshape ( &
3799  ! ............................................................................
3800  [ & ! 1 2 3 4 5 6
3801  !------------------------
3802  no, no, no, no,yes, no, & ! 1
3803  no, no, no, no, no, no, & ! 2
3804  no, no, no, no, no, no, & ! 3
3805  no, no, no, no, no, no, & ! 4
3806  no, no, no, no, no, no, & ! 5
3807  no, no, no, no, no, no, & ! 6
3808  no, no, no, no, no, no, & ! 7
3809  no, no, no, no, no, no, & ! 8
3810  no, no, no, no, no, no, & ! 9
3811  no, no, no, no, no, no, & ! 10
3812  no, no, no, no, no, no, & ! 11
3813  no, no, no, no, no, no ], & ! 12
3814  ! -------------------------
3815  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3816  [max_nalleles,n_chromosomes],[no],[2,1] )
3817  ! Note: additional reshape params: array shape |pad | order
3818  ! |with| by rows
3819  ! ............................................................................
3820 
3821  !> Gaussian perception error parameter (cv) for **light** perception
3822  !! effects on **fear state**.
3823  real(srp), parameter, public :: &
3825 
3826  !-----------------------------------------------------------------------------
3827  !> The genotype structure for **depth** perception effects on **active
3828  !! avoidance** that goes via gamma2gene perception to neuronal response.
3829  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3830  :: depth_actv_avoid_genotype_neuronal = reshape ( &
3831  ! ............................................................................
3832  [ & ! 1 2 3 4 5 6
3833  !------------------------
3834  no, no, no, no, no, no, & ! 1
3835  no, no, no, no,yes, no, & ! 2
3836  no, no, no, no, no, no, & ! 3
3837  no, no, no, no, no, no, & ! 4
3838  no, no, no, no, no, no, & ! 5
3839  no, no, no, no, no, no, & ! 6
3840  no, no, no, no, no, no, & ! 7
3841  no, no, no, no, no, no, & ! 8
3842  no, no, no, no, no, no, & ! 9
3843  no, no, no, no, no, no, & ! 10
3844  no, no, no, no, no, no, & ! 11
3845  no, no, no, no, no, no ], & ! 12
3846  ! -------------------------
3847  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3848  [max_nalleles,n_chromosomes],[no],[2,1] )
3849  ! Note: additional reshape params: array shape |pad | order
3850  ! |with| by rows
3851  ! ............................................................................
3852 
3853  !> Gaussian perception error parameter (cv) for **depth** perception
3854  !! effects on **fear state**.
3855  real(srp), parameter, public :: &
3857 
3858  !-----------------------------------------------------------------------------
3859  !> The genotype structure for **food items count** perception effects on
3860  !! **fear state** that goes via gamma2gene perception to neuronal
3861  !! response.
3862  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3864  ! ............................................................................
3865  [ & ! 1 2 3 4 5 6
3866  !------------------------
3867  no, no, no, no, no, no, & ! 1
3868  no, no, no, no, no, no, & ! 2
3869  no, no, no, no,yes, no, & ! 3
3870  no, no, no, no, no, no, & ! 4
3871  no, no, no, no, no, no, & ! 5
3872  no, no, no, no, no, no, & ! 6
3873  no, no, no, no, no, no, & ! 7
3874  no, no, no, no, no, no, & ! 8
3875  no, no, no, no, no, no, & ! 9
3876  no, no, no, no, no, no, & ! 10
3877  no, no, no, no, no, no, & ! 11
3878  no, no, no, no, no, no ], & ! 12
3879  ! -------------------------
3880  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3881  [max_nalleles,n_chromosomes],[no],[2,1] )
3882  ! Note: additional reshape params: array shape |pad | order
3883  ! |with| by rows
3884  ! ............................................................................
3885 
3886  !> Gaussian perception error parameter (cv) for **food items count**
3887  !! perception effects on **fear state**.
3888  real(srp), parameter, public :: &
3890 
3891  !-----------------------------------------------------------------------------
3892  !> The genotype structure for **food items count** perception effects on
3893  !! **fear state** that goes via gamma2gene perception to neuronal
3894  !! response.
3895  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3896  :: food_mem_actv_avoid_genotype_neuronal = reshape ( &
3897  ! ............................................................................
3898  [ & ! 1 2 3 4 5 6
3899  !------------------------
3900  no, no, no, no, no, no, & ! 1
3901  no, no, no, no, no, no, & ! 2
3902  no, no, no, no, no, no, & ! 3
3903  no, no, no, no,yes, no, & ! 4
3904  no, no, no, no, no, no, & ! 5
3905  no, no, no, no, no, no, & ! 6
3906  no, no, no, no, no, no, & ! 7
3907  no, no, no, no, no, no, & ! 8
3908  no, no, no, no, no, no, & ! 9
3909  no, no, no, no, no, no, & ! 10
3910  no, no, no, no, no, no, & ! 11
3911  no, no, no, no, no, no ], & ! 12
3912  ! -------------------------
3913  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3914  [max_nalleles,n_chromosomes],[no],[2,1] )
3915  ! Note: additional reshape params: array shape |pad | order
3916  ! |with| by rows
3917  ! ............................................................................
3918 
3919  !> Gaussian perception error parameter (cv) for **food items count**
3920  !! perception effects on **fear state**.
3921  real(srp), parameter, public :: &
3923 
3924  !-----------------------------------------------------------------------------
3925  !> The genotype structure for **conspecifics number** perception effects on
3926  !! **fear state** that goes via gamma2gene perception to neuronal
3927  !! response.
3928  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3930  ! ............................................................................
3931  [ & ! 1 2 3 4 5 6
3932  !------------------------
3933  no, no, no, no, no, no, & ! 1
3934  no, no, no, no, no, no, & ! 2
3935  no, no, no, no, no, no, & ! 3
3936  no, no, no, no, no, no, & ! 4
3937  no, no, no, no,yes, no, & ! 5
3938  no, no, no, no, no, no, & ! 6
3939  no, no, no, no, no, no, & ! 7
3940  no, no, no, no, no, no, & ! 8
3941  no, no, no, no, no, no, & ! 9
3942  no, no, no, no, no, no, & ! 10
3943  no, no, no, no, no, no, & ! 11
3944  no, no, no, no, no, no ], & ! 12
3945  ! -------------------------
3946  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3947  [max_nalleles,n_chromosomes],[no],[2,1] )
3948  ! Note: additional reshape params: array shape |pad | order
3949  ! |with| by rows
3950  ! ............................................................................
3951 
3952  !> Gaussian perception error parameter (cv) for **conspecifics number count**
3953  !! perception effects on **fear state**.
3954  real(srp), parameter, public :: &
3956 
3957  !-----------------------------------------------------------------------------
3958  !> The genotype structure for **direct predation** perception effects on
3959  !! **fear state** that goes via gamma2gene perception to neuronal
3960  !! response.
3961  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3963  ! ............................................................................
3964  [ & ! 1 2 3 4 5 6
3965  !------------------------
3966  no, no, no, no, no, no, & ! 1
3967  no, no, no, no, no, no, & ! 2
3968  no, no, no, no, no, no, & ! 3
3969  no, no, no, no, no, no, & ! 4
3970  no, no, no, no, no, no, & ! 5
3971  no, no, no, no,yes, no, & ! 6
3972  no, no, no, no, no, no, & ! 7
3973  no, no, no, no, no, no, & ! 8
3974  no, no, no, no, no, no, & ! 9
3975  no, no, no, no, no, no, & ! 10
3976  no, no, no, no, no, no, & ! 11
3977  no, no, no, no, no, no ], & ! 12
3978  ! -------------------------
3979  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
3980  [max_nalleles,n_chromosomes],[no],[2,1] )
3981  ! Note: additional reshape params: array shape |pad | order
3982  ! |with| by rows
3983  ! ............................................................................
3984 
3985  !> Gaussian perception error parameter (cv) for **direct predation**
3986  !! perception effects on **fear state**.
3987  real(srp), parameter, public :: &
3989 
3990  !-----------------------------------------------------------------------------
3991  !> The genotype structure for **mean predator number** perception effects on
3992  !! **fear state** that goes via gamma2gene perception to neuronal
3993  !! response.
3994  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
3996  ! ............................................................................
3997  [ & ! 1 2 3 4 5 6
3998  !------------------------
3999  no, no, no, no, no, no, & ! 1
4000  no, no, no, no, no, no, & ! 2
4001  no, no, no, no, no, no, & ! 3
4002  no, no, no, no, no, no, & ! 4
4003  no, no, no, no, no, no, & ! 5
4004  no, no, no, no, no, no, & ! 6
4005  no, no, no, no,yes, no, & ! 7
4006  no, no, no, no, no, no, & ! 8
4007  no, no, no, no, no, no, & ! 9
4008  no, no, no, no, no, no, & ! 10
4009  no, no, no, no, no, no, & ! 11
4010  no, no, no, no, no, no ], & ! 12
4011  ! -------------------------
4012  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4013  [max_nalleles,n_chromosomes],[no],[2,1] )
4014  ! Note: additional reshape params: array shape |pad | order
4015  ! |with| by rows
4016  ! ............................................................................
4017 
4018  !> Gaussian perception error parameter (cv) for **mean predator number**
4019  !! perception effects on **fear state**.
4020  real(srp), parameter, public :: &
4022 
4023  !-----------------------------------------------------------------------------
4024  !> The genotype structure for **stomach** perception effects on **active
4025  !! avoidance** that goes via gamma2gene perception to neuronal response.
4026  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4027  :: stom_actv_avoid_genotype_neuronal = reshape ( &
4028  ! ............................................................................
4029  [ & ! 1 2 3 4 5 6
4030  !------------------------
4031  no, no, no, no, no, no, & ! 1
4032  no, no, no, no, no, no, & ! 2
4033  no, no, no, no, no, no, & ! 3
4034  no, no, no, no, no, no, & ! 4
4035  no, no, no, no, no, no, & ! 5
4036  no, no, no, no, no, no, & ! 6
4037  no, no, no, no, no, no, & ! 7
4038  no, no, no, no,yes, no, & ! 8
4039  no, no, no, no, no, no, & ! 9
4040  no, no, no, no, no, no, & ! 10
4041  no, no, no, no, no, no, & ! 11
4042  no, no, no, no, no, no ], & ! 12
4043  ! -------------------------
4044  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4045  [max_nalleles,n_chromosomes],[no],[2,1] )
4046  ! Note: additional reshape params: array shape |pad | order
4047  ! |with| by rows
4048  ! ............................................................................
4049 
4050  !> Gaussian perception error parameter (cv) for **stomach** perception
4051  !! effects on **fear state**.
4052  real(srp), parameter, public :: &
4054 
4055  !-----------------------------------------------------------------------------
4056  !> The genotype structure for **body mass** perception effects on **active
4057  !! avoidance** that goes via gamma2gene perception to neuronal response.
4058  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4059  :: bodymass_actv_avoid_genotype_neuronal = reshape ( &
4060  ! ............................................................................
4061  [ & ! 1 2 3 4 5 6
4062  !------------------------
4063  no, no, no, no, no, no, & ! 1
4064  no, no, no, no, no, no, & ! 2
4065  no, no, no, no, no, no, & ! 3
4066  no, no, no, no, no, no, & ! 4
4067  no, no, no, no, no, no, & ! 5
4068  no, no, no, no, no, no, & ! 6
4069  no, no, no, no, no, no, & ! 7
4070  no, no, no, no, no, no, & ! 8
4071  no, no, no, no,yes, no, & ! 9
4072  no, no, no, no, no, no, & ! 10
4073  no, no, no, no, no, no, & ! 11
4074  no, no, no, no, no, no ], & ! 12
4075  ! -------------------------
4076  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4077  [max_nalleles,n_chromosomes],[no],[2,1] )
4078  ! Note: additional reshape params: array shape |pad | order
4079  ! |with| by rows
4080  ! ............................................................................
4081 
4082  !> Gaussian perception error parameter (cv) for **body mass** perception
4083  !! effects on **fear state**.
4084  real(srp), parameter, public :: &
4086 
4087  !-----------------------------------------------------------------------------
4088  !> The genotype structure for **energy reserves** perception effects on
4089  !! **fear state** that goes via gamma2gene perception to neuronal
4090  !! response.
4091  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4092  :: energy_actv_avoid_genotype_neuronal = reshape ( &
4093  ! ............................................................................
4094  [ & ! 1 2 3 4 5 6
4095  !------------------------
4096  no, no, no, no, no, no, & ! 1
4097  no, no, no, no, no, no, & ! 2
4098  no, no, no, no, no, no, & ! 3
4099  no, no, no, no, no, no, & ! 4
4100  no, no, no, no, no, no, & ! 5
4101  no, no, no, no, no, no, & ! 6
4102  no, no, no, no, no, no, & ! 7
4103  no, no, no, no, no, no, & ! 8
4104  no, no, no, no, no, no, & ! 9
4105  no, no, no, no,yes, no, & ! 10
4106  no, no, no, no, no, no, & ! 11
4107  no, no, no, no, no, no ], & ! 12
4108  ! -------------------------
4109  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4110  [max_nalleles,n_chromosomes],[no],[2,1] )
4111  ! Note: additional reshape params: array shape |pad | order
4112  ! |with| by rows
4113  ! ............................................................................
4114 
4115  !> Gaussian perception error parameter (cv) for **energy reserves** perception
4116  !! effects on **fear state**.
4117  real(srp), parameter, public :: &
4119 
4120  !-----------------------------------------------------------------------------
4121  !> The genotype structure for **age** perception effects on
4122  !! **fear state** that goes via gamma2gene perception to neuronal
4123  !! response.
4124  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4125  :: age_actv_avoid_genotype_neuronal = reshape ( &
4126  ! ............................................................................
4127  [ & ! 1 2 3 4 5 6
4128  !------------------------
4129  no, no, no, no, no, no, & ! 1
4130  no, no, no, no, no, no, & ! 2
4131  no, no, no, no, no, no, & ! 3
4132  no, no, no, no, no, no, & ! 4
4133  no, no, no, no, no, no, & ! 5
4134  no, no, no, no, no, no, & ! 6
4135  no, no, no, no, no, no, & ! 7
4136  no, no, no, no, no, no, & ! 8
4137  no, no, no, no, no, no, & ! 9
4138  no, no, no, no, no, no, & ! 10
4139  no, no, no, no,yes, no, & ! 11
4140  no, no, no, no, no, no ], & ! 12
4141  ! -------------------------
4142  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4143  [max_nalleles,n_chromosomes],[no],[2,1] )
4144  ! Note: additional reshape params: array shape |pad | order
4145  ! |with| by rows
4146  ! ............................................................................
4147 
4148  !> Gaussian perception error parameter (cv) for **age** perception
4149  !! effects on **fear state**.
4150  real(srp), parameter, public :: &
4152 
4153  !-----------------------------------------------------------------------------
4154  !> The genotype structure for **reproductive factor** perception effects on
4155  !! **fear state** that goes via gamma2gene perception to neuronal
4156  !! response.
4157  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4158  :: reprfac_actv_avoid_genotype_neuronal = reshape ( &
4159  ! ............................................................................
4160  [ & ! 1 2 3 4 5 6
4161  !------------------------
4162  no, no, no, no, no, no, & ! 1
4163  no, no, no, no, no, no, & ! 2
4164  no, no, no, no, no, no, & ! 3
4165  no, no, no, no, no, no, & ! 4
4166  no, no, no, no, no, no, & ! 5
4167  no, no, no, no, no, no, & ! 6
4168  no, no, no, no, no, no, & ! 7
4169  no, no, no, no, no, no, & ! 8
4170  no, no, no, no, no, no, & ! 9
4171  no, no, no, no, no, no, & ! 10
4172  no, no, no, no, no, no, & ! 11
4173  no, no, no, no,yes, no ], & ! 12
4174  ! -------------------------
4175  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4176  [max_nalleles,n_chromosomes],[no],[2,1] )
4177  ! Note: additional reshape params: array shape |pad | order
4178  ! |with| by rows
4179  ! ............................................................................
4180 
4181  !> Gaussian perception error parameter (cv) for **reproductive factor**
4182  !! perception effects on **fear state**.
4183  real(srp), parameter, public :: &
4185 
4186  !.............................................................................
4187  ! ### Parameters for the REPRODUCTION motivational state ###
4188 
4189  !-----------------------------------------------------------------------------
4190  !> The genotype structure for **light** perception effects on
4191  !! **reproduction** that goes via gamma2gene perception to neuronal
4192  !! response.
4193  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4194  :: light_reproduce_genotype_neuronal = reshape ( &
4195  ! ............................................................................
4196  [ & ! 1 2 3 4 5 6
4197  !------------------------
4198  no, no, no, no, no,yes, & ! 1
4199  no, no, no, no, no, no, & ! 2
4200  no, no, no, no, no, no, & ! 3
4201  no, no, no, no, no, no, & ! 4
4202  no, no, no, no, no, no, & ! 5
4203  no, no, no, no, no, no, & ! 6
4204  no, no, no, no, no, no, & ! 7
4205  no, no, no, no, no, no, & ! 8
4206  no, no, no, no, no, no, & ! 9
4207  no, no, no, no, no, no, & ! 10
4208  no, no, no, no, no, no, & ! 11
4209  no, no, no, no, no, no ], & ! 12
4210  ! -------------------------
4211  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4212  [max_nalleles,n_chromosomes],[no],[2,1] )
4213  ! Note: additional reshape params: array shape |pad | order
4214  ! |with| by rows
4215  ! ............................................................................
4216 
4217  !> Gaussian perception error parameter (cv) for **light** perception
4218  !! effects on **reproduction**.
4219  real(srp), parameter, public :: &
4221 
4222  !-----------------------------------------------------------------------------
4223  !> The genotype structure for **depth** perception effects on **reproduction**
4224  !! that goes via gamma2gene perception to neuronal response.
4225  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4226  :: depth_reproduce_genotype_neuronal = reshape ( &
4227  ! ............................................................................
4228  [ & ! 1 2 3 4 5 6
4229  !------------------------
4230  no, no, no, no, no, no, & ! 1
4231  no, no, no, no, no,yes, & ! 2
4232  no, no, no, no, no, no, & ! 3
4233  no, no, no, no, no, no, & ! 4
4234  no, no, no, no, no, no, & ! 5
4235  no, no, no, no, no, no, & ! 6
4236  no, no, no, no, no, no, & ! 7
4237  no, no, no, no, no, no, & ! 8
4238  no, no, no, no, no, no, & ! 9
4239  no, no, no, no, no, no, & ! 10
4240  no, no, no, no, no, no, & ! 11
4241  no, no, no, no, no, no ], & ! 12
4242  ! -------------------------
4243  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4244  [max_nalleles,n_chromosomes],[no],[2,1] )
4245  ! Note: additional reshape params: array shape |pad | order
4246  ! |with| by rows
4247  ! ............................................................................
4248 
4249  !> Gaussian perception error parameter (cv) for **depth** perception
4250  !! effects on **reproduction**.
4251  real(srp), parameter, public :: &
4253 
4254  !-----------------------------------------------------------------------------
4255  !> The genotype structure for **food items count** perception effects on
4256  !! **reproduction** that goes via gamma2gene perception to neuronal
4257  !! response.
4258  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4259  :: foodcount_reproduce_genotype_neuronal = reshape ( &
4260  ! ............................................................................
4261  [ & ! 1 2 3 4 5 6
4262  !------------------------
4263  no, no, no, no, no, no, & ! 1
4264  no, no, no, no, no, no, & ! 2
4265  no, no, no, no, no,yes, & ! 3
4266  no, no, no, no, no, no, & ! 4
4267  no, no, no, no, no, no, & ! 5
4268  no, no, no, no, no, no, & ! 6
4269  no, no, no, no, no, no, & ! 7
4270  no, no, no, no, no, no, & ! 8
4271  no, no, no, no, no, no, & ! 9
4272  no, no, no, no, no, no, & ! 10
4273  no, no, no, no, no, no, & ! 11
4274  no, no, no, no, no, no ], & ! 12
4275  ! -------------------------
4276  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4277  [max_nalleles,n_chromosomes],[no],[2,1] )
4278  ! Note: additional reshape params: array shape |pad | order
4279  ! |with| by rows
4280  ! ............................................................................
4281 
4282  !> Gaussian perception error parameter (cv) for **food items count**
4283  !! perception effects on **reproduction**.
4284  real(srp), parameter, public :: &
4286 
4287  !-----------------------------------------------------------------------------
4288  !> The genotype structure for **food items count** perception effects on
4289  !! **reproduction** that goes via gamma2gene perception to neuronal
4290  !! response.
4291  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4292  :: food_mem_reproduce_genotype_neuronal = reshape ( &
4293  ! ............................................................................
4294  [ & ! 1 2 3 4 5 6
4295  !------------------------
4296  no, no, no, no, no, no, & ! 1
4297  no, no, no, no, no, no, & ! 2
4298  no, no, no, no, no, no, & ! 3
4299  no, no, no, no, no,yes, & ! 4
4300  no, no, no, no, no, no, & ! 5
4301  no, no, no, no, no, no, & ! 6
4302  no, no, no, no, no, no, & ! 7
4303  no, no, no, no, no, no, & ! 8
4304  no, no, no, no, no, no, & ! 9
4305  no, no, no, no, no, no, & ! 10
4306  no, no, no, no, no, no, & ! 11
4307  no, no, no, no, no, no ], & ! 12
4308  ! -------------------------
4309  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4310  [max_nalleles,n_chromosomes],[no],[2,1] )
4311  ! Note: additional reshape params: array shape |pad | order
4312  ! |with| by rows
4313  ! ............................................................................
4314 
4315  !> Gaussian perception error parameter (cv) for **food items count**
4316  !! perception effects on **reproduction**.
4317  real(srp), parameter, public :: &
4319 
4320  !-----------------------------------------------------------------------------
4321  !> The genotype structure for **conspecifics number** perception effects on
4322  !! **reproduction** that goes via gamma2gene perception to neuronal
4323  !! response.
4324  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4326  ! ............................................................................
4327  [ & ! 1 2 3 4 5 6
4328  !------------------------
4329  no, no, no, no, no, no, & ! 1
4330  no, no, no, no, no, no, & ! 2
4331  no, no, no, no, no, no, & ! 3
4332  no, no, no, no, no, no, & ! 4
4333  no, no, no, no, no,yes, & ! 5
4334  no, no, no, no, no, no, & ! 6
4335  no, no, no, no, no, no, & ! 7
4336  no, no, no, no, no, no, & ! 8
4337  no, no, no, no, no, no, & ! 9
4338  no, no, no, no, no, no, & ! 10
4339  no, no, no, no, no, no, & ! 11
4340  no, no, no, no, no, no ], & ! 12
4341  ! -------------------------
4342  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4343  [max_nalleles,n_chromosomes],[no],[2,1] )
4344  ! Note: additional reshape params: array shape |pad | order
4345  ! |with| by rows
4346  ! ............................................................................
4347 
4348  !> Gaussian perception error parameter (cv) for **conspecifics number count**
4349  !! perception effects on **reproduction**.
4350  real(srp), parameter, public :: &
4352 
4353  !-----------------------------------------------------------------------------
4354  !> The genotype structure for **direct predation** perception effects on
4355  !! **reproduction** that goes via gamma2gene perception to neuronal
4356  !! response.
4357  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4359  ! ............................................................................
4360  [ & ! 1 2 3 4 5 6
4361  !------------------------
4362  no, no, no, no, no, no, & ! 1
4363  no, no, no, no, no, no, & ! 2
4364  no, no, no, no, no, no, & ! 3
4365  no, no, no, no, no, no, & ! 4
4366  no, no, no, no, no, no, & ! 5
4367  no, no, no, no, no,yes, & ! 6
4368  no, no, no, no, no, no, & ! 7
4369  no, no, no, no, no, no, & ! 8
4370  no, no, no, no, no, no, & ! 9
4371  no, no, no, no, no, no, & ! 10
4372  no, no, no, no, no, no, & ! 11
4373  no, no, no, no, no, no ], & ! 12
4374  ! -------------------------
4375  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4376  [max_nalleles,n_chromosomes],[no],[2,1] )
4377  ! Note: additional reshape params: array shape |pad | order
4378  ! |with| by rows
4379  ! ............................................................................
4380 
4381  !> Gaussian perception error parameter (cv) for **direct predation**
4382  !! perception effects on **reproduction**.
4383  real(srp), parameter, public :: &
4385 
4386  !-----------------------------------------------------------------------------
4387  !> The genotype structure for **mean predator number** perception effects on
4388  !! **reproduction** that goes via gamma2gene perception to neuronal
4389  !! response.
4390  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4392  ! ............................................................................
4393  [ & ! 1 2 3 4 5 6
4394  !------------------------
4395  no, no, no, no, no, no, & ! 1
4396  no, no, no, no, no, no, & ! 2
4397  no, no, no, no, no, no, & ! 3
4398  no, no, no, no, no, no, & ! 4
4399  no, no, no, no, no, no, & ! 5
4400  no, no, no, no, no, no, & ! 6
4401  no, no, no, no, no,yes, & ! 7
4402  no, no, no, no, no, no, & ! 8
4403  no, no, no, no, no, no, & ! 9
4404  no, no, no, no, no, no, & ! 10
4405  no, no, no, no, no, no, & ! 11
4406  no, no, no, no, no, no ], & ! 12
4407  ! -------------------------
4408  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4409  [max_nalleles,n_chromosomes],[no],[2,1] )
4410  ! Note: additional reshape params: array shape |pad | order
4411  ! |with| by rows
4412  ! ............................................................................
4413 
4414  !> Gaussian perception error parameter (cv) for **mean predator number**
4415  !! perception effects on **reproduction**.
4416  real(srp), parameter, public :: &
4418 
4419  !-----------------------------------------------------------------------------
4420  !> The genotype structure for **stomach** perception effects on
4421  !! **reproduction** that goes via gamma2gene perception to neuronal response.
4422  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4423  :: stom_reproduce_genotype_neuronal = reshape ( &
4424  ! ............................................................................
4425  [ & ! 1 2 3 4 5 6
4426  !------------------------
4427  no, no, no, no, no, no, & ! 1
4428  no, no, no, no, no, no, & ! 2
4429  no, no, no, no, no, no, & ! 3
4430  no, no, no, no, no, no, & ! 4
4431  no, no, no, no, no, no, & ! 5
4432  no, no, no, no, no, no, & ! 6
4433  no, no, no, no, no, no, & ! 7
4434  no, no, no, no, no,yes, & ! 8
4435  no, no, no, no, no, no, & ! 9
4436  no, no, no, no, no, no, & ! 10
4437  no, no, no, no, no, no, & ! 11
4438  no, no, no, no, no, no ], & ! 12
4439  ! -------------------------
4440  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4441  [max_nalleles,n_chromosomes],[no],[2,1] )
4442  ! Note: additional reshape params: array shape |pad | order
4443  ! |with| by rows
4444  ! ............................................................................
4445 
4446  !> Gaussian perception error parameter (cv) for **stomach** perception
4447  !! effects on **reproduction**.
4448  real(srp), parameter, public :: &
4450 
4451  !-----------------------------------------------------------------------------
4452  !> The genotype structure for **body mass** perception effects on
4453  !! **reproduction** that goes via gamma2gene perception to neuronal response.
4454  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4455  :: bodymass_reproduce_genotype_neuronal = reshape ( &
4456  ! ............................................................................
4457  [ & ! 1 2 3 4 5 6
4458  !------------------------
4459  no, no, no, no, no, no, & ! 1
4460  no, no, no, no, no, no, & ! 2
4461  no, no, no, no, no, no, & ! 3
4462  no, no, no, no, no, no, & ! 4
4463  no, no, no, no, no, no, & ! 5
4464  no, no, no, no, no, no, & ! 6
4465  no, no, no, no, no, no, & ! 7
4466  no, no, no, no, no, no, & ! 8
4467  no, no, no, no, no,yes, & ! 9
4468  no, no, no, no, no, no, & ! 10
4469  no, no, no, no, no, no, & ! 11
4470  no, no, no, no, no, no ], & ! 12
4471  ! -------------------------
4472  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4473  [max_nalleles,n_chromosomes],[no],[2,1] )
4474  ! Note: additional reshape params: array shape |pad | order
4475  ! |with| by rows
4476  ! ............................................................................
4477 
4478  !> Gaussian perception error parameter (cv) for **body mass** perception
4479  !! effects on **reproduction**.
4480  real(srp), parameter, public :: &
4482 
4483  !-----------------------------------------------------------------------------
4484  !> The genotype structure for **energy reserves** perception effects on
4485  !! **reproduction** that goes via gamma2gene perception to neuronal
4486  !! response.
4487  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4488  :: energy_reproduce_genotype_neuronal = reshape ( &
4489  ! ............................................................................
4490  [ & ! 1 2 3 4 5 6
4491  !------------------------
4492  no, no, no, no, no, no, & ! 1
4493  no, no, no, no, no, no, & ! 2
4494  no, no, no, no, no, no, & ! 3
4495  no, no, no, no, no, no, & ! 4
4496  no, no, no, no, no, no, & ! 5
4497  no, no, no, no, no, no, & ! 6
4498  no, no, no, no, no, no, & ! 7
4499  no, no, no, no, no, no, & ! 8
4500  no, no, no, no, no, no, & ! 9
4501  no, no, no, no, no,yes, & ! 10
4502  no, no, no, no, no, no, & ! 11
4503  no, no, no, no, no, no ], & ! 12
4504  ! -------------------------
4505  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4506  [max_nalleles,n_chromosomes],[no],[2,1] )
4507  ! Note: additional reshape params: array shape |pad | order
4508  ! |with| by rows
4509  ! ............................................................................
4510 
4511  !> Gaussian perception error parameter (cv) for **energy reserves** perception
4512  !! effects on **reproduction**.
4513  real(srp), parameter, public :: &
4515 
4516  !-----------------------------------------------------------------------------
4517  !> The genotype structure for **age** perception effects on
4518  !! **reproduction** that goes via gamma2gene perception to neuronal
4519  !! response.
4520  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4521  :: age_reproduce_genotype_neuronal = reshape ( &
4522  ! ............................................................................
4523  [ & ! 1 2 3 4 5 6
4524  !------------------------
4525  no, no, no, no, no, no, & ! 1
4526  no, no, no, no, no, no, & ! 2
4527  no, no, no, no, no, no, & ! 3
4528  no, no, no, no, no, no, & ! 4
4529  no, no, no, no, no, no, & ! 5
4530  no, no, no, no, no, no, & ! 6
4531  no, no, no, no, no, no, & ! 7
4532  no, no, no, no, no, no, & ! 8
4533  no, no, no, no, no, no, & ! 9
4534  no, no, no, no, no, no, & ! 10
4535  no, no, no, no, no,yes, & ! 11
4536  no, no, no, no, no, no ], & ! 12
4537  ! -------------------------
4538  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4539  [max_nalleles,n_chromosomes],[no],[2,1] )
4540  ! Note: additional reshape params: array shape |pad | order
4541  ! |with| by rows
4542  ! ............................................................................
4543 
4544  !> Gaussian perception error parameter (cv) for **age** perception
4545  !! effects on **reproduction**.
4546  real(srp), parameter, public :: &
4548 
4549  !-----------------------------------------------------------------------------
4550  !> The genotype structure for **age** perception effects on
4551  !! **reproduction** that goes via gamma2gene perception to neuronal
4552  !! response.
4553  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4554  :: reprfac_reproduce_genotype_neuronal = reshape ( &
4555  ! ............................................................................
4556  [ & ! 1 2 3 4 5 6
4557  !------------------------
4558  no, no, no, no, no, no, & ! 1
4559  no, no, no, no, no, no, & ! 2
4560  no, no, no, no, no, no, & ! 3
4561  no, no, no, no, no, no, & ! 4
4562  no, no, no, no, no, no, & ! 5
4563  no, no, no, no, no, no, & ! 6
4564  no, no, no, no, no, no, & ! 7
4565  no, no, no, no, no, no, & ! 8
4566  no, no, no, no, no, no, & ! 9
4567  no, no, no, no, no, no, & ! 10
4568  no, no, no, no, no, no, & ! 11
4569  no, no, no, no, no,yes ], & ! 12
4570  ! -------------------------
4571  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4572  [max_nalleles,n_chromosomes],[no],[2,1] )
4573  ! Note: additional reshape params: array shape |pad | order
4574  ! |with| by rows
4575  ! ............................................................................
4576 
4577  !> Gaussian perception error parameter (cv) for **age** perception
4578  !! effects on **reproduction**.
4579  real(srp), parameter, public :: &
4581 
4582  !.............................................................................
4583  ! ## Modulation parameters ##
4584  ! Parameters for the GENETIC and NON-GENETIC MODULATION of the motivational
4585  ! state. Non-genetic modulation includes developmental modulation of the
4586  ! reproductive modulation by weighting it out at early ages.
4587 
4588  !-----------------------------------------------------------------------------
4589  !> Disable developmental or genetic modulation of the `APPRAISAL` completely.
4590  !! If set to TRUE, **no modulation** is performed and the final motivation
4591  !! values are just equal to the primary modulation values in `APPRAISAL`.
4592  logical, parameter, public :: modulation_appraisal_disable_all = .false.
4593  !-----------------------------------------------------------------------------
4594 
4595  !> Developmental modulation of reproductive motivation. This parameter
4596  !! defines the starting age (time steps) at which reproductive motivation
4597  !! can rise above zero (at all previous ages weight=0.0).
4598  !! See the_neurobio::appraisal_motivation_modulation_non_genetic().
4599  real(srp), parameter, public :: &
4601 
4602  !> Developmental modulation of reproductive motivation. This parameter
4603  !! defines the age (time steps) at which reproductive motivation is weighted
4604  !! fully (weight = 1.0).
4605  !! See the_neurobio::appraisal_motivation_modulation_non_genetic().
4606  real(srp), parameter, public :: &
4608  reprod_modulation_devel_agestart * 2.0_srp / 3.0_srp
4609  !> Developmental modulation of reproductive motivation. This is the
4610  !! interpolation grid abscissa defining at which age reproduction motivation
4611  !! can have non-zero values (reproduction is possible). It defines the
4612  !! weighting factor applied to reproductive motivation.
4613  !!
4614  !! It is calculated as follows. First, the first grid value *A* is set from
4615  !! the parameter commondata::reprod_modulation_devel_agestart (it takes the
4616  !! weight 0.0). Second, the last value of the abscissa grid array *B* is set
4617  !! from the parameter commondata::reprod_modulation_devel_agefull (it has
4618  !! the weight 1.0, full reproductive factor). Third, the interval between
4619  !! *A* and *B* is further split into three intervals and the first point
4620  !! is taken as the second value of the interpolation abscissa array
4621  !! (assigned the weight given by commondata::reprod_modulation_devel_w2).
4622  !! Thus, the interval reproductive factor weighting abscissa looks like this:
4623  !! @verbatim
4624  !! +-------------------------------#----------+------------#----------+
4625  !! 1 ^ ^ LIFESPAN
4626  !! A B
4627  !!
4628  !! #-------#-------|-------#
4629  !! ^
4630  !! A+(B-A)*1/3
4631  !!
4632  !! Resulting array abscissa: [ A, A + (B - A) / 3, B ]
4633  !! ordinate: [ 0.0, REPROD_MODULATION_DEVEL_W2, 1.0 ]
4634  !! @endverbatim
4635  !! See the_neurobio::appraisal_motivation_modulation_non_genetic().
4636  real(srp), parameter, dimension(*) :: reprod_modulation_devel_abscissa = &
4640  reprod_modulation_devel_agestart ) / 3.0_srp, &
4642 
4643  !> Developmental modulation of reproductive motivation. This parameter sets
4644  !! the interpolation array weight that defines how fast the reproduction
4645  !! motivation the_neurobio::state_reproduce is allowed to raise when the age
4646  !! of the agent exceeds the reproductive age. For details see
4647  !! the_neurobio::appraisal_motivation_modulation_non_genetic().
4648  real(srp), parameter, public :: reprod_modulation_devel_w2 = 0.1_srp
4649 
4650  !-----------------------------------------------------------------------------
4651  !> The genotype structure for sex modulation coefficient affecting
4652  !! **reproduction** motivation state in **males**.
4653  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4655  ! ............................................................................
4656  [ & ! 1 2 3 4 5 6
4657  !------------------------
4658  no, no, no, no, no, no, & ! 1
4659  yes, no, no, no, no, no, & ! 2
4660  no, no, no, no, no, no, & ! 3
4661  no, no, no, no, no, no, & ! 4
4662  no, no, no, no, no, no, & ! 5
4663  no, no, no, no, no, no, & ! 6
4664  no, no, no, no, no, no, & ! 7
4665  no, no, no, no, no, no, & ! 8
4666  no, no, no, no, no, no, & ! 9
4667  no, no, no, no, no, no, & ! 10
4668  no, no, no, no, no, no, & ! 11
4669  no, no, no, no, no, no ], & ! 12
4670  ! -------------------------
4671  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4672  [max_nalleles,n_chromosomes],[no],[2,1] )
4673  ! Note: additional reshape params: array shape |pad | order
4674  ! |with| by rows
4675  ! ............................................................................
4676 
4677  !> Gaussian error parameter (cv) for the sex modulation coefficient
4678  !! affecting **reproduction** motivation state in **males**.
4679  real(srp), parameter, public :: &
4681 
4682  !-----------------------------------------------------------------------------
4683  !> The genotype structure for sex modulation coefficient affecting
4684  !! **reproduction** motivation state in **females**.
4685  logical, dimension(MAX_NALLELES,N_CHROMOSOMES),parameter,public &
4687  ! ............................................................................
4688  [ & ! 1 2 3 4 5 6
4689  !------------------------
4690  no, no, no, no, no, no, & ! 1
4691  no, no, no, no, no, no, & ! 2
4692  yes, no, no, no, no, no, & ! 3
4693  no, no, no, no, no, no, & ! 4
4694  no, no, no, no, no, no, & ! 5
4695  no, no, no, no, no, no, & ! 6
4696  no, no, no, no, no, no, & ! 7
4697  no, no, no, no, no, no, & ! 8
4698  no, no, no, no, no, no, & ! 9
4699  no, no, no, no, no, no, & ! 10
4700  no, no, no, no, no, no, & ! 11
4701  no, no, no, no, no, no ], & ! 12
4702  ! -------------------------
4703  ! max. n alleles: 6, 5, 12, 12, 12, 12, 12
4704  [max_nalleles,n_chromosomes],[no],[2,1] )
4705  ! Note: additional reshape params: array shape |pad | order
4706  ! |with| by rows
4707  ! ............................................................................
4708 
4709  !> Gaussian error parameter (cv) for the sex modulation coefficient
4710  !! affecting **reproduction** motivation state in **females**.
4711  real(srp), parameter, public :: &
4713 
4714  !.............................................................................
4715  ! ## Baseline attention switches ##
4716 
4717  !> *Baseline attention switches* @f$ \Psi _{i,j} @f$ control which perception
4718  !! components (*i*) can affect each of the motivational state (*j*). They
4719  !! should be defined for all combinations between the perception components
4720  !! (light, depth... food... predators... etc) and the motivational states.
4721  !! See @ref aha_buildblocks_cogn_arch "Cognitive architecture".
4722  !!
4723  !! These values serve as weight factors are baseline *before* attention
4724  !! is suppressed (the_neurobio::gos_global::attention_modulate()).
4725  !! They can be used for switching specific perceptual components
4726  !! the_neurobio::percept_components_motiv of motivation ON (1.0) or
4727  !! OFF (0.0) . Therefore, they should provide all possible combinations of
4728  !! the motivational states \%state_ (as in the_neurobio::motivation) and
4729  !! perception components the_neurobio::percept_components_motiv.
4730  !!
4731  !> The `ATTENTION_SWITCH_` pattern matrix for all perception components and
4732  !! motivation states is presented in the table below:
4733  !!
4734  !! | | HUNGER | FEAR_DEFENCE | REPRODUCE |
4735  !! | ---------- | ---------- | ------------ | ----------- |
4736  !! | LIGHT | 0.0 | 1.0 | 0.0 |
4737  !! | DEPTH | 0.0 | 1.0 | 0.0 |
4738  !! | FOOD_DIR | 1.0 | 0.0 | 0.0 |
4739  !! | FOOD_MEM | 1.0 | 0.0 | 0.0 |
4740  !! | CONSPEC | 1.0 | 1.0 | 1.0 |
4741  !! | PRED_DIR | 0.0 | 1.0 | 0.0 |
4742  !! | PREDATOR | 0.0 | 1.0 | 0.0 |
4743  !! | STOMACH | 1.0 | 0.0 | 0.0 |
4744  !! | BODYMASS | 1.0 | 0.0 | 1.0 |
4745  !! | ENERGY | 1.0 | 0.0 | 1.0 |
4746  !! | AGE | 0.0 | 0.0 | 1.0 |
4747  !! | REPRFAC | 0.0 | 0.0 | 1.0 |
4748  real(srp), parameter, public :: attention_switch_hunger_light = 0.0_srp
4749  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4750  real(srp), parameter, public :: attention_switch_hunger_depth = 0.0_srp
4751  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4752  real(srp), parameter, public :: attention_switch_hunger_food_dir = 1.0_srp
4753  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4754  real(srp), parameter, public :: attention_switch_hunger_food_mem = 1.0_srp
4755  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4756  real(srp), parameter, public :: attention_switch_hunger_conspec = 1.0_srp
4757  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4758  real(srp), parameter, public :: attention_switch_hunger_pred_dir = 0.0_srp
4759  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4760  real(srp), parameter, public :: attention_switch_hunger_predator = 0.0_srp
4761  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4762  real(srp), parameter, public :: attention_switch_hunger_stomach = 1.0_srp
4763  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4764  real(srp), parameter, public :: attention_switch_hunger_bodymass = 1.0_srp
4765  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4766  real(srp), parameter, public :: attention_switch_hunger_energy = 1.0_srp
4767  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4768  real(srp), parameter, public :: attention_switch_hunger_age = 0.0_srp
4769  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4770  real(srp), parameter, public :: attention_switch_hunger_reprfac = 0.0_srp
4771 
4772  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4773  real(srp), parameter, public :: attention_switch_avoid_act_light = 1.0_srp
4774  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4775  real(srp), parameter, public :: attention_switch_avoid_act_depth = 1.0_srp
4776  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4777  real(srp), parameter, public :: attention_switch_avoid_act_food_dir = 0.0_srp
4778  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4779  real(srp), parameter, public :: attention_switch_avoid_act_food_mem = 0.0_srp
4780  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4781  real(srp), parameter, public :: attention_switch_avoid_act_conspec = 1.0_srp
4782  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4783  real(srp), parameter, public :: attention_switch_avoid_act_pred_dir = 1.0_srp
4784  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4785  real(srp), parameter, public :: attention_switch_avoid_act_predator = 1.0_srp
4786  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4787  real(srp), parameter, public :: attention_switch_avoid_act_stomach = 0.0_srp
4788  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4789  real(srp), parameter, public :: attention_switch_avoid_act_bodymass = 0.0_srp
4790  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4791  real(srp), parameter, public :: attention_switch_avoid_act_energy = 0.0_srp
4792  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4793  real(srp), parameter, public :: attention_switch_avoid_act_age = 0.0_srp
4794  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4795  real(srp), parameter, public :: attention_switch_avoid_act_reprfac = 0.0_srp
4796 
4797  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4798  real(srp), parameter, public :: attention_switch_reproduce_light = 0.0_srp
4799  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4800  real(srp), parameter, public :: attention_switch_reproduce_depth = 0.0_srp
4801  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4802  real(srp), parameter, public :: attention_switch_reproduce_food_dir = 0.0_srp
4803  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4804  real(srp), parameter, public :: attention_switch_reproduce_food_mem = 0.0_srp
4805  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4806  real(srp), parameter, public :: attention_switch_reproduce_conspec = 1.0_srp
4807  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4808  real(srp), parameter, public :: attention_switch_reproduce_pred_dir = 0.0_srp
4809  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4810  real(srp), parameter, public :: attention_switch_reproduce_predator = 0.0_srp
4811  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4812  real(srp), parameter, public :: attention_switch_reproduce_stomach = 0.0_srp
4813  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4814  real(srp), parameter, public :: attention_switch_reproduce_bodymass = 1.0_srp
4815  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4816  real(srp), parameter, public :: attention_switch_reproduce_energy = 1.0_srp
4817  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4818  real(srp), parameter, public :: attention_switch_reproduce_age = 1.0_srp
4819  !> Baseline attention switch, see commondata::attention_switch_hunger_light.
4820  real(srp), parameter, public :: attention_switch_reproduce_reprfac = 1.0_srp
4821 
4822  !.............................................................................
4823  ! Attention modulation curve parameters. Attention modulation by the GOS
4824  ! is obtained via nonlinear interpolation of the basic grid points.
4825 
4826  !> The array defining the **abscissa** (X) of the nonparametric function
4827  !! that defines the **attention modulation curve** by the current Global
4828  !! Organismic State (GOS).
4829  !! @warning Must have the same dimensionality as
4830  !! commondata::attention_modulation_curve_ordinate.
4831  real(srp), dimension(*), parameter, public :: &
4832  attention_modulation_curve_abscissa=[0.0_srp, 0.3_srp, 0.5_srp, 1.0_srp]
4833 
4834  !> The array defining the **ordinate** (Y) of the nonparametric function
4835  !! that defines the **attention modulation curve** by the current Global
4836  !! Organismic State (GOS).
4837  !! @warning Must have the same dimensionality as
4838  !! commondata::attention_modulation_curve_abscissa.
4839  real(srp), dimension(*), parameter, public :: &
4840  attention_modulation_curve_ordinate=[1.0_srp, 0.98_srp, 0.9_srp, 0.0_srp]
4841 
4842  !.............................................................................
4843  ! ## Parameters for the GOS, Global Organismic State ##
4844 
4845  !> The array defining the **abscissa** (X) of the nonparametric function
4846  !! curve that defines the threshold for motivation competition in GOS.
4847  !! @warning Must have the same dimensionality as
4848  !! commondata::motivation_compet_threshold_curve_ordinate.
4849  real(srp), dimension(*), parameter, &
4851  [0.0_srp, 0.2_srp, 0.60_srp, 0.80_srp, 0.90_srp, 1.0_srp, 1.1_srp]
4852 
4853  !> The array defining the **ordinate** (Y) of the nonparametric function
4854  !! curve that defines the threshold for motivation competition in GOS.
4855  !! @warning Must have the same dimensionality as
4856  !! commondata::motivation_compet_threshold_curve_abscissa.
4857  real(srp), dimension(*), parameter, &
4859  [1.0_srp, 0.3_srp, 0.04_srp, 0.01_srp, 0.001_srp, 0.0_srp, 0.0_srp]
4860 
4861  !> Spontaneous arousal dissipation level when a simple **fixed** dissipation
4862  !! factor pattern is used. At each step, `gos_arousal` is reduced by a
4863  !! constant factor, AROUSAL_GOS_DISSIPATION_FACTOR` (e.g. reduced by 0.5)
4864  !! independently on the current GOS time step.
4865  real(srp), parameter, public :: arousal_gos_dissipation_factor = 0.5_srp
4866 
4867  !> This is the array defining the **abscissa** (X) of the nonparametric
4868  !! spontaneous arousal dissipation factor function involving polynomial
4869  !! (or linear) interpolation is used.
4870  !! @warning Must have the same dimensionality as
4871  !! commondata::arousal_gos_dissipation_nonpar_ordinate.
4872  real(srp), dimension(*), parameter, &
4874  [ 1.0, 2.00, 5.00, 10.0, 15.0, 18.0, 20.0 ]
4875 
4876  !> This is the array defining the **ordinate** (Y) of the nonparametric
4877  !! spontaneous arousal dissipation factor function involving polynomial
4878  !! (or linear) interpolation is used.
4879  !! @warning Must have the same dimensionality as
4880  !! commondata::arousal_gos_dissipation_nonpar_abscissa.
4881  real(srp), dimension(*), parameter, &
4883  [ 1.0, 0.98, 0.80, 0.40, 0.22, 0.18, 0.17 ]
4884 
4885  !> Global maximum sensory information that is updated for the whole
4886  !! population of agents.
4887  !! @note This roughly corresponds to the `MaxPercept` array in the G1 model.
4889 
4890  !-----------------------------------------------------------------------------
4891 
4892  !.............................................................................
4893  ! ## Parameters for the behaviours ##
4894 
4895  !> The size of the behaviour labels history stack, i.e. for how many time
4896  !! steps should the stack remember record the behaviour labels.
4897  integer, parameter, public :: history_size_behaviours = history_size_spatial
4898 
4899  !> Default weighting factor for the baseline probability of successful
4900  !! reproduction @f$ \varphi @f$. See implementation details for the function
4901  !! the_neurobio::reproduce_do_probability_reproduction_calc().
4902  real(srp), parameter, public :: probability_reproduction_base_factor = 0.90
4903 
4904  !> Interpolation grid **abscissa** for the body mass ratio factor that
4905  !! scales the probability of reproduction. For details see
4906  !! the_neurobio::reproduce_do_probability_reproduction_calc() procedure.
4907  !! Commands (template) to produce interpolation plots:
4908  !! @verbatim
4909  !! htintrpl.exe [0.5 1 2] [0 1 1.8] 0.2
4910  !! @endverbatim
4911  !! @warning Must have the same dimensionality as
4912  !! commondata::probability_reproduction_delta_mass_ordinate.
4913  real(srp), dimension(*), parameter, &
4915  [0.5_srp, 1.0_srp, 2.0_srp]
4916 
4917  !> Interpolation grid **ordinate** for the body mass ratio factor that
4918  !! scales the probability of reproduction. For details see
4919  !! the_neurobio::reproduce_do_probability_reproduction_calc() procedure.
4920  !! Commands (template) to produce interpolation plots:
4921  !! @verbatim
4922  !! htintrpl.exe [0.5 1 2] [0 1 1.8] 0.2
4923  !! @endverbatim
4924  !! @warning Must have the same dimensionality as
4925  !! commondata::probability_reproduction_delta_mass_abscissa.
4926  real(srp), dimension(*), parameter, &
4928  [0.0_srp, 1.0_srp, 1.8_srp]
4929 
4930  !> This parameter defines the threshold of the current gonadal steroids
4931  !! level that should exceed the baseline value determined by the genome,
4932  !! for reproduction to be possible.
4933  !! @note Note that this parameter should normally exceed 1.0
4934  real(srp), parameter, public :: sex_steroids_reproduction_threshold = 1.3_srp
4935 
4936  !> The weighting factor used in calculation of the default random walk
4937  !! distance, in terms of the agent's body length.
4938  real(srp), parameter, public :: &
4940 
4941  !> The coefficient of variation of the distance for stochastic Gaussian
4942  !! random walk (distance is in terms of the agent's body length). Note that
4943  !! for deterministic walk, cv is zero.
4944  real(srp), parameter, public :: walk_random_distance_stochastic_cv = 0.5_srp
4945 
4946  !> The maximum walk distance, **in units of the average distance to food
4947  !! items** in the current perception object, when the expected food gain is
4948  !! calculated on the bases of the current food availability, not using the
4949  !! the_behaviour::hope() function mechanism. If the average walk distance
4950  !! exceeds this value, the expectancy is based on the the_behaviour::hope()
4951  !! function.
4952  real(srp), parameter, public :: walk_random_food_gain_hope = 4.0_srp
4953 
4954  !> The maximum walk distance, **in units of the agent body length**, when
4955  !! the expected food gain is calculated on the bases of the current food
4956  !! availability, not using the the_behaviour::hope() function mechanism.
4957  !! If the average walk distance exceeds this value, the expectancy is based
4958  !! on the the_behaviour::hope() function.
4959  !! @note This parameter is used for switching between the food gain
4960  !! calculation methods based on current perception or hope function
4961  !! if the agent has no food items in perception object. Normally, if
4962  !! there are food items, the commondata::walk_random_food_gain_hope
4963  !! is used.
4964  real(srp), parameter, public :: walk_random_food_gain_hope_agentl = 100.0_srp
4965 
4966  !> The maximum walk distance, **in units of the agent body length**, when
4967  !! the expected predation risk is calculated on the basis of the current
4968  !! perception value, not using the the_behaviour::hope() function mechanism.
4969  !! If the average walk distance exceeds this value, the risk expectancy is
4970  !! based on the the_behaviour::hope() function.
4971  real(srp), parameter, public :: walk_random_pred_risk_hope_agentl = 150.0_srp
4972 
4973  !> The ratio of the vertical to main horizontal shift parameters of the
4974  !! agent's Gaussian random walk. Random walk is done in the "2.5D" mode
4975  !! (the_environment::spatial_moving::rwalk25d()), i.e. with separate
4976  !! parameters for the main horizontal shift and the vertical depth shift.
4977  !! This is done to avoid a potentially too large vertical displacement
4978  !! of the agent during the movement. Thus, the vertical shift distance
4979  !! should normally be smaller than the horizontal shift. The difference
4980  !! between the main horizontal and (the smaller) vertical shifts is defined
4981  !! by this parameter. For example, if it is equal to 0.5, then the vertical
4982  !! depth shift is 0.5 of the main horizontal shift.
4983  !! See the_behaviour::walk_random_do_execute() for more details.
4984  real(srp), parameter, public :: walk_random_vertical_shift_ratio = 0.5_srp
4985 
4986  !> The ratio of the vertical to the main horizontal coefficients of variation
4987  !! for the **vertical** depth distance in the stochastic Gaussian random walk
4988  !! of the agent. Should normally be equal to the main default value set by
4989  !! commondata::walk_random_distance_stochastic_cv. That is 1.0
4990  real(srp), parameter, public :: walk_random_vertical_shift_cv_ratio = 1.0_srp
4991 
4992  !> This parameter defines the hope function for calculating the food
4993  !! perception expectancy in the the_behaviour::walk_random behaviour.
4994  !! This is the abscissa for the hope function grid array.
4995  !! Plotting: `htintrpl.exe [0 1 3.5 ] [2, 1, 0]`.
4996  !! See the_behaviour::walk_random_do_this().
4997  !! @note Note that the "maximum hope" value for normal random walk is
4998  !! smaller than in the hope function grid for the migration
4999  !! behaviour commondata::migrate_food_gain_maximum_hope. Thus,
5000  !! the maximum incentive for movement is lower here.
5001  !! @warning Must have the same dimensionality as
5002  !! commondata::walk_random_food_hope_ordinate.
5003  real(srp), dimension(*), parameter, public :: &
5004  walk_random_food_hope_abscissa = [ 0.0_srp, 1.0_srp, 3.5_srp ]
5005 
5006  !> This parameter defines the hope function for calculating the food
5007  !! perception expectancy in the the_behaviour::walk_random behaviour.
5008  !! This is the ordinate for the hope function grid array.
5009  !! Plotting: `htintrpl.exe [0 1 3.5 ] [2, 1, 0]`.
5010  !! See the_behaviour::walk_random_do_this().
5011  !! @note Note that the "zero hope" value for normal random walk is
5012  !! higher (non-zero) than in the hope function grid for the
5013  !! migration behaviour. Thus, the maximum incentive for movement
5014  !! is lower here.
5015  !! @warning Must have the same dimensionality as
5016  !! commondata::walk_random_food_hope_abscissa.
5017  real(srp), dimension(*), parameter, public :: &
5018  walk_random_food_hope_ordinate = [ 2.0_srp, 1.0_srp, 0.0_srp ]
5019 
5020  !> Default offset for approach, offset is the difference between the
5021  !! approaching agent and the target object.
5022  real(srp), parameter, public :: approach_offset_default = &
5024 
5025  !> Multiplication factor for the general risk of predation used when the
5026  !! agent evaluates the approach to a target conspecific.
5027  real(srp), parameter, public :: &
5029 
5030  !> Multiplication factor for subjective assessment of the direct risk of
5031  !! predation when the actor agent moves behind the target conspecific, i.e.
5032  !! when the distance between the agent and predator is going to become
5033  !! longer than the distance between the target conspecific and the agent.
5034  !! See the_behaviour::approach_conspecifics_do_this() for details.
5035  real(srp), parameter, public :: &
5037 
5038  !> The grid **abscissa** defining the nonparametric relationship
5039  !! that determines the expected food gain for the "approach conspecifics"
5040  !! behaviour (the_behaviour::approach_conspec class). The function is a
5041  !! weighting factor depending on the ratio of the agent body mass to the
5042  !! target conspecific body mass, for the baseline expected food gain.
5043  !! @verbatim
5044  !! htintrpl.exe [ 0 0.1 1 1.5 ] [ 0 0.01 0.5 1 ]
5045  !! @endverbatim
5046  !! @note The (last) maximum value of the grid defines the body mass ratio
5047  !! that guarantees 100% expectancy of winning of competition for food
5048  !! against the target conspecific. For example, the value of 1.5
5049  !! means that an agent is guaranteed to get the whole baseline
5050  !! expected food gain if its body weight is 1.5 of the target
5051  !! conspecific.
5052  !! See the_behaviour::approach_conspecifics_do_this() for details.
5053  !! @warning Must have the same dimensionality as
5054  !! commondata::approach_food_gain_compet_factor_ordinate.
5055  real(srp), dimension(*), parameter, &
5057  [ 0.00_srp, 0.10_srp, 1.00_srp, 1.50_srp ]
5058 
5059  !> The grid **ordinate** defining the nonparametric relationship
5060  !! that determines the expected food gain for the "approach conspecifics"
5061  !! behaviour (the_behaviour::approach_conspec class). The function is a
5062  !! weighting factor depending on the ratio of the agent body mass to the
5063  !! target conspecific body mass, for the baseline expected food gain.
5064  !! @verbatim
5065  !! htintrpl.exe [ 0 0.1 1 1.5 ] [ 0 0.01 0.5 1 ]
5066  !! @endverbatim
5067  !! See the_behaviour::approach_conspecifics_do_this() for details.
5068  !! @warning Must have the same dimensionality as
5069  !! commondata::approach_food_gain_compet_factor_abscissa.
5070  real(srp), dimension(*), parameter, &
5072  [ 0.00_srp, 0.01_srp, 0.50_srp, 1.00_srp ]
5073 
5074  !> The weighting factor for the distance to the expected food item if the
5075  !! actual distance is uncertain (e.g. no food items currently in perception).
5076  !! See the_behaviour::walk_random_motivations_expect().
5077  real(srp), parameter, public :: dist_expect_food_uncertain_fact = 0.7_srp
5078 
5079  !> The size of the memory window that is used in the assessment of predation
5080  !! risk, as a portion of the commondata::history_size_perception.
5081  !! See the_behaviour::walk_random_do_this() and
5082  !! the_behaviour::walk_random_motivations_expect().
5083  real(srp), parameter, public :: history_perception_window_pred = 0.3_srp
5084 
5085  !> The size of the memory window that is used in the assessment of food
5086  !! gain, as a portion of the commondata::history_size_perception.
5087  !! See the_behaviour::walk_random_do_this() and
5088  !! the_behaviour::walk_random_motivations_expect().
5089  real(srp), parameter, public :: history_perception_window_food = 0.3_srp
5090 
5091  !> The weighting factor used in calculation of the default escape distance.
5092  !! The escape distance is equal to the visibility range of the predator
5093  !! multiplied by this factor. Therefore, it should normally exceed 1.0.
5094  !! Otherwise, the escaping object is still within the visibility range
5095  !! of the predator after the escape.
5096  !! See the_behaviour::escape_dart_do_this() for more details.
5097  real(srp), parameter, public :: escape_dart_distance_default_factor = 1.5_srp
5098 
5099  !> For stochastic escape, this parameter determines the coefficient
5100  !! of variation of the escape walk. See the_behaviour::escape_dart_do_this()
5101  !! for more details.
5102  real(srp), parameter, public :: &
5104 
5105  !> The default size of the up and down walks performed by the GO_DOWN_DEPTH
5106  !! and GO_UP_DEPTH, see the_behaviour::go_down_depth and
5107  !! the_behaviour::go_up_depth classes as well as
5108  !! the_behaviour::go_down_do_this() and the_behaviour::go_up_do_this() methods.
5109  real(srp), parameter, public :: up_down_walk_step_stdlength_factor = 4.0_srp
5110 
5111  !> The maximum distance (in units of the agent body length) a migrating
5112  !! agent can pass for a single time step of the model. This is basically
5113  !! limited by (an implicit) maximum speed of the agent, in terms of its
5114  !! body length. This parameter sets the limit on the length of a single
5115  !! migration bout.
5116  real(srp), parameter, public :: migrate_dist_max_step = 800.0_srp
5117 
5118  !> Default maximum distance towards the target environment (in units of the
5119  !! agent's body size) when the agent could emigrate into this target
5120  !! environment. See the_behaviour::behaviour_do_migrate_random() for details.
5121  real(srp), parameter, public :: migrate_random_max_dist_target = 10.0_srp
5122 
5123  !> The offset, in terms of the body length of the actor agent, for
5124  !! initial penetrating into the target environment when the agent is
5125  !! migrating into this environment. See the_environment::migrate_do_this().
5126  real(srp), parameter, public :: migrate_dist_penetrate_offset = 1.0_srp
5127 
5128  !> This parameter defines the hope function for calculating the food gain
5129  !! expectancy in the migration behaviour. This is the maximum value of the
5130  !! hope function that is achieved at zero ratio of the old to new food gain
5131  !! memory values. Plotting: `htintrpl.exe [0 1 3.5] [2 1 0]`.
5132  !! See the_behaviour::migrate_do_this().
5133  real(srp), parameter, public :: migrate_food_gain_maximum_hope = 2.0_srp
5134 
5135  !> This parameter defines the hope function for calculating the food gain
5136  !! expectancy in the migration behaviour. This is the maximum ratio of the
5137  !! old to new food gain memory values that leads to virtually zero value
5138  !! of the hope function. Plotting: `htintrpl.exe [0 1 3.5] [2 1 0]`.
5139  !! See the_behaviour::migrate_do_this().
5140  real(srp), parameter, public :: migrate_food_gain_ratio_zero_hope = 3.5_srp
5141 
5142  !> This parameter defines the hope function for calculating the general
5143  !! predation risk expectancy in the migration behaviour. This is the
5144  !! maximum value of the hope function that is achieved at zero ratio of the
5145  !! old to new predation values in the memory stack.
5146  !! Plotting: `htintrpl.exe [0 1 3.5] [2 1 0]`.
5147  !! See the_behaviour::migrate_do_this().
5148  real(srp), parameter, public :: migrate_predator_maximum_hope = 2.0_srp
5149 
5150  !> This parameter defines the hope function for calculating the general
5151  !! predation risk expectancy in the migration behaviour. This is the maximum
5152  !! ratio of the old to new predation values in the memory stack that leads
5153  !! to virtually zero value of the hope function.
5154  !! Plotting: `htintrpl.exe [0 1 3.5] [2 1 0]`.
5155  !! See the_behaviour::migrate_do_this().
5156  real(srp), parameter, public :: migrate_predator_zero_hope = 3.5_srp
5157 
5158  !> This parameter array defines the repertoire of predetermined static walk
5159  !! step sizes, in units of the agent's body length, for the
5160  !! the_behaviour::walk_random behavioural unit as executed in the
5161  !! the_behaviour::behaviour::walk_random class level.
5162  !! See the_behaviour::behaviour::select() method for details.
5163  real(srp), dimension(*), parameter, public :: behav_walk_step_stdlen_static &
5164  = [ 1.0_srp, 10.0_srp, 25.0_srp, 50.0_srp, 100.0_srp ]
5165 
5166  !> This parameter array defines the step sizes, in units of the agent's body
5167  !! length, for the the_behaviour::go_down_depth and the_behaviour::go_up_depth
5168  !! behavioural unit as executed in the the_behaviour::behaviour::depth_down
5169  !! and the_behaviour::behaviour::depth_up class level(s).
5170  !! See the_behaviour::behaviour::select() method for details.
5171  real(srp), dimension(*), parameter, public :: &
5173  [ 10.0_srp, 20.0_srp, 50.0_srp, 75.0_srp, 100.0_srp ]
5174 
5175 
5176  !> @}
5177 
5178  !.............................................................................
5179  !.............................................................................
5180 
5181  !> @name Parameters of the Genetic Algorithm
5182  !> @{
5183 
5184  !> Percentage of the best reproducing agents in the pre-evolution phase.
5185  real(srp), parameter, public :: ga_reproduce_pr = 0.05_srp
5186 
5187  !> Upper limit on the number of reproducing individuals in the
5188  !! fixed-fitness pre-evolution phase.
5189  integer, parameter, public :: ga_reproduce_n = int(popsize * ga_reproduce_pr)
5190 
5191  !> Fitness value ascribed to dead agent in pre-evol. See
5192  !! the_individual::individual_agent::fitness_calc().
5193  !! Also note that huge(integer)) = 2147483647
5194  integer, parameter, public :: ga_fitness_dead = 400000000
5195 
5196  !> Fitness threshold for the inclusion of the agent into the reproducing
5197  !! elite group
5198  integer, parameter, public :: ga_fitness_select = 900
5199 
5200  !> Minimum proportion of reproducing agents, but note that the number of
5201  !! number reproducers cannot be smaller than the absolute minimum
5202  !! commondata::ga_reproduce_n_min.
5203  !! See the_population::population::ga_reproduce_max().
5204  real(srp), parameter, public :: ga_reproduce_min_prop = 0.05_srp
5205 
5206  !> Absolute minimum number of reproducing agents in the adaptive GA procedure.
5207  !! See the_population::population::ga_reproduce_max().
5208  integer, parameter, public :: ga_reproduce_n_min = 20
5209 
5210  !> @}
5211 
5212  !-----------------------------------------------------------------------------
5213  !-----------------------------------------------------------------------------
5214 
5215  ! ## Generic interfaces for global COMMONDATA procedures ##
5216  ! Generic interfaces for the general-scope functions go below.
5217  ! Generic interfaces allow to use a general name so that the program
5218  ! selects the appropriate specific function from the list depending
5219  ! on the function parameters. For example, we have different `gamma2gene`
5220  ! functions under the same name, e.g. accepting different type
5221  ! arguments and processing them with different logic.
5222 
5223  !> @brief Sigmoidal relationship between environmental factor and the
5224  !! organism response, as affected by the genotype and environmental
5225  !! error, e.g. perception and neuronal response or intrinsic baseline
5226  !! and phenotypic hormone levels.
5227  !! @details The real function `gamma2gene` finds the sigmoid relationship for
5228  !! a multicomponent allele impact on the neuronal response:
5229  !! @f[ R= \frac{(P/y_{1})^{x_{1}}}{1+(P/y_{1})^{x_{1}}} +
5230  !! \frac{(P/y_{2})^{x_{2}}}{1+(P/y_{2})^{x_{2}}} +
5231  !! \frac{(P/y_{3})^{x_{3}}}{1+(P/y_{3})^{x_{3}}} ... @f]
5232  !! Here, R is the neuronal response, P the strength of the sensory
5233  !! input (scaled 0-1), and x and y are two genes. The indices refer
5234  !! to the additive components of the alleles. Note that their
5235  !! number is set by the parameter `ADDITIVE_COMPS`. Further,
5236  !! `erpcv` defines the coefficient of variation for the perception
5237  !! error (with respect to its true value).
5238  !! *Perception* is calculated as @f[ P=\bar{P}+\varepsilon , @f]
5239  !! where @f$ \bar{P} @f$ is the true environmental variable and
5240  !! @f$ \varepsilon @f$ is Gaussian error. The perception value with
5241  !! error is implemented as a normal Gaussian variate with the mean
5242  !! equal to the true `signal` value @f$ \bar{P} @f$ and the
5243  !! coefficient of variation equal to the `erpcv` input parameter:
5244  !! @f$ erpcv= \frac{\sigma}{\bar{P}} . @f$ Therefore, the raw
5245  !! error variance in the `RNORM` function is equal to the square:
5246  !! @f$ (erpcv \cdot signal)^{2} @f$. We also impose strict *limit*
5247  !! on perception: @f[ P > 0 . @f]
5248  !! The `gamma2gene` function is used as a calculation backend in the
5249  !! "umbrella" procedure `the_genome::individual_genome::neuro_resp()`
5250  !! that translates to `the_genome::individual_genome::trait_init()`
5251  !! and `the_genome::individual_genome::trait_set()`.
5252  !! @note This is the generic interface for `gamma2gene`, currently there
5253  !! are two version making use of the additive allele
5254  !! components (normally used) accepting allele values either integer
5255  !! (assumed raw alleles) or real (assumed values rescaled to 0:1)
5256  !! type.
5257  !! @note The function involving additive allele components has two variants:
5258  !! If called with *integer* parameters one and two (`gs` and `gh`) it
5259  !! automatically invokes the `allelescale` function to convert integer
5260  !! allele values to real raw values within the range 1:0 that go to
5261  !! the sigmoid function (via alleleconv). However, when these
5262  !! arguments are *real* type, it is assumed that it is the true
5263  !! converted 0:1 real gene values and `allelescale` is *not* invoked
5264  !! prior to `alleleconv`.
5265  !! @note It would be more economical to use a single allele conversion
5266  !! function that does both allelescale and alleleconv. It is here
5267  !! for compatibility with the earlier model. Also, this might be
5268  !! a little more intuitive.
5269  interface gamma2gene
5270  module procedure gamma2gene_additive_i4
5271  module procedure gamma2gene_additive_r4
5272  module procedure gamma2gene_fake_vals
5273  end interface gamma2gene
5274  ! @note Note that all component procedures are private.
5276 
5277 
5278  interface gene2gamma
5279  module procedure gamma2gene_reverse
5280  end interface gene2gamma
5281  ! @note Note that all component procedures are private.
5282  private :: gamma2gene_reverse, gene2gamma
5283 
5284  !-----------------------------------------------------------------------------
5285  !> Simple history stack function, add to the end of the stack. We need
5286  !! only to add components on top (end) of the stack and retain
5287  !! `HISTORY_SIZE_SPATIAL` elements of the prior history (for a spatial moving
5288  !! object). The stack works as follows, assuming 100 and 200 are added:
5289  !! @n [1 2 3 4 5 6 7 8 9 10]
5290  !! @n [2 3 4 5 6 7 8 9 10 **100**]
5291  !! @n [3 4 5 6 7 8 9 10 100 **200**]
5292  interface add_to_history
5293  module procedure add_to_history_i4
5294  module procedure add_to_history_r
5295  module procedure add_to_history_char
5296  end interface add_to_history
5297  ! @note Note that all component procedures are private.
5299 
5300  !-----------------------------------------------------------------------------
5301  !> @brief Convert cm to m.
5302  !! @details This is needed because some of the the sizes are expressed
5303  !! in cm but certain functions (e.g. visual range estimator SRGETR)
5304  !! require parameters in m. E.g. FOOD_ITEM_SIZE_DEFAULT is set
5305  !! around 0.5 cm while SRGETR requires prey area in m².
5306  interface cm2m
5307  module procedure cm2m_r
5308  module procedure cm2m_hr
5309  module procedure cm2m_i
5310  end interface cm2m
5311  ! @note Note that all component procedures are private.
5312  private :: cm2m_r, cm2m_hr, cm2m_i
5313 
5314  !> @brief Convert m to cm.
5315  !! @details This is needed because some of the the sizes are expressed
5316  !! in cm but certain functions (e.g. visual range estimator SRGETR)
5317  !! require parameters in m. Therefore, conversion back from visual
5318  !! range function should use these functions.
5319  interface m2cm
5320  module procedure m2cm_r
5321  module procedure m2cm_hr
5322  module procedure m2cm_i
5323  end interface m2cm
5324  ! @note Note that all component procedures are private.
5325  private :: m2cm_r, m2cm_hr, m2cm_i
5326 
5327  !> @brief Convert mm to m.
5328  !! @note This is a similar functions(s) as above sm2m, but converting mm.
5329  interface mm2m
5330  module procedure mm2m_r
5331  module procedure mm2m_i
5332  end interface mm2m
5333  ! @note Note that all component procedures are private.
5334  private :: mm2m_r, mm2m_i
5335 
5336  !> @brief Arbitrary rescales value(s) from one range (A:B) to
5337  !! another (A1:B1).
5338  !! @details Rescales values from A:B to A1:B1, or (if only A1:B1 are provided)
5339  !! from 0:1 to A1:B1.
5340  !! @note Elemental functions.
5341  interface rescale
5342  module procedure rescale_1
5343  module procedure rescale_full
5344  end interface rescale
5345  ! @note Note that all component procedures are private.
5346  private :: rescale_1, rescale_full
5347 
5348  !> Force a value within the range set by the vmin and vmax dummy parameter
5349  !! values.
5350  interface within
5351  module procedure within_i
5352  module procedure within_r
5353  end interface within
5354  ! @note Note that all component procedures are private.
5355  private :: within_i, within_r
5356 
5357  !> Logical function to check if a value is within a specific range,
5358  !! **lower <= X <= upper**.
5359  !! @note See commondata::is_within_operator_r() and
5360  !! commondata::is_within_operator_i() for a related user-defined
5361  !! operator `.within.`.
5362  interface is_within
5363  module procedure is_within_r
5364  module procedure is_within_i
5365  ! @note Note that intel fortran does not allow the same procedures
5366  ! to be placed both in generic interface and user defined operator.
5367  ! That issues this compiler error:
5368  ! The procedure name of the INTERFACE block conflicts with a
5369  ! name in the encompassing scoping unit.
5370  ! Therefore, references to is_within_operator_r and
5371  ! is_within_operator_i are disabled here.
5372  !module procedure is_within_operator_r
5373  !module procedure is_within_operator_i
5374  end interface is_within
5375  ! @note Note that all component procedures are private.
5376  private :: is_within_r, is_within_i
5377 
5378  !> Checks if a real number is near 0.0.
5379  !! Thus function can be used for comparing two real values like this:
5380  !! @code
5381  !! if ( is_near_zero(a) ) then ...
5382  !! @endcode
5383  !! See the backend procedures commondata::is_near_zero_srp() and
5384  !! commondata::is_near_zero_hrp() for details.
5385  interface is_near_zero
5386  module procedure is_near_zero_srp
5387  module procedure is_near_zero_hrp
5388  end interface is_near_zero
5389  ! @note Note that all component procedures are private.
5391 
5392  !> Check if two real values are nearly equal using the
5393  !! commondata::is_near_zero().
5394  !! Thus function can be used for comparing two real values like this:
5395  !! - The exact float comparison (incorrect due to possible rounding):
5396  !! @code
5397  !! if ( a == b ) ...
5398  !! @endcode
5399  !! - should be substituted by such comparison:
5400  !! @code
5401  !! if ( float_equal(a, b) ) ...
5402  !! @endcode
5403  !! .
5404  !! See the backend procedures commondata::float_equal_srp() and
5405  !! commondata::float_equal_hrp() for details.
5406  interface float_equal
5407  module procedure float_equal_srp
5408  module procedure float_equal_hrp
5409  end interface float_equal
5410  ! @note Note that all component procedures are private.
5411  private :: float_equal_srp, float_equal_hrp
5412 
5413  !> "Float equality" operator: Check if two real values are *nearly equal*
5414  !! using the commondata::is_near_zero() function. Thus function can be used
5415  !! for comparing two real values like the below.
5416  !! - The exact real comparison (incorrect due to possible rounding):
5417  !! @code
5418  !! if ( a == b ) ...
5419  !! @endcode
5420  !! - should be substituted by such comparison:
5421  !! @code
5422  !! if ( a .feq. b) ...
5423  !! @endcode
5424  !! .
5425  !! See the backend procedures commondata::float_equal_srp_operator() and
5426  !! commondata::float_equal_hrp_operator() for details and
5427  !! @ref intro_computation_real "Float point" for an introduction.
5428  interface operator (.feq.)
5429  procedure float_equal_srp_operator
5430  procedure float_equal_hrp_operator
5431  end interface operator (.feq.)
5432  ! @note Note that all component procedures are private.
5434 
5435  !> "Approximatel equality" operator: Check if two real values are
5436  !! *approximately equal* using the commondata::is_near_zero() function.
5437  !! Thus function can be used for comparing two real values like the below.
5438  !! - The exact real comparison (incorrect due to possible rounding):
5439  !! @code
5440  !! if ( a == b ) ...
5441  !! @endcode
5442  !! - should be substituted by such *approximately equal* comparison:
5443  !! @code
5444  !! if ( a .approx. b) ...
5445  !! @endcode
5446  !! .
5447  !! See the backend procedures commondata::float_approx_srp_operator() and
5448  !! commondata::float_approx_hrp_operator() for details and
5449  !! @ref intro_computation_real "Float point" for an introduction.
5450  !! @note This `.approx.` operator differs from the `.feq.` by a very high
5451  !! *epsilon* tolerance, that is, a much higher error
5452  !! (commondata::zero * 1000.0) is tolerated.
5453  interface operator (.approx.)
5454  procedure float_approx_srp_operator
5455  procedure float_approx_hrp_operator
5456  end interface operator (.approx.)
5457  ! @note Note that all component procedures are private.
5459 
5460  !> Interface operators `.within.` for testing whether a value (first
5461  !! argument) lies within the limits set by a two-element array (second
5462  !! argument). All the values/parameters are Fortran intrinsic types, real
5463  !! or integer. Usage of the operator:
5464  !! @code
5465  !! if ( value .within. [lower, upper] ) then
5466  !! @endcode
5467  !! See `commondata::is_within_operator_r()` and
5468  !! `commondata::is_within_operator_i()` for more details.
5469  interface operator (.within.)
5470  procedure is_within_operator_r
5471  procedure is_within_operator_i
5472  end interface operator (.within.)
5473  ! @note Note that all component procedures are private.
5475 
5476  !> Concatenate two arrays a and b. This procedure uses array slices which
5477  !! would be faster in most cases than the intrinsic `[a,b]` method.
5478  !! @code
5479  !! a .cat. b ! equivalent to [a, b]
5480  !! @endcode
5481  !! See commondata::stack2arrays_r() and commondata::stack2arrays_i() for
5482  !! details.
5483  interface operator (.cat.)
5484  procedure stack2arrays_r
5485  procedure stack2arrays_i
5486  end interface operator (.cat.)
5487  ! @note Note that all component procedures are private.
5488  private :: stack2arrays_r, stack2arrays_i
5489 
5490  !> Calculate an average of an array excluding missing code values.
5491  interface average
5492  module procedure average_r
5493  module procedure average_i
5494  end interface average
5495  ! @note Note that all component procedures are private.
5496  private :: average_r, average_i
5497 
5498  !> Check if a value is the maximum value of an array.
5499  interface is_maxval
5500  module procedure is_maxval_r
5501  module procedure is_maxval_i
5502  end interface is_maxval
5503  ! @note Note that all component procedures are private.
5504  private :: is_maxval_r, is_maxval_i
5505 
5506  !> Check if a value is the minimum value of an array.
5507  interface is_minval
5508  module procedure is_minval_r
5509  module procedure is_minval_i
5510  end interface is_minval
5511  ! @note Note that all component procedures are private.
5512  private :: is_minval_r, is_minval_i
5513 
5514  !> Interface operator `.radd.` performs a random addition or subtraction
5515  !! of two numbers with equal probability.
5516  !! See `commondata::random_add_subtract()`.
5517  !! The operator can be used as follows:
5518  !! @code
5519  !! temp_hab = a .radd. b
5520  !! @endcode
5521  !! @note Used in the correlated random Gaussian walk routines
5522  !! the_environment::corwalk()
5523  interface operator (.radd.)
5524  procedure random_add_subtract
5525  end interface operator (.radd.)
5526 ! @note Note that all component procedures are private.
5527  private :: random_add_subtract
5528 
5529  !-----------------------------------------------------------------------------
5530  !-----------------------------------------------------------------------------
5531  ! These are public access functions, but probably we don't need to allow
5532  ! public access to functions inside generic interfaces
5533  ! public :: alleleconv, allelescale, gamma2gene, gene2gamma, &
5534  ! LOG_DBG
5535  ! We do not need specific functions outside of this module, always use
5536  ! generic functions.
5538 
5539 contains !---- Various globally-used accessory subroutines and functions here --
5540 
5541  !-----------------------------------------------------------------------------
5542  !> @brief Convert cm to m.
5543  !! @param value_cm value in cm
5544  !! @returns value in m
5545  !! @note This version gets real type argument.
5546  !! @details This is needed because some of the the sizes are expressed
5547  !! in cm but certain functions (e.g. visual range estimator SRGETR)
5548  !! require parameters in m. E.g. FOOD_ITEM_SIZE_DEFAULT is set
5549  !! around 0.5 cm while SRGETR requires prey area in m².
5550  elemental function cm2m_r(value_cm) result(value_m)
5551  real(srp), intent(in) :: value_cm ! @param value_cm value in cm
5552  real(srp) :: value_m ! @returns value in m
5553  real(srp), parameter :: conv_f = 0.01_srp ! conversion factor
5554 
5555  value_m = value_cm * conv_f
5556 
5557  end function cm2m_r
5558 
5559  !-----------------------------------------------------------------------------
5560  !> @brief Convert cm to m.
5561  !! @param value_cm value in cm
5562  !! @returns value in m
5563  !! @note This version uses the **high** `HRP` numerical precision model.
5564  elemental function cm2m_hr(value_cm) result(value_m)
5565  real(hrp), intent(in) :: value_cm ! @param value_cm value in cm
5566  real(hrp) :: value_m ! @returns value in m
5567  real(hrp), parameter :: conv_f = 0.01_hrp ! conversion factor
5568 
5569  value_m = value_cm * conv_f
5570 
5571  end function cm2m_hr
5572 
5573  !-----------------------------------------------------------------------------
5574  !> @brief Convert cm to m.
5575  !! @returns value in m
5576  !! @param value_cm value in cm
5577  !! @note This version gets integer argument (albeit returns real).
5578  elemental function cm2m_i(value_cm) result(value_m)
5579  integer, intent(in) :: value_cm ! @param value_cm value in cm
5580  real(srp) :: value_m ! @returns value in m
5581  real(srp), parameter :: conv_f = 0.01_srp ! conversion factor
5582 
5583  value_m = real(value_cm, srp) * conv_f
5584 
5585  end function cm2m_i
5586 
5587  !-----------------------------------------------------------------------------
5588  !> @brief Convert m to cm.
5589  !! @param value_cm value in cm
5590  !! @returns value in m
5591  !! @note This version gets real type argument.
5592  elemental function m2cm_r(value_m) result(value_cm)
5593  real(srp), intent(in) :: value_m ! @param value_cm value in cm
5594  real(srp) :: value_cm ! @returns value in m
5595  real(srp), parameter :: conv_f = 100.0_srp ! conversion factor
5596 
5597  value_cm = value_m * conv_f
5598 
5599  end function m2cm_r
5600 
5601  !-----------------------------------------------------------------------------
5602  !> @brief Convert m to cm.
5603  !! @returns value in m
5604  !! @param value_cm value in cm
5605  !! @note This version uses the **high** `HRP` numerical precision model.
5606  elemental function m2cm_hr(value_m) result(value_cm)
5607  real(hrp), intent(in) :: value_m ! @param value_cm value in cm
5608  real(hrp) :: value_cm ! @returns value in m
5609  real(hrp), parameter :: conv_f = 100.0_hrp ! conversion factor
5610 
5611  value_cm = value_m * conv_f
5612 
5613  end function m2cm_hr
5614 
5615  !-----------------------------------------------------------------------------
5616  !> @brief Convert m to cm.
5617  !! @param value_cm value in cm
5618  !! @returns value in m
5619  !! @note This version gets integer argument (albeit returns real).
5620  elemental function m2cm_i(value_m) result(value_cm)
5621  integer, intent(in) :: value_m ! @param value_cm value in cm
5622  real(srp) :: value_cm ! @returns value in m
5623  real(srp), parameter :: conv_f = 100.0_srp ! conversion factor
5624 
5625  value_cm = real(value_m, srp) * conv_f
5626 
5627  end function m2cm_i
5628 
5629  !-----------------------------------------------------------------------------
5630  !> @brief Convert mm to m.
5631  !! @param value_cm value in cm
5632  !! @returns value in m
5633  !! @note This version gets real type argument.
5634  elemental function mm2m_r(value_mm) result(value_m)
5635  real(srp), intent(in) :: value_mm ! @param value_cm value in cm
5636  real(srp) :: value_m ! @returns value in m
5637  real(srp), parameter :: conv_f = 0.001_srp ! conversion factor
5638 
5639  value_m = value_mm * conv_f
5640 
5641  end function mm2m_r
5642 
5643  !-----------------------------------------------------------------------------
5644  !> @brief Convert mm to m.
5645  !! @param value_cm value in cm
5646  !! @returns value in m
5647  !! @note This version gets integer argument (albeit returns real).
5648  elemental function mm2m_i(value_mm) result(value_m)
5649  integer, intent(in) :: value_mm ! @param value_cm value in cm
5650  real(srp) :: value_m ! @returns value in m
5651  real(srp), parameter :: conv_f = 0.001_srp ! conversion factor
5652 
5653  value_m = real(value_mm, srp) * conv_f
5654 
5655  end function mm2m_i
5656 
5657  !-----------------------------------------------------------------------------
5658  !> @brief Calculate a circle area.
5659  !! @details Calculate the area of the circle.
5660  !! @param R circle radius.
5661  !! @note Food items are viewed as circular objects with the default
5662  !! **radius** equal to the **size** `FOOD_ITEM_SIZE_DEFAULT` or
5663  !! `FOOD_ITEM_MEAN_SIZE`.
5664  elemental function carea(R) result (area_circ)
5665  real(srp), intent(in) :: r
5666  real(srp) :: area_circ
5667 
5668  area_circ = pi * r * r
5669 
5670  end function carea
5671 
5672  !-----------------------------------------------------------------------------
5673  !> @brief A function linking **body length** with the body **area** in fish.
5674  !! @details For fish, based on the paper by O'Shea et al., 2006,
5675  !! DOI: 10.1111/j.1365-2761.2006.00728.x
5676  !! Approximate formula for the the **whole surface area** is
5677  !! @f[ S = 0.7 \cdot L^{1.9} . @f] Because the side area is 1/2
5678  !! of the total surface area (0.7 / 2 = 0.35), the function takes
5679  !! this half. So the final formula is:
5680  !! @f[ S = 0.35 \cdot L ^{1.8} . @f]
5681  elemental function length2sidearea_fish (body_length) result (side_area)
5682  real(srp), intent(in) :: body_length
5683  real(srp) :: side_area
5684 
5685  side_area = 0.35_srp * body_length ** 1.8_srp
5686 
5687  end function length2sidearea_fish
5688 
5689  !-----------------------------------------------------------------------------
5690  !> @brief Rescale a real variable with the range A:B to have the new
5691  !! range A1:B1.
5692  !! @details Linear transformation of the input value `value_in` such
5693  !! `k * value_in + beta`, where the `k` and `beta` coefficients
5694  !! are found by solving a simple linear system:
5695  !! @f$ \left\{\begin{matrix}
5696  !! A_{1}= k \cdot A + \beta; \\
5697  !! B_{1}= k \cdot B + \beta
5698  !! \end{matrix}\right. @f$. It has this solution:
5699  !! @f$ k=\frac{A_{1}-B_{1}}{A-B},
5700  !! \beta=-\frac{A_{1} \cdot B-A \cdot B_{1}}{A-B} @f$
5701  !! @warning The function does not check if `value_in` lies within [A:B].
5702  !! @note Code for wxMaxima equation solve:
5703  !! @code
5704  !! solve( [A1=A*k+b, B1=B*k+b] ,[k,b] );
5705  !! @endcode
5706  elemental function rescale_full(value_in, A, B, A1, B1) result(rescaled)
5707  real(srp), intent(in) :: value_in
5708  real(srp), intent(in) :: a, b, a1, b1
5709  real(srp) :: rescaled
5710 
5711  ! Local variables
5712  real(srp) :: ck, cb
5713 
5714  !> ### Implementation details ###
5715 
5716  !> First, find the linear coefficients `ck` and `cb`
5717  !! from the simple linear system.
5718  ck = (a1-b1) / (a-b)
5719  cb = -1.0_srp * ((a1*b - a*b1) / (a-b))
5720 
5721  !> Second, do the actual linear rescale of the input value.
5722  rescaled = value_in*ck + cb
5723 
5724  end function rescale_full
5725 
5726  !-----------------------------------------------------------------------------
5727  !> @brief Rescale a real variable with the range 0:1 to have the new
5728  !! range A1:B1.
5729  !! @warning The function does not check if `value_in` lies within [0:1].
5730  !! @note Code for wxMaxima equation solve:
5731  !! @code
5732  !! solve( [A1=0*k+b, B1=1*k+b] ,[k,b] );
5733  !! @endcode
5734  elemental function rescale_1(value_in, A1, B1) result(rescaled)
5735  real(srp), intent(in) :: value_in
5736  real(srp), intent(in) :: a1, b1
5737  real(srp) :: rescaled
5738 
5739  ! Local variables
5740  real(srp) :: ck, cb
5741 
5742  !> ### Implementation details ###
5743 
5744  !> First, find the linear coefficients `ck` and `cb`
5745  !! from the simple linear system.
5746  ck = b1 - a1
5747  cb = a1
5748 
5749  !> Second, do the actual linear rescale of the input value.
5750  rescaled = value_in*ck + cb
5751 
5752  end function rescale_1
5753 
5754  !-----------------------------------------------------------------------------
5755  !> Force a value within the range set by the vmin and vmax dummy parameter
5756  !! values. If the value is within the range, it does not change, if it
5757  !! falls outside, the output force value is obtained as
5758  !! min( max( value, FORCE_MIN ), FORCE_MAX )
5759  !! @param[in] value_in Input value for forcing transformation.
5760  !! @param[in] vmin minimum value of the force-to range (lower limit), if
5761  !! not present, a lower limit of 0.0 is used.
5762  !! @param[in] vmax maximum value of the force-to range (upper limit)
5763  !! @returns an input value forced to the range.
5764  !! @note Note that this is the **real** precision version of the
5765  !! generic `within` function.
5766  elemental function within_r(value_in, vmin, vmax) result (value_out)
5767  real(srp), intent(in) :: value_in
5768  real(srp), optional, intent(in) :: vmin
5769  real(srp), intent(in) :: vmax
5770  real(srp) :: value_out
5771 
5772  ! Local copies of optionals.
5773  real(srp) :: vmin_here
5774 
5775  ! Check optional minimum value, if absent, set to a default value 0.0.
5776  if (present(vmin)) then
5777  vmin_here = vmin
5778  else
5779  vmin_here = 0.0_srp
5780  end if
5781 
5782  value_out = min( max( value_in, vmin_here ), vmax )
5783 
5784  end function within_r
5785 
5786  !-----------------------------------------------------------------------------
5787  !> Force a value within the range set by the vmin and vmax dummy parameter
5788  !! values. If the value is within the range, it does not change, if it
5789  !! falls outside, the output force value is obtained as
5790  !! min( max( value, FORCE_MIN ), FORCE_MAX )
5791  !! @param[in] value_in Input value for forcing transformation.
5792  !! @param[in] vmin minimum value of the force-to range (lower limit), if
5793  !! not present, a lower limit of 0.0 is used.
5794  !! @param[in] vmax maximum value of the force-to range (upper limit)
5795  !! @returns an input value forced to the range.
5796  !! @note Note that this is the **integer** version of the generic
5797  !! `within` function.
5798  elemental function within_i(value_in, vmin, vmax) result (value_out)
5799  integer, intent(in) :: value_in
5800  integer, optional, intent(in) :: vmin
5801  integer, intent(in) :: vmax
5802  integer :: value_out
5803 
5804  ! Local copies of optionals.
5805  integer :: vmin_here
5806 
5807  ! Check optional minimum value, if absent, set to a default value 0.0.
5808  if (present(vmin)) then
5809  vmin_here = vmin
5810  else
5811  vmin_here = 0.0_srp
5812  end if
5813 
5814  ! Calculate the force-limit output value.
5815  value_out = min( max( value_in, vmin_here ), vmax )
5816 
5817  end function within_i
5818 
5819  !-----------------------------------------------------------------------------
5820  !> Logical function to check if a value is within a specific range,
5821  !! **lower <= X <= upper**. The reverse (upper <= x <= lower) range limits
5822  !! can also be used; a corrective adjustment is automatically made.
5823  !! @note This is the real type version.
5824  !! @note See commondata::is_within_operator_r() and
5825  !! commondata::is_within_operator_i() for a related user-defined
5826  !! operator `.within.`.
5827  !! @param[in] x the value to test
5828  !! @param[in] lower the lower limit for the range tested.
5829  !! @param[in] upper the upper limit of the range tested.
5830  !! @return Returns TRUE if `x` lies within [lower,upper] and FALSE otherwise.
5831  elemental function is_within_r (x, lower, upper) result (within_yes)
5832  real(srp), intent(in) :: x, lower, upper
5833  logical :: within_yes
5834 
5835  ! Local copies of swappable variables.
5836  real(srp) :: lower_loc, upper_loc
5837 
5838  !> First, make sure the lower bound is actually smaller than the upper
5839  !! bound. If not, swapped bounds are used to set the range: [upper,lower].
5840  if (lower < upper) then
5841  lower_loc = lower
5842  upper_loc = upper
5843  else
5844  lower_loc = upper
5845  upper_loc = lower
5846  end if
5847 
5848  if ( x >= lower_loc .and. x <= upper_loc ) then
5849  within_yes = .true.
5850  else
5851  within_yes = .false.
5852  end if
5853 
5854  end function is_within_r
5855 
5856  !-----------------------------------------------------------------------------
5857  !> Logical function to check if a value is within a specific range,
5858  !! **lower <= X <= upper**. The reverse (upper <= x <= lower) range limits
5859  !! can also be used; a corrective adjustment is automatically made.
5860  !! @note This is the integer type version.
5861  !! @note See commondata::is_within_operator_r() and
5862  !! commondata::is_within_operator_i() for a related user-defined
5863  !! operator `.within.`.
5864  !! @param[in] x the value to test
5865  !! @param[in] lower the lower limit for the range tested.
5866  !! @param[in] upper the upper limit of the range tested.
5867  !! @return Returns TRUE if `x` lies within [lower,upper] and FALSE otherwise.
5868  elemental function is_within_i (x, lower, upper) result (within_yes)
5869  integer, intent(in) :: x, lower, upper
5870  logical :: within_yes
5871 
5872  ! Local copies of swappable variables.
5873  integer :: lower_loc, upper_loc
5874 
5875  !> First, make sure the lower bound is actually smaller than the upper
5876  !! bound. If not, swapped bounds are used to set the range: [upper,lower].
5877  if (lower < upper) then
5878  lower_loc = lower
5879  upper_loc = upper
5880  else
5881  lower_loc = upper
5882  upper_loc = lower
5883  end if
5884 
5885  if ( x >= lower_loc .and. x <= upper_loc ) then
5886  within_yes = .true.
5887  else
5888  within_yes = .false.
5889  end if
5890 
5891  end function is_within_i
5892 
5893  !-----------------------------------------------------------------------------
5894  !> A wrapper function for commondata::is_within() to build a user defined
5895  !! operator. Basically, it is the same as `is_within`, but the lower and
5896  !! upper limits are set as a two-element array.
5897  !! Usage of the operator:
5898  !! @code
5899  !! if ( value .within. [lower, upper] ) then
5900  !! @endcode
5901  !! @note This is real type version of the procedure.
5902  pure function is_within_operator_r(x, limits) result (return_yesno)
5903  !> @param[in] x the value to test
5904  real(srp), intent(in) :: x
5905  !> @param[in] limits an array of two elements that sets the lower and
5906  !! upper limits for the range tested.
5907  real(srp), dimension(2), intent(in) :: limits
5908  !> @return Returns TRUE if `x` lies within [lower,upper] and FALSE
5909  !! otherwise.
5910  logical :: return_yesno
5911 
5912  !> **The implementation** just calls the real type function
5913  !! commondata::is_within_r().
5914  return_yesno = is_within_r(x, limits(1), limits(2))
5915 
5916  end function is_within_operator_r
5917 
5918  !-----------------------------------------------------------------------------
5919  !> A wrapper function for commondata::is_within() to build a user defined
5920  !! operator. Basically, it is the same as `is_within`, but the lower and
5921  !! upper limits are set as a two-element array.
5922  !! Usage of the operator:
5923  !! @code
5924  !! if ( value .within. [lower, upper] ) then
5925  !! @endcode
5926  !! @note This is an integer type version of the procedure.
5927  pure function is_within_operator_i(x, limits) result (return_yesno)
5928  !> @param[in] x the value to test
5929  integer, intent(in) :: x
5930  !> @param[in] limits an array of two elements that sets the lower and
5931  !! upper limits for the range tested.
5932  integer, dimension(2), intent(in) :: limits
5933  !> @return Returns TRUE if `x` lies within [lower,upper] and FALSE
5934  !! otherwise.
5935  logical :: return_yesno
5936 
5937  !> **The implementation** just calls the integer type function
5938  !! commondata::is_within_i().
5939  return_yesno = is_within_i(x, limits(1), limits(2))
5940 
5941  end function is_within_operator_i
5942 
5943  !-----------------------------------------------------------------------------
5944  !> Calculate an average value of a real array, excluding MISSING values.
5945  !! @param vector_in The input data vector
5946  !! @param missing_code Optional parameter setting the missing data code,
5947  !! to be excluded from the calculation of the mean.
5948  !! @param undef_ret_null Optional parameter, if TRUE, the function returns
5949  !! zero rather than undefined if the sample size is zero.
5950  !! @returns The mean value of the vector.
5951  !! @note This is a real array version.
5952  pure function average_r (array_in, missing_code, undef_ret_null) &
5953  result(mean_val)
5954 
5955  ! @param vector_in The input data vector
5956  real(srp), dimension(:), intent(in) :: array_in
5957 
5958  ! @param missing_code Optional parameter setting the missing data code,
5959  ! to be excluded from the calculation of the mean.
5960  real(srp), optional, intent(in) :: missing_code
5961 
5962  ! @param undef_ret_null Optional parameter, if TRUE, the function returns
5963  ! zero rather than undefined if the sample size is zero.
5964  logical, optional, intent(in) :: undef_ret_null
5965 
5966  ! @returns The mean value of the vector.
5967  real(srp) :: mean_val
5968 
5969  ! Local missing code.
5970  real(srp) :: missing_code_here
5971 
5972  ! Local sample size, N of valid values.
5973  integer :: count_valid
5974 
5975  ! Big arrays can result in huge sum values, to accommodate them,
5976  ! use commondata::hrp and commondata::long types
5977  real(hrp) :: bigsum, bigmean
5978 
5979  !> ### Implementation details ###
5980 
5981  !> Check if missing data code is provided from dummy input.
5982  !! If not, use global parameter.
5983  if (present(missing_code)) then
5984  missing_code_here = missing_code
5985  else
5986  missing_code_here = missing
5987  end if
5988 
5989  !> Fist, count how many valid values are there in the array.
5990  count_valid = count(array_in /= missing_code_here)
5991 
5992  !> If there are no valid values in the array, mean is undefined.
5993  if (count_valid==0) then
5994  if (present(undef_ret_null)) then
5995  if (undef_ret_null) then
5996  mean_val = 0.0_srp !> still return zero if undef_ret_null is TRUE.
5997  else
5998  mean_val = missing
5999  end if
6000  else
6001  mean_val = missing
6002  end if
6003  return
6004  end if
6005 
6006  bigsum = sum( real(array_in, hrp), array_in /= missing_code_here )
6007  bigmean = bigsum / count_valid
6008 
6009  mean_val = real(bigmean, srp)
6010 
6011  end function average_r
6012 
6013  !-----------------------------------------------------------------------------
6014  !> Calculate an average value of an integer array, excluding MISSING values.
6015  !! @returns The mean value of the vector
6016  !! @param vector_in The input data vector
6017  !! @param missing_code Optional parameter setting the missing data code,
6018  !! to be excluded from the calculation of the mean.
6019  !! @param undef_ret_null Optional parameter, if TRUE, the function returns
6020  !! zero rather than undefined if the sample size is zero.
6021  !! @note This is an integer array version.
6022  pure function average_i (array_in, missing_code, undef_ret_null) &
6023  result(mean_val)
6024 
6025  ! @param vector_in The input data vector
6026  integer, dimension(:), intent(in) :: array_in
6027 
6028  ! @param missing_code Optional parameter setting the missing data code,
6029  ! to be excluded from the calculation of the mean.
6030  integer, optional, intent(in) :: missing_code
6031 
6032  ! @param undef_ret_null Optional parameter, if TRUE, the function returns
6033  ! zero rather than undefined if the sample size is zero.
6034  logical, optional, intent(in) :: undef_ret_null
6035 
6036  ! @returns The mean value of the vector
6037  real(srp) :: mean_val
6038 
6039  ! Local missing code
6040  integer :: missing_code_here
6041 
6042  ! Local sample size, N of valid values.
6043  integer :: count_valid
6044 
6045  ! Big arrays can result in huge sum values, to accommodate them,
6046  ! use commondata::hrp and commondata::long types
6047  integer(LONG) :: bigsum
6048  real(hrp) :: bigmean
6049 
6050  !> ### Implementation details ###
6051 
6052  !> Check if missing data code is provided from dummy input.
6053  !! If not, use global parameter.
6054  if (present(missing_code)) then
6055  missing_code_here = missing_code
6056  else
6057  missing_code_here = unknown
6058  end if
6059 
6060  !> Fist, count how many valid values are there in the array.
6061  count_valid = count(array_in /= missing_code_here)
6062 
6063  !> If there are no valid values in the array, mean is undefined.
6064  if (count_valid==0) then
6065  if (present(undef_ret_null)) then
6066  if (undef_ret_null) then
6067  mean_val = 0.0_srp !> still return zero if undef_ret_null is TRUE.
6068  else
6069  mean_val = missing
6070  end if
6071  else
6072  mean_val = missing
6073  end if
6074  return
6075  end if
6076 
6077  bigsum = sum( int(array_in, long), array_in /= missing_code_here )
6078  bigmean = real(bigsum, hrp) / real(count_valid, hrp)
6079 
6080  mean_val = real(bigmean, srp)
6081 
6082  end function average_i
6083 
6084  !-----------------------------------------------------------------------------
6085  !> Calculate standard deviation using trivial formula:
6086  !! @f[ \sigma=\sqrt{\frac{\sum (x-\overline{x})^{2}}{N-1}} . @f]
6087  !! @note This is a real array version.
6088  function std_dev(array_in, missing_code, undef_ret_null) result (stddev)
6089  !> @param vector_in The input data vector
6090  real(srp), dimension(:), intent(in) :: array_in
6091  !> @param missing_code Optional parameter setting the missing data code,
6092  !! to be excluded from the calculation of the mean.
6093  real(srp), optional, intent(in) :: missing_code
6094  !> @param undef_ret_null Optional parameter, if TRUE, the function returns
6095  !! zero rather than undefined if the sample size is zero.
6096  logical, optional, intent(in) :: undef_ret_null
6097  !> @returns The standard deviation of the data vector.
6098  real(srp) :: stddev
6099 
6100  ! Local missing code.
6101  real(srp) :: missing_code_here
6102 
6103  ! Local sample size, N of valid values.
6104  integer :: count_valid
6105 
6106  ! Minimum sample size resulting in real calculation, everythin less
6107  ! than this returns invalid.
6108  integer, parameter :: min_n = 4
6109 
6110  ! An array of squared deviations
6111  real(srp), dimension(size(array_in)) :: dev2
6112 
6113  ! Mean value
6114  real(srp) :: sample_mean
6115 
6116  !> Check if missing data code is provided from dummy input.
6117  !! If not, use global parameter.
6118  if (present(missing_code)) then
6119  missing_code_here = missing_code
6120  else
6121  missing_code_here = missing
6122  end if
6123 
6124  count_valid = count(array_in /= missing_code_here)
6125 
6126  !> If there are no valid values in the array, std. dev. is undefined.
6127  if (count_valid < min_n) then
6128  if (present(undef_ret_null)) then
6129  if (undef_ret_null) then
6130  stddev = 0.0_srp !> still return zero if undef_ret_null is TRUE.
6131  else
6132  stddev = missing
6133  end if
6134  else
6135  stddev = missing
6136  end if
6137  return
6138  end if
6139 
6140  sample_mean = average( array_in, missing_code_here )
6141 
6142  where ( array_in /= missing_code_here )
6143  dev2 = ( array_in - sample_mean ) ** 2
6144  elsewhere
6145  dev2 = missing_code_here
6146  end where
6147 
6148  stddev = sqrt( sum( dev2, dev2 /= missing_code_here ) / (count_valid - 1) )
6149 
6150  end function std_dev
6151 
6152  !-----------------------------------------------------------------------------
6153  !> Concatenate two arrays a and b. This procedure uses array slices which
6154  !! would be faster in most cases than the intrinsic `[a,b]` method.
6155  !> @note This is the **real** type version.
6156  pure function stack2arrays_r(a, b) result (c)
6157  !> param[in] a first array
6158  real(srp), intent(in), dimension(:) :: a
6159  !> param[in] b second array
6160  real(srp), intent(in), dimension(:) :: b
6161  !> return an array [a, b]
6162  real(srp), dimension(:), allocatable :: c
6163 
6164  allocate(c(size(a)+size(b)))
6165  c(1:size(a)) = a
6166  c(size(a)+1:size(a)+size(b)) = b
6167  ! The easier method using intrinsic array joining [a, b] is probably slower.
6168 
6169  end function stack2arrays_r
6170 
6171  !-----------------------------------------------------------------------------
6172  !> Concatenate two arrays a and b. This procedure uses array slices which
6173  !! would be faster in most cases than the intrinsic `[a,b]` method.
6174  !> @note This is the **real** type version.
6175  pure function stack2arrays_i(a, b) result (c)
6176  !> param[in] a first array
6177  integer, intent(in), dimension(:) :: a
6178  !> param[in] b second array
6179  integer, intent(in), dimension(:) :: b
6180  !> return an array [a, b]
6181  integer, dimension(:), allocatable :: c
6182 
6183  allocate(c(size(a)+size(b)))
6184  c(1:size(a)) = a
6185  c(size(a)+1:size(a)+size(b)) = b
6186  ! The easier method using intrinsic array joining [a, b] is probably slower.
6187 
6188  end function stack2arrays_i
6189 
6190 
6191  !-----------------------------------------------------------------------------
6192  !> Checks if a real number is near 0.0.
6193  !! Thus function can be used for comparing two real values like the below.
6194  !! @code
6195  !! if ( is_near_zero(a) ) then ...
6196  !! @endcode
6197  !! @note Note that commondata::float_equal() can be used for approximate real
6198  !! comparisons of two real type values.
6199  !! @note Modified from `Near0_dp()` function from Clerman & Spector 2012,
6200  !! p. 250-251.
6201  !! @note This is the **standard** precision function (commondata::srp).
6202  elemental function is_near_zero_srp(test_number, epsilon) result (ret_val)
6203  !> @param[in] test_number the number to check for being near-zero.
6204  real(srp), intent (in) :: test_number
6205  !> @param[in] epsilon optional (very small) tolerance value.
6206  real(srp), intent (in), optional :: epsilon
6207  !> @return TRUE if the `test_number` is near-zero.
6208  logical :: ret_val
6209 
6210  real(kind(epsilon)) :: local_epsilon
6211  local_epsilon = tolerance_low_def_srp
6212 
6213  if ( present(epsilon) ) then
6214  if ( abs(epsilon) >= tiny_srp ) local_epsilon = abs(epsilon)
6215  end if
6216 
6217  ret_val = abs(test_number) < local_epsilon
6218 
6219  end function is_near_zero_srp
6220 
6221  !-----------------------------------------------------------------------------
6222  !> Checks if a real number is near 0.0.
6223  !! Thus function can be used for comparing two real values like the below.
6224  !! @code
6225  !! if ( is_near_zero(a) ) then ...
6226  !! @endcode
6227  !! @note Note that commondata::float_equal() can be used for approximate real
6228  !! comparisons of two real type values.
6229  !! @note Modified from `Near0_dp()` function from Clerman & Spector 2012,
6230  !! p. 250-251.
6231  !! @note This is the **high** precision function (commondata::hrp).
6232  elemental function is_near_zero_hrp(test_number, epsilon) result (ret_val)
6233  !> @param[in] test_number the number to check for being near-zero.
6234  real(hrp), intent (in) :: test_number
6235  !> @param[in] epsilon optional (very small) tolerance value.
6236  real(hrp), intent (in), optional :: epsilon
6237  !> @return TRUE if the `test_number` is near-zero.
6238  logical :: ret_val
6239 
6240  real(kind(epsilon)) :: local_epsilon
6241  local_epsilon = tolerance_low_def_hrp
6242 
6243  if ( present(epsilon) ) then
6244  if ( abs(epsilon) >= tiny_hrp ) local_epsilon = abs(epsilon)
6245  end if
6246 
6247  ret_val = abs(test_number) < local_epsilon
6248 
6249  end function is_near_zero_hrp
6250 
6251  !-----------------------------------------------------------------------------
6252  !> Check if two real values are nearly equal using the
6253  !! commondata::is_near_zero().
6254  !! Thus function can be used for comparing two real values like the below.
6255  !! The exact comparison (incorrect due to possible rounding):
6256  !! @code
6257  !! if ( a == b ) ...
6258  !! @endcode
6259  !! should be substituted by such comparison:
6260  !! @code
6261  !! if ( float_equal(a, b, 0.00001) ) ...
6262  !! @endcode
6263  !! There is also a user defined operator `.feq.` for approximate float point
6264  !! equality. It differs from this function in that the later allows to set
6265  !! an arbitrary epsilon tolerance value whereas the operator does not (it
6266  !! uses the default epsilon based on the intrinsic `tiny()` function.
6267  !! @note This is the **standard** precision function (commondata::srp).
6268  elemental function float_equal_srp(value1, value2, epsilon) result (equal)
6269  !> @param[in] value1 The first value for comparison.
6270  real(srp), intent(in) :: value1
6271  !> @param[in] value2 The second value for comparison.
6272  real(srp), intent(in) :: value2
6273  !> @param[in] epsilon optional (very small) tolerance value.
6274  real(srp), intent (in), optional :: epsilon
6275  !> @return TRUE if the values `value1` and `value2` are nearly equal.
6276  logical :: equal
6277 
6278  real(kind(epsilon)) :: local_epsilon
6279  local_epsilon = tolerance_low_def_srp
6280 
6281  if ( present(epsilon) ) then
6282  if ( abs(epsilon) >= tiny_srp ) local_epsilon = abs(epsilon)
6283  end if
6284 
6285  equal = is_near_zero( abs(value1 - value2), local_epsilon )
6286 
6287  end function float_equal_srp
6288 
6289  !-----------------------------------------------------------------------------
6290  !> Check if two real values are nearly equal using the
6291  !! commondata::is_near_zero().
6292  !! Thus function can be used for comparing two real values like the below.
6293  !! The exact comparison (incorrect due to possible rounding):
6294  !! @code
6295  !! if ( a == b ) ...
6296  !! @endcode
6297  !! should be substituted by such comparison:
6298  !! @code
6299  !! if ( float_equal(a, b, 0.00001) ) ...
6300  !! @endcode
6301  !! There is also a user defined operator `.feq.` for approximate float point
6302  !! equality. It differs from this function in that the later allows to set
6303  !! an arbitrary epsilon tolerance value whereas the operator does not (it
6304  !! uses the default epsilon based on the intrinsic `tiny()` function.
6305  !! @note This is the **high** precision function (commondata::hrp).
6306  elemental function float_equal_hrp(value1, value2, epsilon) result (equal)
6307  !> @param[in] value1 The first value for comparison.
6308  real(hrp), intent(in) :: value1
6309  !> @param[in] value2 The second value for comparison.
6310  real(hrp), intent(in) :: value2
6311  !> @param[in] epsilon optional (very small) tolerance value.
6312  real(hrp), intent (in), optional :: epsilon
6313  !> @return TRUE if the values `value1` and `value2` are nearly equal.
6314  logical :: equal
6315 
6316  real(kind(epsilon)) :: local_epsilon
6317  local_epsilon = tolerance_low_def_hrp
6318 
6319  if ( present(epsilon) ) then
6320  if ( abs(epsilon) >= tiny_hrp ) local_epsilon = abs(epsilon)
6321  end if
6322 
6323  equal = is_near_zero( abs(value1 - value2), local_epsilon )
6324 
6325  end function float_equal_hrp
6326 
6327  !-----------------------------------------------------------------------------
6328  !> This is a wrapper for the commondata::float_equal_srp() for building
6329  !! the user defined operator `.feq.` with default tolerance
6330  !! (`epsilon` parameter).
6331  !! The exact real comparison (incorrect due to possible rounding):
6332  !! @code
6333  !! if ( a == b ) ...
6334  !! @endcode
6335  !! should be substituted by such comparison:
6336  !! @code
6337  !! if ( a .feq. b) ...
6338  !! @endcode
6339  !! @warning This function is not intended for direct use.
6340  elemental function float_equal_srp_operator(value1, value2) result (equal)
6341  !> @param[in] value1 The first value for comparison.
6342  real(srp), intent(in) :: value1
6343  !> @param[in] value2 The second value for comparison.
6344  real(srp), intent(in) :: value2
6345  !> @return TRUE if the values `value1` and `value2` are nearly equal.
6346  logical :: equal
6347  ! EPSILON_LOC sets the tolerance limit for the default .feq. operator.
6348  real(srp), parameter :: epsilon_loc = tolerance_low_def_srp
6349  equal = is_near_zero( abs(value1 - value2), epsilon_loc )
6350  end function float_equal_srp_operator
6351 
6352  !-----------------------------------------------------------------------------
6353  !> This is a wrapper for the commondata::float_equal_hrp() for building
6354  !! the user defined operator `.feq.` with default tolerance
6355  !! (`epsilon` parameter).
6356  !! The exact real comparison (incorrect due to possible rounding):
6357  !! @code
6358  !! if ( a == b ) ...
6359  !! @endcode
6360  !! should be substituted by such comparison:
6361  !! @code
6362  !! if ( a .feq. b) ...
6363  !! @endcode
6364  !! @warning This function is not intended for direct use.
6365  elemental function float_equal_hrp_operator(value1, value2) result (equal)
6366  !> @param[in] value1 The first value for comparison.
6367  real(hrp), intent(in) :: value1
6368  !> @param[in] value2 The second value for comparison.
6369  real(hrp), intent(in) :: value2
6370  !> @return TRUE if the values `value1` and `value2` are nearly equal.
6371  logical :: equal
6372  ! EPSILON_LOC sets the tolerance limit for the default .feq. operator.
6373  real(hrp), parameter :: epsilon_loc = tolerance_low_def_hrp
6374  equal = is_near_zero( abs(value1 - value2), epsilon_loc )
6375  end function float_equal_hrp_operator
6376 
6377  !-----------------------------------------------------------------------------
6378  !> This is a wrapper for the commondata::float_equal_srp() for building
6379  !! the user defined operator `.approx.` with **very high** tolerance
6380  !! (`epsilon` parameter).
6381  !! The exact real comparison (incorrect due to possible rounding):
6382  !! @code
6383  !! if ( a == b ) ...
6384  !! @endcode
6385  !! should be substituted by such comparison:
6386  !! @code
6387  !! if ( a .approx. b) ...
6388  !! @endcode
6389  !! @warning This function is not intended for direct use.
6390  elemental function float_approx_srp_operator(value1, value2) result (equal)
6391  !> @param[in] value1 The first value for comparison.
6392  real(srp), intent(in) :: value1
6393  !> @param[in] value2 The second value for comparison.
6394  real(srp), intent(in) :: value2
6395  !> @return TRUE if the values `value1` and `value2` are approximately equal.
6396  logical :: equal
6397  ! EPSILON_LOC sets the tolerance limit for the default `.approx.` operator.
6398  ! @note Note that tolerance value here is very high.
6399  real(srp), parameter :: epsilon_loc = tolerance_high_def_srp
6400  equal = is_near_zero( abs(value1 - value2), epsilon_loc )
6401  end function float_approx_srp_operator
6402 
6403  !-----------------------------------------------------------------------------
6404  !> This is a wrapper for the commondata::float_equal_hrp() for building
6405  !! the user defined operator `.approx.` with **very high** tolerance
6406  !! (`epsilon` parameter).
6407  !! The exact real comparison (incorrect due to possible rounding):
6408  !! @code
6409  !! if ( a == b ) ...
6410  !! @endcode
6411  !! should be substituted by such comparison:
6412  !! @code
6413  !! if ( a .approx. b) ...
6414  !! @endcode
6415  !! @warning This function is not intended for direct use.
6416  elemental function float_approx_hrp_operator(value1, value2) result (equal)
6417  !> @param[in] value1 The first value for comparison.
6418  real(hrp), intent(in) :: value1
6419  !> @param[in] value2 The second value for comparison.
6420  real(hrp), intent(in) :: value2
6421  !> @return TRUE if the values `value1` and `value2` are approximately equal.
6422  logical :: equal
6423  ! EPSILON_LOC sets the tolerance limit for the default `.approx.` operator.
6424  ! @note Note that tolerance value here is very high.
6425  real(hrp), parameter :: epsilon_loc = tolerance_high_def_hrp
6426  equal = is_near_zero( abs(value1 - value2), epsilon_loc )
6427  end function float_approx_hrp_operator
6428 
6429  !-----------------------------------------------------------------------------
6430  !> Sanitize a real commondata::srp array, so that any value that is smaller
6431  !! than the minimum sensible value `lvalid` or greater then the maximum
6432  !! sensible value `hvalid` is substituted with `substval`.
6433  !! The procedure also checks the input value for IEEE validity: overflow,
6434  !! underflow, invalid and inexact.
6435  !! @note Note that commondata::do_sanitise() makes use the IEEE math
6436  !! procedures to handle halting on invalid values.
6437  subroutine do_sanitise( array, lvalid, hvalid, substval, only_wrong, tnote )
6438  !> ### Implementation notes ###
6439  !> The automatically generated IEEE wrapper `include "IEEE_wrap.inc`
6440  !! is used to invoke intrinsic or non-intrinsic IEEE math modules.
6441  !! If the compiler support intrinsic modules, this can be changed to
6442  !! @code
6443  !! use, intrinsic :: IEEE_ARITHMETIC
6444  !! use, intrinsic :: IEEE_EXCEPTIONS
6445  !! @endcode
6446  !! @warning Note that IEEE routines cannot be used in pure procedures.
6447  include "IEEE_wrap.inc"
6448  !> @param[inout] array the array to be sanitised
6449  real(SRP), intent(inout), dimension(:) :: array
6450  !> Optional lower valid boundary, default is set to
6451  !! commondata::lo_valid_sanitised
6452  real(SRP), intent(in), optional :: lvalid
6453  !> Optional higher valid boundary, default is set to
6454  !! commondata::hi_valid_sanitised
6455  real(SRP), intent(in), optional :: hvalid
6456  !> Optional substitution value, default is
6457  !! commondata::missing
6458  real(SRP), intent(in), optional :: substval
6459  !> Optional flag to correct only invalid values (`Nan`, `Inf`) without
6460  !! range correction (`lvalid`, `hvalid`), default value is FALSE, i.e.
6461  !! to correct for range (`lvalid` to `hvalid`)
6462  logical, intent(in), optional :: only_wrong
6463  !> Optional text note that is printed in case of IEEE error signalling
6464  !! to assist in the identification of the specific place in the code.
6465  character(len=*), optional, intent(in) :: tnote
6466 
6467  ! Local copies of optionals
6468  real(SRP) :: lvalid_loc, hvalid_loc, substval_loc
6469 
6470  ! Local infinity/error constants from IEEE_ARITHMETIC module
6471  real(SRP) :: INFINITY_POS, INFINITY_NEG, NAN_QUIET
6472 
6473  ! IEEE math flags
6474  logical :: ieee_def_mode_overflow, &
6475  ieee_def_mode_underflow, &
6476  ieee_def_mode_invalid, &
6477  ieee_def_mode_inexact
6478 
6479  ! IEEE error flag obtained
6480  logical :: ieee_get
6481 
6482  ! Local copies of optionals
6483  logical :: fix_only_wrong
6484  character(len=:), allocatable :: tnote_loc
6485 
6486  ! IEEE error code from ::ieee_error_reporting()
6487  integer :: ieee_report_except
6488 
6489  character(len=*), parameter :: PROCNAME = "(do_sanitise)"
6490 
6491  ! IEEE: Get default IEEE halting mode and save for later reset
6492  call ieee_get_halting_mode(ieee_overflow, ieee_def_mode_overflow)
6493  call ieee_get_halting_mode(ieee_underflow, ieee_def_mode_underflow)
6494  call ieee_get_halting_mode(ieee_invalid, ieee_def_mode_invalid)
6495  call ieee_get_halting_mode(ieee_inexact, ieee_def_mode_inexact)
6496  ! IEEE: From now on disable IEEE halting
6497  call ieee_set_halting_mode(ieee_overflow, .false.)
6498  call ieee_set_halting_mode(ieee_underflow, .false.)
6499  call ieee_set_halting_mode(ieee_invalid, .false.)
6500  call ieee_set_halting_mode(ieee_inexact, .false.)
6501 
6502  if (present(lvalid)) then
6503  lvalid_loc = lvalid
6504  else
6505  lvalid_loc = lo_valid_sanitised
6506  end if
6507 
6508  if (present(hvalid)) then
6509  hvalid_loc = hvalid
6510  else
6511  hvalid_loc = hi_valid_sanitised
6512  end if
6513 
6514  if (present(substval)) then
6515  substval_loc = substval
6516  else
6517  substval_loc = missing
6518  end if
6519 
6520  if (present(only_wrong)) then
6521  fix_only_wrong = only_wrong
6522  else
6523  fix_only_wrong = .false.
6524  end if
6525 
6526  if (present(tnote)) then
6527  tnote_loc = tnote
6528  else
6529  tnote_loc = ""
6530  end if
6531 
6532  ! Set the IEEE infinity/error constants from
6533  infinity_pos = ieee_value(0.0_srp, ieee_positive_inf)
6534  infinity_neg = ieee_value(0.0_srp, ieee_negative_inf)
6535  nan_quiet = ieee_value(0.0_srp, ieee_quiet_nan)
6536 
6537  ! Report possible IEEE error in the logger and reset error flag
6538  ieee_report_except = ieee_error_reporting(reset=.true., tnote=tnote_loc)
6539  if ( ieee_report_except == 0 ) then
6540  call log_dbg( ltag_info // "No IEEE exceptions reported " // tnote_loc )
6541  end if
6542  ! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6543  !> The input array is checked for wrong values: `NaN`, `Inf+` and `Inf-`.
6544  !! Any invalid values are substituted by the `substval` or ::missing if
6545  !! that is not defined.
6546  ! IEEE: Note that NaN checks if a value is not equal to itself
6547  ! @note isnan() is GNU extension and can be emulated by `array /= array`
6548  ! (i.e. value is unequal to itself). IEEE_IS_NAN() is standard
6549  ! IEEE function but might not be supported on all compilers/platforms
6550  where ( ieee_is_nan(array) ) array = substval_loc
6551  where ( array == infinity_pos ) array = substval_loc
6552  where ( array == infinity_neg ) array = substval_loc
6553  if (fix_only_wrong .eqv. .false.) &
6554  where ( array < lvalid_loc .or. array > hvalid_loc ) array = substval_loc
6555 
6556  ! IEEE: restore default IEEE halting mode
6557  call ieee_set_halting_mode(ieee_overflow, ieee_def_mode_overflow)
6558  call ieee_set_halting_mode(ieee_underflow, ieee_def_mode_underflow)
6559  call ieee_set_halting_mode(ieee_invalid, ieee_def_mode_invalid)
6560  call ieee_set_halting_mode(ieee_inexact, ieee_def_mode_inexact)
6561 
6562  end subroutine do_sanitise
6563 
6564  !-----------------------------------------------------------------------------
6565  !> Check if an IEEE error condition has occurred.
6566  !> @param[in] reset Logical flag requesting to reset any exceptions that
6567  !! are found (if set to TRUE), default value is TRUE. IEEE exception
6568  !! condition will not be reset if `reset` is `FALSE`.
6569  !! @returns integer IEEE Error code or null if there is no error condition.
6570  !! @verbatim
6571  !! IS_OVERFLOW=101,
6572  !! IS_UNDERFLOW=102,
6573  !! IS_INVALID=103,
6574  !! IS_INEXACT=104,
6575  !! IS_DIVBYZERO=105,
6576  !! NO_SUPPORT_OVERFLOW=901,
6577  !! NO_SUPPORT_UNDERFLOW=902,
6578  !! NO_SUPPORT_INVALID=903,
6579  !! NO_SUPPORT_INEXACT=904,
6580  !! NO_SUPPORT_DIVBYZERO=905,
6581  !! NO_ERROR_FLAG=0
6582  !! @endverbatim
6583  function ieee_error_reporting( reset, tnote ) result (error_code)
6584  !> ### Implementation notes ###
6585  !! The automatically generated IEEE wrapper `include "IEEE_wrap.inc`
6586  !! is used to invoke intrinsic or non-intrinsic IEEE math modules.
6587  !! If the compiler support intrinsic modules, this can be changed to
6588  !! @code
6589  !! use, intrinsic :: IEEE_ARITHMETIC
6590  !! use, intrinsic :: IEEE_EXCEPTIONS
6591  !! @endcode
6592  !! @warning Note that IEEE routines cannot be used in pure procedures.
6593  include "IEEE_wrap.inc"
6594  integer :: error_code
6595  ! Logical flag requesting to reset any exception that is found (if set
6596  ! to TRUE), default value is TRUE. IEEE exception condition will not be
6597  ! reset if `reset` is `FALSE`.
6598  logical, optional, intent(in) :: reset
6599  !> Optional text note that is printed in case of IEEE error signalling
6600  !! to assist in the identification of the specific place in the code.
6601  character(len=*), optional, intent(in) :: tnote
6602 
6603  ! Local copies of optional parameters
6604  logical :: reset_loc
6605  character(len=:), allocatable :: tnote_loc
6606 
6607  character(len=*), parameter :: procname = "(ieee_error_reporting)"
6608 
6609  ! Set return codes for the function, they are necessary because the values
6610  ! defined in intrinsic (or non-intrinsic) IEEE modules may be unavailable
6611  ! to the calling program unit.
6612  integer, parameter :: is_overflow=101, &
6613  is_underflow=102, &
6614  is_invalid=103, &
6615  is_inexact=104, &
6616  is_divbyzero=105, &
6617  no_support_overflow=901, &
6618  no_support_underflow=902, &
6619  no_support_invalid=903, &
6620  no_support_inexact=904, &
6621  no_support_divbyzero=905, &
6622  no_error_flag=0
6623 
6624  ! IEEE error flag obtained
6625  logical :: ieee_get
6626 
6627  if (present(reset)) then
6628  reset_loc = reset
6629  else
6630  reset_loc = .true.
6631  end if
6632 
6633  error_code = no_error_flag
6634 
6635  ! Set the text note
6636  if (present(tnote)) then
6637  tnote_loc = tnote
6638  else
6639  tnote_loc = modname
6640  end if
6641 
6642  ! Report possible IEEE error in the logger and reset error flag
6643  if ( ieee_support_datatype(1.0_srp) .and. &
6644  ieee_support_halting(ieee_overflow) ) then
6645  call ieee_get_flag (ieee_overflow, ieee_get)
6646  if (ieee_get) then
6647  error_code = is_overflow
6648  call log_msg( ltag_error // procname // ";" // tnote_loc // &
6649  ": IEEE_OVERFLOW is signalled!" )
6650  if (reset_loc) call ieee_set_flag (ieee_overflow, .false.)
6651  end if
6652  else
6653  error_code = no_support_overflow
6654  call log_msg( ltag_warn //procname // ";" // tnote_loc // &
6655  ": IEEE_OVERFLOW NOT supported for SRP " // tostr(srp) )
6656  end if
6657 
6658  if ( ieee_support_datatype(1.0_srp) .and. &
6659  ieee_support_halting(ieee_underflow) ) then
6660  call ieee_get_flag (ieee_underflow, ieee_get)
6661  if (ieee_get) then
6662  error_code = is_underflow
6663  call log_msg( ltag_error // procname // ";" // tnote_loc // &
6664  ": IEEE_UNDERFLOW is signalled!" )
6665  if (reset_loc) call ieee_set_flag (ieee_underflow, .false.)
6666  end if
6667  else
6668  error_code = no_support_underflow
6669  call log_msg( ltag_warn //procname // ";" // tnote_loc // &
6670  ": IEEE_UNDERFLOW NOT supported for SRP " // tostr(srp) )
6671  end if
6672 
6673  if ( ieee_support_datatype(1.0_srp) .and. &
6674  ieee_support_halting(ieee_invalid) ) then
6675  call ieee_get_flag (ieee_invalid, ieee_get)
6676  if (ieee_get) then
6677  error_code = is_invalid
6678  call log_msg( ltag_error // procname // ";" // tnote_loc // &
6679  ": IEEE_INVALID is signalled!" )
6680  if (reset_loc) call ieee_set_flag (ieee_invalid, .false.)
6681  end if
6682  else
6683  error_code = no_support_invalid
6684  call log_msg( ltag_warn //procname // ";" // tnote_loc // &
6685  ": IEEE_INVALID NOT supported for SRP " // tostr(srp) )
6686  end if
6687 
6688  !if ( IEEE_SUPPORT_DATATYPE(1.0_SRP) .and. &
6689  ! IEEE_SUPPORT_HALTING(IEEE_INEXACT) ) then
6690  ! call IEEE_GET_FLAG (IEEE_INEXACT, ieee_get)
6691  ! if (ieee_get) then
6692  ! error_code = IS_INEXACT
6693  ! call LOG_MSG( LTAG_ERROR // PROCNAME // ";" // tnote_loc // &
6694  ! ": IEEE_INEXACT is signalled!" )
6695  ! if (reset_loc) call IEEE_SET_FLAG (IEEE_INEXACT, .FALSE.)
6696  ! end if
6697  !else
6698  ! error_code = NO_SUPPORT_INEXACT
6699  ! call LOG_MSG( LTAG_WARN //PROCNAME // ";" // tnote_loc // &
6700  ! ": IEEE_INEXACT NOT supported for SRP " // TOSTR(SRP) )
6701  !end if
6702 
6703  if ( ieee_support_datatype(1.0_srp) .and. &
6704  ieee_support_halting(ieee_divide_by_zero) ) then
6705  call ieee_get_flag (ieee_divide_by_zero, ieee_get)
6706  if (ieee_get) then
6707  error_code = is_divbyzero
6708  call log_msg( ltag_error // procname // ";" // tnote_loc // &
6709  ": IEEE_DIVIDE_BY_ZERO is signalled!" )
6710  if (reset_loc) call ieee_set_flag (ieee_divide_by_zero, .false.)
6711  end if
6712  else
6713  error_code = no_support_divbyzero
6714  call log_msg( ltag_warn //procname // ";" // tnote_loc // &
6715  ": IEEE_DIVIDE_BY_ZERO NOT supported for SRP "//tostr(srp))
6716  end if
6717 
6718  end function ieee_error_reporting
6719 
6720  !-----------------------------------------------------------------------------
6721  !> This function calculates a zero of a function f(x) in the interval
6722  !! (ax,bx).
6723  !! - Brent, R.P., (1973). Algorithms for Minimization Without
6724  !! Derivatives, Prentice-Hall, Inc.
6725  !! - Brent, R.P. (1971). An algorithm with guaranteed convergence for
6726  !! finding a zero of a function, Computer J. 14, 422–425.
6727  !! .
6728  !! Author: Richard Brent, https://maths-people.anu.edu.au/~brent/
6729  !! Source: http://www.netlib.org/go/
6730  !! With some minor changes by Sergey Budaev.
6731  !! @note This function is used in
6732  !! the_environment::minimum_depth_visibility().
6733  !> @param[in] ax left endpoint of initial interval
6734  !> @param[in] bx right endpoint of initial interval
6735  !> @param[in] f function subprogram which evaluates f(x) for any x in
6736  !! the interval (ax,bx).
6737  !> @param[in] tol desired length of the interval of uncertainty of the
6738  !! final result (.ge.0.)
6739  !! @returns Abscissa approximating a zero of f(x) in the
6740  !! interval (ax,bx). Note that this function returns
6741  !! commondata::missing if f(ax) and f(bx) do not have
6742  !! different signs (so there is no function zero within the
6743  !! range).
6744  real(srp) function zeroin(ax,bx,f,tol)
6745  ! @param[in] ax left endpoint of initial interval
6746  ! @param[in] bx right endpoint of initial interval
6747  ! @param[in] f function subprogram which evaluates f(x) for any x in
6748  ! the interval (ax,bx).
6749  ! @param[in] tol desired length of the interval of uncertainty of the
6750  ! final result (.ge.0.)
6751  ! @returns abscissa approximating a zero of f(x) in the
6752  ! interval (ax,bx). Note that this function returns
6753  ! commondata::missing if f(ax) and f(bx) do not have
6754  ! different signs (so there is no function zero within the
6755  ! range).
6756  real(srp), intent(in) :: ax,bx,tol
6757  real(srp) :: f
6758  !
6759  ! a zero of the function f(x) is computed in the interval ax,bx .
6760  !
6761  ! input..
6762  !
6763  ! ax left endpoint of initial interval
6764  ! bx right endpoint of initial interval
6765  ! f function subprogram which evaluates f(x) for any x in
6766  ! the interval ax,bx
6767  ! tol desired length of the interval of uncertainty of the
6768  ! final result (.ge.0.)
6769  !
6770  ! output..
6771  !
6772  ! zeroin abscissa approximating a zero of f in the interval ax,bx
6773  !
6774  ! it is assumed that f(ax) and f(bx) have opposite signs
6775  ! this is checked, and an error message is printed if this is not
6776  ! satisfied. zeroin returns a zero x in the given interval
6777  ! ax,bx to within a tolerance 4*macheps*abs(x)+tol, where macheps is
6778  ! the relative machine precision defined as the smallest representable
6779  ! number such that 1.+macheps .gt. 1.
6780  ! this function subprogram is a slightly modified translation of
6781  ! the algol 60 procedure zero given in Richard Brent, Algorithms for
6782  ! Minimization Without Derivatives, Prentice-Hall, Inc. (1973).
6783  !
6784  real(srp) :: a,b,c,d,e,eps,fa,fb,fc,tol1,xm,p,q,r,s
6785  eps = zero
6786  tol1 = eps+1.0_srp
6787 
6788  a=ax
6789  b=bx
6790  fa=f(a)
6791  fb=f(b)
6792  ! check that f(ax) and f(bx) have different signs
6793  if (fa .eq.0.0_srp .or. fb .eq. 0.0_srp) go to 20
6794  if (fa * (fb/abs(fb)) .le. 0.0_srp) go to 20
6795  ! write(6,2500)
6796  !2500 format(1x,'f(ax) and f(bx) do not have different signs, aborting')
6797  zeroin = missing
6798  return
6799  20 c=a
6800  fc=fa
6801  d=b-a
6802  e=d
6803  30 if (abs(fc).ge.abs(fb)) go to 40
6804  a=b
6805  b=c
6806  c=a
6807  fa=fb
6808  fb=fc
6809  fc=fa
6810  40 tol1=2.0_srp*eps*abs(b)+0.5_srp*tol
6811  xm = 0.5_srp*(c-b)
6812  if ((abs(xm).le.tol1).or.(fb.eq.0.0_srp)) go to 150
6813  !
6814  ! see if a bisection is forced
6815  !
6816  if ((abs(e).ge.tol1).and.(abs(fa).gt.abs(fb))) go to 50
6817  d=xm
6818  e=d
6819  go to 110
6820  50 s=fb/fa
6821  if (a.ne.c) go to 60
6822  !
6823  ! linear interpolation
6824  !
6825  p=2.0_srp*xm*s
6826  q=1.0_srp-s
6827  go to 70
6828  !
6829  ! inverse quadratic interpolation
6830  !
6831  60 q=fa/fc
6832  r=fb/fc
6833  p=s*(2.0_srp*xm*q*(q-r)-(b-a)*(r-1.0_srp))
6834  q=(q-1.0_srp)*(r-1.0_srp)*(s-1.0_srp)
6835  70 if (p.le.0.0_srp) go to 80
6836  q=-q
6837  go to 90
6838  80 p=-p
6839  90 s=e
6840  e=d
6841  if (((2.0_srp*p).ge.(3.0_srp*xm*q-abs(tol1*q))) .or. &
6842  (p.ge. abs(0.5d0*s*q))) go to 100
6843  d=p/q
6844  go to 110
6845  100 d=xm
6846  e=d
6847  110 a=b
6848  fa=fb
6849  if (abs(d).le.tol1) go to 120
6850  b=b+d
6851  go to 140
6852  120 if (xm.le.0.0_srp) go to 130
6853  b=b+tol1
6854  go to 140
6855  130 b=b-tol1
6856  140 fb=f(b)
6857  if ((fb*(fc/abs(fc))).gt.0.0_srp) go to 20
6858  go to 30
6859  150 zeroin=b
6860  return
6861  end function zeroin
6862 
6863  !-----------------------------------------------------------------------------
6864  !> @brief Converts and rescales integer allele value to real value for
6865  !! neural response function
6866  !! @param[in] raw_value raw input value, integer within
6867  !! `commondata::allelerange_min` and `commondata::allelerange_max`
6868  !! @retval Returns the value of conversion function: integer alleles
6869  !! to real internal value ::zero to ::allelescale_max
6870  !! @details Allele conversion function for the relationship between the
6871  !! genome integer allele value and its converted real value in
6872  !! the neuronal response function. The function rescales integer
6873  !! allele value @f$ I_{i} @f$ within the range
6874  !! @f$ [I_{min},I_{max}] @f$ to real values @f$ r @f$ within the
6875  !! range @f$ [0,M] @f$, where @f$ M @f$ is defined by the
6876  !! ::allelescale_max parameter. Conversion is performed by the
6877  !! ::rescale() backend function.
6878  !! See implementation notes on `allele_value` component of the
6879  !! `GENE` derived type.
6880  !! @note Note that it is an *elemental function* that can accept both
6881  !! scalar and vector arguments.
6882  elemental function allelescale(raw_value) result(converted)
6883 
6884  integer, intent(in) :: raw_value
6885  real(srp) :: converted
6886 
6887  converted = rescale( real(raw_value,srp), &
6888  real(allelerange_min,srp), real(ALLELERANGE_MAX,SRP),&
6890 
6891  end function allelescale
6892 
6893  !-----------------------------------------------------------------------------
6894  !> @details Rescales the relationship between the numerical value of an
6895  !! allele in the genome and the numerical value to be used in the
6896  !! neuronal response function.
6897  !! @param raw_value Raw input value from the genome.
6898  !! @retval Returns the rescaled value.
6899  !! @note This is the same component as in the original model ALLELECONV
6900  !! parameter. Thus, if the allele value is integer in `gamma2gene`,
6901  !! then `commondata::allelescale()` is called first (convert
6902  !! integer to real 0..1), then follows `::alleleconv()`
6903  !! (rescale 0..1 to rescaled value).
6904  !! @note Note that it is an *elemental function* that can accept both
6905  !! scalar and vector arguments.
6906  elemental function alleleconv(raw_value) result (converted)
6907  ! @param Raw input value from the genome
6908  real(srp), intent(in) :: raw_value
6909  ! @retval Returns the rescaled value
6910  real(srp) :: converted
6911 
6912  !> Scale factor for the simple linear conversion (Type 3).
6913  real(srp), parameter :: scale_factor = 10.
6914 
6915  !> ### Implementation details ###
6916 
6917  !> ### Type 1 ###
6918  !> *Type 1:* no conversion from 0:1 to output allele value
6919  !! @note identical to old alleleconv 1
6920  !! @code converted = raw_value @endcode
6921  converted = raw_value
6922 
6923  !> ### Type 2 ###
6924  !> *Type 2:* exponential conversion from 0:1 to output allele value,
6925  !! to allow finer resolution at weak perception strengths.
6926  !! @warning This version can produce NaNs.
6927  !! @note identical to identical to old alleleconv 2
6928  !! @code converted = (10 * raw_value) ** 2 @endcode
6929  !converted = (10 * raw_value) ** 2
6930 
6931  !> ### Type 3 ###
6932  !> *Type 3:* linear conversion from 0:1 to output allele value,
6933  !! has been the most used value, although not perfect.
6934  !> @note identical to old alleleconv 3
6935  !! @code converted = raw_value * SCALE_FACTOR @endcode
6936  !converted = raw_value * SCALE_FACTOR
6937 
6938  end function alleleconv
6939 
6940  !-----------------------------------------------------------------------------
6941  !> @brief Calculate the variance from the coefficient of variation.
6942  !! @details The coefficient of variation `cv`
6943  !! @f$ cv= \frac{\sigma}{\bar{P}} @f$. Therefore, the raw
6944  !! variance @f$ {\sigma}^{2} @f$ in the `RNORM` function is equal to
6945  !! @f[ {\sigma}^{2} = {(cv \cdot \bar{P})}^{2} . @f]
6946  !! @returns Variance @f$ {\sigma}^{2} @f$
6947  !! @param cv Coefficient of variation.
6948  !! @param mean Average.
6949  !! @note We need this function because Gaussian parameters in `commondata`
6950  !! are set using the *average* and *CV* to be more intuitive, scale
6951  !! independent. But the function `RNORM` in `HEDTOOLS` gets variance
6952  !! as a parameter.
6953  !! @note Note that this is an elemental function that gets both array and
6954  !! scalar parameters.
6955  elemental function cv2variance (cv, mean) result (variance)
6956  ! @returns Variance
6957  real(srp) :: variance
6958  ! @param cv Coefficient of variation.
6959  real(srp), intent(in) :: cv
6960  ! @param mean Average.
6961  real(srp), intent(in) :: mean
6962 
6963  variance = (mean*cv)**2
6964 
6965  end function cv2variance
6966 
6967  !-----------------------------------------------------------------------------
6968  !> @brief The function gamma2gene finds the sigmoid relationship for
6969  !! a complex multicomponent 2-allele impact on the neuronal response.
6970  !! @details The real function gamma2gene finds the sigmoid relationship for a
6971  !! multicomponent allele impact on the neuronal response:
6972  !! @f[ R= \frac{(P/y_{1})^{x_{1}}}{1+(P/y_{1})^{x_{1}}} +
6973  !! \frac{(P/y_{2})^{x_{2}}}{1+(P/y_{2})^{x_{2}}} +
6974  !! \frac{(P/y_{3})^{x_{3}}}{1+(P/y_{3})^{x_{3}}} ... @f]
6975  !! Here, R is the neuronal response, P the strength of the sensory
6976  !! input (scaled 0-1), and x and y are two genes. The indices refer
6977  !! to the additive components of the alleles. Note that their
6978  !! number is set by the parameter `ADDITIVE_COMPS`. Further,
6979  !! `erpcv` defines the coefficient of variation for the perception
6980  !! error (with respect to its true value).
6981  !! @returns returns the neuronal response.
6982  !! @param[in] gs shape: Gene/constant determining the shape of the gamma
6983  !! function.
6984  !! Note that the raw integer gene values are accepted by this
6985  !! function as `commondata::allelescale()` is called
6986  !! automatically inside.
6987  !! @param[in] gh half-max effect: Gene/constant for the signal strength
6988  !! giving half max effect.
6989  !! Note that the raw integer gene values are accepted by this
6990  !! function as commondata::allelescale() is called automatically
6991  !! inside.
6992  !! @param[in] signal perception: Input value of (external or internal)
6993  !! stimulus perception.
6994  !! @param[in] erpcv error: Additive error of stimulus perception, Gaussian
6995  !! variance added to the true environmental variable.
6996  !! If this parameter is absent, no perception error is
6997  !! introduced.
6998  !!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
6999  !! Maxima function for quick calc:
7000  !! @code g2gene(P,x,y,n) := n * ( (P/y)^x / (1+(P/y)^x) ); @endcode
7001  !> @warning This version of `gamma2gene` accepts *integer* arrays. It *does*
7002  !! invoke `commondata::allelescale()` automatically inside.
7003  function gamma2gene_additive_i4(gs,gh,signal,erpcv) &
7004  result(neuronal_response)
7005 
7006  ! @retval returns the neuronal response.
7007  real(srp) :: neuronal_response
7008 
7009  ! @param[in] gs shape: Gene/constant determining the shape of the gamma
7010  ! function.
7011  ! @note Note that the raw integer gene values are accepted by this
7012  ! function as `allelescale` is called automatically inside.
7013  integer, dimension(:), intent(in) :: gs
7014 
7015  ! @param[in] gh half-max effect: Gene/constant for the signal strength
7016  ! giving half max effect.
7017  ! @note Note that the raw integer gene values are accepted by this
7018  ! function as allelescale is called automatically inside.
7019  integer, dimension(:), intent(in) :: gh
7020 
7021  ! @param[in] signal perception: Input value of (external or internal)
7022  ! stimulus perception.
7023  real(srp), intent(in) :: signal
7024 
7025  ! @param[in] erpcv error: Additive error of stimulus perception, Gaussian
7026  ! variance added to the true environmental variable.
7027  ! @note If this parameter is absent, no perception error is
7028  ! introduced.
7029  real(srp), optional, intent(in) :: erpcv
7030 
7031  ! Local variables:
7032  real(srp) :: perception
7033  real(hrp) :: d1, nr
7034  integer :: i
7035 
7036  ! Parameter that specifies the minimum perception. Can be commondata::zero
7037  ! or commondata::tolerance_low_def_srp
7038  real(srp), parameter :: forced_min_percept = zero
7039 
7040  !> ### Implementation details ###
7041  !! Perception is calculated as @f[ P=\bar{P}+\varepsilon , @f]
7042  !! where @f$ \bar{P} @f$ is the true environmental variable and
7043  !! @f$ \varepsilon @f$ is a Gaussian error. The perception value with
7044  !! error is implemented as a normal Gaussian variate with the mean
7045  !! equal to the true `signal` value @f$ \bar{P} @f$ and the coefficient
7046  !! of variation equal to the `erpcv` input parameter:
7047  !! @f$ erpcv= \frac{\sigma}{\bar{P}} @f$. Therefore, the raw
7048  !! error variance in the `RNORM` function is equal to the square of
7049  !! `erpcv*signal`. We also impose strict limit on perception @f$ P>0 . @f$
7050  if (present(erpcv)) then
7051  if (erpcv > tolerance_high_def_srp) then
7052  perception = max(forced_min_percept, rnorm(signal,(erpcv*signal)**2))
7053  else
7054  perception = max(forced_min_percept, signal)
7055  end if
7056  else
7057  perception = max(forced_min_percept, signal)
7058  end if
7059 
7060  nr = 0.0_hrp
7061 
7062  ! @warning The `do concurrent` construct is F2008 and can not (yet) be
7063  ! implemented in all compilers. Use normal `do` in such a case.
7064  do concurrent(i=1:size(gs))
7065  d1 = (real(perception, hrp) / real(alleleconv(allelescale(gh(i))),hrp)) &
7066  ** real( alleleconv( allelescale(gs(i)) ), hrp )
7067  nr = nr + d1/(1.0_hrp+d1)
7068  end do
7069 
7070  if (nr < zero) then
7071  neuronal_response = zero
7072  else
7073  neuronal_response = real(nr, srp)
7074  end if
7075 
7076  end function gamma2gene_additive_i4
7077 
7078  !-----------------------------------------------------------------------------
7079  !> @brief The function gamma2gene finds the sigmoid relationship for
7080  !! a complex multicomponent 2-allele impact on the neuronal
7081  !! response.
7082  !! @returns returns the neuronal response.
7083  !! @param[in] shape: Gene/constant determining the shape of the gamma
7084  !! function.
7085  !! Note that the raw integer gene values are accepted by this
7086  !! function as `commondata::allelescale()` is called automatically
7087  !! inside.
7088  !! @param[in] half-max effect: Gene/constant for the signal strength giving
7089  !! half max effect.
7090  !! Note that the raw integer gene values are accepted by this
7091  !! function as `commondata::allelescale()` is called automatically
7092  !! inside.
7093  !! @param[in] perception: Input value of (external or internal) stimulus
7094  !! perception.
7095  !! @param[in] error: Additive error of stimulus perception, Gaussian
7096  !! variance added to the true environmental variable.
7097  !! If this parameter is absent, no perception error is
7098  !! introduced.
7099  !! @details The real function gamma2gene finds the sigmoid relationship for a
7100  !! multicomponent allele impact on the neuronal response:
7101  !! @f[ R= \frac{(P/y_{1})^{x_{1}}}{1+(P/y_{1})^{x_{1}}} +
7102  !! \frac{(P/y_{2})^{x_{2}}}{1+(P/y_{2})^{x_{2}}} +
7103  !! \frac{(P/y_{3})^{x_{3}}}{1+(P/y_{3})^{x_{3}}} ... @f]
7104  !! Here, R is the neuronal response, P the strength of the sensory
7105  !! input (scaled 0-1), and x and y are two genes. The indices refer
7106  !! to the additive components of the alleles. Note that their
7107  !! number is set by the parameter `ADDITIVE_COMPS`. Further,
7108  !! `erpcv` defines the coefficient of variation for the perception
7109  !! error (with respect to its true value).
7110  !! - - - - - - - -
7111  !! Maxima function for quick calc:
7112  !! @code g2gene(P,x,y,n) := n * ( (P/y)^x / (1+(P/y)^x) ); @endcode
7113  !> @warning This version of `gamma2gene` accepts *real* arrays. It does *not*
7114  !! invoke `commondata::allelescale()` automatically inside.
7115  function gamma2gene_additive_r4(gs,gh,signal,erpcv) result (neuronal_response)
7116 
7117  ! @returns returns the neuronal response.
7118  real(srp) :: neuronal_response
7119 
7120  ! @param[in] shape: Gene/constant determining the shape of the gamma
7121  ! function.
7122  ! @note Note that the raw integer gene values are accepted by this
7123  ! function as `allelescale` is called automatically inside.
7124  real(srp), dimension(:), intent(in) :: gs
7125 
7126  ! @param[in] half-max effect: Gene/constant for the signal strength giving
7127  ! half max effect.
7128  ! @note Note that the raw integer gene values are accepted by this
7129  ! function as `allelescale` is called automatically inside.
7130  real(srp), dimension(:), intent(in) :: gh
7131 
7132  ! @param[in] perception: Input value of (external or internal) stimulus
7133  ! perception.
7134  real(srp), intent(in) :: signal
7135 
7136  ! @param[in] error: Additive error of stimulus perception, Gaussian
7137  ! variance added to the true environmental variable.
7138  ! @note If this parameter is absent, no perception error is
7139  ! introduced.
7140  real(srp), optional, intent(in) :: erpcv
7141 
7142  ! Local variables:
7143  real(srp) :: perception
7144  real(hrp) :: d1, nr
7145  integer :: i
7146 
7147  ! Parameter that specifies the minimum perception. Can be commondata::zero
7148  ! or commondata::tolerance_low_def_srp
7149  real(srp), parameter :: forced_min_percept = zero
7150 
7151  !> Perception is calculated as @f[ P=\bar{P}+\varepsilon , @f]
7152  !! where @f$ \bar{P} @f$ is the true environmental variable and
7153  !! @f$ \varepsilon @f$ is a Gaussian error. The perception value with
7154  !! error is implemented as a normal Gaussian variate with the mean
7155  !! equal to the true `signal` value @f$ \bar{P} @f$ and the coefficient
7156  !! of variation equal to the `erpcv` input parameter:
7157  !! @f$ erpcv= \frac{\sigma}{\bar{P}} @f$. Therefore, the raw
7158  !! error variance in the `RNORM` function is equal to the square of
7159  !! `erpcv*signal`. We also impose strict limit on perception min=0.
7160  if (present(erpcv)) then
7161  if (erpcv > tolerance_high_def_srp) then
7162  perception = max(forced_min_percept, rnorm(signal,(erpcv*signal)**2))
7163  else
7164  perception = max(forced_min_percept, signal)
7165  end if
7166  else
7167  perception = max(forced_min_percept, signal)
7168  end if
7169 
7170  nr = 0.0_hrp
7171 
7172  ! @warning The `do concurrent` construct is F2008 and can not (yet) be
7173  ! implemented in all compilers. Use normal `do` in such a case.
7174  do concurrent(i=1:size(gs))
7175  d1 = (real(perception,hrp) / real(alleleconv(gh(i)),hrp)) &
7176  ** real( alleleconv(gs(i)),hrp )
7177  nr = nr + d1/(1.0_hrp+d1)
7178  end do
7179 
7180  if (nr < zero) then
7181  neuronal_response = zero
7182  else
7183  neuronal_response = real(nr, srp)
7184  end if
7185 
7186  end function gamma2gene_additive_r4
7187 
7188  !-----------------------------------------------------------------------------
7189  !> This "fake" version of the `gamma2gene` is used to guess the response
7190  !! values in calculations.
7191  !! @retval predicted_val a predicted value (scalar or array) of the
7192  !! sigmoidal neuronal response function. See gamma2gene for details.
7193  elemental function gamma2gene_fake_vals(signal, gs, gh, n_acomps) &
7194  result(predicted_val)
7195  real(srp), intent(in) :: signal
7196  real(srp), optional, intent(in) :: gs, gh
7197  integer, optional, intent(in) :: n_acomps
7198  real(srp) :: predicted_val
7199 
7200  ! Local copies of optionals.
7201  real(srp) :: gs_loc, gh_loc
7202  integer :: n_acomps_loc
7203 
7204  if (present(gs)) then
7205  gs_loc = gs
7206  else
7207  gs_loc = 0.5_srp
7208  end if
7209 
7210  if (present(gh)) then
7211  gh_loc = gh
7212  else
7213  gh_loc = 0.5_srp
7214  end if
7215 
7216  if (present(n_acomps)) then
7217  n_acomps_loc = n_acomps
7218  else
7219  n_acomps_loc = additive_comps
7220  end if
7221 
7222  predicted_val = n_acomps_loc * ( (signal/gh_loc)**gs_loc / &
7223  (1.0_srp+(signal/gh_loc)**gs_loc) )
7224 
7225  end function gamma2gene_fake_vals
7226 
7227  !-----------------------------------------------------------------------------
7228  !> @brief Reverse-calculate perception value from the given neural
7229  !! response value.
7230  !! @details Calculates the value of the raw perception from the neural
7231  !! response function. This is the reverse of the gamma2gene with
7232  !! many components. It is assumed that all x and y values are the
7233  !! same, so the equation solved for the most trivial case.
7234  !! Calculated according to the formula:
7235  !! @f[ P = y\left ( \frac{R}{n-R} \right )^{1/x} , @f] where
7236  !! @f$ P @f$ is the perception value, @f$ R @f$ is the neural
7237  !! response, @f$ x @f$ and @f$ y @f$ are two genes.
7238  !! @returns Signal level for specific neural response, back calculated.
7239  !! @param[in] neuronal_response neuronal response.
7240  !! @param[in] gs shape parameter of the sigmoid function.
7241  !! @param[in] gh half-max parameter of the sigmoid function.
7242  !! @param[in] nc Number of additive components. Optional, if absent
7243  !! assumed 1 (single component).
7244  !! @n
7245  !! @note This function is useful for guessing the average start values
7246  !! of genetically determined traits with Gaussian distribution.
7247  !! @note Note that it is quite difficult to get really small `gamma2gene`
7248  !! values as the signal value should be really small:
7249  !! e.g. to get neural response 1.5E-5 (Fulton condition), we need
7250  !! signal = 2E-12. So, the function very quickly loses precision
7251  !! as we approach really low values. Need kind 8 or 16 precision?
7252  !! @warning This is quite a crude guess at low values. At lower values
7253  !! *underestimates* R, real value is higher. This is due to the
7254  !! limitation that R should never be below zero, causing above-zero
7255  !! truncation.
7256  elemental function gamma2gene_reverse(neuronal_response, gs, gh, nc) &
7257  result(signal)
7258 
7259  !> @returns Signal level for specific neural response, back calculated.
7260  real(srp) :: signal
7261  ! @param[in] neuronal_response neuronal response.
7262  ! gs shape parameter of the sigmoid function.
7263  ! gh half-max parameter of the sigmoid function.
7264  real(srp), intent(in) :: neuronal_response, gs, gh
7265  ! @param[in] nc Number of additive components. Optional, if absent
7266  ! assumed 1 (single component).
7267  integer, intent(in), optional :: nc
7268 
7269  ! Local variable.
7270  integer :: n
7271 
7272  if (present(nc)) then
7273  n=nc
7274  else
7275  n=1
7276  end if
7277 
7278  !> Maxima function for quick calc:
7279  !! @code reverse_gamma(R,x,y,n) := y * (R/(n-R))^(1/x); @endcode
7280  signal = gh * (neuronal_response / n - neuronal_response )**(1.0_srp/gs)
7281 
7282  end function gamma2gene_reverse
7283 
7284  !=============================================================================
7285  ! The two procedures below are for the history stack array
7286 
7287  !-----------------------------------------------------------------------------
7288  !> Simple history stack function, add to the end of the stack. We need
7289  !! only to add components on top of the stack and retain
7290  !! `commondata::history_size_spatial` elements of the prior history (for a
7291  !! spatial moving object). The stack works as follows, assuming 100 and 200
7292  !! are added:
7293  !! @n [1 2 3 4 5 6 7 8 9 10];
7294  !! @n [2 3 4 5 6 7 8 9 10 100];
7295  !! @n [3 4 5 6 7 8 9 10 100 200]
7296  !! @param history_array Integer array that keeps the history.
7297  !! @param add_this we add this element to the end of the history array.
7298  !! @note This is the integer type version.
7299  pure subroutine add_to_history_i4(history_array, add_this)
7300 
7301  ! @param history_array Integer array that keeps the history.
7302  integer, dimension(:), intent(inout) :: history_array
7303  ! @param add_this we add this element to the end of the history array.
7304  integer, intent(in) :: add_this
7305 
7306  ! Local variable to keep the size of the history array
7307  integer :: history_size
7308 
7309  history_size = size(history_array)
7310 
7311  history_array(1:history_size-1) = history_array(2:history_size)
7312  history_array(history_size) = add_this
7313 
7314  end subroutine add_to_history_i4
7315 
7316  !-----------------------------------------------------------------------------
7317  !> Simple history stack function, add to the end of the stack. We need
7318  !! only to add components on top of the stack and retain
7319  !! `commondata::history_size_spatial` elements of the prior history (for a
7320  !! spatial moving object).
7321  !! @param history_array Integer array that keeps the history.
7322  !! @param add_this we add this element to the end of the history array.
7323  !! @note This is the real type version.
7324  pure subroutine add_to_history_r(history_array, add_this)
7325 
7326  ! @param history_array Integer array that keeps the history.
7327  real(srp), dimension(:), intent(inout) :: history_array
7328  ! @param add_this we add this element to the end of the history array.
7329  real(srp), intent(in) :: add_this
7330 
7331  ! Local variable to keep the size of the history array.
7332  integer :: history_size
7333 
7334  history_size = size(history_array)
7335 
7336  history_array(1:history_size-1) = history_array(2:history_size)
7337  history_array(history_size) = add_this
7338 
7339  end subroutine add_to_history_r
7340 
7341  !-----------------------------------------------------------------------------
7342  !> Simple history stack function, add to the end of the stack. We need
7343  !! only to add components on top of the stack and retain
7344  !! `commondata::history_size_spatial` elements of the prior history.
7345  !! @param history_array Integer array that keeps the history.
7346  !! @param add_this we add this element to the end of the history array.
7347  !! @note This is the character string type version
7348  pure subroutine add_to_history_char(history_array, add_this)
7349 
7350  ! @param history_array Integer array that keeps the history.
7351  character(*), dimension(:), intent(inout) :: history_array
7352  ! @param add_this we add this element to the end of the history array.
7353  character(*), intent(in) :: add_this
7354 
7355  ! Local variable to keep the size of the history array.
7356  integer :: history_size
7357 
7358  history_size = size(history_array)
7359 
7360  history_array(1:history_size-1) = history_array(2:history_size)
7361  history_array(history_size) = add_this
7362 
7363  end subroutine add_to_history_char
7364 
7365  !-----------------------------------------------------------------------------
7366  !> Converts logical to integer following a rule, default FALSE = 0, TRUE = 1.
7367  !! @note Note that this function is required to place logical data
7368  !! like the survival status (alive) into the reshape array that is
7369  !! saved as the CSV data file.
7370  elemental function conv_l2i(flag, code_false, code_true) result (num_out)
7371  logical, intent(in) :: flag
7372  integer, optional, intent(in) :: code_false
7373  integer, optional, intent(in) :: code_true
7374  integer :: num_out
7375 
7376  ! Local copies of optionals.
7377  integer :: code_false_loc, code_true_loc
7378  ! Local real parameters for the default FALSE and TRUE.
7379  integer, parameter :: false_def=0, true_def=1
7380 
7381  ! First, check optional parameters.
7382  if (present(code_false)) then
7383  code_false_loc = code_false
7384  else
7385  code_false_loc = false_def
7386  end if
7387 
7388  if (present(code_true)) then
7389  code_true_loc = code_true
7390  else
7391  code_true_loc = true_def
7392  end if
7393 
7394  ! Second, do the actual conversion.
7395  if (flag .eqv. .true.) then
7396  num_out = code_true_loc
7397  else
7398  num_out = code_false_loc
7399  end if
7400  end function conv_l2i
7401 
7402  !-----------------------------------------------------------------------------
7403  !> Converts logical to standard (kind SRP) real, .FALSE. => 0, .TRUE. => 1
7404  !! @note Note that this function is required to place logical data
7405  !! like the survival status (alive) into the reshape array that is
7406  !! saved as the CSV data file.
7407  !! **Example: **
7408  !! @code
7409  !! call CSV_MATRIX_WRITE ( reshape( &
7410  !! [ habitat_safe%food%food%x, &
7411  !! habitat_safe%food%food%y, &
7412  !! habitat_safe%food%food%depth, &
7413  !! conv_l2r(habitat_safe%food%food%eaten), &
7414  !! habitat_safe%food%food%size], &
7415  !! [habitat_safe%food%number_food_items, 5]), &
7416  !! "zzz_food_s" // MODEL_NAME // "_" // MMDD // &
7417  !! "_gen_" // TOSTR(generat, GENERATIONS) // csv, &
7418  !! ["X ","Y ", "D ", "EATN", "SIZE"] &
7419  !! ) @endcode
7420  elemental function conv_l2r(flag, code_false, code_true) result (num_out)
7421  logical, intent(in) :: flag
7422  real(srp), optional, intent(in) :: code_false
7423  real(srp), optional, intent(in) :: code_true
7424  real(srp) :: num_out
7425  ! Local copies of optionals.
7426  real(srp) :: code_false_loc, code_true_loc
7427  ! Local real parameters for the default FALSE and TRUE.
7428  real(srp), parameter :: false_def=0.0_srp, true_def=1.0_srp
7429 
7430  !> First, check optional parameters.
7431  if (present(code_false)) then
7432  code_false_loc = code_false
7433  else
7434  code_false_loc = false_def
7435  end if
7436 
7437  if (present(code_true)) then
7438  code_true_loc = code_true
7439  else
7440  code_true_loc = true_def
7441  end if
7442 
7443  ! Second, do the actual conversion.
7444  if (flag .eqv. .true.) then
7445  num_out = code_true_loc
7446  else
7447  num_out = code_false_loc
7448  end if
7449  end function conv_l2r
7450 
7451  !-----------------------------------------------------------------------------
7452  !> Function to check if the value is the maximum value of an array
7453  !! (returns TRUE), or not (return FALSE).
7454  !! @returns TRUE if `value` is indeed the maximum value of the `array` and
7455  !! FALSE otherwise.
7456  !! @param[in] value The value to check
7457  !! @param[in] array The array to check within.
7458  !! @param[in] tolerance Optional tolerance threshold.
7459  pure function is_maxval_r (value, array, tolerance) result (is_max)
7460 
7461  ! @returns TRUE if `value` is indeed the maximum value of the `array` and
7462  ! FALSE otherwise.
7463  logical :: is_max
7464  ! @param[in] value The value to check
7465  real(srp), intent(in) :: value
7466  ! @param[in] array The array to check within.
7467  real(srp), dimension(:), intent(in) :: array
7468  ! @param[in] tolerance Optional tolerance threshold.
7469  real(srp), optional, intent(in) :: tolerance
7470 
7471  ! Local tolerance threshold.
7472  real(srp) :: tolerance_threshold
7473 
7474  !> @note Check if we are provided with the tolerance threshold, if not, use
7475  !! the default parameter commondata::tolerance_low_def_srp value.
7476  tolerance_threshold = tolerance_low_def_srp
7477  if (present(tolerance)) then
7478  if ( abs(tolerance) >= tiny_srp ) tolerance_threshold = abs(tolerance)
7479  end if
7480 
7481  ! Do the actual comparison.
7482  if ( float_equal(value, maxval(array), tolerance_threshold ) ) then
7483  is_max = .true.
7484  else
7485  is_max = .false.
7486  end if
7487 
7488  end function is_maxval_r
7489 
7490  !-----------------------------------------------------------------------------
7491  !> Function to check if the value is the maximum value of an array
7492  !! (returns TRUE), or not (return FALSE). Integer version.
7493  !! @returns TRUE if `value` is indeed the maximum value of the `array` and
7494  !! FALSE otherwise.
7495  !! @param[in] value The value to check
7496  !! @param[in] array The array to check within.
7497  pure function is_maxval_i (value, array) result (is_max)
7498 
7499  ! @returns TRUE if `value` is indeed the maximum value of the `array` and
7500  ! FALSE otherwise.
7501  logical :: is_max
7502  ! @param[in] value The value to check
7503  integer, intent(in) :: value
7504  ! @param[in] array The array to check within.
7505  integer, dimension(:), intent(in) :: array
7506 
7507  ! Do the actual comparison.
7508  if ( value == maxval(array) ) then
7509  is_max = .true.
7510  else
7511  is_max = .false.
7512  end if
7513 
7514  end function is_maxval_i
7515 
7516  !-----------------------------------------------------------------------------
7517  !> Function to check if the value is the minimum value of an array
7518  !! (returns TRUE), or not (return FALSE).
7519  !! @returns TRUE if `value` is indeed the minimum value of the `array` and
7520  !! FALSE otherwise.
7521  !! @param[in] value The value to check
7522  !! @param[in] array The array to check within.
7523  !! @param[in] tolerance Optional tolerance threshold.
7524  pure function is_minval_r (value, array, tolerance) result (is_max)
7525 
7526  ! @returns TRUE if `value` is indeed the minimum value of the `array` and
7527  ! FALSE otherwise.
7528  logical :: is_max
7529  ! @param[in] value The value to check
7530  real(srp), intent(in) :: value
7531  ! @param[in] array The array to check within.
7532  real(srp), dimension(:), intent(in) :: array
7533  ! @param[in] tolerance Optional tolerance threshold.
7534  real(srp), optional, intent(in) :: tolerance
7535 
7536  ! Local tolerance threshold.
7537  real(srp) :: tolerance_threshold
7538 
7539  !> @note Check if we are provided with the tolerance threshold, if not, use
7540  !! the default parameter commondata::tolerance_low_def_srp value.
7541  tolerance_threshold = tolerance_low_def_srp
7542  if (present(tolerance)) then
7543  if ( abs(tolerance) >= tiny_srp ) tolerance_threshold = abs(tolerance)
7544  end if
7545 
7546  ! Do the actual comparison.
7547  if ( float_equal(value, minval(array), tolerance_threshold ) ) then
7548  is_max = .true.
7549  else
7550  is_max = .false.
7551  end if
7552 
7553  end function is_minval_r
7554 
7555  !-----------------------------------------------------------------------------
7556  !> Function to check if the value is the minimum value of an array
7557  !! (returns TRUE), or not (return FALSE). Integer version.
7558  !! @returns TRUE if `value` is indeed the minimum value of the `array` and
7559  !! FALSE otherwise.
7560  !! @param[in] value The value to check
7561  !! @param[in] array The array to check within.
7562  pure function is_minval_i (value, array) result (is_max)
7563 
7564  ! @returns TRUE if `value` is indeed the minimum value of the `array` and
7565  ! FALSE otherwise.
7566  logical :: is_max
7567  ! @param[in] value The value to check
7568  integer, intent(in) :: value
7569  ! @param[in] array The array to check within.
7570  integer, dimension(:), intent(in) :: array
7571 
7572  ! Do the actual comparison.
7573  if ( value == minval(array) ) then
7574  is_max = .true.
7575  else
7576  is_max = .false.
7577  end if
7578 
7579  end function is_minval_i
7580 
7581  !=============================================================================
7582  ! The two procedures below are for the CPU timer / stopwatch object
7583  ! # Timing (stopwatch) functions #
7584 
7585  !-----------------------------------------------------------------------------
7586  !> Start the timer object, stopwatch is now ON.
7587  !! @param title, an optional title for the stopwatch object
7588  ! @note We do not need exact low-level time as it is machine-specific.
7589  subroutine timer_cpu_start(this, timer_title)
7590  class(timer_cpu), intent(inout) :: this
7591 
7592  ! @param title, an optional title for the stopwatch object
7593  character(len=*), optional, intent(in) :: timer_title
7594 
7595  if (present(timer_title)) then
7596  this%cpu_time_title = timer_title
7597  else
7598  this%cpu_time_title = "DEFAULT_TIMER"
7599  end if
7600 
7601  ! This turns on the CPU stopwatch
7602  call cpu_time(this%cpu_time_start)
7603 
7604  end subroutine timer_cpu_start
7605 
7606  !-----------------------------------------------------------------------------
7607  !> Calculate the time elapsed since the stopwatch subroutine was called
7608  !! for this instance of the timer container object. Can be called several
7609  !! times showing elapsed time since the grand start.
7610  !! @returns the time elapsed since `timer_cpu_start` call (object-bound).
7611  function timer_cpu_elapsed (this) result (cpu_time_elapsed)
7612  class(timer_cpu), intent(in) :: this
7613  ! @returns the time elapsed since `timer_cpu_start` call (object-bound).
7614  real(srp) :: cpu_time_elapsed
7615 
7616  ! Local var
7617  real(srp) :: cpu_time_finish
7618 
7619  ! We use the intrinsic `cpu_time` to get the finish time point.
7620  call cpu_time(cpu_time_finish)
7621 
7622  ! Elapsed time is then trivial to get.
7623  cpu_time_elapsed = cpu_time_finish - this%cpu_time_start
7624 
7625  end function timer_cpu_elapsed
7626 
7627  !-----------------------------------------------------------------------------
7628  !> Return the title of the current timer object.
7629  !! @returns title of the stopwatch timer, allocatable with
7630  !! automatic trimming.
7631  !! @note Useful for outputs.
7632  function timer_cpu_title(this) result (timer_title)
7633  class(timer_cpu), intent(in) :: this
7634 
7635  ! @returns title of the stopwatch timer, allocatable with
7636  ! automatic trimming.
7637  character(len=:), allocatable :: timer_title
7638 
7639  timer_title = trim(this%cpu_time_title)
7640 
7641  end function timer_cpu_title
7642 
7643  !-----------------------------------------------------------------------------
7644  !> A ready to use in output function that returns a formatted
7645  !! string for a timer combining its title and the elapsed time.
7646  !! For example: `Calculating decomposition took 20s`.
7647  function timer_cpu_show(this) result (timer_string)
7648  class(timer_cpu), intent(in) :: this
7649  character(len=:), allocatable :: timer_string
7650  real(srp) :: timer_value
7651 
7652  real(srp), parameter :: add_hours_val_exceed = 120.0_srp
7653 
7654  timer_value = this%elapsed()
7655 
7656  if ( timer_value > tolerance_low_def_srp ) then
7657  timer_string = trim(this%cpu_time_title) // " took " // &
7658  tostr(timer_value) // "s"
7659  !> @note If the value in *seconds* is too big, hours passed are appended
7660  !! in parentheses.
7661  if (timer_value > add_hours_val_exceed) timer_string = &
7662  timer_string // " (" // tostr(timer_value/3600) // " h)"
7663  else
7664  timer_string = trim(this%cpu_time_title) // &
7665  " took ZERO TIME (seems too fast, check data!)"
7666  end if
7667 
7668  end function timer_cpu_show
7669 
7670  !-----------------------------------------------------------------------------
7671  !> A ready to use shortcut function to be used in logger, just adds the
7672  !! TIMER: tag in front of the normal `show`output. @n
7673  !! **Example use:**
7674  !! @code
7675  !! call stopwatch_1%start("Calculate matrix decomposition")
7676  !! .....
7677  !! call LOG_DBG( stopwatch_1%log() )
7678  !! @endcode
7679  function timer_cpu_log(this) result (timer_string)
7680  class(timer_cpu) :: this
7681  character(len=:), allocatable :: timer_string
7682 
7683  timer_string = ltag_timer // this%show()
7684 
7685  end function timer_cpu_log
7686 
7687  !=============================================================================
7688 
7689  !-----------------------------------------------------------------------------
7690  !> Call an external program using a command line. Wrapper to two alternative
7691  !! system shell calling intrinsic procedures.
7692  !! @param[in] command is the command line that should be run by the system.
7693  !! @param[in] suppress_output is an optional logical flag indicating
7694  !! whether to suppress any STDOUT output (silent mode).
7695  !! Default is FALSE, i.e. do show command output (verbose).
7696  !! @param[in] suppress_error is a similar optional flag to suppress STDERR
7697  !! reporting (silent mode). Default is FALSE.
7698  !! @param[in] is_background_task is a logical flag to set execution
7699  !! on the background, based on wait=.false. parameter of
7700  !! `EXECUTE_COMMAND_LINE`. The **default** value is TRUE, i.e.
7701  !! **do** process the command at the background. **Warning:**
7702  !! Setting command execution as a background task will make
7703  !! `cmd_is_success` unusable because the exit code of the
7704  !! child process is is deferred.
7705  !! @param[out] cmd_is_success is a logical flag indicating the command
7706  !! result was *success* (zero exit code).
7707  !! @param[out] exit_code exit code of the child process.
7708  !! @warning All external calls should normally be
7709  !! performed using this wrapper.
7710  subroutine call_external( command, suppress_output, suppress_error, &
7711  is_background_task, cmd_is_success, exit_code )
7712  ! @note Importing C_NULL_CHAR is a workaround against the Intel Fortran
7713  ! compiler bug, see http://ahamodel.uib.no/intel-compiler-bug.html
7714  ! https://software.intel.com/en-us/forums/intel-fortran-compiler-for-linux-and-mac-os-x/topic/743814
7715  ! `execute_command_line` intrinsic must add C null string to the end
7716  ! of the command line to avoid Intel Fortran crashing.
7717  use iso_c_binding, only: c_null_char
7718  ! @param[in] command is the command line that should be run by the system.
7719  character(len=*), intent(in) :: command
7720  ! @param[in] suppress_output is an optional logical flag indicating
7721  ! whether to suppress any STDOUT output (silent mode).
7722  ! Default is FALSE, i.e. do show command output (verbose).
7723  logical, optional, intent(in) :: suppress_output
7724  ! @param[in] suppress_error is a similar optional flag to suppress STDERR
7725  ! reporting (silent mode). Default is FALSE.
7726  logical, optional, intent(in) :: suppress_error
7727  ! @param[in] is_background_task is a logical flag to set execution
7728  ! on the background, based on wait=.false. parameter of
7729  ! `EXECUTE_COMMAND_LINE`. The **default** value is TRUE, i.e.
7730  ! **do** process the command at the background.
7731  ! @warning Setting command execution as a background task will make
7732  ! `cmd_is_success` unusable because the exit code of the
7733  ! child process is is deferred.
7734  logical, optional, intent(in) :: is_background_task
7735  ! @param[out] cmd_is_success is a logical flag indicating the command
7736  ! result was *success* (zero exit code).
7737  logical, optional, intent(out) :: cmd_is_success
7738  ! @param[out] exit_code exit code of the child process.
7739  integer, optional, intent(out) :: exit_code
7740 
7741  ! Local copies of optionals.
7742  logical :: wait_exec
7743 
7744  ! Local finally built command.
7745  character(len=:), allocatable :: cmd_execute
7746  character(len=LONG_LABEL_LENGTH) :: cmd_error_msg
7747 
7748  !> ### Implementation details ###
7749 
7750  !> Output is suppressed by redirection to the null device, which is
7751  !! platform-specific.
7752  character(len=*), parameter :: NO_STDOUT_UNIX = " >/dev/null"
7753  character(len=*), parameter :: NO_STDOUT_WINDOWS = " >:NULL"
7754  character(len=*), parameter :: NO_STDOUT_DISABLE = ""
7755 
7756  !> Output of the STDERR is also redirected to the platform-specific
7757  !! null device. For the Windows platform STDERR redirection see
7758  !! http://support.microsoft.com/en-us/kb/110930.
7759  character(len=*), parameter :: NO_STDERR_UNIX = " 2>/dev/null"
7760  character(len=*), parameter :: NO_STDERR_WINDOWS = " 2>&1"
7761  character(len=*), parameter :: NO_STDERR_DISABLE = ""
7762 
7763  ! Final null device redirection string.
7764  character(len=:), allocatable :: null_redirect_stdout, null_redirect_stderr
7765 
7766  ! The `system` intrinsic has the second optional parameter showing status.
7767  integer :: status_int, status_err
7768 
7769  ! PROCNAME is the procedure name for logging and debugging (with MODNAME).
7770  character(len=*), parameter :: PROCNAME = "(call_external)"
7771 
7772  ! Check disable STDOUT flag.
7773  if (present(suppress_output)) then
7774  if (suppress_output) then
7775  ! Check platform type to set redirection to null device.
7776  if ( platform_running == platform_windows ) then
7777  null_redirect_stdout = no_stdout_windows
7778  else
7779  null_redirect_stdout = no_stdout_unix
7780  end if
7781  else
7782  null_redirect_stdout = no_stdout_disable
7783  end if
7784  else
7785  null_redirect_stdout = no_stdout_disable
7786  end if
7787 
7788  ! Check disable STDERR flag
7789  if (present(suppress_error)) then
7790  if (suppress_error) then
7791  ! Check platform type to set redirection to null device.
7792  if ( platform_running == platform_windows ) then
7793  null_redirect_stderr = no_stderr_windows
7794  else
7795  null_redirect_stderr = no_stderr_unix
7796  end if
7797  else
7798  null_redirect_stderr = no_stderr_disable
7799  end if
7800  else
7801  null_redirect_stderr = no_stderr_disable
7802  end if
7803 
7804  !> Check background task optional option `is_background_task`.
7805  !! @note If the older non-standard `system` (disabled) command is used
7806  !! for executing background task on Unix systems may add "&" at the
7807  !! end of the command, but cannot be easily implemented on Windows.
7808  !! This functionality is currently not implemented as `system` is
7809  !! disabled.
7810  wait_exec = .false. !> Background parallel execution is enabled by default.
7811  if (present(is_background_task)) then
7812  if ( is_background_task .eqv. .false. ) wait_exec = .true.
7813  end if
7814 
7815  status_int = 0
7816  status_err = 0
7817  cmd_error_msg = "unknown"
7818 
7819  !- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
7820  !> The intrinsic procedure `system` is a GNU extension and may not be
7821  !! available on all platforms and compilers.
7822  !! It is currently disabled.
7823  !! @note If the older non-standard `system` command is used
7824  !! for executing background task on Unix systems may add "&" at
7825  !! the end of the command, but cannot be easily implemented on
7826  !! Windows. This functionality is currently not implemented as
7827  !! `system` is normally disabled. A further caveat with `system`
7828  !! is that the returned integer exit status parameter works only
7829  !! using the IFPORT portability library on Intel Fortran.
7830  !! @warning The `system` is normally **disabled**. Should be enabled if
7831  !! the standard-compliant `execute_command_line` is not supported
7832  !! by the local compiler or results in errors.
7833  !! @warning On some systems, notably 'ahaworkshop', `execute_command_line`
7834  !! issues runtime error: `Could not execute command line` when
7835  !! calling the debug plotting utilities
7836  !! - commondata::debug_histogram_save()
7837  !! - commondata::debug_scatterplot_save()
7838  !! - commondata::debug_interpolate_plot_save()
7839  !! .
7840  !! The reason of such crashes is unknown. Probably this caused by
7841  !! system specific limitations on child processes when numerous
7842  !! child processes of plotting are generated too quickly. A
7843  !! workaround is to disable debug plots by setting the parameter
7844  !! commondata::is_plotting FALSE using the environment variable
7845  !! `AHA_DEBUG_PLOTS=NO`. If plotting is absolutely essential,
7846  !! `execute_command_line` should be disabled and the inferior
7847  !! `system` call used. The latter does not seem to result in
7848  !! crashes, although this has not been well tested.
7849  !! @code
7850  !! call system( cmd_execute, status_int ) ! GNU Fortran
7851  !! call system( cmd_execute ) ! Intel Fortran requires IFPORT
7852  !! @endcode
7853  !> The F2008 `execute_command_line` should be better used here because it
7854  !! allows to control asynchronous/synchronous command execution and returns
7855  !! the exit status.
7856  !! @code
7857  !! call execute_command_line( command = cmd_execute, &
7858  !! exitstat = status_int, wait = wait_exec, &
7859  !! cmdmsg = cmd_error_msg )
7860  !! @endcode
7861  !! @warning The intrinsic procedure `execute_command_line` is part of F2008
7862  !! standard and may not be implemented yet on all platforms and
7863  !! compilers.
7864  cmd_execute = command // null_redirect_stdout // null_redirect_stderr &
7865  // c_null_char
7866  call log_dbg( ltag_info // "Calling full command line " // cmd_execute // &
7867  ", with synchronous mode " // tostr(wait_exec), &
7868  procname, modname )
7869  call execute_command_line( command = cmd_execute, &
7870  wait = wait_exec, &
7871  exitstat = status_int, cmdstat = status_err, &
7872  cmdmsg = cmd_error_msg )
7873  !call system( cmd_execute )
7874  !- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
7875 
7876  !> It is possible to get the command execution status if the logical
7877  !! `cmd_is_success` flag is provided.
7878  if (present(cmd_is_success)) then
7879  cmd_is_success = ( status_int == 0 .and. status_err == 0 )
7880  end if
7881 
7882  if (present(exit_code)) exit_code = status_int
7883 
7884  !> Finally, log the command and its reported exit status if in
7885  !! the DEBUG mode.
7886  call log_dbg( ltag_info // "Called command line " // command // &
7887  ", with execution status: " // tostr(status_err) // &
7888  " and " // "exit code: " // tostr(status_int) // &
7889  ", error message: " // trim(cmd_error_msg), &
7890  procname, modname )
7891 
7892  end subroutine call_external
7893 
7894  !-----------------------------------------------------------------------------
7895  !> Check if an external procedure is executable and can be run.
7896  function check_external(exec) result (is_valid)
7897  character(len=*), intent(in) :: exec
7898  logical :: is_valid
7899 
7900  call call_external( exec, suppress_output=.true., suppress_error=.true., &
7901  is_background_task=.false., cmd_is_success=is_valid )
7902 
7903  end function check_external
7904 
7905  !-----------------------------------------------------------------------------
7906  !> Check if an external procedure can be called and log the result.
7907  !! @param[in] exec external executable name to call.
7908  !! @param[in] debug_only flag indicating that checking is only
7909  !! done in the @ref intro_debug_mode "debug mode".
7910  !! @param[out] is_valid returns if the external procedure is executable
7911  !! (TRUE) or not (FALSE).
7912  subroutine log_check_external(exec, debug_only, is_valid)
7913  ! @param exec external executable name to call.
7914  character(len=*), intent(in) :: exec
7915  ! @param debug_only flag indicating that checking is only
7916  ! done in the @ref intro_debug_mode "debug mode".
7917  logical, optional, intent(in) :: debug_only
7918  ! @param[out] is_valid returns if the external procedure is executable
7919  ! (TRUE) or not (FALSE).
7920  logical, optional, intent(out) :: is_valid
7921 
7922  ! Local copy of optional.
7923  logical :: is_valid_here
7924 
7925  ! Local exit code of the external procedure.
7926  integer :: int_code
7927 
7928  ! PROCNAME is the procedure name for logging and debugging
7929  character(len=*), parameter :: PROCNAME = "(log_check_external)"
7930 
7931 
7932  if (present(debug_only)) then
7933  if (debug_only .and. .not. is_debug) return
7934  end if
7935 
7936  call log_dbg( ltag_info // "Calling command " // exec, procname, modname )
7937 
7938  call call_external( exec, suppress_output=.true., suppress_error=.true., &
7939  is_background_task=.false., &
7940  cmd_is_success=is_valid_here, &
7941  exit_code=int_code )
7942 
7943  if ( .not. is_valid_here .or. int_code /= 0 ) &
7944  call log_msg( ltag_warn // exec // " could not be started, exit code " &
7945  // tostr(int_code) // "." )
7946 
7947  if (present(is_valid)) is_valid = is_valid_here
7948 
7949  end subroutine log_check_external
7950 
7951  !-----------------------------------------------------------------------------
7952  !> Produce a **debug plot** of histogram using an external program
7953  !! `hthist` from HEDTOOLS tools.
7954  !! @param[in] x_data The data to be plotted.
7955  !! @param[in] delete_csv Logical flag, if TRUE, csv file will be deleted
7956  !! after plot is done.
7957  !! @param[in] csv_out_file Optional plot file name, if absent will
7958  !! be auto-generated.
7959  !! @param[in] enable_non_debug Optional flag to enable plot
7960  !! even in NON- @ref intro_debug_mode "DEBUG mode". Normally,
7961  !! all plot outputs are disabled in non- @ref intro_debug_mode
7962  !! "DEBUG mode" (`IS_DEBUG` is `FALSE`, see commondata::is_debug)
7963  !! because this may significantly slow down execution and produce
7964  !! lots of big PostScript files.
7965  subroutine debug_histogram_save(x_data, delete_csv, csv_out_file, &
7966  enable_non_debug)
7967  ! @param[in] x_data The data to be plotted.
7968  real(SRP), dimension(:), intent(in) :: x_data
7969  ! @param[in] delete_csv Logical flag, if TRUE, csv file will be deleted
7970  ! after plot is done.
7971  logical , optional, intent(in) :: delete_csv
7972  ! @param[in] csv_out_file Optional plot file name, if absent will
7973  ! be auto-generated.
7974  character(len=*), optional, intent(in) :: csv_out_file
7975  ! @param[in] enable_non_debug Optional flag to enable plot
7976  ! even in NON- @ref intro_debug_mode "DEBUG mode".
7977  logical, optional, intent(in) :: enable_non_debug
7978 
7979  ! @warning Had to use fixed length string for file name as a workaround
7980  ! against logger disk file output halting with allocatable string.
7981  character(len=FILENAME_LENGTH) :: csv_file_here
7982 
7983  logical :: do_background
7984 
7985  ! PROCNAME is the procedure name for logging and debugging (with MODNAME).
7986  character(len=*), parameter :: PROCNAME = "(debug_histogram_save)"
7987 
7988  !> ### Implementation notes ###
7989  !> The histogram plot is actually produced using a separate program
7990  !! with the executable name set by the character parameter constant
7991  !! `commondata::exec_histogram` (that should be in the system
7992  !! path). The plotting program code is normally part of the
7993  !! HEDTOOLS modelling tools and is placed in HEDTOOLS%\tools folder.
7994  !! @note Building plotting tools is done with `"make tools"` in the main
7995  !! HEDTOOLS file hierarchy. Building requires PGPLOT library and
7996  !! can be easily done on Linux; on Windows building can be more
7997  !! tricky. See code and output of `commondata::exec_histogram`.
7998  !! @note Debug plots are not essential, so are done by a separate program
7999  !! that can be absent on the runtime system.
8000  !> Plots are generated only if the protected parameter
8001  !! commondata::is_plotting is set to `TRUE`.
8002  if (.not. is_plotting) return
8003  !> Normally, plots are generated only in the @ref intro_debug_mode
8004  !! "debug mode" or if the `enable_non_debug` parameter is explicitly set
8005  !! to `TRUE`. This is because the code can easily generate huge number of
8006  !! plots. Also calling external commands has big calculation speed
8007  !! overhead and can exhaust OS-specific limits on child processes.
8008  if (.not. is_debug ) then
8009  if (present(enable_non_debug)) then
8010  if (enable_non_debug .eqv. .false.) return
8011  else
8012  return
8013  end if
8014  end if
8015 
8016  !> The plotting backend program obtains the input data for the scatterplot
8017  !! from a CSV file. Its name is normally provided on the command line.
8018  !> In this procedure, input data vector `x_data` is passed into the
8019  !! called plotting executable via a temporary CSV file. Its
8020  !! name can be automatically generated or provided explicitly as the
8021  !! `csv_out_file` dummy parameter. The CSV data file for plotting can also
8022  !! be saved. Therefore, the histogram could be easily regenerated from
8023  !! the data using an alternate program (e.g. high quality file prepared
8024  !! using a different program for publication).
8025  if (present(csv_out_file)) then
8026  csv_file_here = csv_out_file
8027  else
8028  csv_file_here = "debug_histogr_" // mmdd // &
8029  "_rev_" // svn_version // &
8030  rand_string(8,label_cst,label_cen) // csv
8031  end if
8032 
8033  do_background = .true.
8034  if (present(delete_csv)) then
8035  if (delete_csv) do_background = .false.
8036  end if
8037 
8038  call log_msg( "INFO: Saving histogram, data :" // trim(csv_file_here) )
8039 
8040  !> First, the plot vector data are saved into the temporary CSV file.
8041  !! @note Note that the data vector is saved *vertical* (`vertical=.TRUE.`).
8042  call csv_matrix_write ( x_data, trim(csv_file_here), .true. )
8043 
8044  !> Second, the external command to plot the data **histogram** is called
8045  !! using the `commondata::call_external()` wrapper procedure. We use only
8046  !! a one-dimensional vector of data and histogram is from the first column.
8047  !> No exit status or even the availability of
8048  !! `commondata::exec_scatterplot` is checked. However, the dummy
8049  !! parameter `is_background_task` controls whether the plotting program
8050  !! should be executed as a parallel background task (if `TRUE`) or the
8051  !! model executable should wait for the plotting program to terminate.
8052  !! The non-parallel (default) mode is safer because calling numerous
8053  !! child processes can exhaust the system-specific limit on child
8054  !! processes resulting in an uncontrollable crash. However, non-parallel
8055  !! mode is obviously much slower.
8056  call call_external( &
8057  command = exec_histogram // " 1 " // trim(csv_file_here) // " " // &
8058  trim(csv_file_here) // ps, &
8059  suppress_output = .true., suppress_error = .true., &
8060  is_background_task = do_background )
8061 
8062  if (present(delete_csv)) then
8063  if (delete_csv) then
8064  ! @warning `unlink` is the easiest and most reliable way to
8065  ! delete a file, but it is not standard (GNU extension)
8066  ! and may not work on all compilers and systems.
8067  ! try different methods if this does not work:
8068  ! system command `del` and opening and closing the file
8069  ! with the `delete` status:
8070  ! @code
8071  ! open(1, file=filename, form='unformatted')
8072  ! ...
8073  ! close(1, status='delete')
8074  ! @endcode
8075  !call unlink(trim(csv_file_here))
8076  call file_delete(trim(csv_file_here))
8077  end if
8078  end if
8079 
8080  end subroutine debug_histogram_save
8081 
8082  !-----------------------------------------------------------------------------
8083  !> Produce a **debug plot** of 2-d scatterplot using an external program
8084  !! `htscatter` from HEDTOOLS tools.
8085  !! @param[in] x_data The data to be plotted.
8086  !! @param[in] delete_csv Logical flag, if TRUE, csv file will be deleted
8087  !! after plot is done.
8088  !! @param[in] csv_out_file Optional plot data file name, if absent will
8089  !! be auto-generated.
8090  !! @param[in] enable_non_debug Optional flag, if TRUE, the plot output is
8091  !! saved even when *not* in the DEBUG mode. Normally, all plot outputs
8092  !! are disabled in non-DEBUG mode (`commondata::is_debug` is `FALSE`,
8093  !! see `commondata::is_debug`) because this may significantly slow
8094  !! down execution and produce lots of big PostScript files.
8095  subroutine debug_scatterplot_save(x_data, y_data, delete_csv, csv_out_file, &
8096  enable_non_debug)
8097  ! @param[in] x_data The data to be plotted.
8098  real(SRP), dimension(:), intent(in) :: x_data, y_data
8099  ! @param[in] delete_csv Logical flag, if TRUE, csv file will be deleted
8100  ! after plot is done.
8101  logical , optional, intent(in) :: delete_csv
8102  ! @param[in] csv_out_file Optional plot file name, if absent will
8103  ! be auto-generated.
8104  character(len=*), optional, intent(in) :: csv_out_file
8105  ! @param[in] enable_non_debug Optional flag to enable plot
8106  ! even in NON-DEBUG mode.
8107  logical, optional, intent(in) :: enable_non_debug
8108 
8109  ! @warning Had to use fixed length string for file name as a workaround
8110  ! against logger disk file output halting with allocatable string.
8111  character(len=FILENAME_LENGTH) :: csv_file_here
8112 
8113  logical :: do_background
8114 
8115  ! PROCNAME is the procedure name for logging and debugging (with MODNAME).
8116  character(len=*), parameter :: PROCNAME = "(debug_scatterplot_save)"
8117 
8118  !> ### Implementation notes ###
8119  !! The scatterplot is actually produced with a a separate program
8120  !! with the executable name set by the character parameter constant
8121  !! `commondata::exec_scatterplot` (that should be in the system
8122  !! path). The scatterplot program code is normally part of the
8123  !! HEDTOOLS modelling tools and is placed in `HEDTOOLS\tools` folder.
8124  !! @note Building plotting tools is done with `"make tools"` in the main
8125  !! HEDTOOLS file hierarchy. Building requires PGPLOT library and
8126  !! can be easily done on Linux; on Windows building can be more
8127  !! tricky. See code and output of `commondata::exec_scatterplot`.
8128  !! @note Debug plots are not essential, so are done by a separate program.
8129  !! They may be especially useful for controlling the quality of
8130  !! polynomial `DDPINTERPOL` interpolation, that has a tendency
8131  !! towards "wrapped" ends.
8132  !> Plots are generated only if the protected parameter
8133  !! commondata::is_plotting is set to `TRUE`.
8134  if (.not. is_plotting) return
8135  !> Plots are normally produced only in the @ref intro_debug_mode
8136  !! "debug mode" or if the `enable_non_debug` parameter is explicitly set
8137  !! to `TRUE`.
8138  if (.not. is_debug ) then
8139  if (present(enable_non_debug)) then
8140  if (enable_non_debug .eqv. .false.) return
8141  else
8142  return
8143  end if
8144  end if
8145 
8146  !> The plotting backend program obtains the input data for the scatterplot
8147  !! from a CSV file. Its name is normally provided on the command line.
8148  !> In this procedure, input data vectors `x_data` and `y_data` are passed
8149  !! into the called plotting executable via a temporary CSV file. Its
8150  !! name can be automatically generated or provided explicitly as the
8151  !! `csv_out_file` dummy parameter. The CSV data file for plotting can also
8152  !! be saved. Therefore, the scatterplot could be easily regenerated from
8153  !! the data using an alternate program (e.g. high quality file prepared
8154  !! using a different program for publication).
8155  if (present(csv_out_file)) then
8156  csv_file_here = csv_out_file
8157  else
8158  csv_file_here = "debug_scatterplot_" // mmdd // &
8159  "_rev_" // svn_version // &
8160  rand_string(8,label_cst,label_cen) // csv
8161  end if
8162 
8163  do_background = .true.
8164  if (present(delete_csv)) then
8165  if (delete_csv) do_background = .false.
8166  end if
8167 
8168  call log_msg( "INFO: Saving scatterplot, data :" // trim(csv_file_here) )
8169 
8170  !> First, the vector data are saved into the temporary CSV file.
8171  !! @note Note that if X and Y vectors are different size, the bigger is
8172  !! used for the reshaped array and extra values are padded with
8173  !! `MISSING` (see commondata::missing).
8174  call csv_matrix_write ( reshape( &
8175  [ x_data, y_data], &
8176  [max(size(x_data),size(y_data)), 2], [missing]),&
8177  trim(csv_file_here), ["X_DATA","Y_DATA"] )
8178 
8179  !> Second, the external command to produce the plot is called
8180  !! using the `commondata::call_external()` wrapper procedure.
8181  !> No exit status or even the availability of
8182  !! `commondata::exec_scatterplot` is checked. However, the dummy
8183  !! parameter `is_background_task` controls whether the plotting program
8184  !! should be executed as a parallel background task (if `TRUE`) or the
8185  !! model executable should wait for the plotting program to terminate.
8186  !! The non-parallel (default) mode is safer because calling numerous
8187  !! child processes can exhaust the system-specific limit on child
8188  !! processes resulting in an uncontrollable crash. However, non-parallel
8189  !! mode is obviously much slower.
8190  call call_external( &
8191  command = exec_scatterplot // " " // trim(csv_file_here) // " " // &
8192  trim(csv_file_here) // ps, &
8193  suppress_output = .true., suppress_error = .true., &
8194  is_background_task = do_background )
8195 
8196  if (present(delete_csv)) then
8197  if (delete_csv) then
8198  ! @warning `unlink` is the easiest and most reliable way to
8199  ! delete a file, but it is not standard (GNU extension)
8200  ! and may not work on all compilers and systems.
8201  ! @note try different methods if this does not work:
8202  ! system command `del` and opening and closing the file
8203  ! with the `delete` status:
8204  ! @code
8205  ! open(1, file=filename, form='unformatted')
8206  ! ...
8207  ! close(1, status='delete')
8208  ! @endcode
8209  !call unlink(trim(csv_file_here))
8210  call file_delete(trim(csv_file_here))
8211  end if
8212  end if
8213 
8214  end subroutine debug_scatterplot_save
8215 
8216  !-----------------------------------------------------------------------------
8217  !> Produce a **debug plot** of the **interpolation data** using an external
8218  !! program `htinterp` from the HEDTOOLS tools.
8219  !! @param grid_xx Interpolation grid arrays.
8220  !! @param grid_yy Interpolation grid arrays.
8221  !! @param ipol_value Interpolation value.
8222  !! @param algstr Algorithm string.
8223  !! @param output_file The file name for debug plot output (PostScript).
8224  !! @param enable_non_debug Optional flag, if TRUE, interpolation plot is
8225  !! saved even when *not* in the DEBUG mode. Normally, all plot outputs
8226  !! are disabled in non-DEBUG mode (`IS_DEBUG` is `FALSE`, see
8227  !! `commondata::is_debug`) because this may significantly slow
8228  !! down execution and produce lots of big PostScript files.
8229  subroutine debug_interpolate_plot_save( grid_xx, grid_yy, ipol_value, &
8230  algstr, output_file, enable_non_debug )
8231 
8232  ! Interpolation grid arrays.
8233  real(SRP), dimension(:), intent(in) :: grid_xx, grid_yy
8234  ! Interpolation value.
8235  real(SRP), intent(in) :: ipol_value
8236  ! Algorithm string.
8237  character(*), intent(in) :: algstr
8238  ! The file name for debug plot output (PostScript).
8239  character(len=*), intent(in) :: output_file
8240  ! Optional flag, if TRUE, interpolation plot is saved even when not in
8241  ! the @ref intro_debug_mode "debug mode".
8242  logical, optional, intent(in) :: enable_non_debug
8243 
8244  ! Local copy of optional
8245  logical :: enable_non_debug_here
8246 
8247  ! Local finally built command.
8248  character(len=:), allocatable :: cmd_execute
8249 
8250  !> ### Implementation notes ###
8251  !> Plots are generated only if the protected parameter
8252  !! commondata::is_plotting is set to `TRUE`. So the first thing
8253  !! is to check if it is so.
8254  if (.not. is_plotting) return
8255 
8256  !> By default, saving interpolation plots in non
8257  !! @ref intro_debug_mode "debug mode" is disabled (.FALSE.)
8258  if (present(enable_non_debug)) then
8259  enable_non_debug_here = enable_non_debug
8260  else
8261  enable_non_debug_here = .false.
8262  end if
8263 
8264  !> Produce a **debug plot** of the interpolation data. The plot is done by
8265  !! a separate program with the executable name set by the character
8266  !! parameter `commondata::exec_interpolate` (that should be in the system
8267  !! path). This program is called is called using the
8268  !! `commondata::call_external()` wrapper procedure.
8269  !! The interpolation plot program code is normally part of the
8270  !! HEDTOOLS modelling tools and is placed in `HEDTOOLS\tools` folder.
8271  !! @note Building plotting tools is done with `"make tools"` in the main
8272  !! HEDTOOLS file hierarchy. Building requires PGPLOT library and
8273  !! can be easily built on Linux; on Windows building can be more
8274  !! tricky. See code and output of `commondata::exec_interpolate`.
8275  !! @note Debug plots are not essential, so are done by a separate program.
8276  !! They may be especially useful for controlling the quality of
8277  !! polynomial `DDPINTERPOL` interpolation, that has a tendency
8278  !! towards "wrapped" ends.
8279  if (is_debug .or. enable_non_debug_here ) then
8280  call log_msg( "INFO: Saving interpolation plot: " // trim(output_file) )
8281  !> All the data for plotting are transferred into the plotting program
8282  !! via command line parameters. Each of the array or parameter should
8283  !! be in square brackets.
8284  !> No exit status or even the availability of
8285  !! `commondata::exec_interpolate` is checked. However, the dummy
8286  !! parameter `is_background_task` controls whether the plotting program
8287  !! should be executed as a parallel background task (if `TRUE`) or the
8288  !! model executable should wait for the plotting program to terminate.
8289  !! The non-parallel (default) mode is safer because calling numerous
8290  !! child processes can exhaust the system-specific limit on child
8291  !! processes resulting in an uncontrollable crash. However, non-parallel
8292  !! mode is obviously much slower.
8293  ! @note If the program is NOT in PATH on Unix systems, should add
8294  ! the prefix "./", check platform and adjust in call_external?
8295  cmd_execute = exec_interpolate // " [" // tostr(grid_xx) // "] [" // &
8296  tostr(grid_yy) // "] [" // tostr(ipol_value) // "] [" // algstr // &
8297  "] [" // trim(output_file) // "]"
8298  call call_external( &
8299  command = cmd_execute, &
8300  suppress_output = .true., suppress_error = .true., &
8301  is_background_task = .false. )
8302  end if
8303 
8304  end subroutine debug_interpolate_plot_save
8305 
8306  !-----------------------------------------------------------------------------
8307  !> Delete a file from the local file system using Fortran open status=delete
8308  !! or fast POSIX C call.
8309  !! @note The easiest way is to use `unlink` but it is non-standard (GNU
8310  !! extension).
8311  !! @note HEDTOOLS now implement a few POSIX procedures for manipulation
8312  !! of the file system. Among them, `FS_UNLINK()` is used to delete
8313  !! a file (**not** directory) and `FS_REMOVE()` deletes a file or
8314  !! a directory. Example call:
8315  !! @code
8316  !! call FS_UNLINK("obsolete_file", iostat)
8317  !! @endcode
8318  !! `iostat` is an optional integer error status of the operation.
8319  !! @warning POSIX-based `FS_UNLINK()` is now used in this procedure if the
8320  !! parameter `commondata::use_posix_fs_utils` is set to TRUE.
8321  !! See portability note on this parameter.
8322  subroutine file_delete(file_name, success)
8323  character(len=*), intent(in) :: file_name
8324  logical, optional, intent(out) :: success
8325 
8326  integer :: file_unit, file_error_status
8327  logical :: openedq, existq
8328 
8329  ! PROCNAME is the procedure name for logging and debugging (with MODNAME).
8330  character(len=*), parameter :: PROCNAME = "(file_delete)"
8331 
8332  ! #### POSIX Utilities ####
8333  ! Try to use POSIX C calls if `commondata::use_posix_fs_utils` is set.
8334  posix_used: if ( use_posix_fs_utils ) then
8335  call fs_unlink( file_name, file_error_status )
8336  if (file_error_status == 0 ) then
8337  call log_dbg( ltag_info // procname // " Deleted file " // file_name &
8338  // " using POSIX call, result is success." )
8339  if (present(success)) success = .true.
8340  else
8341  call log_msg( ltag_error // procname // " Could not delete file " // &
8342  file_name // " using POSIX call (unlink)." )
8343  if (present(success)) success = .false.
8344  end if
8345  return
8346  end if posix_used
8347 
8348  ! #### Fortran specific "manual" calls ####
8349  ! Check if the file is opened, this is important on Windows as we could
8350  ! not delete opened files, will get sharing violation error.
8351  ! can use the CHECK_FILE_OPEN() function from HEDTOOLS.
8352  inquire(file=file_name, opened=openedq, exist=existq, &
8353  iostat=file_error_status)
8354 
8355  ! If the file is accessible and not opened it can be safely deleted.
8356  if ( .not. openedq .and. existq .and. file_error_status==0 ) then
8357  ! Get a free file unit.
8358  file_unit = get_free_funit()
8359  ! Try to open
8360  open (unit=file_unit, file=file_name, status='old', &
8361  iostat=file_error_status)
8362  ! and close right away with `status='delete'`.
8363  close(unit=file_unit, status='delete', iostat= file_error_status)
8364  ! Report success status.
8365  if (present(success)) then
8366  success = (file_error_status == 0)
8367  call log_dbg( ltag_info // procname // " Deleted file " // file_name &
8368  // " with success flag " // tostr(success) // "." )
8369  end if
8370  call log_msg( ltag_info // procname // " Deleted file " // file_name &
8371  // " , result is success." )
8372  else
8373  if (present(success)) success = .false.
8374  call log_msg( ltag_info // procname // " Could not delete file " // &
8375  file_name // "." )
8376  end if
8377 
8378  end subroutine file_delete
8379 
8380 
8381  !-----------------------------------------------------------------------------
8382  !> Random operator, adds or subtracts two values with equal probability,
8383  !! used in the random walk functions.
8384  function random_add_subtract(x, y) result (out_val)
8385  !> @param[in] x is the first real number
8386  real(srp), intent(in) :: x
8387  !> @param[in] y is the second real number
8388  real(srp), intent(in) :: y
8389  !> @return *x + y* or *x - y* with equal 0.5 probability.
8390  real(srp) :: out_val
8391 
8392  if (rand_i(1,2)==1) then
8393  out_val = x + y
8394  else
8395  out_val = x - y
8396  end if
8397 
8398  end function random_add_subtract
8399 
8400  !-----------------------------------------------------------------------------
8401  !> @brief Initialises the system environment and sets basic parameters.
8402  !! @note This procedure also initialises the logger by a call of
8403  !! `commondata::logger_init`.
8404  subroutine system_init()
8405  use csv_io, only : get_free_funit
8406  ! Local string variable to keep a temporary value while parsing parameters.
8407  ! @note The character string variable that gets its value from the
8408  ! environment variable or command line intrinsic procedures
8409  ! `get_environment_variable` or `get_command_argument` cannot
8410  ! be allocatable. In such a case it does not allocate and remains
8411  ! blank string value.
8412  character(len=LABEL_LENGTH) :: debug_string
8413 
8414  ! Checking validity (is executable) codes for external programs.
8415  logical :: check_1, check_2, check_3, check_4
8416 
8417  ! Flag to avoid checking external executables which breaks Intel Fortran.
8418  logical :: do_check_externals
8419 
8420  ! PROCNAME is the procedure name for logging and debugging
8421  character(len=*), parameter :: PROCNAME = "(system_init)"
8422 
8423  ! Local variable to check commondata::lock_file exists.
8424  logical :: lock_preexists
8425 
8426  ! Local variable used to get the lock file write iostat value.
8427  integer :: lock_iostat
8428 
8429  ! Local variable that keeps IEEE error condition code
8430  integer :: ieee_check_result
8431 
8432  !> ### Check lock file ###
8433  !> First, the program checks if @ref intro_overview_lockfile
8434  !! "the lock file" exists. If it does, this can mean that a simulation
8435  !! is already running in the working directory. Thus, the current process
8436  !! is terminated before any files are written to avoid mess.
8437  !! @note If the commondata::lock_file has not been deleted automatically
8438  !! for any reason but one is sure that no simulation is actually
8439  !! running (e.g. there was a crash before or the program was closed
8440  !! by Ctrl+C), just delete the commondata::lock_file and restart the
8441  !! program.
8442  inquire( file=lock_file, exist=lock_preexists )
8443  if ( lock_preexists ) then
8444  call system_halt( is_error = .true., &
8445  message=error_lock_preexists, &
8446  ignore_lockfile = .true. )
8447  end if
8448 
8449  !> ### Random seed ###
8450  !> Then, the random seed is initialised by
8451  !! [RANDOM_SEED_INIT()](http://ahamodel.uib.no/doc/ar01s09.html#_subroutine_random_seed_init)
8452  !! from `HEDTOOLS`. Note that it is platform-dependent and uses the system
8453  !! entropy pool on Unix systems and the date on Windows.
8454  call random_seed_init()
8455 
8456  !> ### Execution control ###
8457  !> #### The DEBUG mode ####
8458  !> The protected global variable `IS_DEBUG` (commondata::is_debug) sets
8459  !! up the @ref intro_debug_mode "debug mode" of execution. The debug mode
8460  !! results in huge amount of output and logs that significantly slows
8461  !! down execution. Debug mode can be set using the environment variable
8462  !! `AHA_DEBUG=1`, `AHA_DEBUG=YES` or `AHA_DEBUG=TRUE`.
8463  call get_environment_variable(name="AHA_DEBUG", value=debug_string)
8464  debug_string = lowercase(debug_string)
8465  if ( trim(debug_string)=="1" .or. &
8466  trim(debug_string)=="yes" .or. &
8467  trim(debug_string)=="true" ) then
8468  ! DEBUG_COMPILER_OPTIMISE: see 'Compiler optimisation of debug mode'
8469  is_debug =.true.
8471  else if ( trim(debug_string)=="0" .or. &
8472  trim(debug_string)=="no" .or. &
8473  trim(debug_string)=="false" ) then
8474  ! DEBUG_COMPILER_OPTIMISE: see 'Compiler optimisation of debug mode'
8475  is_debug =.false.
8477  end if
8478 
8479  !> Debug mode can also be set by setting the runtime **command line**
8480  !! parameter to `DEBUG`, `DEBUG=1`, `DEBUG=YES` or `DEBUG=TRUE` to the
8481  !! model executable, e.g.
8482  !! @code{.sh}
8483  !! ./MODEL.exe DEBUG
8484  !! @endcode
8485  !! See @ref intro_debug_mode "The DEBUG mode" for more details.
8486  !> #### Logging in the DEBUG mode ####
8487  !! The procedure `CALL_DBG()` (see commondata::log_dbg()) is used to
8488  !! issue logger messages only in the DEBUG mode. Those messages, that
8489  !! should be issued in any mode, both DEBUG and non-DEBUG, `LOG_MSG()`
8490  !! from the HEDTOOLS should be used.
8491  !!
8492  !! **Examples:** This code produces the logger message:
8493  !! @code
8494  !! call LOG_MSG("Revision ID: " // SVN_Version // ".")
8495  !! @endcode
8496  !! However, the below code produces logger output only in the
8497  !! @ref intro_debug_mode "debug mode":
8498  !! @code
8499  !! call LOG_DBG(LTAG_INFO // "Agent is freezing.", PROCNAME, MODNAME)
8500  !! @endcode
8501  !! Note the use of the logger tag commondata::ltag_info in the later
8502  !! example.
8503  call get_command_argument(number=1, value=debug_string)
8504  debug_string = lowercase(debug_string)
8505  if ( trim(debug_string)=="debug" .or. &
8506  trim(debug_string)=="debug=1" .or. &
8507  trim(debug_string)=="debug=yes" .or. &
8508  trim(debug_string)=="debug=true" ) then
8509  ! DEBUG_COMPILER_OPTIMISE: see 'Compiler optimisation of debug mode'
8510  is_debug =.true.
8512  end if
8513 
8514  !> #### Compiler optimisation of the debug mode ####
8515  !> @anchor system_debug_optimise
8516  !! Setting the `IS_DEBUG` as a protected variable commondata::is_debug
8517  !! enables one to switch between the DEBUG and non-DEBUG mode of the
8518  !! program execution. However, it can have a performance penalty because
8519  !! all the calls to the debugging code remains in the model. The program
8520  !! then has to test numerous if conditions `if ( IS_DEBUG ) then...` which
8521  !! are likely to slow down execution. Setting commondata::is_debug as a
8522  !! fixed parameter (i.e. with the `parameter` attribute) would allow a
8523  !! highly optimising compiler to determine at the compile time that the
8524  !! numerous debugging instructions are never executed and remove them
8525  !! from the machine instructions that are then generated. However,
8526  !! declaring parameter won't allow to change the value of the `IS_DEBUG`.
8527  !! All such cases should be disabled. Within the code, such places are
8528  !! marked with the DEBUG_COMPILER_OPTIMISE tag. If `IS_DEBUG` is declared
8529  !! as a parameter, all these places should be disabled, e.g.
8530  !! @code
8531  !! trim(debug_string)=="true" ) then
8532  !! ! DEBUG_COMPILER_OPTIMISE: see 'Compiler optimisation of debug mode'
8533  !! ! IS_DEBUG =.TRUE.
8534  !! IS_SCREEN_OUTPUT = .TRUE.
8535  !! @endcode
8536  !! In effect, it would not be possible to switch between the debug modes
8537  !! on the fly.
8538 
8539  !> #### Controlling the screen output ####
8540  !> The logger outputs normally go to the log file. But can also be shown
8541  !! on the terminal screen (standard output). This is controlled by the
8542  !! protected global variable `commondata::is_screen_output`.
8543  !!
8544  !! The Screen mode can be reset independently of DEBUG mode using the
8545  !! shell environment variable `AHA_SCREEN=1`, `AHA_SCREEN=YES` or
8546  !! `AHA_SCREEN=TRUE`.
8547  !! For example, on Linux it is done
8548  !! @code{.sh}
8549  !! export AHA_SCREEN=1
8550  !! @endcode
8551  !! on Windows command line:
8552  !! @code{.sh}
8553  !! set AHA_SCREEN=1
8554  !! @endcode
8555  !!
8556  !! It is possible to change the output channel of the logger during the run
8557  !! time using the `LOG_CONFIGURE()` procedure. For example certain log
8558  !! message can selectively appear on the terminal standard output, and then
8559  !! the default behaviour controlled by the commondata::is_screen_output
8560  !! parameter restored:
8561  !! @code
8562  !! call LOG_CONFIGURE("writeonstdout" , .TRUE.) ! Enable screen temporarily
8563  !! call LOG_MSG( "*** START DEBUG BLOCK ***" ) ! Send message
8564  !! call LOG_CONFIGURE("writeonstdout" , IS_SCREEN_OUTPUT) ! Enable default
8565  !! @endcode
8566  !! For more details see the
8567  !! [LOGGER Module](http://ahamodel.uib.no/doc/ar01s10.html) documentation of
8568  !! the HEDTOOLS.
8569  call get_environment_variable(name="AHA_SCREEN", value=debug_string)
8570  debug_string = lowercase(debug_string)
8571  if ( trim(debug_string)=="1" .or. &
8572  trim(debug_string)=="yes" .or. &
8573  trim(debug_string)=="true" ) is_screen_output =.true.
8574  if ( trim(debug_string)=="0" .or. &
8575  trim(debug_string)=="no" .or. &
8576  trim(debug_string)=="false" ) is_screen_output =.false.
8577 
8578  !> #### Generation of debug plots ####
8579  !> The debug plots can be generated. However, their number is normally just
8580  !! huge. Also, debug plots are produced by calling external programs which,
8581  !! if done too frequently, can exhaust the system-specific limit on the
8582  !! number of child processes. Production of debug plots is globally
8583  !! by the protected global variable `commondata::is_plotting`.
8584  !!
8585  !! This can be reset independently of using the shell environment variable
8586  !! `AHA_DEBUG_PLOTS=1`, `AHA_DEBUG_PLOTS=YES` or `AHA_DEBUG_PLOTS=TRUE`.
8587  !! For example, on Linux it is done
8588  !! @code{.sh}
8589  !! export AHA_DEBUG_PLOTS=1
8590  !! @endcode
8591  !! on Windows command line:
8592  !! @code{.sh}
8593  !! set AHA_DEBUG_PLOTS=1
8594  !! @endcode
8595  call get_environment_variable(name="AHA_DEBUG_PLOTS", value=debug_string)
8596  debug_string = lowercase(debug_string)
8597  if ( trim(debug_string)=="1" .or. &
8598  trim(debug_string)=="yes" .or. &
8599  trim(debug_string)=="true" ) is_plotting =.true.
8600  if ( trim(debug_string)=="0" .or. &
8601  trim(debug_string)=="no" .or. &
8602  trim(debug_string)=="false" ) is_plotting =.false.
8603 
8604  !> #### Compression of big output data files ####
8605  !> The model can generate big data files for the agent population and
8606  !! habitat objects. These files can be automatically compressed using the
8607  !! external command defined by the commondata::cmd_zip_output parameter.
8608  !! This compression option is determined by the protected global variable
8609  !! `commondata::is_zip_outputs`.
8610  !!
8611  !! This can be reset using the shell environment variable
8612  !! `AHA_ZIP_FILES=1`, `AHA_ZIP_FILES=YES` or `AHA_ZIP_FILES=TRUE`.
8613  !! For example, on Linux it is done
8614  !! @code{.sh}
8615  !! export AHA_ZIP_FILES=1
8616  !! @endcode
8617  !! on Windows command line:
8618  !! @code{.sh}
8619  !! set AHA_ZIP_FILES=1
8620  !! @endcode
8621  call get_environment_variable(name="AHA_ZIP_FILES", value=debug_string)
8622  debug_string = lowercase(debug_string)
8623  if ( trim(debug_string)=="1" .or. &
8624  trim(debug_string)=="yes" .or. &
8625  trim(debug_string)=="true" ) is_zip_outputs =.true.
8626  if ( trim(debug_string)=="0" .or. &
8627  trim(debug_string)=="no" .or. &
8628  trim(debug_string)=="false" ) is_zip_outputs =.false.
8629 
8630  !> #### Checking external executables ####
8631  !> This procedure checks external procedures for existence and being
8632  !! executable. However, there seems to be a
8633  !! [bug in Intel Fortran](https://software.intel.com/en-us/forums/intel-fortran-compiler-for-linux-and-mac-os-x/topic/743814)
8634  !! implementation of the intrinsic `execute_command_line` procedure:
8635  !! if the called program is not found in the `PATH`, the whole program
8636  !! crashes with "Segmentation fault".
8637  !! @code{.sh}
8638  !! forrtl: severe (174): SIGSEGV, segmentation fault occurred
8639  !! @endcode
8640  !! A workaround is to avoid checking the externals in such a case.
8641  !! This can be done by setting the
8642  !! environment variable `AHA_CHECK_EXTERNALS` to `0`, `no` or `false`.
8643  !! @note This is not normally required if GNU gfortran is used for
8644  !! building.
8645  !! For example, on Linux it is done
8646  !! @code{.sh}
8647  !! export AHA_CHECK_EXTERNALS=NO
8648  !! @endcode
8649  !! on Windows command line:
8650  !! @code{.sh}
8651  !! set AHA_CHECK_EXTERNALS=NO
8652  !! @endcode
8653  do_check_externals =.true.
8654  call get_environment_variable(name="AHA_CHECK_EXTERNALS", value=debug_string)
8655  debug_string = lowercase(debug_string)
8656  if ( trim(debug_string)=="0" .or. &
8657  trim(debug_string)=="no" .or. &
8658  trim(debug_string)=="false" ) do_check_externals =.false.
8659 
8660  !> ### Implementation details ###
8661  !> - Get the time tag for the model in this format (YYYYMMDD) by call to
8662  !! the `commondata::tag_mmdd()` procedure. commondata::mmdd is a global
8663  !! public protected variable. It should be used for all date tagging.
8664  mmdd = tag_mmdd()
8665 
8666  !> - Initialise the system logger by `commondata::logger_init`. Some
8667  !! system parameters, e.g. the platform type are determined in the
8668  !! `commondata::logger_init`.
8669  call logger_init()
8670 
8671  !> #### Quick integrity checks ####
8672  call log_msg( ltag_info // "Starting initial checks." )
8673 
8674  !> - Check and make sure IEEE float point errors are supported and not
8675  !! present at the start
8676  call log_msg(ltag_info // "Checking IEEE math exception support")
8677  ieee_check_result = ieee_error_reporting( reset=.true. )
8678  if ( ieee_check_result == 0 ) then
8679  call log_msg( ltag_info // "No IEEE exception is reported.")
8680  else
8681  call log_msg( ltag_info // "IEEE exception is reported, error code: " &
8682  // tostr(ieee_check_result) )
8683  call log_msg( ltag_info // "Note that it can be processor-dependent,"// &
8684  "some exceptions (e.g. IEEE_INEXACT) can be just ignored.")
8685  ieee_check_result = ieee_error_reporting( reset=.true. )
8686  if (ieee_check_result == 0) then
8687  call log_msg( ltag_info // "So far all exceptions are reset to FALSE.")
8688  else
8689  call log_msg( ltag_error // "Cannot reset IEEE exception flags," // &
8690  "something may be wrong, but is platform/CPU dependent.")
8691  end if
8692  end if
8693 
8694  !> - Check external executables that are called from the model code.
8695  !! These are basically not essential and mainly used only in the
8696  !! @ref intro_debug_mode "debug mode".
8697  if (do_check_externals) then
8698  call log_delimiter(log_level_chapter)
8699  call log_msg (ltag_info // "Checking external procedures. " // &
8700  "Note: may not work on all platforms.")
8701  call log_msg (ltag_warn // "THIS CAN CRASH THIS PROGRAM IF INTEL FORTRAN")
8702  call log_msg (ltag_warn // "COMPILER IS USED FOR BUILDING.")
8703  call log_msg (ltag_warn // "IN SUCH A CASE SET ENVIRONMENT VARIABLE")
8704  call log_msg (ltag_warn // "'AHA_CHECK_EXTERNALS=FALSE' AND DISABLE")
8705  call log_msg (ltag_warn // "DEBUG PLOTS BY SETTING ENVIRONMENT VARIABVLE")
8706  call log_msg (ltag_warn // "'AHA_DEBUG_PLOTS=FALSE'.")
8707  call log_delimiter(log_level_chapter)
8708 
8709  call log_check_external(exec_interpolate, is_valid = check_1)
8710  call log_check_external(exec_scatterplot, is_valid = check_2)
8711  call log_check_external(exec_histogram, is_valid = check_3)
8712 
8713  !> - If the commondata::is_zip_outputs is enabled (TRUE), a check is
8714  !! done if the external compression program
8715  !! (commondata::cmd_zip_output) can be called. It involves
8716  !! compressing a small test file and getting the exit code.
8717  check_zip: block
8718  character(len=*), parameter :: test_file_zip = "ztest_compression"
8719  integer :: test_file_unit
8720  check_4 = .true.
8721  if ( is_zip_outputs ) then
8722  test_file_unit = get_free_funit()
8723  open( unit=test_file_unit, file=test_file_zip, &
8724  iostat=lock_iostat, action='write', status='replace', &
8725  position='append' )
8726  close(test_file_unit)
8727  call log_msg( ltag_info // "Checking if compression of data " // &
8728  "files is possible: " // &
8729  cmd_zip_output // " " // test_file_zip )
8730  call log_msg( ltag_warn // "If this command hangs, disable " // &
8731  "data file compression by setting environment " // &
8732  "variable AHA_ZIP_FILES=NO." )
8733  !> @warning commondata::log_check_external() procedure is called
8734  !! in the synchronous mode and might hang the system if
8735  !! the child process hangs for any reason, e.g. if the
8736  !! compression utility is wrongly configured and waits
8737  !! input from the standard input.
8738  call log_check_external( cmd_zip_output // " " // test_file_zip, &
8739  is_valid = check_4 )
8740  call log_msg( ltag_info // "Command executed and not hanged.")
8741  !> If compression fails, automatic background compression is
8742  !! disabled. commondata::is_zip_outputs is set to FALSE.
8743  if ( check_4 .eqv. .false. ) then
8744  call file_delete( test_file_zip )
8745  is_zip_outputs = .false.
8746  call log_msg( ltag_info // cmd_zip_output//" "//test_file_zip // &
8747  ": Compression test failed, IS_ZIP_OUTPUTS disabled")
8748  else
8749  call file_delete( test_file_zip // zip_file_extenssion )
8750  end if
8751  end if
8752  end block check_zip
8753 
8754  !> - The results of these checks are reported in the logger.
8755  call log_msg( ltag_info // "Validity (is executable) codes: " // &
8756  tostr([check_1, check_2, check_3, check_4]) )
8757 
8758  !> If **any** of the external *plotting utilities* cannot be executed:
8759  !! - commondata::exec_interpolate
8760  !! - commondata::exec_scatterplot
8761  !! - commondata::exec_histogram
8762  !! .
8763  !! plotting is disabled by setting commondata::is_plotting to FALSE.
8764  if ( any([check_1,check_2,check_3] .eqv. .false.) ) then
8765  call log_msg( ltag_warn // "External procedures cannot be called" // &
8766  ", generation of debug plots is DISABLED: " // &
8767  "IS_PLOTTING set to FALSE." )
8768  is_plotting = .false.
8769  call log_delimiter(log_level_volume)
8770  call log_msg( " DEBUG is: " // tostr(is_debug) // &
8771  "; SCREEN is: " // tostr(is_screen_output) // &
8772  "; PLOTTING is: " // tostr(is_plotting) )
8773  call log_delimiter(log_level_volume)
8774  end if
8775  end if
8776 
8777  !> - Check automatic allocation of arrays on intrinsic assignment. The
8778  !! code here and there depends on this recent feature of Fortran.
8779  !! If the test fails, manual allocation of such arrays with
8780  !! [allocate](http://ahamodel.uib.no/intel/hh_goto.htm#GUID-2E8BB6B6-6454-4DB6-9982-5BD97DEB47C1.html)
8781  !! should be recoded. The test is tagged as `TEST_AUTOALLOC`.
8782  test_autoalloc: block
8783  real(SRP), allocatable, dimension(:) :: test_array
8784  test_array = [ 1.0_srp, 2.0_srp, 3.0_srp ]
8785  if ( .not. allocated(test_array) .or. size(test_array) /= 3 ) then
8786  call log_delimiter(log_level_chapter)
8787  call log_msg( ltag_crit // "TEST_AUTOALLOC: Automatic array " // &
8788  "allocation is not enabled or supported" // &
8789  " by the compiler. " // procname // "::" // modname )
8790  call system_halt(is_error=.true., message=error_no_autoalloc )
8791  end if
8792  end block test_autoalloc
8793 
8794  !> - Check automatic determination of the size in parameter parameter
8795  !! arrays of the dimension statement style: `dimension(*)`. All fairly
8796  !! modern Fortran compilers should support this feature.
8797  test_auto_param_arrays: block
8798  !> @note If the compiler does not support `dimension(*)` it would
8799  !! probably just fail to compile this code. So, it won't run
8800  !! up to this point.
8801  real(SRP), parameter, dimension(*) :: test_array = &
8802  [ 1.0_srp, 2.0_srp, 3.0_srp ]
8803  if ( size(test_array) /= 3 .or. &
8804  test_array(1) /= 1.0_srp .or. &
8805  test_array(2) /= 2.0_srp .or. &
8806  test_array(3) /= 3.0_srp ) then
8807  call log_delimiter(log_level_chapter)
8808  call log_msg( ltag_crit // "TEST_AUTO_PARAM_ARRAYS: Constant array " &
8809  // "automatic size determination is not supported" // &
8810  " by the compiler. " // procname // "::" // modname )
8811  call system_halt(is_error=.true., message=error_auto_param_arrays )
8812  end if
8813  end block test_auto_param_arrays
8814 
8815  !> - If fatal tests (`TEST_AUTOALLOC`, `TEST_AUTO_PARAM_ARRAYS`) fail,
8816  !! commondata::system_halt() is called
8817  !! .
8818  !!
8819  !> Finally, a @ref intro_overview_lockfile "lock file" is created. This
8820  !! file keeps opened during the whole simulation and is closed and deleted
8821  !! at the end. Thus, its primary use is to signal that the simulation is
8822  !! still going. See commondata::lock_file and commondata::lock_file_unit
8823  !! and @ref intro_overview_lockfile "The lock file" for details.
8824  !! @note Lock file operation uses native Fortran intrinsic `open`
8825  !! statement rather than any higher level procedures like
8826  !! @ref file_io. This is because the file is for signalling
8827  !! only (intended to be empty) and nothing is actually written
8828  !! into it.
8829  lock_file_unit = get_free_funit()
8830  open( unit=lock_file_unit, file=lock_file, iostat=lock_iostat, &
8831  action='write', status='replace', position='append' )
8832  !> Note that if the lock file cannot be written, the simulation is not
8833  !! halted automatically, but an error is issued to the logger because
8834  !! such error signals severe problems with disk access (e.g. read only
8835  !! mode, no space left etc.).
8836  if ( lock_iostat /= 0 ) then
8837  call log_msg( ltag_error // "Cannot write lock file: " // lock_file // &
8838  ". Trying to continue but errors and crashes are " // &
8839  "expected due to disk write problems!" )
8840  else
8841  call log_msg( ltag_info // "Created Lock file " // lock_file // &
8842  ", unit " // tostr(lock_file_unit) )
8843  end if
8844 
8845  end subroutine system_init
8846 
8847  !-----------------------------------------------------------------------------
8848  !> Halt execution of the system with a specific message and exit code.
8849  !! The exit code is normally passed to the operating system. However, this
8850  !! behaviour is implementation dependent and can be unexpected on specific
8851  !! the platform(s) and the compiler(s).
8852  !! - Checking the exit code in bash can be done with "`$?`" variable.
8853  !! - Checking exit code on Windows is done using "`%ERRORLEVEL%`" variable
8854  !! e.g.
8855  !! @code
8856  !! if %ERRORLEVEL% EQU 0 echo Normal termination
8857  !! @endcode
8858  !! .
8859  !> @note Using specific exit code could allow to place the simulation model
8860  !! into an automated batch job more easily. For example, several
8861  !! simulations with different parameters could be processed. In such
8862  !! a case it would be good to know if the program failed or not.
8863  !> An example termination call due to an error:
8864  !! @code
8865  !! call system_halt(is_error=.TRUE., message=ERROR_NO_AUTOALLOC )
8866  !! @endcode
8867  subroutine system_halt(is_error, message, ignore_lockfile)
8868 
8869  !> The standard error unit is obtained from the `ISO_FORTRAN_ENV`.
8870  !! The final termination messages go to the standard error device rather
8871  !! than standard output to adhere the standard.
8872  use, intrinsic :: iso_fortran_env, only : error_unit
8873 
8874  !> @param[in] is_error Optional flag that signals that the program is
8875  !! terminating due to error. The default is normal error-free
8876  !! termination with zero exit code.
8877  logical, optional, intent(in) :: is_error
8878  !> @param[in] message Optional message that is passed the the logger
8879  !! immediately before the program is terminated.
8880  character (len=*), optional, intent(in) :: message
8881  !> @param[in] ignore_lockfile is an optional flag to ignore closing and
8882  !! deleting @ref intro_overview_lockfile "the lock file". The
8883  !! default value is FALSE. If it is TRUE, the lock file is
8884  !! not touched. This is primarily necessary to halt the
8885  !! execution because the program discovers the lock file on
8886  !! startup which may indicate another simulation is currently
8887  !! running here. In such a case, deleting the lock file would
8888  !! interfere with this pre-running simulation.
8889  logical, optional, intent(in) :: ignore_lockfile
8890 
8891  ! Local copies of optionals
8892  integer :: error_code
8893  character(len=LONG_LABEL_LENGTH) :: message_loc
8894 
8895  !> ### Implementation notes ###
8896  !> There are two possible exit code:
8897  !> - **EXIT_CODE_DEF** is the default exit code that is returned to
8898  !! the operating system. The default value for error-free termination is
8899  !! zero.
8900  integer, parameter :: EXIT_CODE_DEF = 0
8901 
8902  !> - **EXIT_CODE_ERROR** is the fixed exit code that is returned to the
8903  !! operating system in case of error.
8904  !! .
8905  integer, parameter :: EXIT_CODE_ERROR = 255
8906 
8907  ! Local variable used to get the lock file write iostat value.
8908  integer :: lock_iostat
8909  ! Logical flag to process the @ref intro_overview_lockfile "lock file".
8910  logical :: do_not_touch_lock
8911 
8912  error_code = exit_code_def
8913  if (present(is_error)) then
8914  if (is_error) error_code = exit_code_error
8915  end if
8916 
8917  if (present(message)) then
8918  message_loc = message
8919  else
8920  message_loc = "Program terminated with exit code " // &
8921  tostr(error_code) // "."
8922  end if
8923 
8924  !> The @ref intro_overview_lockfile "lock file" commondata::lock_file is
8925  !! closed and then deleted (commondata::file_delete()).
8926  !! See commondata::lock_file and commondata::lock_file_unit and
8927  !! @ref intro_overview_lockfile "The lock file" for details.
8928  !! @note Note that setting `ignore_lockfile` parameter to TRUE disables
8929  !! checking and deleting the lock file.
8930  if (present(ignore_lockfile)) then
8931  do_not_touch_lock = ignore_lockfile
8932  else
8933  do_not_touch_lock = .false.
8934  end if
8935  if ( do_not_touch_lock .eqv. .false. ) then
8936  close(lock_file_unit, iostat=lock_iostat)
8937  if ( lock_iostat /= 0 ) then
8938  call log_msg( ltag_error // "Cannot close lock file " // lock_file // &
8939  ", it will NOT be deleted automatically!" )
8940  else
8941  call file_delete( lock_file )
8942  end if
8943  end if
8944 
8945  !> The logger is now issues the final messages and shuts down.
8946  call log_delimiter(log_level_volume)
8947  call log_msg( ltag_major // "EXITING with message: " // message_loc )
8948  call log_dbg( ltag_major // "Exit code returned to the OS: " // &
8949  tostr(error_code) )
8950  call log_delimiter(log_level_volume)
8951  call log_shutdown()
8952 
8953  !> The final message goes to the standard error device.
8954  write(error_unit,*) message_loc
8955 
8956  !> And the program terminates with specific exit code.
8957  select case (error_code)
8958  case (exit_code_error)
8959  stop exit_code_error
8960  case (exit_code_def)
8961  stop exit_code_def
8962  case default
8963  stop exit_code_def
8964  end select
8965 
8966  end subroutine system_halt
8967 
8968  !-----------------------------------------------------------------------------
8969  !> @brief **logger_init** Initialise the system and the system logger.
8970  !! @details `logger_init` is called only once at `commondata::system_init()`
8971  !! to set up the basic parameters and the logging facility.
8972  !! For example, it sets the log file name, if timestamps should be
8973  !! produced, if we need screen output, log delimiter characters and
8974  !! any other similar parameters. They can be changed later if needed.
8975  !! `logger_init` also writes some short initial information to the
8976  !! log file like model name etc.
8977  subroutine logger_init()
8978 
8979  ! Subroutine/function name for DEBUG LOGGER. Every subroutine and function
8980  ! must contain a private parameter `PROCNAME` setting its name for
8981  ! the loger. But it is not used here.
8982  character (len=*), parameter :: procname = "(logger_init)"
8983 
8984  !> ### Implementation details ###
8985  !> #### Notable variables ####
8986  !> **logfile** character variable defines the file name for the main
8987  !! log output. Such a log file name is normally assembled from pieces,
8988  !! such as model name, date and time tag etc.
8989  ! @note Assigning logfile a specific name directly within this character
8990  ! variable declaration results in this gfortran internal
8991  ! **compiler error**:
8992  ! `f951: internal compiler error: in is_illegal_recursion, at
8993  ! fortran/resolve.c:1483
8994  ! Please submit a full bug report,
8995  ! with preprocessed source if appropriate.
8996  ! See <file:///usr/share/doc/gcc-4.8/README.Bugs> for instructions.`
8997  ! The same compiler error results if `logfile` is declared as a
8998  ! `parameter` constant (with assignment), the same with `(len=*)`
8999  ! or `(len=FILENAME_LENGTH)`.
9000  character (len=FILENAME_LENGTH) :: logfile
9001 
9002  !> **run_on_hostname** is an character string variable that keeps the
9003  !! hostname of the system the model is running on.
9004  !! @warning Hostname is determined using the `hostnm` function that is
9005  !! non-standard and not portable. However, it is supported by
9006  !! GNU and Intel Fortran compilers. If not supported by the
9007  !! currently used compiler, call to this function should be
9008  !! disabled in this procedure.
9009  character (len=FILENAME_LENGTH) :: run_on_hostname
9010  integer :: istat
9011 
9012  ! Logger raw parameters.
9013  integer :: logger_unit
9014  logical :: is_stdout, is_logfile
9015 
9016  ! Local counter
9017  integer :: i
9018 
9019  ! Model abstract from the abstract file
9020  character(len=LONG_LABEL_LENGTH), allocatable, dimension(:) :: &
9021  model_abstract_array
9022 
9023  ! @warning Assign value to `logfile` separately as doing this in the
9024  ! declaration line results in weird internal compiler error
9025  !! with gfortran.
9026  logfile = "output_" // model_name // "_" // mmdd // "_MAIN.log"
9027  logfile = "output_model_debug_MAIN.log" ! fixed name for debug only
9028 
9029  !...........................................................................
9030  !> #### The procedure ####
9031  !> We first set parameters of the log, switch timestamps, screen output
9032  !! when DEBUG=TRUE, set delimiters and file optionally unit.
9033  call log_configure("timestamp", .true.) ! do timestamps in the log
9034  call log_configure("writeonstdout" , is_screen_output)
9035 
9036  !> Delimiters here have the length 60 character.
9037  call log_configure("level_string_volume", repeat("=",60)) ! delimiters
9038  call log_configure("level_string_chapter", repeat("-",60))
9039  call log_configure("level_string_section", repeat("*",60))
9040  call log_configure("level_string_subsection", repeat("+",60))
9041 
9042  !> We then initialise the log and set the log file name. The second dummy
9043  !! parameter set to FALSE defines log file overwrite (don't append to the
9044  !! old log file).
9045  ! @note Note that we have to use `trim` to delete trailing blanks from
9046  ! the fixed length string.
9047  call log_startup (trim(logfile), .false.)
9048 
9049  !> We also print some some initial info to the log, like the name of the
9050  !! model.
9051  call log_delimiter(log_level_volume)
9052  call log_msg("Starting model: " // model_name // " --- Date Tag: " // &
9053  mmdd // ".")
9054  call log_msg("Model description: " // model_descr)
9055  call log_msg("Model Revision string: " // svn_version_string)
9056  svn_version = parse_svn_version() !< `SVN_Version` is global public.
9057  call log_msg(" Revision ID: " // svn_version // ".")
9058 
9059  !> The Model Abstract is obtained from the abstract file
9060  !! commondata::model_abstract_file and logged.
9061  call log_delimiter(log_level_chapter)
9062  model_abstract_array = parse_abstract()
9063  call log_msg( "Model Abstract (" // tostr(size(model_abstract_array)) // &
9064  " lines):" )
9065  do i = 1, size( model_abstract_array )
9066  call log_msg( model_abstract_array(i) )
9067  end do
9068  call log_delimiter(log_level_chapter)
9069 
9070  !> Then detect the runtime platform and set integer platform ID that shows
9071  !! if we are running on Windows or Unix.
9072  if ( platform_is_windows() ) then
9074  call log_msg(" Running on Microsoft Windows platform: PLATFORM_WINDOWS.")
9075  else
9077  call log_msg(" Running on a Unix/Linux platform: PLATFORM_UNIX " // &
9078  "(probably).")
9079  end if
9080 
9081  !> Determine the compiler version and the compiler parameters using the
9082  !! F2008 `compiler_version()` and `compiler_options()` inquiry functions.
9083  !! Because this functionality may not have been implemented in many
9084  !! current compilers (e.g. Intel Fortran 17), it is disabled here.
9085  ! @warning `compiler_version` and `compiler_options` are part of F2008 and
9086  ! may not be available on all compilers and systems. They are
9087  ! defined in `ISO_FORTRAN_ENV` (require `use ISO_FORTRAN_ENV`).
9088  ! @warning The F2008 `compiler_version()` and `compiler_options()` inquiry
9089  ! functions are **not** supported by Intel Fortran 2017. So
9090  ! **disabled** here.
9091  !call LOG_MSG(" Compiled by " // compiler_version() // " with options: " &
9092  ! // compiler_options() )
9093 
9094  !> Determine the hostname (computer name) the program is running on. Then
9095  !! log hostname if determined successfully.
9096  !! @warning Hostname is determined using the `hostnm` function that is
9097  !! non-standard and not portable. However, it is supported by
9098  !! GNU and Intel Fortran compilers. If not supported by the
9099  !! currently used compiler, call to this function should be
9100  !! disabled in this procedure. With Intel Fortran compiler,
9101  !! using this functionality requires declaring.
9102  !! use IFPORT, only : hostnm
9103  !! Therefore, determining hostname is disabled so far.
9104  run_on_hostname = "undefined"
9105  !istat = hostnm( run_on_hostname ) ! @warning Nonstandard and not portable!
9106  !if ( istat == 0 ) then
9107  ! call LOG_MSG(" Hostname: " // trim(run_on_hostname))
9108  !end if
9109 
9110  call log_msg(" DEBUG is: " // tostr(is_debug) // &
9111  "; SCREEN is: " // tostr(is_screen_output) // &
9112  "; PLOTTING is: " // tostr(is_plotting) )
9113  !> Print the logger parameters in to the log itself.
9114  call log_cget("writeonstdout", is_stdout)
9115  call log_cget("writeonlogfile", is_logfile)
9116  call log_cget("logfileunit", logger_unit)
9117  call log_msg("Logger configuration options:")
9118  call log_msg(" Write standard output is " // tostr(is_stdout) // &
9119  ", write to logfile is " // tostr(is_logfile) // &
9120  " with unit number " // tostr(logger_unit))
9121 
9122  !> Print some basic constants, e.g. commondata::srp, commondata::hrp etc.
9123  call log_msg("Basic constants: ")
9124  call log_msg(" Standard (SRP) precision: " // tostr(srp))
9125  call log_msg(" High (HRP) precision: " // tostr(hrp))
9126  call log_msg(" LONG integer precision: " // tostr(long))
9127  call log_msg(" ZERO (SRP): " // tostr(zero))
9128  call log_msg(" Smallest real value TINY_SRP: " // tostr(tiny_srp))
9129  call log_msg(" Default low tolerance TOLERANCE_LOW_DEF_SRP: " // &
9130  tostr(tolerance_low_def_srp))
9131  call log_msg(" Default high tolerance TOLERANCE_HIGH_DEF_SRP: " // &
9132  tostr(tolerance_high_def_srp))
9133  call log_msg(" Sanitisers bounds: " // tostr(lo_valid_sanitised) // &
9134  ":" // tostr(hi_valid_sanitised) )
9135  !> Print the main parameters of the model, population size etc.
9136  call log_msg("Main parameters of the model:")
9137  call log_msg(" Population size " // tostr(popsize))
9138  call log_msg(" Lifecycle length " // tostr(lifespan))
9139 
9140  !> Print also some parameters of the Genetic Algorithm.
9141  call log_msg("Genetic Algorithm parameters:")
9142  call log_msg(" Pre-evolution selection of the best, proportion: " // &
9143  tostr(ga_reproduce_pr) // ", N=" // tostr(ga_reproduce_n) )
9144  call log_msg(" Pre-evolution life cycle starts from " // &
9145  tostr(preevol_tsteps) // " cycles (full lifespan is " // &
9146  tostr(lifespan) // ")" )
9147 
9148  !> Finally, issue a horizontal line delimiter into the log. This finishes
9149  !! initialising the logger.
9150  call log_delimiter(log_level_volume)
9151 
9152  end subroutine logger_init
9153 
9154  !-----------------------------------------------------------------------------
9155  !> @brief `LOG_DBG`: debug message to the log. The message goes to the
9156  !! logger only when running in the DEBUG mode.
9157  !! @param[in] message_string String text for the log message
9158  !! @param[in] procname Optional procedre name for debug messages
9159  !! @param[in] modname Optional module name for debug messages
9160  !! @details This subroutine is a wrapper to `LOG_MSG()` from HEDTOOLS for
9161  !! writing debug messages by the module `LOGGER`. The debug message
9162  !! message defined by the `message_string` parameter is issued only
9163  !! when the model runs in the @ref intro_debug_mode "debug mode",
9164  !! i.e. if `IS_DEBUG=.TRUE.`
9165  !! @note Standard `LOG_MSG()` procedure should be used for all logger
9166  !! messages that are produced in the normal non
9167  !! @ref intro_debug_mode "debug mode".
9168  !! How the DEBUG mode is controlled is described in the
9169  !! `commondata::system_init()` reference.
9170  subroutine log_dbg(message_string, procname, modname)
9171 
9172  ! @note PROCNAME is NOT used here as it conflicts with the dummy parameter.
9173  ! Calling parameters:
9174  ! @param[in] message_string String text for the log message
9175  character (len=*), intent(in) :: message_string
9176  ! @param[in] procname Optional procedre name for debug messages
9177  character (len=*), optional, intent(in) :: procname
9178  ! @param[in] modname Optional module name for debug messages
9179  character (len=*), optional, intent(in) :: modname
9180 
9181  ! Local variables
9182  character (len=:), allocatable :: prefix_msg
9183 
9184  if (is_debug) then
9185 
9186  !> We first generate the message prefix = MODNAME PROCNAME
9187  !! if called with these parameters, so the location of the code
9188  !! in which the message has been issued is precisely known.
9189  if (present(procname)) then
9190  if (present(modname)) then
9191  prefix_msg="DEBUG: " // modname // "::" // procname // ": "
9192  else
9193  prefix_msg="DEBUG: ::" // procname // ": "
9194  end if
9195  else
9196  if (present(modname)) then
9197  prefix_msg="DEBUG: " // modname // ":: "
9198  else
9199  prefix_msg="DEBUG: "
9200  end if
9201  end if
9202 
9203  !> And then we issue the message to the log as usual.
9204  call log_msg( prefix_msg // message_string )
9205 
9206  end if
9207 
9208  end subroutine log_dbg
9209 
9210  !-----------------------------------------------------------------------------
9211  !> @brief `LOG_IEEE`: Check and log IEEE signalling flags. Logging normally
9212  !! occurs only if any nonzero output from ::ieee_error_reporting()
9213  !! is found.
9214  subroutine log_ieee( ttag, always_log, reset_flags )
9215  !> Optional text tag that is passed to logger to identify the specific
9216  !! algorithm place where the IEEE condition is checked/flagged.
9217  character(len=*), optional, intent(in) :: ttag
9218  !> Optional flag to request logger output even if IEEE signalling is NOT
9219  !! reported. Normally defaults to FALSE, but to TRUE if ::is_debug is TRUE.
9220  logical, optional, intent(in) :: always_log
9221  !> Optional flag to reset all IEEE conditions after checking and logging.
9222  !! The default value is TRUE, i.e. reset all flags to zero
9223  logical, optional, intent(in) :: reset_flags
9224 
9225  ! Local copies of optionals
9226  character(len=:), allocatable :: ttag_loc
9227  logical :: always_log_here, reset_here
9228 
9229  integer :: ieee_report
9230 
9231  if ( present(ttag) ) then
9232  ttag_loc = ttag
9233  else
9234  ttag_loc = "[]"
9235  end if
9236 
9237  if ( present(always_log) ) then
9238  always_log_here = always_log
9239  else
9240  if ( is_debug ) then
9241  always_log_here = .true.
9242  else
9243  always_log_here = .false.
9244  end if
9245  end if
9246 
9247  if ( present(reset_flags) ) then
9248  reset_here = reset_flags
9249  else
9250  reset_here = .true.
9251  end if
9252 
9253  ieee_report = ieee_error_reporting( reset_here, ttag_loc )
9254 
9255  if ( always_log_here ) then
9256  call log_msg( ltag_info // "IEEE Signalling: " // tostr(ieee_report) )
9257  else
9258  if ( ieee_report > 0 ) &
9259  call log_msg( ltag_info // "IEEE Signalling: " // tostr(ieee_report) )
9260  end if
9261 
9262  end subroutine log_ieee
9263 
9264  !-----------------------------------------------------------------------------
9265  !> Parse and cut revision **number** in form of string from the whole SVN
9266  !! revision string. SVN revision number can therefore be included into the
9267  !! model outputs and output file names. This is convenient because the model
9268  !! version is identified by a single SVN revision number.
9269  !! @returns revision number from Subversion.
9270  !! @warning `STRINGS` module uses unsafe coding prone to bugs, e.g.
9271  !! does not clearly state dummy parameters intent and doesn't
9272  !! work correctly with `parameter`s.
9273  function parse_svn_version () result (sversion)
9274  character(len=:), allocatable :: sversion ! @returns revision number.
9275  ! @note Have to copy `SVN_VERSION_STRING` to this local variable as
9276  ! `PARSE` is broken when used with fixed parameters (no `intent`).
9277  character(len=len(SVN_VERSION_STRING)) :: &
9278  svn_string_copy = svn_version_string
9279  ! Delimiters for substrings.
9280  character(len=3) :: delims = " :$"
9281  ! String parts after parsing and cutting. Are 3 parts enough?
9282  character(len=len(SVN_VERSION_STRING)), dimension(3) :: sargs
9283  integer :: n_args
9284 
9285  !> ### Implementation notes ###
9286  !> Subversion has a useful feature: various keywords can be inserted and
9287  !! automatically updated in the source code under revision control, e.g.
9288  !! revision number, date, user etc. The character string parameter constant
9289  !! `commondata::svn_version_string` keeps the Subversion revision tag.
9290  !! This subroutine parses the tag striping all other characters out.
9291  call parse(svn_string_copy, delims, sargs, n_args)
9292  sversion = trim(sargs(n_args)) ! Version number is the last part.
9293 
9294  end function parse_svn_version
9295 
9296  !-----------------------------------------------------------------------------
9297  !> Get and parse the model abstract. Model abstract is a short descriptive
9298  !! text that can span several lines and is kept in a separate file that is
9299  !! defined by the commondata::model_abstract_file.
9300  !!
9301  !! The separate Model Abstract file is useful because it can integrate
9302  !! dynamic information, such as the latest version control log(s) via
9303  !! Subversion or Mercurial hooks mechanism.
9304  function parse_abstract(file_name) result (abstract_array)
9305  !> @param[in] file_name optional name of the abstract file. If this
9306  !! parameter is absent, commondata::model_abstract_file is used.
9307  character(len=*), optional, intent(in) :: file_name
9308  !> @return An allocatable character string array that contains all the
9309  !! lines from the Model Abstract file.
9310  character(len=LONG_LABEL_LENGTH),allocatable,dimension(:) :: abstract_array
9311 
9312  ! Local copies of optionals
9313  character(len=:), allocatable :: file_name_loc
9314 
9315  ! Local variables for reading the abstract file
9316  integer :: abstract_unit, file_error_status
9317  logical :: file_is_success
9318 
9319  ! Number of lines in the abstract file, it is also equal to the size of
9320  ! the output abstract character string array.
9321  integer :: abstract_file_lines
9322 
9323  ! Counter.
9324  integer :: i
9325 
9326  if (present(file_name)) then
9327  file_name_loc = file_name
9328  else
9329  file_name_loc = model_abstract_file
9330  end if
9331 
9332  !> Try to open the abstract file and count its lines with the function
9333  !! CSV_FILE_LINES_COUNT() from HEDTOOLS.
9334  abstract_file_lines = csv_file_lines_count( &
9335  csv_file_name=file_name_loc, &
9336  numeric_only=.false., &
9337  csv_file_status=file_is_success )
9338 
9339  !> - If the function return status is 'error' or the number of lines is
9340  !! less than 1, the abstract file is invalid and the abstract array is
9341  !! automatically allocated to one and assigned the model description
9342  !! string from commondata::model_descr.
9343  if ( .not. file_is_success .or. abstract_file_lines < 1 ) then
9344  abstract_array = [ model_descr ]
9345  return
9346  end if
9347 
9348  !> - Otherwise,
9349  !! - allocate the output abstract array to the number of lines
9350  !! in the abstract file and initialise it to empty strings
9351  allocate( abstract_array(abstract_file_lines) )
9352  abstract_array = ""
9353 
9354  !> - get the free file unit for reading...
9355  abstract_unit = get_free_funit()
9356 
9357  !> - open the abstract file for reading
9358  open ( unit=abstract_unit, file=file_name_loc, status='old', &
9359  iostat=file_error_status)
9360 
9361  if ( file_error_status /= 0 ) then
9362  abstract_array = [ model_descr ]
9363  return
9364  end if
9365 
9366  !> - And read all the contents of the file into the output abstract array.
9367  do i=1, abstract_file_lines
9368  read ( unit=abstract_unit, fmt="(a)", iostat=file_error_status ) &
9369  abstract_array(i)
9370  if ( file_error_status /= 0 ) exit
9371  end do
9372 
9373  !> - Finally, close the file.
9374  !! .
9375  !! .
9376  close(abstract_unit)
9377 
9378  end function parse_abstract
9379 
9380  !-----------------------------------------------------------------------------
9381  !> Date (YYYYMMDD) tag for file names and logs.
9382  !! @warning Note that this procedure should be called only once during the
9383  !! system initialisation. Then a fixed value is given to the global
9384  !! variable commondata::mmdd: this global variable should be used
9385  !! for all tags. This procedure has *private* accessibility status
9386  !! and is not available outside of @ref commondata.
9387  function tag_mmdd() result (MMDD)
9388 
9389  character (len=*), parameter :: procname = "(tag_mmdd)"
9390  !> @retval MMDD Function returns an 8-character string for YYYYMMDD
9391  character(len=:), allocatable :: mmdd
9392 
9393  integer date_time(8)
9394  character(10) b(3)
9395 
9396  call date_and_time(b(1), b(2), b(3), date_time)
9397 
9398  mmdd = tostr(date_time(1),2016) // tostr(date_time(2),10) // &
9399  tostr(date_time(3),10)
9400 
9401  end function tag_mmdd
9402 
9403 end module commondata
Simple history stack function, add to the end of the stack. We need only to add components on top (en...
Definition: m_common.f90:5292
Calculate an average of an array excluding missing code values.
Definition: m_common.f90:5491
Convert cm to m.
Definition: m_common.f90:5306
Check if two real values are nearly equal using the commondata::is_near_zero(). Thus function can be ...
Definition: m_common.f90:5406
Sigmoidal relationship between environmental factor and the organism response, as affected by the gen...
Definition: m_common.f90:5269
Check if a value is the maximum value of an array.
Definition: m_common.f90:5499
Check if a value is the minimum value of an array.
Definition: m_common.f90:5507
Checks if a real number is near 0.0. Thus function can be used for comparing two real values like thi...
Definition: m_common.f90:5385
Logical function to check if a value is within a specific range, lower <= X <= upper.
Definition: m_common.f90:5362
Convert m to cm.
Definition: m_common.f90:5319
Convert mm to m.
Definition: m_common.f90:5329
Arbitrary rescales value(s) from one range (A:B) to another (A1:B1).
Definition: m_common.f90:5341
Force a value within the range set by the vmin and vmax dummy parameter values.
Definition: m_common.f90:5350
COMMONDATA – definitions of global constants and procedures.
Definition: m_common.f90:1497
real(srp), parameter, public stomach_content_init_cv
Set the coefficient of variation for the stomach capacity at init.
Definition: m_common.f90:3156
real(srp), parameter, public reprfac_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for age perception effects on reproduction.
Definition: m_common.f90:4579
logical, parameter, public agent_can_assess_predator_attack_rate
A logical flag of whether the agents can assess the individual inherent attack rates of the predators...
Definition: m_common.f90:2395
elemental logical function, private is_near_zero_hrp(test_number, epsilon)
Checks if a real number is near 0.0. Thus function can be used for comparing two real values like the...
Definition: m_common.f90:6233
logical, dimension(max_nalleles, n_chromosomes), parameter, public energy_genotype_phenotype
The initial value of the energy reserves at birth is genetically determined. This is the Genotype x P...
Definition: m_common.f90:3172
logical, public, protected is_debug
Sets the model in the debug mode if TRUE. The Debug mode generates huge additional outputs and logs....
Definition: m_common.f90:1981
real(srp), parameter, public depth_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for depth perception effects on fear state.
Definition: m_common.f90:3855
pure real(srp) function, dimension(:), allocatable, private stack2arrays_r(a, b)
Concatenate two arrays a and b. This procedure uses array slices which would be faster in most cases ...
Definition: m_common.f90:6157
integer, parameter, public preevol_tsteps
Number of time steps in the agent's life at the pre-evolution stage.
Definition: m_common.f90:2069
character(len= *), parameter, private modname
MODNAME always refers to the name of the current module for use by the LOGGER function LOG_DBG....
Definition: m_common.f90:1591
integer, public global_generation_number_current
The current global generation number. This is a global non fixed-parameter variable that is updated i...
Definition: m_common.f90:2063
real(srp), parameter, public conspcount_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for conspecifics number count perception effects on hunger.
Definition: m_common.f90:3548
real(srp), parameter, public cost_factor_foraging_smr
Set the cost of foraging in terms of SMR.
Definition: m_common.f90:3165
real(srp), parameter, public history_perception_window_pred
The size of the memory window that is used in the assessment of predation risk, as a portion of the c...
Definition: m_common.f90:5083
character(len= *), parameter, public zip_file_extenssion
This parameter defines the compressed file extension for the external compression utility defined by ...
Definition: m_common.f90:2033
real(srp), parameter, public approach_offset_default
Default offset for approach, offset is the difference between the approaching agent and the target ob...
Definition: m_common.f90:5022
character(len= *), parameter, public ltag_error
Definition: m_common.f90:1823
elemental logical function, private float_approx_hrp_operator(value1, value2)
This is a wrapper for the commondata::float_equal_hrp() for building the user defined operator ....
Definition: m_common.f90:6417
real(srp), parameter, public attention_switch_reproduce_stomach
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4812
integer, parameter, public pred_select_items_index_partial
Sets the limit for partial indexing and ranking of predators in the visual range of the agent.
Definition: m_common.f90:3368
character(len= *), parameter, public error_lock_preexists
Definition: m_common.f90:1858
logical, parameter, public init_agents_depth_is_fixed
This parameter determines if the agents are initialised at a fixed depth at the initialisation....
Definition: m_common.f90:2139
real(srp), parameter, public predator_attack_capture_probability_half
The probability of capture of a fish agent by a predator at the distance equal to 1/2 of the visual r...
Definition: m_common.f90:2369
logical, dimension(max_nalleles, n_chromosomes), parameter, public pred_meancount_reproduce_genotype_neuronal
The genotype structure for mean predator number perception effects on reproduction that goes via gamm...
Definition: m_common.f90:4390
real(srp), parameter, public body_length_max
Maximum body length.
Definition: m_common.f90:2121
real(srp), parameter, public attention_switch_hunger_light
Baseline attention switches control which perception components (i) can affect each of the motivatio...
Definition: m_common.f90:4748
real(srp), parameter, public probability_reproduction_base_factor
Default weighting factor for the baseline probability of successful reproduction ....
Definition: m_common.f90:4902
logical, dimension(max_nalleles, n_chromosomes), parameter, public conspcount_actv_avoid_genotype_neuronal
The genotype structure for conspecifics number perception effects on fear state that goes via gamma2g...
Definition: m_common.f90:3928
real(srp), parameter, public control_unselected_gerror_cv
Genotype to phenotype initialisation, Gaussian error parameter. Coefficient of variation for the cont...
Definition: m_common.f90:3274
real(srp), parameter, public food_item_size_default_cv
Coefficient of variation for Gaussian food items.
Definition: m_common.f90:2445
real(srp), parameter, public individual_mortality_risk_cv
The coefficient of variation for Gaussian stochastic individually-specific mortality risk of the agen...
Definition: m_common.f90:2345
real(srp), parameter, public migrate_predator_zero_hope
This parameter defines the hope function for calculating the general predation risk expectancy in the...
Definition: m_common.f90:5156
integer, parameter, public history_size_spatial
The size of the history for spatial moving objects, i.e. how many time steps positions to remember in...
Definition: m_common.f90:2264
real(srp), parameter, public reprod_modulation_devel_w2
Developmental modulation of reproductive motivation. This parameter sets the interpolation array weig...
Definition: m_common.f90:4648
real(srp), parameter, public attention_switch_hunger_energy
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4766
integer, parameter, public long_label_length
The length of long labels.
Definition: m_common.f90:1739
logical, dimension(max_nalleles, n_chromosomes), parameter, public light_reproduce_genotype_neuronal
The genotype structure for light perception effects on reproduction that goes via gamma2gene percepti...
Definition: m_common.f90:4193
character(len= *), parameter, public exec_interpolate
There are a few external programs which are called from the model code. The name of the interpolation...
Definition: m_common.f90:1793
real(srp), parameter, public smr_init
This is the initial value of SMR that goes through the gamma2gene.
Definition: m_common.f90:3306
real(srp), parameter, public adrenaline_init
Genotype to phenotype gamma2gene initialisation value for adrenaline
Definition: m_common.f90:2907
real(srp), parameter, public genome_recombination_ratio_mother
The ratio of the genome that inherited from the mother. The other part is inherited from the father....
Definition: m_common.f90:2673
character(len= *), parameter, public error_no_autoalloc
Error message for **"no automatic intrinsic array allocation"**. Fortran compilers support automatic ...
Definition: m_common.f90:1841
logical, dimension(max_nalleles, n_chromosomes), parameter, public pred_meancount_actv_avoid_genotype_neuronal
The genotype structure for mean predator number perception effects on fear state that goes via gamma2...
Definition: m_common.f90:3994
real(srp), parameter, public hi_valid_sanitised
Higher bound for do_sanitise() procedure. This is the highest value that considered valid.
Definition: m_common.f90:1664
logical, dimension(max_nalleles, n_chromosomes), parameter, public sex_female_modulation_reproduce_genotype
The genotype structure for sex modulation coefficient affecting reproduction motivation state in fema...
Definition: m_common.f90:4685
real(srp), dimension(*), parameter, public approach_food_gain_compet_factor_abscissa
The grid abscissa defining the nonparametric relationship that determines the expected food gain for ...
Definition: m_common.f90:5055
logical, dimension(max_nalleles, n_chromosomes), parameter, public foodcount_hunger_genotype_neuronal
The genotype structure for food items count perception effects on hunger that goes via gamma2gene per...
Definition: m_common.f90:3458
character(len= *), parameter, private model_abstract_file
The name of the file that contains the Model abstract, a short description that can span several line...
Definition: m_common.f90:1953
logical, dimension(max_nalleles, n_chromosomes), parameter, public thyroid_genotype_phenotype
Genotype x Phenotype matrix for thyroid.
Definition: m_common.f90:2847
character(len= *), parameter, public model_name
Model name for tags, file names etc. Must be very short. See Model descriptors.
Definition: m_common.f90:1938
logical, dimension(max_nalleles, n_chromosomes), parameter, public estrogen_genotype_phenotype
Genotype x Phenotype matrix for ESTROGEN.
Definition: m_common.f90:2987
real(srp), parameter, public tolerance_low_def_srp
Default value of low tolerance (high precision). This is the standard commondata::srp precision....
Definition: m_common.f90:1671
real(srp), parameter, public energy_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for energy reserves perception effects on hunger.
Definition: m_common.f90:3723
character(len= *), parameter, public ps
Standard file extension for debug and other PostScript plots.
Definition: m_common.f90:1716
integer, parameter, public n_chromosomes
The number of chromosomes for the agents.
Definition: m_common.f90:2622
real(srp) function zeroin(ax, bx, f, tol)
This function calculates a zero of a function f(x) in the interval (ax,bx).
Definition: m_common.f90:6745
real(srp), parameter, public migrate_predator_maximum_hope
This parameter defines the hope function for calculating the general predation risk expectancy in the...
Definition: m_common.f90:5148
real(hrp), parameter, public tolerance_low_def_hrp
Default value of low tolerance (high precision). This is the high commondata::hrp precision....
Definition: m_common.f90:1676
real(srp), parameter, public attention_switch_reproduce_light
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4798
subroutine do_sanitise(array, lvalid, hvalid, substval, only_wrong, tnote)
Sanitize a real commondata::srp array, so that any value that is smaller than the minimum sensible va...
Definition: m_common.f90:6438
real(srp), parameter, public sex_steroids_reproduction_threshold
This parameter defines the threshold of the current gonadal steroids level that should exceed the bas...
Definition: m_common.f90:4934
real(srp), dimension(*), parameter, public reproduct_body_mass_offspr_ordinate
The array defining the ordinate (Y) of the nonparametric function curve that defines the relationship...
Definition: m_common.f90:2225
real(srp), parameter, public daylight_cv
Coefficient of variation for stochastic DAYLIGHT,.
Definition: m_common.f90:2517
real(srp), parameter, public testosterone_gerror_cv
Genotype to phenotype gamma2gene Gaussian error parameter. This is really the coefficient of variatio...
Definition: m_common.f90:2982
logical, parameter, public no
Definition: m_common.f90:1633
subroutine debug_histogram_save(x_data, delete_csv, csv_out_file, enable_non_debug)
Produce a debug plot of histogram using an external program hthist from HEDTOOLS tools.
Definition: m_common.f90:7967
integer, parameter, public ga_fitness_dead
Fitness value ascribed to dead agent in pre-evol. See the_individual::individual_agent::fitness_calc(...
Definition: m_common.f90:5194
character(len= *), parameter, public ltag_stats
Definition: m_common.f90:1826
real(srp), parameter, public thyroid_gerror_cv
Genotype to phenotype gamma2gene Gaussian error parameter. This is really the coefficient of variatio...
Definition: m_common.f90:2877
real(srp), parameter, public age_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for age perception effects on fear state.
Definition: m_common.f90:4150
pure logical function, private is_maxval_r(value, array, tolerance)
Function to check if the value is the maximum value of an array (returns TRUE), or not (return FALSE)...
Definition: m_common.f90:7460
real(srp), parameter, public attention_switch_reproduce_depth
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4800
logical, dimension(max_nalleles, n_chromosomes), parameter, public bodymass_reproduce_genotype_neuronal
The genotype structure for body mass perception effects on reproduction that goes via gamma2gene perc...
Definition: m_common.f90:4454
integer, parameter, public q_prec_128
Definition: m_common.f90:1536
elemental real(srp) function, private m2cm_r(value_m)
Convert m to cm.
Definition: m_common.f90:5593
logical, parameter, public init_agents_depth_is_gauss
This parameter determines if the agents are initialised at a fixed depth at the initialisation....
Definition: m_common.f90:2154
integer, parameter, public srp
Definition of the standard real type precision (SRP).
Definition: m_common.f90:1551
logical, dimension(max_nalleles, n_chromosomes), parameter, public control_unselected_genotype_phenotype
The initial value of the control unselected trait. This trait is is genetically determined but is not...
Definition: m_common.f90:3244
real(srp), parameter, public escape_dart_distance_default_stoch_cv
For stochastic escape, this parameter determines the coefficient of variation of the escape walk....
Definition: m_common.f90:5102
real(srp), parameter, public approach_conspecfic_dilute_adjust_pair_behind
Multiplication factor for subjective assessment of the direct risk of predation when the actor agent ...
Definition: m_common.f90:5035
real(srp), dimension(*), parameter, public attention_modulation_curve_ordinate
The array defining the ordinate (Y) of the nonparametric function that defines the attention modulati...
Definition: m_common.f90:4839
real(srp), parameter, public smr_min
Minimum SMR value, anything lower is not allowed.
Definition: m_common.f90:3313
elemental real(srp) function, private cm2m_i(value_cm)
Convert cm to m.
Definition: m_common.f90:5579
logical, dimension(max_nalleles, n_chromosomes), parameter, public reprfac_actv_avoid_genotype_neuronal
The genotype structure for reproductive factor perception effects on fear state that goes via gamma2g...
Definition: m_common.f90:4157
real(srp), parameter, public reprfac_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for reproductive factor perception effects on hunger.
Definition: m_common.f90:3787
logical, dimension(max_nalleles, n_chromosomes), parameter, public energy_reproduce_genotype_neuronal
The genotype structure for energy reserves perception effects on reproduction that goes via gamma2gen...
Definition: m_common.f90:4487
real(srp), parameter, public arousal_gos_dissipation_factor
Spontaneous arousal dissipation level when a simple fixed dissipation factor pattern is used....
Definition: m_common.f90:4865
real(srp), parameter, public pi
The PI number.
Definition: m_common.f90:1710
elemental real(srp) function cv2variance(cv, mean)
Calculate the variance from the coefficient of variation.
Definition: m_common.f90:6956
real(srp), parameter swimming_cost_exponent_laminar
Default swimming cost body mass exponent parameter for laminar flow. See doi:10.1242/jeb....
Definition: m_common.f90:3318
real(srp), parameter, public stom_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for stomach perception effects on hunger.
Definition: m_common.f90:3659
character(len= *), parameter, public model_descr
Model description - a fixed descriptive text, used in text outputs etc. See Model descriptors.
Definition: m_common.f90:1942
integer, parameter, public unknown
Numerical code for invalid or missing integer counts.
Definition: m_common.f90:1704
real(srp), parameter, public init_agents_depth_cv
This parameter sets the Coefficient of Variation for the Gaussian depth initialisation of the agents ...
Definition: m_common.f90:2169
real(srp), parameter, public linear_growth_exponent
Growth exponent linking linear growth and body mass growth. Based on Fulton's condition factor "cube ...
Definition: m_common.f90:3114
integer, parameter, public generations
Maximum number of generations in GA.
Definition: m_common.f90:2058
subroutine call_external(command, suppress_output, suppress_error, is_background_task, cmd_is_success, exit_code)
Call an external program using a command line. Wrapper to two alternative system shell calling intrin...
Definition: m_common.f90:7712
real(srp), parameter, public daylight
Maximum above-surface light intensity at midday, DAYLIGHT=500.0.
Definition: m_common.f90:2509
real(hrp), parameter, public tiny_hrp
The smallest positive number in the commondata::hrp high precision real model. See Float point comput...
Definition: m_common.f90:1656
character(len= *), parameter, public ltag_major
Tag prefixes for the logger system. The log may use tags for some common information pieces,...
Definition: m_common.f90:1819
logical, dimension(max_nalleles, n_chromosomes), parameter, public sex_genotype_phenotype
Sex definition can be implemented differently from all other traits. Here is an example of the phenot...
Definition: m_common.f90:2753
character(len= *), parameter, public ltag_crit
Definition: m_common.f90:1824
real(srp), parameter, public walk_random_food_gain_hope_agentl
The maximum walk distance, in units of the agent body length, when the expected food gain is calculat...
Definition: m_common.f90:4964
logical, dimension(max_nalleles, n_chromosomes), parameter, public adrenaline_genotype_phenotype
Genotype x Phenotype matrix for adrenaline
Definition: m_common.f90:2882
real(srp), parameter, public pred_direct_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for direct predation perception effects on hunger.
Definition: m_common.f90:3580
real(srp), parameter, public predator_attack_rate_cv
Coefficient of variation for a single predator attack among the whole population of stochastic predat...
Definition: m_common.f90:2364
real(srp), parameter, public up_down_walk_step_stdlength_factor
The default size of the up and down walks performed by the GO_DOWN_DEPTH and GO_UP_DEPTH,...
Definition: m_common.f90:5109
logical, dimension(max_nalleles, n_chromosomes), parameter, public cortisol_genotype_phenotype
Genotype x Phenotype matrix for cortisol.
Definition: m_common.f90:2917
real(srp), dimension(3), parameter, public universe_min_coord_notuse
Overall size of the global 3D universe of the model.
Definition: m_common.f90:2254
real(srp), parameter, public attention_switch_avoid_act_stomach
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4787
real(srp), parameter, public attention_switch_avoid_act_food_mem
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4779
real(srp), parameter, public food_item_density
The (physical) density of a single food item. TODO: need to parametrise!
Definition: m_common.f90:2452
subroutine debug_scatterplot_save(x_data, y_data, delete_csv, csv_out_file, enable_non_debug)
Produce a debug plot of 2-d scatterplot using an external program htscatter from HEDTOOLS tools.
Definition: m_common.f90:8097
integer, parameter, public sex_steroids_check_history
The number of the latest historical values that are checked for change when setting an increment of t...
Definition: m_common.f90:3024
real(srp), parameter, public swimming_cost_factor_buoyancy_up
This parameter defines the cost of the buoyancy-based locomotion as a fraction of normal laminar flow...
Definition: m_common.f90:3334
integer, parameter, public ga_fitness_select
Fitness threshold for the inclusion of the agent into the reproducing elite group.
Definition: m_common.f90:5198
real(srp), parameter, public eyesat
Saturation parameter of eye (Ke) (uE m-2 s-1), EYESAT=500.0.
Definition: m_common.f90:2542
real(srp), parameter, public attention_switch_reproduce_energy
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4816
logical function check_external(exec)
Check if an external procedure is executable and can be run.
Definition: m_common.f90:7897
real(srp), parameter, public body_length_init
The initial value of body length, the average (gon-genetic).
Definition: m_common.f90:3232
integer, parameter, public filename_length
Set the standard length of the file name, are 255 characters enough?
Definition: m_common.f90:1722
real(srp), parameter, public pred_meancount_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for mean predator number perception effects on hunger.
Definition: m_common.f90:3612
logical, dimension(max_nalleles, n_chromosomes), parameter, public food_mem_reproduce_genotype_neuronal
The genotype structure for food items count perception effects on reproduction that goes via gamma2ge...
Definition: m_common.f90:4291
character(len= *), parameter stop_file
The name of the stop file. The stop file is checked before each new generation of the Genetic Algorit...
Definition: m_common.f90:1777
real(srp), parameter, public foodcount_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for food items count perception effects on hunger.
Definition: m_common.f90:3484
real(srp), parameter, public smr_gerror_cv
Genotype to phenotype initialisation, Gaussian error parameter. Coefficient of variation for the SMR_...
Definition: m_common.f90:3310
elemental integer function, private within_i(value_in, vmin, vmax)
Force a value within the range set by the vmin and vmax dummy parameter values. If the value is withi...
Definition: m_common.f90:5799
real(srp), parameter, public reproduction_cost_unsuccess
The energetic cost of unsuccessful reproduction in terms of the agent's body mass lost....
Definition: m_common.f90:2204
integer, parameter, public history_size_perception
Sets the size of the perception memory stack.
Definition: m_common.f90:3377
logical, dimension(max_nalleles, n_chromosomes), parameter, public smr_genotype_phenotype
The initial value of the standard metabolic rate (SMR) at birth is genetically determined....
Definition: m_common.f90:3281
character(len=:) function, allocatable, private timer_cpu_show(this)
A ready to use in output function that returns a formatted string for a timer combining its title and...
Definition: m_common.f90:7648
pure logical function, private is_minval_r(value, array, tolerance)
Function to check if the value is the minimum value of an array (returns TRUE), or not (return FALSE)...
Definition: m_common.f90:7525
real(srp), parameter, public attention_switch_avoid_act_depth
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4775
logical, dimension(max_nalleles, n_chromosomes), parameter, public depth_reproduce_genotype_neuronal
The genotype structure for depth perception effects on reproduction that goes via gamma2gene percepti...
Definition: m_common.f90:4225
real(srp), parameter, public reproduction_cost_body_mass_fix
The energetic cost of reproduction in terms of the agent's body mass loss.
Definition: m_common.f90:2175
integer, parameter, public label_length
The length of standard character string labels. We use labels for various objects,...
Definition: m_common.f90:1736
logical, dimension(max_nalleles, n_chromosomes), parameter, public conspcount_hunger_genotype_neuronal
The genotype structure for conspecifics number perception effects on hunger that goes via gamma2gene ...
Definition: m_common.f90:3522
real(srp), parameter, public food_item_migrate_depth_cv
Coefficient of variation parameter for the local random walk movement of food items in the vertical (...
Definition: m_common.f90:2498
logical, dimension(max_nalleles, n_chromosomes), parameter, public genome_crossover_fixed_mother
Boolean 2D matrix that determines the pattern of fixed chromosome crossover. For each chromosome,...
Definition: m_common.f90:2684
integer, public platform_running
Global variable that shows what is the current platform. Should use the above platform constants,...
Definition: m_common.f90:1788
logical, dimension(max_nalleles, n_chromosomes), parameter, public light_actv_avoid_genotype_neuronal
The genotype structure for light perception effects on fear state that goes via gamma2gene perception...
Definition: m_common.f90:3797
real(srp), parameter, public pred_meancount_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for mean predator number perception effects on fear state.
Definition: m_common.f90:4020
real(srp), parameter, public reproduction_cost_body_mass_factor_female
The component of the energetic cost of reproduction in females that is proportional to the agent's bo...
Definition: m_common.f90:2198
logical, dimension(max_nalleles, n_chromosomes), parameter, public reprfac_reproduce_genotype_neuronal
The genotype structure for age perception effects on reproduction that goes via gamma2gene perception...
Definition: m_common.f90:4553
real(srp), dimension(*), parameter, public behav_walk_step_stdlen_static
This parameter array defines the repertoire of predetermined static walk step sizes,...
Definition: m_common.f90:5163
real(srp), parameter, public migrate_food_gain_ratio_zero_hope
This parameter defines the hope function for calculating the food gain expectancy in the migration be...
Definition: m_common.f90:5140
integer, parameter, public food_select_items_index_partial
Sets the limit for partial indexing and ranking of food items in the visual range of the agents.
Definition: m_common.f90:3360
real(srp), parameter, public attention_switch_hunger_bodymass
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4764
real(srp), parameter, public adrenaline_gerror_cv
Genotype to phenotype gamma2gene Gaussian error parameter. This is really the coefficient of variatio...
Definition: m_common.f90:2912
integer, parameter, public food_abundance_habitat_danger
The food abundance in the dangerous habitat.
Definition: m_common.f90:2318
integer, parameter, public ga_reproduce_n
Upper limit on the number of reproducing individuals in the fixed-fitness pre-evolution phase.
Definition: m_common.f90:5189
real(srp), parameter, public attention_switch_avoid_act_energy
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4791
real(srp), parameter, public eggmortality_def
Default level of egg mortality in the habitat.
Definition: m_common.f90:2335
integer, parameter, public s_prec_32
Standard precision for real data type. We first define 32, 64 and 128 bit real kinds.
Definition: m_common.f90:1534
real(srp), parameter, public growhorm_init
Genotype to phenotype gamma2gene initialisation value for growth hormone
Definition: m_common.f90:2826
real(srp), parameter, public food_mem_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for food items count perception effects on hunger.
Definition: m_common.f90:3516
logical, dimension(max_nalleles, n_chromosomes), parameter, public energy_actv_avoid_genotype_neuronal
The genotype structure for energy reserves perception effects on fear state that goes via gamma2gene ...
Definition: m_common.f90:4091
elemental logical function, private is_near_zero_srp(test_number, epsilon)
Checks if a real number is near 0.0. Thus function can be used for comparing two real values like the...
Definition: m_common.f90:6203
real(srp), parameter, public tiny_srp
The smallest positive number in the commondata::srp standard real model.
Definition: m_common.f90:1651
real(srp), dimension(3), parameter, public universe_whole_size_notuse
Definition: m_common.f90:2256
character(len=:) function, allocatable, private tag_mmdd()
Date (YYYYMMDD) tag for file names and logs.
Definition: m_common.f90:9388
real(srp), parameter, public predator_attack_capture_prob_frz_50
A parameter factor defining the probability of capture of an immobile (freezing) agent by a predator:...
Definition: m_common.f90:2383
real(srp), parameter, public other_risks_habitat_safe
Habitat-specific mortality risk (not linked with predation) in the safe habitat.
Definition: m_common.f90:2328
integer, parameter, public chromosome_ploidy
The ploidy of the chromosome set. Can theoretically be haploid (=1), diploid (=2) or,...
Definition: m_common.f90:2667
logical, dimension(max_nalleles, n_chromosomes), parameter, public stom_reproduce_genotype_neuronal
The genotype structure for stomach perception effects on reproduction that goes via gamma2gene percep...
Definition: m_common.f90:4422
real(srp), parameter, public predation_risk_weight_immediate
The weight of the immediately seen predators over those in the perceptual memory stack....
Definition: m_common.f90:3621
logical, dimension(max_nalleles, n_chromosomes), parameter, public depth_actv_avoid_genotype_neuronal
The genotype structure for depth perception effects on active avoidance that goes via gamma2gene perc...
Definition: m_common.f90:3829
real(srp), dimension(*), parameter, public approach_food_gain_compet_factor_ordinate
The grid ordinate defining the nonparametric relationship that determines the expected food gain for ...
Definition: m_common.f90:5070
real(srp), parameter, public cortisol_init
Genotype to phenotype gamma2gene initialisation value for cortisol
Definition: m_common.f90:2942
integer, parameter, public platform_unix
Definition: m_common.f90:1783
elemental logical function, private float_equal_hrp_operator(value1, value2)
This is a wrapper for the commondata::float_equal_hrp() for building the user defined operator ....
Definition: m_common.f90:6366
real(srp), parameter swimming_cost_exponent_turbulent
Default swimming cost body mass exponent parameter for turbulent flow. See doi:10....
Definition: m_common.f90:3323
elemental real(srp) function, private m2cm_i(value_m)
Convert m to cm.
Definition: m_common.f90:5621
logical, public, protected is_zip_outputs
This parameter enables or disables post-processing compression of the data: if TRUE,...
Definition: m_common.f90:2014
real(srp), parameter, public energy_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for energy reserves perception effects on fear state.
Definition: m_common.f90:4117
real(srp), parameter, public sex_female_modulation_reproduce_gerror_cv
Gaussian error parameter (cv) for the sex modulation coefficient affecting reproduction motivation st...
Definition: m_common.f90:4711
real(srp), parameter, public food_item_capture_probability_min
The minimum probability of capture a food item, when the item is at a distance equal to the visual ra...
Definition: m_common.f90:2467
integer, parameter, public additive_comps
Number of additive allele components.
Definition: m_common.f90:2590
elemental real(srp) function, private gamma2gene_reverse(neuronal_response, gs, gh, nc)
Reverse-calculate perception value from the given neural response value.
Definition: m_common.f90:7258
real(srp), parameter, public conspcount_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for conspecifics number count perception effects on fear sta...
Definition: m_common.f90:3954
real(srp), parameter, public light_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for light perception effects on reproduction.
Definition: m_common.f90:4219
integer, parameter, public predators_num_habitat_safe
The number of predators in the safe habitat.
Definition: m_common.f90:2309
real(srp), dimension(3), parameter, public habitat_danger_min_coord
Definition: m_common.f90:2301
real(srp), parameter, public walk_random_distance_default_factor
The weighting factor used in calculation of the default random walk distance, in terms of the agent's...
Definition: m_common.f90:4938
real(srp), parameter, public migrate_food_gain_maximum_hope
This parameter defines the hope function for calculating the food gain expectancy in the migration be...
Definition: m_common.f90:5133
real(srp), parameter, public stom_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for stomach perception effects on fear state.
Definition: m_common.f90:4052
real(srp), parameter, public max_stomach_capacity_def
Set the maximum stomach capacity default value – fraction of the body mass available for food....
Definition: m_common.f90:3142
real(srp), parameter, public missing
Numerical code for missing and invalid real type values.
Definition: m_common.f90:1699
logical, parameter, public daylight_stochastic
Flag for stochastic daylight pattern (if TRUE) or deterministic sinusoidal (when FALSE)....
Definition: m_common.f90:2513
real(srp), parameter, public attention_switch_reproduce_age
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4818
integer, parameter, public allelerange_min
The minimum possible value of alleles (allele range minimum) See implementation notes on the_genome::...
Definition: m_common.f90:2576
real(srp), parameter, public attention_switch_reproduce_conspec
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4806
real(srp), parameter, public predator_attack_capture_probability_min
Minimum probability of capture, e.g. at a distance exceeding the visual range. The latter assumes tha...
Definition: m_common.f90:2376
elemental real(srp) function, private within_r(value_in, vmin, vmax)
Force a value within the range set by the vmin and vmax dummy parameter values. If the value is withi...
Definition: m_common.f90:5767
real(srp), parameter, public other_risks_habitat_danger
Habitat-specific mortality risk (not linked with predation) in the dangerous habitat.
Definition: m_common.f90:2332
real(srp), parameter, public walk_random_distance_stochastic_cv
The coefficient of variation of the distance for stochastic Gaussian random walk (distance is in term...
Definition: m_common.f90:4944
integer, parameter, public platform_windows
Runtime platform ID constants. Use these constants for determining the current runtime platform,...
Definition: m_common.f90:1782
real(srp), parameter, public ga_reproduce_min_prop
Minimum proportion of reproducing agents, but note that the number of number reproducers cannot be sm...
Definition: m_common.f90:5204
logical, dimension(max_nalleles, n_chromosomes), parameter, public testosterone_genotype_phenotype
Genotype x Phenotype matrix for testosterone.
Definition: m_common.f90:2952
elemental real(srp) function, private mm2m_i(value_mm)
Convert mm to m.
Definition: m_common.f90:5649
real(srp), parameter, public percept_error_cv_def
Default perception error in the commondata::gamma2gene() neuronal response functions....
Definition: m_common.f90:2104
logical, dimension(max_nalleles, n_chromosomes), parameter, public bodymass_hunger_genotype_neuronal
The genotype structure for body mass perception effects on hunger that goes via gamma2gene perception...
Definition: m_common.f90:3665
integer, dimension(n_chromosomes), parameter, public len_chromosomes
The number of alleles in each of the chromosomes. NOTE: This must be an array (vector) of the size co...
Definition: m_common.f90:2629
real(srp), parameter, public attention_switch_hunger_age
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4768
elemental logical function, private is_within_r(x, lower, upper)
Logical function to check if a value is within a specific range, lower <= X <= upper....
Definition: m_common.f90:5832
logical, dimension(max_nalleles, n_chromosomes), parameter, public growhorm_genotype_phenotype
Genotype x Phenotype matrix for growth hormone.
Definition: m_common.f90:2800
real(srp), parameter, public estrogen_init
Genotype to phenotype gamma2gene initialisation value for estrogen
Definition: m_common.f90:3012
integer, parameter, public hrp
Definition of the high real precision (HRP). This real type kind is used in pieces where a higher lev...
Definition: m_common.f90:1556
logical, dimension(max_nalleles, n_chromosomes), parameter, public foodcount_actv_avoid_genotype_neuronal
The genotype structure for food items count perception effects on fear state that goes via gamma2gene...
Definition: m_common.f90:3862
real(srp), parameter, public attention_switch_avoid_act_pred_dir
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4783
real(srp), parameter, public approach_conspecfic_dilute_general_risk
Multiplication factor for the general risk of predation used when the agent evaluates the approach to...
Definition: m_common.f90:5027
real(srp), parameter, public reprod_modulation_devel_agefull
Developmental modulation of reproductive motivation. This parameter defines the age (time steps) at w...
Definition: m_common.f90:4606
real(srp), parameter, public attention_switch_avoid_act_conspec
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4781
integer, parameter, public popsize
Maximum population size.
Definition: m_common.f90:2055
real(srp), dimension(*), parameter, public motivation_compet_threshold_curve_ordinate
The array defining the ordinate (Y) of the nonparametric function curve that defines the threshold fo...
Definition: m_common.f90:4857
subroutine log_dbg(message_string, procname, modname)
LOG_DBG: debug message to the log. The message goes to the logger only when running in the DEBUG mode...
Definition: m_common.f90:9171
real(srp), parameter, public attention_switch_reproduce_pred_dir
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4808
real(hrp), parameter, public tolerance_high_def_hrp
Default value of high tolerance (low precision). This is the high commondata::hrp precision real....
Definition: m_common.f90:1690
integer, parameter, public long
In some (perhaps quite rare) cases of exponentiation we may also need huge integers,...
Definition: m_common.f90:1569
real(srp), parameter, public predator_body_size
The body size of the predator. In this version all predators have the same body size set by this para...
Definition: m_common.f90:2357
real(srp), parameter, public ga_mutationrate_batch_max
Maximum batch mutation rate in the adaptive Fixed Fitness Genetic Algorithm.
Definition: m_common.f90:2607
real(srp), parameter, public food_mem_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for food items count perception effects on reproduction.
Definition: m_common.f90:4317
elemental real(srp) function, private mm2m_r(value_mm)
Convert mm to m.
Definition: m_common.f90:5635
real(srp), parameter, public bodymass_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for body mass perception effects on fear state.
Definition: m_common.f90:4084
integer, parameter, public predator_risk_group_select_index_partial
Sets the limit for partial indexing and ranking of prey agents in the visual range of the predator....
Definition: m_common.f90:2402
real(srp), dimension(3), parameter, public habitat_safe_max_coord
Definition: m_common.f90:2297
pure real(srp) function, private average_r(array_in, missing_code, undef_ret_null)
Calculate an average value of a real array, excluding MISSING values.
Definition: m_common.f90:5954
real(srp), parameter, public dist_expect_food_uncertain_fact
The weighting factor for the distance to the expected food item if the actual distance is uncertain (...
Definition: m_common.f90:5077
integer, parameter, public food_abundance_habitat_safe
The food abundance in the safe habitat.
Definition: m_common.f90:2315
real(srp), parameter, public pred_direct_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for direct predation perception effects on fear state.
Definition: m_common.f90:3987
subroutine log_check_external(exec, debug_only, is_valid)
Check if an external procedure can be called and log the result.
Definition: m_common.f90:7913
real(srp), dimension(*), parameter, public attention_modulation_curve_abscissa
The array defining the abscissa (X) of the nonparametric function that defines the attention modulati...
Definition: m_common.f90:4831
real(srp), parameter, public depth_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for depth perception effects on reproduction.
Definition: m_common.f90:4251
real(srp), parameter, public body_mass_min
Minimum possible body mass, hard limit.
Definition: m_common.f90:2126
pure subroutine, private add_to_history_char(history_array, add_this)
Simple history stack function, add to the end of the stack. We need only to add components on top of ...
Definition: m_common.f90:7349
subroutine, private timer_cpu_start(this, timer_title)
Start the timer object, stopwatch is now ON.
Definition: m_common.f90:7590
real(srp), parameter, public init_agents_depth
The fixed depth at which the agents are initialised at the start of the simulation....
Definition: m_common.f90:2163
integer, parameter, public allelerange_max
The maximum possible value of alleles (allele range maximum) See implementation notes on the_genome::...
Definition: m_common.f90:2582
character(len= *), parameter lock_file
The name of the lock file. The lock file is created at the start of the simulation and is deleted at ...
Definition: m_common.f90:1754
elemental logical function, private float_approx_srp_operator(value1, value2)
This is a wrapper for the commondata::float_equal_srp() for building the user defined operator ....
Definition: m_common.f90:6391
real(srp), parameter, public attention_switch_reproduce_predator
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4810
real(srp), parameter, public stomach_content_emptify_factor
Stomach content emptify factor at each step.
Definition: m_common.f90:3148
real(srp), parameter, public walk_random_vertical_shift_cv_ratio
The ratio of the vertical to the main horizontal coefficients of variation for the vertical depth dis...
Definition: m_common.f90:4990
elemental logical function, private float_equal_srp(value1, value2, epsilon)
Check if two real values are nearly equal using the commondata::is_near_zero(). Thus function can be ...
Definition: m_common.f90:6269
real(srp) function, private random_add_subtract(x, y)
Random operator, adds or subtracts two values with equal probability, used in the random walk functio...
Definition: m_common.f90:8385
character(len=long_label_length) function, dimension(:), allocatable parse_abstract(file_name)
Get and parse the model abstract. Model abstract is a short descriptive text that can span several li...
Definition: m_common.f90:9305
logical, dimension(max_nalleles, n_chromosomes), parameter, public body_length_genotype_phenotype
The initial value of the body length at birth is genetically determined. This is the Genotype x Pheno...
Definition: m_common.f90:3207
real(srp), parameter, public living_cost
Living cost in terms of food consumed. metabolic costs, p roportional to body size.
Definition: m_common.f90:3105
integer, parameter, public history_size_agent_prop
History stack size for the agent's basic properties, such as body length and body mass....
Definition: m_common.f90:3101
real(srp), parameter, public mutationrate_point
Mutation rate for point allele mutations.
Definition: m_common.f90:2595
real(srp), parameter, public thyroid_init
Genotype to phenotype gamma2gene initialisation value for thyroid
Definition: m_common.f90:2872
logical, parameter, public true
Safety parameter avoid errors in logical values, so we can now refer to standard Fortran ....
Definition: m_common.f90:1632
real(srp), parameter, public attention_switch_avoid_act_light
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4773
real(srp), parameter, public sex_ratio
Sex ratio for initialising genomes.
Definition: m_common.f90:2711
real(srp), parameter, public attention_switch_avoid_act_reprfac
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4795
real(srp), parameter, public energy_init
This is the initial value of the energy reserves, non-genetic mean.
Definition: m_common.f90:3197
subroutine system_halt(is_error, message, ignore_lockfile)
Halt execution of the system with a specific message and exit code. The exit code is normally passed ...
Definition: m_common.f90:8868
logical, parameter, public yes
Definition: m_common.f90:1633
integer, parameter, public label_cen
Definition: m_common.f90:1743
elemental real(hrp) function, private m2cm_hr(value_m)
Convert m to cm.
Definition: m_common.f90:5607
real(srp), public global_rescale_maximum_motivation
Global maximum sensory information that is updated for the whole population of agents.
Definition: m_common.f90:4888
real(srp), parameter, public age_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for age perception effects on reproduction.
Definition: m_common.f90:4546
character(len=:), allocatable, public, protected mmdd
MMDD tag, year, month and day, used in file names and outputs. The value of the tag should be obtaine...
Definition: m_common.f90:2052
real(srp), parameter, public predator_attack_rate_default
Mean rate of a single predator attack.
Definition: m_common.f90:2360
elemental logical function, private float_equal_srp_operator(value1, value2)
This is a wrapper for the commondata::float_equal_srp() for building the user defined operator ....
Definition: m_common.f90:6341
character(len= *), parameter, public error_allocation_fail
Error message **"Cannot allocate array or object"** is issued if an array or an object is checked and...
Definition: m_common.f90:1855
pure integer function, dimension(:), allocatable, private stack2arrays_i(a, b)
Concatenate two arrays a and b. This procedure uses array slices which would be faster in most cases ...
Definition: m_common.f90:6176
pure logical function, private is_maxval_i(value, array)
Function to check if the value is the maximum value of an array (returns TRUE), or not (return FALSE)...
Definition: m_common.f90:7498
real(srp), parameter, public migrate_dist_penetrate_offset
The offset, in terms of the body length of the actor agent, for initial penetrating into the target e...
Definition: m_common.f90:5126
real(srp), parameter, public zero
Some parameters should never be zero or below. In such cases they could be set to some smallest disti...
Definition: m_common.f90:1644
real(srp), dimension(*), parameter, public probability_reproduction_delta_mass_ordinate
Interpolation grid ordinate for the body mass ratio factor that scales the probability of reproductio...
Definition: m_common.f90:4926
real(srp), parameter, public relocation_swap_rate
Mutation rate for chromosome relocation, i.e. probability of a gene moving to a different position on...
Definition: m_common.f90:2614
integer, parameter, public dielcycles
Number of days and nights in a lifespan, DIELCYCLES=500.
Definition: m_common.f90:2260
logical, parameter, public zip_outputs_background
This parameter defines if the output files are compressed in the background in the parallel mode or t...
Definition: m_common.f90:2019
logical, public, protected is_screen_output
Sets the model in screen output mode. If TRUE, the logger output goes to the screen (standard output ...
Definition: m_common.f90:1999
integer, parameter, public lifespan
Number of time steps in the agent's maximum life length.
Definition: m_common.f90:2066
real(srp), dimension(*), parameter, public predator_risk_group_dilution_ordinate
The array defining the ordinate grid values for the weighting nonparametric function linking the dist...
Definition: m_common.f90:2417
logical, dimension(max_nalleles, n_chromosomes), parameter, public food_mem_hunger_genotype_neuronal
The genotype structure for food items count perception effects on hunger that goes via gamma2gene per...
Definition: m_common.f90:3490
integer, public global_frame_number
The current global time frame. Frames are time steps within the time step defined by the commondata::...
Definition: m_common.f90:2099
integer, parameter, public history_size_behaviours
The size of the behaviour labels history stack, i.e. for how many time steps should the stack remembe...
Definition: m_common.f90:4897
real(srp), parameter, public depth_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for depth perception effects on hunger.
Definition: m_common.f90:3452
real(srp), parameter, public preycontrast_default
Inherent contrast of prey, CONTRAST =1.0.
Definition: m_common.f90:2527
real(srp), parameter, public food_item_capture_prop_cost
The cost of the food item catching, in terms of the food item mass (proportional cost)....
Definition: m_common.f90:2457
logical, dimension(max_nalleles, n_chromosomes), parameter, public pred_meancount_hunger_genotype_neuronal
The genotype structure for mean predator number perception effects on hunger that goes via gamma2gene...
Definition: m_common.f90:3586
real(srp), parameter, public attention_switch_hunger_food_dir
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4752
real(srp), parameter, public mutationrate_batch
Mutation rate for point allele mutations, a whole batch of allele components.
Definition: m_common.f90:2603
real(srp), dimension(*), parameter, public reproduct_body_mass_offspr_abscissa
The array defining the abscissa (X) of the nonparametric function curve that defines the relationship...
Definition: m_common.f90:2211
elemental real(srp) function alleleconv(raw_value)
Definition: m_common.f90:6907
real(srp), parameter, public reprod_modulation_devel_agestart
Developmental modulation of reproductive motivation. This parameter defines the starting age (time st...
Definition: m_common.f90:4599
real(srp), parameter, public attention_switch_reproduce_reprfac
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4820
elemental real(srp) function allelescale(raw_value)
Converts and rescales integer allele value to real value for neural response function.
Definition: m_common.f90:6883
real(srp), dimension(*), parameter, public behav_go_up_down_step_stdlen_static
This parameter array defines the step sizes, in units of the agent's body length, for the the_behavio...
Definition: m_common.f90:5171
real(srp) function std_dev(array_in, missing_code, undef_ret_null)
Calculate standard deviation using trivial formula:
Definition: m_common.f90:6089
logical, parameter, public modulation_appraisal_disable_all
Disable developmental or genetic modulation of the APPRAISAL completely. If set to TRUE,...
Definition: m_common.f90:4592
real(srp), parameter, public bodymass_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for body mass perception effects on reproduction.
Definition: m_common.f90:4480
pure subroutine, private add_to_history_r(history_array, add_this)
Simple history stack function, add to the end of the stack. We need only to add components on top of ...
Definition: m_common.f90:7325
real(srp), dimension(*), parameter, public linear_growth_hormone_increment_factor_curve_ordinate
The array defining the ordinate (Y) of the nonparametric function curve that defines the function lin...
Definition: m_common.f90:3134
logical, public, protected is_plotting
This parameter controls if the debug plots are produced. They can be huge number that takes lots of s...
Definition: m_common.f90:1992
real(srp), parameter, public invalid
Definition: m_common.f90:1699
logical, dimension(max_nalleles, n_chromosomes), parameter, public conspcount_reproduce_genotype_neuronal
The genotype structure for conspecifics number perception effects on reproduction that goes via gamma...
Definition: m_common.f90:4324
real(srp), parameter, public attention_switch_hunger_reprfac
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4770
real(srp), parameter, public light_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for light perception effects on hunger.
Definition: m_common.f90:3420
real(srp), dimension(*), parameter, public linear_growth_hormone_increment_factor_curve_abscissa
The array defining the abscissa (X) of the nonparametric function curve that defines the function lin...
Definition: m_common.f90:3123
real(srp), dimension(*), parameter, public arousal_gos_dissipation_nonpar_ordinate
This is the array defining the ordinate (Y) of the nonparametric spontaneous arousal dissipation fact...
Definition: m_common.f90:4881
logical, dimension(max_nalleles, n_chromosomes), parameter, public pred_direct_actv_avoid_genotype_neuronal
The genotype structure for direct predation perception effects on fear state that goes via gamma2gene...
Definition: m_common.f90:3961
elemental real(srp) function, private gamma2gene_fake_vals(signal, gs, gh, n_acomps)
This "fake" version of the gamma2gene is used to guess the response values in calculations.
Definition: m_common.f90:7195
elemental real(srp) function conv_l2r(flag, code_false, code_true)
Converts logical to standard (kind SRP) real, .FALSE. => 0, .TRUE. => 1.
Definition: m_common.f90:7421
logical, dimension(max_nalleles, n_chromosomes), parameter, public depth_hunger_genotype_neuronal
The genotype structure for depth perception effects on hunger that goes via gamma2gene perception to ...
Definition: m_common.f90:3426
real(srp), parameter, public attention_switch_hunger_pred_dir
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4758
pure logical function, private is_within_operator_r(x, limits)
A wrapper function for commondata::is_within() to build a user defined operator. Basically,...
Definition: m_common.f90:5903
real(srp), parameter, public attention_switch_reproduce_food_mem
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4804
real(srp) function, private timer_cpu_elapsed(this)
Calculate the time elapsed since the stopwatch subroutine was called for this instance of the timer c...
Definition: m_common.f90:7612
logical, dimension(max_nalleles, n_chromosomes), parameter, public pred_direct_reproduce_genotype_neuronal
The genotype structure for direct predation perception effects on reproduction that goes via gamma2ge...
Definition: m_common.f90:4357
real(srp), parameter, public food_item_capture_probability_subjective_errorr_cv
Subjective error assessing the food item capture probability when assessing the subjective GOS expect...
Definition: m_common.f90:2473
elemental real(srp) function carea(R)
Calculate a circle area.
Definition: m_common.f90:5665
integer, parameter, public predation_risk_weight_memory_window
The length of the perceptual memory window that is taken into account and weighted against the curren...
Definition: m_common.f90:3627
character(len= *), parameter, public ltag_warn
Definition: m_common.f90:1822
real(srp), parameter, public attention_switch_hunger_depth
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4750
real(srp), parameter, public reprfac_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for reproductive factor perception effects on fear state.
Definition: m_common.f90:4183
character(len=:) function, allocatable, private parse_svn_version()
Parse and cut revision number in form of string from the whole SVN revision string....
Definition: m_common.f90:9274
subroutine debug_interpolate_plot_save(grid_xx, grid_yy, ipol_value, algstr, output_file, enable_non_debug)
Produce a debug plot of the interpolation data using an external program htinterp from the HEDTOOLS t...
Definition: m_common.f90:8231
real(srp), parameter, public energy_gerror_cv
Genotype to phenotype initialisation, Gaussian error parameter. Coefficient of variation for the ENER...
Definition: m_common.f90:3201
real(srp), dimension(3), parameter, public habitat_safe_min_coord
Definition of the habitat spatial limits.
Definition: m_common.f90:2295
real(srp), parameter, public attention_switch_hunger_predator
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4760
integer, parameter, public d_prec_64
Definition: m_common.f90:1535
real(srp), parameter, public food_item_size_default
Default size of a single food item.
Definition: m_common.f90:2438
logical, dimension(max_nalleles, n_chromosomes), parameter, public age_reproduce_genotype_neuronal
The genotype structure for age perception effects on reproduction that goes via gamma2gene perception...
Definition: m_common.f90:4520
character(len= *), dimension(n_chromosomes), parameter, public lab_chromosomes
Set the labels of the chromosomes. NOTE, must be an array(vector) ) of the size commondata::n_chromos...
Definition: m_common.f90:2653
character(len= *), parameter, public exec_histogram
The name of the histogram program (hthist.f90 from HEDTOOLS) executable.
Definition: m_common.f90:1801
real(srp), dimension(3), parameter, public habitat_danger_max_coord
Definition: m_common.f90:2303
real(srp), parameter, public body_length_gerror_cv
Genotype to phenotype initialisation, Gaussian error parameter. Coefficient of variation for the BODY...
Definition: m_common.f90:3236
real(srp), parameter, public body_length_min
Minimum body length possible.
Definition: m_common.f90:2118
real(srp), parameter, public control_unselected_init
The initial value of the control unselected trait that goes through the gamma2gene.
Definition: m_common.f90:3270
real(srp), parameter, public foodcount_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for food items count perception effects on fear state.
Definition: m_common.f90:3888
real(srp), dimension(*), parameter, public probability_reproduction_delta_mass_abscissa
Interpolation grid abscissa for the body mass ratio factor that scales the probability of reproductio...
Definition: m_common.f90:4913
real(srp), parameter, public food_item_mean_size
The above is also the average size of a stochastic Gaussian food items.
Definition: m_common.f90:2442
real(srp), parameter, public escape_dart_distance_default_factor
The weighting factor used in calculation of the default escape distance. The escape distance is equal...
Definition: m_common.f90:5097
elemental real(hrp) function, private cm2m_hr(value_cm)
Convert cm to m.
Definition: m_common.f90:5565
real(srp), parameter, public beamatt
Beam attenuation coefficient of water (m-1),BEAMATT = 1.0.
Definition: m_common.f90:2522
real(srp), dimension(*), parameter reprod_modulation_devel_abscissa
Developmental modulation of reproductive motivation. This is the interpolation grid abscissa defining...
Definition: m_common.f90:4636
real(srp), parameter, public reproduction_cost_offspring_fract_female
The component of the energetic cost of reproduction in females that is proportional to the total offs...
Definition: m_common.f90:2186
elemental real(srp) function, private rescale_1(value_in, A1, B1)
Rescale a real variable with the range 0:1 to have the new range A1:B1.
Definition: m_common.f90:5735
real(srp), parameter, public age_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for age perception effects on hunger.
Definition: m_common.f90:3755
character(len=:) function, allocatable, private timer_cpu_title(this)
Return the title of the current timer object.
Definition: m_common.f90:7633
integer, public, protected lock_file_unit
This is the unit number that identifies the lock file. The lock file is created at the start of the s...
Definition: m_common.f90:1766
real(srp), parameter, public attention_switch_hunger_conspec
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4756
real(srp), dimension(*), parameter, public walk_random_food_hope_abscissa
This parameter defines the hope function for calculating the food perception expectancy in the the_be...
Definition: m_common.f90:5003
logical, dimension(max_nalleles, n_chromosomes), parameter, public light_hunger_genotype_neuronal
The genotype structure for light perception effects on hunger that goes via gamma2gene perception to ...
Definition: m_common.f90:3394
real(srp), parameter, public attention_switch_avoid_act_age
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4793
real(srp), parameter, public food_item_migrate_depth_mean
Mean shift parameter for the local random walk movement of food items in the vertical (depth) plane.
Definition: m_common.f90:2488
integer, parameter, public label_cst
This parameter defines the range of characters that is used for generating random labels,...
Definition: m_common.f90:1743
elemental real(srp) function, private rescale_full(value_in, A, B, A1, B1)
Rescale a real variable with the range A:B to have the new range A1:B1.
Definition: m_common.f90:5707
real(srp), dimension(*), parameter, public arousal_gos_dissipation_nonpar_abscissa
This is the array defining the abscissa (X) of the nonparametric spontaneous arousal dissipation fact...
Definition: m_common.f90:4872
integer, parameter, public ga_reproduce_n_min
Absolute minimum number of reproducing agents in the adaptive GA procedure. See the_population::popul...
Definition: m_common.f90:5208
elemental logical function, private float_equal_hrp(value1, value2, epsilon)
Check if two real values are nearly equal using the commondata::is_near_zero(). Thus function can be ...
Definition: m_common.f90:6307
logical, parameter, public preevol_tsteps_force_debug_enabled
This parameter enables the forced smaller fixed number of time steps set by the commondata::preevol_t...
Definition: m_common.f90:2085
real(srp), parameter, public testosterone_init
Genotype to phenotype gamma2gene initialisation value for testosterone
Definition: m_common.f90:2977
integer, public global_time_step_model_current
The current global time step of the model. This is a global non fixed-parameter variable that is upda...
Definition: m_common.f90:2095
real(srp), parameter, public reproduction_cost_body_mass_factor_male
The component of the energetic cost of reproduction in males that is proportional to the agent's body...
Definition: m_common.f90:2192
real(srp), parameter, public foodcount_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for food items count perception effects on reproduction.
Definition: m_common.f90:4284
logical, dimension(max_nalleles, n_chromosomes), parameter, public age_actv_avoid_genotype_neuronal
The genotype structure for age perception effects on fear state that goes via gamma2gene perception t...
Definition: m_common.f90:4124
character(len=:), allocatable, public, protected svn_version
Subversion or Mercurial revision number that is parsed by commondata::parse_svn_version()....
Definition: m_common.f90:1627
subroutine system_init()
Initialises the system environment and sets basic parameters.
Definition: m_common.f90:8405
real(srp), parameter, public growhorm_gerror_cv
Genotype to phenotype gamma2gene Gaussian error parameter. This is really the coefficient of variatio...
Definition: m_common.f90:2831
real(srp), parameter, public attention_switch_reproduce_bodymass
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4814
logical, dimension(max_nalleles, n_chromosomes), parameter, public foodcount_reproduce_genotype_neuronal
The genotype structure for food items count perception effects on reproduction that goes via gamma2ge...
Definition: m_common.f90:4258
elemental real(srp) function, private cm2m_r(value_cm)
Convert cm to m.
Definition: m_common.f90:5551
real(srp), parameter, public energy_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for energy reserves perception effects on reproduction.
Definition: m_common.f90:4513
logical, dimension(max_nalleles, n_chromosomes), parameter, public age_hunger_genotype_neuronal
The genotype structure for age perception effects on hunger that goes via gamma2gene perception to ne...
Definition: m_common.f90:3729
character(len= *), parameter, private procname
PROCNAME is the procedure name for logging and debugging (with commondata::modname).
Definition: m_common.f90:1605
pure subroutine, private add_to_history_i4(history_array, add_this)
Simple history stack function, add to the end of the stack. We need only to add components on top of ...
Definition: m_common.f90:7300
real(srp), parameter, public cortisol_gerror_cv
Genotype to phenotype gamma2gene Gaussian error parameter. This is really the coefficient of variatio...
Definition: m_common.f90:2947
integer, parameter, public preevol_tsteps_force_debug
Number of time steps in the agent's life at the fixed fitness pre-evolution stage....
Definition: m_common.f90:2079
logical, dimension(max_nalleles, n_chromosomes), parameter, public bodymass_actv_avoid_genotype_neuronal
The genotype structure for body mass perception effects on active avoidance that goes via gamma2gene ...
Definition: m_common.f90:4058
elemental real(srp) function length2sidearea_fish(body_length)
A function linking body length with the body area in fish.
Definition: m_common.f90:5682
real(srp), parameter, public relocation_shift_rate
Definition: m_common.f90:2615
real(srp), parameter, public ga_mutationrate_point_max
Maximum point mutation rate in the adaptive Fixed Fitness Genetic Algorithm.
Definition: m_common.f90:2599
real(srp), parameter, public allelescale_max
Conversion parameter that defines the scaling of the integer allele values ::ALLELERANGE_MIN to ALLEL...
Definition: m_common.f90:2587
real(srp), parameter, public attention_switch_avoid_act_bodymass
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4789
logical, dimension(max_nalleles, n_chromosomes), parameter, public reprfac_hunger_genotype_neuronal
The genotype structure for reproductive factor perception effects on hunger that goes via gamma2gene ...
Definition: m_common.f90:3761
real(srp), parameter, public food_item_capture_probability
The baseline probability that the food item is captured. See the_neurobio::food_item_capture_probabil...
Definition: m_common.f90:2463
real(srp), parameter, public migrate_dist_max_step
The maximum distance (in units of the agent body length) a migrating agent can pass for a single time...
Definition: m_common.f90:5116
character(len= *), parameter, public csv
Standard data file extension for data output is now .csv.
Definition: m_common.f90:1713
real(srp), parameter, public attention_switch_avoid_act_food_dir
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4777
real(srp), dimension(*), parameter, public motivation_compet_threshold_curve_abscissa
The array defining the abscissa (X) of the nonparametric function curve that defines the threshold fo...
Definition: m_common.f90:4849
real(srp), parameter, public conspcount_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for conspecifics number count perception effects on reproduc...
Definition: m_common.f90:4350
real(srp), parameter, public preyarea_default
Area of prey (m2), PREYAREA = 3.E-6.
Definition: m_common.f90:2532
integer, parameter, public consp_select_items_index_partial
Sets the limit for partial indexing and ranking of conspecifics in the visual range of the agent.
Definition: m_common.f90:3364
logical, parameter, public use_posix_fs_utils
Logical flag for setting if POSIX direct filesystem procedures are used. These utilities are implemen...
Definition: m_common.f90:1730
elemental integer function conv_l2i(flag, code_false, code_true)
Converts logical to integer following a rule, default FALSE = 0, TRUE = 1.
Definition: m_common.f90:7371
real(srp), parameter, public light_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for light perception effects on fear state.
Definition: m_common.f90:3823
elemental logical function, private is_within_i(x, lower, upper)
Logical function to check if a value is within a specific range, lower <= X <= upper....
Definition: m_common.f90:5869
real(srp), parameter, public walk_random_pred_risk_hope_agentl
The maximum walk distance, in units of the agent body length, when the expected predation risk is cal...
Definition: m_common.f90:4971
real(srp), dimension(*), parameter, public sex_steroids_increment_factor_age_curve_abscissa
The array defining the abscissa (X) of the nonparametric function curve that defines the relationship...
Definition: m_common.f90:3040
integer, parameter, public max_nalleles
This parameter defines the maximum number of alleles within the chromosome It IS NOT intended to vary...
Definition: m_common.f90:2643
real(srp), parameter, public ga_reproduce_pr
Percentage of the best reproducing agents in the pre-evolution phase.
Definition: m_common.f90:5185
real(srp), parameter, public food_item_migrate_xy_mean
Mean shift parameter for the local random walk movement of food items in the horizontal plane.
Definition: m_common.f90:2483
logical, dimension(max_nalleles, n_chromosomes), parameter, public energy_hunger_genotype_neuronal
The genotype structure for energy reserves perception effects on hunger that goes via gamma2gene perc...
Definition: m_common.f90:3697
integer, parameter, public history_size_motivation
Sets the size of the emotional state memory stack.
Definition: m_common.f90:3386
character(len= *), parameter, public exec_scatterplot
The name of the scatterplot program (htscatter.f90 from HEDTOOLS) executable.
Definition: m_common.f90:1797
real(srp), dimension(*), parameter, public sex_steroids_increment_factor_len_curve_ordinate
The array defining the ordinate (Y) of the nonparametric function curve that defines the relationship...
Definition: m_common.f90:3083
real(srp), parameter, public estrogen_gerror_cv
Genotype to phenotype gamma2gene Gaussian error parameter. This is really the coefficient of variatio...
Definition: m_common.f90:3017
real(srp), parameter, public food_mem_actv_avoid_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for food items count perception effects on fear state.
Definition: m_common.f90:3921
real(srp), parameter, public individual_mortality_risk_def
Default individually-specific mortality risk. It can increase or decrease depending on various factor...
Definition: m_common.f90:2341
real(srp), parameter, public migrate_random_max_dist_target
Default maximum distance towards the target environment (in units of the agent's body size) when the ...
Definition: m_common.f90:5121
real(srp), parameter, public lo_valid_sanitised
Lower bound for do_sanitise() procedure. This is the lowest value that considered valid.
Definition: m_common.f90:1660
integer function ieee_error_reporting(reset, tnote)
Check if an IEEE error condition has occurred.
Definition: m_common.f90:6584
real(srp), parameter, public attention_switch_hunger_food_mem
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4754
integer, parameter, public predators_num_habitat_danger
The number of predators in the dangerous habitat.
Definition: m_common.f90:2312
subroutine log_ieee(ttag, always_log, reset_flags)
LOG_IEEE: Check and log IEEE signalling flags. Logging normally occurs only if any nonzero output fro...
Definition: m_common.f90:9215
subroutine, private logger_init()
logger_init Initialise the system and the system logger.
Definition: m_common.f90:8978
real(srp), parameter, public reproduction_cost_offspring_fract_male
The component of the energetic cost of reproduction in males that is proportional to the total offspr...
Definition: m_common.f90:2180
real(srp), parameter, public pred_direct_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for direct predation perception effects on reproduction.
Definition: m_common.f90:4383
real(srp), parameter, public food_item_minimum_size
The minimum size of a food item. This is the "floor" in case the stochastically generated (e....
Definition: m_common.f90:2449
real(srp), parameter, public tolerance_high_def_srp
Default value of high tolerance (low precision). This is the standard commondata::srp precision real....
Definition: m_common.f90:1683
pure real(srp) function, private average_i(array_in, missing_code, undef_ret_null)
Calculate an average value of an integer array, excluding MISSING values.
Definition: m_common.f90:6024
real(srp), parameter, public lightdecay
Vertical conservation of light, per depth (old code lightdecay=0.2).
Definition: m_common.f90:2554
real(srp), dimension(*), parameter, public walk_random_food_hope_ordinate
This parameter defines the hope function for calculating the food perception expectancy in the the_be...
Definition: m_common.f90:5017
real(srp), dimension(*), parameter, public sex_steroids_increment_factor_age_curve_ordinate
The array defining the ordinate (Y) of the nonparametric function curve that defines the relationship...
Definition: m_common.f90:3053
real(srp), parameter, public food_item_migrate_xy_cv
Coefficient of variation parameter for the local random walk movement of food items in the horizontal...
Definition: m_common.f90:2493
real(srp), parameter, public walk_random_vertical_shift_ratio
The ratio of the vertical to main horizontal shift parameters of the agent's Gaussian random walk....
Definition: m_common.f90:4984
pure logical function, private is_within_operator_i(x, limits)
A wrapper function for commondata::is_within() to build a user defined operator. Basically,...
Definition: m_common.f90:5928
logical, dimension(max_nalleles, n_chromosomes), parameter, public stom_actv_avoid_genotype_neuronal
The genotype structure for stomach perception effects on active avoidance that goes via gamma2gene pe...
Definition: m_common.f90:4026
real(srp), parameter, public pred_meancount_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for mean predator number perception effects on reproduction.
Definition: m_common.f90:4416
real(srp), parameter, public viscap
Dimensionless descriptor of fish eye quality, VISCAP=1.6E6.
Definition: m_common.f90:2537
character(len= *), parameter, public cmd_zip_output
This parameter defines the compression program that is executed to "zip" the data files if commondata...
Definition: m_common.f90:2029
character(len= *), parameter, public svn_version_string
Subversion or Mercurial revision number (or ID) of the model code.
Definition: m_common.f90:1613
real(srp), parameter, public history_perception_window_food
The size of the memory window that is used in the assessment of food gain, as a portion of the common...
Definition: m_common.f90:5089
real(srp) function, private gamma2gene_additive_r4(gs, gh, signal, erpcv)
The function gamma2gene finds the sigmoid relationship for a complex multicomponent 2-allele impact o...
Definition: m_common.f90:7116
real(srp), dimension(*), parameter, public sex_steroids_increment_factor_len_curve_abscissa
The array defining the abscissa (X) of the nonparametric function curve that defines the relationship...
Definition: m_common.f90:3070
logical, parameter, public lifecycle_predation_disabled_debug
This parameter completely disables predation in the GA life cycle procedure.
Definition: m_common.f90:2091
character(len= *), parameter, public male
Set names of the sexes – the allele labels.
Definition: m_common.f90:2718
logical, dimension(max_nalleles, n_chromosomes), parameter, public stom_hunger_genotype_neuronal
The genotype structure for stomach perception effects on hunger that goes via gamma2gene perception t...
Definition: m_common.f90:3633
real(srp), parameter, public swimming_cost_factor_buoyancy_down
This parameter defines the cost of the buoyancy-based locomotion as a fraction of normal laminar flow...
Definition: m_common.f90:3327
logical, dimension(max_nalleles, n_chromosomes), parameter, public sex_male_modulation_reproduce_genotype
The genotype structure for sex modulation coefficient affecting reproduction motivation state in male...
Definition: m_common.f90:4653
real(srp) function, private gamma2gene_additive_i4(gs, gh, signal, erpcv)
The function gamma2gene finds the sigmoid relationship for a complex multicomponent 2-allele impact o...
Definition: m_common.f90:7005
logical, parameter, public enable_save_agents_each_timestep
This parameter defines if all agents data is saved at each time step of the life cycle....
Definition: m_common.f90:2040
real(srp), parameter, public swimming_speed_cost_burst
Set the weighting factor parameter of burst swimming cost in terms of the agent body size and the dis...
Definition: m_common.f90:3162
real(srp), parameter, public sex_male_modulation_reproduce_gerror_cv
Gaussian error parameter (cv) for the sex modulation coefficient affecting reproduction motivation st...
Definition: m_common.f90:4679
real(srp), parameter, public walk_random_food_gain_hope
The maximum walk distance, in units of the average distance to food items in the current perception o...
Definition: m_common.f90:4952
character(len= *), parameter, public error_auto_param_arrays
Error message for **"no automatic determination of the size in parameter"** arrays in the style:
Definition: m_common.f90:1849
character(len= *), parameter, public female
Definition: m_common.f90:2718
real(srp), parameter, public individual_visual_contrast_default
Inherent contrast of the agent, It is used in determining the visual range of an agent in perception ...
Definition: m_common.f90:3374
real(srp), parameter, public attention_switch_avoid_act_predator
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4785
character(len=label_length), parameter sexlocus_label
Labels for the sex locus alleles (gene) - vector as we don't need to label individual alleles....
Definition: m_common.f90:2715
character(len= *), parameter, public ltag_timer
Definition: m_common.f90:1825
pure logical function, private is_minval_i(value, array)
Function to check if the value is the minimum value of an array (returns TRUE), or not (return FALSE)...
Definition: m_common.f90:7563
character(len=:) function, allocatable, private timer_cpu_log(this)
A ready to use shortcut function to be used in logger, just adds the TIMER: tag in front of the norma...
Definition: m_common.f90:7680
real(srp), parameter, public stomach_content_init
Set average stomach capacity at birth/init in units of body weight,.
Definition: m_common.f90:3153
logical, dimension(max_nalleles, n_chromosomes), parameter, public pred_direct_hunger_genotype_neuronal
The genotype structure for direct predation perception effects on hunger that goes via gamma2gene per...
Definition: m_common.f90:3554
subroutine file_delete(file_name, success)
Delete a file from the local file system using Fortran open status=delete or fast POSIX C call.
Definition: m_common.f90:8323
real(srp), parameter, public stom_reproduce_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for stomach perception effects on reproduction.
Definition: m_common.f90:4448
real(srp), parameter, public other_risks_def
Default level of other mortality risks in the habitat.
Definition: m_common.f90:2324
logical, parameter, public false
Definition: m_common.f90:1632
real(srp), parameter, public predator_attack_capture_prob_frz_75
A parameter factor defining the probability of capture of an immobile (freezing) agent by a predator:...
Definition: m_common.f90:2388
logical, dimension(max_nalleles, n_chromosomes), parameter, public food_mem_actv_avoid_genotype_neuronal
The genotype structure for food items count perception effects on fear state that goes via gamma2gene...
Definition: m_common.f90:3895
character(len= *), parameter, public ltag_stage
Definition: m_common.f90:1820
real(srp), parameter, public mass_growth_threshold
A minimum body mass increment when any linear growth is possible, in units of the body mass (e....
Definition: m_common.f90:3109
character(len= *), parameter, public ltag_info
Definition: m_common.f90:1821
real(srp), parameter, public attention_switch_reproduce_food_dir
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4802
real(srp), parameter, public attention_switch_hunger_stomach
Baseline attention switch, see commondata::attention_switch_hunger_light.
Definition: m_common.f90:4762
real(srp), parameter, public bodymass_hunger_genotype_neuronal_gerror_cv
Gaussian perception error parameter (cv) for body mass perception effects on hunger.
Definition: m_common.f90:3691
CPU timer container object for debugging and speed/performance control. Arbitrary timers can be insta...
Definition: m_common.f90:1883