\chapter{The make-up of an experiment}\label{makeup}  % -*- Mode:TeX -*-

The purpose of this chapter is to make you familiar with the overall
structure of an experiment file and with what sort of things may
appear in it. The available resources are discussed more systematically
in the following chapters.

For a good understanding, you'll have to refer quite often both to the
book {\sl Cellular Automata Machines} mentioned in the
introduction---briefly, the ``{\sl CAM book\/}''---and to the glossary
(Appendix \ref{gloss}) at the end of this manual.  The former provides
the conceptual background for much of the present material; references
to it use a notation of the form `\cf{7.2}' for ``Section 7.2 of the
{\sl CAM book}.'' The latter provides concise technical definitions;
references to it are implicit, that is, all Forth words (which are set
in a typewriter font) mentioned in this book that are not of purely local
interest will be found listed and explained in the glossary.



\section{A minimal experiment}\label{barelife}

Assuming the work disk\index{Work disk} mentioned in Section \ref{soft-pack} is on
line, from \cam's \cp\ type \keyE\targ{barelife} (that's an upper-case {\tt E}) to
examine, through the screen editor's window, the source code for the \prog{BARELIFE}
experiment mentioned in Section \ref{first-exp} (cf.\ \cf{3.1,5.3}).  Figure
\ref{fig.barelife} is a verbatim reproduction of what you see in the window; the
entire source for this experiment consists ofjust that one screen.  

 \begin{figure}[tb]
 $$
        \begin{tabular}{|c|}
        \multicolumn{1}{c}{\small\tt Screen 1 \hfill BARELIFE.EXP \hfill (100\%)}\\\hline
        \begin{minipage}{\scrn}\small\smallskip
        \begin{verbatim}
\ BARELIFE (LIFE, with no frills)                     04Jan87tmt

NEW-EXPERIMENT

N/MOORE                                          
                                              : 8SUM ( -- n)
                          N.WEST NORTH N.EAST
                            WEST         EAST
                          S.WEST SOUTH S.EAST
                                + + + + + + + ;
                                              : LIFE
        8SUM { 0 0 CENTER 1 0 0 0 0 0 } >PLN0 ;

MAKE-TABLE LIFE
HALF 0 RND>PL




\end{verbatim}
        \microskip
        \end{minipage}\\\hline
        \end{tabular}
 $$
 \caption{Source screen for the {\tt BARELIFE} experiment}
 \label{fig.barelife}
 \end{figure}

Before discussing the contents of the screen, a few words about its
layout---which is meant to enhance readability.  We have chosen to set
flush with the left edge of the screen those commands that are to be
directly {\sl executed} by the Forth interpreter, while words that are
to be {\sl compiled} into the dictionary are aligned vertically on the
right.  Thus, by ``thumbing'' the left edge of the screen you see what
Forth is being asked to {\sl do}; by thumbing the right edge, you see
what it is being taught---and thereafter expected to {\sl know}. These
conventions are followed (somewhat loosely) throughout this manual.

The first line of code, \iprog{NEW-EXPERIMENT}, resets \cam's hardware and software
to a known, repeatable default state (see Section \ref{init} for more details).  In
particular, (a) all the Forth words added to the dictionary by the previous
experiment are wiped out, (b) the bit planes are cleared, (c) the look-up tables are
filled with zeros, (d) the color map defaults to the ``standard'' map \iprog{STD-MAP}
(Section \ref{std-map}), and (e) all the neighbor ``probes'' (as explained in
\cf{7.2}, which you may want to re-read now; Section 
\ref{neighborhoods} of the present manual can be used as a quick reference to neighborhoods)
are disconnected.\footnote
        {More precisely, they are parked on the
{\sl user inputs} of the external connector\cf{7.3.1}.}
        The screen is black, and would remain black if you issued
{\sl Step} commands at this point.


The second line, \prog{N/MOORE}\index{N.MOORE{\tt N/MOORE}}, is a {\sl neighborhood
assignment},\index{Neighborhood assignment} telling both software and
hardware that you plan to use the Moore neighborhood\cf{7.3.1}.  The
hardware will connect the relevant neighbor probes\cf{7.2}, while the
software will make the corresponding neighbor names available as Forth
words to be used in defining the rule.  We recall that \cam\ consists of
two ``halves,'' namely \cama\ (planes 0 and 1) and \camb\ (planes 2 and
3).  For the moment it will be convenient to imagine that only \cama\ is
present; then, the neighbors that are connected and made available as
Forth words by the \prog{N/MOORE} assignment are
        \begin{verbatim}
              N.WEST  NORTH  N.EAST
                WEST CENTER    EAST       CENTER'
              S.WEST  SOUTH  S.EAST\end{verbatim}
        where the unprimed variables refer to bits in plane 0.  The
primed variable \prog{CENTER'} refers to a bit in plane 1; our \id|LIFE| rule will
have no use for it.

The word \prog{8SUM} defines a function---namely the sum of the values
of the eight nearest neighbors---which will be used in defining the rule
itself.  (The pretty layout of these eight neighbor words in the Forth
text is of course only of mnemonic value; we could have typed them one
after the other.  Their order is irrelevant, since we add them all up.)

The word \prog{LIFE} provides an algorithmic description for the ``life''
rule\index{Rule description}---in terms of the behavior of a single, generic cell
(all cells will obey the same rule).  With reference to Figure \ref{fig.barelife}, from the
values of a number of neighbors (namely, the eight nearest neighbors, through the
word \prog{8SUM}, and the center cell, through the word \prog{CENTER}) the algorithm
(embodied in the word \prog{LIFE}) computes a 1-bit result, using a {\sc case}
construct (the one with curly braces; see Section \ref{case}); the word \prog{>PLN0}
specifies that this result is meant as the ``new-state'' bit for plane 0.

The line before the last, \iprog{MAKE-TABLE}\prog{LIFE}, tells the software to translate
the above description into tabular form\cf{7.6} and download the resulting
string of \id|0|s and \id|1|s---one ``new-state'' bit entry for each possible neighbor
configuration (see \cf{7.2} and Section \ref{table-generation} for details)---to
\cam's look-up tables.  Only at this moment is \cam\ ready to run ``life,'' as
in Section \ref{first-exp}.


\medskip

Thus, it is not the Forth word \prog{LIFE} as such that \cam\ will
execute 65,536 times (256\by256) per step.  \prog{LIFE} is merely a {\sl
table descriptor\/}\cf{4.2,7.6},\index{Lookup table/descriptor} and is executed {\sl by the \pc} once
for each entry of \cam's lookup tables\index{Lookup table/generation}, that is, $2^{12}$=4096 times;\footnote
        {Even though we are explicitly using only 9 neighbors, the tables are generated
for all possible values of the 12 available address lines (Section \ref{lookup}), some
of which are, in this case, irrelevant.}
        this is done once and for all while loading an experiment, before \cam\
even starts running.  This ``computational investment'' may take a few
seconds, but will be handsomely repaid every time \cam\ takes a step: by
having precomputed results available in the lookup tables, the amount of
``thinking'' \cam\ has to do in real time in order to update a cell is
reduced to a minumum.

When you start writing your own \cam\ experiments, if may happen that
any initial configuration will vanish after one step.  Before looking
for bugs in the rule, check that you do have a \prog{MAKE-TABLE}
command; without it, \cam\ can't possibly know anything about your rule.
\medskip

In conclusion, the minimal requirements for a complete, repeatable experiment
setup are
        \begin{itemize}
        \item The \iprog{NEW-EXPERIMENT} command,
        \item a neighborhood assignment,\index{Neighborhood assignment}
        \item a table descriptor\index{Lookup table/descriptor} for the desired rule, and
        \item a \iprog{MAKE-TABLE} command.
        \end{itemize}
Of course, before running the experiment one will have to put in the bit-planes
a suitable initial pattern. The last line of Figure \ref{barelife}, \prog{HALF 0 RND>PL},
fills bit-plane 0 randomly with half {\tt 0}s and half {\tt 1}s.


Practically all of the experiments of Chapters 1--10 of the \cambook\
are based on this minimal format; the variety of behavior illustrated there
arises from a suitable choice of rules and initial conditions---rather
that from the use of more advanced hardware or software \cam\ resources.

\section{The standard color map}\label{std-map}

In running \prog{BARELIFE} you'll have noted that live cells are shown
green on a black background.  In fact, the default, or {\sl standard}, color map---called
\iprog{STD-MAP}---uses {\sl green} for any cell that contains a \id|1| in
plane 0 only, {\sl blue} for plane 1 only, and {\sl red} for cells
having a \id|1| in both planes\cf{3.2}; in addition \id|1|s in planes 2
or 3 turn on the ``intensity'' beam, thus lightening a cell's
color.\index{Color map/standard}
 \begin{equation}\label{eq.std}
  \begin{tabular}{|c|c||c|c|c|c|l|}
   \multicolumn{7}{l}{Color-map: {\tt STD-MAP}} \\
   \hline
   \multicolumn{2}{|c||}{Plane} & \multicolumn{4}{c|}{Monitor line} & Pixel\\\cline{1-6}
    0  & 1  & I       & R       & G       & B       & color \\\hline\hline
   \tt0&\tt0& $\ast$  &         &         &         & black \\\hline
   \tt0&\tt1& $\ast$  &         &         &$\bullet$& blue  \\\hline
   \tt1&\tt0& $\ast$  &         &$\bullet$&         & green \\\hline
   \tt1&\tt1& $\ast$  &$\bullet$&         &         & red   \\\hline
   \multicolumn{7}{l}{$\ast$ `On' when planes 2 or 3 are `on'.}
  \end{tabular}
 \end{equation}
        This map is convenient when most of the action is in planes 0 or
1, as in many simple (and not so simple) experiments.  Later on (Section
\ref{color-map}) we shall discuss how to define custom color maps.

\section{Small changes}\label{small changes}

You may now start from a familiar situation, such as the above
\prog{BARELIFE} experiment, and try to make a few small changes or additions.

To avoid spoiling your distribution file \prog{BARELIFE.EXP}, copy it first to a
new file,\index{File/copying} say, \prog{PLAY.EXP}; a few keypresses
from the \cp\ will do (cf.\ Section \ref{editing}):
        \begin{itemize}
        \item Type \keyE\targ{barelife} to visit the first file.  
        \item Type \ctrlc\targ{play} to copy this file to a new file called \id|PLAY.EXP|.
        \item As soon as the copy is ready the editor will take you directly
to screen 1 of the new file; you may safely play with it.
        \end{itemize}

\medskip

You'll certainly be tempted to try some variants of ``life,'' for instance permuting
or complementing some of the \id|0|s and \id|1|s that appear in the {\sc case} list
(between braces in Figure \ref{fig.barelife}).  After making each change, escape from
the editor with \keyesc, load the \prog{PLAY} file again (using \keyl) and run a few
steps to see the results.

\medskip

Suppose, now, that you want to add the {\sc echo}\index{Echo} feature\cf{3.2} to
``life;'' that is, at each step, as \cam\ overwrites the state of plane 0 with a
new state as specified by \prog{LIFE}, the old state should be
saved in plane 1---so that this plane always reflects the situation of
plane 0 one step before.

In \cam\ Forth, one way to achieve this is to add (a) a separate table descriptor
for the evolution of plane 1 and (b) a separate \prog{MAKE-TABLE} command to translate
this descriptor and write the resulting information to \cam's lookup tables:
        \begin{verbatim}
                                      : ECHO
                         CENTER >PLN1 ;
    MAKE-TABLE ECHO\end{verbatim}
        Another way is to replace the \prog{LIFE} descriptor by one that
specifies the evolution of plane 1 as well\cf{7.6}, as follows
        \begin{verbatim}
                                      : LIFE ( with ECHO)
 8SUM {0 0 CENTER 1 0 0 0 0 0 } >PLN0 
                         CENTER >PLN1 ;\end{verbatim}
        With this table descriptor, the command \id|MAKE-TABLE LIFE|
will fill both \prog{PLN0} and \prog{PLN1} columns of the lookup
tables. Similar considerations apply to the {\sc trace}\index{Trace} feature\cf{3.3}, defined
as follows
        \begin{verbatim}
                                      : TRACE
              CENTER CENTER' OR >PLN1 ;\end{verbatim}
        (with {\sc trace}, a bit in plane 1 is turned on if the corresponding
bit in plane 0 was on---as with {\sc echo}---but then it {\em stays} on, so that
moving objects in plane 0 leave a continuous trace on plane 1).

Note that the words \iprog{ECHO} and \iprog{TRACE} (of plane 0 onto
plane 1), as well as \iprog{FREEZE} and \iprog{BARE} (two more handy
rule components which respectively ``freeze'' and ``keep clear'' plane 1's
contents) are predefined in the \cam\ software.  Thus, if you want plane
1 to ``hold on'' to whatever pattern you choose to store there---while plane 0
runs a rule---it is enough to put the command
        \begin{verbatim}
    MAKE-TABLE FREEZE\end{verbatim}
        in the source file, since the definition
        \begin{verbatim}
                                      : FREEZE
                        CENTER' >PLN1 ;\end{verbatim}
        is already present in the \cam\ Forth dictionary. You use \prog{BARE}
in a similar way to restore column \prog{PLN1} of the lookup table
to its default, ``all zeros'' state (cf.\ \ref{barelife}).

\section{Customizing the control panel}\label{attach}

We have seen how to change some aspects of a rule---for instance to
go from ``bare life'' to ``life with echo'' to ``life with trace'' and
back to ``bare life''---by editing the experiment file and loading it
again.  This, however, re-initializes the whole experiment, 
clearing whatever pattern you have in the bit-planes.

Since in this case all you want to do is modify the lookup tables,
a better way is to press the \keyf\ key to go to the Forth
interpreter, type, say, \id|MAKE-TABLE ECHO|, and go back to the \cp\
via the \keyesc\ key. Wouldn't it be much easier if by
just pressing a \cxp\ key one could switch on-the-fly from one variant
of the rule to the other?

\medskip

In \cam\ Forth, the {\sc unshifted}, {\sc shifted}, and {\sc control} versions
of each key are permanently associated with standard \cam\ or \pc\ functions, as
documented in Parts I and II.  On the other hand, the {\sl alternate} ({\tt
Alt-}) version of each key \index{Control-panel commands/user-defined commands} (obtained by
pressing that key while holding the {\sc Alt} key down) may be temporarily
attached to custom, user-defined functions through the ``alias'' mechanism
explained below.

Suppose you want to devote the \altt\ key to turning on the {\sc trace}
mode.  To attach the command \id|MAKE-TABLE TRACE| to this key, you
first define a new Forth word expressing that command, and {\sl immediately
after this definition\/} you write \iprog{ALIAS}\id|T|, as follows
        \begin{verbatim}
                                      : Trace
                     MAKE-TABLE TRACE ;   ALIAS T\end{verbatim} 
        We have chosen the name \id|Trace| (in lower case, to
distinguish it from \id|TRACE|) for mnemonic reasons; any other name
would do.  From this moment, every time you type \altt\ from the \cp\
the word \id|Trace| is immediately executed---just as if you had
typed it from the Forth interpreter.

\medskip

As long as they are in force, custom \cxp\ commands have exactly the
same status as standard commands.\footnote
        {In fact, the standard commands of \cam's \cp\ were attached
to their keys by the very same ``alias'' mechanism, during system
generation. Look, for example, at the source file {\tt CAM-KEYS.4TH}.}
        In particular, after attaching the word \id|Trace| to the \altt\ key
as above, the \id|ALTERNATE| menu, which you get by typing \narg{5}\keym\
(Section \ref{menus}) and is initially empty, will display the item
        \begin{verbatim}
    T Trace\end{verbatim} 
        Moreover, the name of this custom \cxp\ command---namely
\id|Trace|---will be echoed on the terminal whenever you hit the \altt\
key from the \cp, exactly as it happens for the standard commands.

A custom command remains in force until you attach a new custom command
to the same key, or execute \prog{NEW-EXPERIMENT} (in which case the key
to which it was attached reverts to ``Undefined'').

\medskip

Aliases are liberally used in the experiment of Figure \ref{fig.lifevar}.
Two alternative rule-components for plane 0 are defined; one is
the usual \id|LIFE|, the other, called \id|OTHER-LIFE|, is a slight variation on the 
same theme. For plane 1 we have the choice between \id|BARE|, \id|ECHO|, \id|TRACE|,
and \id|FREEZE|.

Note that, if we ignore for a moment the last line, this experiment file
gives a lot of definitions but does not actually send any tables to
\cam.  Once the file is loaded and the happy-face prompt reappears, it
will be your responsibility to select a rule, by typing, for example,
\alto\,\alte\ for ``other-life with echo.''

To make sure that at the beginning of the experiment a nonvacuous rule
will be present in \cam, the last line of Figure \ref{fig.lifevar}, namely
\id|Life Bare|, makes an initial selection (``plain life'') for you,
just as if you had hit the custom keys \altl\,\altb.

 \begin{figure}[tb]
 $$
        \begin{tabular}{|c|}
        \multicolumn{1}{c}{\small\tt Screen 1 \hfill VARLIFE.EXP \hfill (100\%)}\\\hline
        \begin{minipage}{\scrn}\small\smallskip
        \begin{verbatim}
\ Life variations                                     05Jan87tmt
NEW-EXPERIMENT N/MOORE                        : 8SUM
                          N.WEST NORTH N.EAST
                            WEST         EAST
                          S.WEST SOUTH S.EAST
                                + + + + + + + ;
                                              : LIFE
         8SUM {0 0 CENTER 1 0 0 0 0 0 } >PLN0 ;
                                              : OTHER-LIFE
         8SUM {0 0 CENTER 1 1 1 0 0 0 } >PLN0 ;
          : Life        MAKE-TABLE LIFE       ; ALIAS L
          : Other-life  MAKE-TABLE OTHER-LIFE ; ALIAS O
          : Bare        MAKE-TABLE BARE       ; ALIAS B
          : Echo        MAKE-TABLE ECHO       ; ALIAS E
          : Trace       MAKE-TABLE TRACE      ; ALIAS T
          : Freeze      MAKE-TABLE FREEZE     ; ALIAS F
Life Bare \end{verbatim}
        \microskip
        \end{minipage}\\\hline
        \end{tabular}
 $$
 \caption{Source screen for {\tt LIFE} variations.}
 \label{fig.lifevar}
 \end{figure}

\medskip

Run the experiment and play with the custom keys just introduced.
Instead of a random soup as an initial configuration, try also
one containing glider guns (file \id|GUNS.PAT|), which you can
load into plane 0 by typing \narg{0}\keyG\targ{guns}.


\section{Props}\label{props}

If you are giving a critical demo, you don't want to spend your time fumbling
with keys or trying to remember what you had called a certain pattern
file\index{File/pattern} to be used in the experiment.\index{Pattern/initial}

Suppose, for example, that you intend to play the glider-breeding
experiment discussed in\cf{3.4}. You want to run ``life''
starting from a primeval soup, and after a second or two you want to
{\sc and} the pattern on the screen with a circular mask, thus erasing
everything except the central portion of the picture.  From the shores
of this ``island,'' free-swimming gliders are likely to emerge.

\medskip

The idea is to have the experiment start not only with the \id|LIFE| rule
in the lookup tables and a few custom keys defined,
but also with the appropriate initial configuration already in
plane 0 and the desired mask pattern\index{Pattern/mask} already stored in planes 0's buffer.
When your audience is ready, you hit \keyS\ to start running.  After a
few seconds, without stopping the simulation, you hit the custom key
\altm\ to mask out the desired portion of the screen; a few gliders will
hopefully emerge. Hit the custom key
\altr\ to repopulate plane 0 with a new random configuration: in this way,
several breeding trials can be shown in close succession by alternating
\altr\ and \altm.

Here is the relevant portion of an experiment file for this
(we assume that \id|LIFE| has already been defined):
 {\small
        \begin{verbatim}
                 : Mask                0 AND>PL ;  ALIAS M
                 : Random         HALF 0 RND>PL ;  ALIAS R  

    OPEN-PATTERN DISK.PAT  \ Open desired pattern file
    0 FILE>PL              \ Move patt. from file, via plane 0
    0 PL>PB                \    to buffer 0

    MAKE-TABLE LIFE        \ Compile and download lookup tables
    MAKE-TABLE ECHO

    Random                 \ Start with random soup\end{verbatim}
 
 }
 \noindent  Refer to the glossary for a detailed explanation of the
new Forth words used here. Briefly,
        \begin{itemize}
        \item \id|Mask| will {\sc and} buffer
0 to plane 0, and is attached to the \altm\ key.
        \item \id|Random| will populate plane 0 with 50\%
randomness\index{Pattern/random} (the first argument of
\prog{RND>PL}\index{RND.PL{\tt RND>PL}} is the expected number of
\id|1|s; one-half of 256\by256 is a round 8000 in hexadecimal, or 37,768
in decimal---and is predefined for convenience as a constant called
\prog{HALF}), and is attached to the \altr\ key.
        \item \iprog{OPEN-PATTERN} creates a file control block for a pattern file
(in this case \id|DISK.PAT|) and makes it the {\sl current pattern}\index{File/pattern}
file, i.e., the one to which operations such as \prog{FILE>PL}
implicitly refer.
        \item \prog{FILE>PL}\index{FILE.PL{\tt FILE>PL}} with argument 0 moves this pattern from
its file to plane 0, and similarly \prog{PL>PB}\index{PL.PB{\tt PL>PB}} moves it from plane 0
to plane 0's buffer (no words are provided in \cam\ Forth for moving a
pattern directly from disk to a plane buffer).
        \item Note that, although we have attached \id|Random| to
a \cxp\ key, nothing prevents us from also using it from the interpreter
level, as we do in the last line in order to start the experiment
with a random soup already on the screen.
        \end{itemize}

Before being filled with the random soup, plane 0 will for
a short time contain the disk pattern (in transit for buffer 0).  To
avoid distracting your audience (the pattern would briefly flash on the \cam\
screen), you can momentarily inhibit the \cam\ display and then restore it
by using the commands \id|TRUE|\iprog{INVISIBLE} and \id|FALSE INVISIBLE|.

\medskip

The \cam\ words that are most likely to be useful in creating custom commands
are discussed under the following glossary headings
        \begin{verbatim}
    ALIAS ARG ARG?
    AREA AND>PL NOT-PL RND>BUF 
    OPEN-PATTERN FILE>IMAGE FILE>PLN
    MAKE-CMAP COLOR-MASK SHOW-FUNCTION SHOW-STATE
    MAKE-CYCLE NEXT-STEP STEP
    SHIFTS
    EVENT-COUNT
    OPEN-DATA
    OPEN-TABLE MAKE-TABLE 
        \end{verbatim}

\section{On-line analysis}\label{analysis}

\index{Data analysis}Let us consider, for a change, the ``brain'' rule of \cf{6.1}---a neural
network whose neurons communicate with their neighbors by immediate
contact.  A \id|1| in plane 0 means that the corresponding neuron is
firing; a \id|1| in plane 1 means that the neuron is in a refractory
state (``recovering''). The rule is repeated here in Figure \ref{fig.brainmon}.

If we start this rule with 90\% of the neurons firing, this fraction will
quickly drop; if we start with 1\%, this fraction will climb. In either case, the
fraction will converge toward an equilibrium value of approximately
2\%. We'd like to monitor in real-time the number of neurons that are firing,
by literally counting them at each step. By plotting this number vs time,
one can get an idea of how fast the system approaches equilibrium, and of the typical
size of the fluctuations about equilibrium.

\medskip

The firing of a neuron is a simple example of a {\sl cell event}, i.e., of a
situation that can be recognized by local and uniform mechanisms similar to
those used for updating a cell (see Sections \ref{color-map} and
\ref{show-function} for more details).

\Cam\ comes equipped with a real-time event counter,\index{Event counter} i.e., one that can
count cell events at the same rate as they occur.  For design
simplicity, the input of this counter is permanently connected to the
{\sl I} (``intensity'') output of the color map; that is, at the end of
each active step the number stored in the counter tells us how many intensified
pixels appeared on the screen during that step.  

The main programming issue, then, is how to translate occurrences of the
desired kind of cell event into \id|1|s on the {\sl I\/} line.  In the
above ``brain'' case the events to be counted are just the \id|1|s in
plane 0; thus, it is sufficient to use a color map where the {\sl I\/}
line directly reflects the contents of plane 0.  Clearly, the
{\sl IRGB\/} color map (Section \ref{irgb}) will do.

\medskip

A second issue has to do with the proper reading of the counter.  During
each active step\index{Step/active} (in which \cam\ scans and updates
the entire cell array) \cam's hardware counter is also updated---as the
sought-for events are encountered.\index{Step/idle}\footnote
    {During idle steps, in which \cam\ displays but does not update the
cell array, no counting is done.}
    At the end of the step, the contents of this hardware counter is
transferred to a {\sl count register} in the \pc.  In what follows, by
the `(event) count' or the `value of the (event) counter' we shall mean
the contents of this software register, which is readily accessible
and remains constant from the end of one active step to the end of the
next one.

We also have to decide what to do with the event counts as they are read.  We
could accumulate them in a memory buffer of reasonable size, and once in
a while flush this buffer to disk (Section \ref{data-files}); such a permanent
record may be used for off-line analysis.  We could plot them vs time as
they come---it is even possible to use a spare bit-plane of \cam\ as a
real-time plotting device (see sample file \id|Q2REOS.EXP|).  In the present case,
however, we will just print these counts on the terminal. Thus, we'll
have to tell the system that the default action attached to one tick
of the cellular-automaton clock (cf.\ Section \ref{run-cycle}), namely
``step,'' should be replaced by the sequence ``step, read count, print
count.'' An appropriate setup for the above experiment is given by the Forth
screen of Figure \ref{fig.brainmon}.

\medskip

 \begin{figure}
 $$
        \begin{tabular}{|c|}
        \multicolumn{1}{c}{\small\tt Screen 1 \hfill BRAIN.EXP \hfill (100\%)}\\\hline
        \begin{minipage}{\scrn}\small\smallskip
        \begin{verbatim}
\ Monitoring the BRAIN                                04Jan87tmt
NEW-EXPERIMENT N/MOORE                                : STIMULUS
    NORTH SOUTH WEST EAST N.WEST N.EAST S.WEST S.EAST
                                        + + + + + + + 
                                { 0 0 1 0 0 0 0 0 0 } ;
                                                      : BRAIN
          STIMULUS CENTERS 0= AND >PLN0  CENTER >PLN1 ;
MAKE-TABLE BRAIN
MAKE-CMAP IRGB-MAP                                    : FUD.
                         0 0 AT  (UD.) TYPE-S  8 0 AT ;
                                                      : COUNTING
                                STEP EVENT-COUNT FUD. ;   
            : Counting  DARK 8 0 AT   NEW-EVENTS STEP 
                                  MAKE-CYCLE COUNTING ;  ALIAS C
            : Normal    DARK    IDLE EVENT-COUNT FUD.
                                      MAKE-CYCLE STEP ;  ALIAS N\end{verbatim}
        \microskip
        \end{minipage}\\\hline
        \end{tabular}
 $$
 \caption{Source screen for monitoring the firings of {\tt BRAIN}.}
 \label{fig.brainmon}
 \end{figure}

The first part of this screen, up to \id|MAKE-TABLE BRAIN|, is by now
routine; the command
        \begin{verbatim}
    MAKE-CMAP IRGB-MAP\end{verbatim}
        makes \cam\ use the {\sl IRGB\/} color map (Section \ref{irgb}),
so that the contents of plane 0 will go verbatim to the {\sl I} beam,
to which the counter is attached.

The word \id|COUNTING| defines a {\sl run cycle}\cf{11.5}\index{Run cycle} suitable for
our counting needs (see Section \ref{run-cycle}).  In particular, \iprog{STEP} asks \cam\ to start a
new step as soon as possible (the previous step may still be in progress
at the moment \id|STEP| is executed) and waits until the new step is
actually ready to start; \iprog{EVENT-COUNT} picks up
the value of the event counter and places it on the the stack as a {\sl double
number\/}.\index{Forth/double number}\footnote
        {A Forth cell, consisting of 16 bits, can represent an unsigned
integer in the range 0--65,535 ({\tt 0000}--{\tt FFFF} in hex).  On the other hand,
the number of cells in the array---and thus the maximum value of an
event count---is 65,536, so that two cells are needed to store this
count. If you know for some reason that a count of 65,536 can never arise,
you can convert the double number to a single number using \prog{DROP};
otherwise you must use double-precision arithmetic (Section \ref{precision}).}
        Finally, \id|FUD.| prints this number on the terminal in a special
way that will be discussed in a moment together with the words \id|DARK| and \id|AT|---which
also have to do with printing.

The word \id|Counting|, attached to the custom key \altc, contains
(besides the phrase \id|NEW-EVENTS STEP|, discussed below) the command
\iprog{MAKE-CYCLE}\id|COUNTING|, which replaces the default run cycle by
the custom one just defined by us\cf{11.5}---namely \id|COUNTING|.  The
custom key \altn\ restores the default run cycle---which is simply
\prog{STEP}---after performing some final servicing of the counter.

\medskip

Load this experiment, put a random configuration in plane 0, and run the rule.
After a few seconds hit \altc\ to turn on the counting feature:
as the simulation proceeds, a stream of numbers
will start pouring out of the terminal
        \begin{verbatim}
    1990 1981 2007 1962 1991 1970 2012 ...\end{verbatim} 
        where each number represents how many cells were firing at the
corresponding step.  To turn off this stream, hit \altn.

\bigskip

An astute observer may notice that when one stops the simulation while
\id|COUNTING| is active, the
count last printed on the screen does not refer to the last step
executed but to the previous one: one count still has to come out.  This
occurs because the count is double-buffered, so that a new step can be
started before analysis of the previous step is performed.\footnote
    {This arrangement allows one to do a significant amount
of analysis even while \cam\ is running
at full speed.}
    The existence of this double-buffering mechanism (a first-in/first-out
pipeline with a two-item capacity)  also explains the
need for the phrase \iprog{NEW-EVENTS}\iprog{STEP} in the above
definition of \id|Counting|---which serves to prime the pipeline---and
the phrase \id|IDLE EVENT-COUNT FUD.|---which pulls the last count
out of the pipeline.

Details on the stepping process, the make-up of the run cycle, and
counting options are given in Sections \ref{run-cycle} and \ref{show-function}.

\medskip

The reason why we have to make recourse to a special printing procedure
is that the DOS terminal output routines are very inefficient, and would
take over a sixtieth of a second to print the count on the screen,
thus slowing down the simulation. \id|FUD.| makes use of
BIOS routines that are much faster.

\noteskip

{\small

The F83 word \id|(UD.)| converts a double number on the stack to a
character string. \id|TYPE-S| prints this string 
starting from the current cursor position. Since the BIOS routine
called by \id|TYPE-S| is not smart enough to start a new line when
the current line is full, we have to explicitly position the cursor
before each count is printed, using \id|AT| preceded by column and
row number. We chose to position the cursor at the upper-left
corner of the screen when printing the count, and reposition it 8 characters
to the right for the normal \cxp\ messages. \id|DARK| clears the screen
of any garbage left over by previous \cxp\ activity.

}

\noteskip

In spite of the above precautions, you'll notice that once in a while \cam\
still idles for one step when \id|COUNTING| is active: some
terminal-output activity is keeping the \pc\ busy right at the moment
when a new step should be scheduled, and the step is missed.

The essential tasks that the \pc\ must perform at each step in order to
keep \cam\ running at full speed are handled by interrupts, are
essentially invisible to the user, and take up only a small fraction of
one-sixtieth of a second (the duration of one \cam\ step).  If you avoid
getting bogged down in input/output, there is plenty of time left during
each step for the \pc\ to do substantial data analysis using a custom
run cycle.

If at any time the on-line data analysis tasks performed by the \pc\
should take longer than one \cam\ step (e.g., when you have to transfer
a memory buffer to disk), or are poorly timed (as in the above case)
nothing bad will happen: \cam\ will wait until the \pc\ is done (in
increments of one step time) and the simulation will just slow down.

\section{Data logging}\label{logging}

In the course of an experiment it may be useful to record on disk in a
continuous, incremental way some of the data produced by real-time
analysis (cf.\ previous section), or read from disk a stream of data to
be used as time-varying parameters for the experiment itself.

The \cam\ software provides basic interfacing with {\sl data
files}\index{File/data} for these and similar uses (see
Section \ref{data-files} and \iprog{OPEN-DATA} in the Glossary).  The experiment
\iprog{Q2REOS} provides a serious example of use of data files.
Here we will briefly illustrate the most basic concepts.

\medskip

In the \prog{BRAIN} experiment of Section \ref{analysis} we showed how
to count the number of cells that are firing at each step, and how to
display the sequence of such counts on the \pc\ screen.  Suppose, now,
that we want to make runs of 1024 steps of \prog{BRAIN} and log the resulting
counts, step by step as they come, on a disk file for subsequent
analysis. 

\medskip

The new version of the experiment is listed in Figure \ref{brainlog}.

First, we have to create the data file that will hold the counts.  Since
these counts come as double numbers\index{Forth/double number} (cf.\
Section \ref{precision}), and thus consist of four bytes each, the
experiment will generate 4096 bytes of data, equivalent to 4
blocks\index{Forth/block}
        \begin{verbatim}
    4 CREATE-FILE BRAIN.DAT\end{verbatim}
        Then, before the experiment starts running, we open this file as a
{\sl data} file
        \begin{verbatim}
    OPEN-DATA BRAIN.DAT\end{verbatim}
        Among other things, this reserves a block-size buffer in memory to 
temporarily hold data on their way to the disk (we don't want to slow
down the simualtion by making a separate disk access at every step),
and initializes the associated pointer to point to the very beginning
of the file.

        In Figure \ref{brainmon}, every time that during the course of
the experiment we got a count from \iprog{EVENT-COUNT} we displayed it
on the screen by means of the word \prog{FUD.}.  Here, the word
\prog{PUT-COUNT} gets the event-count data and appends it to the
currently open data file as a record consisting of two Forth
cells\index{Forth/cell} (i.e., the size of a double number).

The experiment is set up so that the run cycle runs the entire 1024
steps and closes the data file (\iprog{CLOSE-DATA}) at the end of it,
thus insuring that the memory buffer is safely stored to disk.  Load
this experiment and hit the \keyS\ key.  The
simulation will run the 1024 steps (the disk light will blink a few
times) and then stop by itself, with the logged counts recorded in the
\prog{BRAIN.DAT} file.  \iprog{REWIND} brings the file pointer back to
the beginning of the file, ready for another run.\footnote
        {In spite of its the name, {\tt CLOSE-DATA} actually leaves
the file open.}
        A new run will, of course, overwrite the data.  In between runs,
you may want to examine the logged data, do some further analysis on
them, or copy them to another file (cf.\ Section \ref{access-dos}).

\medskip

 \begin{figure}
 $$
        \begin{tabular}{|c|}
        \multicolumn{1}{c}{\small\tt Screen 1 \hfill BRAINLOG.EXP \hfill (100\%)}\\\hline
        \begin{minipage}{\scrn}\small\smallskip
        \begin{verbatim}
\ Monitoring the BRAIN                                04Jan87tmt
NEW-EXPERIMENT N/MOORE                               : STIMULUS
   NORTH SOUTH WEST EAST N.WEST N.EAST S.WEST S.EAST
                + + + + + + +  { 0 0 1 0 0 0 0 0 0 } ;
                                                     : BRAIN
         STIMULUS CENTERS 0= AND >PLN0  CENTER >PLN1 ;
MAKE-TABLE BRAIN
MAKE-CMAP IRGB-MAP                                   : PUT-COUNT
                       EVENT-COUNT PUT-DATA PUT-DATA ;
                                                     : LOGGING
                          NEW-EVENTS STEP  1023 0 DO
                                 STEP PUT-COUNT LOOP 
                                 IDLE PUT-EVENT STOP 
                                   CLOSE-DATA REWIND ;
4 CREATE-FILE BRAIN.DAT   OPEN-DATA BRAIN.DAT
MAKE-CYCLE LOGGING   HALF 0 RND>PL\end{verbatim}

        \microskip
        \end{minipage}\\\hline
        \end{tabular}
 $$
 \caption{Source screen for logging the firing counts of {\tt BRAIN}.}
 \label{fig.brainlog}
 \end{figure}
