GENESIS Reference ManualMay 5, 2001: GENESIS Object Reference

Previous Next Table of Contents

## 26. GENESIS Object Reference

## 26.1 Ca_concen

    Object Type:    Ca_concen

    Description:    Single pool model for Ca concentration.

    Author:         M. Wilson, Caltech (2/89)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  Ca_concen_type  [in src/segment/seg_struct.h]

    Size:           112 bytes

    Fields:         tau             time constant of decay
                    Ca_base         resting (base level) concentration
                    B               equals 1/(ion_charge * Faraday * volume)
                    Ca              Resulting concentraton of Ca++ ions
                    C               Intermediate result, Ca - Ca_base
                    thick           Holds thickness of shell (used by readcell)

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       CaConcen  [in src/segment/Ca_concen.c]

    Classes:        concentration segment

    Actions:        INIT
                    PROCESS
                    RESET
                    CHECK
                    SAVE2
                    RESTORE2

    Messages:       I_Ca  Ik              Receives ionic current Ik from a channel
                    BASE  Ca_base         Sets Ca_base with a message
                    fI_Ca Ik fraction     Receives fractional current Ik*fraction
                    INCREASE  delta_Ik    Add delta_Ik to incoming current
                    DECREASE  delta_Ik    Subtract delta_Ik from incoming current

    ------------------------------------------------------------------------------

    Notes:          Single shell model for Ca concentration.
                    Solves  dC/dt = B*Ik - C/tau.
                    Ca = Ca_base + C.

                    In SI units, where concentration is moles/m^3
                    (milli-moles/liter) and current is in amperes, theory gives B
                    = 5.2e-6/(shell volume).  In practice, B is a parameter to be
                    fitted or estimated from experiment, as buffering, non-uniform
                    distribution of Ca, etc., will modify this value.  If thick =
                    0, the readcell routine calculates B by dividing the "density"
                    parameter in the cell parameter file by the volume of the
                    compartment.  Otherwise, it scales as a true shell, with the
                    volume of a shell having thickness thick.  A negative value of
                    the "density" parameter may be used to indicate that it should
                    be taken as an absolute value of B, without scaling.

    Example:        see Scripts/burster

See also: readcell

## 26.2 Kpores

    OBJECT                          KPORES                  3/14/92 (AS)

    DESCRIPTION:
        Simulates a population of potassium ion channel proteins (pores)
        embedded in a patch of membrane over an isopotential region.  Each
        individual pore undergoes standard Markov kinetics through a five state
        scheme:

                  4an->        3an->        2an->         an->
            [n0]---------[n1]---------[n2]---------[n3]---------[n4]
                  <-bn         <-2bn        <-3bn        <-4bn

            where [n4] = Open State and an and bn have voltage dependencies
            given by:

            an = (alpha_A + alpha_B*Vk)/(alpha_C + exp((alpha_D+Vk)/alpha_F))

            bn = (beta_A + beta_B*Vk)/(beta_C + exp((beta_D+Vk)/beta_F))

            The total population of pores is given by Nt.
            The total number of pores within each of the five stable states
            at any given iteration is given by n0, n1, n2, n3, n4, respectively.
            The total number of pores in the open stable state is given
            by No = n4.
            The open state conductance of a pore is given by Gmax.
            The effective conductance for the population of pores at any
            given iteration is then Gk = Gmax*No.

    SPECIFICATIONS:
        FUNCTION            KPorePop()
        DATA STRUCTURE      K_pore_type
        CLASS               segment membrane
        SIZE                ?? bytes
        AUTHOR              A. Strassberg Caltech 3/92

    ACTIONS:
        CHECK       null
        RESET       sets initial distribution of pores into the various stable
                    states based upon the equilibrium solutions to the Markov
                    matrix for given Vk.
        PROCESS     updates the distribution of the stable states of the
                    population based upon the rate constants an and bn, derived
                    from the current transmembrane voltage Vk.
        INIT        null

    MESSAGES:
        VOLTAGE     sends transmembrane voltage Vk to the population of pores.
                    This Vk is used to update the state distribution after each
                    iteration.

    FIELDS:
        See DESCRIPTION

    RELATED COMMANDS/TOPICS:
        Napores

    ERROR MESSAGES:

    BUGS:

    NOTES:
        See Strassberg and DeFelice, 1993, Neural Computation 5:6
        and the demonstration scripts in Scripts/examples/pore

## 26.3 Mg_block

    Object Type:    Mg_block

    Description:    Implementation of voltage- and [Mg]-dependent
                    blocking of a channel.

    Author:         E. De Schutter, Caltech (11/90)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  Mg_block_type  [in src/segment/seg_struct.h]

    Size:           120 bytes

    Fields:         Ik              blocked value of current
                    Gk              blocked value of current
                    Ek              blocked value of current k
                    Zk              charge; may also be used as
                                    {charge / relative fraction of I},
                                    e.g. 2/(Ica/Itot) -> msg to difpool
                    KMg_A           A-factor K(v) in eq'n for Mg block reaction
                    KMg_B           B-factor K(v) in eq'n for Mg block reaction
                    CMg             [Mg] in mM

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       MgBlock  [in src/segment/Mg_block.c]

    Classes:        segment channel

    Actions:        INIT            [INIT does nothing]
                    PROCESS
                    RESET
                    CHECK

    Messages:       VOLTAGE Vm              voltage from the compartment
                    CHANNEL Gk Ek           unblocked Gk and Ek from compartment
                    CHANNEL1 Gk
                    CHANNEL2 Gk Ek
                    CHARGE Zk

    ------------------------------------------------------------------------------

    Notes:          An Mg_block element may be interposed between a synaptically
                    activated channel (a synchan or hebsynchan) and a compartment.
                    This calculates a blocked value of Gk that is reduced from
                    the incoming Gk by a factor of A/(A + [Mg]*exp(-Vm/B)).

                    The example below puts this in the form of the Zador, Koch,
                    and Brown equation [Proc. Natl. Acad. Sci. USA 10:6718-6722
                    (1990)], with A = 1/eta and B = 1/gamma.

    Example:

        float CMg = 2                       // [Mg] in mM
        float eta = 0.33                    // per mM
        float gamma = 60                    // per Volt
        create      synchan               {compartment}/{channel}
        setfield         ^ \
                    Ek                      {Ek} \
                    tau1                    {tau1} \
                    tau2                    {tau2} \
                    gmax                    {gmax}
        create Mg_block {compartment}/{channel}/block
            setfield         ^ \
                    CMg                     {CMg} \
                    KMg_A                   {1.0/eta} \
                    KMg_B                   {1.0/gamma}
        addmsg   {compartment}/{channel} {compartment}/{channel}/block \
                    CHANNEL Gk Ek
        addmsg   {compartment}/{channel}/block {compartment} CHANNEL Gk Ek
        addmsg   {compartment}   {compartment}/{channel}/block VOLTAGE Vm
        // Even though the channel current isn't used, CHECK expects this message
        addmsg   {compartment}   {compartment}/{channel} VOLTAGE Vm

See also: synchan

## 26.4 Napores

    OBJECT                          NAPORES                 3/14/92 (AS)

    DESCRIPTION:
        Simulates a population of sodium ion channels proteins (pores) embedded
        in a patch of membrane over an isopotential region.  Each individual pore
        undergoes standard Markov kinetics through an eight state scheme:

                      3am->                 2am->                 am->
            [m0h1]---------------[m1h1]---------------[m2h1]---------------[m3h1]
              |       <-bm         |       <-2bm        |        <-3bm       |
              |                    |                    |                    |
           /\ |                 /\ |                 /\ |                 /\ |
           ah | bh              ah | bh              ah | bh              ah | bh
              | \/                 | \/                 | \/                 | \/
              |                    |                    |                    |
              |       3am->        |        2am->       |         am->       |
            [m0h0]---------------[m1h0]---------------[m2h0]---------------[m3h0]
                      <-bm                 <-2bm                 <-3bm

        where [m3h1] = Open State and am, bm, ah and bh have voltage
        dependencies given by:

        am = (malpha_A + malpha_B*Vk)/(malpha_C + exp((malpha_D+Vk)/malpha_F))

        bm = (mbeta_A + mbeta_B*Vk)/(mbeta_C + exp((mbeta_D+Vk)/mbeta_F))

        ah = (halpha_A + halpha_B*Vk)/(halpha_C + exp((halpha_D+Vk)/halpha_F))

        bh = (hbeta_A + hbeta_B*Vk)/(hbeta_C + exp((hbeta_D+Vk)/hbeta_F))

        The total population of pores is given by Nt.  The total number of pores
        within each of the eight stable states at any given iteration is given by
        m0h0, m1h0, m2h0, m3h0, m0h1, m1h1, m2h1, and m3h1, respectively.  The
        total number of pores in the open stable state is given by No = m3h1.
        The open state conductance of a pore is given by Gmax.  The effective
        conductance for the population of pores at any given iteration is then
        Gk = Gmax*No.

    SPECIFICATIONS:
        FUNCTION            NaPorePop()
        DATA STRUCTURE      Na_pore_type
        CLASS               segment membrane
        SIZE                ?? bytes
        AUTHOR              A. Strassberg Caltech 3/92

    ACTIONS:
        CHECK       null
        RESET       sets initial distribution of pores into the various stable
                    states based upon the equilibrium solutions to the Markov
                    matrix for given Vk.
        PROCESS     updates the distribution of the stable states of the
                    population based upon the rate constants an and bn, derived
                    from the current transmembrane voltage Vk.
        INIT        null

    MESSAGES:
        VOLTAGE     sends transmembrane voltage Vk to the population of pores.
                    This Vk is used to update the state distribution after each
                    iteration.

    FIELDS:
        See DESCRIPTION

    RELATED COMMANDS/TOPICS:
        Kpores

    ERROR MESSAGES:

    BUGS:

    NOTES:
        See Strassberg and DeFelice, 1993, Neural Computation 5:6
        and the demonstration scripts in Scripts/examples/pore

## 26.5 PID

    Object Type:    PID

    Description:    PID (proportional, integral, derivative) feedback controller

    Author:         M. Nelson, Caltech (4/89)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  PID_type  [in src/user/user_struct.h]

    Size:           144 bytes

    Fields:         cmd          inputs the command (desired) value of sns
                    sns          inputs the sensed (measured) value
                    output       = gain*(e + tau_d*de/dt + 1/tau_i * e_integral)
                    gain         determines the sensitivity of the controller
                    tau_i        integration time constant, typically = dt
                    tau_d        derivative time constant, typically = dt/4
                    saturation   sets permissible range of output
                    e            internal variable (error = cmd-sns)
                    e_integral   internal variable (integral of e dt)
                    e_deriv      internal variable
                    e_previous   internal variable

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       PIDcontroller  [in src/user/PID.c]

    Classes:        device

    Actions:        INIT
                    PROCESS
                    RESET

    Messages:       CMD command
                    SNS sense
                    GAIN gain

    ------------------------------------------------------------------------------

    Notes:

    The PID is used for feedback control of dynamical systems.  For example, in
    a voltage clamp circuit it is used with a pulsegen, RC, and diffamp device
    to provide the required injection current to maintain the membrane voltage
    at the desired level.  The RC-filtered command voltage is scaled by the
    diffamp and then presented to the PID with a CMD message.  The output is
    sent to a compartment with an INJECT message, and the resulting Vm in the
    compartment is fed back to the PID with a SNS message.  A higher gain gives
    a better clamp, but requires a smaller integration time step to avoid
    numerical instability.

    For more information on PID controllers see: Franklin, Powel, Emami-Naeini
    (1986) "Feedback Control of Dynamic Systems", Addison-Wesley, pp. 99-106.

    Example:        Scripts/squid/squid_electronics.g

    See also:

## 26.6 RC

    Object Type:    RC

    Description:    A series resistance R, shunted by a capacitance C.

    Author:         M. Wilson, Caltech (6/88)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  RCunit_type  [in /usr/genesis/src/segment/seg_struct.h]

    Size:           96 bytes

    Fields:         V0      initial value of "state" (set on RESET)
                    R       series resistance
                    C       shunting capacitance
                    state   output value
                    inject  input value

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       RC_Unit  [in src/segment/rcunit.c]

    Classes:        segment

    Actions:        CHECK  PROCESS  RESET

    Messages:       INJECT inject (input-value)

    ------------------------------------------------------------------------------

    Notes:

    An RC element is often used as a low-pass filter, as with a voltage clamp
    circuit, in order to prevent a step change in the command voltage from
    causing numerical instabilities.

    Example:        Scripts/squid/squid_electronics.g

    See also:

## 26.7 asc_file

    Object Type:    asc_file

    Description:

    The asc_file object is used to write data to a file in ASCII format.  A new
    line is written at every time step of the clock which is assigned.  Unless
    the notime flag is set, the first item on each line is the simulation time.
    Each SAVE message which is received adds another item to the line.

    Author:         M. Wilson, Caltech (4/89)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  ascfile_type  [in src/out/out_struct.h]

    Size:           88 bytes

    Fields:
                    filename        data file name to be written
                    fp              data file pointer
                    is_open         flag: is file currently open?
                    initialize      flag: has file been initialized?
                    leave_open      flag: leave file open? 1 leaves the file open
                                    all the time so you can write on it whenever
                                    you want (a good idea if the file is used
                                    frequently, but there is a limit to number of
                                    files that can be left open at any time);
                                    0 closes the file after every write to it
                                    (only useful if you have more than 30 files;
                                    this is slow)
                    append          flag: append data after resetting?
                    flush           flag: flush data to disk at each interval?
                                    1 forces program to send data to the disk at
                                    once and not store it in a buffer (slow but
                                    secure); 0 (default) writes data in a buffer
                                    (fast)
                    notime          flag: if non-zero, don't output the time

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       AscFileOutput  [in src/out/out_ascfile.c]

    Classes:        output

    Actions:        RESET  PROCESS  DELETE  SAVE  FLUSH  OUT_OPEN  OUT_WRITE

    Messages:       SAVE data

    ------------------------------------------------------------------------------

    Notes:

    If the filename field is not set, the output file will be given the same
    name as the element which is created from the asc_file object.

    When the append flag is zero, a reset will close and reopen the file,
    setting the file pointer at the begining, effectively creating a new file
    if the simulation is stepped again.  When the append flag is set to a
    non-zero value, additional steps after a reset will be appended to the
    file.  The OUT_WRITE action may be called to write any string to the file.
    The OUT_OPEN command is used to manually initialize the file for writing,
    and must be called before calling OUT_WRITE.  In append mode, it must be
    called after changing the filename to a new output file name, or renaming
    an existing one.

    For binary data, use disk_out.

    Example:

        create asc_file /out
        setfield /out    flush 1    leave_open 1    append 1
        setclock 1 0.001
        useclock /out 1
        // Assume the existence of /cell/soma to provide output
        addmsg       /cell/soma     /out       SAVE Vm
        setfield /cell/soma inject 0
        step 0.1 -t
        // append the results of a new run with different injection
        setfield /cell/soma inject 0.1e-9
        reset
        step 0.1 -t
        // now do yet another injection with output to a different file
        setfield /out filename out2
        call /out OUT_OPEN
        call /out OUT_WRITE "Run #2"        // Write a header
        setfield /cell/soma inject 0.2e-9
        reset
        step 0.1 -t

See also: disk_out , disk_in

## 26.8 autocorr

    Object Type:    autocorr

    Description:    Computes the auto-correlation of a spike train
                    A histogram containing the count of
                    events for each bin is constructed.

    Author:         D. Jaeger, Caltech (9/92)
                    revised for Genesis v2.2 11/99

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  doac_type  [in genesis/src/device/spike_struct.h]

    Size:           100 bytes

    Fields:         num_bins        (int) number of bins in histogram
                    binwidth        (float) binwidth in sec
                    reset_mode      (int) 0 or 1
                    threshold       (float) input amplitude triggering spike event
                    *acarray        (int)   histogram array containing data
                    nospks          (int) number of spikes from source
                    *sptimes        (float) array of spike times from source
                    curridx         (int) internal indexing
                    calcidx         (int) internal indexing
                    maxspikes       (int) internal boundary condition
                    wintime         (float) internal boundary condition
                    dont            (int) internal condition
                    allocated       (int) internal condition

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Doac  [in genesis/src/device/acxc.c]
    Classes:        datanal

    Actions:        PROCESS         update *sptimes, *acarray, nospks
                    RESET           if reset_mode = 0, empties *sptimes but not
                                            *acarray
                                    if reset_mode = 1, empties *sptimes and
                                            recreates *acarray

    Messages:       SPIKE : signal amplitude from source

    ------------------------------------------------------------------------------

    Notes:
                    User must setfield num_bins and binwidth (in sec) so
            that a data array is created on RESET. The input is assumed to
            cross the amplitude given in the threshold field only for one
            timestep to generate a spike. Vm is not to be used as an input field.
            Valid inputs may be derived from random, neutral or spike objects.
                    An internal spike time buffer is set up for a maximal
            spike rate of 1000 events / second. A greater density of spikes
            will lead missed events in the histogram.
                    The auto-corrlation histogram is updated with each timestep.
            However, the first results will only be available after the
            simulation time has reached the value of num_bins * binwidth.
            This is due to the fact that any spike needs to be correlated
            with other spikes across a time window of this duration.
                    The data are stored in *acarray and can be accessed with
            a getfield command (see example).

    Example:

    create autocorr /ac
    setfield ^ binwidth 0.002 num_bins 200 threshold 0.5

    /* this example uses random object for input */
    create random /input
    setfield ^ min_amp 1 max_amp 1 rate {in1_rate} reset 1 reset_value 0
    addmsg /input1 /ac SPIKE state

    /* To display data on a graph, use this function after creating the graph */
    function plotac(source, dest, pname, color)
        str source,dest,color
        int maxbin

        int i,barval

        maxbin = {getfield {source}, num_bins}
        setfield {dest} xmax {maxbin}
        call {dest} RESET

        for(i=0; i < maxbin; i = i + 1)
            barval = {getfield {source}, acarray[{i}]}
            addpts {dest} -plotname {pname} -color {color} {i} 0
            addpts {dest} -plotname {pname} -color {color} {i} {barval}
            addpts {dest} -plotname {pname} -color {color} {{i}+1} 0
        end
    end

See also: crosscorr , interspike , peristim , Scripts/examples/spike/spikes.g

## 26.9 calculator

    Object Type:    calculator

    Description:    Adds, subtracts, multiplies, and divides using messages.

    Author:         Erik De Schutter, BBF-UIA 6/98

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  calc_type [in src/device/dev_struct.h]

    Size:           100 bytes

    Fields:         output          computed value
                    resetclock      clock # used to reset output value (default 0)
                    output_init     value of output after reset (default 0)

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       CalculatorFunc [in src/device/calculator.c]

    Classes:        device

    Actions:        RESET  PROCESS  DELETE  CREATE

    Messages:       SUM         number
                    SUBTRACT    number
                    MULTIPLY    number
                    DIVIDE      number

    ------------------------------------------------------------------------------

    Notes:

    The calculator is often used to sum multiple inputs.  For example, the
    total channel current in a cell could be calculated with:

        foreach s ({el /cell/##[CLASS=channel]})
            addmsg {s} /calculator_element SUM Ik
        end

    With the resetclock default of clock 0, the calculator is reinitialized to
    output_init (default 0) at every time step, so that it may calculate a new
    value of the sum from incoming messages at each time step.  If resetclock is
    set to a clock with a longer time step, then operations are performed on
    the previous output, until it is time to reset the output to output_init.
    The example below uses a resetclock with a longer time step in order to
    generate a periodic ramp output.

    Example:

    create xform /data
    create xgraph /data/calculator
    create xbutton /data/RESET -script reset
    create xbutton /data/RUN -script "step 100"
    create xbutton /data/QUIT -script quit
    xshow /data

    // Create a ramp generator by summing a constant input
    // The length of the ramp is given by the resetclock

    setclock 0 1.0
    setclock 1 25.0
    create neutral /source
    setfield /source x 4
    create calculator /source/ramp
    setfield /source/ramp resetclock 1

    addmsg /source /source/ramp SUM x
    addmsg /source/ramp /data/calculator PLOT output *output *red
    addmsg /source /data/calculator PLOT x *input *blue
    reset

    See also:

## 26.10 compartment

    Object Type:    compartment

    Description:    Axially asymmetric compartment. Ra is located on
                    one side of the compartment. This is slightly more
                    computationally efficient than the symmetric counterpart.

    Author:         M. Wilson, Caltech (6/88)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  compartment_type  [in src/segment/seg_struct.h]

    Size:           124 bytes

    Fields:         Rm              total membrane resistance
                    Cm              total membrane capacitance
                    Em              membrane resting potential
                    Ra              axial resistance
                    inject          injected current in membrane
                    dia             compartment diameter
                    len             compartment length
                    Vm              voltage across the membrane
                    previous_state  Vm at previous time step
                    Im              approximation to the total membrane current
                    initVm          initial value to set Vm on reset

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Compartment  [in src/segment/compartment.c]

    Classes:        segment
                    membrane

    Actions:        INIT            assign previous_state = Vm
                    PROCESS         update Vm, calculate Im
                    RESET           assign Vm = Em
                    CHECK           make sure Rm>0, Cm>0,
                                    Ra'>0 (if RAXIAL message is present),
                                    Ra>0 (if AXIAL message is present)
                    SAVE2
                    RESTORE2

    Messages:       CHANNEL Gk Ek   delivers the conductance and equilibrium
                                    potential of channel within the compartment
                    RAXIAL Ra Vm    delivers the Ra and Vm of a compartment
                    AXIAL Vm        delivers the Vm of a compartment
                    INJECT inject   sets the inject field to the message value
                    EREST Em        sets the Em  field to the message value

    ------------------------------------------------------------------------------

    Notes:          Simulates a section of passive membrane or cable. The
                    potential across the membrane is given by Vm. There is a
                    leakage path for current through the resistance Rm. This
                    resistance is in series with a leakage battery Em. This
                    compartment can be coupled to other compartments with an axial
                    resistance Ra.  The compartment is not symmetrical, with Ra
                    lumped to one side of the compartment.  Any number of ionic
                    channels can be introduced into the membrane (Gk, Ek in the
                    circuit diagram).  The membrane also allows current
                    injection.

                    The compartment Im is the sum of axial currents and injected
                    current only.  The (transmembrane) channel currents or the
                    leakage current are not included.  For a multicompartment
                    cell, under a quasistatic approximation (C*dV/dt is small), Im
                    is approximately equal to the sum of the channel and leakage
                    currents, due to charge conservation.  This approximation is
                    used in the efield object (see efield.doc) to allow Im to be
                    used to calculate external field potentials.  The exception to
                    this is when Im is calculated with hsolve in chanmode 4.  In
                    that case, Im is directly calculated as the sum of the channel
                    currents and leakage current though Rm.

                    When a compartment performs its RESET action (usually
                    invoked by the reset command), Vm is set to the value of the
                    initVm field.  Normally, initVm follows any changes to Em,
                    so Vm will be initialized to Em upon reset.  If, as in the
                    Hodgkin-Huxley model, Em is a leakage potential that is
                    different from the rest potential, initVm may be set to the
                    rest potential.  It will then no longer follow Em, and Vm
                    will be set to the rest potential upon reset.

                    Calculates Vm using:

                        dVm/dt = {(Em - Vm)/Rm + SUM[(Ek - Vm)*Gk] +
                            (Vm' - Vm)/Ra' + (Vm'' - Vm)/Ra + inject}/Cm

                    In the diagram, the compartment shown in the middle
                    receives the Vm' and Ra' of the upper compartment with
                    an RAXIAL message, and the Vm'' of the lower compartment
                    with an AXIAL message.  Channels deliver their Gk and Ek
                    with a CHANNEL message.

                        Vm'
                       o_________________________________________________
                       |                |             |        |        |
                       \
                       /  Ra'
                       \
                       |
                       |
                       | Vm
                       o_________________________________________________
                       |                |             |        |        |
                       \                |             |        |        |
                       /  Ra            \             \        |        |
                       \              --/-->          /        |     ___|___
                       |             Gk \        Rm   \       / \    _______ Cm
                       |                |             |      / A \      |
                       |                |             |      \ | /      |
                       |         Ek    ---       Em  ---      \ /       |
                       |             -------       -------     | Iinject|
                       |                |             |        |        |
                       |                |_____________|________|________|
                       |
                       | Vm''
                       o_________________________________________________
                       |                |             |        |        |

    Example:

See also: symcompartment

## 26.11 concchan

    Object Type:    concchan

    Description:    Concentration-driven membrane channel. Equivalent
                    to 1-D diffusion of molecules across a membrane. The
                    concchan, like the enzyme, is a property of a pool and so
                    each concchan should be attached to a pool which specifies
                    the number of concchans.

    Author:         U. S. Bhalla MSSM Aug/93

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  [in src/kinetics/kin_struct.h]

    Size:           124 bytes

    Fields:
                    A, B            Internal state variables, used to
                                    communicate with pools. A represents
                                    increase in the pool n, B is the decrease.
                    perm            Permeability
                    gmax            conductance (not currently used)
                    n               number of concchans
                    Vm              potential across channel (not currently used)
                    use_nernst      flag (not currently used)

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       [in src/kinetics/concchan.c]

    Classes:        segment

    Actions:        SET  PROCESS  RESET

    Messages:
                    SUBSTRATE   n vol  Number of molecules in substrate pool
                    PRODUCT     n vol  Number of molecules in product pool
                    NUMCHAN     n      Number of concchans specified by pool
                    Vm          Vm     Sets the Vm field (not currently used)

    ------------------------------------------------------------------------------

    Notes:          The concchan allows the substrate and product pools to diffuse

                    back and forth.  The state variables A and B are used in the
                    return messages to the substrates and products.  (However the
                    roles of A and B are reversed for the product pools).

                    If there are both substrate and product pools (as evidenced by
                    having both a SUBSTRATE and a PRODUCT message to the
                    concchan), the SUBSTRATE message calculates conc1 = n/vol, and
                    PRODUCT calculates conc2 = n/vol.  Here, n/vol represents the
                    density of molecules in the pool, not the density of conchans.
                    Then A and B are set to

                            A = conc2 * perm * n
                            B = conc1 * perm * n

                    where n is the number of concchans.

    Example:        // numerically attach the chan to the pool
                    addmsg {pool} {chan} NUMCHAN n
                    // Attaches the pool to the chan as a substrate
                    addmsg {chan} {pool} REAC A B
                    addmsg {pool} {chan} SUBSTRATE n vol

                    // Attaches the pool to the chan as a product
                    addmsg {chan} {pool} REAC B A
                    addmsg {pool} {chan} PRODUCT n vol

See also: pool

## 26.12 concpool

    Object Type:    concpool

    Description:    A "well-mixed" concentration pool without diffusion that can
                    have miscellaneous in/out flows (when coupled to other
                    objects).  It has better controls over size/volume than
                    Ca_concen and does not include its own equilibration
                    mechanisms.

    Author:         E. De Schutter BBF-UIA 4/94 - 3/99

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  concpool_type [in src/concen/conc_struct.h]

    Size:           132 bytes

    Fields:         C               concentration (calculated by concpool) in mM
                    prev_C          concentration at previous time step
                    Ceq             equilibrium concentration in mM
                    val             ionic valence
                    leak            constant in/outflow in mM/sec
                    shape_mode      Set to one of the predefined global variables
                                    SHELL=0, SLICE=SLAB=1, TUBE=2, USERDEF=3.

                        SHELL: onion shell. Set len for cylindrical shell (zero
                        length for spherical shell), dia (outer diameter of shell)
                        and thick (thickness of shell); vol, is computed on RESET.

                        SLICE (or SLAB): salami slices of cylinder.  Set dia
                        (diameter of cylinder) and thick (thickness of slab), len
                        is not used; vol is computed on RESET.

                        TUBE: a cylinder with diameter dia and length len.  For
                        concpools inside a difshell: make dia negative in the
                        prototype; readcell will scale len so as to obtain an
                        appropriate change in vol relative to the difshell.

                        USERDEF: len, dia, thick are not used. Set vol field
                        to desired pool volume.

                    len             shell length
                    dia             shell diameter
                    thick           shell thickness
                    vol             shell volume

    -----------------------------------------------------------------------
    SIMULATION PARAMETERS

    Function:       ConcPool [in src/concen/concpool.c]

    Classes:        concentration segment

    Actions:        RESTORE2  SAVE2  CHECK  RECALC  RESET  PROCESS  INIT

    Messages:       CONCEN      C             (sets C with a message)
                    STOREINFLUX flux          (flux into store in moles/sec;
                                              increases C)
                    STOREOUTFLUX flux         (flux out of store in moles/sec;
                                              decreases C)
                    BUFFER kBf kBb Bfree Bbound (fields sent from a buffer,
                                                        e.g. a fixbuffer)
                    HILLPUMP    vmax Kd Hill  (sent from a hillpump; setting
                                               Hill=1 is equivalent to an
                                               MMMPUMP message from an mmpump)

    ------------------------------------------------------------------------------

    Notes:

    Unlike the difshell, the concpool provides a single shell model of a
    "well-mixed" concentration pool without diffusion between shells.  As it can
    also couple to buffers and pumps, it provides for multiple mechanisms for
    calcium removal and has better controls over size/volume than the Ca_concen.

    The buffers (e.g, fixbuffer) interact with a difshell or concpool to model the
    binding of calcium to buffer molecules and to calculate the concentrations of
    free and bound ions using a kinetic scheme with forward and backward rate
    constants for the binding and release of calcium.  The BUFFER message from a
    buffer passes on the rate constants and the calculated free and bound
    concentrations so that the concpool may calculate the resulting ion
    concentration C.  Details of the fields that are passed to the concpool with
    messages from buffers and the hillpump are provided in the documentation for
    these objects.

    For a general description of buffered calcium diffusion see:  De Schutter E.,
    and Smolen P., "Calcium dynamics in large neuronal models", in Methods in
    neuronal modeling: From ions to networks (2nd edition), C. Koch and I. Segev
    editors, pp. 211-250 (1998).

    Example:

See also: difshell , fixbuffer , hillpump

## 26.13 crosscorr

    Object Type:    crosscorr

    Description:    Computes the cross-correlation between two trains of
                    spike events. A histogram containing the count of
                    events for each bin is constructed.

    Author:         D. Jaeger, Caltech (9/92)
                    revised for Genesis v2.2 11/99

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  doxc_type  [in genesis/src/device/spike_struct.h]

    Size:           116 bytes

    Fields:         num_bins        (int) number of bins in histogram
                    binwidth        (float) binwidth in sec
                    reset_mode      (int) 0 or 1
                    threshold       (float) input amplitude triggering spike event
                    *xcarray        (int)   histogram array containing data
                    no1spks         (int) number of spikes from source 1
                    no2spks         (int) number of spikes from source 2
                    *sp1times       (float) array of spike times from source 1
                    *sp2times       (float) array of spike times from source 2
                    curr1idx        (int) internal indexing
                    curr2idx        (int) internal indexing
                    calc1idx        (int) internal indexing
                    calc2idx        (int) internal indexing
                    maxspikes       (int) internal boundary condition
                    wintime         (float) internal boundary condition
                    dontnow         (int) internal condition
                    allocated       (int) internal condition

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Doxc  [in genesis/src/device/acxc.c]
    Classes:        device

    Actions:        PROCESS         update *spktimes, *xcarray, nospks
                    RESET           if reset_mode = 0, empties *spktimes but not
                                            *xcarray
                                    if reset_mode = 1, empties *spktimes and
                                            recreates *xcarray

    Messages:       XSPIKE : signal amplitude from source 1
                    YSPIKE : signal amplitdue from source 2

    ------------------------------------------------------------------------------

    Notes:
                    User must setfield num_bins (only even number of bins
            are allowed) and binwidth (in sec) so that a data array
            is created on RESET. The input is assumed to cross the amplitude
            given in the threshold field only for one timestep to generate
            a spike. Vm is not to be used as an input field. Valid inputs
            may be derived from random, neutral or spike objects.
                    An internal spike time buffer is set up for a maximal
            spike rate of 1000 events / second. A greater density of spikes
            will lead to missing events in the histogram.
                    The cross-corrlation table is updated with each timestep.
            However, the first results will only be available after the
            simulation time has reached the value of num_bins * binwidth.
                    The data are stored in *xcarray and can be accessed with
            a getfield command (see example). The 0 delay time bin is stored in
            the center of the histogram, i.e. for num_bins = 100, xcarray[49]
            contains the 0 delay time bin.

    Example:

    create autocorr /xc12
    setfield ^ binwidth 0.002 num_bins 200 threshold 0.5

    /* this example uses random object for input */
    create random /input1
    setfield ^ min_amp 1 max_amp 1 rate {in1_rate} reset 1 reset_value 0
    create random /input2
    setfield ^ min_amp 1 max_amp 1 rate {in1_rate} reset 1 reset_value 0

    addmsg /input1 /xc12 XSPIKE state
    addmsg /input2 /xc12 YSPIKE state

    /* To display data on a graph, use this function after creating the graph */
    function plotxc(source, dest, color)
        str source, dest, color
        int bins, minbin, maxbin, barval

        /*  display *xcarray of doxc element {source} on graph {dest}
             The display could be made nicer than this.  */

        bins = getfield {source}, num_bins
        minbin = -({bins} / 2)
        maxbin = {bins} / 2
        setfield {dest} xmin {minbin} xmax {maxbin}
        call {dest} RESET
        for(i=minbin; i < maxbin; i = i + 1)
             barval = {getfield {source}, xcarray[{{i}+{maxbin}}]}
             addpts {dest} -plotname xcor -color {color} {i} 0
             addpts {dest} -plotname xcor -color {color} {i} {barval}
             addpts {dest} -plotname xcor -color {color} {i} 0
        end
    end

    ------------------------------------------------------------------------------

    Notes:
            User must setfield num_bins and binwidth (in sec) so
        that a data array is created on RESET. The input is assumed to
        cross the amplitude given in the threshold field only for one
        timestep to generate a spike. Vm is not to be used as an input field.
        Valid inputs may be derived from random, neutral or spike objects.
            An internal spike time buffer is set up for a maximal
        spike rate of 1000 events / second. A greater density of spikes
        will lead missed events in the histogram.
            The cross-corrlation histogram ought to be used with clock 0.
        The first results will only be available after the
        simulation time has reached the value of num_bins * binwidth.
        This is due to the fact that any spike needs to be correlated
        with other spikes across a time window of this duration.
            The data are stored in *xcarray and can be accessed with
        a getfield command (see example).

See also: autocorr , interspike , peristim , Scripts/examples/spike/spikes.g

## 26.14 ddsyn

    Object Type:    ddsyn

    Description:    modified synchan with table front end to transform voltage
                    to activation, for dendro-dendritic synapses.  Calculates
                    channel current therefore needs membrane state.

    Author:         U. S. Bhalla, Caltech (5/91)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  dd_syn_type  [in src/olf/olf_struct.h]

    Size:           164 bytes

    Fields:         Gk              channel conductance
                    Ik              channel current
                    Ek              channel reversal potential
                    gmax            maximum conductance
                    tau1            open time constant of channel activation
                    tau2            close time constant of channel activation
                    transf          table for transform from Vm to activation;
                                    usual interpolation element with the normal
                                    set of fields; set up using TABCREATE, filled
                                    by indexing as usual, and interpolated using
                                    TABFILL
                    activation      channel activation; set either by a table
                                    lookup of the transform of the incoming
                                    VOLTAGE message or by synaptic input
                    transf_alloced  flag for allocation of transform
                    X               state variable for time response
                    Y               state variable for time response

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       DDSyn  [in src/olf/dd_syn.c]

    Classes:        segment, channel

    Actions:        INIT
                    PROCESS
                    RESET
                    CHECK
                    SET
                    DUMP
                    SAVE2
                    RESTORE2
                    TABCREATE
                    TABFILL

    Messages:       VOLTAGE voltage                 [tells channel what membrane
                                                    potential is]

                    ACTIVATION activation           [sends activation directly to
                                                    channel; sums linearly with
                                                    other ACTIVATION input and
                                                    transformed V_PRESYN input]

                    V_PRESYN presynaptic-voltage    [sends presynaptic voltage to
                                                    transform table; sums linearly
                                                    at output of table, so
                                                    multiple V_PRESYN inputs are
                                                    first transformed, then their
                                                    activations are summed]

                    RAND_ACTIVATION                 [rather than sending direct
                      probability  amplitude        activation signal, specifies
                                                    probability (from 0 to 1) that
                                                    activation of size amplitude
                                                    will occur at synapse (useful
                                                    for sending random synaptic
                                                    input to synapse)]

    ------------------------------------------------------------------------------

    Notes:          Dendrodendritic synapse with tabulated transform
                    from presyn potential to postsyn activation.
                    The table for the transform is created using tabcreate
                    and is shared with all copies of the element

                    The ddsyn element is the equivalent of a synchan element
                    with a tabulated transform from input voltage to channel
                    activation. This serves as a way of representing
                    dendro-dendritic synapses.  The usual fields and messages for
                    the synchan element remain available. The table entries are
                    filled in the usual ways from the script interface, and can be
                    shared between ddsyn elements.

    Example:        Here we create a ddsyn channel to act as the synaptic input
                    for granule cells in an olfactory bulb model.

                        // for dd, ax, and centrif inputs
                        create      ddsyn   glu_gran_usb
                        call glu_gran_usb TABCREATE 10 -0.070   0.05
                        setfield  glu_gran_usb \
                            Ek          {EGlu} \
                            tau1        4.0e-3 \   // sec
                            tau2        6.0e-3 \   // sec
                            gmax        {GGlu} \   // Siemens
                        // Setting up the table for transforming
                        // from presyn Vm to activation
                            transf->table[0] 0 \
                            transf->table[1] 0.05 \
                            transf->table[2] 0.1 \
                            transf->table[3] 0.2 \
                            transf->table[4] 0.5 \
                            transf->table[5] 0.7 \
                            transf->table[6] 0.8 \
                            transf->table[7] 0.9 \
                            transf->table[8] 0.95 \
                            transf->table[9] 0.98 \
                            transf->table[10] 1
                        call glu_gran_usb TABFILL 1000 0

    See also:  Scripts/examples/ddsyn

## 26.15 dif2buffer

    Object Type:    dif2buffer

    Description:    Implementation of a first-order diffusible (mobile) buffer
                    with variable total buffer concentration.  Should be coupled
                    to a difshell, where the change in the concentration of the
                    buffered ion is computed.

    Author:         E. De Schutter BBF-UIA 8/94 - 4/96

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  dif2buffer_type [in src/concen/conc_struct.h]

    Size:           172 bytes

    Fields:         activation     ion concentration from incoming CONCEN message
                    Bfree          free buffer concentration (calculated) in mM
                    Bbound         bound buffer concentration (calculated) in mM
                    prev_free      Bfree at previous time step
                    prev_bound     Bbound at previous time step
                    Btot           total buffer concentration in mM (used on reset)
                    kBf            forward rate constant in 1/(mM*sec)
                    kBb            backward rate constant in 1/sec
                    Dfree          diffusion constant for Bfree in m^2/sec
                    Dbound         diffusion constant for Bbound in m^2/sec
                    shape_mode     Set to one of the predefined global
                                   variables SHELL=0, SLICE=SLAB=1, USERDEF=3.

                        SHELL: onion shell, for radial diffusion. Set len for
                        cylindrical shell (zero length for spherical shell), dia
                        (outer diameter of shell) and thick (thickness of shell);
                        vol, surf_up, and surf_down are computed on RESET.

                        SLICE (or SLAB): salami slices of cylinder, for axial
                        diffusion. Set dia (diameter of cylinder) and thick
                        (thickness of slab), len is not used; vol, surf_up, and
                        surf_down are computed on RESET.

                        USERDEF: len, dia, thick are not used. Set vol, surf_up
                        and surf_down.

                    len             shell length
                    dia             shell diameter
                    thick           shell thickness
                    vol             shell volume
                    surf_up         area of upper (outer) shell surface
                    surf_down       area of lower (inner) shell surface

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Dif2Buffer [in src/concen/dif2buffer.c]

    Classes:        concbuffer segment

    Actions:        RESTORE2  SAVE2  CHECK  RECALC  RESET  PROCESS  INIT

    Messages:       CONCEN  C                  (buffered ion concentration, sent
                                               from a difshell or concpool)
                    BDIFF_DOWN prev_free prev_bound thick (diffusion to inner shell,
                                               sent from an outer shell)
                    BDIFF_UP prev_free prev_bound thick   (diffusion to outer shell,
                                               sent from an inner shell)

    ------------------------------------------------------------------------------

    Notes:

    The buffers (e.g, fixbuffer) interact with a difshell to model the binding of
    calcium to buffer molecules and to calculate the concentrations of free and
    bound buffer molecules, using a kinetic scheme with forward and backward rate
    constants for the binding and release of calcium.  Intracellular buffers are
    often mobile, and the diffusion of buffer molecules can carry calcium with
    them.  This can often make a significant contribution to the transport of
    calcium, in addition to the diffusion of free Ca++ ions that is modeled by the
    difshell object.  These diffusible buffers can be modeled with the difbuffer
    and dif2buffer objects, instead of using the non-mobile fixbuffer.

    Like the fixbuffer, the dif2buffer interacts with a difshell to model the
    binding of calcium to buffer molecules and to calculate the concentrations of
    free and bound buffer molecules using a kinetic scheme with forward and
    backward rate constants for the binding and release of calcium.  The rate
    constants kBf and kBb are set by the user, and the concentration C is sent
    with a CONCEN message from the difshell.  The BUFFER message to a difshell
    from a buffer passes on the rate constants and the calculated free and bound
    buffer concentrations.

    In addition, the dif2buffer acts like a difshell, in the sense that it allows
    diffusion between adjacent buffer shells.  However, it is the free and bound
    buffer molecules, rather than free ions that are diffusing.  Adjacent buffer
    shells are coupled by BDIFF_DOWN and BDIFF_UP messages that are analogous to
    the DIFF_DOWN and DIFF_UP messages that link adjacent difshells.  Note that a
    dif2buffer should have the same dimensions and shape_mode as the difshell to
    which it is coupled.

    For the difbuffer, the assumption is made that the diffusion rate for bound
    and free buffer molecules is the same (as they are much larger than the Ca
    atoms), so there is a single diffusion constant D, and they diffuse together,
    with dBbound/dt = -dBfree/dt.  The dif2buffer does not make this assumption,
    and treats the diffusion of free and bound molecules separately.  Thus, there
    are separate diffusion constants Dfree and Dbound, and the BDIFF_DOWN and
    BDIFF_UP messages pass both the previous step Bfree and Bbound values along
    with the buffer shell thickness.

    NOTE: When using difshell, difbuffer, or dif2buffer elements without hsolve
    (or in chanmodes 0 or 1), it will be necessary to issue two reset commands
    after setting up the simulation.

    For a general description of buffered calcium diffusion see:
    De Schutter E., and Smolen P., "Calcium dynamics in large neuronal
    models", in Methods in neuronal modeling: From ions to networks
    (2nd edition), C. Koch and I. Segev editors, pp. 211-250 (1998).

    Example:

See also: difshell , difbuffer , fixbuffer

## 26.16 difbuffer

    Object Type:    difbuffer

    Description:    Implementation of a first-order diffusible (mobile) buffer
                    with constant total buffer concentration.  Should be coupled
                    to a difshell, where the change in the concentration of the
                    buffered ion is computed.

    Author:         E. De Schutter BBF-UIA 8/94 - 6/96

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  difbuffer_type [in src/concen/conc_struct.h]

    Size:           168 bytes

    Fields:         activation     ion concentration from incoming CONCEN message
                    Bfree          free buffer concentration (calculated) in mM
                    Bbound         bound buffer concentration (calculated) in mM
                    prev_free      Bfree at previous time step
                    prev_bound     Bbound at previous time step
                    Btot           total buffer concentration in mM (free + bound)
                    kBf            forward rate constant in 1/(mM*sec)
                    kBb            backward rate constant in 1/sec
                    D              diffusion constant of buffer molecules, m^2/sec
                    shape_mode     Set to one of the predefined global
                                   variables SHELL=0, SLICE=SLAB=1, USERDEF=3.

                        SHELL: onion shell, for radial diffusion. Set len for
                        cylindrical shell (zero length for spherical shell), dia
                        (outer diameter of shell) and thick (thickness of shell);
                        vol, surf_up, and surf_down are computed on RESET.

                        SLICE (or SLAB): salami slices of cylinder, for axial
                        diffusion. Set dia (diameter of cylinder) and thick
                        (thickness of slab), len is not used; vol, surf_up, and
                        surf_down are computed on RESET.

                        USERDEF: len, dia, thick are not used. Set vol, surf_up
                        and surf_down.

                    len             shell length
                    dia             shell diameter
                    thick           shell thickness
                    vol             shell volume
                    surf_up         area of upper (outer) shell surface
                    surf_down       area of lower (inner) shell surface

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       DifBuffer [in src/concen/difbuffer.c]

    Classes:        concbuffer segment

    Actions:        RESTORE2  SAVE2  CHECK  RECALC  RESET  PROCESS  INIT

    Messages:       CONCEN  C                  (buffered ion concentration, sent
                                               from a difshell or concpool)
                    BDIFF_DOWN prev_free thick (diffusion to inner shell, sent from
                                               an outer shell)
                    BDIFF_UP prev_free thick   (diffusion to outer shell, sent from
                                               an inner shell)
                    DIFF_DOWN prev_free thick  (alias for BDIFF_DOWN)
                    DIFF_UP prev_free thick    (alias for BDIFF_UP)
    ------------------------------------------------------------------------------

    Notes:

    The buffers (e.g, fixbuffer) interact with a difshell to model the binding of
    calcium to buffer molecules and to calculate the concentrations of free and
    bound buffer molecules, using a kinetic scheme with forward and backward rate
    constants for the binding and release of calcium.  Intracellular buffers are
    often mobile, and the diffusion of buffer molecules can carry calcium with
    them.  This can often make a significant contribution to the transport of
    calcium, in addition to the diffusion of free Ca++ ions that is modeled by the
    difshell object.  These diffusible buffers can be modeled with the difbuffer
    and dif2buffer objects, instead of using the non-mobile fixbuffer.

    Like the fixbuffer, the difbuffer interacts with a difshell to model the
    binding of calcium to buffer molecules and to calculate the concentrations of
    free and bound buffer molecules using a kinetic scheme with forward and
    backward rate constants for the binding and release of calcium.  The rate
    constants kBf and kBb are set by the user, and the concentration C is sent
    with a CONCEN message from the difshell.  The BUFFER message to a difshell
    from a buffer passes on the rate constants and the calculated free and bound
    buffer concentrations.

    In addition, the difbuffer acts like a difshell, in the sense that it allows
    diffusion between adjacent buffer shells.  However, it is the free and bound
    buffer molecules, rather than free ions that are diffusing.  Adjacent buffer
    shells are coupled by BDIFF_DOWN and BDIFF_UP messages that are analogous to
    the DIFF_DOWN and DIFF_UP messages that link adjacent difshells.  Note that a
    difbuffer should have the same dimensions and shape_mode as the difshell to
    which it is coupled.

    For the difbuffer, the assumption is made that the diffusion rate for bound
    and free buffer molecules is the same (as they are much larger than the Ca
    atoms), so there is a single diffusion constant D, and they diffuse together,
    with dBbound/dt = -dBfree/dt.  The dif2buffer does not make this assumption,
    and treats the diffusion of free and bound molecules separately.

    NOTE: When using difshell, difbuffer, or dif2buffer elements without hsolve
    (or in chanmodes 0 or 1), it will be necessary to issue two reset commands
    after setting up the simulation.

    For a general description of buffered calcium diffusion see:
    De Schutter E., and Smolen P., "Calcium dynamics in large neuronal
    models", in Methods in neuronal modeling: From ions to networks
    (2nd edition), C. Koch and I. Segev editors, pp. 211-250 (1998).

    Example:

See also: difshell , fixbuffer , dif2buffer

## 26.17 diffamp

    Object Type:    diffamp

    Description:    Difference amplifier, takes two inputs and produces an
                    output proportional to their difference.

    Author:         M. Wilson, Caltech (2/89)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  diffamp_type  [in src/device/dev_struct.h]

    Size:           96 bytes

    Fields:         gain
                    saturation
                    plus
                    minus
                    output

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       DifferenceAmp  [in src/device/diffamp.c]

    Classes:        device

    Actions:        RESET           sets the output to zero
                    PROCESS         calculates and sets the output from the inputs

    Messages:       PLUS +input
                    MINUS -input
                    GAIN gain

    ------------------------------------------------------------------------------

    Notes:

    Adds inputs from PLUS messages and subtracts those received with MINUS
    messages.  The output is this total, multiplied by gain, but limited to the
    range -saturation to +saturatation.  If there are no MINUS messages, the
    minus input is taken as zero.  Normally, the gain field is set using
    "setfield", but it may also be varied with a GAIN message.  This object also
    provides a convenient way to sum or scale quantities which are to be plotted
    by sending a PLOT message to an xgraph.

    Example:

    See also:

## 26.18 difshell

    Object Type:    difshell

    Description:    Implementation of a concentration shell that can have
                    miscellaneous in/out flows (when coupled to other objects),
                    and one-dimensional diffusion between other difshells.

    Author:         E. De Schutter BBF-UIA 4/94 - 3/99

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  difshell_type [in src/concen/conc_struct.h]

    Size:           152 bytes

    Fields:         C               concentration (calculated by difshell) in mM
                    prev_C          concentration at previous time step
                    Ceq             equilibrium concentration in mM
                    D               diffusion constant in m^2/sec
                    val             ionic valence
                    leak            constant in/outflow in mM/sec
                    shape_mode      Set to one of the predefined global
                                    variables SHELL=0, SLICE=SLAB=1, USERDEF=3.

                        SHELL: onion shell, for radial diffusion. Set len for
                        cylindrical shell (zero length for spherical shell), dia
                        (outer diameter of shell) and thick (thickness of shell);
                        vol, surf_up, and surf_down are computed on RESET.

                        SLICE (or SLAB): salami slices of cylinder, for axial
                        diffusion. Set dia (diameter of cylinder) and thick
                        (thickness of slab), len is not used; vol, surf_up, and
                        surf_down are computed on RESET.

                        USERDEF: len, dia, thick are not used. Set vol, surf_up
                        and surf_down.

                    len             shell length
                    dia             shell diameter
                    thick           shell thickness
                    vol             shell volume
                    surf_up         area of upper (outer) shell surface
                    surf_down       area of lower (inner) shell surface

    ------------------------------------------------------------------------------
    SIMULATION PARAMETERS

    Function:       DifShell [in src/concen/difshell.c]

    Classes:        concentration segment

    Actions:        RESTORE2  SAVE2  CHECK  RECALC  RESET  PROCESS  INIT

    Messages:       INFLUX      I_Ca          (current flow in A; increases C)
                    OUTFLUX     I_Ca          (current flow in A; decreases C)
                    FINFLUX     I_Ca fraction (current flow, scaled by fraction)
                    FOUTFLUX    I_Ca fraction (current flow, scaled by fraction)
                    STOREINFLUX flux          (flux into store in moles/sec;
                                              increases C)
                    STOREOUTFLUX flux         (flux out of store in moles/sec;
                                              decreases C)
                    DIFF_DOWN   prev_C thick  (diffusion to inner shell, sent from
                                               an outer shell)
                    DIFF_UP     prev_C thick  (diffusion to outer shell, sent from
                                               an inner shell)
                    BUFFER      kBf kBb Bfree Bbound    (fields sent from a buffer,
                                                        e.g. a fixbuffer)
                    TAUPUMP     kP Ceq        (sent from a taupump)
                    EQTAUPUMP   kP            (sent from a taupump; uses Ceq from
                                              the difshell)
                    MMPUMP      vmax Km       (sent from a mmpump)
                    HILLPUMP    vmax Kd Hill  (sent from a hillpump)

    ------------------------------------------------------------------------------

    Notes:

    The concentration of intracellular calcium close to the cell membrane surface
    can have a significant influence on the conductance of calcium dependent
    potassium channels and on mechanisms for synaptic plasticity.  Unless the
    neural compartment is very small and the calcium is "well-mixed", the calcium
    concentration may vary considerably within the compartment.  It may then be
    necessary to model diffusion within the compartment by dividing it into a
    number of shells.  The difshell object is used for modeling these shells and
    diffusion between them.  It may also be used for modeling axial diffusion
    between compartments.  Just as the length of a neural compartment should be
    chosen to give small differences in membrane potential between adjacent
    compartments, the thickness of diffusion shells should be chosen to give small
    differences in concentration between adjacent shells.

    A difshell is typically coupled to buffers and/or pumps, in order to provide
    for multiple mechanisms for calcium removal.

    The buffers (e.g, fixbuffer) interact with a difshell or concpool to model the
    binding of calcium to buffer molecules and to calculate the concentrations of
    free and bound ions using a kinetic scheme with forward and backward rate
    constants for the binding and release of calcium.  The BUFFER message from a
    buffer passes on the rate constants and the calculated free and bound
    concentrations so that the difshell may calculate the resulting ion
    concentration C in the shell.

    The ionic pumps provide various mechanisms to remove ions from the shell.
    Details of the fields that are passed to the difshell with messages from
    the pumps are provided in the documentation for the various pump objects.

    The various FLUX messages assume SI units for the Faraday constant, currents
    and dimensions.  If other units are used, scale the val parameter to account
    for this.

    NOTE: When using difshell, difbuffer, or dif2buffer elements without hsolve
    (or in chanmodes 0 or 1), it will be necessary to issue two reset commands
    after setting up the simulation.

    For a general description of buffered calcium diffusion see:
    De Schutter E., and Smolen P., "Calcium dynamics in large neuronal
    models", in Methods in neuronal modeling: From ions to networks
    (2nd edition), C. Koch and I. Segev editors, pp. 211-250 (1998).  The
    spinedemo simulation gives a detailed example of the use of the difshell,
    taupump, and fixbuffer objects for modeling calcium diffusion in dendritic
    spines.

    Example:

      /* based on spinedemo, for spine head initial shell (headshell0) */

      create difshell headshell0
      setfield headshell0 C 0.000020 Ceq 0.000020 D 6.0e-10 val 2.0  leak 0.0
      setfield headshell0 shape_mode {SLAB} len 0.0 dia 0.5e-6 thick 0.1e-6

      /* Ca fraction of NMDA current is influx into outer shell */
      addmsg Mg_block headshell0 FINFLUX  Ik 0.128

      /* attach fast immobile buffer */  headbuf0
      create fixbuffer headbuf0
      setfield headbuf0 Btot 0.2 kBf 5.0e5 kBb 500 // mM, 1/(mM*sec), 1/sec
      addmsg headbuf0 headshell0 BUFFER kBf kBb Bfree Bbound
      addmsg headshell0 headbuf0 CONCEN C

      /* attach the pump */
      create taupump headpump0
      setfield headpump0 Ceq 0.000020
      /* The pump rate is proportional to the surface-to-volume ratio
         spine head initial shell is end of cylinder, so stv=1/thick */
      setfield headpump0 T_C {thick/Pump_kP} // pump rate Pump_kP = 1.4e-5
      addmsg headpump0 headshell0 TAUPUMP kP Ceq

      /* set up diffusion messages, assuming the existence of headshell1 */
      addmsg headshell0 headshell1 DIFF_DOWN prev_C  thick
      addmsg headshell1 headshell0 DIFF_UP   prev_C thick

      // similar statements for the other shells ...

See also: taupump , fixbuffer , Scripts/examples/spinedemo

## 26.19 disk_in

    Object Type:    disk_in

    Description:    Reads in a 2-d array of data from an ascii or binary file.

    Author:         U. S. Bhalla, Caltech (1/90)
                    Coordinate read-in added by U. S. Bhalla, Mt. Sinai, 5/95.

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  disk_in_type  [in src/olf/olf_struct.h]

    Size:           148 bytes + allocation for arrays and interpols

    Fields:         filename        name of data file
                    leave_open      flag: leave file open between steps [cycles]
                    nx              x dimension of input val array
                    ny              y dimension of input val array
                    loop            flag: return to start of file on EOF
                    val             2D array of input values
                    fp              pointer to file
                    fileformat      flag: 0 (default) for ASCII, 1 for FMT1
                    time_offset     offset from sim time for FMT1 files
                    is_open         internal flag : is file open yet?
                    allocated       internal flag: Is array allocated yet?
                    tempdata        data array used for FMT1 reading
                    start_time      field used for FMT1 handling
                    dt              field used for FMT1 handling
                    datatype        field used for FMT1 handling
                    header_size     field used for FMT1 handling
                    lastpos         field used for FMT1 handling
                    xpts,ypts,zpts  Interpols used for storing coordinate
                                    information when FMT1 files are read.

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       DiskIn  [in src/olf/disk_in.c]

    Classes:        segment

    Actions:
            RECALC  CHECK  SET  RESET  PROCESS  INIT

    Messages:
            none
    ------------------------------------------------------------------------------

    Notes:
                    The disk_in element reads in data from a file to the val
                    array in the element every clock tick.  This is a 2-d array
                    with dimensions set by the nx and ny fields.

                    The source file can be either in ASCII or FMT1 formats.  FMT1
                    is the GENESIS-specific format used by disk_out.  Data in
                    FMT1 files is time-stamped, and accessed according to the
                    current simulation clock.

                    At RESET, disk_in automatically figures out if the file
                    is FMT1. If not it assumes it is ASCII. The fileformat
                    flag is set accordingly.

                    FMT1 files contain information on the number of data items,
                    and the 3-d coordinate information for each item. On RESET,
                    the 'val' array is automatically allocated for the data values.
                    nx is set to 1, and ny is set to the number of data items.
                    Also on RESET, the coordinate information is loaded into the
                    xpts,ypts,zpts interpol-structs, which are automatically
                    allocated as needed. These interpols can be accessed in
                    the usual ways. See the interpol documentation.

                    ASCII files do not have coordinate information. The nx and ny
                    fields must be set prior to reading in an ASCII file, so
                    that the disk_in can figure out how many data points to
                    read per time-step. Changing nx and ny causes
                    automatic reallocation of the 'val' array, with dire
                    results for any messages that had been linked to earlier
                    incarnations of the val array.  In other words, never set
                    the nx or ny unless you are sure that no messages
                    are being sent from the input array. Typically one sets
                    nx and ny as soon as one creates the disk_in, and
                    later adds messages.

                    The leave_open flag should normally be set to 1 to avoid
                    closing and reopening the file every clock tick.

                    The time_offset field allows one to specify the difference
                    between the simulation time and the FMT1 internal time stamp.

                    The format of the ascii file is simply a sequence of numbers,
                    separated by spaces, tabs or newlines, with a maximum of 16
                    numbers per line.  They are read in sequentially to fill the
                    val[x][y] array, the x index being incremented more rapidly .
                    Every time a new clock tick is read in, the reading starts
                    from a new line, discarding any unread data on the previous
                    line.

                    The format of the FMT1 file is highly condensed. See the
                    source (in src/out/out_view.c) and the documentation for
                    disk_out for more details. In general, it includes information
                    on the size of the file, the coordinates of all elements
                    whose values are stored, and the time-step at which successive
                    data values are stored.

    Example:

        create disk_in /in
        // read a single line with 2 variables at each time step
        // from the file Vm1 (in Scripts/MultiCell)
        setfield  /in nx 2 ny 1 filename Vm1 dt 1 leave_open 1
        create xform /form
        create xgraph /form/graph
        setfield /form/graph xmax 500 ymin -100 ymax 50
        // The Vm value is the second one on each line
        addmsg /in /form/graph PLOT val[1][0] *Vm *red
        xshow /form
        reset
        step 500
    Alternatively, the message from the disk_in element could have been an INPUT
    message to a spikegen element.  The spikegen element could then send a SPIKE
    message to a synchan element, as in Scripts/tutorials/tutorial4.g.

    If we had 100 cells, each containing a spikegen element, with names
    ``cell[0]/spike'' through ``cell[99]/spike'' and a data file containing
    multiple groups of 10 lines with 10 Vm values each, to represent 100
    simultaneous inputs, we could use statements like this:

        // send a message for each spike generator
        for (i=0;i<=9; i = i + 1)
            for (j=0;j<=9; j = j + 1)
                 addmsg /in /cell[{j + 10*i}]/spike INPUT val[{i}][{j}]
            end
         end

    Normally, you will want to use a clock with a much larger step for reading
    in the data than that used for the integration of the equations for
    calculating membrane potentials, etc.  Otherwise, the data file would have
    to be very large.  The example in Scripts/examples/XODUS/fileview also
    illustrates the use of arrays and the binary format.

See also: asc_file , disk_out

## 26.20 disk_out

    Object Type:    disk_out

    Description:

    The disk_out object is used to write data to a file in a special binary
    format.  This is done at every time step of the clock which is assigned.
    These files are usually used with a disk_in object and the xview widget or
    the xgraph widget to "replay" the results of a simulation.  An external
    program (or your own compiled GENESIS function) can write files in this
    format in order to provide a convenient interface to the display
    capabilities of XODUS.

    Author:         M. Wilson, Caltech (6/88)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  file_type  [in src/out/out_struct.h]

    Size:           88 bytes

    Fields:         filename        data file name to be written
                    fp              data file pointer
                    is_open         flag: is file currently open?
                    initialize      flag: has file been initialized?
                    leave_open      flag: leave file open? 1 leaves the file open
                                    all the time so you can write on it whenever
                                    you want (a good idea if the file is used
                                    frequently, but there is a limit to number of
                                    files which can be left open any any time);
                                    0 closes the file after every write to it
                                    (only useful if you have more than 30 files;
                                    this is slow)
                    append          flag: append data after resetting?
                    flush           flag: flush data to disk at each interval?
                                    1 forces program to send data to the disk at
                                    once and not store it in a buffer (slow but
                                    secure); 0 (default) writes data in a buffer
                                    (fast)

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       FileOutput  [in src/out/out_file.c]

    Classes:        output

    Actions:
            SAVE  DELETE  PROCESS  RESET

    Messages:       SAVE data

    ------------------------------------------------------------------------------

    Notes:

    If the filename field is not set, the output file will be given the same
    name as the element which is created from the disk_out object.  Use asc_file
    for writing the data in ASCII format.

    Example:

    (from Scripts/orient_tut/V1_output.g)

    function do_disk_out(diskpath,srcpath,field)
      str name
      create disk_out /output/{diskpath}
      setfield /output/{diskpath} leave_open 1  flush 1
      addmsg {srcpath} /output/{diskpath} SAVE {field}
    end

    do_disk_out vert_disk /lgn/vert/soma[] Vm
    do_disk_out horiz_disk /lgn/horiz/soma[] Vm

    Also see the example in Scripts/examples/XODUS/fileview/generate.g.

    Normally, you need not be concerned with the format of the files produced
    by a disk_out element.  However, you may wish to write either a GENESIS
    function or an external program which produces an output file which can
    be displayed with an xview widget.  The code which writes a disk_out
    file can be found in /usr/genesis/src/out/out_file.c, and the code which
    reads the data from the file can be found in /usr/genesis/src/out/out_view.c.

    The following two C programs describe this format and show how to write and
    read these data files.

    ------------------------------------------------------------------------------

    /* diskwrt.c - a demo program to write a sample file "test_disk" in the
    GENESIS "disk_out" format, to be viewed with the xfileview widget.  */

    #include <stdio.h>
    #include <math.h>

    main()
    {
    FILE *fpr;
    int width = 5;
    int height = 5;
    float start = 0.0;
    float dt = 1.0;
    float x, y, data;
    int ntimes;

    fpr = fopen("test_disk", "w");
    headerwrt(start, dt, width, height, fpr);

    data = 0.0;     /* make some bogus data */
    for (ntimes = 0; ntimes < 20; ntimes++)
        for (y = 0.0; y < height; y++) {
            for (x = 0.0; x < width; x++) {
                data = x*x + y*y + height*ntimes;
                fwrite (&data, sizeof (float),1, fpr);
            }
    }
    fclose(fpr);
    } /* end main */

    headerwrt(start, deltat, width, height, fp)
    /* Header for files compatible with GENESIS disk_out
    "FMT1" - 80 byte null terminated character string as identifying label
    start - starting time - float
    dt - time step - float
    ndata - number of data points per time step - int
    datatype - int code for data type - disk_out uses only FLOAT = 4, but
            display routines can use DOUBLE = 5, INT = 3, SHORT = 2.
    x1,y1,z1,x2,y2,z2,....,xndata,yndata,zndata - x,y,z coordinates for icon
            representing each data point - float
    The header is then followed by data -  ndata values for each time step,
            with the data type specified by "datatype".
    */

    float start, deltat;
    int   width, height;
    FILE *fp;
    {
    char label[80];
    float strt, dt;
    int ndata, datatype;
    float x, y, z;
    float dx = 2.0;         /* horiz spacing between icons */
    float dy = 2.0;         /* vert spacing between icons */
    int i, j;

        strt = start;       /* use local variables so addresses are correct */
        dt = deltat;        /* otherwise fwrite gets wrong start and deltat  */

        strcpy(label,"FMT1");
        fwrite (label, sizeof (char),80, fp);
        fwrite (&strt, sizeof (float),1, fp);
        fwrite (&dt, sizeof (float),1, fp);
        ndata = width*height;
        fwrite (&ndata, sizeof (int),1, fp);
        datatype = 4;       /* use float data */
        fwrite (&datatype, sizeof (int),1, fp);
        z = 0.0;            /* 2-D display */
        for (j=0, y = 0.0; j < height; j++) {
            for (i=0, x = 0.0; i < width; i++) {
                fwrite (&x, sizeof (float),1, fp);
                fwrite (&y, sizeof (float),1, fp);
                fwrite (&z, sizeof (float),1, fp);
                x = x + dx;
            }
            y = y + dy;
        }
    }
    ------------------------------------------------------------------------------

    /* diskrd.c - Reads and displays the header information of files produced by
    the GENESIS disk_out widget */

    #include <stdio.h>

    main(argc,argv)
    int     argc;
    char    **argv;
    {
    char    label[100];
    float   fval;
    int     i;
    int ndata;
    int datatype;
    FILE    *fp;

        if(argc < 2){
            printf("usage: %s filename\n",argv[0]);
            exit();
        }
        if((fp = fopen(argv[1],"r")) == NULL){
            printf("unable to find file '%s'\n",argv[1]);
            exit();
        }
        /*    read in the file header    */
        fread(label,sizeof(char),80,fp);
        /*    check the label    */
        if(strncmp("FMT1",label,4) != 0){
            printf("file '%s' is not a valid FMT1 data file\n",argv[1]);
            fclose(fp);
            exit();
        }

        /*    starting time    */
        fread (&fval, sizeof (float),1,fp);
        printf("%-20s = %e\n","start time",fval);
        /*   time step    */
        fread (&fval, sizeof (float),1,fp);
        printf("%-20s = %e\n","time step",fval);
        /*    number of data points    */
        fread (&ndata, sizeof (int),1,fp);
        printf("%-20s = %d\n","ndata points",ndata);
        /** data type    */
        fread (&datatype, sizeof (int),1,fp);
        printf("%-20s = %d\n","data type",datatype);
        fclose(fp);
    }

    ----------------------------------------------------------------------------

See also: disk_in , asc_file

## 26.21 diskio

    Object Type:    diskio

    Description:

    The diskio object can be used to open/create a binary format file on disk
    (specified with -fileformat option) that can be then used to read/write
    data or metadata from/to it with child objects, 'variable' or 'metadata'
    respectively in this same library.  Unlike disk_out/disk_in, the reading
    and writing actions are combined into this one new object.

    For purposes of backwards compatibility (BC), diskio responds to the
    set of messages that disk_out and disk_in respond to at a minimum, and
    allows the user to read/write files directly from/to the disk at every
    time-step of the clock which is assigned. It also allows the "replay" of
    the results of a simulation through the xview and xgraph widgets in XODUS
    by message passing as well as the "xsimplot" command added in genesis 2.2.

    As of GENESIS 2.2, diskio supports files in the FMT1 and Netcdf formats.
    Netcdf is a portable, network transparent, public domain binary format.
    Netcdf interfaces to various popular analysis/signal-processing tools
    including MATLAB are available in the public domain. Specifically,

            * MEXCDF
                    WEB: http://crusty.er.usgs.gov/mexcdf.html
                    FTP: crusty.er.usgs.gov (128.128.19.19) or contact
                             Rich Signell at rsignell@crusty.er.usgs.gov.

            * MexEPS
                    WEB: http://www.pmel.noaa.gov/epic/mexeps.html
                    FTP: ftp.pmel.noaa.gov/epic/mexeps/

            * fanmat
                    WEB: http://www.unidata.ucar.edu/packages/netcdf/contrib.html
                    FTP: ftp.unidata.ucar.edu/pub/netcdf/contrib/fanmat.taz

    are freely available packages that allow MATLAB to read/write/visualize
    netcdf data.

    The implementation of the diskio library and the diskio, metadata, and
    variable objects makes use of netcdf, which is Copyright
    1993-1997 by University Corporation for Atmospheric Research/Unidata.  the
    netcdf library is provided as per the terms of the UCAR/Unidata license,
    described in the copyright notice found in the src/diskio/interface/netcdf
    directory tree.

    Author:         V.Jagadish, Caltech (9/96)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure: Gen_Diskio_Type  [in src/diskio/diskio_struct.h]

    Size:           172 bytes + allocation for arrays and interpols

    Fields:         accessmode      Mode with which the file is accessed
                                    - 'r', 'w' or 'a' (Read/Write/Append)

                                    - Read-only field specifiable on the
                                      command line using the -accessmode option
                                      but cannot be set/unset subsequently
                                      using setfield

                                    - Defaults to 'r' (Read mode) as this is the
                                      most non-destructive
                                    - Append 'a' mode is not supported currently

                                    - BC NOTE: Due to the default mode being
                                      readonly 'r', it is not sufficient to
                                      merely replace creation-lines of disk_out
                                      with diskio but to add the option
                                      "-accessmode w" as well.  cf. See Examples.

                    filename        Data file name to read from or write into
                                    - Defaults to name of object if not specified
                                    - Can be set/unset as required : The old file
                                      will have data and metadata written into it
                                      till that point in time, if the accessmode
                                      was 'w' (write).

                    fileformat      Format of the data file
                                    - Unlike disk_out it is a character string
                                      field but allows numerical setting for BC.
                                      ("1" => FMT1, "2" => netcdf)
                                    - Defaults to FMT1 if not specified
                                    - Subsequent setting/unsetting of this
                                      field is allowed only to preserve BC with
                                      disk_out/disk_in. This is effectively a
                                      NOP as far as the physical file is
                                      concerned. Only the the value of the
                                      field changes to reflect the setting and
                                      is not recommended.

                    append          Flag: 1 => data should be appended to file
                                    after RESET. This has certain implications
                                    from the point of view of interpreting the
                                    'variable' object value[], input and output
                                    fields.  If the append flag is on, there
                                    could be more than 1 value associated with
                                    a single time instance. The output field
                                    will always reflect the first value for the
                                    time instant set for the input field. All
                                    values however can be retrieved from the
                                    value[] field and the size field of the
                                    variable will show the total number of
                                    values stored. The user needs to keep track
                                    of when the reset was done and the time
                                    step rate (dt) to interpret the values
                                    stored in the value[] field.

                    is_open         Read-only flag: is file currently open?

                    is_writable     Read-only flag: is file writable?

                    val             2D array of input values

                    nx              x dimension of input val array

                    ny              y dimension of input val array

                    xpts,ypts,zpts  Interpols used for storing coordinate
                                    information when the binary file is read

                    flush           Same functionality as in disk_out

                    leave_open      Same functionality as in disk_out

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Gen_Diskio  [in src/diskio/gen_diskio.c]

    Classes:        output

    Actions:        CREATE PROCESS SET ADDMSGIN DELETEMSGIN SHOW

                    RESET:
                            It is essential that the RESET action be called
                            on the diskio object for allocating and filling the
                            "xpts ypts zpts" interpol arrays before using
                            them to render/replay data graphically on the
                            xview objects.
                            cf. Example: Scripts/examples/diskiolib/diskio
                                                            /replayview.g

                    QUIT:
                    FLUSH:
                    UPDATE: when called on the diskio object, allows the user
                            to commit any changes done interactively
                            or in the process of running a simulation or script,
                            to the file on disk. This allows another diskio
                            object to simultaneously access updated data from the
                            same file.

                    DELETE: also commits changes but with the usual effect of
                            deleting the object and all its children. Please note
                            that this action does not delete the physical file on
                            disk.

                    GENERAL NOTE:   The process of committing changes to disk is
                                    time-consuming for netcdf files. This is
                                    inherent in the implementation of the
                                    netcdf library. So please expect high
                                    latency after you quit or do a delete or
                                    call one of the above 4 actions on the
                                    diskio object, when supporting the netcdf
                                    fileformat. In general, the netcdf library
                                    provides its portability across
                                    architectures at the cost of efficiency in
                                    speed. Therefore, performance-wise one will
                                    notice diskio is slower than
                                    disk_out/disk_in, in this situation. The
                                    same is however not true for FMT1 file
                                    support.

    Messages:       SAVE data

                    IMPORTANT BACKWARDS COMPATIBILITY (BC) NOTES:
                    ---------------------------------------------

                    As previously mentioned, diskio responds to the same set of
            messages that disk_out and disk_in respond to as a minimum, for
            purposes of BC.

            Since the actual data is encapsulated within the variable object
            and the design eventually envisages the exclusive use of this child
            object to manipulate data, any incoming SAVE messages to the diskio
            object (thro the addmsg command) will result in the automatic
            creation of child variables and the forwarding of the message to
            them. So the data will be stored and manipulated via these child
            variables, while letting the user transparently deal only with the
            diskio object as was done previously with disk_out/disk_in.

            For every SAVE message there will be a specially named child
            variable object - 'autoSAVE_diskio[i]', where i is the index of
            the element and that corresponds to the number of the message.
            The indices will be reused if any messages are deleted and added
            later.

            Also, for every SAVE message, the 3-D position coords of the source
            element needs to be stored for possible future replay via graphical
            objects like xview. This is done through the automatic creation of
            specially named indexed metadata children -
            'auto3-DPosSAVE_diskio[i]'.

            So in applications where diskio is intended to be used as a
            replacement for disk_out/disk_in, these variables & metadata will
            be automatically created in the hierarchy for every SAVE message to
            the object. Directly manipulating these child objects should be
            avoided, since it would essentially change the contents of the
            file, if committed.

            Example:
                    * Run Scripts/examples/diskiolib/diskio/generate.g
                    * genesis> le /diskio

    ------------------------------------------------------------------------------

    Notes:

    As a departure from the disk_out/disk_in objects, this object internally
    just serves to interface (open/create/close) with a binary file on disk.

    The actual data in the file can be more flexibly managed using the child
    'variable' objects in this library.  For purposes of backwards
    compatibility, however, the diskio object will respond to the same messages
    as the disk_out and disk_in objects at a minimum to actively write/read
    data to/from the file during a simulation run.

    Some binary file formats notably netcdf (which this library supports) allow
    descripive data (metadata) to be stored in them along with the actual data.
    Child 'metadata' objects in this library allow the user to manipulate the
    metadata content in these files.

    Use asc_file for writing data in ASCII format.

    Examples:

    0. create diskio /dout -filename testfile.nc -fileformat netcdf -accessmode w

            // Not specifiying a fileformat while creating a file defaults to FMT1
    1. create diskio /dout_FMT1 -filename testfile.fmt1 -accessmode w

    2. call /dout UPDATE

    3. delete /dout

    4. Also, please see Scripts/examples/diskiolib/diskio/
                                            - generate.g
                                            - generate_netcdf.g
                                            - replayview.g
                                            - replaygraph.g
                                            - simplot.g
    ______________________________________________________________________________

See also: variable , metadata , disk_out , disk_in , asc_file

## 26.22 efield

    Object Type:    efield

    Description:    An extracellular field potential recording electrode that uses
                    current sources and their distance from the electrode site to
                    calculate the field.

    Author:         M. Wilson, Caltech (2/89)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  efield_type  [in src/device/dev_struct.h]

    Size:           64 bytes

    Fields:         scale
                    field
                    x
                    y
                    z

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       ExtracellularRecordingElectrode  [in src/device/efield.c]

    Classes:        device

    Actions:        PROCESS
                    RESET
                    RECALC

    Messages:       CURRENT current 0.0

    ------------------------------------------------------------------------------

    Notes:          If one assumes that the medium surrounding neurons is
                    of homogeneous resistivity and has no capacitance,
                    then the field potential generated by a compartmental
                    model can be calculated from the following equation:

                                              Im
                                  1      n      i
                            F = ------  SUM  -----  (see Nunez, 1981)
                                4*pi*s  i=1    R
                                                i

                    where F is the field potential in volts, s is
                    conductivity in 1/(Ohms*m), Im_i is the transmembrane
                    current (Amperes) accoss the ith  neural compartment,
                    and R_i is the distance from the ith neural
                    compartment to the recording electrode (i.e. the
                    efield object).

                    This equation is most accurate in the case of elongated
                    neurons oriented with the axis perpendicular to the scalp, as
                    is the case with cortical pyramidal cells.  It is probably not
                    very good for a small cell.  See the documentation of
                    compartment and symcompartment for details of the calculation
                    of the compartment Im.

                    In the case of the efield object, the term 1/(4*pi*s)
                    is replaced by the scale field, otherwise the same
                    equation is used to calculate field potentials.
                    The RECALC action must be called in order for efield
                    to calculate the distances to neural compartments.

                    For more information about field potentials and how
                    they are used in GENESIS simulations, see Chapter 9 in
                    The Book of GENESIS.  For a derivation of the above
                    equation, see:

                    Nunez, P.L. (1981) Electric Fields of the Brain: The
                    Neurophysics of EEG, Oxford University Press, Oxford.

    Example:        create efield electrode
                    setfield electrode scale -1e3 x 0.00 y 0.00 x 0.00
                    addmsg some_compartment electrode CURRENT Im 0.0
                    call electrode RECALC

See also: Scripts/piriform/field.g, compartment , symcompartment

## 26.23 enz

    Object Type:    enz

    Description:    Enzyme activity for a pre-existing pool. An enz does two
                    things: it handles the reactions in the Michaelis-Menten (MM)
                    scheme below, and it also acts as a pool to represent the
                    enzyme-substrate complex. It can only be
                    created on a pool, it is not an independent object.

                    The MM scheme is modeled as:
                                            k1              k3
                    Substrate + Enzyme  <-----> EnzComplex ----> Enz + Prd
                                            k2

                    The enz is really a utility object, as it replaces
                    two reacs and a pool, but does not add anything extra.

    Author:         U. S. Bhalla, National Centre for Biological Sciences,
                    Bangalore, India. (1993).

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  enz_type  [in src/kinetics/kin_struct.h]

    Size:           bytes

    Fields:         CoComplex               Concentration of enz-substrate complex.
                                            CoComplex = nComplex/vol
                    CoComplexInit           Initial concentration of enz-substrate
                                            complex.
                                            CoComplex gets set to this value on
                                            RESET.
                    nComplex                Number of molecules of complex.
                    nComplexInit            Initial number of molecules of complex.
                                            'nComplex'gets set to this value on
                                            RESET.
                    vol                     Volume occupied by enzyme. Often
                                            involves scale factor so as to have
                                            direct conversion from 'n' to some
                                            sensible units of Co, such as
                                            micromolar.
                    sA                      A state variable to pass to substrate
                                            in messages.
                    pA                      A state variable to pass to products
                                            in messages.
                    eA                      A state variable to pass to parent
                                            enzyme pool in messages.
                    B                       B state variable to pass to substrate
                                            and parent enzyme pool in messages
                    k1,k2,k3                Michaelis-Menten parameters.

                    keepconc                Flag determining whether to change
                                            concs or n when volume changes
                    usecomplex              Flag. Determines whether the enzyme
                                            complex is used when the parent enzyme
                                            is involved in other reactions.
                                            Consider:

                                            E + A <----> E.A

                                            where E is a pool reacting with A.
                                            Suppose E has an enzyme site. Then,
                                            whenever some of the enzyme is complexed
                                            with a substrate, the conc of E
                                            decreases unless 'usecomplex' is true.
                    ksum                    Internal variable. ksum = k2 + k3.

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       EnzFunc  [in src/kinetics/enz.c]

    Classes:        segment

    Actions:        PROCESS
                    RESET
                    SET

    Messages:       ENZYME          n       [n is number of molecules of enzyme
                                            pool to which this site is attached]
                    SUBSTRATE       n       [Number of molecules of substrate]
                    VOL             vol     [volume of enzyme pool]
                    INTRAMOL        n       [Total number of molecules in an
                                            intramolecular reaction]

    ------------------------------------------------------------------------------

    Notes: See pool documentation for example of use.

    ------------------------------------------------------------------------------

## 26.24 event_tofile

    Object Type:    event_tofile

    Description:    A gizmo that collects an INPUT message. When value
                    in message exceeds threshold, current simulation
                    time is written to asci file.

                    Designed to allow ascii output from a range of
                    objects, like channelC3, synchan, timetable.

    Author:         D. Jaeger, Caltech (3/95)

    ---------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  event_tofile_type [in genesis/src/device/spike_struct.h]

    Size:           64 bytes

    Fields:         fname           File name of asci output
                    fp              file pointer
                    open            flag
                    threshold       threshold above which time is written to file

    -----------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Event_tofileFunc  [in genesis/src/device/event_tofile.c]

    Classes:        device

    Actions:        PROCESS
                    SET
                    OPEN
                    CLOSE
                    FLUSH

    Messages:       INPUT compared against threshold

    -----------------------------------------------------------------------

    Notes:  An ascii file containing simulation times at which an event
            occurred is generated. The event arrives via an INPUT
            message, and is generated when the input value exceeds
            threshold. Only positive thresholds are implemented.

            Before activation the file needs to be opened with a reset or call
            OPEN statement.  The generic openfile, writefile, and closfile
            commands can NOT be used with the same file.

    Example:

    create synchan syn
    create event_tofile etf
    set etf fname test.asc
    sendmsg syn etf INPUT activation
    reset
    ... // run simulation
    call etf CLOSE

See also: openfile , writefile , closefile (for general asci file control), timetable , spikegen , randomspike (for good source elements to feed into event_tofile), Scripts/examples/spike/spikes.g.

## 26.25 facsynchan

    Object Type:  facsynchan

    Description:    Synaptically activated channel with synaptic facilitation
                    and/or synaptic depression.

    Author:         Mike Vanier

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  fac_synchan_type  [in src/newconn/newconn_struct.h]

    Size:           252 bytes

    Fields:         activation         driving force ("transmitter") for channel
                                       conductance
                    Ik                 channel current
                    Gk                 time varying channel conductance
                    Ek                 reversal potential of channel
                    tau1               first time constant of channel activation
                    tau2               second time constant of channel activation
                    gmax               peak channel conductance (but see Notes below)
                    nsynapses          number of incoming spike messages
                                       (readonly)
                    event_buffer_size  size of event buffer (readonly)
                    pending_events     number of pending spike events in event
                                       buffer (readonly)
                    nodes_per_synapse  number of event nodes to allocate per
                                       synapse (default 1)
                    synapse            synapse buffer
                    fac_depr_on        flag: no fac/depr if 0
                    max_fac            upper limit on facilitation
                    fac_per_spike      synaptic facilitation per spike
                    fac_tau            time constant of synaptic facilitation
                    depr_per_spike     synaptic depression per spike
                    depr_tau           time constant of synaptic depression

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       FacSynchan  [in src/newconn/facsynchan.c]

    Classes:        segment channel synchannel

    Actions:        CREATE          Set default values and initialize object.
                    PROCESS         Update Gk, calculate Ik, update facilitation/
                                    depression state of synaptic weights.
                    RESET           Assign activation = 0, Gk = 0; calculate
                                    time-step-dependent coefficients; remove
                                    all pending SPIKE events; reset facilitation/
                                    depression state of synaptic weights.
                    RECALC          Recalculate time-step-dependent coefficients.
                    CHECK           Make sure tau1>0, tau2>0, gmax>0; make sure a
                                    VOLTAGE message is present (in order to
                                    calculate Ik); make sure facilitation/
                                    depression parameters are reasonable.
                    SAVE2           Called by the save command.
                    RESTORE2        Called by the restore command
                    EVENT           Put a spike event into the event buffer.
                    ADDMSGIN        Add a new message.
                    DELETEMSGIN     Delete a message.
                    MSGINDELETED    Do cleanup after message is deleted.
                    RESETBUFFER     Reset size of event buffer to
                                    (nodes_per_synapse * nsynapses) nodes.
                    DELETE          Delete the element.
                    COPY            Copies the element.

    Messages:       VOLTAGE         Vm
                    SPIKE

    ------------------------------------------------------------------------------

    Notes:          The `facsynchan' object is a version of the synchan object
                    that can exhibit synaptic facilitation, synaptic depression,
                    or some combination of the two.

                    1) General information about synchans.

                    The `facsynchan' object, like all synchan objects, simulates a
                    time dependent synaptically activated ionic channel.  A
                    variable channel conductance `Gk' is activated by the
                    application of transmitter. This conductance then changes with
                    damped second-order characteristics with a time course given
                    by two time constants `tau1' and `tau2'.  This gives rise to
                    an alpha function/dual exponential conductance waveform for an
                    impulse spike input.  The channel also calculates channel
                    current (`Ik') and therefore needs the membrane state (`Vm').

                    Each SPIKE message to a synchan establishes a synaptic
                    connection and increments `nsynapses'.  The synapses are
                    numbered starting with 0, and each contains a field for a
                    synaptic weight and a propagation delay.  For example, the
                    weight of the first synaptic connection is held in the field
                    `synapse[0].weight' while the delay is `synapse[0].delay'.
                    `Gk' reaches a value (`gmax' * `weight') for a single event
                    delivered with a SPIKE message.  Note that even though
                    synapses are not elements, they do have fields that can be
                    accessed individually.  They can be thought of as
                    "sub-elements" or substructures of the element.  Note also
                    that `gmax' is not the absolute maximum conductance of the
                    synapse; it is just the maximum conductance given a single
                    synaptic connection with a weight of 1.0 only.  Multiple
                    synapses onto a particular synchan, weights higher than 1.0,
                    and/or synaptic facilitation can all give rise to total
                    conductances that are greater than `gmax'.

                    Any number of spike events can be pending per synapse.  The
                    `facsynchan' object stores all spike events in a buffer until
                    they are scheduled to occur.  If enough events come in to
                    overload the buffer, the buffer will dynamically expand to
                    enable storage of all events.  The size of the buffer in
                    events is stored in the `event_buffer_size' field which is
                    readonly.  The number of actual spikes in the buffer which
                    have not yet hit the channel are stored in the
                    `pending_events' field (also readonly).  The
                    `nodes_per_synapse' field controls how many large the event
                    buffer is initially.  The default is to have one node per
                    synapse, but if you expect a lot of events or very few events
                    you can change this number to be greater or less than the
                    default (1), respectively.  This will speed up the simulation
                    slightly in the first case and save memory in the second.  If
                    you leave this field alone the object will still work fine.
                    The "resetsynchanbuffers" command will cause all the buffers
                    in all synchan and derived objects to be reset to a size of
                    `nodes_per_synapse' * `nsynapses' (which will also cause all
                    pending events to be flushed).

                    The "copy" command will fail for any synchan type which is
                    receiving SPIKE messages.  The correct way to set up
                    simulations is to set up prototype cells which do not receive
                    any SPIKE messages on their synchans, copy these cells, and
                    then add the appropriate SPIKE messages (by hand or by using
                    planarconnect or volumeconnect).  We may eventually build a
                    more intelligent copy command which will permit copying of
                    synchans with SPIKE messages, but for now, don't do it.

                    2) Specific information about implementing synaptic
                       facilitation and depression.

                    Each synapse, in addition to its `weight' and `delay' fields,
                    has two other fields called `fac' and `depr' which represent
                    the current level of synaptic facilitation and depression,
                    respectively.  Each time a spike hits, the facilitation and
                    depression values are incremented by a fixed amount
                    (`fac_per_spike' and `depr_per_spike', respectively) which can
                    be zero but not negative.  The facilitation and depression
                    values decay away with a time constant equal to `fac_tau' and
                    `depr_tau', respectively.  The effective synaptic weight when
                    a spike hits is calculated from these equations:

                        wt_multiplier = max((1 + fac) / (1 + depr), max_fac)
                        wt_effective  = wt * wt_multiplier

                    Thus, a `fac' value of 1.0 and a `depr' value of 0.0 will give
                    rise to a wt_multiplier value of 2.0 (assuming that `max_fac'
                    > 2.0), so the effective weight at that point in time will be
                    twice the listed synaptic weight.  The `max_fac' field allows
                    you to limit the amount that a particular synaptic weight can
                    grow; however, there is no limit to how low a weight can
                    shrink due to depression.  If `max_fac' is negative, there is
                    no maximum facilitation level.  This is the default (`max_fac'
                    = -1, to be precise).

                    You can switch facilitation/depression off by setting
                    `fac_dep_on' to 0.  The default is 1 (facilitation on).

    Example:        Scripts/examples/facsynchan/facdemo.g

    Bugs:           The SAVE2/RESTORE2 actions have not been tested and may
                    contain bugs.  Please report any bugs you find.

    Caveats:        The facsynchan object is not supported by the cell reader
                    (readcell), so if it is to be used in a model described
                    by a cell parameter (.p) file, you will need to use it in
                    a prototype compartment that is included with the readcell
                    "*compt" option.

See also: synchan , resetsynchanbuffers , Connections , NewSynapticObjects , readcell

## 26.26 fixbuffer

    Object Type:    fixbuffer

    Description:    Implementation of a first-order fixed (non-mobile) buffer.
                    Should be coupled to a difshell or concpool, where the change
                    in the concentration of the buffered ion is computed.

    Author:         E. De Schutter BBF-UIA 8/94 - 9/95

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  fixbuffer_type [in src/concen/conc_struct.h]

    Size:           124 bytes

    Fields:         activation     ion concentration from incoming CONCEN message
                    Bfree          free buffer concentration (calculated) in mM
                    Bbound         bound buffer concentration (calculated) in mM
                    prev_free      Bfree at previous time step
                    prev_bound     Bbound at previous time step
                    Btot           total buffer concentration in mM (free + bound)
                    kBf            forward rate constant in 1/(mM*sec)
                    kBb            backward rate constant in 1/sec

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       FixBuffer [in src/concen/fixbuffer.c]

    Classes:        concbuffer segment

    Actions:        RESTORE2  SAVE2  CHECK  RESET  PROCESS  INIT

    Messages:       CONCEN  C   (buffered ion concentration, sent from a
                                difshell or concpool)

    ------------------------------------------------------------------------------

    Notes:

    The fixbuffer interacts with a difshell or concpool to model the binding of
    calcium to buffer molecules and to calculate the concentrations of free and
    bound buffer molecules using a kinetic scheme with forward and backward rate
    constants for the binding and release of calcium:

        dBfree/dt = kBb*Bbound - kBf*Bfree*C
        Bbound = Btot - Bfree, where Btot == constant

    The rate constants kBf and kBb are set by the user, and the concentration C is
    sent with a CONCEN message from the difshell or concpool.  The BUFFER message
    to a difshell or concpool from a buffer passes on the rate constants and the
    calculated free and bound buffer concentrations.

    For a general description of buffered calcium diffusion see:  De Schutter E.,
    and Smolen P., "Calcium dynamics in large neuronal models", in Methods in
    neuronal modeling: From ions to networks (2nd edition), C. Koch and I. Segev
    editors, pp. 211-250 (1998).  The spinedemo simulation gives a detailed
    example of the use of the difshell, taupump, and fixbuffer objects for
    modeling calcium diffusion in dendritic spines.

    Example:        create fixbuffer headbuf0
                    setfield headbuf0 Btot 0.2 \ // Total buffer conc in mM
                                      kBf 5.0e5 \// Forward binding rate 1/(mM*sec)
                                      kBb 500    // Backward rate, 1/sec
                    addmsg headbuf0 headshell0 BUFFER kBf kBb Bfree Bbound
                    addmsg headshell0 headbuf0 CONCEN C

See also: difshell , taupump , Scripts/examples/spinedemo

## 26.27 freq_monitor

    Object Type:    freq_monitor

    Description:    Calculates running event (spike) frequency over a given time
                    window using exponential weighting.

    Author:         M. Wilson, Caltech (2/89), modified by D. Jaeger

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  freq_mon_type  [in src/device/dev_struct.h]

    Size:           84 bytes

    Fields:         tmin            minimum time interval which must be held by
                                      the buffer
                    size            buffer size, in number of events
                    current         current buffer location
                    start           starting buffer location - 1
                    end             last occupied buffer location
                    event_size      size of each event data structure
                    event           circular event buffer
                    exponent        power by which to weight
                    frequency       curent calculated value of the frequency
                                    (set to zero on reset)

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       FrequencyMonitor  [in src/device/new_frequency.c]

    Classes:        device

    Actions:        PROCESS  RESET  CREATE

    Messages:       NONZERO_TRIG    input   trigger on nonzero input
                    ZERO_TRIG       input   trigger only when input is zero
                    POSITIVE_TRIG   input   trigger on positive input
                    NEGATIVE_TRIG   input   trigger on negtive input
                    WINDOW          tmin    sets the window size tmin
                    CONTINUOUS      input   triggers every time

    ------------------------------------------------------------------------------

    Notes:          This is a frequency measuring device which computes the
                    running event frequency over a time interval using exponential
                    weighting.  The field "tmin" should be set in order to specify
                    the interval or "window" for averaging.  Larger values give a
                    smoother result.  If "exponent" is unequal to the default
                    value of zero, inputs are weighted by exp(exponent*time).  The
                    frequency field may be examined or sent to a graph.

                    The first four messages are used to give it an input, and the
                    counting of input events is triggered by one of the four
                    conditions.  The most common way to use the frequency monitor
                    is to set the "tmin" field to an appropriate timing window,
                    send it a POSITIVE_TRIG message with the state of a spiking
                    element, and send a "PLOT frequency" message from the monitor
                    to a graph.

    Example:        See the demonstration script Scripts/examples/spike/freqmon.g.

    See also:

## 26.28 funcgen

    Object Type:    funcgen

    Description:

    This is a function generator which produces periodic output with a waveform
    set by the mode field.

    Author:         M. Wilson, Caltech (4/89)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  funcgen_type  [in src/device/dev_struct.h]

    Size:           96 bytes

    Fields:         mode            flag: 0=sine; 1=square; 2=triangle; 3=constant
                    amplitude       peak-to-peak amplitude
                    dc_offset       constant to be added to output
                    phase           phase in degrees
                    frequency       frequency
                    output          output waveform

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       FunctionGenerator  [in src/device/funcgen.c]

    Classes:        device

    Actions:        CHECK  PROCESS  RESET

    Messages:       AMPLITUDE amplitude
                    DC_OFFSET dc_offset
                    PHASE phase
                    FREQUENCY frequency

    ------------------------------------------------------------------------------

    Notes:

    In a simulation, you would set up messages between the funcgen element
    (in our example it is called "funky") and other elements which are to
    receive its output.  For example:

      addmsg funky funcplot PLOT output *function *red  // funcplot is an xgraph
      addmsg funky Exc_channel ACTIVATION output  // Exc_channel is a synchan

    Example:        Scripts/examples/sigmoid

    See also:

## 26.29 fura2

    Object Type:    fura2

    Description:    Computes fura2 fluorescence in a single difshell.

    Author:         E. De Schutter BBF-UIA 1/95

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  fura2_type [in src/concen/conc_struct.h]

    Size:           104 bytes

    Fields:         F340            F340 fluorescence
                    F380            F380 fluorescence
                    ratio           F340/F380

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       FuraRatio [in src/concen/fura2.c]

    Classes:        concentration  segment

    Actions:        RESET  PROCESS

    Messages:       CONCEN  Bfree Bbound vol    (from all fura2 difbuffers)

    ------------------------------------------------------------------------------

    Notes:          Computes the fluorescence signal of the fura-2 calcium
                    indicator dye by adding together information from a series of
                    difbuffers (representing the fura2 in shells).

                    In order to use the fura2 object, create difbuffers to model
                    the diffusion of the fura-2 dye and Ca buffering for each
                    difshell that is associated with a compartment.  The Btot, D,
                    kBf, and kBb fields for the difbuffers should be set to values
                    that are typical of the ionic environment of the dye.  The
                    difbuffers are linked to their difshells with the usual
                    messages.

                    Then send "CONCEN Bfree Bbound vol" messages to a single fura2
                    element from each difbuffer that corresponds to the
                    compartment for which you wish to calculate the fura-2
                    fluorescence signal.

                    For a general description of buffered calcium diffusion see:
                    De Schutter E., and Smolen P., "Calcium dynamics in large
                    neuronal models", in Methods in neuronal modeling: From ions
                    to networks (2nd edition), C. Koch and I. Segev editors, pp.
                    211-250 (1998).  Details of the GENESIS implementation of the
                    fura2 object are given in Sec. 6.6.4.  Also see Blumenfeld et.
                    al., Biophys. J. 63: 1146-1164 (1992) for additional
                    discussion of fura-2 parameters.

    Example:

See also: difshell , difbuffer

## 26.30 ghk

    Object Type:    ghk

    Description:    Calculates the Goldman-Hodgkin-Katz (constant field) equation
                    for a single ionic species.  Provides current as well as
                    reversal potential and slope conductance.

    Author:         Subba Shankar 8/25/91, modified by EDS 9/93-10/96

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  ghk_type [in src/segment/seg_struct.h]

    Size:           136 bytes

    Fields:         Ik              channel current (calculated)
                    Gk              channel conductance (calculated)
                    Ek              channel reversal potential (calculated)
                    T               temperature (degrees Celcius)
                    p               permeability
                    Vm              membrane potential
                    Cin             concentration inside the compartment in mM
                    Cout            concentration outside the cell in mM
                    valency         charge on ion

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Ghk [in src/segment/ghk.c]

    Classes:        device channel

    Actions:        CHECK  PROCESS  RESET

    Messages:       Cin             concentration
                    Cout            concentration
                    VOLTAGE         Vm
                    PERMEABILITY    p

    ------------------------------------------------------------------------------

    Notes:

    The general equation used is:

                                Cin * exp(K * Vm) - Cout
       Ik    =  -p * F * K * Vm  ------------------------
                                   exp(K * Vm) - 1

                valency * F
      where K = -------------
                R * (T + 273)

      F = Faraday's constant (9.6487e4 coul/mol)

      R = universal gas constant (8.314 volts*coul/(deg K * mol))

    Unlike the tabchannel or tab2Dchannel, it is not assumed that the current
    obeys Ohm's law and is proportional to the membrane potential Vm.  However, a
    compartment (or symcompartment) will expect a channel element to provide Gk
    and the reversal potential Ek in a "CHANNEL Gk Ek" message, and use these to
    calculate the incoming ionic current from Ik = Gk*(Ek - Vm).   In order for
    a ghk element to be used like a channel, suitable values of Gk and Ek must
    be provided.  This may be done by making the assumption that over a single time
    step, Gk and Ek vary slowly compared to Vm.  Then the approximation can be
    made that dIk/dVm = - Gk, and that Ek = (Ik + Gk*Vm)/Gk.  Thus, Ek is
    calculated by the ghk element, rather than being set by the user or by
    an incoming message.  Note that the sign of the current expresses the GENESIS
    convention that current flow into a compartment is positive.

    One way to use this object would be to let a voltage or ligand gated channel
    element determine the permeability of the channel as a function of time,
    voltage, concentration of ligand, etc., and then send that permeability to a
    ghk element (as a message) to determine the net current through the channel.
    The resulting Gk and Ek could be sent to the compartment that contains the
    channel.  If you are keeping track of the concentration of your ion with a
    concentration type element, you could send it the Ik field of the ghk element.
    You could then get Cin or Cout messages from the concentration element into
    the ghk element.

    In the example below, the conductance Gk is sent to the ghk element in
    a PERMEABILITY message.  Although the permeability p and conductance Gk
    have differnet units, the scaling has been taken into account in the ghk
    object, as long as SI (MKS) units are used.

    A full explanation of the constant field equation can be found in:

      1) From Neuron to Brain, Kuffler, et al., Sinauer Assoc.
           2nd edition, (1984) p. 123, 130.
      2) Electric Current Flow in Excitable Cells, Jack, et al.,
           Oxford Press, (1983) p. 237.
      3) Ionic Channels of Ecitable Membranes, Hille, Sinauer Assoc.
           2nd edition, (1992) pp 345-347.

    Example:    create ghk soma/Ca_ghk
                setfield soma/Ca_ghk Cin {CCaI} Cout {CCaO} valency 2.0 T {Temp}
                addmsg soma soma/Ca_ghk VOLTAGE Vm
                addmsg soma/Ca_ghk soma CHANNEL Gk Ek

                addmsg soma soma/CaT VOLTAGE Vm
                setfield soma/CaT Gbar {GCaTs*surf}
                addmsg soma/CaT soma/Ca_ghk PERMEABILITY Gk

                addmsg soma soma/CaP VOLTAGE Vm
                setfield soma/CaP Gbar {GCaPs*surf}
                addmsg soma/CaP soma/Ca_ghk PERMEABILITY Gk

See also: tabcurrent , setupghk , setupNaCa

## 26.31 hebbsynchan

    Object Type:    hebbsynchan

    Description:    Synaptically activated channel with a simple mechanism for
                    hebbian weight changes as a function of pre- and postsynaptic
                    activities.

    Author:         Mike Vanier 9/95; revised 4/96

    --------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  HebbSynchan_type  [in src/newconn/newconn_struct.h]

    Size:           296 bytes

    Fields:         activation         driving force (transmitter) for channel
                                       conductance
                    Ik                 channel current
                    Gk                 time varying channel conductance
                    Ek                 reversal potential of channel
                    tau1               first time constant of channel activation
                    tau2               second time constant of channel activation
                    gmax               peak channel conductance
                    frequency          random activation frequency (default = 0)
                    nsynapses          number of incoming spike messages (read only)
                    event_buffer_size  size of event buffer (read only)
                    pending_events     number of pending spike events in event
                                       buffer (read only)
                    nodes_per_synapse  number of event nodes to allocate per
                                       synapse (default = 1)
                    synapse            synapse buffer
                    pre_tau1           rise time constant for presynaptic averaging
                    pre_tau2           decay time constant for presynaptic averaging
                    pre_thresh_lo      lower presynaptic threshold
                    pre_thresh_hi      upper presynaptic threshold
                    avg_Vm             averaged membrane potential (read only)
                    post_tau           time constant for postsynaptic averaging
                    post_thresh_lo     lower postsynaptic threshold
                    post_thresh_hi     upper postsynaptic threshold
                    post_scale         scaling factor for postsynaptic activities
                    weight_change_rate rate of weight change (roughly in units/sec)
                    min_weight         minimum weight
                    max_weight         maximum weight
                    change_weights     flag: nonzero means weights can be changed

    --------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       HebbSynchan  [in src/newconn/hebbsynchan.c]

    Classes:        segment channel synchannel

    Actions:        CREATE             set synapse_size hidden field
                    INIT               assign activation = 0
                    PROCESS            update Gk, calculate Ik; calculate hebbian
                                       presynaptic and postsynaptic activities
                    RESET              assign activation = 0, Gk = 0; calculate
                                       time-step-dependent coefficients
                    RECALC             recalculate time-step-dependent coefficients
                    CHECK              make sure tau1 > 0, tau2 > 0; make sure a
                                       VOLTAGE message is present (in order to
                                       calculate Ik); check hebbian fields, etc.
                    SAVE2              called by the save command
                    RESTORE2           called by the restore command
                    EVENT              put a spike event into the event buffer
                    ADDMSGIN
                    DELETEMSGIN
                    MSGINDELETED
                    RESETBUFFER        reset size of event buffer to
                                       (nodes_per_synapse * nsynapses) nodes
                    DELETE             delete the element
                    COPY               copies the element

    Messages:       VOLTAGE            Vm
                    ACTIVATION         activation
                    RAND_ACTIVATION    probability amplitude
                    MOD                modulation
                    WEIGHT_CHANGE_MOD  modulation
                    SPIKE

    ------------------------------------------------------------------------------

    Notes:          This object simulates a time-dependent synaptically
                    activated ionic channel.  A variable channel conductance Gk
                    is activated by the application of transmitter. This
                    conductance then changes with damped second-order
                    characteristics with a time course given by two time
                    constants tau1 and tau2.  This gives rise to an
                    alpha-function/dual-exponential conductance waveform for an
                    impulse spike input.  The channel also calculates channel
                    current Ik and therefore needs the membrane state (Vm).

                    Each SPIKE message to a synchan or hebbsynchan establishes a
                    synaptic connection and increments nsynapses.  The synapses
                    are numbered starting with 0, and each contains a field for a
                    synaptic weight and a propagation delay.  For example, the
                    weight of the first synaptic connection is held in the field
                    "synapse[0].weight".  Gk reaches a value gmax*weight for a
                    single event delivered with a SPIKE message.  Note that even
                    though synapses are not elements, they do have fields that can
                    be accessed individually.  They can be thought of as
                    "sub-elements" or substructures of the element.  The fields
                    the user should be concerned about in the synapse are "weight"
                    and "delay".

                    The above description is also true for the synchan object.
                    Hebbsynchans also have a "pre_activity" field, described
                    below.  Note that this field was named "pre_avg" in GENESIS
                    version 2.0.1.  The hebbsynchan object also updates the
                    synaptic weights of the synapses based on the presynaptic
                    "activities" (which are calculated separately for each
                    synapse) and the postsynaptic activity (which is the same for
                    all synapses which are part of a given hebbsynchan).  The
                    activities are artificial values which do not have a direct
                    relationship to any real biological entities; very loosely we
                    can think of the presynaptic activity as being the amount of
                    calcium current through an NMDA receptor while the
                    postsynaptic activity is derived from an average of the
                    postsynaptic membrane potential (which will affect NMDA
                    receptors in reality).  The pre- and postsynaptic activities
                    are used to update the weights in a roughly Hebbian manner
                    described below, which is similar but by no means identical to
                    the way NMDA-dependent LTP works.  For serious GENESIS
                    hackers, we have isolated the actual weight change algorithm
                    in a single function in "hebbsynchan.c" which can be altered
                    if you need a different algorithm.  If you want to calculate
                    pre- or postsynaptic activities differently you have to do a
                    lot more work.

                    The presynaptic activity is calculated by having each spike
                    generate a generalized alpha-function waveform with a
                    maximum size of 1 in the "pre_activity" field of the
                    synapse.  This is meant to be analogous to an NMDA channel
                    conductance so the rise and fall times should be slow; for
                    instance we might use pre_tau1 of 10 msec and pre_tau2 of
                    100 msec.  Note that this activity value doesn't mean that
                    there is a slow conductance being simulated here; it's just
                    used to determine a measure of presynaptic spiking
                    activity.  When weight updates occur, the presynaptic
                    activity relative to two thresholds (pre_thresh_lo and
                    pre_thresh_hi) are used to calculate the weight change (see
                    below).

                    Also at each time step, the membrane potential of the
                    compartment the hebbsynchan is connected to is used to
                    update the "avg_Vm" field.  This is done by running the Vm
                    of the compartment through a leaky integrator with a time
                    constant of post_tau.  When weight updates occur, the
                    postsynaptic activity relative to two thresholds
                    (post_thresh_lo and post_thresh_hi) are used to calculate
                    the weight change (see below).  Also, since presynaptic
                    activity values are dimensionless but avg_Vm has the
                    dimensions of volts, postsynaptic activities are internally
                    calculated by dividing the difference between avg_Vm and
                    the nearest threshold by "post_scale", which is also in
                    units of volts.  You can think of post_scale as the amount
                    that avg_Vm has to be above threshold to give a
                    postsynaptic activity of 1.0.

                    The 2-d space defined by the pre- and postsynaptic
                    activities are separated into 9 regions based on two
                    presynaptic and two postsynaptic thresholds (called
                    "pre_thresh_lo", "pre_thresh_hi", "post_thresh_lo", and
                    "post_thresh_hi").  The values of the thresholds are fixed
                    and are specified by the user.  The weight changes in each
                    of the nine regions are as follows:

                 ---------> Presynaptic activity ----->

                 low              medium              high

    Post-                 |                    |
    synaptic              |                    |
    activity:             |                    |
                 no       |     no change      |  decrease
    low        change     |                    |
     |                    |                    |
     |                    |                    |
     |       -------------------------------------------------- <--- post_thresh_lo
     |                    |                    |
     |                    |                    |
    \|/       no change   |     no change      |  no change
    medium                |                    |
     |                    |                    |
     |                    |                    |
     |                    |                    |
     |       -------------------------------------------------- <--- post_thresh_hi
     |                    |                    |
     |                    |                    |
    \|/       decrease    |     no change      |  increase
    high                  |                    |
                          |                    |
                          |                    |
                          |                    |

                         ^^^                  ^^^
                    pre_thresh_lo          pre_thresh_hi

                    The diagram shows what happens for various combinations of
                    pre- and postsynaptic activities.  Note that if
                    pre_thresh_lo = pre_thresh_hi and post_thresh_lo =
                    post_thresh_hi then there are only four regions and the
                    weights will always be changing unless both presynaptic and
                    postsynaptic activities are below the thresholds.  The
                    weight change algorithm used converts pre_activity into a
                    value which is the difference between the pre_activity of
                    the synapse and the nearest threshold value i.e.

                    real_pre_activity = pre_activity - pre_thresh_hi
                                      (if pre_activity > pre_thresh_hi), OR
                                      = pre_activity - pre_thresh_lo
                                      (if pre_activity < pre_thresh_lo;
                                       note that this gives a negative number), OR
                                      = 0 otherwise

                    Similarly, the weight change algorithm calculates a "real"
                    postsynaptic activity as follows:

                    real_post_activity = (avg_Vm - post_thresh_hi) / post_scale
                                       (if avg_Vm > post_thresh_hi), OR
                                       = (avg_Vm - post_thresh_lo) / post_scale
                                       (if post_activity < post_thresh_lo;
                                       note that this gives a negative number), OR
                                       = 0 otherwise

                    Note that the post_thresh values are both in units of
                    volts, like avg_Vm.

                    Once we have the "real" pre- and postsynaptic activities we
                    can update the weights.  Essentially the algorithm now is
                    just the Hebb algorithm:

                    weight_change = real_pre_activity * real_post_activity *
                                    weight_change_rate * dt;

                    where dt is the time step size in seconds.  The
                    weight_change_rate is a field in the object and has units
                    of (1/time).  Thus the overall weight change is
                    dimensionless, as is the weight itself.  If
                    (real_pre_activity * real_post_activity *
                    weight_change_rate) equalled 1.0, then the weight would
                    increase roughly at the rate of 1 unit per second.  One
                    neat feature of this scheme is that if weight_change_rate
                    is negative you get an anti-Hebbian synapse.

                    Unfortunately, there's more to it than this.  There are
                    also two fields called "min_weight" and "max_weight" which
                    keep the weights of synapses connected to the hebbsynchan
                    within specified limits.  We could in theory just truncate
                    the weights if the weight change algorithm tried to push it
                    beyond the limits, but in order to make it more smooth the
                    weight change calculated above is modified depending on how
                    close you are to min_weight or max_weight.  The effect of
                    this is that the weight change rate is reduced when you
                    approach either limit.

                    There is also a field called "change_weights".  If this is
                    set to zero, no weight changes will occur.  Otherwise,
                    weight updates will occur according to the above algorithm.
                    In addition, hebbsynchans can receive a WEIGHT_CHANGE_MOD
                    message (or multiple messages of this type) which will
                    modify the effective value of weight_change_rate based on
                    the message value.  In this case the effective
                    weight_change_rate is the product of the value in the field
                    of the object and the value in the message.  The field
                    value is not changed.  Thus you can have, say, a
                    sinusoidally varying weight change rate by setting
                    weight_change_rate to 1.0 and adding a WEIGHT_CHANGE_MOD
                    message from a sine wave generator (funcgen object) where
                    the sine wave varies from 0 to 2.0, say.

                    The "copy" command will fail for any synchan or hebbsynchan
                    which is receiving SPIKE messages.  The correct way to set
                    up simulations is to set up prototype cells which do not
                    receive any SPIKE messages on their synchans, copy these
                    cells, and then add the appropriate SPIKE messages (by hand
                    or by using planarconnect or volumeconnect).  We are
                    working on a more "intelligent" copy command which will
                    permit copying of synchans with SPIKE messages, but for
                    now, don't do it.

                    Default values of hebbian parameters (SI units are assumed
                    here):

                    pre_tau1             0.010     // seconds
                    pre_tau2             0.100     // seconds
                    pre_thresh_lo        3.0
                    pre_thresh_hi        3.0
                    post_thresh_lo      -0.065     // Volts
                    post_thresh_hi      -0.065     // Volts
                    post_scale           0.002     // Volts
                    weight_change_rate   1.0
                    min_weight           0.0
                    max_weight           100.0
                    change_weights       1

                    The RESET action does not restore the weights to the original
                    (unlearned) values.  If you wish to re-run a simulation
                    starting from the initial state, write a script function that
                    sets the weights to the original values and then performs a
                    reset.

    Example:        Scripts/examples/hebb/hebb.g

See also: synchan , resetsynchanbuffers , Connections , NewSynapticObjects

## 26.32 hh_channel

    Object Type:    hh_channel

    Description:    Implements the channel model described in A.L.Hodgkin and
                    A.F.Huxley, J.Physiol(Lond) 117, pp 500-544 (1952)

                    In the Hodgkin-Huxley model, the general form for the
                    channel conductance is represented as being proportional to
                    an activation state variable raised to an integer power
                    times an inactivation state variable raised to another
                    integer power.  The hh_channel object calculates the channel
                    conductance from the equation

                            Gk = Gbar*X^Xpower * Y^Ypower

                    In the usual Hodgkin-Huxley notation for the Na channel, X
                    corresponds to the activation variable, m, with Xpower = 3,
                    and Y corresponds to the inactivation variable, h, with
                    Ypower = 1.

                    Channel elements which are created from the hh_channel
                    object calculate both X and Y by solving differential
                    equations of the form

                            dX/dt = alpha*(1-X) - beta*X

                    The voltage-dependent rate variables, alpha and beta, can
                    each assume one of the three functional forms:

                    1 (EXPONENTIAL): alpha(v) = A exp((v-V0)/B)
                    2 (SIGMOID):     alpha(v) = A / (exp((v-V0)/B) + 1)
                    3 (LINOID):      alpha(v) = A (v-V0) / (exp((v-V0)/B) - 1)

                    The form to be used and the constants A, B and V0 are
                    specified for each rate variable by setting fields in the
                    hh_channel element.

    Author:         M. Nelson, Caltech (8/88)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  hh_channel_type  [in src/hh/hh_struct.h]

    Size:           184 bytes

    Fields:         activation      channel activation
                    Gk              channel conductance
                    Ik              channel current
                    Ek              channel reversal potential
                    Gbar            channel maximum conductance
                    X               value of X gate (m)
                    Y               value of Y gate (h)
                    Xpower          power to raise X gate to
                    Ypower          power to raise Y gate to
                    X_alpha_FORM    Equation form for X gate alpha rate constant
                                    1 = EXPONENTIAL, 2 = SIGMOID, 3 = LINOID
                    X_alpha_A       A constant for X gate alpha rate constant
                    X_alpha_B       B constant for X gate alpha rate constant
                    X_alpha_V0      V0 constant for X gate alpha rate constant
                    X_beta_FORM     Equation form for X gate beta rate constant
                                    1 = EXPONENTIAL, 2 = SIGMOID, 3 = LINOID
                    X_beta_A        A constant for X gate beta rate constant
                    X_beta_B        B constant for X gate beta rate constant
                    X_beta_V0       V0 constant for X gate beta rate constant
                    Y_alpha_FORM    Equation form for Y gate alpha rate constant
                                    1 = EXPONENTIAL, 2 = SIGMOID, 3 = LINOID
                    Y_alpha_A       A constant for Y gate alpha rate constant
                    Y_alpha_B       B constant for Y gate alpha rate constant
                    Y_alpha_V0      V0 constant for Y gate alpha rate constant
                    Y_beta_FORM     Equation form for Y gate beta rate constant
                                    1 = EXPONENTIAL, 2 = SIGMOID, 3 = LINOID
                    Y_beta_A        A constant for Y gate beta rate constant
                    Y_beta_B        B constant for Y gate beta rate constant
                    Y_beta_V0       V0 constant for Y gate beta rate constant

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       hh_channel  [in src/hh/channel.c]

    Classes:        segment channel

    Actions:        INIT
                    PROCESS
                    RESET
                    CHECK
                    CALC_ALPHA
                    CALC_BETA
                    CALC_MINF

    Messages:       VOLTAGE Vm

    ------------------------------------------------------------------------------

    Notes:          The tabchannel object provides a faster and more general way
                    to implement this type of channel.

                    The CALC_ALPHA, CALC_BETA, and CALC_MINF actions are used with
                    calls of the form

                            y = {call <element> CALC_ALPHA <gate> <x-value>}

                    in order to access values of alpha, beta or m_inf (the steady
                    state activation, alpha/(alpha + beta)) for the specified gate
                    (X or Y) and a particular value of the independent variable.
                    This feature is most often used for making plots of these
                    quantities.  Note that the activation time constant can be
                    calculated from tau = 1/(alpha + beta).

    Example:        Scripts/neurokit/prototypes/hhchan.g

See also: tabchannel , vdep_channel

## 26.33 hillpump

    Object Type:    hillpump

    Description:    A simple model for the store membrane pump (SERCA), similar
                    to the mmpump, but with a Hill exponent.

    Author:         E. De Schutter BBF-UIA 11/97

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  hillpump_type [in src/concen/conc_struct.h]

    Size:           92 bytes

    Fields:         vmax            maximum pump velocity, scaled by mebrane
                                    surface area.  i.e., max ion flux in moles/sec.
                    Kd              disassociation constant
                    Hill            Hill exponent

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       HillPump [in src/concen/hillpump.c]]

    Classes::       gate segment

    Actions:        CHECK  RESET  PROCESS  INIT

    Messages:       MMKD   Kd  (changes Kd value)

    ------------------------------------------------------------------------------

    Notes:

    The hillpump is similar to the mmpump, and is coupled to a difshell to reduce
    the concentration in the shell, and to a concpool to increase the
    concentration.  The message "HILLPUMP vmax Kd Hill" to a difshell causes the
    concentration to change as dC/dt = -vmax*(C^Hill/(C^Hill+Kd)/vol.  When sent
    to a concpool, it changes the concentration with the opposite sign.  Note that
    the maximum pump velocity vmax should have previously been multiplied by the
    membrane surface area, so that it is in moles/sec.

    This does not have the electrogenic effect (Ik) calculation of the mmpump.  It
    gets Kd from a MMKD message (or a setfield), and simply stores Kd, vmax, Hill,
    letting the difshell or concpool do the calculations.

    Example:

See also: mmpump , difshell , concpool

## 26.34 hsolve

    Object Type:    hsolve

    Description:    An object used for implementing the Hines method for the
                    implicit solution of dendritic trees, as well as a set of
                    routines that maximize speed.  This allows faster, more
                    stable numerical integration methods to be used with GENESIS,
                    particularly when there are many compartments in a cell.

    Author:         U. S. Bhalla and E. De Schutter Caltech 91-93,
                    E. De Schutter BBF-UIA 94-99.

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  hsolve_type  [in src/hines/hines_struct.h]

    Size:   552 bytes

    Fields: path            wildcard list of compartments to be
                            integrated; specifies all compartments
                            belonging to cell which hsolve element will
                            deal with.  The default is
                            ./##[][TYPE=compartment]

            chanmode        flag that controls channel computations and
                            chip-array use.

                            0 = default. It is the most general, uses least memory
                            and is slowest (no chip-array).  It takes over the
                            actions of compartments only, computing all other
                            object types as before.  As a consequence, all
                            computed fields of the original elements are updated,
                            and all user-setable fields may be set, just as before
                            the element was taken over by the hsolve element.
                            This means that you can add and delete outgoing
                            messages to compartments or other elements whenever
                            you like and easily change parameters during the
                            course of the simulation, making this the easiest mode
                            to use.  It is also the most compatible mode of
                            operation, and is guaranteed to work with any future
                            new object type.  One significant limitation is that
                            you cannot add or delete AXIAL, RAXIAL or CHANNEL
                            messages, once the hsolve element has been created.
                            In order to calculate the compartment Im field,
                            the compute_Im flag must be set.

                            1 = like chanmode 0, but optimizes calculations for
                            tabchannel equations.  This will be faster than
                            chanmode 0 for models containing tabchannels and
                            tab2Dchannels.

                            2 = assumes integer exponents (maximum = 6) for
                            tabchannel and tab2Dchannel gate variables.  Chanmodes
                            2-5 are the fastest because of the large 'chip-array'.
                            Under these moses, you can no longer assume that all
                            the fields of the elements that are taken over by
                            hsolve will be updated.  Incoming and outgoing
                            messages to and from the disabled elements will work
                            properly, provided that they were added prior to
                            setting up the hsolve element.  However, the Vm fields
                            of all compartments are automatically updated under
                            chanmode 2, whether or not there were pre-existing
                            messages to output Vm.  Note also that several fields
                            (Gk, Ik, Ek, and Im) are not available for output in
                            chanmodes 2 and 3, so you have to use chanmode 4 or 5
                            with findsolvefield if you want to output these fields.

                            3 = as chanmode 2, but Vm fields of compartments are
                            not automatically updated.  This mode is faster than
                            chanmode 2, at the expense of somewhat greater memory
                            usage.  All disabled elements (including compartments)
                            that had outgoing messages to non-hsolved objects
                            during the SETUP call are updated at a rate determined
                            by outclock.  Thus SAVE and PLOT messages will work
                            properly, except with the fields Gk, Ik, Ek, and Im.

                            4 = as chanmode 3, but more variables (e.g. Gk, Ik,
                            Ek, Im and leak) are stored by hsolve so that they can
                            be accessed by SAVE or PLOT messages (see
                            findsolvefield documentation for more details).  The
                            added field, leak, is available for each compartment
                            to give the current flowing through the membrane
                            resistance Rm.  Im is calculated directly as the sum
                            of the channel currents and the leakage current.

                            5 = as chanmode 4, but normalizes the currents and
                            conductances stored in the hsolve givals array (for
                            display purposes only).

            computeIm       flag to determine whether the compartment Im field
                            is calculated in chanmodes 0 and 1.  If set, Im is
                            approximated by the sum of axial currents and injected
                            current, as done for non-hsolved compartments and
                            symcompartments.

                            0 = the default, does not calculate Im.
                            1 = calculates Im, with a decrease in speed.

            comptmode       flag that selects option for compartment computations

                            0 = uses least memory, and is slightly slower. However
                            the amount of time spent in this part is usually less
                            than 10% of the total, so this should not matter.

                            1 = the default, uses a lot of memory and is twice as
                            fast for the actual Hines matrix calculation.  This
                            may be only a 5% difference.  comptmode 1 is
                            required for chanmodes 2-5.

            calcmode        flag affecting operations for chanmodes 2-5.

                            0 = no interpolation will be performed in lookup
                            tables.  This mode is for backward compatibility with
                            older versions of hsolve (prior to GENESIS 2.1) which
                            did not use interpolation.

                            1 = default mode with linear interpolation of values
                            in lookup tables.

            storemode       flag, only valid for chanmodes 4 and 5,  to allow the
                            output of total currents and conductances.  For each
                            type of voltage gated channel in the model, the total
                            currents or conductances are the sum of the
                            corresponding Ik or Gk fields for all compartments
                            where the channel is present.  This assumes that these
                            channels have the same name in each compartment.
                            These are stored in an array called itotal.  When the
                            hsolve element is set up, a message will be output
                            giving a list of channel names and corresponding
                            itotal indices, if the 'silent' command has previously
                            been given with a negative argument.

                            0 = no sums are stored.
                            1 = total currents are stored.
                            2 = total conductances are stored.

            no_elminfo      = 0/1; flag that controls whether the HPUT and HSET
                            actions will work.  Is relevant only for chanmodes
                            2-5.  Default is zero (HPUT and HSET work).
                            Saves memory if non-zero value is used (HPUT, HSET
                            do not work; HRESTORE and HSAVE do).

            outclock        number [0-99] of the clock used for all element
                            updates if chanmode = 3, 4, or 5, will affect SAVE and
                            PLOT messages.  The element update routines are not
                            very efficient, so setting them to a slower clock will
                            speed up things.  Note however that any object that is
                            not computed by the hines solver and that depends on a
                            message from a hsolve-computed object will be affected.

            The other fields displayed with the showobject command are NOT
            to be set by the user.

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       HinesSolver  [in src/hines/hsolve.c]

    Classes:        hsolver

    Actions:        RESET   does the standard reset functions, but also for
                            chanmodes 2-5, it will update all parameters in
                            the chip-array (equivalent to a HRESTORE call) and
                            recompute rate factor tables if clocks were changed.

                    DELETE  standard actions
                    PROCESS standard actions

                    SETUP   setup all internal tables.  Must be called before the
                            hsolve element is used.  User accessible fields
                            (path, chanmode, etc.) should have been set.  Model
                            changes after the SETUP call may have no effect on
                            the computations.

                    DUPLICATE  does an efficient duplication of an hsolve element.
                            Use this in a network simulation for identical
                            copies of a neuron. Only the tables containing
                            changing parameters (Vm, etc.) will be duplicated.
                            Syntax: call hsolve1 DUPLICATE hsolve2 duplic_path

                    HPUT    updates chip-array.  Fields from a single element are
                            put into the chip-array (chanmodes 2 or 3).  Do this
                            call after a setfield command on the element.
                            Syntax: call hsolve HPUT element_path

                    HGET    updates hsolve-computed element.  Computed values are
                            put from the chip-array into a single element
                            (chanmodes 2-5).  Do this call before a getfield on
                            the element.  Syntax: call hsolve HGET element_path

                    HRESTORE the complete chip-array is updated.  Fields from all
                            hsolve-computed elements are put into chip-array
                            (chanmodes 2-5).  Do this call after a restore
                            command or after multiple setfield commands.
                            Syntax: call hsolve HRESTORE

                    HSAVE   all hsolve-computed elements are updated.  Computed
                            values are put from the chip array into all elements
                            (chanmodes 2-5).  Do this call before a save
                            command or before multiple getfield commands.
                            Syntax: call hsolve HSAVE

    Messages:       None.

    Example:

            // Do all the preparatory grunge work
            .
            .
            // create the cell as an hsolve element
            readcell test.p /test -hsolve

            // set the chanmode, comptmode and calcmode (if other than defaults)
            setfield /test chanmode 2

            // set up the arrays and tables for the solver
            call /test/solve SETUP
            // use the Crank-Nicholson method for the hsolve element
            setmethod 11
            // It is essential to call reset (or reschedule) after setting
            // up an hsolver, so that the process list gets updated.
            reset

    ------------------------------------------------------------------------------

    Notes:

    The hsolve element completely takes over the calculations for compartment and
    symcompartment elements and certain other elements specified as part of the
    cell. Each hsolve element should only solve one cell. The timestep for the
    integration is determined by the clock assigned to the hsolve element, and the
    clocks for these elements which are taken over are ignored.

    When using the Hines solver with a neuron, it is best to think of the entire
    neuron as a single object since the individual compartments within the cell
    are no longer responsible for their own computations.  This loss of object
    orientedness is mitigated to some degree by the ability of the solver to
    transparently interact with elements utilizing other integration schemes.

    There are 2 basic modes for hsolve operation: without chip-array (chanmode 0
    or 1), or with chip-array (chanmodes 2-5).  Without chip-array is the most
    compatible mode, but is the slowest.  With the chip-array, hsolve is much
    faster because the original elements are no longer used, instead all
    simulation parameters are stored in a huge array (this improves memory access
    times).  Unfortunately you can no longer expect that it will update the fields
    in computed objects (like Vm in a compartment or Ca in Ca_concen) so that
    graphic or file output might not work.  Vice versa, if you change a field
    (like inject in compartment) it might not affect the simulation.  However,
    there are methods available to get values in and out of the chip-array, which
    involve special settings and/or the use of the HPUT, HGET, HSAVE and HRESTORE
    actions listed above.  This is ilustrated in another example below.  The
    documentation for findsolvefield describes another method, introduced in
    GENESIS 2.1, that also allows access to these values.

    The example above illustrates the process of setting up the hsolve element.
    First, one should create the cell as an hsolve element at the root of the cell
    element tree.  This may be done in one step by using the "-hsolve" option with
    readcell.  Note that, starting with GENESIS version 2.2, it is necessary to
    provide the full path to the cell when using readcell to directly create an
    hsolve.  (e.g.  you can't use "readcell test.p test -hsolve", even if "/" is
    the current working element.)

    If readcell is not used, then the hsolved cell should be created with
    statements like

        create hsolve /test
        create compartment /test/soma
        create tabchannel /test/soma/Na_channel
        ...

    It is required that only compartments (or symcompartments) be children of the
    cell, and that channel, concentration, etc. elements should be children or
    grandchildren of the compartment to which they are attached.

    Next, set any fields of the hsolve which are needed to specify non-default
    values of chanmode, comptmode, calcmode, storemode, etc.  Then, one needs to
    call the SETUP action in order to tell the hsolve element to create all the
    solution arrays and tables.  Finally, chose either method 10 (backwards Euler)
    or 11 (Crank-Nicholson) as the method to be used.  All elements that lie
    outside this tree will continue to be treated by the previous explicit method
    (typically exponential Euler).  The Scripts/examples/hines directory contains
    an example that which demonstrates both chanmodes 0 and 2.

    Although it is not presently necessary to create the hsolve element as the
    root of the element tree, future versions of hsolve may require this.  The
    older method of creating the hsolve is to create the cell as a neutral
    element, create the hsolve element as a child element, and then set the hsolve
    path field to indicate which elements will be taken over.  Typically, a
    wildcard path is used to refer to all compartment elements in the simulation.
    This includes all hsolvable sublelements of these compartments.  For example,

            // readcell will place the compartments below the neutral '/test'
            readcell test.p /test

            // create the hines solver element below the cell '/test'
            create hsolve /test/solve

            // Specify the path for the solver
            setfield /test/solve path /test/##[][TYPE=compartment]

    RESTRICTIONS

    It is important to be aware of some of the restrictions imposed by the use
    of hsolve:

    Only the objects compartment, symcompartment, tabchannel, tab2Dchannel,
    tabcurrent, spikegen, Ca_concen, concpool, nernst, Mg_block, ghk, taupump,
    mmpump, hillpump, difshell, fixbuffer, difbuffer, dif2buffer, fura2, synchan,
    and the oldconn library channels channelC2 and channelC3 are handled by
    hsolve.  If your simulation uses these listed objects, the use of hsolve will
    increase speed significantly.  Note that as of GENESIS version 2.2,
    symcompartment objects are handled by hsolve.

    An important restriction introduced in GENESIS version 2.1 is that, for
    chanmodes 2-5, the element tree of your cell (or other element tree to be
    taken over by hsolve) must not contain any non-hsolvable elements other than
    neutral elements.  For existing simulations which violate this restriction, it
    will be easiest to switch to chanmode 0 or 1.

    It is not guaranteed that messages from unlisted objects to listed objects
    will work, though solve should alert you about any such incompatibilities.
    Most incoming messages will work if you use chanmodes 2-5, however you will
    receive a warning if the source of the message is not hsolved.  This is to let
    you know that the source element is being solved by a less accurate explicit
    method.  Messages from listed to unlisted objects will only work for certain
    chanmode settings.

    hsolve does not keep track of changes made to the model after the hsolve SETUP
    command (particularly the following commands: create, copy, delete, addmsg,
    deletemsg).  In chanmode 0 or 1 this only affects the listed objects and
    messages between them; in chanmodes 2-5 this affects the listed objects and
    ALL messages going in or out from them.  The hsolver should be used in these
    modes only for finished models (you can use it for parameter searches); do not
    use it if you are still constructing and testing a model.

    hsolve may miscalculate if you change clocks used by tabchannels,
    tab2Dchannels, synchans, or channelC2/C3 objects without doing a reset (only
    in chanmodes 2-5).

    The Hines solver utilizes a considerable amount of memory.  Memory use
    increases as the result of comptmode + chanmode - no_elminfo flags.  In
    particular, going from chanmode 0 or 1 to chanmode 2, 3, or 4 causes a big
    jump in memory usage.  Approximately 100 bytes are required per compartment if
    the speed-optimized version of the hsolve element is used. Most of this
    storage is for tables describing the sequence of calculations. These tables
    can, however, be shared between cells which are identical in topology and
    differ only in parameter values.

    FURTHER EXAMPLES

    * Copying cells with the hsolve element

    When a cell using the hsolve element is copied, the pointers in the
    duplicated hsolve element are unchanged. In other words, they refer back to
    the original cell. One could simply change the path to refer to the current
    cell and call SETUP again, but that would unnecessarily duplicate a lot of
    tables.  The efficient option would be to use the original tables where they
    are identical, and construct new ones where they refer to the current cell.
    This is done using the DUPLICATE sction, which takes the name of the new
    hsolve element and a wildcard path duplic_path as arguments.  duplic_path
    points to all compartments that should be taken over by the new solver.
    For example,

            // Copy the original cell to /test2
            copy /test /test2

            // create the hines solver element below the cell '/test'
            create hsolve /test/solve

            // Specify the path for the solver and the chanmode
            setfield /test/solve path /test/##[][TYPE=compartment] chanmode 4

            call /test/solve SETUP

            // Duplicate the hsolver
            call /test/solve DUPLICATE /test2/solve /test2/##[][TYPE=compartment]

            reset

    There are several commands, including createmap and cellsheet, that copy
    cells. The DUPLICATE command should be issued for the hsolvers on each copy.
    When using chanmodes 3 or higher, findsolvefield must be used with messages in
    order to access fields of duplicated hsolves, as shown in the documentation
    for findsolvefield.

    * Deleting hsolve elements

    When an hsolve element is set up it removes the relevant channels and
    compartments from the list of elements to be processed, by setting a bit
    (0x100) on the flag field of those elements. These elements are re-enabled
    and the bit set back to 0 when the hsolve element is deleted.

    WARNING: in the present implementation, the hsolve element does not check
    whether it has had duplicates made using the DUPLICATE command. This makes it
    possible to delete the tables for all of the copies by deleting any one of
    them, resulting in segmentation violations and similar amusements. In other
    words, do not delete hsolves on duplicated cells.

    * Accessing data fields in chanmodes 2-5.

    A script similar to this example might be used for running a long simulation
    as a background job, using no graphics.  The HPUT and HSAVE actions are used
    in chanmode 2 or 3 to allow the simulation results and the final state of
    the simulation to be saved to disk.  A disk_out element is used to output the
    Vm of a soma compartment in a compressed binary format.  However, it is
    equally possible to output Vm from every compartment, or from an array of
    cells.  Later, a script using a disk_in element can display the results using
    messages from the disk_in to an xgraph or xview.  The save command is used
    here to save field values of all elements except nernst elements and the
    hsolve element.  This will allow the simulation to be resumed from its final
    state by using the restore command.

    For more details, see Scripts/examples/XODUS/fileview and the documentation
    for disk_out, disk_in, save, and restore.

            /* load scripts and global variables */
            include defaults
            include other_stuff

            pushe /library
            make_my_stuff
            pope

            /* make the model */
            readcell my_cell {my_cellpath} -hsolve

            /* set the clocks */
            setclock 0 1e-5   /* integration */
            setclock 1 1e-4   /* output */

            /* create the output or graphics elements */

            /* note that if you want to output Vm only, but from multiple
            ** compartments, you should use chanmode == 2; if you want to
            **  output other fields or Vm from only one compartment,
            ** use chanmode == 3 */

            create disk_out /output/disk
            useclock /output/disk 1
            addmsg {my_cellpath}/soma /output/disk Vm
            addmsg ...

            /* create any other elements */
            ....

            /* setup the hines solver */
            setfield {my_cellpath} \
                    comptmode   1 \
                    chanmode    3 \
                    outclock    1
            call {my_cellpath} SETUP
            setmethod 11              // Crank-Nicholson integration method

            /* initialize output */
            setfield /output/plot_out filename {filename} initialize 1
            setfield /output/plot_out filename {filename} append 1 leave_open 1

            reset

            step 0.10 -t
            /* do a current injection */
            setfield {my_cellpath}/soma inject 1.0e-9         /* in Amps */
            /* update chip array */
            call {my_cellpath} HPUT {my_cellpath}/soma
            step 2.00 -t

            /* save the integration values to disk */
            call {my_cellpath} HSAVE
            save {my_cellpath}/##[][TYPE!=nernst][TYPE!=hsolve] {savename}

            quit

    ---------------------------------------------------------------------------
    DETAILED DESCRIPTION

    The Hines library provides elements and functions for the efficient implicit
    solution of the systems of differential equations arising in single-neuron
    models. The sparse matrix arising from the the branched structure of neurons
    is ordered by the method described by Michael Hines, which permits it to be
    solved in order N operations using Gaussian elimination without pivoting.
    The nonlinear equations resulting from the Hodgkin-Huxley description of ion
    channels are treated as conditionally linear, and also solved in an
    efficient, second-order manner.  Compatibility with other integration
    schemes is maintained so that mixed integration schemes are feasible.

    The element sets up a data structure whereby the only change needed for
    other identical cells is to reassign pointers to the compartment and channel
    elements.  This avoids having to reallocate and rederive the solving
    scheme.  Solutions are done using gaussian forward and backward elimination
    without pivoting. The numbering and evaluation sequence ensures that no new
    off-diagonal terms are formed which might mess up the sparse matrix
    representation.  The sparse matrix is represented by a single 'values' array
    indexed using the ri and cip arrays.  The actual solution system is stored
    as a linear sequence of operations on the 'values' array, in an attempt to
    speed things up a bit.

    The implicit method leads to numerically stable solutions for all time
    steps.  Numerical accuracy, however, imposes limits on the integration time
    step which must be empirically evaluated for each simulation.  Typical
    values are 100 microsecond time steps for purely passive membranes and 20
    microsecond time steps for membranes with active channels.  This confers a
    considerable speed up in detailed neuronal simulations where the presence of
    electrotonically small compartments (such as dendritic spines) leads to
    systems of equations which are numerically very stiff. In order to obtain
    similar accuracy using explicit integration methods, time steps in the
    nanosecond range may be required.

    In addition to the substantial speed advantage gained from the use of an
    implicit solution, the coding of the Hines solver element has been done with
    a view to computational efficiency.  This results in a speed up of around 50%
    compared to the same model with the same time step, using the conventional
    explicit Euler integration scheme.

    Code changes needed for the Hines library

    This section is probably of interest only to individuals who have developed
    their own code libraries and who are deeply entangled in GENESIS coding
    issues. For most users the changes are transparent, once the .simrc and
    schedule.g file have been updated to reflect the addition of a new library.

    The incorporation of a completely new integration scheme to the simulator can
    be expected to have numerous repercussions. Fortunately, the changes needed for
    the Hines library turned out to be relatively painless. No changes were needed
    for the code of any of the existing elements. There is a slight rearrangement
    of the order of fields in the various channel objects, and a new globally
    #define'd type called CHAN_TYPE has been created so that all these channel
    objects have the following common fields at identical memory offsets: Ik, Gk
    and Ek (See src/sim/struct_defs.h). All channels whose structures obey this
    convention can be used in cells utilizing the hsolve element.  A very small
    number of channel objects (such as channelC) do not share these fields and
    therefore cannot be part of cell models which use the hines solver.

    A new flag (0x100) has been employed for the Hines solver, which causes the
    removal of compartment and tabchannel elements from the action list (the list
    of elements whose action functions are to be called according to the clocks).
    This flag is similar to the disable option except that it leaves the children
    of these elements intact.

    In the interests of speed (which is, after all, what the Hines method is all
    about) I have 'unrolled' the sparse matrix solution into a single giant
    function array. This is done at setup time, so the actual solution does not
    involve any conditionals and minimises array lookups. This is moderately
    expensive in terms of memory. The size of the function array allocated is

         S = FA * sizeof (int) ;  FA = 10 + 1.5 * M^2 / N

    where S is the size of the array, FA is the number of functions allocated, M
    is the number of non-zero coefficients in the solution matrix and N is the
    number of compartments. M depends strongly on the branching pattern of the
    cell. FA is an approximation to, and is greater than F, which is the actual
    number of locations needed in the function table.  For example, in a mitral
    cell model, which has limited branching:

         N = 286 ; M = 856 ; FA = 3853 ; S = 15412 ; F = 3710

    In a granule cell model with numerous dendritic spines:

         N = 944 ; M = 2830 ; FA = 12736 ; S = 50944 ; F = 12264

    A reasonable approximation is that each compartment requires about 54 bytes in
    the function table, which is not too bad.

    References:     Hines, M. (1984) Efficient computation of branched nerve
                    equations.  Int. J. Bio-Med. Comp.  15: 69-76

                    Mascagni, M.V. (1989) Methods in Neuronal Modeling Ed: Koch
                    and Segev. Chapter 13. 439-484

See also: setmethod , findsolvefield

## 26.35 interspike

    Object Type: interspike

    Description: Generates an interspike interval histogram.

    Author:      E. De Schutter Caltech 8/91

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  interspike_type [in src/device/dev_struct.h]
    Size:           116 bytes

    Fields:         output        gives the most recent interspike interval
                    threshold     voltage threshold for determining when a spike
                                  occurs
                    binwidth      time interval between bins
                    num_bins      number of table entries (bins)
                    trigger_mode  0 (free run) or 1 (triggered)
                    reset_mode    if 1 then bins will be emptied upon RESET
                    table         table with the number of spikes for that bin
                    prev_time     time of last event (not set by user)
                    triggered     set to 1 on RESET if trigger_mode = 0 (free run),
                                  else is 0 until a TRIGGER message is received
                                  (not set by user)
                    spiking       flag indicating spike in progress
                                  (not set by user)
                    allocated     flag indicating table has been allocated
                                  (not set by user)

    ------------------------------------------------------------------------------
    Function:       InterSpikeInterval [in src/device/interspike.c]

    Classes:        device

    Actions:        CHECK  PROCESS  RESET

    Messages:       SPIKE   time     (Time of occurrence of a spike.)
                    TRIGGER state    (If state is > 0, the previous spike time is
                                     set to the current time, and binning starts
                                     at first bin.)
                    INPUT   voltage  (The Vm value sent to be compared with
                                     threshold.)

    ------------------------------------------------------------------------------

    Notes:          interspike produces an interspike interval histogram (ISI).
                    Incoming data is used to fill an internal array (called table)
                    that contains num_bins entries from which the histogram values
                    can be read.  These objects can collect data on-line during a
                    simulation, but do not produce much useful information during
                    the simulation (the output field of interspike can be used to
                    look at the most recent interspike interval).  At the end of
                    the run, the histogram results can be retrieved with commands
                    such as "getfield /interspike table[{i}]", with i taking on
                    values from 0 through nbins-1.  The example script reads the
                    table entries and and plots a histogram after the run phase of
                    the simulation.

                    The last bin also contains the number of intervals with
                    values larger than that of the last bin.

                    There are two modes that may be used, as determined by the
                    "trigger_mode" field.  If the field is 0, the system is
                    free-running and begins accumulating data right away.
                    Otherwise, the system waits until it receives a trigger to
                    start binning incoming events.  The trigger should be a single
                    time step event like the state field of a 'spikegen' or
                    'randomspike' object, sent with a TRIGGER message.

                    Events can be defined in one of two ways.  They can be
                    determined from the time that the value of an INPUT message
                    first exceeds threshold.  The voltage must then fall below
                    threshold before another spike event can be recorded.)
                    Alternatively, a SPIKE message can be sent giving the time
                    that a spike occurs.  Note that this is NOT like the SPIKE
                    message of a synchan, which does not require an argument.

    Example:        See Scripts/examples/spike.

See also: peristim

## 26.36 leakage

    Object Type:    leakage

    Description:    Provides a constant conductance in series with a battery.
                    This is often used to implement a passive "leakage" channel
                    having a fixed conductance.

    Author:         M. Wilson, Caltech (6/88)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  leakage_type  [in src/segment/seg_struct.h]

    Size:           96 bytes

    Fields:         Gk              the Gk to be sent in a CHANNEL message
                    Ek              the leakage battery
                    activation      the leakage conductance used to calculate Ik
                    Ik              channel current
                    inject          not used

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Leakage  [in src/segment/leakage.c]

    Classes:        segment
                    channel

    Actions:        PROCESS         Calculates Ik
                    RESET           Sets Ik = 0
                    CHECK           Checks to see if an incoming VOLTAGE
                                    message has been established.

    Messages:       VOLTAGE Vm

    ------------------------------------------------------------------------------

    Notes:          This object is intended to be used as a flexible leakage
                    term in conjunction with the membrane model.  As with any
                    other type of channel, it normally is used to send its
                    conductance (Gk) and reversal potential (the battery in series
                    with Gk) to the parent compartment using a CHANNEL message.
                    In this case, Gk has a constant value, to be set by the user.

                    Although this feature is not often used, a leakage element
                    also calculates the current, Ik = (Ek - Vm)*activation.  Here,
                    Vm is the compartment membrane potential received with a
                    VOLTAGE message, and "activation" is a conductance.  This
                    would normally be set by the user to the same value as Gk, but
                    this is not done automatically.  As Gk does not depend on Vm,
                    a VOLTAGE message is not strictly required if Ik not is
                    needed.  However, the check command will issue a warning if
                    one has not been established.
    Example:
                    create leakage K_leak
                    setfield K_leak Ek {EK} Gk {Gleak}
                    addmsg K_leak   ..     CHANNEL Gk Ek
                    addmsg ..       K_leak VOLTAGE Vm

    See also:

## 26.37 metadata

    Object Type:    metadata

    Description:

    File formats such as netcdf allow the inclusion of descriptive content in
    addition to actual data. This is extremely useful from the perspective of
    having important documentation, such as time of creation, author, purpose
    or critical information about individual variables or the file as a whole,
    alongside the actual data in the same file.
    The genesis metadata object allows the user to manipulate this descriptive
    data that is in an existing file or write new metadata content into it. As
    already mentioned, descriptive data can describe individual variables in
    the file (local metadata) or the file as a whole (global metadata). This
    distinction is replicated well, through the hierarchical element structure
    in genesis. So a metadata object will be identified as a local attribute if
    the immediate parent is a 'variable' object and global if the 'diskio' object
    is the immediate parent.

    FMT1 files do not support the notion of metadata and hence arbitrary
    creation of metadata objects in this case will not be allowed. For the sake
    of consistency, however, when SAVE messages are sent to the diskio object,
    automatically created metadata elements (auto3-DPosSAVE_diskio[]) store
    relevant information for inspection. The fields are made readonly in the
    case of FMT1.

    Author:         V.Jagadish (9/96)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS:

    DataStructure:  Gen_Metadata_Type [in src/diskio/diskio_struct.h]

    Size:           92 bytes

    Fields:         datatype        The type of the value(s) held in the metadata
                                    - The list of valid types are given in the
                                      notes section of this document.
                                    - Defaults to 'char8' (8-bit char)
                                    - readonly for FMT1 files.

                    size            The maximum number of descriptive values the
                                    object can hold.
                                    - Like variables, metadata objects can hold
                                      an array of descriptive values the size of
                                      which is limited by the value of this field.
                                    - If the datatype is 'char8' (default) the
                                      user could provide a string as an argument
                                      to the value field without
                                      specifying a size or index, and the size
                                      (which is the number of chars in the string
                                       including the '/0' character) is
                                      internally calculated and set in this field.
                                    - The default value is 1.
                                    - readonly for FMT1 files.

                    value           The value(s) held by the metadata.
                                    - Since metadata can hold an array of
                                      values or a single one, an index (with
                                      the genesis style indexing syntax) needs
                                      to be specified while setting or showing
                                      this field. The index defaults to 0 if
                                      not specified, the exception to it being
                                      the case that the datatype is 'char8'.
                                    - Not specifying the index for a 'char8' type
                                      metadata will translate to mean the entire
                                      string and individual indices will mean the
                                      character in that position.
                                    - As in the case of the variable object,
                                      multiple argument values can be specified
                                      for this field (see examples) and the values
                                      will be accessed starting with index 0.
                                    - The default value is 0 for numerical
                                      datatypes and ''(blank) for character types
                                    - readonly for FMT1 files.

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Gen_Metadata [in src/diskio/gen_metadata.c]

    Classes:        output

    Actions:        CREATE PROCESS RESET SET SHOW ADDMSGIN

                    FLUSH:
                    UPDATE: the object commits the underlying metadata values
                            to the file on disk.

                    DELETE: commits any changes to disk if necessary and then
                            deletes the object but does not remove the
                            underlying attribute on file.

    ------------------------------------------------------------------------------

    Notes:

    The default metadata is an 8-bit single blank character (char8)
    The datatype field stores the type of the variable as a string. The types
    are chosen to be as generic as possible. They are not based on the usual
    'C' data types but rather on the user's perspective.
    Table 1.2 shows the valid datatype names and what they mean to the user.
    Please note that not all these types are supported by all file formats.
    An error to that effect will be printed if a metadata obeject of an
    unsupported type is attempted to be created.

    As opposed to variables, the size and datatype fields of metadata objects
    can be reset within netcdf.

    A smaller size setting than the original truncates values and a larger size
    does not disturb the old values but adds the appropriate number of default
    values (0 or '').

    Changing the datatype for a metadata object defaults all the values
    (as specified by the size field) to the new type. The old values will be lost.

    Table 1.2 - Valid datatypes

    Name                            Description
    ____            |               ___________
                    |
                    |
    uint8           |               8-bit unsigned int
                    |
    int8            |               8-bit signed int
                    |
    uint16          |               16-bit unsigned int
                    |
    int16           |               16-bit signed int
                    |
    uint32          |               32-bit unsigned int
                    |
    int32           |               32-bit signed int
                    |
    uint64          |               64-bit unsigned int
                    |
    int64           |               64-bit signed int
                    |
    float32         |               32-bit float
                    |
    float64         |               64-bit float
                    |
    uchar8          |               8-bit unsigned char
                    |
    char8           |               8-bit signed char
                    |
    char16          |               16-bit (unicode) char
                    |
    string          |               string type (i.e not an array of chars)
                    |
    ________________+______________________________________________________

    Examples:

    create diskio /dout -filename "testfile.nc" -accessmode w

    create metadata /dout/author -value "Venkat Jagadish"

    showfield /dout/author value // This will print out the entire string
    showfield /dout/author value[2] // This will print the 3rd char - 'n'

    create variable /dout/Vmtrace -datatype float32
    create metadata /dout/Vmtrace/starttimes -datatype float32 -size 3  \
    -value "5 45 65"
    create metadata /dout/Vmtrace/stoptimes -datatype float32 -size 3 \
    -value "20 60 80"
    setfield /dout/Vmtrace/starttimes value[1] 55
    setfield /dout/Vmtrace/stoptimes value[1] 70

    setfield /dout/Vmtrace/starttimes datatype float64
    showfield /dout/Vmtrace/starttimes value[1] // Setting datatype resets
                                                // values to default - 0
                                                // (in this case)

    _______________________________________________________________________

See also: diskio , variable

## 26.38 mmpump

    Object Type:    mmpump

    Description:    Implementation of a simple pump with Michaelis Menten kinetics,
                    to be coupled to a difshell.

    Author:         E. De Schutter BBF-UIA 9/94 - 3/99

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  mmpump_type [in src/concen/conc_struct.h]

    Size:           108 bytes

    Fields:         Ik              computed electrogenic effect (if val!=0)
                    vmax            maximum pump velocity, scaled by mebrane
                                    surface area.  i.e., max ion flux in moles/sec.
                    val             charge of ion
                    Kd              half-maximal activating concentration in mM
                    mmconst         mmconst=vmax*val*FARADAY (calculated on reset)

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       MMPump [in src/concen/mmpump.c]

    Classes:        gate segment

    Actions:        CHECK  RESET  PROCESS  INIT

    Messages:       CONCEN  C   (use for electrogenic effect only)
                    MMKD    Kd  (changes Kd value)

    ------------------------------------------------------------------------------

    Notes:

    The mmpump and other ionic pumps provide various mechanisms to remove ions
    from a concentration shell (difshell).   The mmpump is a simple model
    for the plasma membrane pump (PMCA) with Michaelis Menten kinetics.

    For a general description of buffered calcium diffusion and ionic pumps, see:
    De Schutter E., and Smolen P., "Calcium dynamics in large neuronal models", in
    Methods in neuronal modeling: From ions to networks (2nd edition), C. Koch and
    I. Segev editors, pp. 211-250 (1998).  Sec.  6.3.2 and Eq. 6.10 describe the
    Michaelis Menten pump, which may be used to model a Ca-ATPase pump.  This is
    also discussed in A. Zador, C. koch, and T. H. Brown, Proc. Natl. Acad. Sci.
    (USA) 87: 6718-6722 (1990).

    Note that this object does not compute anything by itself, unless the
    electrogenic action is simulated by specifying a non-zero value of val.  When
    coupled to a difshell with a MMPUMP message that sends the vmax and Kd field
    values, the difshell computes its change in ion concentration from dC/dt =
    -vmax*(C/(Kd + C))/vol.  This corresponds to De Schutter and Smolen Eq. 6.10,
    if the maximum pump velocity vmax has previously been multiplied by the
    membrane surface area, so that it is in moles/sec.

    The current outflow across the membrane due to the electrogenic effect of the
    pump can also be simulated by using a CONCEN message into the pump, and using
    a non-zero value for the valence (e.g. val = 2, for Ca++ ions).  In this case,
    the mmpump calculates Ik = mmconst * C/(Kd + C), where the constant mmconst is
    set to vmax * val * FARADAY on reset.  Note that, in contrast to the GENESIS
    channel objects, the Ik calculated by the mmpump has a positive sign for an
    outward current, rather than obeying the usual GENESIS convention of "inward
    positive".

    Example:        addmsg mmpump0 shell0 MMPUMP vmax Kd

See also: difshell , taupump , Scripts/examples/spinedemo

## 26.39 nernst

    Object Type:    nernst

    Description:    Calculates the Nernst potential for the given
                    ionic concentrations and temperature.

    Author:         M. Wilson, Caltech (3/89)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  nernst_type  [in src/device/dev_struct.h]

    Size:           96 bytes

    Fields:         E               equilibrium (Nernst) potential
                    T               temperature in degrees Celsius
                    valency         ionic valency z
                    scale           voltage scale factor
                    Cin             internal ionic concentration
                    Cout            external ionic concentration
                    constant        scale*(R/zF)*(T + 273.15)
                                    This is set by the element,
                                    and should not be set by the user.

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Nernst  [in src/device/nernst.c]

    Classes:        device
                    channel

    Actions:        PROCESS         sets the fields from incoming messages
                                    and calculates constant and E.
                    RESET           similar to a single PROCESS step.
                    CHECK           checks for valid messages and parameters.

    Messages:       CIN Cin         sets the Cin field.
                    COUT Cout       sets the Cout field.
                    TEMP T          sets the T field, and calculates constant.

    ------------------------------------------------------------------------------

    Notes:          A nernst element calculates E = constant * ln(Cout/Cin)
                    = scale*(R/zF)*(T + 273.15)*ln(Cout/Cin), where R is the
                    universal gas constant (1.9872 cal/mol deg) and F is Faraday's
                    constant (23061 cal/volt mol).  Note that the temperature in
                    degrees Celsius is internally converted to degrees Kelvin.  A
                    scale factor of 1 gives E in volts, and a scale factor of
                    1e3 gives E in millivolts.

                    A nernst element is usually used with a channel and a
                    Ca_concen element to calculate the channel equilibrium
                    potential (Ek) from the internal ionic concentration in a
                    shell near the compartment surface.  The equilibrium potential
                    is sent from the nernst element to the channel with an EK
                    message, and the nernst element receives the concentration
                    from the Ca_concen element with a Cin message.  The Ca_concen
                    element calculates this concentration from ionic currents
                    delivered with an I_k message.

                    It is also possible to perform a "one-time" calculation of E
                    with fixed values of the ionic concentrations by setting these
                    fields instead of setting up messages, and performing a reset.
                    If this is done, the nernst element should be disabled to
                    avoid wasting time performing the PROCESS action.

    Example:
            // assume that a  tabchannel `Ca' has been set up
            create Ca_concen conc
            setfield  conc                          \
                B       {5.2e-6/(area*shell_thick)} \
                Ca_base 4.0e-5                      \
                tau     1e-4                        \
                thick   {shell_thick}

            create nernst nernst
            setfield nernst \
                Cout    4.0 \   // external Ca concentration of 4 mM.
                T       21  \   // near room temperature
                valency 2   \   // Ca++
                scale   1       // E in volts

            addmsg Ca       conc        I_Ca    Ik
            addmsg conc     nernst      CIN     Ca
            addmsg nernst   Ca          EK      E

            function reset_nernst // Insure that resets are done in proper order
                call Ca RESET
                call conc RESET   // Ca_concen must be reset before nernst
                reset             // reset everything
            end

See also: Ca_concen

## 26.40 neutral

    Object Type:    neutral

    Description:    empty object used for grouping

    Author:         Caltech

    ELEMENT PARAMETERS

    DataStructure:  element_type  [in src/sim/sim_struct.h]

    Size:           68 bytes

    Fields:         [none]

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       NULL [i.e., none]

    Classes:        element

    Actions:        [none]

    Messages:       [none]

    ------------------------------------------------------------------------------

    Notes:          A set of default element types is distributed with GENESIS.
                    One of the simplest is the "neutral" object which can be
                    used to create an empty element used for grouping, much like
                    a directory in the UNIX file system.  It is often used to
                    represent a cell, containing subelements for compartments,
                    channels, etc.  Although it has no other fields, it has the
                    usual setable [x,y,z] coordinate fields possesed by other
                    objects.  This allows it to be given a position in a network.

                    The addfield, addaction, and addmsgdef commands can be used
                    to give a neutral element new fields, actions, and messages,
                    allowing it to be used as customizable element, or the basis
                    of an extended object

    Example:

    See also:

## 26.41 paramtableBF

    Object Type:    paramtableBF

    Description:    This object implements a brute-force search as part of a
                    parameter search process, and also stores the parameter
                    tables and various bookkeeping information relating to the
                    parameter search process.  It is mainly for use in
                    systematically mapping out the parameter space of a model.

    Author:         Mike Vanier, Caltech

    -------------------------------------------------------------------------

    ELEMENT PARAMETERS

    Data structure: paramtableBF_type  [in src/param/param_struct.h]

    Size:       168 bytes (more when tables are loaded)

    Fields:
                iteration_number        iteration number
                num_params              total number of parameters
                num_params_to_search    number of parameters to search over
                search                  array of flags:
                                        0 = don't search this parameter,
                                        1 = do search this parameter
                type                    type of parameter:
                                        0 = additive,
                                        1 = multiplicative
                range                   of parameter values
                min                     of parameter values
                max                     of parameter values
                label                   label of parameter,
                                        for documentation purposes only
                current                 array of parameter values
                                        to be simulated next
                current_match           match value of current parameter set
                                        being simulated
                best                    array of parameter values
                                        giving best match so far
                best_match              best match value
                new_best_match          flag: 1 if last match was the best so far
                done                    flag: 1 when the simulation is finished
                filename                where parameter information is
                                        stored/saved as a binary file
                alloced                 flag: 1 means tables are allocated
                orig                    array of original parameter values
                search_divisions        number of points on the range
                                          to test
                search_rangemod         fraction of the full range to
                                          search over
                search_count            where we are in the search for
                                          each param

    -------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:   ParamtableBF  [in src/param/paramtableBF.c]

    Classes:    param

    Actions:    Note: required arguments to actions are in <angle brackets>;
                      optional arguments are in [square brackets].

                CREATE      Creates the object (not invoked directly).

                TABCREATE <num_params>
                            Initializes the object for a given number of
                            parameters.

                DELETE      Deletes all allocated memory.

                TABDELETE   Same as DELETE.

                INITSEARCH  Initializes the search process.
                            Usage: ParamtableBF_INITSEARCH \
                                   <param-number1> <npts1> <scale1> ... \
                                   <param-numbern> <nptsn> <scalen>

                            This function expects its arguments to be in the
                            form of (<param_number> <npts> <scale>) triplets,
                            where <param_number> is the index of the parameter
                            to be varied, <npts> is the number of
                            equally-spaced points along the parameter axis to
                            test, and <scale> is the proportion of the total
                            range to use; 1.0 means use the entire range.  Note
                            that the range is relative to a center point which
                            is where the parameter search starts from.

                EVALUATE <match>
                            Copies the match value into the current_match field.
                            If this match is the best match so far, this action
                            copies the current parameter set into the best
                            parameter set and the current_match field into the
                            best_match field.

                UPDATE_PARAMS
                            Chooses the next set of parameters to simulate.
                            This object systematically works its way through
                            parameter space, simulating all points on a
                            multidimensional grid whose features are specified
                            in the INITSEARCH action.

                SAVE [filename]
                            Saves the object as a binary file.  If no
                            argument given, use the "filename" field
                            of the element.

                SAVEBEST <filename>
                            Saves the best parameter set to an ascii file.

                RESTORE [filename]
                            Restores the object from a binary file.  If no
                            argument given, use the "filename" field of the
                            element.

                RESTOREBEST Restores the best parameter table from a text file.

                DISPLAY     Displays the best parameter set obtained so
                            far on stdout.

                CHECK       Runs a series of self-check diagnostics on this
                            object.

    Messages:   none

    -------------------------------------------------------------------------

    Notes:      This object stores parameter tables and calculates new tables
                to be simulated in a parameter search process using a
                brute-force algorithm.  The algorithm divides the parameter
                space into a multidimensional grid where all points are
                equidistant to their neighbors in each dimension.  Then it
                systematically walks through the space, calculating and
                outputting a match value for each point.

                This algorithm is effectively useless for searching parameter
                space per se because of the combinatorial explosion that occurs
                when you have more than a few parameters (e.g. 3 or 4).
                However, it can be used effectively to map out parameter space
                very coarsely for a small number of parameters.  For instance,
                you could keep all but two parameters fixed and map out the
                two-dimensional parameter space that consists of varying values
                for each of the two parameters.  This may give some insight
                into various aspects of a model.  Alternatively, you could map
                out all the parameters at a very coarse scale, which can be
                used (for instance) to give a reasonable starting point for
                other algorithms.  In practice, this is still not feasible for
                more than 5 or 6 parameters.

    Example:    See Scripts/param/BF for demo scripts.

See also: Parameter Search ( Param ), Paramtable , setsearch , initparamBF , paramtableCG , paramtableGA , paramtableSA , paramtableSS

## 26.42 paramtableCG

    Object Type:    paramtableCG

    Description:    This object implements a conjugate gradient descent
                    algorithm as part of a parameter search process, and also
                    stores the parameter tables and various bookkeeping
                    information relating to the parameter search process.

    Author:         Mike Vanier, Caltech

    -------------------------------------------------------------------------

    ELEMENT PARAMETERS

    Data structure: paramtableCG_type  [in src/param/param_struct.h]

    Size:       308 bytes (more when tables are loaded)

    Fields:     iteration_number        iteration number
                num_params              total number of parameters
                num_params_to_search    number of parameters to search over
                search                  array of flags:
                                        0 = don't search this parameter,
                                        1 = do search this parameter
                type                    type of parameter:
                                        0 = additive,
                                        1 = multiplicative
                center                  of parameter values in range
                range                   of parameter values
                min                     of parameter values
                max                     of parameter values
                label                   label of parameter,
                                        for documentation purposes only
                current                 array of parameter values
                                        to be simulated next
                current_match           match value of current parameter set
                                        being simulated
                best                    array of parameter values
                                        giving best match so far
                best_match              best match value
                new_best_match          flag: 1 if last match was the best so far
                done                    flag: 1 when the simulation is finished
                filename                where parameter information is
                                        stored/saved as a binary file
                alloced                 flag: 1 means tables are allocated
                linemin_number          which line minimization we're doing;
                                        for bookkeeping only
                state                   state of parameter search:
                                        0 = random searches at startup
                                        1 = gradient calculation
                                        2 = line minimization
                deriv_method            0 = do a proper derivative;
                                        1 = quick-and-dirty estimate
                                            (not yet implemented)
                deriv_index             index of parameter we're taking
                                          the derivative of
                deriv_h_init            initial values of h (the spatial step
                                          size) to use in derivative
                                          calculations
                deriv_h_decrease        how fast to decrease h
                deriv_h_min             lowest permissible value of h
                deriv                   array of 1st partial derivatives:
                                          d(match)/d(param)
                dir                     direction vector
                tolerance               tolerance of parameter search as a whole
                linemin_tolerance       tolerance of line minimization
                                          routines

    -------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:   ParamtableCG  [in src/param/paramtableCG.c]

    Classes:    param

    Actions:    Note: required arguments to actions are in <angle brackets>;
                      optional arguments are in [square brackets].

                CREATE      Creates the object (not invoked directly).

                TABCREATE <num_params>
                            Initializes the object for a given number of
                            parameters.

                DELETE      Deletes all allocated memory.

                TABDELETE   Same as DELETE.

                INITSEARCH  Initializes the search process.

                RANDOMIZE   Picks a random parameter set from the parameter
                            space as a potential starting point for the search.

                EVALUATE <match>
                            Copies the match value into the current_match field.
                            If this match is the best match so far, this action
                            copies the current parameter set into the best
                            parameter set and the current_match field into the
                            best_match field.

                UPDATE_PARAMS
                            Chooses the next set of parameters to
                            simulate based on past results.

                UPDATE_PARAMS2
                            Increments iteration_number.  Only used in
                            random searches at the beginning of a CG
                            parameter search.

                LOADBEST    Copies best parameter values to current values;
                            can be used to start the search at the best values
                            found so far.

                RESTART     Re-initializes parameter search at the
                            best point found so far.

                SAVE [filename]
                            Saves the object as a binary file.  If no
                            argument given, use the "filename" field
                            of the element.

                SAVEBEST <filename>
                            Saves the best parameter set to an ascii file.

                RESTORE [filename]
                            Restores the object from a binary file.  If no
                            argument given, use the "filename" field of the
                            element.

                RESTOREBEST Restores the best parameter table from a text file.

                DISPLAY     Displays the best parameter set obtained so
                            far on stdout.

                CHECK       Runs a series of self-check diagnostics on this
                            object.

    Messages:   none

    -------------------------------------------------------------------------

    Notes:      This object stores parameter tables and calculates new tables
                to be simulated in a parameter search process using a
                conjugate gradient-descent algorithm.  Here is a brief
                description of the algorithm:

                The conjugate-gradient (CG) method is a type of gradient
                descent algorithm.  In this method the gradient of the match
                function at a given point in parameter space and the direction
                of steepest descent with respect to this function are computed.
                A line minimization in the direction of steepest descent is
                done to find the point on the line with the best match value.
                A new gradient is calculated at this point and the procedure is
                iterated until the method converges to a local minimum of the
                matching function.  Successive line minimizations are done in
                directions which are "conjugate" to one another so that
                successive minimizations are as nearly independent of each
                other as possible.  In theory this will guarantee that the
                parameter search will find a local minimum of the objective
                function.

                The termination criteria used by the algorithm is that either
                (a) the gradient must be very close to zero, or (b) successive
                line minimizations must produce nearly identical results.  Note
                that this can happen fairly early in the search, resulting in
                rapid convergence to a local minimum which is nowhere near the
                global minimum.  Welcome to gradient-descent algorithms :-)  One
                way around this is to simply rerun the search from random
                starting points again and again until you find better matches.
                A better alternative is to use the simulated annealing (SA)
                method instead of this one, which also incorporates a
                (modified) gradient descent algorithm so that you get the best
                of both worlds (i.e. ability to escape from local minima
                characteristic of SA methods, and convergence to local minima
                characteristic of gradient descent algorithms).

                The fields deriv_h_init, deriv_h_decrease, deriv_h_min do not
                have to be set explicitly; they are set to "reasonable" values
                by default.  deriv_h_init is actually an array of values, one
                per parameter.  The (hidden) field h represents the spatial
                step size used in the derivative calculation.  You can find
                more information about this in the source code; don't mess with
                it unless you know what you're doing or your results will
                probably be worse.

                The code for this routine was adapted from the conjugate
                gradient code in Numerical Recipes in C, 2nd Ed., by Press
                et. al. (chapter 10).  The actual code is substantially
                different but the algorithm is essentially the same.

    Example:    See Scripts/param/CG for demo scripts.

See also: Parameter Search ( Param ), Paramtable , setsearch , initparamCG , paramtableGA , paramtableSA , paramtableSS

## 26.43 paramtableGA

    Object Type:    paramtableGA

    Description:    This object implements a simple genetic algorithm as part
                    of a parameter search process, and also stores the
                    parameter tables and various bookkeeping information
                    relating to the parameter search process.

    Author:         Mike Vanier, Caltech

    -------------------------------------------------------------------------

    ELEMENT PARAMETERS

    Data structure: paramtableGA_type  [in src/param/param_struct.h]

    Size:       272 bytes (more when tables are loaded)

    Fields:     generation              generation number
                num_tables              number of parameter tables
                num_params              number of parameters per table
                num_params_to_search    number of parameters to search over
                search                  array of flags:
                                        0 = don't search this parameter,
                                        1 = do search this parameter
                type                    type of parameter:
                                        0 = additive,
                                        1 = multiplicative
                center                  of parameter values in range
                range                   of parameter values
                label                   label of parameter,
                                        for documentation purposes only
                best                    array of parameter values
                                        giving best match (fitness) so far
                best_match              best match (fitness) value
                filename                where parameter information is
                                        stored/saved as a binary file
                alloced                 flag: 1 means tables are allocated
                param_size              size of parameters in bytes:
                                        1, 2, 4 are the only choices
                param                   two-dimensional parameter array
                fitness                 array of fitness values for
                                        parameter sets
                min_fitness             minimum fitness value
                max_fitness             maximum fitness value
                avg_fitness             average fitness value
                stdev_fitness           standard deviation of fitness values
                min_fitness_index       index of minimum fitness in fitness
                                        array
                max_fitness_index       index of maximum fitness in fitness
                                        array
                normfitness             array of normalized fitness values
                cumulfitness            array of cumulative normalized
                                        fitness values
                preserve                number of best matches to
                                        retain unchanged
                crossover_type          type of crossover algorithm:
                                        0 = choose exactly <crossover_number>
                                            crossover points for all
                                            parameter sets that are being
                                            crossed over
                                        1 = choose an average of
                                            <crossover_number> crossover points
                                            for all parameter sets that are
                                            being crossed over
                crossover_probability   probability of crossover
                crossover_number        number of crossovers per parameter
                                        string
                crossover_break_param   flag: if 0, crossovers can't
                                        occur inside parameter values.
                mutation_probability    probability of mutation per bit
                use_gray_code           flag: if nonzero, use Gray code
                                        for encoding numbers (see below).
                do_restart              flag for whether to restart ever
                restart_after           restart after this many
                                        unproductive generations
                restart_count           count of unproductive generations
                old_fitness             old fitness value, that we have
                                        to do better than
                restart_thresh          need to get this much above
                                        old_fitness to not restart

    -------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:   ParamtableGA  [in src/param/paramtableGA.c]

    Classes:    param

    Actions:    Note: required arguments to actions are in <angle brackets>;
                      optional arguments are in [square brackets].

                CREATE          Creates the object (not invoked directly).

                TABCREATE <num_tables> <num_params>
                                Initializes the object for a given number of
                                parameter tables and a given number of
                                parameters.

                DELETE          Deletes all allocated memory.

                TABDELETE       Same as DELETE.

                INITSEARCH [random]
                                Initializes the search process. If "random" is
                                given as the argument then the first parameter
                                set is the original parameter set and all other
                                sets are chosen randomly within the given
                                ranges; if "random" is not given as the
                                argument then *all* parameter sets are chosen
                                randomly.

                RANDOMIZE       Randomizes parameters in tables.  Not
                                normally called directly.

                UPDATE_PARAMS   Chooses the next set of parameters to
                                simulate based on past results.
                                Calls the REPRODUCE, CROSSOVER, and MUTATE
                                actions.

                REPRODUCE       Performs fitness-proportional reproduction.
                                Not normally invoked directly.

                CROSSOVER       Performs crossing-over between parameter sets.
                                Not normally invoked directly.

                MUTATE          Mutates each bit of the parameter sets with
                                a fixed (low) probability.  Not normally
                                invoked directly.

                FITSTATS        Calculates statistics on the fitnesses of
                                the parameter sets currently stored in the
                                tables.

                RECENTER        Moves the center points of the parameter
                                ranges to correspond to the best parameter
                                set obtained so far.

                RESTART         Re-seeds the all the parameter tables with
                                random values in the allowed range, except
                                for the protected tables (see below).

                SAVE [filename]
                                Saves the object as a binary file.  If no
                                argument given, use the "filename" field
                                of the element.

                SAVEBEST <filename>
                                Saves the best parameter set to an ascii file.

                RESTORE [filename]
                                Restores the object from a binary file.  If no
                                argument given, use the "filename" field of the
                                element.

                RESTOREBEST     Restores a parameter set from a text file,
                                normally the best set so far obtained.  You
                                can use INITSEARCH without the "random"
                                option to keep this set and randomize the rest
                                of the table.

                CHECK           Runs a series of self-check diagnostics on this
                                object.

    Messages:   none

    -------------------------------------------------------------------------

    Notes:      This object stores parameter tables and calculates new tables
                to be simulated in a parameter search process using a
                simple genetic algorithm.  Here is a short description of the
                algorithm:

                The genetic algorithm (GA) method treats each parameter set as
                an individual in a large breeding population.  A new generation
                of the population is derived from the preceding generation by
                reproduction, crossing-over and mutation.  This is accomplished
                by discretizing the parameter values into bit strings and
                crossing-over and mutating the different bit strings.  A
                population of parameter sets is selected randomly from the
                parameter space and the fitness of each one is evaluated.
                Fitness values, unlike the match values calculated by functions
                like `spkcmp', are increasing for better and better models; a
                perfect parameter set would have infinite fitness.  Typically,
                you take the inverse (or some power of the inverse) of the
                value returned by `spkcmp' or `shape_match' to get the fitness
                value.

                Once fitnesses are calculated, the next generation is
                determined by reproducing the current generation, with each
                parameter set being chosen for reproduction in proportion to
                its fitness (fitness-proportional reproduction).  Then a fixed
                percentage of the resulting parameter sets are crossed over by
                choosing pairs of parameter sets at random, choosing one or
                more breakpoints within the bit string and exchanging the bit
                strings above the breakpoint (single-point recombination).
                Finally, each parameter set is subjected to mutation with a low
                probability per bit.  In this way, highly fit parameter sets
                are selected for and less fit sets are eliminated from the
                population over a series of generations.  Furthermore, the
                processes of crossing-over and recombination can generate new
                parameter combinations whose fitness is greater than that of
                its predecessors.

                Parameters can be stored as bit strings in one of two ways.  In
                the first way, the parameter range can be divided up into even
                increments and the position of the parameter within that range
                can be encoded by converting its relative position from a
                floating-point number into an integer, where 0 represents one
                end of the parameter range and the maximum possible integer
                (which depends on the param_size field) represents the other
                end.  Successive binary numbers represent successively higher
                parameter values.  This is specified by setting the
                "use_gray_code" field to 0.  If "use_gray_code" is 1, then the
                binary encoding is a Gray code encoding in which successive
                values are guaranteed to differ by one bit exactly.  This turns
                out to be mildly advantageous for genetic algorithms, so
                "use_gray_code" is set to 1 by default.  If you don't
                understand any of this, don't worry; just use the defaults and
                you'll be fine.

                By default, a crossover in a bit string can occur anywhere,
                even inside the bit string that represents a single parameter.
                Note that a crossover occurring inside a parameter is
                effectively mutating that parameter too.  If you don't want
                this, set the field "crossover_break_param" to 0.  This is the
                default as well.  In practice, this makes very little
                difference.

                There are two different kinds of crossover algorithms that can
                be used, which are determined by the field "crossover_type".
                In one case (crossover_type = 0), the field "crossover_number"
                represents the exact number of crossovers for each pair of
                parameter sets that is crossed over.  Thus, if crossover_number
                is 1, you have single-point crossovers; if crossover_number is
                2, you have two-point crossovers, etc.  In the other case
                (crossover_type = 1) the crossover_number field represents the
                *average* number of crossovers per pair of parameter sets.  In
                this case, there is a low probability for a crossover for each
                possible crossover location between a pair of parameter sets.
                This leads to a roughly Poisson distribution of crossovers for
                the parameter sets chosen.  The advantage of this is that you
                can get single, double, triple etc. crossovers within the same
                population, which can be useful in selecting for highly fit
                parameter sets.  The disadvantage is that some parameter sets
                which are meant to be crossed over will not be.  I suspect that
                having crossover_type set to 1 is advantageous, although I have
                no hard data to back me up.  It is the default.

                Note that the "mutation_probability" field is calculated per
                bit, not per parameter.  For each bit of each parameter table,
                a separate random number is generated to determine whether to
                mutate that bit.

                A non-standard (but not original) feature of the genetic
                algorithm implemented here is the ability to preserve the best
                tables unchanged from generation to generation.  This is very
                useful (in fact, I consider it essential) because GA parameter
                searches in genesis often use fairly small populations.  This
                means that genetic drift can easily cause the best parameter
                sets to be crossed-over and/or mutated out of existence.  To
                prevent this, the field "preserve" sets the number of best
                parameter tables to retain unchanged (unmutated,
                uncrossed-over) between generations.  For instance, if preserve
                is 5, the 5 best parameter tables will be copied unchanged from
                one generation to the next.  These tables can also participate
                in crossing-over and mutations, but you are guaranteed that one
                unaltered copy of each of the tables will be present in the
                next generation.  The default value of preserve is 1 (preserve
                only the best table); I recommend you leave it at that.

                Another non-standard feature of the genetic algorithm
                implemented here is that if no real progress has been achieved
                after a large number of generations, then the parameter tables
                can be reseeded (i.e. replaced with random values from the
                allowable parameter ranges for all parameters).  This is called
                "restarting", which is a bit of a misnomer since the best
                parameter tables are not altered.  This is controlled by the
                "do_restart" field, which is 1 if restarts are enabled and 0 if
                not (1 is the default).  If restarts are enabled, then the
                object keeps track of the best fitness value and the generation
                that it was first achieved at.  If, after a certain number of
                generations (set by the field "restart_after" which defaults to
                25), the best fitness has not improved substantially (set by
                the field "restart_thresh" which defaults to 1.0), then all the
                parameter tables will be replaced by random values except for
                the best table(s) (set by the preserve field as described
                above) which are preserved unaltered.  This can be useful if
                you get into a suboptimal region of parameter space which is
                difficult to get out of by crossing over and mutating, for
                whatever reason.

                If you are running genesis on a 64-bit machine (e.g. DEC
                alpha), then you may have to change the definitions of
                Param_short, Param_medium, and/or Param_long in
                src/param/param_struct.h.  All of these should be unsigned
                integer types.  Param_short should be one byte long,
                Param_medium should be two bytes long, and Param_long should be
                four bytes long.

                Note that this object only instantiates one kind of genetic
                algorithm.  There are as many variations of the genetic
                algorithm concept as there are people working on them.  Feel
                free to come up with your own variants and tell us all about
                them :-)

                Finally, if all the above has left you hopelessly confused,
                don't worry; just use the default values for all the fields and
                use the GA demo as a template, and you should do fine.  The
                options are mainly for experts and/or hackers to play with.

    Example:    See Scripts/param/GA for demo scripts.

See also: Parameter Search ( Param ), Paramtable , setsearch , initparamGA , getparamGA , setparamGA , paramtableBF , paramtableCG , paramtableSA , paramtableSS

## 26.44 paramtableSA

    Object Type:    paramtableSA

    Description:    This object implements a continuous version of simulated
                    annealing as part of a parameter search process, and also
                    stores the parameter tables and various bookkeeping
                    information relating to the parameter search process.

    Author:         Mike Vanier, Caltech

    -------------------------------------------------------------------------

    ELEMENT PARAMETERS

    Data structure: paramtableSA_type  [in src/param/param_struct.h]

    Size:       276 bytes (more when tables are loaded)

    Fields:     iteration_number        iteration number
                num_params              total number of parameters
                num_params_to_search    number of parameters to search over
                search                  array of flags:
                                        0 = don't search this parameter,
                                        1 = do search this parameter
                type                    type of parameter:
                                        0 = additive,
                                        1 = multiplicative
                center                  of parameter values in range
                range                   of parameter values
                min                     of parameter values
                max                     of parameter values
                label                   label of parameter,
                                        for documentation purposes only
                current                 array of parameter values
                                        to be simulated next
                current_match           match value of current parameter set
                                        being simulated
                best                    array of parameter values
                                        giving best match so far
                best_match              best match value
                new_best_match          flag: 1 if last match was the best so far
                done                    flag: 1 when the simulation is finished
                filename                where parameter information is
                                        stored/saved as a binary file
                alloced                 flag: 1 means tables are allocated
                iterations_per_temp     number of iterations per temperature level
                temperature             of annealing process
                inittemp                initial temperature of annealing process
                annealing_method        0 = manual,
                                        1 = linear decay,
                                        2 = exponential decay
                max_iterations          maximum number of iterations;
                                        for linear decay only
                annealing_rate          how fast the temperature drops;
                                        for proportional decay only
                testtemp                test for whether simulation is finished
                                        when temperature is below this value
                tolerance               if matches are within this distance
                                        of each other we're done
                stop_after              if best match hasn't changed after
                                        this many iterations then stop
                restart_every           call RESTART action every x iterations
                state                   of search process (0-5)
                simplex_init_noise      proportion of initial noise in
                                        simplex; a number in (0,1); default = 0
                simplex                 points on the simplex:
                                        (num_params + 1) x (num_params)
                simplex_match           match values for each point in the simplex
                scale                   "typical" length scale of starting points
                scalemod                modifiers of length scales in
                                        (num_params) dimensions; default: all = 1

    -------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:   ParamtableSA  [in src/param/paramtableSA.c]

    Classes:    param

    Actions:    Note: required arguments to actions are in <angle brackets>;
                      optional arguments are in [square brackets].

                CREATE      Creates the object (not invoked directly).

                TABCREATE <num_params>
                            Initializes the object for a given number of
                            parameters.

                DELETE      Deletes all allocated memory.

                TABDELETE   Same as DELETE.

                INITSEARCH [random]
                            Initializes the search process; sets up initial
                            simplex values (see below); if "random" is given as
                            the argument then the simplex is populated by
                            random points in the parameter space; otherwise one
                            point on the simplex represents the original model.

                EVALUATE <match>
                            Copies the match value into the current_match field.
                            If this match is the best match so far, this action
                            copies the current parameter set into the best
                            parameter set and the current_match field into the
                            best_match field.

                UPDATE_PARAMS
                            Chooses the next set of parameters to
                            simulate based on past results.

                RECENTER    Moves the center points of the parameter
                            ranges to correspond to the best parameter
                            set obtained so far.

                RESTART     Replaces the worst point on simplex with the
                            point corresponding to the best match.

                RESTART2    Like INITSEARCH, but preserves the best
                            match obtained so far.

                SAVE [filename]
                            Saves the object as a binary file.  If no
                            argument given, use the "filename" field
                            of the element.

                SAVEBEST <filename>
                            Save the best parameter set to an ascii file.

                RESTORE [filename]
                            Restores the object from a binary file.  If no
                            argument given, use the "filename" field of the
                            element.

                DISPLAY     Displays the best parameter set obtained so
                            far on stdout.

                DISPLAY2    Same as DISPLAY, but also prints the current
                            parameters.

                CHECK       Runs a series of self-check diagnostics on this
                            object.

    Messages:   none

    -------------------------------------------------------------------------

    Notes:      This object stores parameter tables and calculates new tables
                to be simulated in a parameter search process using a
                continuous-space simulated annealing algorithm.  The algorithm
                is taken from Press et. al., Numerical Recipes in C,
                2nd. edition, chapter 10, pp. 451-455.  This algorithm is much
                too complex to describe in detail here, but here is the
                two-second summary:

                The algorithm constructs a geometrical object called a simplex.
                If there are N parameters, the simplex has N+1 points
                (vertices) and conceptually occupies a volume in parameter
                space.  For instance, a triangle is a 3-simplex in 2 dimensions
                and a tetrahedron is a 4-simplex in three dimensions.
                Confused?  There's more :-) Each vertex of the simplex
                corresponds to a particular parameter set in parameter space.
                Each vertex's corresponding parameter set is simulated and its
                match value is calculated.  Depending on the state of the
                algorithm, several different things can happen, but typically
                the worst point is discarded and a new point is selected.  By
                itself, this describes a gradient-descent algorithm; the
                simulated annealing process comes in by adding noise to the
                match values based on a temperature parameter (the higher the
                temperature, the more noise).  At high temperatures, the
                simplex performs essentially a random walk in parameter space,
                but as the temperature lowers, the simplex spends more and more
                time exploring areas of the space which correspond to good
                match values.  As the temperature drops to zero, the simplex
                will perform a gradient descent in the parameter space and find
                a local minimum (which is hopefully close to the global minimum
                as well).

    Example:    See Scripts/param/SA for demo scripts.

See also: Parameter Search ( Param ), Paramtable , setsearch , initparamSA , paramtableBF , paramtableCG , paramtableGA , paramtableSS

## 26.45 paramtableSS

    Object Type:    paramtableSS

    Description:    This object implements a stochastic-search (SS)
                    algorithm as part of a parameter search process, and also
                    stores the parameter tables and various bookkeeping
                    information relating to the parameter search process.

    Author:         Mike Vanier, Caltech

    -------------------------------------------------------------------------

    ELEMENT PARAMETERS

    Data structure: paramtableSS_type  [in src/param/param_struct.h]

    Size:       184 bytes (more when tables are loaded)

    Fields:     iteration_number        iteration number
                num_params              total number of parameters
                search                  array of flags:
                                        0 = don't search this parameter,
                                        1 = do search this parameter
                type                    type of parameter:
                                        0 = additive,
                                        1 = multiplicative
                range                   of parameter values
                min                     of parameter values
                max                     of parameter values
                label                   label of parameter,
                                        for documentation purposes only
                current                 array of parameter values
                                        to be simulated next
                best                    array of parameter values
                                        giving best match so far
                best_match              best match value
                filename                where parameter information is
                                        stored/saved as a binary file
                alloced                 flag: 1 means tables are allocated
                round_number            number of expansion-contraction cycles
                                        we have completed
                variance                current variance of gaussian
                                        distribution
                minvariance                minimum variance of algorithm
                maxvariance                maximum variance of algorithm
                addvarscale                scaling factor for variances of
                                        additive parameters
                multvarscale            scaling factor for variances of
                                        multiplicative parameters
                contract                rate of variance contraction

    -------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:   ParamtableSS  [in src/param/paramtableSS.c]

    Classes:    param

    Actions:    Note: required arguments to actions are in <angle brackets>;
                      optional arguments are in [square brackets].

                CREATE      Creates the object (not invoked directly).

                TABCREATE <num_params>
                            Initializes the object for a given number of
                            parameters.

                DELETE      Deletes all allocated memory.

                TABDELETE   Same as DELETE.

                INITSEARCH  Initializes the search process.  Note that
                            TABCREATE must be called before calling this
                            action.  Also, the maxvariance field must
                            be set before calling this action.  This action
                            will start the search off at the parameters set
                            by the initparamSS function.

                RANDOMIZE   Randomizes parameters in tables; uses a uniform
                            distribution from (best - range, best + range).
                            Can be used after INITSEARCH to pick a random
                            point in the parameter space to start with.

                UPDATE_PARAMS
                            Chooses the next set of parameters to
                            simulate based on past results.

                ACCEPT <match>
                            Copies the match value to the best_match field
                            and the current parameters to the best fields.

                RECENTER    Recalculates the min and max values based on
                            the best and range values.  You might try doing
                            this after a best match is found to allow you
                            to search through a larger search space than
                            the initial limits would allow.

                SAVE [filename]
                            Saves the object as a binary file.  If no
                            argument given, use the "filename" field
                            of the element.

                SAVEBEST <filename>
                            Saves the best parameter set to an ascii file.

                RESTORE [filename]
                            Restores the object from a binary file.  If no
                            argument given, use the "filename" field of the
                            element.

                DISPLAY     Displays the best parameter set obtained so
                            far on stdout.

                CHECK       Runs a series of self-check diagnostics on this
                            object.

    Messages:   none

    -------------------------------------------------------------------------

    Notes:      This object stores parameter tables and calculates new tables
                to be simulated in a parameter search process using a
                stochastic-search algorithm.  Here is a brief description of
                this algorithm:

                A random starting point in parameter space is chosen.  New
                points are selected from a multidimensional Gaussian
                distribution centered on the starting point with a given
                (initially large) variance.  These new points are evaluated,
                and if one is found that is a better match than the previous
                best match, the Gaussian distribution is moved so that it is
                centered on the new (best) point.  In addition, the variance of
                the distribution decreases each iteration until it reaches some
                minimum value, at which time it is increased to the original
                value.  This constitutes one "round", and successive
                expansion-contraction rounds are performed for as long as the
                modeler wants.  In principle, choosing points from a
                distribution with a large variance will allow the modeler to
                search over large regions of parameter space, while choosing
                points from a distribution with a much smaller variance will
                allow the modeler to find locally optimal points in small
                regions of parameter space.

                In general, this algorithm performs more poorly than the
                simulated annealing and the genetic algorithm methods.  It was
                included mostly for comparison purposes, since some
                investigators have used this method for parameterizing neural
                models.  Nevertheless, we recommend that you skip this method
                entirely and instead use the GA or SA methods.

                You can modify the variance separately for additive and
                multiplicative parameters using the addvarscale and
                multvarscale fields.  This can be useful since the scales of
                additive and multiplicative parameters can be very different
                (e.g. of order 1.0 for Gbar scaling (multiplicative) and of
                order 0.001 (1 mV) for minf offsets (additive)).  Ideally you'd
                like to be able to modify the variance on a per-parameter basis
                (like the scalemod fields in paramtableSA) but we haven't
                gotten around to that yet.

    Example:    See Scripts/param/SS for demo scripts.

See also: Parameter Search ( Param ), Paramtable , setsearch , initparamSS , paramtableBF , paramtableCG , paramtableGA , paramtableSA

## 26.46 peristim

    Object Type:    peristim

    Description:    Generates a peristimulus spike histogram.

    Author:         E. De Schutter Caltech 8/91; embellished by D. Jaeger 8/92

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  new_peristim_type [in src/device/dev_struct.h]

    Size:           112 bytes

    Fields:         output        gives the most recent peristimulus value
                    threshold     voltage threshold for determining when a spike
                                  occurs
                    binwidth      time interval between bins
                    num_bins      number of table entries (bins)
                    trigger_mode  0 (free run) or 1 (triggered)
                    reset_mode    if 1 then bins will be emptied upon RESET
                    table         contains num_bins entries of histogram values
                    bin_index     index into the table, giving current bin
                                  (not set by user)
                    bin_steps     time steps since the start of the current bin
                                  (not set by user)
                    spiking       flag indicating spike in progress
                                  (not set by user)
                    allocated     flag indicating table has been allocated
                                  (not set by user)

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       NewPeriStimulusDistribution [in src/device/new_peristim.c]

    Classes:        device

    Actions:        CHECK  PROCESS  RESET

    Messages:       INVM      voltage   (Records a spike event when voltage first
                                        exceeds threshold.  The voltage must then
                                        fall below threshold before another spike
                                        event can be recorded.)

                    TRIGGER   state     (Starts recording spikes starting with the
                                        first bin, when state is non-zero.)

                    READTIME  time      (Adds a spike event to the table in the
                                        bin appropriate for the value of time.
                                        This could be used with a timetable,
                                        table, or asc_file element to retrieve
                                        spike times from a table or a file.)

                    INSPIKE   state     (Records a spike event whenever state
                                        exceeds threshold.  This message would be
                                        sent by an element, such as a spikegen,
                                        that represents a spike by a state that
                                        lasts for a single time step.)

    ------------------------------------------------------------------------------

    Notes:          In the example below, there are 1000 bins to process 1 second
                    of spike events, using a 1 msec bin width.  The typical use
                    would be to run the simulation, and send a trigger event to
                    the peristim element at 1 second intervals.  This would
                    normally coincide with the application of some stimulus to the
                    cell.

                    Each time the triggering device generates a triggering event
                    and stimulates the cell, the resulting action potentials will
                    be counted and placed in bins according to the time that they
                    occurred since the trigger event.  At the end of the run, the
                    histogram results can be retrieved with commands such as
                    "getfield /peristim table[{i}]", with i taking on values from
                    0 through nbins-1.

                    If trigger_mode is set to zero (free run mode), then spike
                    data is gathered continously, looping through all the bins and
                    then starting again in the first bin.  Otherwise, data after
                    the last bin is ignored until a TRIGGER message is received.
                    When a non-zero TRIGGER message is received, subseqent spike
                    events are binned starting with the the first bin, table[0].
                    This is true regardless of the value of trigger_mode.
                    Normally the source of the TRIGGER message is an element, such
                    as a spikegen, that sends the value of a state field that
                    lasts for a single time step.

    Example:

    float binwidth = 0.001; int nbins = 1000
    create peristim /peristim
    setfield /peristim threshold 0 num_bins {nbins}  binwidth {binwidth}
    setfield /peristim trigger_mode 1

    // Assume that /trigger_device generates spike events in its state field
    addmsg /trigger_device  /peristim TRIGGER state
    // Assume a cell, generating action potentials in the soma compartment
    addmsg /cell/soma /peristim INVM Vm

See also: interspike

## 26.47 playback

    Object Type:    playback

    Description:    update a pre-filled buffer

    Author:         M. Wilson, Caltech (6/88)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  playback_type  [in src/buffer/buf_struct.h]

    Size:           100 bytes

    Fields:
                    tmin
                    size
                    current
                    start
                    end
                    event_size
                    event
                    state

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       PlaybackBuffer  [in src/buffer/playback.c]

    Classes:        buffer

    Actions:        PROCESS
                    RESET
                    COPY BufferCopy
                    CREATE BufferCreate

    Messages:       none

    ------------------------------------------------------------------------------

    Notes:          The putevent command may be used to fill the buffer

    Example:

        create playback /test
        putevent /test 10 10.0 20 0.0 30 30.0 40 0.0 50 50.0 60 0.0
        create xform /testform
        create xgraph /testform/graph
        addmsg /test /testform/graph PLOT state *playback *blue
        xshow /testform
        reset
        step 100

See also: putevent

## 26.48 pool

    Object Type:    pool

    Description:    Pool of molecules involved in chemical reactions and
                    transport between cellular compartments. Keeps track of the
                    number of molecules resulting from forward and backward
                    reactions. Uses mean-rate theory which assumes large numbers
                    of molecules, not probabilities of transitions of individual
                    molecules.

                    Does Michaelis-Menten enzyme kinetics when hooked to the 'enz'
                    object, and standard kinetic reactions with the 'reac' object.
                    The MM scheme is modeled as:
                                            k1              k3
                    Substrate + Enzyme  <-----> EnzComplex ----> Enz + Prd
                                            k2
                    The generic reaction scheme is:
                                            kf
                    Substrate1 + S2 + ..  <----> Prd1 + Prd2 + ...
                                            kb

                    Note that vol, n and Co are interdependent. vol is never
                    changed except by the user or by messages. n changes if Co is
                    changed.  Co changes if either vol or n is changed.  Volume is
                    typically scaled by the Avogadro number, so that Co is in
                    convenient units such as micromolar.

                    During integration, all calculations are done in terms of
                    n, and, where needed, vol. Co is calculated as n / vol on
                    each timestep.

    Author:         U. S. Bhalla, National Centre for Biological Sciences,
                    Bangalore, India. (1993).

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  pool_type  [in src/kinetics/kin_struct.h]

    Size:           bytes

    Fields:         Co                      Concentration of molecule. Calculated
                                            from 'n' as n/vol.
                    CoInit                  Initial concentration of molecule.
                                            Co gets set to this value on RESET.
                    CoTotal                 Total concentration of molecule. Used
                                            when applying conservation rules.
                    CoRemaining             CoTotal - Co.
                    n                       Number of molecules. This is the
                                            value used for all calcultions.
                    nInit                   Initial number of molecules.
                                            'n 'gets set to this value on RESET.
                    nTotal                  Total number of molecules. Used
                                            when applying conservation rules.
                    nRemaining              nTotal - n
                    nMin                    Minimum allowed number of molecules.
                                            Normally zero.
                    vol                     Volume occupied by pool. Often involves
                                            extra units so as to have direct
                                            conversion from 'n' to some sensible
                                            units of Co, such as micromolar.
                    slave_enable            Flag used to control buffering and
                                            other overrides. Values:
                                            1 - Obey slave message, representing n
                                            2 - Obey slave message, representing Co
                                            4 - Buffering on: n is set to nInit,
                                                    Co to CoInit, every timestep.
                                            See below for details.
                    keepconc                Flag determining whether to change
                                            concs or n when volume changes
                    consv_flag              Internal flag keeping track of presence
                                            of CONSERVE and SUMTOTAL msgs

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       PoolFunc  [in src/kinetics/pool.c]

    Classes:        segment, concentration

    Actions:        CREATE
                    PROCESS
                    RESET
                    SET

    Messages:       REAC            A B     [A is increment to n,
                                            B is decrement to n,
                                            where n is number of molecules in pool.
                                            This message is used for hooking up
                                            all reactions and enzymes.]
                    MM_PRD          A       [increment n by A. This message is
                                            used for the product of enzymes.
                                            We assume it is irreversible, so there
                                            is no B term]
                    SLAVE           number  [Sets n or Co to this command number
                                            depending on the slave_enable status,
                                            described below. This message is
                                            used to make concentrations in the pool
                                            follow an external signal.]
                    REMAINING       n       [decrement to nRemaining]
                    CONSERVE        n nInit [This message is used for setting up
                                            conservation relationships.
                                            n from all derived molecules is summed
                                            to do the conservation. nInit is used
                                            during RESET to calculate the total
                                            number of molecules. See notes.]
                    VOL             vol     [volume of pool]
                    SUMTOTAL        n nInit [This message is used to make a pool
                                            whose n is the sum of that of several
                                            other pools. nInit is used at
                                            RESET to get the initial levels]

    ------------------------------------------------------------------------------

    Notes:

            The pool has numerous extras used in practical simulations.
            Most of these are readily accessed from within kinetikit, which is
            the recommended way of developing kinetic simulations. For
            completeness, here is a list of features of the pool:

            1. Buffering. When slave_enable is set to 4, then all the pool
            does is assign n to nInit and Co to CoInit every timestep.

            2. Following an external signal. This works when the SLAVE
            message is passing in the external number. if slave_enable is
            1 then the external number represents n. If it is 2 the
            external number represents Co.

            3. Conservation relationships. In some cases it helps stability
            and accuracy to apply explicit conservation relationships,
            rather than rely on the implicit ones that arise from the
            numerical integrations. Warning: in some cases explicit
            conservation relationships actually worsen stability ! So
            try it for each case before relying on it. Conservation
            relationships are set up in two phases:
            - identify the pool whose value you want to be calculated
            from conservation.
            - Send CONSERVE messages from all pools to which this molecule
            gets converted. Be sure you have found ALL the pools: this is
            a very common source of error. For example, you may need to
            send a CONSERVE message from enzyme intermediates, which
            are represented by 'enz' objects.

            4. Summation. In some cases the final amount of an active
            species recieves contributions from several independent pathways.
            An example is an enzyme whose active site always has the same
            activity regardless of the means of activation. The total amount
            of the active enzyme could then be represented as the sum of
            the active forms from several independent activation pathways.
            The SUMTOTAL message is used for such cases.

            5. Calculating the amount of the molecule that has reacted, and is
            no longer in this pool.
            The nRemaining field plus the REMAINING message are used for this.
            Again, the REMAINING message must come in from all other molecules
            into which this pool may convert. This is mainly useful for checking
            accuracy and stability.

            The combination of pools, reacs, and tables is capable in principle of
            implementing very complicated ODEs, not restricted to
            chemical reactions. The pools represent the variables, reacs represent
            processes increasing and decreasing variables, and the tables can
            twiddle the rate constants of the reacs according to arbitrary
            complicated functions. It should be stressed that this is an
            extremely inefficient but reasonably general way of doing this.

    Example:

    Message setup between pools, reacs and enzymes:

            For the reaction

                      kf
            2X + Y <======> Z
                      kb

            we would have 3 pools, and 1 reac. The messaging would be as follows:

                    addmsg  X       reac    SUBSTRATE       n
                    addmsg  X       reac    SUBSTRATE       n
                    addmsg  reac    X       REAC            A B
                    addmsg  reac    X       REAC            A B

                    addmsg  Y       reac    SUBSTRATE n
                    addmsg  reac    Y       REAC            A B

                    addmsg  Z       reac    SUBSTRATE       n
                    addmsg  reac    Z       REAC            B A

            Some points about this messaging scheme:
            1. We need N sets of SUBSTRATE and REAC messages between a pool and
            a reac, where the order of the reaction for that pool is N.
            2. The Z pool, which is the product, has the A and B state variables
            reversed in the message. This is because any decrease in X or Y is an
            _increase_ in Z.

            Setting up the enzymatic reaction:

                    Sub + X --> Prd

            We normally put the enzyme site enz as a child of the pool which
            represents the enzyme.

                    create enz X/enz

            A given pool can have any number of enzyme
            'sites'. This is required when an enzyme has different levels
            of activity for different substrates, as each of the enzyme 'sites'
            can then be given different rates. The messaging would look like this:

                    addmsg  X       X/enz   ENZYME          n
                    addmsg  X/enz   X       REAC            eA B

                    addmsg  sub     X/enz   SUBSTRATE       n
                    addmsg  X/enz   sub     REAC            sA B

                    addmsg  X/enz   prd     MM_PRD          pA

            Some points about this messaging scheme:
            1. In the irreversible Michaelis-Menten model we are using, the
            enzyme cannot reduce the level of the product. So there is only one
            term required in the outgoing message, and no incoming message from
            the product to the enzyem
            2. If this scheme doesn't suit you, you can always build better
            enzyme models using combinations of reacs and intermediate pools.

## 26.49 pulsegen

    Object Type:    pulsegen

    Description:    General purpose pulse generator

    Author:         M. Nelson, Caltech (4/89)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  pulsegen_type  [in src/user/user_struct.h]

    Size:           120 bytes

    Fields:         level1          level of pulse1
                    width1          width of pulse1
                    delay1          delay of pulse1
                                      (wrt ext. input - trig or gate mode)
                                      (wrt pulse2     - free run mode)
                    level2          level of pulse2
                    width2          width of pulse2
                    delay2          delay of pulse2 (wrt pulse1)
                    baselevel       baseline level
                    trig_mode       flag: 0=free run, 1=ext. trig, 2=ext. gate
                    output          output
                    trig_time       internal state variable
                    previous_input  internal state variable

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       PulseGen  [in src/user/pulsegen.c]

    Classes:        device

    Actions:        PROCESS  RESET

    Messages:       INPUT "gate/trig"   (0 = low, non-0 = high)
                    LEVEL pulse# level
                    WIDTH pulse# width
                    DELAY pulse# delay

    ------------------------------------------------------------------------------

    Notes:

    This device can generate a variety of pulse patterns:  single pulses, double
    pulses (each with its own level and width), and pulse trains (of single
    pulses or pairs).  It can be triggered, gated, or allowed to free run.

    In combination with a spikegen object, it can be used to generate bursts of
    spikes for use as synaptic input.  (See Scripts/neuron/inputs.g.)

    The following diagram illustrates the relationships between the fields:

                          +-----------------+ level1
      trigger             |                 |
         |                |                 |        +-------------+ level2
         |                |                 |        |             |
         V                |                 |        |             |
         +--- baselevel --+                 +--------+             +----

         <---- delay1 ----><---- width1 ---->         <-- width2 -->
                           <--------- delay2 -------->
    If delay2 <= width1, then level2 starts imediately after the end of the
    pulse at level1.  This means that if delay2, width2 and level2 are not set
    and remain at their default values of 0, there will be only one type of
    pulse.  It will repeat after a time delay1 after the end of the pulse
    (free run mode) or a time delay1 after it is triggered (trigger or gate
    mode).

    Example:        Scripts/examples/pulsegen/PulseGenDemo.g

    See also:

## 26.50 randomspike

    Object Type:    randomspike

    Description:    place a random event into the buffer

    Author:         M. Wilson, Caltech 6/88, Dave Bilitch 1/94

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  Randomspike_type  [src/newconn/newconn_struct.h]

    Size:           100 bytes

    Fields:         min_amp         minimum amplitude of event
                    max_amp         maximum amplitude of event
                    rate            rate of generation of events
                    reset           flag for whether to reset after each event
                    reset_value     what to reset state to
                    state           current state of object
                    abs_refract     minimum time between events

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       RandomEvent  [in src/newconn/randomspike.c]

    Classes:        buffer

    Actions:        INIT
                    RESET
                    PROCESS

    Messages:       RATE    rate
                    MINMAX  min max

    ------------------------------------------------------------------------------

    Notes:          Generates a time series of events at a rate given by the rate
                    parameter. The probability of an event for a single time step
                    is given by rate*dt where dt is the clock rate of the
                    element.  However, no event will be generated at a time less
                    than abs_refract.  When an event has been generated, the
                    amplitude of the event is a random variable uniformly
                    distributed between min_amp and max_amp.  The state field
                    has the value of the event amplitude if an event has been
                    generated. If an event is not generated then the value of
                    the state field depends on the reset field.  If reset is
                    non-zero then the state is takes on the value given in
                    reset_value. Otherwise the state will behave like a latch
                    containing the amplitude of the previous event.

    Example:        Scripts/tutorials/tutorial4.g

    See also:

## 26.51 reac

    Object Type:    reac

    Description:    Chemical reaction object. Works with pools to provide kf and
                    kb. Reacs calculate the changes in concs for each pool hooked
                    into them. The pool is responsible for adding up all the
                    up and down changes resulting from various reactions it is
                    involved in. Each reac can handle any number of substrates
                    and products, though reactions of order greater than 2 are
                    rare. Any number of reacs can be hooked up to a given pool.

                    The generic reaction scheme is:
                                            kf
                    Substrate1 + S2 + ..  <----> Prd1 + Prd2 + ...
                                            kb

    Author:         U. S. Bhalla, National Centre for Biological Sciences,
                    Bangalore, India. (1996).

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  reac_type  [in src/kinetics/kin_struct.h]

    Size:           bytes

    Fields:         kf                      Forward rate constant. Units depend
                                            on the order of the reaction, ie,
                                            the number of molecules on the
                                            left hand side. First
                                            order is sec^-1, second order is
                                            sec^-1.num^-1, etc.
                    kb                      Backward rate constant. Units depend
                                            on the number of molecules on the
                                            right hand side, in a similar way.
                    A, B                    Internal state variables, used to
                                            communicate with pools. A represents
                                            increase in the pool n, B is the
                                            decrease.

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       ReacFunc  [in src/kinetics/reac.c]

    Classes:        segment

    Actions:        PROCESS
                    RESET
                    SET

    Messages:       SUBSTRATE       n       [Number of molecules in substrate pool]
                    PRODUCT         n       [Number of molecules in product pool]
                    KF              kf      [Forward rate constant]
                    KB              kb      [Backward rate constant]

    ------------------------------------------------------------------------------

    Notes:          See pool documentation for complete example.

    ------------------------------------------------------------------------------

## 26.52 receptor

    Object Type:    receptor

    Description:    takes the weighted sum of up to 10 odors to determine membrane
                    voltage and spike rates.

    Author:         U. S. Bhalla, Caltech (1/90)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  olf_receptor_type  [in src/olf/olf_struct.h]

    Size:           144 bytes

    Fields:         response        table of weights to apply to incoming odor
                                    messages

                    Vmin            minimum bound of membrane potential
                    Vmax            maximum bound of membrane potential
                    gain            scaling factor on input odors
                    Vm              calculated current membrane potential

                    min_rate        minimum bound of spike firing rate
                    max_rate        maximum bound of spike firing rate
                    state           spike flag; will be 1 if receptor has fired,
                                    0 otherwise

                    activation      not used
                    transfer_form   not used

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       OlfReceptor  [in src/olf/receptor.c]

    Classes:        segment

    Actions:        INIT
                    PROCESS
                    RESET
                    RECALC
                    CHECK
                    SAVE2
                    RESTORE2

    Messages:       ODOR strength           strength of odor
                    GAIN sensitivity        sets gain field in element; globally
                                            scales sensitivity of receptor to odors

    ------------------------------------------------------------------------------

    Notes:

                    The receptor is used as an olfactory receptor, taking a
                    weighted sum of up to 10 ODOR messages, to represent
                    components of olfactory stimulus. The weights are defined in
                    an array on the element, this enables one to construct any
                    combination of odor sensitivities on the neuron.  The output
                    is both in the form of a membrane potential and a spike.

                    The receptor element takes the weighted sum of up to 10 odors
                    to determine membrane voltage and spike rates. The odor inputs
                    arrive as messages. These can be scaled by the gain field
                    which can also be set by messages.  Each odor is weighted by
                    the appropriate entry in the response table.

                    response - table of 10 weights for incoming odor messages
                    (messages are multiplied by weights before being scaled by
                    gain and summed to get Vm).

                    Vm is meant to be the equivalent of membrane potential,
                    calculated by:

                      sum [from i=0 to i=nodors-1] of odor_i x response[i] x gain

                    (always bounded by Vmin and Vmax). There is no time course
                    involved in Vm, it is simply recalculated every time step.

                    state is calculated in a probabilistic manner every time step
                    as follows:

                      state is set to 1 if:

                        min_rate + Vm * (max_rate - min_rate)  >
                           a random number (calculated every time step)
                             between 0 and 1

                    State is meant to be used as the origin of a message to an
                    axon, for connecting to other neurons.

                    This element had been largely superseded by the receptor2
                    element, which is is a much more realistic version of an
                    olfactory receptor protein-membrane channel complex.
    Example:

See also: receptor2

## 26.53 receptor2

    Object Type:    receptor2

    Description:    Olfactory Receptor. Takes weighted sum of any number of
                    messages to get the activation for a channel. The messages
                    represent components of an olfactory stimulus.

    Author:         U. S. Bhalla, Caltech (1/90)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  olf_receptor2_type  [in src/olf/olf_struct.h]

    Size:           172 bytes

    Fields:         response        table of weights to be set for each odor
                    nodors          number of odors
                    tau1            open time constant of channel
                    tau2            close time constant of channel
                    gmax            peak conductance
                    Ik              channel current
                    modulation      scale all odors; gain control on responses
                    Gk              resulting channel conductance
                    Ek              equilibrium potential

                    activation      channel activation calculated from incoming
                                    messages

                    allocated       internal flag
                    X               state variable for time response
                    Y               state variable for time response
                    xconst1         internal variable, not normally set by user
                    xconst2         internal variable, not normally set by user
                    yconst1         internal variable, not normally set by user
                    yconst2         internal variable, not normally set by user
                    norm            internal variable, not normally set by user

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       OlfReceptor2  [in src/olf/receptor2.c]

    Classes:        segment
                    channel

    Actions:        INIT
                    PROCESS
                    RESET
                    RECALC
                    SET
                    CHECK
                    SAVE2
                    RESTORE2

    Messages:       VOLTAGE Vm              usual message from parent compartment
                                            to channel to tell what the membrane
                                            potential is

                    ODOR activation odor_no describes odor; activation = strength
                                            of particular odor; odor_no = integer
                                            specifying response table index having
                                            weight for that odor

                    MODULATION modulation   sets modulation field; provides means
                                            for scaling the overall sensitivity of
                                            receptor up or down

    ------------------------------------------------------------------------------

    Notes:          Does a weighted sum of odors to get activation
                    of a channel with usual conductance properties.

                    The receptor2 element is a much more realistic version of an
                    olfactory receptor protein-membrane channel complex than the
                    receptor element. The receptor2 is a channel similar to the
                    synchan element, except that this channel responds to odors
                    via ODOR messages, and does not have synapses with weights and
                    delays.

                    Any number of odor messages may be sent to the receptor2.
                    They are scaled by the weights in the response table, and then
                    their summed effects act as the activation of the channel. The
                    channel has the usual time courses and conductance fields, and
                    can be incorporated into membrane compartments just like
                    ordinary synaptic channels.

    Example:        Scripts/neurokit/prototypes/newbulbchan.g

                    Here is a section of script that puts random numbers from 0
                    to 1 in each of the entries of the response array. You will
                    need to set the other fields (especially modulation) to
                    sensible values, of course.

                    create receptor2 /foo
                    setfield /foo nodors 10
                    int i
                    for (i = 0; i < 10; i = i + 1)
                        setfield /foo response[{i}] {rand 0 1}
                    end

See also: receptor

## 26.54 script_out

    Object Type:    script_out

    Description:    executes a script command at each step of a simulation

    Author:         M. Wilson, Caltech (2/89)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  script_output_type  [in src/out/out_struct.h]

    Size:           80 bytes

    Fields:         command     Command string (function name + optional args)
                    argc        Number of arguments, including function name
                    argv        array of arguments (argv[0] = function name)

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       ScriptOutput  [in src/out/out_script.c]

    Classes:        output

    Actions:        PROCESS
                    SET
                    RESET
                    RECALC

    Messages:       none

    ------------------------------------------------------------------------------

    Notes:

    The command field of a script_out element is used to hold the name of a script
    language function which will be executed at every step of the clock used by
    the script_out.  This will normally by clock 0, the default simulation clock.
    As the definition of this script function will be interpreted by the SLI,
    execution will be much slower than with the compiled PROCESS action of other
    predefined GENESIS objects.  For that reason it is best to assign a slower
    clock to the script_out element.

    If the command field is set to a string consisting of the function name
    plus one or more optional arguments, then argv[{n}] will contain the
    nth argument.  Extended objects provide a much more flexible alternative
    to the script_out object.

    Example:

    // spikebeep.g - illustrate the use of the script_out element to beep
    // whenever a spike is produced  (assuming your terminal window
    // beeps when a ctrl-G is echoed).
    // Include this file at the end of Scripts/tutorials/tutorial4.g

    // The script_out element checks for a spike at every simulation step
    create script_out /catchspike
    setfield /catchspike command "checkspike"
    useclock /catchspike 0

    function checkspike
            if ({getfield /cell/soma/spike state} != 0)
                   echo {chr 7} -nonewline
            end
    end
    reset

See also: Extended , Scripts/orient_tut/ret_input.g

## 26.55 sigmoid

    Object Type:    sigmoid

    Description:

    Computes the sigmoidal transformation of the input and places the result in
    'state'.  The equation being applied is

            state = amplitude*(tanh(gain*(input - thresh)) + 1)/2.0

    This gives a ``squashing'' function which is commonly used in connectionist
    models as an approximation to the relation between the amount of synaptic
    input to a cell and its firing rate.

    Author:         M. Wilson, Caltech (6/88)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    Data Structure: sigmoid_type  [in src/buffer/buf_struct.h]

    Size:           116 bytes

    Fields:         thresh
                    amplitude
                    input
                    state
                    gain

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       SigmoidEvent  [in src/buffer/sigmoid.c]

    Classes:        buffer
                    segment

    Actions:        PROCESS RESET COPY CREATE

    Messages:       INPUT   input
                    THRESH  threshold
                    GAIN    gain
                    AMP     amplitude

    ------------------------------------------------------------------------------

    Notes:

    Example:        Scripts/examples/sigmoid.

    See also:

## 26.56 spikegen

    Object Type:    spikegen

    Description:    Performs threshold spike discrimination.
                    Generates an impulse each time an input crosses the
                    spike threshold at a maximal rate set by abs_refract.

    Author:         M. Wilson, Caltech 6/88, ave Bilitch 1/94

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  Spikegen_type  [in src/newconn/newconn_struct.h]

    Size:           88 bytes

    Fields:
                    state           current spiking state
                    thresh          threshold level for spike generation
                    abs_refract     minimum interval between spikes
                    output_amp      spike event amplitude

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       SpikeEvent  [in src/newconn/spikegen.c]

    Class:          spiking

    Actions:        RESET                   clear the history buffer, removing
                                            any existing events
                    PROCESS                 determine whether a spike is
                                            generated, set the state to 0 for no
                                            spike or to output_amp for a spike
                    CHECK                   make sure there is a source of input
                                            to drive spike generation
                    RESTORE2                called by the restore command
                    SAVE2                   called by the save command

    Messages:       INPUT  input
                    THRESH threshold

    ------------------------------------------------------------------------------

    Notes:          Simulates a thresholded spike generation mechanism. When the
                    input exceeds the specified threshold and there has not been a
                    spike for at least the interval specified by 'abs_refract' a
                    single spike event is generated with amplitude given by
                    'output_amp'.  The spikegen typically receives action
                    potentials from a compartment via the INPUT message and
                    sends spike events to a synchan or synchan2 element with
                    a SPIKE message.

    Example:        Scripts/tutorials/tutorial4.g

## 26.57 spikehistory

    Object Type:    spikehistory

    Description:

    The spikehistory object is used to record into an ASCII file the spikes
    produced by a neuron or by a network of neurons.  When the network is large or
    when it is simulated during several seconds, it becomes impractical to record
    the complete membrane potential traces of the constituent neurons through
    messagess to an asc_file or to a graph element. In addition, one is usually
    only interested in the spike responses, which could be compared with
    "extracellularly" recorded spike potentials.

    The occurrence of a spike must be sent from a spikegen element to the
    spikehistory element through a SPIKESAVE message, which is established with
    the usual addmsg command (no parameters needed). A SPIKESAVE message is an
    active message. This means that a nonzero state field of a spikegen element
    actively triggers the execution of the EVENT action of the spikehistory
    element. (Note that the spikehistory object does not have the usual PROCESS
    action, normally executed on each time step.) This EVENT action consists of
    adding a line to the ASCII file. The first item on each line is the
    identification of the spikegen element that sent the spike. Depending on the
    initialization value of the ident_toggle field of the spikehistory element,
    this item is either the index assigned to the spikegen element (or to its
    parents) in a map created with createmap (ident_toggle 0) or the full path
    name of the spikegen element (ident_toggle 1).  Each EVENT action triggered by
    a SPIKESAVE message adds another line.

    Author:         R. Maex, UI Antwerp (1/96) (reinoud@bbf.uia.ac.be)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  spikehistory_type  [in src/out/out_struct.h]

    Size:           88 bytes

    Fields:
                    filename        data file name to be written
                    fp              data file pointer
                    is_open         flag: is file currently open?
                    initialize      flag: has file been initialized?
                    leave_open      flag: leave file open? 1 leaves the file open
                                    all the time so you can write on it whenever
                                    you want (a good idea if the file is used
                                    frequently, but there is a limit to number of
                                    files which can be left open any any time);
                                    0 closes the file after every write to it
                                    (only useful if you have more than 30 files;
                                    this is slow)
                    append          flag: append data after resetting?
                    flush           flag: flush data to disk at each interval?
                                    1 forces program to send data to the disk at
                                    once and not store it in a buffer (slow but
                                    secure); 0 (default) writes data in a buffer
                                    (fast)
                    ident_toggle    flag: if zero,  output as an identifier
                                    the map index of the sending spikegen element;
                                    if non-zero, output the full path name
                                    of the sending spikegen element

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       SpikeHistory  [in src/out/spike_history.c]

    Classes:        output

    Actions:        RESET  EVENT  SAVE

    Messages:       SPIKESAVE

    ------------------------------------------------------------------------------

    Notes:

    When indices are used as sender specification, it is required that the
    sequence in which the SPIKESAVE messages are established to the spikehistory
    element be the same as the order of the sender elements in the map of sender
    elements. Indeed, the SpikeHistory EVENT action loops through the MsgIn list
    to find the sender element. It assumes that this loop index is the same as the
    index of the sender in the afferent map. This requires of course also that
    every map has its private spikehistory element!

    If the filename field is not set, the output file will be given the
    same name as the element which is created from the asc_file object.
    For binary data, use disk_out.

    Example with index specification:

       str cellpath = "/Granule"
    // read cell data from .p file
       readcell Gran1M0.p {cellpath}

    // add a spikegen object
       create spikegen {cellpath}/soma/spike
       setfield {cellpath}/soma/spike thresh -0.02 \
                                      abs_refract 0.005 \
                                      output_amp 1
       addmsg {cellpath}/soma {cellpath}/soma/spike INPUT Vm

    // create a map
       create neutral /granule_cell_layer
       createmap {cellpath} /granule_cell_layer \
                 20 1 -delta 1.0 0.0 -origin 0.0 0.0

    // create a spikehistory element
       create spikehistory granule_cells.history
       setfield granule_cells.history ident_toggle 0 \ // index specification
                                      filename "granule_cells.spikes" \
                                      initialize 1 leave_open 1 flush 1

    // add messages from the spikegen elements to the spikehistory element
       addmsg /granule_cell_layer/Granule[]/soma/spike \
              granule_cells.history SPIKESAVE

See also: asc_file , spikegen

## 26.58 symcompartment

    Object Type:    symcompartment

    Description:    Axially symmetric compartment. Ra is divided into
                    two equal components across the compartment.

    Author:         M. Wilson, Caltech (6/88)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  symcompartment_type  [in src/segment/seg_struct.h]

    Size:           132 bytes

    Fields:         Rm              total membrane resistance
                    Cm              total membrane capacitance
                    Em              membrane resting potential
                    Ra              axial resistance
                    inject          injected current in membrane
                    dia             compartment diameter
                    len             compartment length
                    Vm              voltage across the membrane
                    previous_state  Vm at previous time step
                    Im              approximation to the total membrane current
                    initVm          initial value to set Vm on reset

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       SymCompartment  [in src/segment/symcompartment.c]

    Classes:        segment
                    membrane

    Actions:        INIT            assign previous_state = Vm
                    PROCESS         update Vm, calculate Im
                    RESET           assign Vm = Em, set internal constants
                                    depending on the types of incoming messages.
                    CHECK           make sure Rm>0, Cm>0, Ra>0
                    SAVE2
                    RESTORE2

    Messages:       CHANNEL Gk Ek   delivers the conductance and equilibrium
                                    potential of channel within the compartment
                    INJECT inject   sets the inject field to the message value
                    EREST Em        sets the Em  field to the message value

                    CONNECTHEAD   Ra Vm  used to connect to the child compartment
                    CONNECTTAIL   Ra Vm  used to connect to the parent compartment
                    CONNECTCROSS  Ra Vm  used to cross-connect the first
                                         compartments after a  binary or multiple
                                         branch.
                    RAXIAL Ra Vm    alias for CONNECTTAIL
                    AXIAL Ra Vm     alias for CONNECTHEAD; note that for the
                                    asymmetric compartment, AXIAL only receives Vm.
                    RAXIAL2 Ra Vm   alias for CONNECTHEAD
                    RAXIALC Ra Vm   alias for CONNECTCROSS

    ------------------------------------------------------------------------------

    Notes:          Like the compartment object, the symcompartment simulates
                    a section of passive membrane or cable. The potential across
                    the membrane is given by Vm. There is a leakage path for
                    current through the resistance Rm. This resistance is in
                    series with a leakage battery Em, and there is a membrane
                    capacitance in parallel with Rm and Em. This compartment can
                    be coupled to other compartments with an axial resistance Ra,
                    which is divided into two pieces of resistance Ra/2 on either
                    side of the point having the potential Vm.  In most respects,
                    the symcompartment is similar to the asymetric compartment
                    object, and its use is more fully described in the
                    documentation for compartment.  However, the division of Ra
                    requires different messages to be used when linking
                    symcompartments.

                    For linear chains of symmetric compartments, all of the
                    connection messages are equivalent, and all compartments may
                    be linked by exchanging RAXIAL messages.  However, for
                    branched structures, the the incoming current must be
                    calculated differently, depending on whether it is from a
                    parent, child, or connected sibling in the tree of
                    compartments, using the messages described above.  Because of
                    this added complexity, it is best to use the readcell routine
                    with a cell parameter file when constructing cells with
                    symcompartments.  This will link the compartments with the
                    proper messages.

                    Prior to GENESIS version 2.2, the CONNECTSPHERE message was
                    use to connect a cylinder to a sphere, assuming that all the
                    dendrites are distributed perfectly over the soma/sphere.
                    This is now performed automatically by readcell, and this
                    message is no longer needed.  Using CONNECTHEAD or CONNECTTAIL
                    instead connects all denrites to one point on the soma/sphere.

                    A note on spherical compartments by Erik De Schutter:  If you
                    use readcell, spherical compartments will have zero length (a
                    GENESIS convention) and the Ra field will NOT be zero.  This
                    means that the (small) resistive component of the spherical
                    compartment will be used in computing the axial current
                    between the spherical soma and dendrite.  This is very
                    different from the asymmetric case (where the connections are
                    usually arranged to go through the larger Ra of the adjacent
                    dendritic cylinder instead of the small soma Ra).  This may
                    look strange for the case of a single dendrite.  It makes more
                    sense in the case of an apical and basal dendrite: if synaptic
                    current flows from one to the other, one imagines that the
                    soma has some effect.  Note also that whether you use a
                    CONNECTCROSS message between cylindrical compartments onto the
                    same sphere really should depend on their topological
                    relation.  For example, basal dendrites should probably be
                    cross-connected to each other but not to an apical one.
                    readcell will issue all the possible CONNECTCROSS messages
                    automatically, so you may want to delete some which are not
                    consistent with your intended topology.

                    The compartment Im is the sum of axial currents and injected
                    current only.  The (transmembrane) channel currents or the
                    leakage current are not included.  For a multicompartment
                    cell, under a quasistatic approximation (C*dV/dt is small), Im
                    is approximately equal to the sum of the channel and leakage
                    currents, due to charge conservation.  This approximation is
                    used in the efield object (see efield.doc) to allow Im to be
                    used to calculate external field potentials.  The exception to
                    this is when Im is calculated with hsolve in chanmode 4.  In
                    that case, Im is directly calculated as the sum of the channel
                    currents and leakage current though Rm.

                    As of GENESIS version 2.2, symcompartments may be used
                    with the hsolve method, allowing the use of fast implicit
                    numerical integration methods.

    Example:        Use the showmsg command to examine the messages to and from
                    /CA3/soma, /CA3/apical_10, /CA3/basal_8, etc. in the traub91
                    simulation.

See also: compartment , readcell

## 26.59 synchan

    Object Type:    synchan

    Description:    Synaptically activated channel.

    Author:         Mike Vanier 11/94

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  Synchan_type  [in src/newconn/newconn_struct.h]

    Size:           200 bytes

    Fields:         activation         driving force (transmitter) for channel
                                       conductance
                    Ik                 channel current
                    Gk                 time varying channel conductance
                    Ek                 reversal potential of channel
                    tau1               first time constant of channel activation
                    tau2               second time constant of channel activation
                    gmax               peak channel conductance
                    frequency          random activation frequency (default = 0)
                    nsynapses          number of incoming spike messages (readonly)
                    event_buffer_size  size of event buffer (readonly)
                    pending_events     number of pending spike events in event
                                       buffer (readonly)
                    nodes_per_synapse  number of event nodes to allocate per
                                       synapse (default 1)
                    synapse            synapse buffer

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Synchan  [in src/newconn/synchan.c]

    Classes:        segment channel synchannel

    Actions:        CREATE          set synapse_size hidden field
                    INIT            assign activation = 0
                    PROCESS         update Gk, calculate Ik
                    RESET           assign activation = 0, Gk = 0; calculate
                                    time-step-dependent coefficients
                    RECALC          recalculate time-step-dependent coefficients
                    CHECK           make sure tau1>0, tau2>0; make sure a VOLTAGE
                                    message is present (in order to calculate Ik)
                    SAVE2           called by the save command
                    RESTORE2        called by the restore command
                    EVENT           put a spike event into the event buffer
                    ADDMSGIN
                    DELETEMSGIN
                    MSGINDELETED
                    RESETBUFFER     reset size of event buffer to
                                    (nodes_per_synapse * nsynapses) nodes
                    DELETE          delete the element
                    COPY            copies the element

    Messages:       VOLTAGE         Vm
                    ACTIVATION      activation
                    RAND_ACTIVATION probability amplitude
                    MOD             modulation
                    SPIKE

    ------------------------------------------------------------------------------

    Notes:          Simulates a time dependent synaptically activated ionic
                    channel.  A variable channel conductance Gk is activated by
                    the application of transmitter. This conductance then changes
                    with damped second-order characteristics with a time course
                    given by two time constants tau1 and tau2.  This gives rise to
                    an alpha function/dual exponential conductance waveform for an
                    impulse spike input.  The channel also calculates channel
                    current Ik and therefore needs the membrane state (Vm).

                    Each SPIKE message to a synchan establishes a synaptic
                    connection and increments nsynapses.  The synapses are
                    numbered starting with 0, and each contains a field for a
                    synaptic weight and a propagation delay.  Thus, a synchan has
                    some of the characteristics of the axons that make synaptic
                    connections to activate the conductance.  For example, the
                    weight of the first synaptic connection is held in the field
                    "synapse[0].weight" while the delay is "synapse[0].delay".  Gk
                    reaches a value gmax*weight for a single event delivered with
                    a SPIKE message.  Note that even though synapses are not
                    elements, they do have fields that can be accessed
                    individually.  They can be thought of as "sub-elements" or
                    substructures of the element.

                    Any number of spike events can be pending per synapse.
                    synchan stores all spike events in a buffer until they are
                    scheduled to occur.  If enough events come in to overload
                    the buffer, the buffer will dynamically expand to enable
                    storage of all events.  The size of the buffer in events is
                    stored in the "event_buffer_size" field which is readonly.
                    The number of actual spikes in the buffer which have not
                    yet hit the channel are stored in the "pending_events"
                    field (also readonly).  The "nodes_per_synapse" field
                    controls how many large the event buffer is initially.  The
                    default is to have one node per synapse, but if you expect
                    a lot of events or very few events you can change this
                    number to be greater or less than the default (1),
                    respectively.  This will speed up the simulation slightly
                    in the first case and save memory in the second.  If you
                    leave this field alone the object will still work fine.
                    The "resetsynchanbuffers" command will cause all the
                    buffers in all synchan and derived objects to be reset to
                    a size of nodes_per_synapse*nsynapses (which will also
                    cause all pending events to be flushed).

                    Unlike most messages, a SPIKE message may only be sent from
                    certain objects, e.g. the spikegen and randomspike objects.
                    The example in Scripts/tutorials/tutorial4.g illustrates the
                    use of synaptic connections with a very simple model of a
                    neuron that translates action potentials generated in the soma
                    into spike events using a spikegen, and then creates a
                    feedback synaptic connection to a synchan in its dendrite.
                    The synchan also receives random background activation with
                    spikes provided by a randomspike element.  Chapters in "The
                    Book of GENESIS" describe this tutorial in detail, the
                    construction of networks with synchans, and the use of GENESIS
                    utility functions to create synaptic connections and provide
                    information about connections in a network.  The documentation
                    for Connections also provides information about ways to make
                    synaptic conections.

                    The ACTIVATION message can be used to directly activate the
                    synchan conductance without creating a synapse.  ACTIVATION
                    messages do not create synapses with weight and delay fields.
                    One use would be to deliver spikes to a synchan from objects
                    that cannot deliver SPIKE messages, without using an
                    intermediate spikegen object to create SPIKE messages.  In
                    this case the activation that is sent with the SPIKE message
                    should last for a single time step dt, and have an amplitude
                    of 1/dt to normalize the activation to a unit area when
                    integrated over this single time step.  Then, it will have the
                    same effect as a SPIKE message, and the result will be
                    independent of dt.  The other case would be one in which an
                    activation is given that persists over multiple time steps, as
                    in an in vitro experiment that provides synaptic activation
                    that does not arise from axonal spikes.  In that case, no
                    normalization by 1/dt is needed.  The activation will be
                    integrated over the duration of the stimulus, and will not
                    depend on dt.

                    The MOD message is used to to implement neuromodulation.
                    The MOD message simply scales the channel activation for
                    that time step by the factor which is sent with the MOD
                    message.  Note that this globally affects all the synapses
                    in the synchan.  If you want synchans where some synapses
                    are modifiable but not others, you should divide it into two
                    synchans and only have a MOD message on the modifiable one.
                    The MOD message could also be used to implement learned
                    time-dependent modification of activation, by using a
                    script_out or extended object to implement an algorithm for
                    synaptic plasticity and to send the MOD message.  The
                    hebbsynchan and facsynchan objects provide other mechanisms
                    for implementing synaptic plasticity.

                    The "copy" command will fail for any synchan, facsynchan, or
                    hebbsynchan which is receiving SPIKE messages.  The correct
                    way to set up simulations is to set up prototype cells which
                    do not receive any SPIKE messages on their synchans, copy
                    these cells, and then add the appropriate SPIKE messages (by
                    hand or by using planarconnect or volumeconnect).  We are
                    working on a more "intelligent" copy command which will permit
                    copying of synchans with SPIKE messages, but for now, don't do
                    it.

                    This object used to be called synchan2 in genesis 2.0.1.
                    Since it does everything that the old synchan does without
                    the limitations of that object we have retired the old
                    synchan and renamed synchan2 to be synchan.  "synchan2" is
                    now just an alias for synchan -- they are identical.

    Example:        (Using Scripts/tutorials/tutorial4.g)

                    genesis > showfield /cell/dend/Ex_channel synapse[1].weight
                    [ /cell/dend/Ex_channel ]
                    synapse[1].weight    = 10

                    genesis > echo {getfield /cell/dend/Ex_channel synapse[1].delay}
                    0.004999999888

See also: resetsynchanbuffers , Connections , NewSynapticObjects , hebbsynchan , facsynchan , getsyncount , getsynindex , getsynsrc , getsyndest

## 26.60 synchan2

    Object Type:    synchan2

    Description:    Synaptically activated channel.

    Author:         Mike Vanier 11/94

    Notes:          This object is just an alias for synchan, for
                    backwards-compatibility.  The synchan2 object from genesis
                    2.0.1 has been renamed synchan, since it has all the
                    functionality of the old synchan object without its
                    limitations.

See also: synchan

## 26.61 tab2Dchannel

    Object Type:    tab2Dchannel

    Description:    Hodgkin-Huxley type channel with two-dimensional tables
    for alpha (A) and alpha + beta (B), allowing the rate variables to
    have dependencies on two variables, x and y (e.g., membrane voltage
    and an ion concentration).

    Author:         E. De Schutter, BBF-UIA Aug 94Caltech (1/91)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  tab2channel_type  [in src/olf/olf_struct.h]

    Size:           184 bytes

    Fields:         Gk              channel conductance
                    Ik              channel current
                    Ek              channel reversal potential
                    Gbar            channel maximum conductance
                    X               value of X gate; optional gate, X=m
                    Y               value of Y gate; optional gate, X=h
                    Z               value of Z gate; optional gate,
                    X_A             table for alpha function for X
                    X_B             table for alpha + beta function for X
                    X_alloced       flag for allocation of X_A and X_B
                    Y_A             table for alpha function for Y
                    Y_B             table for alpha + beta function for Y
                    Y_alloced       flag for allocation of Y_A and Y_B
                    Z_A             table for alpha function for Z
                    Z_B             table for alpha + beta function for Z
                    Z_alloced       flag for allocation of Z_A and Z_B
                    Xpower          power to raise X gate to
                    Ypower          power to raise Y gate to
                    Zpower          power to raise Z gate to
                    instant         {INSTANTX}, {INSTANTY}, or {INSTANTZ} to
                                    determine the gate to instantly set to A/B
                    Xindex          specifies role of x and y for X gate
                    Yindex          specifies role of x and y for Y gate
                    Zindex          specifies role of x and y for Z gate
                    surface         compartment surface area used with DOMAINCONC

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       Tab2DChannel  [in src/olf/tab2channel.c]

    Classes:        segment channel

    Actions:        TABREAD TABSAVE RESTORE2 SAVE2 SHOW SET TABCREATE
                    CHECK PROCESS RESET INIT

    Messages:       VOLTAGE     voltage     [membrane voltage of compartment]
                    EK          Ek          [reversal potential]
                    CONCEN      concen      [ion concentration sent to channel]
                    CONCEN1     concen      [ion concentration sent to channel]
                    CONCEN2     concen      [ion concentration sent to channel]
                    DOMAINCONC  Ik scale    [ion current from another channel, to
                                            be multiplied by scale, and divided by
                                            the surface field]
                    ADD_GBAR    offset      [increment to be added to Gbar]

    ------------------------------------------------------------------------------

    Notes:          The tab2Dchannel object is very similar to the tabchannel, and
                    calculates the channel conductance and current from the
                    equations

                            Gk = Gbar*X^Xpower * Y^Ypower * Z^Zpower
                            Ik = Gk * (Ek - V)

                    where the gates obey the Hodgkin-Huxley equations

                            dX/dt = A_X - B_X*X
                            dY/dt = A_Y - B_Y*Y
                            dZ/dt = A_Z - B_Z*Z

                    Note that, as with the tabchannel, A corresponds to the
                    Hodgkin-Huxley alpha rate variable, and that B = alpha + beta
                    = 1/tau.

                    However, the TABCREATE action for the tab2Dchannel takes
                    additional arguments ydivs, ymin, and ymax, in in order to
                    allocate the two-dimensional tables for X_A, X_B, Y_A, etc.
                    The tables now have two indices, where the first one runs from
                    0 to xdivs and the second one from 0 to ydivs.  Typical
                    commands for allocating tables and setting values would be

                        call {chanpath} TABCREATE X {xdivs} {xmin} {xmax} \
                            {ydivs} {ymin} {ymax}

                        setfield {chanpath} X_B->table[{i}][{j}] {alpha + beta}

                    As there are currently no utilities like setupalpha or
                    setuptau for filling tab2Dchannel tables, the setfield command
                    above would be used in a doubly-nested for loop that
                    calculates the A and B values for the two indices.

                    When using two-dimensional tables, it may be necessary to
                    experiment with the table size in order to obtain the desired
                    accuracy without using large tables, which would result in
                    both excessive memory use and setup time.  When using a
                    one-dimensional table, it is customary to use a large table,
                    either by setting xdivs to a large value, or by using TABFILL
                    to expand the table with interpolated values.  Then the
                    calc_mode field for each table would be set to zero
                    (NO_INTERP), in order to save computation time.  For objects
                    that use 2-D tables, it is best to use a smaller values of
                    xdivs and ydivs and to perform linear interpolation is
                    performed at run time.  This is the default.  In the unlikely
                    event that you want to disable interpolation, set the table
                    calc_mode to NO_INTERP (zero).  For example:

                        setfield {chanpath} X_A->calc_mode {NO_INTERP}

                    As with the tabchannel, a message carrying the membrane
                    voltage or a concentration is sent to the channel so that the
                    channel can retrieve the appropriate A and B table values to
                    calculate the gate activations (X, Y and Z) and the resulting
                    channel conductance.  However, the tab2Dchannel can have two
                    messages, in order to specify both the x and y variables.
                    There are two new messages for sending concentrations (or
                    anything else), CONCEN1 (the same as CONCEN) and CONCEN2.
                    Another message DOMAINCONC provides a highly simplified model
                    to obtain the ionic concentration directly, using the current
                    sent from another channel, times a scale factor, and dividing
                    by the surface area of the parent compartment.

                    There are also three fields Xindex, Yindex, and Zindex.  These
                    fields are used for each gate to define which message refers
                    to the x variable and which refers to the y variable.  The
                    index fields may each be assigned to one of the pre-defined
                    global variables VOLT_INDEX, C1_INDEX, C2_INDEX, DOMAIN_INDEX,
                    VOLT_C1_INDEX, VOLT_C2_INDEX, VOLT_DOMAIN_INDEX, C1_C2_INDEX,
                    and DOMAIN_C2_INDEX.

                    The first four of these are used when a gate depends on only
                    one variable.  In this case, xdivs should be set to zero for
                    that gate, and the y variable (corresponding to the second
                    index) used to fill the A and B tables.  Then, the prefix
                    (VOLT, C1, C2 or DOMAIN) specifies whether the VOLTAGE,
                    CONCEN1, CONCEN2, or DOMAINCONC message is used to provide the
                    y variable.  The remaining five of these index variables are
                    of the form x_y_INDEX, and similarly specify which of two
                    messages are used to specify the x and y variables.  Thus if
                    Xindex is set to VOLT_C1_INDEX, a VOLTAGE message would
                    specify the x variable of the X_A and X_B tables, and a
                    CONCEN1 message would specify the y variable.  If you wanted
                    to have a second gate Y which depended on another ionic
                    concentration, you would also send a CONCEN2 message, and set
                    Yindex to C2_INDEX.

                    The instant field may be set to {INSTANTX}, {INSTANTY}, or
                    {INSTANTZ} to specify that the X, Y, or Z gate value will be
                    instantly set to A/B, rather than using the A and B table
                    values in the differential equations above.  This allows the
                    channel conductance to have a multiplicative factor of A/B.
                    This is often used to model a conductance having a
                    multiplicative Ca-dependent factor, or to implement
                    Morris-Lecar models with zero time constant for activation.

                    The TABSAVE and TABREAD functions may be called to save the
                    channel tables to a file to be read in when making a
                    subsequent simulation run.  These are described in the
                    documentation for the tabchannel.

                    See the documentation for tabchannel for explanations of the
                    other actions that are often called in a simulation script.

    Example:        see Scripts/neurokit/prototypes/MoczydKC.g

See also: Interpol documentation ( Tables ), tabchannel

## 26.62 tabchannel

    Object Type:    tabchannel

    Description:    Hodgkin-Huxley type voltage activated channel with tabulated
                    equations.

    Author:         E. De Schutter, Caltech (1/91)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  tab_channel_type  [in src/olf/olf_struct.h]

    Size:           168 bytes

    Fields:
                    activation      channel activation
                    Gk              channel conductance
                    Ik              channel current
                    Ek              channel reversal potential
                    Gbar            channel maximum conductance
                    X               value of X gate; optional gate, X=m
                    Y               value of Y gate; optional gate, X=h
                    Z               value of Z gate; optional gate, Z is
                                    concentration-dependent
                    X_A             table for alpha function for X
                    X_B             table for beta function for X
                    X_alloced       flag for allocation of X_A and X_B
                    Y_A             table for alpha function for Y
                    Y_B             table for beta function for Y
                    Y_alloced       flag for allocation of Y_A and Y_B
                    Z_A             table for alpha function for Z
                    Z_B             table for beta function for Z
                    Z_alloced       flag for allocation of Z_A and Z_B
                    Xpower          power to raise X gate to
                    Ypower          power to raise Y gate to
                    Zpower          power to raise Z gate to
                    instant         {INSTANTX}, {INSTANTY}, or {INSTANTZ} to
                                    determine the gate to instantly set to A/B
                    surface         compartment surface area used with DOMAINCONC

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       TabChannel  [in src/olf/tabchannel.c]

    Classes:        segment channel

    Actions:        CALC_BETA  CALC_ALPHA  CALC_MINF  DUMP  RESTORE2  SAVE2
                    SHOW  SET  TABDELETE  TABFILL  TABCREATE TABREAD TABSAVE
                    CHECK  PROCESS RESET  INIT

    Messages:       VOLTAGE     voltage     [membrane voltage of compartment]
                    EK          Ek          [reversal potential]
                    CONCEN      concen      [ion concentration sent to channel]
                    DOMAINCONC Ik  scale    [ion current from another channel, to
                                            be multiplied by scale, and divided by
                                            surface field]
                    ADD_GBAR    offset      [increment to be added to Gbar]

    ------------------------------------------------------------------------------

    Notes:          Tabulated hh-like channel.  The standard voltage dependent
                    activation (X) and inactivation (Y) factors are present. For
                    concentration dependent processes a third factor (Z) has
                    added.  Z can do a lot of things; the most important is that
                    it gets a different message (CONCEN) than X and Y (VOLTAGE).
                    Standard use for Z is concentration dependent inactivation,
                    using a Zpower > 0.  An alternative is to use it for
                    codependent activation; using Zpower<0, Z will equal concen
                    value times v-dependent table-value.  The DOMAINCONC message
                    provides a highly simplified model to obtain the ionic
                    concentration directly, using the current sent from another
                    channel, times a scale factor, and dividing by the surface
                    area of the parent compartment.

                    The table for the object is created using a call to the
                    TABCREATE action of the object.  For computational efficiency
                    the forward rate factor alpha (A) and 1/tau (B) are tabulated
                    in A-table and B-table.

                    The tabchannel element is very similar to the hh_channel
                    element, except that it uses tables for the voltage and other
                    dependencies. It speeds up computation by using table lookups
                    rather than calculations depending on exponentials. It also
                    provides more flexibility, being able to specify voltage
                    dependencies not falling in the traditional Hodgkin-Huxley
                    forms.

                    The gate obeys the following equations:

                            dX/dt = A_X - B_X*X
                            dY/dt = A_Y - B_Y*Y
                            dZ/dt = A_Z - B_Z*Z
                            Gk = Gbar X^Xpower} Y^Ypower} Z^Zpower}
                            Ik = Gk * (Ek - V)

                    NOTE: These equations are slightly different from the usual
                    Hodgkin-Huxley equations where:

                      dX/dt = alpha*(1 - X) - beta*X

                    The tables in this element are therefore actually A = alpha,
                    and B = 1/tau = alpha + beta.  This change reduces the number
                    of calculations to be made on the table output during the
                    integration.

                    The alpha and beta functions of the X, Y and Z gates are
                    implemented as tables and therefore have to be explicitly
                    allocated using the TABCREATE function.  Copies of tabchannel
                    use the original arrays unless new arrays are explicitly
                    allocated.  The X and Y gates use the same VOLTAGE message.
                    The Z gate uses the CONCEN message, which can be any field. It
                    allows for dependencies on other parameters.

                    The instant field may be set to {INSTANTX}, {INSTANTY}, or
                    {INSTANTZ} to specify that the X, Y, or Z gate value will
                    be instantly set to A/B, rather than using the A and B
                    table values in the differential equations above.  This
                    allows the channel conductance to have a multiplicative
                    factor of A/B.  This is often used with the Z gate to model
                    a Ca-dependent conductance, or to implement Morris-Lecar
                    models having zero time constant for activation.  For an
                    example, see the implementation of the Ca-dependent K
                    Channel in Scripts/neurokit/prototypes/traub91chan.g.

                    The TABCREATE function

                    TABCREATE here is different from the table and tabgate
                    elements. We only need to specify which gate to set up, and
                    both tables for the gate will be filled.

                        call <element> TABCREATE <X/Y/Z> <xdivs> <xmin> <xmax>

                    This call creates two tables for X, Y, or Z with indices from
                    0 to xdivs, i.e. xdvivs + 1 entries which span the range xmin
                    to xmax.  Values outside this range are linearly extrapolated
                    using the nearest 2 table entries.

                    Entries in these tables are made with statements like

                            setfield Na_chan X_A->table[0] 0.05

                    There are several alternatives to using a long sequence of
                    setfield commands to fill the tables.  The file2tab command
                    can be used to fill the tables from a file of values.  If the
                    rate (alpha and beta) or state (tau and minf) variables can be
                    expressed as a mathematical function, a for loop may be used
                    to fill the tables.  For functions of the form (A + B * x) /
                    (C + exp((x + D) / F)), the setupalpha or setuptau commands
                    may be used.   This is also discussed in Chapter 19 of The
                    Book of GENESIS (2nd ed.)

                    The TABDELETE function

                    When deleting tabchannels, or the cells or compartments
                    containing them, you must call TABDELETE first, in order to
                    deallocate the memory for the tables.  Finally, you have to
                    give the "reclaim" command for the memory to actually be
                    freed.  Note that the tables are shared among all tabchannels
                    that are created by copy or readcell from a prototype.
                    Therefore, you shouldn't call TABDELETE unless you plan to
                    delete all copies of the tabchannel.

                    The TABFILL function

                    TABFILL expands the table by using interpolation on the
                    existing table entries.  Again, the syntax is different from
                    that for table and tabgate elements, and one just has to call
                    TABFILL once to fill both the arrays corresponding to that
                    gate:

                        call <element> TABFILL <X/Y/Z> <xdivs> <fill_mode>

                    xdivs specifies the number of divisions that the expanded
                    tables should have.

                    fill_mode is one of
                        0 = B-spline fill (default)
                        1 = cubic spline fill (not yet implemented)
                        2 = Linear fill

                    Tables have a calc_mode field that is by default set to
                    LIN_INTERP (a pre-defined global variable equal to one), so
                    that linear interpolation is performed at run time, allowing
                    the use of a smaller table.  If sufficient memory is
                    available, it will be faster to perform the interpolation when
                    the table is created, by expanding it with TABFILL.  Then, run
                    time interpolation should be disabled by setting the calc_mode
                    of the tables to NO_INTERP (zero).  For example:

                        setfield {chanpath} X_A->calc_mode {NO_INTERP}
                        setfield {chanpath} X_B->calc_mode {NO_INTERP}

                    The TABSAVE and TABREAD functions

                    As filling the tables can be time-consuming (particularly if
                    it is done using a for loop in a script), the TABSAVE and
                    TABREAD functions can be useful for saving channel tables and
                    re-loading them when the simulation is run again.

                    TABSAVE may be called after the channel has been created and
                    set up, in order wto save the tables to a file.  For example:

                        call Purk_Kdr TABSAVE Purk_Kdr.tab

                    TABREAD is called after the channel has been created and the
                    tables have been allocated.  For example:

                    if (!{exists Purk_Kdr})
                        create tabchannel Purk_Kdr
                        setfield Purk_Kdr Ek {EK} Gbar {GK} Ik 0 Gk 0 \
                            Xpower 2 Ypower 1 Zpower 0
                        call Purk_Kdr TABCREATE X {xdivs} {xmin}  {xmax}
                        call Purk_Kdr TABCREATE Y {xdivs} {xmin}  {xmax}
                    end
                    call Purk_Kdr TABREAD Purk_Kdr.tab

                    Scaling tables

                    When the fields X_A->sx, X_A->sy, X_A->ox, X_A->oy, and the
                    corresponding fields on X_B, Y_A, Y_B, Z_A, Z_B are set, the
                    tabgate element automatically scales on the entries in the
                    interpol_struct array so as to avoid scaling computations
                    during simulations.  Care must be taken since the B table
                    contains 1/tau rather than the beta values. It is recommended,
                    therefore, that both alpha and beta be adjusted simultaneously
                    and identically.  Alternatively, the scaletabchan function may
                    be used to scale the two tables in such a way as to scale
                    alpha, beta, tau, or the steady state activation (minf).

                    The CALC_ALPHA, CALC_BETA, and CALC_MINF functions

                    The CALC_ALPHA, CALC_BETA, and CALC_MINF actions are used with
                    calls of the form

                            y = {call <element> CALC_ALPHA <X/Y/Z> <x-value>}

                    in order to access values of alpha, beta or m_inf (the steady
                    state activation, alpha/(alpha + beta)) for the specified gate
                    (X, Y, or Z) and a particular value of the independent
                    variable.  This feature is most often used for making plots of
                    these quantities.  Note that the activation time constant can
                    be calculated from tau = 1/(alpha + beta).

    Example:        see Scripts/neurokit/prototypes/traub91chan.g

See also: Interpol documentation ( Tables ), scaletabchan , setupalpha , setuptau , tweakalpha , tweaktau , hh_channel , tab2Dchannel

## 26.63 tabcurrent

    Object Type:    tabcurrent

    Description:    A non-ohmic ionic current that provides instantaneous values
                    for Ik and the slope conductance Gk from 2-D tables.

    Author:         E. De Schutter, BBF-UIA 2/95-6/98

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  tab_current_type [in src/olf/olf_struct.h]

    Size:           120 bytes

    Fields:         Ik              channel current (calculated)
                    Gk              channel conductance (calculated)
                    Ek              channel reversal potential (calculated)
                    Gbar            scaling factor for Gk and Ik
                    Gindex          specifies role of x and y for G_tab and I_tab
                    alloced         flag (= 2 when both tables have been allocated
                    surface         compartment surface area used with DOMAINCONC
                    G_tab           2-D table for Gk
                    I_tab           2-D table for Ik

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       TabCurrent [in src/olf/tabcurrent.c]

    Classes:        channel segment

    Actions:        TABREAD  TABSAVE  TABCREATE  SHOW  CHECK  PROCESS  RESET

    Messages:       VOLTAGE     voltage     [membrane voltage of compartment]
                    CONCEN      concen      [alias for CONCEN1]
                    CONCEN1     concen      [ion concentration sent to channel]
                    CONCEN2     concen      [ion concentration sent to channel]
                    DOMAINCONC  Ik scale    [ion current from another channel, to
                                            be multiplied by scale, and divided by
                                            the surface field]
                    ADD_GBAR    Gbar        [increment to be added to Gbar]

    ------------------------------------------------------------------------------

    Notes:

    The tabcurrent object provides a fairly general way to compute non-ohmic
    currents that depend on voltage or (more typically) both voltage and
    concentration.  The resulting current Ik and conductance Gk are obtained (with
    interpolation, by default) from the two-dimensional tables I_tab and G_tab,
    which are then scaled by the Gbar value.  The cell reader (readcell) sets the
    Gbar value by multiplying the conductance density specified in a cell
    parameter file by the compartment area, as is does for other channels.

    Unlike the tabchannel or tab2Dchannel, it is not assumed that the current
    obeys Ohm's law and is proportional to the membrane potential Vm.  However, a
    compartment (or symcompartment) will expect a channel element to provide Gk
    and the reversal potential Ek in a "CHANNEL Gk Ek" message, and use these to
    calculate the incoming ionic current from Ik = Gk*(Ek - Vm).  In order for a
    tabcurrent element to be used like a channel, the G_tab table must contain
    values that will produce the proper result for Ik when this calculation is
    performed.  This may be done by making the assumption that over a single time
    step, Gk and Ek vary slowly compared to Vm.  Then the approximation can be
    made that dIk/dVm = - Gk, and that Ek = (Ik + Gk*Vm)/Gk.  Thus, Ek is
    calculated by the tabcurrent object, rather than being set by the user or by
    an incoming message.  Note that the sign of the current expresses the GENESIS
    convention that current flow into a compartment is positive.

    Thus, the I_tab table should be filled with values of Ik/Gbar and the G_tab
    table should be filled with -dI_tab/dVm.  GENESIS has two commands, setupNaCa
    and setupghk, that will create and fill these tables for the special cases of
    the Na-Ca exchanger pump and the Goldman-Hodgkin-Katz constant field equation.

    For other cases, you will have to create and fill the tables yourself.
    A table is allocated by calling the the TABCREATE function, for example:

      call mytabcurrent TABCREATE I_tab {xdivs} {xmin} {xmax} {ydivs} {ymin} {ymax}

    As the I_tab and G_tab tables are related, and must have the same dimensions,
    calling TABCREATE for one of them automatically allocates memory for the
    other.  Thus, it is not necessary to call TABCREATE again for G_tab.  As with
    the table2D and tab2Dchannel objects, xdivs and ydivs refer to the number of
    divisions in the tables, with the first index running from 0 to xdivs and the
    second one from 0 to ydivs.

    The tables are filled by commands of the form:

        setfield mytabcurrent I_tab->table[{i}][{j}] {Ivalue}
        setfield mytabcurrent G_tab->table[{i}][{j}] {Gvalue}

    The source code for setupNaCa and setupghk (in src/concen/tabcurrent.c)
    provides examples of filling the tables using C, rather than the scripting
    language.  This would be a good starting point for adding your own GENESIS
    commands for setting up specialized non-ohmic currents.

    By default, objects that use tables have the calc_mode for the tables set to
    LIN_INTERP (a pre-defined global variable equal to one), so that linear
    interpolation is performed at run time, allowing the use of a smaller table.
    In the unlikely event that you want to disable interpolation, set the
    calc_mode to NO_INTERP (zero).  For example:

        setfield mytabcurrent G_tab->calc_mode {NO_INTERP}
        setfield mytabcurrent I_tab->calc_mode {NO_INTERP}

    The TABSAVE and TABREAD functions may be called to save the channel tables to
    a file to be read in when making a subsequent simulation run.  These are
    described in the documentation for the tabchannel.

    The units to be used when setting the Gbar field depend on the units used for
    the G_tab table, and should be chosen to that it results in the proper units
    of conductance for Gk, e.g. Siemens.  For example, the setupNaCa command
    creates I_tab with units of (mM)^4 and G_tab with units of (mM)^4/Volts Then,
    Gbar should be in units of Amperes/(mM)^4.

    The Gindex field is similar to the Xindex, Yindex, and Zindex fields of the
    tab2Dchannel, and is used to specify which message refers to the x variable
    and which refers to the y variable when performing the table lookups.  The
    Gindex field may be assigned to one of the pre-defined global variables
    VOLT_INDEX, C1_INDEX, C2_INDEX, DOMAIN_INDEX, VOLT_C1_INDEX, VOLT_C2_INDEX,
    VOLT_DOMAIN_INDEX, C1_C2_INDEX, and DOMAIN_C2_INDEX.

    The first four of these are used when a gate depends on only one variable.  In
    this case, xdivs should be set to zero for that gate, and the y variable
    (corresponding to the second index) used to fill the I_tab and G_tab tables.
    Then, the prefix (VOLT, C1, C2 or DOMAIN) specifies whether the VOLTAGE,
    CONCEN1, CONCEN2, or DOMAINCONC message is used to provide the y variable.
    The remaining five of these index variables are of the form x_y_INDEX, and
    similarly specify which of two messages are used to specify the x and y
    variables.  Thus if Gindex is set to VOLT_C1_INDEX, a VOLTAGE message would
    specify the x variable of the I_tab and G_tab tables, and a CONCEN1 message
    would specify the y variable.

    In principle, any of these values for Gindex are allowed by the tabcurrent
    object.  But, a VOLTAGE message is required in order to calculate Ek.
    Although tabcurrent does not check to be sure that the VOLTAGE message is used
    as an index into the tables, the tables would have to depend on voltage, in
    order to have G_tab = -dI_tab/dV.  So, in practice, Gindex is restricted to be
    VOLT_INDEX, VOLT_C1_INDEX, VOLT_C2_INDEX, or VOLT_DOMAIN_INDEX.  The most
    common use of tabcurrent is when Ik depends on both membrane potential Vm and
    an ionic concentration.  Then, both VOLTAGE and CONCEN1 (or CONCEN) messages
    are used, and Gindex is set to VOLT_C1_INDEX.

    Example:

See also: tab2Dchannel , setupNaCa , setupghk , Tables

## 26.64 tabgate

    Object Type:    tabgate

    Description:    A gate with tabulated dependencies on any field for
                    opening and closing.

    Author:         U. S. Bhalla, Caltech (2/90)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  tab_gate_type  [in src/olf/olf_struct.h]

    Size:           96 bytes

    Fields:         activation      input field, usually accessed by messages
                    m               state of gate
                    alpha           rate variable table filled by TABCREATE
                    alpha_alloced   internal flag for table allocation
                    beta            rate variable table filled by TABCREATE
                    beta_alloced    internal flag for table allocation
                    instantaneous   flag for looking at instantaneous response

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       TabGate  [in src/olf/tabgate.c]

    Classes:        segment
                    gate

    Actions:        PROCESS
                    CHECK
                    RESET
                    SET
                    SAVE2
                    RESTORE2
                    TABCREATE
                    TABFILL
                    CALC_MINF
                    CALC_ALPHA
                    CALC_BETA

    Messages:       VOLTAGE compartment-voltage
                    SUM_ALPHA value-to-sum-onto-alpha-func
                    PRD_ALPHA value-to-multiply-alpha-func-by
                    SUM_BETA value-to-sum-onto-beta-func
                    PRD_BETA value-to-multiply-beta-func-by
                    EREST resting-potential-for-resets

    Notes:          A gate with tabulated dependencies on any variable for opening
                    and closing. Voltage and ion concentration are the most common
                    variables for dependencies.  The tabgate object is very
                    similar to the vdep_gate object, except that it uses tables
                    for the voltage and other dependencies. It also has message
                    slots for additional dependencies.  It is normally used to
                    send MULTGATE messages to a vdep_channel.  However, this
                    combination has been largely supplanted by the tabchannel
                    object.

                    A gate state is calculated from the following differential
                    equation:

                      dm/dt = alpha(1 - m) - beta * m

                    The alpha and beta functions are implemented as tables and
                    therefore have to be explicitly allocated using the TABCREATE
                    function. Copies of tabgate use the original arrays unless new
                    arrays are explicitly allocated.

                    The TABCREATE function

                    TABCREATE here is different from the table element since we
                    need to specify which table to create:

                      call <element> TABCREATE <alpha/beta> <xdivs> <xmin> <xmax>

                    This call creates an array on alpha or on beta with xdivs
                    entries, which spans the range xmin to xmax. Values outside
                    this range are linearly extrapolated using the nearest 2 table
                    entries.

                    The TABFILL function

                    TABFILL expands the table by using interpolation on the
                    existing table entries.  The syntax is different from the
                    table element, as one has to specify the array (alpha or beta)
                    being filled:

                      call <element> TABFILL <alpha/beta> <xdivs> <fill_mode>

                    xdivs + 1 specifies the number of entries that the expanded
                    tables should have.

                    fill_mode is one of
                        0 = B-spline fill (default)
                        1 = cubic spline fill (not yet implemented)
                        2 = Linear fill

                    Scaling tables

                    When the fields alpha->sx, alpha->sy, alpha->ox, alpha->oy,
                    and the corresponding fields on beta are set, the table
                    element automatically scales on the entries in the
                    interpol_struct array so as to avoid scaling computations
                    during simulations.

                    The CALC_ALPHA, CALC_BETA, and CALC_MINF functions

                    The CALC_ALPHA, CALC_BETA, and CALC_MINF actions are used with
                    calls of the form

                            y = {call <element> CALC_ALPHA  <x-value>}

                    In order to access values of alpha, beta or m_inf (the steady
                    state activation, alpha/(alpha + beta)) for a particular value
                    of the dependent variable.  This feature is most often used
                    for making plots of these quantities.  Note that the
                    activation time constant can be calculated from tau = 1/(alpha
                    + beta).

    Example:        see Scripts/neurokit/prototypes/traub91chan.g

See also: Interpol documentation ( Tables ), tabchannel , vdep_channel

## 26.65 table

    Object Type:    table

    Description:    A table with a couple of message slots for adding
                    dependencies on other fields.
                    The table can be used in several modes, depending on the
                    step_mode field. These include:

                        Table lookup - incoming messages are used as an
                            index to the contents of the table. The output
                            is calculated using interpolation if the appropriate
                            mode is selected in the interpol_struct.

                        Function generation - The table steps through
                            its entries and emits the values. The
                            stepsize determines the rate at which the table is
                            scanned. Again, interpolation may be used.

                        Output buffering - Input message values arriving at the
                            table are stored on each timestep, and the table index
                            is incremented, till the table is full

                        Delay line - Input message values arriving at the table
                            are stored on each timestep, using the table as a
                            ring buffer.  The output is the input from an earlier
                            time.

                        Spike output buffering - Input message values arriving at
                            the table are checked for threshold crossing. If
                            they pass, then the current simulation time is
                            stored in a table entry, and the table index
                            incremented.

                        Monitoring a large number of incoming messages -
                            Input message values are placed into successive
                            or defined table entries on every clock tick. This
                            is made much more useful because of a hack which
                            allows the table values to be sent backwards along
                            the messages using the TAB2FIELDS action.

                    The usual options for interpol_struct manipulations are
                    available for the table. These include special set options
                    for setting an entire interpol_struct at a time, file-
                    interface commands like tab2file and file2tab, and the
                    loadtab command for filling the table from the command line.

    Author:         U. S. Bhalla, Caltech (2/90)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  table_type  [in src/olf/olf_struct.h]

    Size:           80 bytes (minimum)

    Fields: input           input field to table, usually set by
                            messages.  If step_mode=1, input field keeps
                            track of the current position in the table

            output          output value
            table           interpol struct for table; assigned by
                            TABCREATE
            alloced         internal flag for table allocation
            step_mode       This flag selects between several modes of
                            operation of the table.
                            0 = TAB_IO - Default mode. Table does lookup.
                            1 = TAB_LOOP - Table acts as a function
                                    generator, looping back to the beginning
                                    when all the entries have been scanned.
                                    The input field is incremented by
                                    step_size on each timestep, and
                                    is used to perform the lookup.
                            2 = TAB_ONCE - Table acts as a function
                                    generator, terminating when
                                    all the entries have been scanned.
                                    At this stage the output is fixed
                                    at the last entry in the table.
                            3 = TAB_BUF - Table acts as a buffer.
                                    Incoming msg values are stored in
                                    successive table entries on each
                                    timestep. The output field keeps
                                    track of the table index.
                            4 = TAB_SPIKE - Table acts as a buffer
                                    for spike times. Incoming msg values
                                    are checked for crossing a
                                    threshold, which is stored in the
                                    'stepsize' field. If they pass,
                                    then the simulation time is stored
                                    in the table entry. The output
                                    field keeps track of the table index.
                            5 = TAB_FIELDS - Table acts as a buffer for
                                    many incoming messages. If the
                                    messages are INPUT messages, each
                                    message value is placed in a successive
                                    table entry. If the messages are INPUT2,
                                    then the second slot of the message
                                    holds the table index.
                                    The TAB2FIELDS action will go
                                    back along these messages and place
                                    the table values into the source fields.
                                    This option does not work in parallel
                                    or with extended fields.

                            6 = TAB_DELAY - Table acts as a delay line. Input to
                                    the table arrives from the INPUT message as
                                    usual, and output from the table is available
                                    at the 'output' field as usual. The delay is
                                    implemented as a simple ring buffer, in which
                                    the 'input' field indexes the table to specify
                                    which entry should receive input and supply
                                    output. The 'input' field is incremented by
                                    one each timestep.  (This is unlike the
                                    TAB_BUF mode, where the current sample number
                                    is stored in the 'output' field.)  The
                                    duration of the delay is therefore equal to
                                    xdivs * dt, where xdivs is the size of the
                                    interpol struct and dt is the timestep of the
                                    clock used by the table.  Note that the
                                    'stepsize' field is not used, and that the
                                    contents of the table are NOT erased on RESET.
                                    This restriction is necessary in case a
                                    predefined input is required in the delay
                                    line. If the user wishes to wipe out the table
                                    then the command "setfield /table table ===0"
                                    will set all entries to zero.  (See the
                                    documentation for Tables for an explanation of
                                    this enhanced setfield syntax.)

            stepsize        increment to input for stepping through table
                            with each clock tick in step_modes 1 and 2.
                            In the case of step_mode 4, stepsize acts
                            as the spike threshold.

                            In step_modes 1 and 2, stepsize can also be
                            set to zero to use the current simulation time
                            to look up a value. The table uses the sum of
                            the current simulation time and the value of the
                            'input' field. This is designed for generating
                            a predefined stimulus waveform controlled by
                            the simulation time, even if the timesteps are
                            changing. Thus, if the input field has value -3,
                            and the simulation time is 10, the stimulus waveform
                            will be looked up for a time of 7. In this manner,
                            by using negative values in the input field, one
                            can delay the start of a stimulus waveform.

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       TableFunc  [in src/olf/table.c]

    Classes:        segment

    Actions:        PROCESS
                    RESET
                    SET
                    TABCREATE       Must be called to allocate the interpol_struct
                                    of the table.

                                    syntax:
                                      call table TABCREATE xdivs xmin xmax

                                    This produces a table with indices from 0 to
                                    xdivs, i.e. xdvivs + 1 entries
                                    which span the range xmin to xmax.

                    TABFILL         Expands the table by using interpolation
                                    on the existing table entries.

                                    syntax:
                                      call table TABFILL xdivs fill_mode

                                    xdivs + 1 specifies the number of entries that
                                    the expanded table should have.

                                    fill_mode is one of
                                        0 = B-spline fill (default)
                                        1 = C_Spline fill (not yet implemented)
                                        2 = Linear fill

                    TAB2FIELDS      Sends values from the table back to the
                                    originating element fields, only works with
                                    the TAB_FIELDS stepmode.

                                    syntax:
                                            call table TAB2FIELDS

                    TABOP           Carries out an operation on the entries in
                                    the table, putting the result in the
                                    'output' field.

                                    syntax:
                                      call table TABOP op [min max]

                                    where op is the operation to perform and
                                    min and max are the x range on the table
                                    on which to operate

                                    The available operations are:
                                            a = average
                                            m = min
                                            M = Max
                                            r = range (i.e., max - min)
                                            s = slope
                                            i = intercept
                                            f = freq
                                            S = Sqrt(sum of squares)

                    DUMP            Saves the table fields and interpol entries
                                    in a script-readable file. This is an
                                    internal action only.

    Messages:       INPUT input-value-for-lookup
                    SUM value-to-sum-onto-output
                    PRD value-to-multiply-output-by
                    INPUT2 input-value-for-table index-for-value-to-go-to

    ------------------------------------------------------------------------------

    Notes:          A table with a couple of message slots for adding dependencies
                    on other fields. The table for the object is created using
                    tabcreate.

                    Does a table lookup with interpolation. Also permits one to
                    modify the table with sum and product messages, so as to
                    extend the dimensionality of the table.

                    The table element is a way of defining arbitrary input-output
                    functions.  It is based on the interpol_struct described
                    above, and provides the simplest form of access to it.  Other
                    values (possibly generated by other tables) may be summed or
                    multiplied into the output value by means of messages, to
                    permit pseudo-multidimensional functions to be generated by
                    the table. Tables can also be used as function generators.

                    The array with the table values has to be explicitly allocated
                    using the TABCREATE function. Copies of a table use the
                    original array unless a new array is explicitly allocated.
                    Basically:

                      output = lookup[input] * (prd values) + (sum values)

                    TABCREATE

                    The syntax for tables is simple, since there is only one
                    interpol_struct to worry about:

                      call <element> TABCREATE <xdivs> <xmin> <xmax>

                    This call creates the interpol_struct data structure, which is
                    rather badly named ``table''.

                    Scaling tables

                    When the fields table->sx, table->sy, table->ox, table->oy
                    are set, the table element automatically scales on the
                    entries in the interpol_struct array so as to avoid scaling
                    computations during simulations.

    Example : Using the TAB_FIELDS options
    ============================CUT HERE======================================

    //genesis
    // This example illustrates the use of the TAB_FIELDS options in
    // the table element.
    // First, we create a bunch of neutrals. The createmap command
    // lays them out in a 10x10 square array with unit spacing.
    createmap neutral /foo 10 10 -object

    // Then we create a table
    create table /bar
    call /bar TABCREATE 100 0 100

    // We now assign the TAB_FIELDS step_mode. In this mode, incoming
    // messages are sent to successive table entries, and updated
    // on every clock tick.
    setfield /bar step_mode 5 // TAB_FIELDS
    addmsg /foo/proto[] /bar INPUT x

    reset
    step // To do the clock tick and assign the table values.

    int i

    /* Here we show the x fields */
    echo
    echo Showing x fields before:
    for (i = 0; i < 100; i = i + 1)
            echo {getfield /foo/proto[{i}] x} " " -n
    end

    // Here we show that the table entries are now equal to the
    // x fields
    echo
    echo Showing table array
    for (i = 0; i < 100; i = i + 1)
            echo {getfield /bar table->table[{i}]} " " -n
    end

    // here we add 0.5 to each of the values in the table array.
    for (i = 0; i < 100; i = i + 1)
            setfield /bar table->table[{i}] \
                    {{getfield /bar table->table[{i}]} + 0.5}
    end

    // here we call the action in the table which goes back through
    // the messages and puts the new values in the source fields,
    // in this case the x coords of the array of neutrals.
    call /bar TAB2FIELDS

    // Here we look to see what happened.
    echo
    echo Showing x fields after:

    for (i = 0; i < 100; i = i + 1)
            echo {getfield /foo/proto[{i}] x} " " -n
    end

    echo

    ============================CUT HERE======================================

    Bugs:           All of the interpolation options depend on an internal field
                    of the interpol_struct, called invdx, which is set up during
                    table allocation using TABCREATE. Unfortunately this field is
                    not updated upon subsequent manipulations of the table or
                    interpol structure. Invdx has the value 1/dx where dx = (xmax
                    - xmin)/xdivs. To work around the bug please explicitly set it
                    when you need to use the interpolation options.

See also: Interpol documentation ( Tables ).

## 26.66 table2D

    Object Type:    table2D

    Description:    A two-dimensional table with interpolation.

    Author:         U. S. Bhalla MSSM May/93

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  [in src/olf/olf_struct.h]

    Size:           124 bytes (minimum)

    Fields:         input       x value input to table
                    input2      yvalue input to table
                    output      Output of table lookup
                    negoutput   Negative of table output
                    table       2d interpol struct for table
                    alloced     Internal flag for table allocation
                    step_mode   Not implemented
                    stepsize    Not implemented

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       [in src/olf/table2d.c]

    Classes:        segment

    Actions:        SET  TABCREATE  PROCESS  RESET

    Messages:       INPUT  x-value-for-lookup  y-value-for-lookup
                    SUM    value-to-sum-onto-output
                    PRD    value-to-multiply-output-by
                    X      x-value-for-lookup
                    Y      y-value-for-lookup

    ------------------------------------------------------------------------------

    Notes:          TABCREATE must be called to allocate the interpol_struct
                    of the table.  The syntax is:

                    call table-element TABCREATE xdivs xmin xmax [ydivs ymin ymax]

                    As with other interpol_structs, xdivs and ydivs refer to the
                    number of divisions in the table, with the first index running
                    from 0 to xdivs and the second one from 0 to ydivs.  If the
                    ydivs, ymin, and ymax parameters are not given, these will be
                    set to the values used for the x variable.

                    By default, objects that use 2-D tables (tab2Dchannel,
                    table2D, and tabcurrent) have the calc_mode for the tables set
                    to LIN_INTERP (a pre-defined global variable equal to one), so
                    that linear interpolation is performed at run time, allowing
                    the use of a smaller table.  In order to disable
                    interpolation, set the calc_mode to NO_INTERP (zero).  For
                    example:

                    setfield my2Dtable table->calc_mode {NO_INTERP}

    Example:        genesis > create table2D /foo
                    genesis > call /foo TABCREATE 5 0 1 5 0 1
                    genesis > setfield /foo table->table[0][0] 5
                    genesis > setfield /foo table->table[1][1] 10
                    genesis > setfield /foo table->table[3][3] 105

                   genesis > echo {getfield /foo table->table[3][3]}
                   105

See also: table , Interpol documentation ( Tables ).

## 26.67 taupump

    Object Type:    taupump

    Description:    Implementation of a simple pump with a variable time constant
                    of removal.  Should be coupled to a difshell, where the change
                    in concentration is computed.

    Author:         E. De Schutter, Caltech (11/90)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  taupump_type  [in /usr/genesis/src/concen/conc_struct.h]

    Size:           108 bytes

    Fields:         kP              pump rate = inverse of tau in s
                    Ceq             equilibrium concentration in mM
                    T_A             factor for Tau
                    T_B             exp factor for Tau
                    T_V             half-voltage for Tau
                    T_C             constant offset for Tau
    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       TauPump  [in src/concen/taupump.c]

    Classes:        gate segment

    Actions:        INIT
                    PROCESS
                    RESET
                    CHECK

    Messages:       VOLTAGE Vm
    ------------------------------------------------------------------------------

    Notes:

    The taupump and other ionic pumps provide various mechanisms to remove ions
    from a concentration shell (difshell).

    If a VOLTAGE message is received, carrying a membrane potential Vm (or any
    other parameter used to vary the pump rate), the time constant is given
    by tau = T_A*exp((Vm - T_V)/T_B) + T_C, and the pump rate is kP = 1.0/tau.
    If there is no VOLTAGE message, tau is fixed to T_C, or to T_A if T_C = 0.

    The pump rate kP and equilibrium concentration Ceq are sent with a
    TAUPUMP message to a difshell, which uses them to produce a change in
    its ion concentration dC/dt = -kPump*(C-Ceq).

    For a general description of buffered calcium diffusion see:
    De Schutter E., and Smolen P., "Calcium dynamics in large neuronal
    models", in Methods in neuronal modeling: From ions to networks
    (2nd edition), C. Koch and I. Segev editors, pp. 211-250 (1998).  The
    spinedemo simulation gives a detailed example of the use of the difshell,
    taupump, and fixbuffer objects for modeling calcium diffusion in dendritic
    spines.

    Example:        addmsg headpump0 headshell0 TAUPUMP kP Ceq

See also: difshell , fixbuffer , Scripts/examples/spinedemo

## 26.68 timetable

    Object Type:    timetable

    Description:    A table of time values at which an activation variable
                    is set to different value for one timestep.
                    Designed to allow timestep independent synaptic activation
                    with controlled sequences of input.

    Author:         D. Jaeger, Caltech (3/95)
                    revised and extended for GENESIS 2.2 4/00

    ------------------------------------------------------------------------

    ELEMENT PARAMTERS

    DataStructure:  timetable_type [in genesis/src/device/spike_struct.h]

    Size:           176 bytes

    Fields:         method          1 = exponential inter-time interval
                                    2 = gamma iti
                                    3 = regular iti
                                    4 = read times from ascii file
                    meth_desc1      method parameter
                    meth_desc2      method parameter
                    meth_dexc3      method parameter
                    seed            random number generator seed
                    act_val         value of activation when set to on
                    maxtime         max. time up to which table is filled
                    maxpos          table size
                    tabpos          current table index
                    fname           name of file if times are read from file

                    ------- fields below should not be touched by user ----

                    *timetable      floating point array
                    allocated       allocation flag

    ------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       TimetableFunc [in genesis/src/device/timetable.c]

    Classes:        device

    Actions:        SET
                    RESET
                    PROCESS
                    TABCREATE
                    TABFILL
                    TUPDATE

    Messages:       [none]

    -------------------------------------------------------------------------

    Notes:  The timetable consists of a floating point array of values
            at which an activation variable is set to on.

            The table can be filled with various distributions of inter-
            time intervals. This procedure is controlled by the
            TABCREATE, TABFILL, and TUPDATE actions. The fields
            method, meth_desc1, meth_desc2, and meth_desc3 control
            the process. Here is how it works:

            TABCREATE: a table of size maxpos is allocated and filled with zeros.
            TABFILL: a table is created and filled according to the following
                    rules:
                    method=1: exponential iti distribution.
                            -> meth_desc1 = mean iti.
                    method=2: gamma iti distribution with added refractory period
                            -> meth_desc1 = mean iti.
                            -> meth_desc2 = absolute refractory period.
                            -> meth_desc3 = order of gamma distribution
                                    (integer between 1 and 6)
                    method=3: regular iti distribution
                            -> meth_desc1 = iti
                    method=4: read times from ascii file
                            -> filename = filename

                    maxtime: table is filled up to maximal value of maxtime
                            and appropriate table is allocated and maxpos is
                            set automatically.
                    seed:   if seed != 0 then random number generator is
                            seeded before filling table with methods 1 or 2.

            TUPDATE: the table is changed in the following way.
            example: call timetable TUPDATE mode mintime maxtime new_iti [new_iti2]
                    i.e. the TUPDATE is done with a call statement and
                            4 variables need to be supplied.
                    mode=1: The time values are randomly jitterd for
                            +- 0.5 new_iti
                    mode=2: A new distribution following the current
                            method field is inserted between mintime and
                            maxtime. The old values in this time range
                            are thrown out, but surrounding values stay
                            intact.  The new_iti field determines the new
                            mean iti. If a new_iti2 is given, the new iti is
                            changed linearly from new_iti to new_iti2 during
                            the period between mintime and maxtime.
                    mode=3: A specified number of spikes can be inserted
                            into a given time window. Usage:
                            call <tt> TUPDATE 3 starttime endtime n jitval
                            The first spike is inserted at starttime. If more
                            than one spike is to be inserted, subsequent spikes
                            are inserted at regular intervals until the nth
                            spike is inserted at endtime. If jitval <> 0 then
                            each inserted spike is randomly jittered by a value
                            of max. +-jitval.

    Example:

    create timetable tt
    setfield tt maxtime 1 act_val 1.0 method 1 meth_desc1 0.02
    /* create table with exponential distribution of mean 0.02 */
    call tt TABFILL
    /* connect table to synaptic events */
    create synchan c3
    addmsg tt c3 ACTIVATION activation

    /* put burst with faster itis  (iti 0.001)  at time 0.1 to 0.2 */
    call tt TUPDATE 2 0.1 0.2 0.001

    /* put burst of diminishing itis (iti 0.001 to 0.01)  at time 0.5 to 0.7 */
    call tt TUPDATE 2 0.5 0.7 0.001 0.01

See also: event_tofile , Scripts/examples/spike/spikes.g

## 26.69 variable

    Object Type:    variable

    Description:

    The variable object allows the user to manipulate the actual
    simulation data that is in an existing file or write new data into
    it. It responds to incoming SAVE messages to write data to the file
    and users can use its 'output' field to send messages to other
    elements to display traces and so on.  The functionality to replay
    data in a variable on through an xview element is currently not in
    place.

    Values may need to be stored in a single variable at every time
    step. File formats(including netcdf) allow variables to be arrays
    so multiple values can be stored.  The access of individual values in
    a variable is done by indexing it. This index is associated with the
    value of the simulation time.

    As an example, if the Vm of the soma is saved every time step for 100 steps,

     * values will be stored sequentially along the array. Assuming the
       clockrate of the variable object (rate of acquisition) is 1.0
       second, Vm at the 0th, 45th and 99th second can be got from
       value[0], value[45] and value[99] respectively.

     * Now if the rate at which the data was saved i.e the clockrate of
       the variable object was set at 1e-03 (1 msec), the above values
       would reflect the Vm values at times 0, 45 and 99 milliseconds
       respectively.

     * A better way for the user to establish/understand this relationship
       can be achieved through the 'input' and 'output' fields of the
       variable.  The input field values represent the actual time values
       and the output field reflects the value corresponding to the input,
       i.e the value corresponding to a specific time instant.

     * In the previous example for the acquisition rate being 1 msec, one
       could set the input field to 45e-03 and expect to show a valid
       output value.  However if the input were set to just 45 (45 secs),
       the output value will be undefined (usually a very large +ve number
       or an extremely small +ve number not equal to 0. This indeterminate
       value depends on the file format used as well as the operating
       system in which it is executing)

     * The append field in the diskio element also has an effect on how these
       values should be interpreted. See Doc/diskio.doc for an explanation.

     * Another important issue to note is that interpolated values will
       not be returned for inputs that do not match the time instants
       precisely.  For instance, if the input field were set to 45.5 e-03,
       the value returned in the output field will be the one that
       corresponds to the prior time instant, in this case 45msec and not
       a value interpolated between values at 45 msec and 46 msec.

     * Also, for a correct acquisition of data at proper time instants,
       the clockrate of the variable object should match that of the
       parent diskio.  If this is not the case, a reset would print a
       warning to this effect but continue to function without crashing
       the sytem. However, the values returned by the output values will
       not directly correspond to the actual simulation time instant at
       which the value was saved.

    The file itself has to be initially opened or created by the parent
    diskio object.  In other words, a variable can be created only as the
    child of a diskio object. The results of a simulation stored in the
    file can be replayed through an xgraph widget by sending the
    appropriate message and data(output field) to it from the variable
    object. At present, the mechanics to replay data written by the
    variable object through an xview/xvar widget are not in place but will
    be made available in the near future.

    NOTE: Variable objects can be created only for fileformats that
            support creation of arbitrary variables, such as
            Netcdf. Variables and metadata CANNOT BE CREATED ARBITRARILY
            for FMT1 files, for example.

            For purposes of consistency, however, when SAVE messages are
            directly sent to the diskio object, the autoSAVE_diskio and
            auto3-DPosSAVE_diskio child elements are automatically created
            in both cases. These should NOT BE MANIPULATED but can be used
            to inspect values in the file.

            Since FMT1 files do not support the notion of arbitrary
            variables the 'input' and 'output' fields are hidden and the
            other fields are made readonly.

    Author:         V.Jagadish (9/96)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS:

    DataStructure:  Gen_Variable_Type [in src/diskio/diskio_struct.h]

    Size:           120 bytes

    Fields:         datatype The type of the value(s) held in the variable
                    - The list of valid types are specified in the notes
                    section.  - Defaults to 'float64' (64-bit float) if
                    not specified in the create command line - readonly
                    for FMT1 files

                    size            The maximum number of data values the object
                                    can hold.
                                    - Can be specified on the create command
                                      line with the -size option.
                                    - The special size value 'unlimited' allows
                                      any number of values to be written into
                                      the variable.
                                    - Defaults to 'unlimited' if not specified.
                                    - If the datatype is char8 (8-bit char) the
                                      user could provide a string as the argument
                                      to the 'value' field without specifying a
                                      size or index, and the size (which is the
                                      number of chars in the string including the
                                      trailing '\0') is internally
                                      calculated and set in this field.
                                    - readonly for FMT1 files

                    value           The value(s) held by the variable.
                                    - Since variables
                                      can hold an array of values or a single one,
                                      an index (with the genesis-style indexing
                                      mechanism) needs to be specified while
                                      setting or showing this field. The index
                                      defaults to 0 if not specified, the
                                      exception to it being the case that the
                                      datatype is 'char8'.
                                    - If the type is 'char8', not
                                      specifying an index would translate
                                      to mean the entire string and
                                      individual indices would return the
                                      character at that location.(See
                                      examples)
                                    - Multiple argument values can be
                                      specified for this field (see
                                      examples) and the values will be
                                      accessed starting with index 0.
                                    - The default value is undefined for all
                                      data types
                                    - readonly for FMT1 files

                    input           This field stores the actual simulation time
                                    for analog traces. In combination
                                    with the output field it thus provides a way
                                    for the user to see what trace (output) value
                                    is associated with a particular simulation
                                    time value(input). - See examples.
                                    - Datatype of this field is hard-coded as
                                      float64 (64-bit float)
                                    - Default value is 0
                                    - hidden for FMT1 files

                    output          This read-only field serves as the data for
                                    outgoing messages from the variable object to
                                    other elements such as xgraph. The value
                                    of this field always reflects the one
                                    associated with the particular simulation
                                    time value stored in the input field. It
                                    acquires also the value specified through the
                                    incoming SAVE message to the variable object.
                                    - Datatype of this field is hard-coded as
                                      float64 (64-bit float)
                                    - Default value would be the value of the
                                      variable corresponding to the default
                                      input field value of 0 seconds.
                                      (starting simulation time)
                                    - hidden for FMT1 files

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:               Gen_Variable [in src/diskio/gen_variable.c]

    Classes:                output

    Actions:                CREATE PROCESS RESET SET SHOW ADDMSGIN

                            FLUSH:
                            UPDATE: allows the object to commit to the file on disk
                                    by writing out its contents

                            DELETE: allows committing to the file on disk,
                                    if necessary and then deletes the
                                    object and any children but does not
                                    delete the underlying variable or any
                                    of its attributes on file.

    Messages:               SAVE data
                            - An incoming message of this type to the variable
                              object indicates that the value of the field
                              (specified in the 'data' argument) of the source
                              element needs to be saved in it.
                            - These values will be stored in the value field
                              and the output field of the variable every time
                              step and if the variable is an array
                              the location for this value is determined according
                              to the current time as explained earlier.

    ------------------------------------------------------------------------------

    Notes:

    The default variable is an unlimited size array of 64-bit floating point
    values and associated with the actual simulation time.
    So, if the -size option is not specified while creating a variable
    the size would be internally set to 'unlimited' but an attempt to show
    the size field would show a number. This number is the maximum number of
    elements written so far, maybe in another variable associated with
    the simulation time. If no values had been written or if this were the first
    variable created, then the size would indicate 0. Any number of values
    could be subsequently set on this variable.

    In order to create a scalar variable (that holds a single value) not
    associated with time, use the -valuetype option with 'scalar'
    as the argument. There is, however, no field named valuetype.

    The datatype field stores the type of the variable as a string. The
    types are chosen to be as generic as possible. They are not based on
    the usual 'C' data types but rather on the user's perspective.
    Table 1.1 shows the valid datatype names and what they mean to
    the user.
    Please note that not all these types are supported by all file formats.
    An error to that effect will be printed if a variable of an unsupported
    type is attempted to be created. Netcdf, in particular does not allow
    resetting of datatypes or sizes for variables at all and an error will
    be issued if setfield attempts to change the values of these fields.

    Table 1.1 - Valid datatypes

    Name                            Description
    ____            |               ___________
                    |
                    |
    uint8           |               8-bit unsigned int
                    |
    int8            |               8-bit signed int
                    |
    uint16          |               16-bit unsigned int
                    |
    int16           |               16-bit signed int
                    |
    uint32          |               32-bit unsigned int
                    |
    int32           |               32-bit signed int
                    |
    uint64          |               64-bit unsigned int
                    |
    int64           |               64-bit signed int
                    |
    float32         |               32-bit float
                    |
    float64         |               64-bit float
                    |
    uchar8          |               8-bit unsigned char
                    |
    char8           |               8-bit signed char
                    |
    char16          |               16-bit (unicode) char
                    |
    string          |               string type (i.e not an array of chars)
                    |
    ________________+______________________________________________________

    Examples:

    create diskio /dout -filename "testfile.nc" -accessmode w

    create variable /dout/stringvar -datatype char8 -value "This is a string variable";
    showfield /dout/stringvar value // Would display the whole string
    showfield /dout/stringvar value[1] // Would display the character h

    create variable /dout/fixedsizevar -size 3 -datatype float64 -value \
    "1.0 2.0 3.0"

    create variable /dout/scalarvar -valuetype scalar -datatype int32 \
    -value 10

    create variable /dout/variablesizevar -datatype float32 -value  \
    "100.0 200.0 300.0"
    showfield /dout/variablesizevar value[0] value[2]
    showfield /dout/variablesizevar value[3] // This would show a very large +ve or
                                             // -ve number => undefined

    setfield /dout/variablesizevar value[0] 150.0 value[2] 250.0
    showfield /dout/variablesizevar value[0] value[2]

    create xform /f
    create xgraph /f/g

    addmsg /path/to/some-element /dout/variablesizevar SAVE <some-element-field>
    addmsg /dout/variablesizevar /f/g PLOT output *<plotname> *<color>

    step 100

    setfield /dout/variablesizevar input 30
    showfield /dout/variablesizevar output

    delete /dout

    For a clear example dealing with the SAVE message and replays,
    please see :
            Scripts/examples/diskiolib/variable/generate.g
            Scripts/examples/diskiolib/variable/replaygraph.g

    ------------------------------------------------------------------------------

See also: diskio , metadata

## 26.70 vdep_channel

    Object Type:    vdep_channel

    Description:    A Hodgkin-Huxley type voltage-dependent channel, which
                    receives activation gate values from other elements.

    Author:         M. Wilson, Caltech (2/89)

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  vdep_channel_type  [in src/hh/hh_struct.h]

    Size:           96 bytes

    Fields:         Gk              channel conductance
                    Ik              channel current
                    Ek              channel reversal potential
                    gbar            channel maximum conductance

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       VDepChannel  [in src/hh/vchannel.c]

    Classes:        segment channel

    Actions:        RESET
                    PROCESS
                    CHECK           [CHECK does nothing]
                    SAVE2           invoked with the save command
                    RESTORE2        invoked with the restore command

    Messages:       VOLTAGE voltage
                    MULTGATE gate_state power
                    ADDGATE gate_state power
                    GMAX gmax
                    EK Ek

    ------------------------------------------------------------------------------

    Notes:  A vdep_channel calculates Gk by multiplying gbar by any number of
            factors of the form (gate_state)^(power).  These are typically
            received with the MULTGATE message from a tabgate element. For
            example, Gk = gbar*h*m^3 could be implemented with:

                    addmsg Na_squid/m Na_squid MULTGATE m 3
                    addmsg Na_squid/h Na_squid MULTGATE m 1

            Here, m and h are vdep_gate or tabgate elements, and Na_squid is a
            vdep_channel.  Note that the field for the gate variable is called
            'm', regardless of the name of the gate element.

            For most uses, the vdep_channel has been superseded by the
            tabchannel.  It is sometimes used with a table and tabgate element
            to implement conductances which depend on both concentration and
            voltage (e.g. the potassium C-current).

    Example:        see Scripts/neurokit/prototypes/traub91chan.g

See also: hh_channel , tabchannel , tabgate

## 26.71 xbutton

    Object Type:    xbutton

    Description:    Executes script actions from button presses

    Author:         Maneesh Sahani / Upi Bhalla  Caltech Feb/93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xbutton_type [in src/Xodus/widg/xbutton_struct.h]

    Size:           132 bytes

    Fields:         fg      Foreground color of text in button
                    bg      Background color.
                    onfg    Foreground color of text in button,
                            for on (pressed) state.
                    onbg    Foreground color for on (pressed) state.
                    offfg   Background color of text in button,
                            for off (unpressed) state.
                    offbg   Background color for off (unpressed) state.
                    xgeom   Position of left edge of button.
                    ygeom   Position of upper edge of button.
                    wgeom   Width of button.
                    hgeom   Height of button.
                    onlabel optional text string to display in on state
                            Defaults to widget name in the GENESIS hierarchy.
                    offlabel optional text string to display in off state
                            Defaults to widget name in the GENESIS hierarchy.
                    onfont  optional font for text in on state.
                    offfont optional font for text in on state.
                    script  string representing actions to be performed
    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XButton [in src/Xodus/widg/xbutton.c]

    Classes:        widget output

    Actions:
                    B1DOWN: Button 1 pressed (left button)
                    B2DOWN: Button 2 pressed (middle button on 3 button mouse)
                    B3DOWN: Button 3 pressed (right button on 3 button mouse)
                    ANYBDOWN: Any button pressed.
                    XUPDATE: update internal fields when
                            displayed widget is changed.

    Messages:       none.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a form widget
                    The xbutton does not perbutton any computational operations.
                    It issues script calls depending on button presses.

    Example:

      create xform /form [0,0,500,100]
      create xbutton /form/button1 [0,0,100%,100%] \
        -onlabel "This button widget is on" \
        -offlabel "This button widget is off" \
        -onfg red \
        -offfg blue \
        -onfont 12x24 \
        -script "echo.d1 left button; echo.d3 right button; echo any button"
      xshow /form

See also: Widget documentation. Mouse events documentation ( Clicks ), Scripts/examples/XODUS/widgets.g.

## 26.72 xcell

    Object Type:    xcell

    Description:    The cell pix is similar to the view pix, but is specialized to
                    display the geometry and state of compartments in
                    multicompartmental cell models. Each compartment is
                    represented by a line segment of variable thickness and color.
                    The position and length of each line segment comes from the
                    3-D coordinates of the element that the line represents. Each
                    compartment is drawn from the coordinates of the previous
                    compartment (electrically speaking) to the current one.  The
                    color of the compartment may be used to represent the value of
                    a field of the compartment or of one of its subelements.

                    As with the view pix, it is displayed within a draw widget,
                    and refreshes itself every time its assigned clock ticks.
                    Therefore, care should be taken to ensure that the cell is
                    only being refreshed as often as you really want it to be.
                    For refreshes that are not associated with a running
                    simulation, the xupdate command can be used on the parent draw
                    widget.

    Author:         Upi Bhalla Mount Sinai June/93

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xcell_type [in src/Xodus/draw/xcell_struct.h]

    Size:           ?       Depends on the number of compartments in the cell
                            being displayed.
    Fields:
                    fg      foreground color of cell, applies to labels for
                            compartments, which are as yet unimplemented.

                    script  Script operation(s) to perform on a mouse click.

                    tx      Translation distance in the x dimension. The
                            cell is displaced in the draw by this amount.
                    ty      Translation in y.
                    tz      Translation in z.

                    value   contains path to the compartment which is clicked on.

                    pixflags  set of flags specifying visibility, refreshes,
                            mouse sensitivity, and many other options.  Use
                            the 'pixflags' utility command to find out more.

                    dia     table of compartment diameters.  For example,
                            "showfield cell dia->table[10]".

                    color   table showing the current value of the field which
                            is used to set the color of a compartment.

                    colmin  value of the displayed field corresponding to the
                            minimum of the color scale.

                    colmax  value of the displayed field corresponding to the
                            maximum of the color scale.

                    diamin  Compartments of this diameter or less are drawn at
                            minimum thickness (as a line).

                    diamax  Compartments of this diameter or less are drawn at
                            maximum thickness, specified by diarange.

                    diarange  specifies the maximum thickness of the line that
                            represents a compartment.  There are two modes: if it
                            is a negative number, then the absolute value is
                            taken as the thickness of the line in pixels.  If it
                            is positive, then the value is taken as the diameter
                            of the compartment in real space.  The pixel
                            specification is easier to use, but does not scale
                            when the user zooms in or out in the draw widget. The
                            real space option requires one to have good values
                            for diameters, and take care that the units are
                            correct, or the lines may be so thick that they fill
                            the screen.  Note that these values are the thickness
                            of the thickest compartment (usually the soma). The
                            remaining compartments will be scaled linearly
                            towards zero. The dependence on diamin and diamax is
                            described above.  The default value of diarange is
                            -20, meaning that the thickest compartment will be
                            drawn with a line 20 pixels wide.

                    autocol When set to 1 (or TRUE), colmin and colmax are set to
                            the minimum and maximum values of the displayed field
                            in the cell, each time the pix is updated.  The
                            default is 0 (FALSE), meaning that colmin and colmax
                            should be set by the user.

                    autodia When set to the default value of 1 (or TRUE), the
                            diamin and diamax values are automatically set to the
                            minimum and maxiumum compartment diameters of the cell
                            being represented.  In order to set diamin and diamax
                            to other values, set autodia to 0 (or FALSE) before
                            setting diamin and diamax.

                    soma    contains the index of the compartment to be displayed
                            as a spherical soma.  When the xcell is created with
                            the default value of -1, the soma field is
                            automatically reset to the index of the compartment
                            having the largest diameter.  When it has a value of
                            -2, all compartments are displayed as cylinders.

                    names   array of compartment names, eg. "showfield cell
                            names[10]".

                    path    sets the path (as a wildcard list) of all the
                            compartments (or symcompartments) to be displayed.
                            For example, /cell/##[TYPE=compartment] is a valid
                            path for a cell whose parent element is called /cell.

                    field   the field to be displayed by color.

                    fieldpath may be used to optionally specify the path to a
                            child element of the compartments, so that "field"
                            will refer to a field of this element, rather than a
                            field of the compartment.  For instance, one might
                            wish to display the current in an ion channel present
                            in some compartments.

                    labelmode  when set, will allow compartments to be labeled by
                            number or name (not yet implemented).

                    cellmode  specifies how to draw the cell.  The allowed values
                            are endcoords (the default) or midcoords. (One will
                            usually not want to change this.)

                    npts    When path is set, npts gives the number of compartments
                            which are represented.  This value is useful when
                            looping over the names, color, or dia tables.

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XCell [in src/Xodus/draw/xcell.c]

    Classes:        output gadget

    Actions:        DELETE COPY SET CREATE RESET PROCESS

                    XUPDATE: update internal fields when
                            displayed widget is changed.
                    B1DOWN: Invoked when mouse Button 1 is pressed.
                    B2DOWN: Invoked when mouse Button 2 is pressed.
                    B3DOWN: Invoked when mouse Button 3 is pressed.
                    ANYBDOWN:       Invoked when any mouse button is pressed.
                    B1DOUBLE: Invoked on a double click on mouse button 1.
                    B2DOUBLE: Invoked on a double click on mouse button 2.
                    B3DOUBLE: Invoked on a double click on mouse button 3.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field
                    XODROP: Called when a another pix is dropped onto this one.
                    XODRAG: Called when the mouse is clicked on this pix, and
                            the mouse moves while the mouse button is held down.
                    XOWASDROPPED: Called after this pix has been dropped onto
                            another one.

    Messages:       COLDIAPOS color dia x y z
                    COLDIA color dia
                    POSITION x y z
                    DIAMETER dia
                    COLOR color

    ------------------------------------------------------------------------------

    Notes:          The xmin, xmax, ymin, and ymax fields of the parent draw
                    widget should be set to values which are appropriate for the
                    dimensions of the cell.  As with other pixes displayed in a
                    draw widget, the arrow keys may be used to translate the image
                    in the draw, and "<" and ">" to zoom out (smaller) and in
                    (larger).  Likewise, the coordinate transformations described
                    in the xdraw documentation are available.  You may find these
                    keyboard commands useful for fine tuning the xmin, xmax, ymin,
                    and ymax fields.  Then, after inspecting them with showfield,
                    you may enter the final values in your script.

                    The messages which are accepted by the cell pix are usually
                    issued automatically, and not explicitly added by SLI addmsg
                    commands.  As may be verified with the showmsg command, each
                    compartment which is represented in the xcell sends a COLOR
                    message to the xcell, giving the value of the field which is
                    to be mapped to a color.

    Example:

        // traub91proto.g and CA3.p should be copied from Scripts/traub91
        include traub91proto.g

        // Create a library of prototype elements to be used by the cell reader
        create neutral /library
        pushe /library
        create symcompartment symcompartment
        make_Na
        make_Ca
        make_K_DR
        make_K_AHP
        make_K_C
        make_K_A
        make_Ca_conc
        pope

        // Build the cell from a parameter file using the cell reader
        readcell CA3.p /cell

        // create and display the xcell
        create xform /cellform [620,50,400,400]
        create xdraw /cellform/draw [0,0,100%,100%]
        setfield /cellform/draw xmin -0.003 xmax 0.001 ymin -5e-5 ymax 5e-5 \
            zmin -1e-3 zmax 1e-3
        xshow /cellform
        echo creating xcell
        create xcell /cellform/draw/cell
        // Note that this particular cell uses symcompartments, not compartments
        setfield /cellform/draw/cell colmin -0.1 colmax 0.1 \
            path /cell/##[TYPE=symcompartment] field Vm \
        script "echo widget clicked on = <w> value = <v>"
        xcolorscale hot
        reset

See also: xpix , xview , xdraw , Clicks

## 26.73 xcoredraw

    Object Type:    xcoredraw

    Description:    Foundation object class for displaying pixes. All other
                    draw classes (at present: dumbdraw, draw, and graph) are
                    subclassed from coredraw. Therefore these subclasses perform
                    a superset of the operations described here.
                    Coredraw and its subclasses can be thought of as providing
                    a window into a space where pixes reside, or a screen onto
                    which pixes are projected. One can select the size,
                    orientation and other parameters of this window/screen
                    according to the set of functions described below.
                    The functions provided by coredraw, which are inherited or
                    overridden by its subclasses, include:
                            Displaying and managing pixes.
                            Handling forward transforms for drawing pixes
                            Handling backward transforms for identifying
                                    location of mouse events
                            Keyboard control over transformation parameters
                                    such as zoom and pan.
                            Providing a mechanism for deciding which child
                                    pix should recieve mouse events

                    Coredraw and subclassses do not display anything on their own.
                    The pixes provide the actual images and drawing routines
                    displayed in a coredraw widget/subclasses. It is important
                    to note that since the pix display, transformation and event
                    handling functions are present in the coredraw class, any pix
                    can be displayed in any draw subclass.

                    The coredraw widget can only display pixes using planar
                    orthographic projections in the xy plane. In other
                    words, x is to the right, y is up and the z coordinate
                    of pixes is ignored.

                    In a future revision the z coordinate will be used to determine
                    the order of redrawing pixes to enable pixes to obscure
                    each other according to depth.

                    Unless flexibility in transformation options would be
                    a handicap (e.g., in displaying a simulation layout where
                    alternative projections would just confuse matters) the
                    coredraw widget is not especially useful for displays.
                    The draw widget is recommended for all cases where
                    flexibility is desired, since the overhead in performing
                    the general transformations is minimal.

    Author:         Upi Bhalla Caltech April 93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xcoredraw_type [in src/Xodus/draw/xcoredraw_struct.h

    Size:           ?

    Fields:         fg      Foreground color of coredraw (not used)
                    bg      Background color.
                    xgeom   Position of left edge of coredraw.
                    ygeom   Position of upper edge of coredraw.
                    wgeom   Width of coredraw
                    hgeom   Height of coredraw
                    xmin    left edge of window for displaying pixes.
                    ymin    bottom edge of window for displaying pixes.
                    xmax    right edge of window for displaying pixes.
                    ymax    top edge of window for displaying pixes.
                    script  Script operation(s) to perform on a mouse
                            click. The script calls to the coredraw widget
                            are only made if none of the child pixes has
                            expressed an interest in the event.

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XCoreDraw [in src/Xodus/widg/xcoredraw.c]

    Classes:        widget output

    Actions:        XUPDATE: update internal fields when
                            displayed widget is changed.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field
                    XODROP: Called when a pix is dropped into the widget.

    Messages:       none.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a form widget
                    The xcoredraw does not perform any computational operations
                    driven by the simulation clock.

    Example:
                    create xform /form [0,0,500,500]
                    create xcoredraw /form/coredraw [0,0,100%,100%] \
                            -bg red -script "echo Hello, I am a coredraw widget"
                    setfield /form/coredraw xmin -2 xmax 2 ymin -2 ymax 2
                    // display the pixes here
                    create xsphere /form/coredraw/sphere -fg green -r 1\
                            -script "echo Hello, I am a sphere pix"
                    xshow /form

See also: XODUS documentation, pix documentation, documentation for coredraw subclasses.

## 26.74 xdialog

    Object Type:    xdialog

    Description:    Maintains dialog state and executes script actions
                    from mouse button presses.

    Author:         Maneesh Sahani / Upi Bhalla  Caltech May/93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xdialog_type [in src/Xodus/widg/xdialog_struct.h]

    Size:           116 bytes

    Fields:         fg      Foreground color of text in dialog
                    bg      Background color.
                    xgeom   Position of left edge of dialog.
                    ygeom   Position of upper edge of dialog.
                    wgeom   Width of dialog.
                    hgeom   Height of dialog.
                    label   optional text string to display in button.
                            Defaults to widget name in the GENESIS hierarchy.
                    font    optional font for text in on state.
                    value   Maintains character string displayed in widget.
                    fvalue  Maintains float containing converted value of
                            widget.
                    script  string representing operations to be performed
    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XDialog [in src/Xodus/widg/xdialog.c]

    Classes:        widget output

    Actions:
                    B1DOWN: Button 1 pressed to turn on dialog (left mouse button)
                    B2DOWN: Button 2 pressed to turn on dialog
                            (middle button on 3 button mouse)
                    B3DOWN: Button 3 pressed to turn on dialog
                            (right button on 3 button mouse)
                    ANYBDOWN: Any button pressed.
                    KEYPRESS: Any key pressed.
                    XPDATE: update internal fields when widget is changed.

    Messages:       INPUT.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a form widget
                    The xdialog does not perform any computational operations.
                    It issues script calls depending on button presses and
                    'returns'. It can also display the value of incoming messages.

    Example
                    create xform /form [0,0,500,100]
                    create xdialog /form/dialog1 [0,0,100%,100%] \
                            -label "dialog" \
                            -fg green \
                            -bg black \
                            -font r24 \
                            -script "echo The value on <widget> is: <value>"
                    xshow /form

See also: Widget documentation. Mouse events documentation ( Clicks )

## 26.75 xdraw

    Object Type:    xdraw

    Description:    Main object class for displaying pixes. Subclassed
                    from coredraw. This widget provides general projection
                    transforms for pixes.
                    Like other coredraw subclasses, draw can be thought of as
                    providing a window into a space where pixes reside, or a
                    screen onto which pixes are projected. One can select the size,
                    orientation and other parameters of this window/screen
                    according to the set of functions described below.
                    The functions provided by draw, which are inherited or
                    overridden from the coredraw class, include:
                            Displaying and managing pixes.
                            Handling forward transforms for drawing pixes
                            Handling backward transforms for identifying
                                    location of mouse events
                            Keyboard control over transformation parameters
                                    such as zoom and pan.
                            Providing a mechanism for deciding which child
                                    pix should recieve mouse events

                    Draw does not display anything on its own. The pixes
                    provide the actual images and drawing routines displayed
                    in a draw widget.

                    Keyboard commands may be used to translate or zoom the display
                    of pixes within a draw widget.  Use the arrow keys to
                    translate the image in the draw, and "<" and ">" to zoom out
                    (make smaller) and in (make larger).

                    The draw widget can display pixes using both orthographic
                    and perspective projections.  One can select between these
                    using keyboard commands as follows:

                    plane                   perspective     key
                    -------------------------------------------
                    xy                      off             z
                    xy                      on              Z
                    yz                      off             x
                    yz                      on              X
                    xz                      off             y
                    xz                      on              Y
                    general orthographic    off             o
                    general perspective     on              p

                    In a future revision the z coordinate will be used to determine
                    the order of redrawing pixes to enable pixes to obscure
                    each other according to depth.

    Author:         Upi Bhalla Caltech April 93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xdraw_type [in src/Xodus/draw/xdraw_struct.h

    Size:           172 bytes

    Fields:         fg      Foreground color of draw (not used)
                    bg      Background color.
                    xgeom   Position of left edge of draw.
                    ygeom   Position of upper edge of draw.
                    wgeom   Width of draw
                    hgeom   Height of draw
                    xmin    x lower limit for displaying pixes.
                    ymin    y lower limit for displaying pixes.
                    zmin    z lower limit for displaying pixes.
                    xmax    x upper limit for displaying pixes.
                    ymax    y upper limit for displaying pixes.
                    zmax    z upper limit for displaying pixes.
                    cx      x coord of point in space which is to be located
                            at center of projection
                    cy      y coord of point at center of projection
                    cz      z coord of point at center of projection
                    wx      window 'width'. Provided for backwards compatibility.
                    wy      window 'height'. Provided for backwards compatibility.
                    vx      x coord of viewpoint for 'o' and 'p' projections.
                    vy      y coord of viewpoint for 'o' and 'p' projections.
                    vz      z coord of viewpoint for 'o' and 'p' projections.
                    script  Script operation(s) to perform on a mouse
                            click. The script calls to the draw widget
                            are only made if none of the child pixes has
                            expressed an interest in the event.
                    transform       The projection transformation to
                            perform while displaying the pixes.  One of
                            (z, Z, x, X, y, Y, o, p), described in the table
                            above.

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XDraw [in src/Xodus/draw/xdraw.c]

    Classes:        widget output

    Actions:        XUPDATE: update internal fields when
                            displayed widget is changed.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field
                    XODROP: Called when a pix is dropped into a draw widget.

    Messages:       CENTER cx cy cz
                    ZOOM   wx wy
                    VIEWPOINT vx vy vz
                            where the values of these messages set the
                            specified projection controlling fields.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a form widget
                    If the xdraw is receiving messages it will recalculate
                    the projections each clock tick.

    Example
                    create xform /form [0,0,500,500]
                    create xdraw /form/draw [0,0,100%,100%] \
                            -bg red -script "echo Hello, I am a draw widget"
                    setfield /form/draw xmin -2 xmax 2 ymin -2 ymax 2
                    // display the pixes here
                    create xsphere /form/coredraw/sphere -fg green \
                            -script "echo Hello, I am a sphere pix"
                    xshow /form

    See also:       Widget documentation, pix documentation, documentation
                    for coredraw and other subclasses.

## 26.76 xdumbdraw

    Object Type:    xdumbdraw

    Description:    Demonstration object class for displaying pixes. Subclassed
                    from coredraw. While this widget is functional, it is not
                    particularly useful for anything other than demo purposes for
                    code developers.
                    The coredraw widget should be used if the projections need
                    to be restricted to the xy plane, and the draw widget in
                    other cases.
                    Like other coredraw subclasses, dumbdraw can be thought of as
                    providing a window into a space where pixes reside, or a
                    screen onto which pixes are projected. One can select the size,
                    orientation and other parameters of this window/screen
                    according to the set of functions described below.
                    The functions provided by coredraw, which are inherited or
                    overridden by its subclasses, include:
                            Displaying and managing pixes.
                            Handling forward transforms for drawing pixes
                            Handling backward transforms for identifying
                                    location of mouse events
                            Keyboard control over transformation parameters
                                    such as zoom and pan.
                            Providing a mechanism for deciding which child
                                    pix should recieve mouse events

                    Dumbdraw does not display anything on its own. The pixes
                    provide the actual images and drawing routines displayed
                    in a dumbdraw widget.

                    The dumbdraw widget can only display pixes using planar
                    orthographic projections. One can select between the
                    xy, yz and xz planes using the keyboard commands
                    z,  x, and y  respectively.

                    In a future revision the z coordinate will be used to determine
                    the order of redrawing pixes to enable pixes to obscure
                    each other according to depth.

    Author:         Upi Bhalla Caltech April 93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xdumbdraw_type [in src/Xodus/draw/xdumbdraw_struct.h

    Size:           ?

    Fields:         fg      Foreground color of dumbdraw (not used)
                    bg      Background color.
                    xgeom   Position of left edge of dumbdraw.
                    ygeom   Position of upper edge of dumbdraw.
                    wgeom   Width of dumbdraw
                    hgeom   Height of dumbdraw
                    xmin    x lower limit for displaying pixes.
                    ymin    y lower limit for displaying pixes.
                    zmin    z lower limit for displaying pixes.
                    xmax    x upper limit for displaying pixes.
                    ymax    y upper limit for displaying pixes.
                    zmax    z upper limit for displaying pixes.
                    script  Script operation(s) to perform on a mouse
                            click. The script calls to the dumbdraw widget
                            are only made if none of the child pixes has
                            expressed an interest in the event.
                    transform       The projection transformation to
                            perform while displaying the pixes.
                            z = xy plane
                            y = xz plane
                            x = yz plane.
                            (think of it as looking down from the selected
                            axis (eg, z) onto a plane (eg, xy).

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XDumDraw [in src/Xodus/widg/xdumbdraw.c]

    Classes:        widget output

    Actions:        XUPDATE: update internal fields when
                            displayed widget is changed.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field
                    XODROP: Called when a pix is dropped into a draw widget.

    Messages:       none.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a form widget
                    The xdumbdraw does not perform any computational operations
                    driven by the simulation clock.

    Example:
                    create xform /form [0,0,500,500]
                    create xdumbdraw /form/dumbdraw [0,0,100%,100%] \
                            -bg red -script "echo Hello, I am a dumbdraw widget"
                    setfield /form/dumbdraw xmin -2 xmax 2 ymin -2 ymax 2
                    // display the pixes here
                    create xsphere /form/dumbdraw/sphere -fg green -r 1 \
                            -script "echo Hello, I am a sphere pix"
                    xshow /form

    See also:       XODUS documentation, pix documentation, documentation
                    for coredraw and other subclasses.

## 26.77 xfastplot

    Object Type:    xfastplot

    Description:    Optimised but limited graphing widget. Designed mainly for
                    high-speed display similar to an oscilloscope. Also designed
                    to use minimal memory so that large numbers of xfastplots
                    can be in use simultaneously. Limitations are that the number
                    of points on the plot must be known in advance, axes are
                    rudimentary, and only single plots are possible.

                    Plots in 6 modes, related to what an oscilloscope might do.
                    roll, oscilloscope, ring, xyring, waveplot, xywaveplot.

                    roll: New data points appear on the right and the old data
                    points shift leftwards.

                    oscilloscope: Trace fills in data points from left to right,
                    clearing after screen is full. Various trigger options.

                    ring: Similar to oscilloscope except that screen does not
                    clear. Instead the oldest points are overwritten. No triggering.

                    xyring: Same as ring except both x and y coordinates are
                    specified by separate messages for each point. Oldest points
                    are overwritten.

                    waveplot: All the Y points on the plot are simultaneously
                    specified. X points increase linearly across the plot.
                    Previous plot is lost.

                    xywaveplot: X and Y coordinates for all points are
                    simultaneously specified by separate messages for each point.

                    Each mode can be displayed using points or lines. Overlay
                    can be enabled for any mode, in which case old points are not
                    erased.

                    The color of each new set of data points can be
                    specified by the COLOR message.

                    Data points can abe added a variable number of points at a
                    time (Roll, oscilloscope, ring and xyring modes).  Here the
                    NPLOT message is used. The first argument is the first entry
                    in an array of data points (e.g. an interpol_struct). The
                    second argument is the number of points to be plotted, and the
                    third is the starting index in the array.  Scalar fields (e.g.
                    Vm) can be plotted as single-entry arrays with a starting
                    index of 0.  The XPLOT message can be used along with NPLOT to
                    specify xyring mode. In this case, the argument to the XPLOT
                    message is the first entry in the corresponding X array of
                    data points.

                    Data points can also be plotted a full screen at a time
                    (waveplot or xywaveplot modes). The WAVEPLOT message
                    is used, and the argument of the message is the first
                    entry in the array of Y data points. If the XPLOT message
                    is also present, this becomes an xywaveplot. Again, the
                    argument of the XPLOT message is the first entry in the
                    array of X data points.

                    The fastplot widget has a number of special key and mouse
                    mappings:

                    event           operation
                    -------------------------------------------------------
                    arrow keys      Move the little tick marks on the x and
                                    y axes up and down. The xval and yval
                                    fields are updated to match the position
                                    of the tick marks. This event triggers script
                                    function calls if the function has the
                                    .k suffix.

                    Mouse button    Standard click operations. Passes x and y
                                    coordinate values to the script using
                                    the <x> and <y> special arguments.

    Author:         Upi Bhalla NCBS Bangalore May 1998

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xfastplot_type [in src/Xodus/widg/xfastplot_struct.h]

    Size:           384 bytes (element) + 236 bytes (graphics) + 4 * npts (data)

    Fields:         fg      Foreground color of graph (used for axes and labels)
                    bg      Background color.
                    xgeom   Position of left edge of graph.
                    ygeom   Position of upper edge of graph.
                    wgeom   Width of graph
                    hgeom   Height of graph
                    npts    int, number of points in plot.
                    overlay_flag    If 1, overlay output traces rather than clearing
                    line_flag       If 1, draw lines rather than dots
                    roll_flag       If 1, use roll mode rather than ring mode
                    oscope_flag     If 1, use oscilloscope mode rather than ring
                    trig_sign       0: Auto triggering
                                    1: Trigger on +ve going events
                                    -1: Trigger on -ve going events
                    ac_trig_flag    0: DC trig
                                    1: AC trig
                    trig_thresh     (double): Threshold for triggering.
                    update_dt       average dt to maintain between X updates
                    request_dt      Not yet used
                    xval            Position of x tick mark
                    yval            Position of y tick mark
                    xaxis_flag      Draw x axis and tick if 1
                    yaxis_flag      Draw y axis and tick if 1
                    color           Color (0 - 64) to use for next point(s)
                    title           Title text, top middle of graph
                    xtextmax        X axis top text, lower right of graph
                    xtextmid        X axis middle text, lower middle of graph
                    xtextmin        X axis origin text, lower left of graph
                    ytextmax        Y axis top text, top left of graph
                    ytextmid        Y axis middle text, middle left of graph
                    ytextmin        Y axis origin text, lower left of graph
                    script          Script function to execute on clicks and
                                    key events.
                    shortptr_flag   If 1, treat the message as a pointer to
                                    a short. Needed to work around a GENESIS
                                    messaging limitation.

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       FastPlot [in src/Xodus/widg/xfastplot.c]

    Classes:        widget output

    Actions:        XUPDATE: update internal fields when
                            displayed widget is changed.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field
                    PROCESS: Update the plot display with new values
                    RESET: Clear out the plot display, zero out the values
                    CREATE: Make the plot
                    SET: used to handle special cases of set where memory
                            allocation is involved. The remainder
                            use the generic GENESIS set methods.
                    DELETE: Destroys the element and widget and storage

    Messages:
                    NPLOT   data_array n index
                            The first argument is the first entry in the data
                            array.  The second argument is the number of entries
                            to use for data, and the third argument is the index
                            of the starting data entry.
                    WAVEPLOT data_array n
                            The first argument is the first entry in the data
                            array.  The second argument is the number of points to
                            use.
                    XPLOT   data
                            This message is only used in combination with NPLOT or
                            WAVEPLOT.  The data argument is the first entry in the
                            x data array.
                    COLOR   data
                            An integer from 1 to 64.
                    UPDATE_DT
                            Not yet implemented.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a form widget

    Example: This example sets up 20 xfastplots getting various kinds of inputs.
    The inputs are shown in the conventional xgraph on the left of the screen.
    Most of this example is actually devoted to setting up interesting inputs.
    The type of the xfastplot is indicated in the title of each plot.
    The display mode is indicated at the bottom.

    ================================= cut here =================================
    //genesis
    int i, j

    xcolorscale rainbow

    create xform /form [0,0,1000,600]
    create xgraph /form/graph [0,0,30%,100%] \
            -xmax 400 -ymax 4 -yoffset 1 -ymin -1
    for (i = 0; i < 5; i = i + 1)
            for (j = 0; j < 4; j = j + 1)
                    create xfastplot /form/plot{i}{j} \
                            [{i * 12 + 30}%,{j * 15}%,12%,15%]
            end
    end
    xshow /form

    create xform /form2 [500,500,200,220]
    create xbutton /form2/quit -script quit
    create xtoggle /form2/overlay \
            -onlabel "Overlay ON" -offlabel "Overlay OFF" \
            -script "do_set overlay_flag <v>"
    create xtoggle /form2/line \
            -onlabel "Line mode" -offlabel "Dot mode" \
            -script "do_set line_flag <v>"
    create xtoggle /form2/xaxis \
            -onlabel "X axis on" -offlabel "X axis off" \
            -script "do_set xaxis_flag <v>"
    create xtoggle /form2/yaxis \
            -onlabel "Y axis on" -offlabel "Y axis off" \
            -script "do_set yaxis_flag <v>"
    create xbutton /form2/run -script "step 400"
    create xbutton /form2/reset -script reset
    xshow /form2

    create table /tab[0]
    call /tab[0] TABCREATE 100 0 100
    for (i = 0; i < 101; i = i + 1)
            setfield /tab[0] table->table[{i}] {sin {i / 10.0}}
    end
    setfield /tab[0] step_mode 1

    create table /tab[1]
    call /tab[1] TABCREATE 1 0 100
    setfield /tab[1] table->table[0] 0
    setfield /tab[1] table->table[1] 1
    setfield /tab[1] step_mode 1

    create table /tab[2]
    call /tab[2] TABCREATE 100 0 100
    for (i = 0; i < 101; i = i + 1)
            setfield /tab[2] table->table[{i}] {sin {0.5 + i / 17.0}}
    end
    setfield /tab[2] step_mode 1

    create table /tab[3]
    call /tab[3] TABCREATE 100 0 100
    for (i = 0; i < 101; i = i + 1)
            setfield /tab[3] table->table[{i}] {rand 0 1}
    end
    setfield /tab[3] step_mode 1

    create table /tab[4]
    call /tab[4] TABCREATE 100 0 100
    for (i = 1; i < 51; i = i + 1)
            addmsg /tab[4] /tab[4] INPUT2 table->table[{i}] {i - 1}
            addmsg /tab[4] /tab[4] INPUT2 table->table[{100 - i}] {101 - i}
    end
    addmsg /tab[0] /tab[4] INPUT2 output 50
    setfield /tab[4] step_mode 5

    create table /tab[5]
    call /tab[5] TABCREATE 100 0 100
    for (i = 1; i < 51; i = i + 1)
            addmsg /tab[5] /tab[5] INPUT2 table->table[{i}] {i - 1}
            addmsg /tab[5] /tab[5] INPUT2 table->table[{100 - i}] {101 - i}
    end
    addmsg /tab[2] /tab[5] INPUT2 output 50
    setfield /tab[5] step_mode 5

    create table /tab[6]
    call /tab[6] TABCREATE 63 0 63
    for (i = 0; i < 64; i = i + 1)
            setfield /tab[6] table->table[{i}] {i}
    end
    setfield /tab[6] step_mode 1
    addmsg /tab[6] /form/plot# COLOR output

    addmsg /tab[0] /form/graph PLOT output *tab0 *red
    addmsg /tab[1] /form/graph PLOT output *tab1 *green
    addmsg /tab[2] /form/graph PLOT output *tab2 *blue
    addmsg /tab[3] /form/graph PLOT output *tab3 *black

    for (i = 0; i < 4; i = i + 1)
            addmsg /tab[{i}] /form/plot0{i} NPLOT output 1 0
            setfield /form/plot0{i} title NPLOT npts 256

            addmsg /tab[{i %2 + 4}] /form/plot1{i} NPLOT table->table[0] index 0
            setfield /form/plot1{i} title NPLOT npts 256

            addmsg /tab[{i % 2 + 4}] /form/plot2{i} WAVEPLOT table->table[0] 100
            setfield /form/plot2{i} title WAVEPLOT npts 100

            addmsg /tab[{i}] /form/plot3{i} NPLOT output 1 0
            addmsg /tab[{(i + 1)%4}] /form/plot3{i} XPLOT output
            setfield /form/plot3{i} title XYRING npts 256 xmin -1 xmax 1

            addmsg /tab[{i % 2 + 4}] /form/plot4{i} WAVEPLOT table->table[0] 100
            addmsg /tab[{(i + 1)%2 + 4}] /form/plot4{i} XPLOT table->table[0]
            setfield /form/plot4{i} title XYWAVEPLOT npts 100 xmin -1 xmax 1
    end

    setfield /form/plot00 xtextmid ring
    setfield /form/plot01 xtextmid ring
    setfield /form/plot02 roll_flag 1 xtextmid roll
    setfield /form/plot03 oscope_flag 1 xtextmid oscope

    setfield /form/plot10 xtextmid ring
    setfield /form/plot11 xtextmid ring
    setfield /form/plot12 roll_flag 1 xtextmid roll
    setfield /form/plot13 oscope_flag 1 xtextmid oscope

    setfield /form/plot# script "echo Hi from <w>; show_val.k <w>" ymin -1

    function do_set(field, value)
            str field
            int value

            setfield /form/plot# {field} {value}
    end

    function show_val(widget)
            echo xval={getfield {widget} xval}, yval={getfield {widget} yval}
    end

    reset

    ================================= cut here =================================

See also: xgraph , XODUS documentation

## 26.78 xform

    Object Type:    xform

    Description:    Containing window for other graphical interface objects.

    Author:         Maneesh Sahani Caltech July/92

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xform_type [in src/Xodus/widg/xform_struct.h

    Size:           124 bytes

    Fields:         fg      Foreground color (not used)
                    bg      Background color (not used)
                    xgeom   Position of left edge of form with respect to screen.
                            This value is an integer. If it is suffixed with a
                            '%' symbol (eg set form xgeom 20%) then percent of
                            screen size is used.
                    ygeom   Position of upper edge of form with respect to screen.
                    wgeom   Width of form
                    hgeom   Height of form
                            The geometry fields can optionally be set on the
                            create line using the square brackets notation:
                            [xgeom,ygeom,wgeom,hgeom]
                    title   Optional text string to be placed on top of widget.
                            Currently only available at create time.
                    nested  Read-only flag that indicates if the form was created
                            as an embedded form or not.
                            (1 => embedded, 0 => top-level)

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XForm [in src/Xodus/widg/xform.c]

    Classes:        widget

    Actions:        XUPDATE: update internal fields when
                            displayed widget is changed.

    Messages:       none.

    ----------------------------------------------------------------------------

    Notes:          Invisible until 'xshow' command is issued unless it is
                    created as an embedded form with the '-nested' option.

                    One could also create an embedded form and
                    make it invisible by default using the '-noautomap' option
                    in conjunction with the '-nested' option. For obvious
                    reasons, the '-noautomap' option is superfluous when used
                    with top-level forms.

                    The xform does not perform any computational operations.

                    Important: xforms are top-level unless created with the
                               -nested option.

    Example
                    create xform /foo [0,0,500,50%] -title "I am a top-level form"
                    xshow /foo

                    create xform /foo/embedded_foo [0,0,100%,40%] -nested -title \
                            "I am an embedded form"

                    create xform /foo/popup_foo [20,20:embedded_foo,,] -nested  \
                            -noautomap -title "xshow/xhide to map/unmap me"

See also: Scripts/examples/XODUS/widgets.g, XODUS documentation.

## 26.79 xgif

    Object Type:    xgif

    Description:    Displays gif images as a pix within a draw.

    Author:         Upi Bhalla / Jason Leigh Aug/93

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xgif_type  [in  src/Xodus/draw/xgif_struct.h]

    Size:           124 bytes

    Fields:
                    fg      Foreground color (not currently used).
                    script  Script operation(s) to perform on a mouse
                            click. The script calls of the pix are only made
                            if the draw determines that the pix is the nearest
                            to the event and if the event occurred within the
                            bounding region of the pix.

                    value   Set with setfield, and accessible in script functions
                            with the <v> or <value> argument.

                    tx      Transposition distance in the x dimension. The
                            pix is transposed (ie, displaced, offset) by this
                            amount.
                    ty      Transposition in y.
                    tz      Transposition in z.
                    pixflags        Set of flags specifying visibility,
                            refreshes, mouse sensitivity and many other options.
                            Use the 'pixflags' utility function to find out more.

                    filename   Name of the file containing the image.
                    format  Image format.  The default, gif, is the only format
                            currently supported.
                    srcx    left margin of image in gif file (not currently used).
                    srcy    top margin of image in gif file (not currently used).
                    dstx    left margin of image in draw (not currently used).
                    dsty    top margin of image in draw (not currently used).

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XGif  [in src/Xodus/draw/xgif.c]

    Classes:        output, gadget

    Actions:        DELETE COPY SET CREATE RESET PROCESS
                    XUPDATE: update internal fields when
                            displayed widget is changed.
                    B1DOWN: Invoked when mouse Button 1 is pressed.
                    B2DOWN: Invoked when mouse Button 2 is pressed.
                    B3DOWN: Invoked when mouse Button 3 is pressed.
                    ANYBDOWN:       Invoked when any mouse button is pressed.
                    B1DOUBLE: Invoked on a double click on mouse button 1.
                    B2DOUBLE: Invoked on a double click on mouse button 2.
                    B3DOUBLE: Invoked on a double click on mouse button 3.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field
                    XODROP: Called when a another pix is dropped onto this one.
                    XODRAG: Called when the mouse is clicked on this pix, and
                            the mouse moves while the mouse button is held down.
                    XOWASDROPPED: Called after this pix has been dropped onto
                            another one.

    Messages:       none

    ------------------------------------------------------------------------------

    Notes:          Unlike ximage, which displays a gif image in a form, xgif
                    displays the image as a pix inside a draw widget.

    Example:        Scripts/examples/XODUS/draws.g

See also: ximage , xpix

## 26.80 xgraph

    Object Type:    xgraph

    Description:    Main object class for displaying graphs. Subclassed
                    from coredraw. This widget provides many special functions
                    for helping to display graphs.
                    Like other coredraw subclasses, graph can be thought of as
                    providing a window into a space where pixes reside, or a
                    screen onto which pixes are projected. Usually the only
                    pixes displayed in a graph widget are xplots and xaxis
                    pixes. Furthermore, xplots are usually not created explicitly
                    and are instead automatically generated when the graph is
                    created or receives messages. The axis pixes for the x and
                    y axes are created automatically when the xgraph is created.

                    The functions provided by xgraph, which are inherited or
                    overridden from the coredraw class, include:
                            Displaying and managing pixes.
                            Handling forward transforms for drawing pixes
                            Handling backward transforms for identifying
                                    location of mouse events
                            Keyboard control over transformation parameters
                                    such as zoom and pan.
                            Providing a mechanism for deciding which child
                                    pix should recieve mouse events

                    The graph widget can only display pixes in the xy plane.

                    The graph widget has a number of special key and mouse
                    mappings:

                    event           operation
                    -------------------------------------------------------
                    'a'             'all' : Change the axes to display all
                                    the plots in their entirety.

                    arrow keys      change the x and y axis offsets.

                    shift-arrow     Change the scale on the x and y axes.
                    keys

                    ctrl-arrow      Change the lower boundaries of the graph
                    keys

                    shift-ctrl-arrow  Change the upper boundaries of the graph
                    keys

                    Mouse events    Selects plots, and passes appropriate
                    on labels       actions to the scripts associated with the
                    for plots       plots.

                    Click and drag  Changes the selected axis range
                    on upper/lower
                    values of axes

                    Click and drag  Changes the selected axis offset.
                    on middle
                    values of axes

                    ctrl-p          Prints the graph to a postscript
                                    printer/file

    Author:         Upi Bhalla Mt. Sinai May 93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xgraph_type [in src/Xodus/graph/xgraph_struct.h]

    Size:           184 bytes

    Fields:         fg      Foreground color of graph (not used)
                    bg      Background color.
                    xgeom   Position of left edge of graph.
                    ygeom   Position of upper edge of graph.
                    wgeom   Width of graph
                    hgeom   Height of graph
                    xmin    x lower limit for axis for plots. Note that the is
                            NOT the lower limit of the region in which pixes
                            can be drawn. That is given by cdxmin.
                    ymin    y lower limit for axis
                    xmax    x upper limit for axis
                    ymax    y upper limit for axis
                    cdxmin  x lower limit for draw region of graph
                    cdymin  y lower limit for draw region of graph
                    cdxmax  x upper limit for draw region of graph
                    cdymax  y upper limit for draw region of graph
                    xoffset X-offset to apply to successive plots in the graph.
                    yoffset Y-offset to apply to successive plots in the graph.
                    overlay Flag for whether or not to save old plots. If
                            set to 0, old plots are discarde. If set to 1,
                            old plots are retained and moved into the
                            subelement 'xoverlay' which is a child of the
                            graph.
                    script  Script operation(s) to perform on a mouse
                            click. The script calls to the graph widget
                            are only made if none of the child pixes has
                            expressed an interest in the event.
                    title   Title text, top middle of graph
                    xlabel  Label text, centered under x-axis
                    XUnits  Units text, at end of x-axis
                    ylabel  Label text, vertically to left of y-axis
                    YUnits  Units text, at end of y-axis

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XGraph [in src/Xodus/widg/xgraph.c]

    Classes:        widget output

    Actions:        XUPDATE: update internal fields when
                            displayed widget is changed.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field
                    XODROP: Called when a pix is dropped into a draw widget.
                    ADDMSGIN: Monitors commands for adding messages. If a
                            PLOT, PLOTSCALE or WAVEPLOT message is received,
                            the appropriate xplot pixes are created.

    Messages:       PLOT    data name color
                            In this mode successive data points are added to
                            the end of the plot as the simulation progresses.
                    PLOTSCALE data name color scale yoffset
                            Similar to PLOT, except that the scale and yoffset
                            of this plot are also included in the message.
                    X       x-coordinate-of-PLOT-msg name-of-corresponding-PLOT-msg
                            This is used for creating xy (phase) plots. To use
                            this, first the PLOT msg must be sent, then the
                            corresponding X msg can be set up. See the
                            example below.
                    WAVEPLOT data name color
                            This is used to create a plot whose y coordinates
                            vary as the simulation progresses. For example,
                            if we have 10 waveplot messages with the same name,
                            they will specify 10 successive y coordinates on
                            a line. With every timestep the y coordinates get
                            updated so the effect is like the profile of a
                            travelling wave.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a form widget
                    The xgraph does not actually handle messages itself.
                    Instead it forwards them to the appropriate xplot
                    pix.

    Example.

    ================================= cut here =================================

    //genesis
    // This example tests the various graph modes. First click 'runit',
    // then click reset and then runit again.
    // Click on any of the plots to toggle their visibility

    create xform /form [1,1,500,800] -title "OUTPUT" -fg black
    ce /form
    create xbutton runit
        setfield runit script \
       "step 1000; setfield /form/instr1 fg black; setfield /form/instr2 fg blue"
    create xbutton reset -wgeom 50% -script reset
    create xbutton quit -ygeom 0:runit -xgeom 50% -wgeom 50% -script quit
    create xgraph /form/graph -hgeom 30%
    ce /form/graph
            setfield script "echo in graph" xmin 0 xmax 100 ymin -1 ymax 5
            setfield yoffset 2
            setfield xmax 1000 ymax 15
            setfield overlay 1

    create xgraph /form/phasegraph -hgeom 30%
    ce /form/phasegraph
            setfield script "echo in graph" xmin 0 xmax 100 ymin -1 ymax 5
            setfield yoffset 2
            setfield xmin -1 xmax 1 ymin -1 ymax 3
            setfield overlay 1

    create xgraph /form/wavegraph -hgeom 20%
    ce /form/wavegraph
            setfield script "echo in graph" xmin 0 xmax 100 ymin -1 ymax 5
            setfield xmin -0.5 xmax 1.5 ymin -1 ymax 1

    create xlabel /form/instr1 \
            -label "First click 'runit' to activate the demo." -fg blue
    create xlabel /form/instr2 \
            -label "After the run ends, click 'reset' and 'runit' again."
    create xlabel /form/instr3 \
            -label "Click on any of the plot names to toggle their visibility"
    int i
    create xplot /form/graph/foo
            ce /form/graph/foo
            for(i = 0; i < 200 ; i = i + 1)
                    setfield xpts->table[{i}] {i}
                    setfield ypts->table[{i}] {sin {i/10.0} }
            end
            setfield npts 200 fg blue wx 1 wy 1
            //set xmin 0 xmax 100 ymin -1 ymax 1 wx 1 wy 1
            ce ..

    create table /tab
            call /tab TABCREATE 400 0 400
            setfield /tab step_mode 1 stepsize 1
            for(i = 0; i < 400 ; i = i + 1)
                    setfield /tab table->table[{i}] {cos {5+ i/30.0} }
            end

    create table /tab2
            call /tab2 TABCREATE 400 0 400
            setfield /tab2 step_mode 1 stepsize 1
            for(i = 0; i < 400 ; i = i + 1)
                    setfield /tab2 table->table[{i}] {sin {4 +i/16.0} }
            end

    addmsg /tab /form/graph PLOT output *output *yellow
    addmsg /tab2 /form/graph PLOT output *output *green
    addmsg /tab2 /form/graph PLOTSCALE output *plotscale *red -0.5 0.5

    addmsg /tab /form/phasegraph PLOT output *output *yellow
    addmsg /tab2 /form/phasegraph X output *output

    addmsg /tab /form/wavegraph WAVEPLOT output *wave *blue
    addmsg /tab2 /form/wavegraph WAVEPLOT output *wave *blue

    setfield /form/#[TYPE=xgraph]/#[TYPE=xplot] script "toggle_visibility <w>"

    function toggle_visibility(widget)
            str widget
            if ({getfield {widget} pixflags} & 1)
                    setfield {widget} pixflags ~v
            else
                    setfield {widget} pixflags v
            end
    end

    xshow /form
    ================================= cut here =================================

See also: xplot , xaxis, XODUS documentation, pix documentation,documentation for coredraw and other subclasses.

## 26.81 ximage

    Object Type:    ximage

    Description:    Displays a gif image in a form.

    Author:         Jason Leigh U Illinois @ Chicago / Upi Bhalla  Caltech Feb/93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  ximage_type [in src/Xodus/widg/ximage_struct.h]

    Size:           depends on the image

    Fields:         fg      Not used
                    bg      Not used
                    xgeom   Position of left edge of image.
                    ygeom   Position of upper edge of image.
                    wgeom   Width of image.
                    hgeom   Height of image.
                    srcx    left margin of image in gif file
                    srcy    top margin of image in gif file
                    dstx    left margin of image in widget
                    dsty    top margin of image in widget
                    script  Script function to execute on button event.
                    filename   name of gif file to load.

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XImage [in src/Xodus/widg/ximage.c]

    Classes:        widget

    Actions:
                    B1DOWN: Button 1 pressed (left)
                    B2DOWN: Button 2 pressed (middle)
                    B3DOWN: Button 3 pressed (right)
                    ANYBDOWN: Any button pressed.
                    XUPDATE: update internal fields when
                            displayed widget is changed.

    Messages:       none.

    ----------------------------------------------------------------------------

    Notes:          An ximage can only be displayed in a form widget.
                    The ximage does not perform any computational operations,
                    but can issue script calls when the mouse is clicked in it.

                    srcx and srcy control the coordinates of the upper left corner
                    of the image to be displayed expressed relative to the origin
                    of the image itself.  dstx and dsty control the positioning of
                    the image relative to the parent form.  In the example below,
                    the changes to srcx and srcy would would strip out 40 pixels
                    from the left-side of the image and 50 pixels from the bottom
                    of the image.  The changes to dstx and dsty would shift the
                    image 40 pixels to the left and 20 pixels down from the parent
                    form.

    Example:
                    create xform /form [0,0,400,250]
                    create ximage /form/image [0,0,100%,100%] \
                            -filename xodus.gif  // in Scripts/examples/XODUS
                    xshow /form

                    // try these interactively, one at a time
                    setfield /form/image srcx 40 srcy -50
                    setfield /form/image dstx 40 dsty 20

See also: xgif , XODUS documentation, Mouse events documentation ( Clicks )

## 26.82 xlabel

    Object Type:    xlabel

    Description:    Static display for a text string.

    Author:         Maneesh Sahani Caltech July/92

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xlabel_type [in src/Xodus/widg/xlabel_struct.h]

    Size:           104 bytes

    Fields:         fg      Foreground color of text in label
                    bg      Background color.
                    xgeom   Position of left edge of label with respect to parent
                            form. This value is an integer. If it is suffixed with
                            a '%' symbol (eg set label xgeom 20%) then percent of
                            form size is used. Relative positions with respect
                            to other widgets can be specified by following the
                            distance with a :widgetname
                            (eg set label xgeom 20:otherwidget)
                    ygeom   Position of upper edge of label with respect to form.
                    wgeom   Width of label
                    hgeom   Height of label
                            The geometry fields can optionally be set on the
                            create line using the square brackets notation:
                            [xgeom,ygeom,wgeom,hgeom]
                    label   optional text string to display. Defaults to
                            widget name in the GENESIS hierarchy.
                    font    optional font for text.

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XLabel [in src/Xodus/widg/xlabel.c]

    Classes:        widget

    Actions:        XUPDATE: update internal fields when
                            displayed widget is changed.

    Messages:       none.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a form widget
                    The xlabel does not perform any computational operations.

    Example
                    create xform /form [0,0,500,500]
                    create xlabel /form/label1 [0,0,30%,50%] \
                            -label "I am a label" \
                            -fg red
                    create xlabel /form/label2 [0:/form/label1,0,50%,20%] \
                            -label "I am another label" \
                            -font r24 \
                            -bg red
                    xshow /form

See also: XODUS documentation.

## 26.83 xpix

    Object Type:    xpix

    Description:    Foundation object class for pixes. All other
                    pix classes are subclassed from pix. Therefore
                    these subclasses perform a superset of the operations
                    described here.
                    Pix and its subclasses can be thought of as being
                    graphical objects in a 3-d space, which can be viewed
                    using the coredraw widget and its subclasses. In the same
                    way that other widgets can only be created in a form,
                    pixes can only be created in a coredraw or a subclass
                    thereof. However, a pix need not be the direct child element
                    of a draw widget as long as the draw widget is somewhere
                    there among its ancestors.

                    The functions provided by pix, which are inherited or
                    overridden by its subclasses, include:
                            Specifying a set of coordinates.
                            Calling the transformation routines (which
                                    are specified by the draws).
                            Drawing an image based on the transformed coordinates.
                            Providing information to the draw for determining
                                    which pix should respond to a mouse click
                            Executing script functions in response to mouse or
                                    keyboard events.

                    Coredraw and subclassses do not display anything on their own.
                    The pixes provide the actual images and drawing routines
                    displayed in a coredraw widget/subclasses. It is important
                    to note that since the pix display, transformation and event
                    handling functions are present in the coredraw class, any pix
                    can be displayed in any draw subclass.

                    The exact transformation used to display the pix is defined
                    by the draw widget it lives in. Note that the coordinates of
                    the pix are not changed by any of the transformations.

                    In a future revision the z coordinate will be used to determine
                    the order of redrawing pixes to enable pixes to obscure
                    each other according to depth.

                    All pixes have a special field 'pixflags' which contains
                    a large number of options for drawing, projecting and so
                    on. The 'pixflags' utility function allows one to see the
                    options for this field. While pixflags can be set directly
                    to the appropriate hexadecimal number, there is a special
                    parser which will interpret options as set out by the
                    pixflags utility funciton.

    Author:         Upi Bhalla Caltech April 93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xpix_type [in src/Xodus/draw/xpix_struct.h

    Size:           ?

    Fields:         fg      Foreground color of pix.
                    script  Script operation(s) to perform on a mouse
                            click. The script calls of the pix are only made
                            if the draw determines that the pix is the nearest
                            to the event and if the event occurred within the
                            bounding region of the pix.
                    tx      Transposition distance in the x dimension. The
                            pix is transposed (ie, displaced, offset) by this
                            amount.
                    ty      Transposition in y.
                    tz      Transposition in z.
                    pixflags        Set of flags specifying visibility,
                            refreshes, mouse sensitivity and many other options.
                            Use the 'pixflags' utility function to find out more.

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XPix [in src/Xodus/widg/xpix.c]

    Classes:        gadget

    Actions:        XUPDATE: update internal fields when
                            displayed widget is changed.
                    B1DOWN: Invoked when mouse Button 1 is pressed.
                    B2DOWN: Invoked when mouse Button 2 is pressed.
                    B3DOWN: Invoked when mouse Button 3 is pressed.
                    ANYBDOWN:       Invoked when any mouse button is pressed.
                    B1DOUBLE: Invoked on a double click on mouse button 1.
                    B2DOUBLE: Invoked on a double click on mouse button 2.
                    B3DOUBLE: Invoked on a double click on mouse button 3.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field
                    XODROP: Called when a another pix is dropped onto this one.
                    XODRAG: Called when the mouse is clicked on this pix, and
                            the mouse moves while the mouse button is held down.
                    XOWASDROPPED: Called after this pix has been dropped onto
                            another one.

            Example: If pix A is moved onto pix B, the following sequence of
                     events is issued:
                            B1DOWN on A
                            XODRAG on A
                            XODROP on B
                            XOWASDROPPED on A.

    Messages:       none.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a coredraw widget subclass.
                    The xpix does not perform any computational operations
                    driven by the simulation clock.

    Example:        Scripts/examples/XODUS/clicks.g

See also: xcoredraw , Clicks

## 26.84 xplot

    Object Type:    xplot

    Description:    Main object class for displaying graphs. Subclassed
                    from pix. The xplot pix stores and plots sequences of points.
                    Like xpix, xplot can be thought of as being
                    graphical objects in a 3-d space, which can be viewed
                    using the coredraw widget and its subclasses. In the same
                    way that other widgets can only be created in a form,
                    xplots can only be created in a coredraw or a subclass
                    thereof. xplots are usually created in xgraph widgets,
                    which are a subclass of coredraw specialized for plotting
                    graphs.
                    Xplot at this time displays line plots only. There is no
                    facility at present for adding markers or error bars
                    to the points plotted.

            SPECIAL XPLOT CREATION FACILITY
                    For reasons of convenience and backwards compatibility,
                    there is a special facility for the automatic creation of
                    xplots when the appropriate messages are sent to the parent
                    xgraph. In particular, the messages

                    PLOT, PLOTSCALE, and WAVEPLOT

                    sent to the parent xgraph, will cause a new xplot to be
                    created if necessary, and then copies of these messages
                    will be sent to the new xplot. This does not affect the
                    normal commands for creation and message-passing to xplots.

                    In other words, the commands
                            create xgraph /form/graph
                            addmsg /foo /form/graph PLOT *plot *red
                    will produce the same plot as
                            create xgraph /form/graph
                            create xplot /form/graph/plot
                            addmsg /foo /form/graph/plot PLOT *plot *red

            DATA STORAGE IN XPLOT
                    The points displayed by xplots are stored in two
                    interpol_structs called xpts and ypts respectively.
                    As is obvious from their names, point #i displayed in
                    the xplot is stored in location
                            (xpts->table[i],ypts->table[i])
                    There are several options for passing information into
                    the xpts/ypts arrray.
                    1. The points can be filled in explicitly through the usual
                    script commands for handling tables, e.g.:
                                    setfield /form/graph/plot \
                                            xpts->table[0] 10
                                            ypts->table[0] 20
                            ....
                    or
                                    loadtab /form/graph/plot xpts 1 10 0 10 \
                                            1 2 3 4 5 6 7 8 9 10
                                    loadtab /form/graph/plot ypts 1 10 0 10 \
                                            1 2 1 4 1 6 1 8 1 10
                    or
                                    setfield /form/graph/plot ypts /foo/table

                    2. The points can be loaded in from a file using the
                    file2tab function, e.g.:
                                    file2tab ypointsfile /form/graph/plot \
                                            ypts -autofill xpts
                    (see the file2tab documentation for more information and
                    other options.)

                    3. The points can be filled in during the course of a
                    simulation using messages, which are described in more
                    detail below. This option is the most commonly used one,
                    for watching the progress of a simulation.

                    Note that once the data is in the xpts and ypts tables,
                    it is accessible just like any other data in GENESIS
                    tables.

            MEMORY HANDLING OPTIONS
                            An obvious problem resulting from monitoring a
                    very long simulation is that all those data points will
                    fill up all the available memory. There are a number
                    of ways around this.
                    1. Don't store all the data. One very rarely needs to
                    monitor the output of the simulation at the same fine
                    time-step that the numerical calculations use. Typically
                    the plots can be run at 10 to 100 times longer time-steps.
                    This makes the simulation run faster, too.
                    2. Compress the data. There is an option (on by default)
                    which compresses the incoming data on the fly using a very
                    simplistic, lossy compression scheme. All this does is
                    to discard points which are closer than a defined number
                    in the y-coordinate. The 'ysquish' field stores this
                    number, which is initialized to 1/100 of the range
                    of the y axis of the graph. If it ever looks like the
                    plotted data is seriously distorted, this is a likely
                    culprit and 'ysquish' should be squished. A value of zero
                    will result, obviously, in no compression.
                    3. Set a maximum limit for the number of points allowed
                    (the 'limit' mode). This is unlikely to be useful to anybody.
                    4. Use the 'oscilloscope' mode, where the plot starts
                    over from zero after filling up.
                    5. Use the 'roll' mode to scroll the points like a
                    stripchart, except that unlike a paper stripchart the
                    scrolled points are lost.

                    To recapitulate, the available memory handling modes
                    are :
                            s[quish] : default, attempts lossy compression
                                    depending on the ysquish parameter.
                                    Expands memory use as required.
                            l[imit] : Prevent plotting points past predefined
                                    allocation.
                            r[oll] : Roll the data like a stripchart.
                            o[scilloscope]: Start over at zero once the
                                    allocated memory is used up.

            MANIPULATING XPLOTS.
                    Xplots can be created copied, moved and deleted in just the
                    same way as other pixes, which is almost the same as
                    ordinary elements with the following restrictions:
                    1. A an instance of the coredraw subclass must be an ancestor
                    of the xplot. In other words, there must be an element which
                    is a subclass of xcoredraw somewhere in the heirarchy above
                    (closer to the root) the point where the xplot is created.
                    2. An xplot can only be moved within the subtree arising
                    from this ancestral coredraw element.

    Author:         Upi Bhalla Mt. Sinai May 93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xplot_type [in src/Xodus/draw/xplot_struct.h]

    Size:   Variable depending on number of points stored. Makes
            extensive use of realloc, so it may fragment memory.

    Fields: fg      Foreground color of plot.
            script  Script operation(s) to perform on a mouse
                    click. The script calls of the pix are only made
                    if the draw determines that the pix is the nearest
                    to the event and if the event occurred within the
                    bounding region of the pix.
            tx      Transposition distance in the x dimension. The
                    pix is transposed (ie, displaced, offset) by this amount.
            ty      Transposition in y.
            tz      Transposition in z.
            pixflags    Set of flags specifying visibility,
                    refreshes, mouse sensitivity and many other options.
                    Use the 'pixflags' utility function to find out more.
                    The most commonly used pixflag option with xplot is 'f',
                    which prevents flushing the entire display every time a point
                    is added. This greatly speeds up the display if there are many
                    xplots or other widgets being updated each timestep.
            xpts    interpol-struct containing x-coords for plot
            ypts    interpol-struct containing y-coords for plot
            npts    Number of points currently being displayed in plot
            linewidth       Width (in pixels) of plotted line
            linestyle       One of: LineSolid (default), LineOnOffDash,
                                    LineDoubleDash
            xmin,ymin,xmax,ymax:    Determine range of plotted values.
                            The offsets and scaling factors are handled
                            by adjusting these. Normally managed by the
                            parent xgraph, but must be assigned explicitly
                            when in another coredraw subclass.

            wx, wy: Window size for plot. Normally both are 1.0.
            memory_mode:    One of:
                            s[quish]: default. Attempts lossy compression.
                            l[imit]: limit number of plotted points
                            r[oll] : Roll the data like a stripchart.
                            o[scilloscope]: Start over at zero once the
                                    allocated memory is used up.
            auto_mode:      For future extensions.
            ysquish:        cutoff for 'squish' mode data compression.

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XPlot [in src/Xodus/draw/xplot.c]

    Classes:        gadget output

    Actions:        XUPDATE: update internal fields when
                            displayed widget is changed.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field
                    XODROP: Called when a pix is dropped into a draw widget.
                    XODRAG: Called when a pix is dropped into a draw widget.
                    XOWASDROPPED:   Called when a pix is dropped into a draw widget.
                    B1DOWN: Invoked when mouse Button 1 is pressed.
                    B2DOWN: Invoked when mouse Button 2 is pressed.
                    B3DOWN: Invoked when mouse Button 3 is pressed.
                    ANYBDOWN:       Invoked when any mouse button is pressed.
                    B1DOUBLE: Invoked on a double click on mouse button 1.
                    B2DOUBLE: Invoked on a double click on mouse button 2.
                    B3DOUBLE: Invoked on a double click on mouse button 3.
                    PROCESS: Handle plot input.
                    RESET:  Checks various message options.
                    SET:    Handles special set options including table sets.
                    ADDPTS: Plots (x,y) values as points; equivalent to old
                            xaddpts: call {plot-name} ADDPTS {x} {y}

    Messages:       PLOT    data name color
                            In this mode successive data points are added to
                            the end of the plot as the simulation progresses.
                    PLOTSCALE data name color scale yoffset
                            Similar to PLOT, except that the scale and yoffset
                            of this plot are also included in the message.
                    X       x-coordinate-of-PLOT-msg name-of-corresponding-PLOT-msg
                            This is used for creating xy (phase) plots. To use
                            this, first the PLOT msg must be sent, then the
                            corresponding X msg can be set up. See the
                            example below.
                    WAVEPLOT data name color
                            This is used to create a plot whose y coordinates
                            vary as the simulation progresses. For example,
                            if we have 10 waveplot messages with the same name,
                            they will specify 10 successive y coordinates on
                            a line. With every timestep the y coordinates get
                            updated so the effect is like the profile of a
                            travelling wave.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a xcoredraw widget subclass

    Example 1.

    ================================= cut here =================================

    //genesis
    // This example tests the various graph modes. First click 'runit',
    // then click reset and then runit again.
    // Click on any of the plots to toggle their visibility

    create xform /form [1,1,500,800] -title "OUTPUT" -fg black
    ce /form
    create xbutton runit
    setfield runit script \
       "step 1000; setfield /form/instr1 fg black; setfield /form/instr2 fg blue"
    create xbutton reset -wgeom 50% -script reset
    create xbutton quit -ygeom 0:runit -xgeom 50% -wgeom 50% -script quit
    create xgraph /form/graph -hgeom 30%
    ce /form/graph
            setfield script "echo in graph" xmin 0 xmax 100 ymin -1 ymax 5
            setfield yoffset 2
            setfield xmax 1000 ymax 15
            setfield overlay 1

    create xgraph /form/phasegraph -hgeom 30%
    ce /form/phasegraph
            setfield script "echo in graph" xmin 0 xmax 100 ymin -1 ymax 5
            setfield yoffset 2
            setfield xmin -1 xmax 1 ymin -1 ymax 3
            setfield overlay 1

    create xgraph /form/wavegraph -hgeom 20%
    ce /form/wavegraph
            setfield script "echo in graph" xmin 0 xmax 100 ymin -1 ymax 5
            setfield xmin -0.5 xmax 1.5 ymin -1 ymax 1

    create xlabel /form/instr1 \
            -label "First click 'runit' to activate the demo." -fg blue
    create xlabel /form/instr2 \
            -label "After the run ends, click 'reset' and 'runit' again."
    create xlabel /form/instr3 \
            -label "Click on any of the plot names to toggle their visibility"
    int i
    create xplot /form/graph/foo
            ce /form/graph/foo
            for(i = 0; i < 200 ; i = i + 1)
                    setfield xpts->table[{i}] {i}
                    setfield ypts->table[{i}] {sin {i/10.0} }
            end
            setfield npts 200 fg blue wx 1 wy 1
            //set xmin 0 xmax 100 ymin -1 ymax 1 wx 1 wy 1
            ce ..

    create table /tab
            call /tab TABCREATE 400 0 400
            setfield /tab step_mode 1 stepsize 1
            for(i = 0; i < 400 ; i = i + 1)
                    setfield /tab table->table[{i}] {cos {5+ i/30.0} }
            end

    create table /tab2
            call /tab2 TABCREATE 400 0 400
            setfield /tab2 step_mode 1 stepsize 1
            for(i = 0; i < 400 ; i = i + 1)
                    setfield /tab2 table->table[{i}] {sin {4 +i/16.0} }
            end

    addmsg /tab /form/graph PLOT output *output *yellow
    addmsg /tab2 /form/graph PLOT output *output *green
    addmsg /tab2 /form/graph PLOTSCALE output *plotscale *red -0.5 0.5

    addmsg /tab /form/phasegraph PLOT output *output *yellow
    addmsg /tab2 /form/phasegraph X output *output

    addmsg /tab /form/wavegraph WAVEPLOT output *wave *blue
    addmsg /tab2 /form/wavegraph WAVEPLOT output *wave *blue

    setfield /form/#[TYPE=xgraph]/#[TYPE=xplot] script "toggle_visibility <w>"

    function toggle_visibility(widget)
            str widget
            if ({getfield {widget} pixflags} & 1)
                    setfield {widget} pixflags ~v
            else
                    setfield {widget} pixflags v
            end
    end

    xshow /form
    ================================= cut here =================================

See also: xgraph , xaxis, XODUS documentation, pix documentation, documentation for coredraw and other subclasses.

## 26.85 xshape

    Object Type:    xshape

    Description:    The shape pix draws assorted shapes, and was developed in
                    order to allow users to design their own graphical objects
                    such as clickable labels, arrows, and other icons under the
                    draw widget.  It provides access to the primitive graphical
                    operations of drawing geometrical shapes and text, as well as
                    to the `higher functions' such as icons, mouse clicks and
                    hilighting.  It is also automatically created as a subordinate
                    pix for the xvar, xview, and xtree widgets.  For example, two
                    filled rectangle xshapes, shape[0] and shape[1], are created
                    as child elements of a view widget when the view is created.
                    The shape pix contains fields for the coordinates of the
                    shape, and assorted fields for controlling draw modes using
                    the coordinates, a set of fields related to the text string
                    that the pix can display, and a field for setting a return
                    value when the shape is clicked on.

    Author:         Upi Bhalla Caltech Apr/93

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xshape_type [in src/Xodus/draw/xshape_struct.h]

    Size:           156 bytes

    Fields:         fg      Color of the shape

                    script  Script operation(s) to perform on a mouse
                            click. The script calls of the shape are only made
                            if the draw determines that the shape is the nearest
                            to the event and if the event occurred within the
                            bounding region of the shape.

                    value   Set with setfield, or with a PATH message, and
                            accessible in script functions with the <v> or
                            <value> argument.

                    tx      Transposition distance in the x dimension. The
                            shape is displaced in the draw by this amount.
                    ty      Transposition in y.
                    tz      Transposition in z.

                    pixflags        Set of flags specifying visibility,
                            refreshes, mouse sensitivity and many other options.
                            Use the 'pixflags' utility function to find out more.

                    xpts    Interpol struct (table) of x coordinates.
                    ypts    Interpol struct (table) of y coordinates.
                    zpts    Interpol struct (table) of z coordinates.
                    npts    Contains the number of points which were set.

                    drawmode    One of: DrawLines (default), DrawPoints, DrawSegs
                                (takes coordinate pairs and draws lines between
                                them; The last coordinate is ignored if there is
                                an odd number of coordinates.), DrawArrows (same
                                as DrawSegs, only arrows are drawn instead of
                                segments), FillPoly (draws a filled polygon
                                bounded by the coordinates specified.  It will
                                close the polygon if the last point is different
                                from the first.), or FillRects (takes coordinate
                                pairs and draws filled rectangles from one to the
                                next.  If there are an odd number of coordinates
                                specified, then the last coordinate is ignored.).

                    linewidth   Line width in pixels.

                    linestyle   One of: LineSolid (solid line of fg color, the
                                default), LineOnOffDash (dashed line of fg color),
                                or LineDoubleDash (dashed line of fg color, with
                                white between the dashes).

                    capstyle    End of line style; One of: CapButt (rectangular
                                end, the default), CapRound (round end),
                                CapProjecting (adds an extra pixel to the end), or
                                CapNotLast (skips the last pixel of the line).

                    joinstyle   Style of line joints; One of: JoinMiter (sharp
                                corners, the default), JoinRound (rounded
                                corners), or JoinBevel (beveled corners).

                    text        Text string to display (if any).
                    textcolor   Color of the text string.

                    textmode    Mode for drawing text; One of: draw (print the
                                text on the draw background, the default), fill
                                (add a white background to the text), or nodraw
                                (do not display the text).

                    textfont    Font used for the text string.

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XShape [in src/Xodus/draw/xshape.c]

    Classes:        output, gadget

    Actions:        XUPDATE: update internal fields when
                            displayed widget is changed.
                    B1DOWN: Invoked when mouse Button 1 is pressed.
                    B2DOWN: Invoked when mouse Button 2 is pressed.
                    B3DOWN: Invoked when mouse Button 3 is pressed.
                    ANYBDOWN:       Invoked when any mouse button is pressed.
                    B1DOUBLE: Invoked on a double click on mouse button 1.
                    B2DOUBLE: Invoked on a double click on mouse button 2.
                    B3DOUBLE: Invoked on a double click on mouse button 3.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field.
                    XODROP: Called when a another pix is dropped onto this one.
                    XODRAG: Called when the mouse is clicked on this pix, and
                            the mouse moves while the mouse button is held down.
                    XOWASDROPPED: Called after this pix has been dropped onto
                            another one.

                    XSHAPE_ADDPT x y z:  adds a point to the arrays, and
                                         increments npts.
                    XSHAPE_MOVEPT x y z: finds the nearest point to [x,y,z] and
                                         moves it there.

    Messages:       PATH    dummy
                            When a PATH message is present, then the value field
                            is set to the full path of the source of the message
                            on PROCESS.

    ------------------------------------------------------------------------------

    Notes:          After changing some of the fields related to the display
                    modes, it will be necessary to perform an xupdate of the
                    parent draw widget for the changes to take effect.

                    The coordinates of the shape can be set in the xpts, ypts, and
                    zpts tables, using the usual commands for interpol_structs,
                    e.g. "setfield shape xpts->table[0] 0.5".  However, there is a
                    shorthand notation for setting several coordinate sets at
                    once, for example:

                        setfield shape2 coords [1,0,0][0,1,0][0,0,1]

                    The example below shows how this notation may be used at the
                    time the shape is created.  The use of this notation has the
                    additional advantage of automatically setting npts to the
                    number of coordinate sets which were specified.  Otherwise,
                    npts must be explicitly set before the shape will be
                    displayed.

    Example:        create xform /form
                    create xdraw /form/draw [0,0,100%,100%] \
                        -xmin -1 -xmax 2 -ymin -2 -ymax 2
                    create xshape /form/draw/shape -fg green -drawmode FillPoly \
                        -coords [0,0,0][0.5,1,0][1,0,0][0,0,0] \
                        -text "I am a green triangle" \
                        -script "echo You clicked on <w>"
                    xshow form

See also: xview , xvar , xpix , Clicks , Tables , and the scripts Scripts/examples/XODUS/draws.g, Scripts/CPG/viewform.g

## 26.86 xsphere

    Object Type:    xsphere

    Description:    Example pix which draws a filled circle.

    Author:         Upi Bhalla Caltech Apr/93

    ------------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xsphere_type  [in src/Xodus/draw/xsphere_struct.h]

    Size:        104 bytes

    Fields:
                 fg         Color of sphere.
                 script     Script operation(s) to perform on a mouse
                            click.
                 tx         Transposition distance in the x dimension. The
                            pix is transposed (ie, displaced, offset) by this
                            amount.
                 ty         Transposition in y.
                 tz         Transposition in z.
                 value
                 pixflags   Set of flags specifying visibility,
                            refreshes, mouse sensitivity and many other options.
                 r          Radius of the sphere.

    ------------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XSphere  [in src/Xodus/draw/xsphere.c]

    Classes:        output, gadget

    Actions:

            XOWASDROPPED XODRAG XOCOMMAND XODROP XUPDATE B3ENTER B2ENTER B1ENTER
            B3DOUBLE B2DOUBLE B1DOUBLE ANYBDOWN B3DOWN B2DOWN B1DOWN DELETE COPY
            SET CREATE RESET PROCESS

    Messages:       none

    ------------------------------------------------------------------------------

    Notes:

    Example:        Scripts/examples/XODUS/draws.g

See also: xpix , Clicks

## 26.87 xtext

    Object Type:    xtext

    Description:    Display and optional editor for text.

    Author:         Maneesh Sahani Caltech/ Jason Leigh U Illinois@Chicago July 93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xtext_type [in src/Xodus/widg/xtext_struct.h]

    Size:           ?

    Fields:         fg      Foreground color of text in text
                    bg      Background color.
                    xgeom   Position of left edge of xtext.
                    ygeom   Position of upper edge of xtext.
                    wgeom   Width of text
                    hgeom   Height of text
                    font    optional font for text.
                    initialtext     optional text string to display.
                    editable        Flag determining if text can be altered.
                    filename        Optional name of an ascii file for widget
                                    to display.

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XText [in src/Xodus/widg/xtext.c]

    Classes:        widget

    Actions:        XUPDATE: update internal fields when
                            displayed widget is changed.

    Messages:       none.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a form widget
                    The xtext does not perform any computational operations.

    Example
                    create xform /form [0,0,500,500]
                    create xtext /form/text1 [0,0,100%,100%] \
                            -initialtext "I am a text widget" \
                            -fg red \
                            -font r24 \
                            -bg green
                    xshow /form

See also: Scripts/examples/XODUS/widgets.g, XODUS documentation.

## 26.88 xtoggle

    Object Type:    xtoggle

    Description:    Maintains toggle state and executes script actions
                    from mouse button presses.

    Author:         Maneesh Sahani / Upi Bhalla  Caltech Feb/93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xtoggle_type [in src/Xodus/widg/xtoggle_struct.h]

    Size:           136 bytes

    Fields:         fg      Foreground color of text in toggle
                    bg      Background color.
                    onfg    Foreground color of text in toggle,
                            for on (pressed) state.
                    onbg    Foreground color for on (pressed) state.
                    offfg   Background color of text in toggle,
                            for off (unpressed) state.
                    offbg   Background color for off (unpressed) state.
                    xgeom   Position of left edge of toggle.
                    ygeom   Position of upper edge of toggle.
                    wgeom   Width of toggle.
                    hgeom   Height of toggle.
                    onlabel optional text string to display in on state.
                            Defaults to widget name in the GENESIS hierarchy.
                    offlabel optional text string to display in off state.
                            Defaults to widget name in the GENESIS hierarchy.
                    onfont  optional font for text in on state.
                    offfont optional font for text in on state.
                    state   Maintains state of widget. 1 if on, 0 if off.
                            Defaults to 0.
                    script  string representing operations to be performed
    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XToggle [in src/Xodus/widg/xtoggle.c]

    Classes:        widget

    Actions:
                    B1DOWN: Button 1 pressed to turn on toggle (left mouse button)
                    B2DOWN: Button 2 pressed to turn on toggle
                            (middle button on 3 button mouse)
                    B3DOWN: Button 3 pressed to turn on toggle
                            (right button on 3 button mouse)
                    ANYBDOWN: Any button pressed.
                    B1UP:   Button 1 pressed to turn off toggle (left button)
                    B2UP:   Button 2 pressed to turn off toggle
                            (middle button on 3 button mouse)
                    B3UP:   Button 3 pressed to turn off toggle
                            (right button on 3 button mouse)
                    ANYBUP: Any button pressed to turn off toggle.
                    XPDATE: update internal fields when widget is changed.

    Messages:       none.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a form widget
                    The xtoggle does not perform any computational operations.
                    It issues script calls depending on button presses and
                    internal state.

    Example:
    create xform /form [0,0,500,100]
    create xtoggle /form/toggle1 [0,0,100%,100%] \
        -onlabel "This toggle widget is on" \
        -offlabel "This toggle widget is off" \
        -onfg green \
        -offfg black \
        -onfont r24 \
        - script "echo.d1 LMB <value> ; echo.u3 released RMB <v> ; echo any MB <v>"
    xshow /form

See also: XODUS documentation. Mouse events documentation ( Clicks )

## 26.89 xtree

    Object Type:    xtree

    Description:    Object for displaying and manipulating the relationships
            between elements and objects in a simulation. This is an extremely
            complex widget designed for building click-and-drag interfaces
            within Xodus.  The default mode provides a heirarchical
            tree display of a simulation. The additional options include
            alternative display modes, issuing script calls based on the
            source and destinations of mouse-drag operations, and options
            for changing the appearance of individual items in the tree.

            Xtree is subclassed from pix and can only be displayed in coredraw
            or its subclasses.

            xtree is not designed to be updated every time step. It is quite
            expensive to recalculate. The contents of xtree are updated by
            calling the RESET action.

            Like xvar and xview, xtree maintains a set of child xshapes named
            shape[0], shape[1], ... The items displayed by the xtree use
            the coordinate and drawing information in these shapes for display.
            When drawing an item, the tree finds a string associated with
            the item (usually its object name, see below). It then scans the
            list of child shapes to find a match between the 'value' field of
            the xshape and this string. The selected shape is used as the icon
            for representing the item in the tree. If no match is found, shape[0]
            is used. The child xshape shape[0] is created automatically when
            the xtree is created.

            The 'items' that the xtree can represent include elements and
            objects. In addition to representing these items, xtree can also
            display heirarchical (parent-child-sibling) relationships between
            them in the form of a tree structure as one of the display options.
            Furthermore, xtree can display messages between elements in the
            form of arrows.

    Display options

            Several display options are available:
            tree:   a heirarchical display, eg, of a directory structure or
                    a GENESIS heirarchy.  Any orientation can be selected.
            treenotrunc: ?
            custom: The coordinates of the items are user-specified and just
                    stored in an array.
            grid:   The items are placed on a rectangular grid or as a single
                    row or column, as specified by the orientation option.
            geometry: The items are located according to their x,y,z coords.
            obj_grid: The objects are located on a rectangular grid. This
                    may be modified depending on the orientation option.
            obj_custom: The objects are located according to user-specified
                    positions.
            orientation: Determines two kinds of things: first, the orientation
                    of the heirarchy in the tree mode. Second, the orientation
                    and layout of the grid.
                    In the tree mode the orientation can be one of
                    u: up - the leaves are up , the root is down
                    d: down - the leaves are down, the root is up.
                    l: left - the leaves are on the left, the root on the right.
                    r: right - the leaves are on the right, the root on the left.

                    In the grid or obj-grid modes, the orientation can be
                    u: Grid with horizontal long axis
                    U: Grid with horizontal long axis and staggered entries.
                    d: Single column
                    l: Grid with vertical long axis
                    r: Single row
                    R: Single row with staggered entries
                    m<n>: multiple rows with n entries each.
                    M<n>: multiple rows with n entries each, staggered in the y
                            direction to minimize text overlap.

    Displaying messages
            The tree is frequently used to display messages between elements.
            Messages can be displayed in any treemode, except, of course,
            between objects. Messages are displayed as arrows which start and
            end a few pixels from the item on the screen. If the pair of items
            being displayed is very close, the messages are not displayed.
            The details of the message display are determined by the MSGARROW
            array, which is manipulated using the ADDMSGARROW action.

    Executing functions in response to graphical events.
            Trees are especially useful for performing drag-and-drop operations,
            though the usual set of actions on the tree is also allowed. The
            ADDMSGARROW action, in addition to loading in the specification
            for msg display, is also used to set up the script functions to
            be performed under various sets of drag-drop operations between
            specified object classes.

    The ADDMSGARROW action.
            As already described, ADDMSGARROW is used both to specify how to
            display msgs between elements of particular object-classes, and
            also to execute functions in response to particular graphical
            operations like drag-and-drop.

            The syntax of ADDMSGARROW is:
            call tree ADDMSGARROW msgsrc msgdest msgtype msgdesttype fg index
                    fliparrow script script_add script_drop

            msgsrc and msgdest are wildcard paths to two sets of elements.
            msgtype is a string defining the type of msg.
            msgdesttype is the type of the element at the destination of the msg
            fg is the color of the arrow used to draw the msg
            index is for identifying this ADDMSGARROW entry among the array
                    of other entries. If it is >=  0, the msgarrow
                    information is placed at the specified index, overwriting
                    whatever else may have been stored there. If it is
                    less than 0, the the information is first checked to ensure
                    that it does not duplicate an existing entry. If not, then
                    the information is placed in the first free entry.
            fliparrow is a flag (0 or 1) to tell the display routines to draw
                    the arrow backwards. Normally (fliparrow = 0) the arrowhead
                    points to the destination of the msg.
            script, script_add and script_drop are strings with the standard
                    Xodus syntax for specifying functions and arguments.

            The msgsrc and msgdest wildcards are used in two ways. If one is
            drawing messages, they are used to specify the elements that the
            tree is supposed to check for the sources and the dests of the message,
            respectively.  If one is executing functions, then the lists are
            scanned to check if the source and dest elms of a drag-drop operation
            lie on the lists. If so, then the function named in "script" is
            executed every time; the function named in "script_add" is executed if
            there is NO message of the specified msgtype between the src and dest,
            and the function named in "script_drop" is executed if there is
            already a message between src and dest. The intention is that
            operations involving creation of messages be specified with the
            "script_add", deletion by "script_drop", and other operations by the
            function defined in "script".

    SIMULATION PARAMETERS

    Function:       XTree [in src/Xodus/widg/xtree.c]

    Classes:        gadget output

    Actions:        PROCESS: redraws tree - does NOT check for changes to contents.
                    RESET:  rebuilds tree from scratch, thereby updating any
                            changes.
                    CREATE: Creates the tree and the default child xshape
                    COPY : currently incomplete
                    SET: Special handling for the fields
                            pixflags
                            sizescale
                    DELETE: Frees up allocated entries.
                    DUMP: Saves all the internal information for the tree,
                            specially the ADMMSGARROW info and the coords of
                            the display items in certain modes.
                    UNDUMP: Loads in the information stored using DUMP
                    ADDMSGARROW: Sets modes for displaying msgs and handling
                            drag-drop operations. See above.
                    SHOWMSGARROW: Lists existing msgarrows
                    MOVECUSTOM: args: elmpath x y z recurse_flag
                            Handles xyz moves of tree items in custom mode
                    TRUNCATE: args: elmname [mode]
                            Applies to treemode 'tree'. Sets truncation of the tree
                            at the element 'elmname'. If mode is 0, truncation is
                            turned on. If 1, it is turned off. If -1 (default),
                            it is toggled.
                    XUPDATE: update internal fields when
                            displayed widget is changed.
                    Xodus actions: handled normally, with the following
                            exceptions
                            1. In treemode 'tree', action B1DOUBLE toggles
                            the truncation of the the tree at the clicked item.
                            2. Drags and drops are checked against entries
                            in the msgarrow table to decide if the scriptfuncs
                            specified by ADDMSGARROW should be called. These
                            are only called for operations within the same tree.
                            3. B1DOWN, B2DOWN and B3DOWN are checked against
                            the hlmode. If it is "one", then one element is
                            highlit. If it is "multi" then the element is added
                            to the list of entries to be highlit. If it is "none"
                            or the default, then no permanent highlight flags are
                            set.

    Messages:       none.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a coredraw widget subclass.
                    Not meant to be clocked.

    Examples:       Scripts/examples/XODUS/xtree_example

See also: xshape , xview

## 26.90 xvar

    Object Type:    xvar

    Description:    Object for displaying numerical values graphically. Xvar is
            subclassed from pix and can only be displayed in coredraw
            subclasses.

            The following parameters of the graphical display can be
            used to display values in xvar:
                    1. Color
                    2-4. x,y and z offsets
                    5. Coordinates (morphing)
                    6. Line thickness. *
                    7. Text color *
                    8. Text
                    9. Minigraph. *
                    10. Surface *
                    11. Contour *
            * Not yet available.

            While these parameters can in principle be used to
            simultaneously display 9 independent parameters, in practice
            it gets rather confusing if more than 2 or 3 are used at a
            time.
            Values are specified either through messages or by directly
            setting the 'values' array in the xvar. At this time 5 such
            messages are permitted (VAL1, VAL2, VAL3, VAL4, VAL5).
            The color_val, xoffset_val, morph_val etc.
            fields are used to bind the message number to the specified
            display variable. Thus setting color_val to 1 means that
            message VAL1 will be used to control the color of the xvar pix.
            By default all _vals are set to 0, which disables them.

            The xvar pix displays values (except text and minigraph) by linear
            interpolation. Every xvar has at least two child elements of class
            xshape, named shape[0], shape[1], etc. These shapes determine the
            extreme points for the linear interpolation. Therefore if shape[0]
            has foreground color 0, and shape[1] has color 10, the range of
            colors displayed would be interpolated between 0 and 10. Likewise,
            if shape[0] displays a tall thin rectangle, and shape[1] a short
            wide rectangle, the shapes displayed would be 'morphed' between
            these two extremes. Of course, to get these effects one would have
            to set the color_val and morph_val to the appropriate values.
            In addition to the shapes themselves, three arrays are used to specify
            how the xvar does interpolation. As already mentioned, the 'values'
            array specifies the actual values to be displayed. 'value_min'
            contains the values that correspond to the lower end of the
            interpolated range. Thus if value[0] was equal to value_min[0],
            the parameter displayed would correspond to shape[0]. Likewise,
            value_max contains the upper end of the interpolated range.

            One can have multiple xshapes. In this case the interpolation
            first decides which pair of shapes to use. In this version, each pair
            of shapes handles an equal range between value_min and value_max.
            Having selected the appropriate pair of shapes,
            the algorithm then proceeds as outlined above.

            The 'text' option simply prints out the floating point value of the
            appropriate message. The 'minigraph' option (which will be
            implemented one of these days) displays a little graph of the
            value, without any optional extras like axes.

            By default, the xvar object is created along with two child shapes,
            shape[0] and shape[1]. The default shapes are squares, shape[0] being
            a small one with color 0 and shape[1] a big (1x1) square in color 63.
            The child shapes can have parameters set in the usual ways, but are
            not displayed independently of the xvar pix. For the technically
            minded, this is because their pixflags have been set to visible_not.

            Note on 'morphing': Morphing in the xvar pix is simply linear
            interpolation between corresponding points. When one shape has a
            different number of points from the other, then the algorithm
            assumes that the missing points are [0,0,0] and does interpolation
            accordingly. This may lead to peculiar effects, so usually one
            uses the same number of points in all xshapes.

    Author:         Upi Bhalla Caltech Dec 93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xvar_type [in src/Xodus/draw/xvar_struct.h

    Size:           ?       Depends on number of associated shapes.

    Fields: fg      Foreground color of var.
            script  Script operation(s) to perform on a mouse
                    click. The script calls of the var are only made
                    if the draw determines that the var is the nearest
                    to the event and if the event occurred within the
                    bounding region of the var.
            tx      Transposition distance in the x dimension. The
                    var is transposed (ie, displaced, offset) by this
                    amount.
            ty      Transposition in y.
            tz      Transposition in z.
            pixflags        Set of flags specifying visibility,
                    refreshes, mouse sensitivity and many other options.
                    Use the 'pixflags' utility function to find out more.

            varmode Specifies the mode of operation of the xvar. Can be
                    one of:
                    shape - Does interpolation between shapes
                    graph - draws a minigraph (Not yet implemented)
                    surface - Draws a plane in 3-d, specified by 3
                            points in space (not yet implemented)
                    contour - Draws contour lines for a plane in 3-d. NYI.
                    colorview - Backwards compatibility hack. Uses 'shape'
                              mode to display boxes of different color.
                    boxview - Backwards compatibility hack. Uses 'shape'
                              mode to display boxes of different sizes.
                    colorboxview - Backwards compatibility hack. Default
                              varmode. Uses 'shape' mode to display VAL1
                              using both the morph and color modes for
                              a box.
                    fillboxview - Backwards compatibility hack. Uses 'shape'
                            mode to display filled boxes of different sizes.
            value_min       1-d array with lower limits for shape parameters.
            value_max       1-d array with upper limits for shape  parameters.
            values          1-d array with display values.
            color_val       Specifies message to use for color
                              display values. 0=disabled is default.
                              If you wish to cause var to change colors,
                              use color_val.
            morph_val       Specifies message to use for morphing.
                              If you wish to have the var change
                              shape, use morph_val.
            xoffset_val     Specifies message to use for xoffset.
                              If you wish to cause a var to
                              bounce around on the screen,
                              use the offset_vals.
            yoffset_val     Specifies message to use for yoffset.
            zoffset_val     Specifies message to use for zoffset.
            text_val        Specifies message whose value should
                              be printed out.
            textcolor_val   Specifies message which determines
                              the color of the text.
            linethickness_val  Specifies message determining the
                              line thickness used in the var.
            sizescale       Rescales all the shapes. The default
                              shapes have a size of 1.

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XVar [in src/Xodus/draw/xvar.c]

    Classes:        gadget output

    Actions:        PROCESS: Redo interpolation and display.
                    RESET:  Required when changing child xshapes.
                    CREATE: Automatically creates 2 child xshapes.
                    XUPDATE: update internal fields when
                            displayed widget is changed.
                    B1DOWN: Invoked when mouse Button 1 is pressed.
                    B2DOWN: Invoked when mouse Button 2 is pressed.
                    B3DOWN: Invoked when mouse Button 3 is pressed.
                    ANYBDOWN:       Invoked when any mouse button is pressed.
                    B1DOUBLE: Invoked on a double click on mouse button 1.
                    B2DOUBLE: Invoked on a double click on mouse button 2.
                    B3DOUBLE: Invoked on a double click on mouse button 3.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field
                    XODROP: Called when a another pix is dropped onto this one.
                    XODRAG: Called when the mouse is clicked on this pix, and
                            the mouse moves while the mouse button is held down.
                    XOWASDROPPED: Called after this pix has been dropped onto
                            another one.

    Messages:       COORDS x y z
                    VAL1 data
                    VAL2 data
                    VAL3 data
                    VAL4 data
                    VAL5 data

                    All messages can contain values for any display parameter.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a coredraw widget subclass.
                    The xvar performs the interpolation between shapes and
                    redraws them on every clock tick.

    Example:

See also: xview , xshape

## 26.91 xview

    Object Type:    xview

    Description:    Object for displaying large numbers of numerical values
            graphically. Xview can be thought of as an array of xvars, though it
            uses much less memory than multiple xvars would. It also provides
            many more features for accessing the fields and messages of groups
            of elements.  Xview is subclassed from pix and can only be displayed
            in coredraw or its subclasses.

            Xview displays multiple 'points' in space, each behaving rather like
            an xvar.  Each 'point' in xview usually represents a single entity
            in the simulation, such as a compartment.

            Each 'point' in xview can be clicked to select, and the 'value'
            field of the xview will be set according to the 'valuemode'. By
            default the 'valuemode' is set to "path", so a click action will
            place the path of the element represented by the clicked point in
            xview into the 'value' field. Alternative valuemodes are "index",
            which returns the index of clicked point in the internal xview list;
            and "lookup", which looks up the value displayed for the clicked
            point.

            Values in xview are specified in three ways.

            - First, one can set the 'values' array directly (e.g., using the set
            command). Note that 'values' is 2-dimensional in xview.

            - Second, one can send up to 5 messages (VAL1, VAL2, VAL3, VAL4,
            VAL5), for each point. The points themselves must be previously
            specified using the COORDS message. It is assumed that the order of
            sending the COORDS messages is identical to the order of sending the
            values.  This is guaranteed if a wildcard list is used to set up the
            messages.  This method is recommended for all dynamic displays, as
            it is far and away the most efficient. The use of messages also
            enables displays on parallel machines.

            - Third, one can specify 'path' for looking up the coords. 'path' is
            usually a wildcard list of elements.  'relpath' is used for finding
            the actual elements containing the fields, relative to the coords.
            This is NOT a wildcard list. If no relpath is used, it can be set to
            "" or ".".  Only two values can be displayed in this mode, using
            'field' and 'field2'.

            In addition, one can set 'field' to one of "msgout" or "msgin". If
            these options are selected, one can view values that are contained
            in messages. The 'msgpath' is a wildcard list of elements connected
            to the 'path' by the message type specified in 'msgtype'. The
            direction of the messages is specified, as mentioned above, by
            'field'. The view looks for the first message that satisfies all the
            above criteria for each coordinate, and displays the appropriate
            value. If it fails to find a suitable message the value becomes 0.
            This option enables one to display connectivity patterns in a
            network.  Using 'path' and its related options for displaying values
            is the most flexible option, and the slowest. Connections can only be
            displayed using this option. It is recommended for static displays
            such as during setup.

            The display options outlined below are essentially identical to
            the 'xvar' widget.

            The following parameters of the graphical display can be
            used to display values in xview:
                    1. Color
                    2-4. x,y and z offsets
                    5. Coordinates (morphing)
                    6. Line thickness. *
                    7. Text color *
                    8. Text
                    9. Minigraph. *
                    10. Surface *
                    11. Contour *
            * Not yet available.
            Any or all of the display parameters can in principle be used to
            simultaneously display values pertaining to each point.
            In practice it gets rather confusing if more than 2 or 3 are
            used at a time.
            The color_val, xoffset_val, morph_val etc.
            fields are used to bind the message number to the specified
            display variable. Thus setting color_val to 1 means that
            message VAL1 will be used to control the color of the xview pix.
            By default all _vals are set to 0, which disables them.

            The xview pix displays values (except text and minigraph) by linear
            interpolation. Every xview has at least two child elements of class
            xshape, named shape[0], shape[1], etc. These shapes determine the
            extreme points for the linear interpolation. Therefore if shape[0]
            has foreground color 0, and shape[1] has color 10, the range of
            colors displayed would be interpolated between 0 and 10. Likewise,
            if shape[0] displays a tall thin rectangle, and shape[1] a short
            wide rectangle, the shapes displayed would be 'morphed' between
            these two extremes. Of course, to get these effects one would have
            to set the color_val and morph_val to the appropriate values.
            In addition to the shapes themselves, three arrays are used to specify
            how the xview does interpolation. As already mentioned, the 'values'
            array specifies the actual values to be displayed. 'value_min'
            contains the values that correspond to the lower end of the
            interpolated range. Thus if value[0][0] was equal to value_min[0],
            the parameter displayed would correspond to shape[0]. Likewise,
            value_max contains the upper end of the interpolated range.

            One can have multiple xshapes. In this case the interpolation first
            decides which pair of shapes to use. In this version, each pair of
            shapes handles an equal range between value_min and value_max.
            Having selected the appropriate pair of shapes, the algorithm then
            proceeds as outlined above.

            The 'text' option simply prints out the floating point value of the
            appropriate message. The 'minigraph' option (which will be
            implemented one of these days) displays a little graph of the
            value, without any optional extras like axes.

            By default, the xview object is created along with two child shapes,
            shape[0] and shape[1]. The default shapes are squares, shape[0] being
            a small one with color 0 and shape[1] a big (1x1) square in color 63.
            The child shapes can have parameters set in the usual ways, but are
            not displayed independently of the xview pix. For the technically
            minded, this is because their pixflags have been set to visible_not.

            Note on 'morphing': Morphing in the xview pix is simply linear
            interpolation between corresponding points. When one shape has a
            different number of points from the other, then the algorithm
            assumes that the missing points are [0,0,0] and does interpolation
            accordingly. This may lead to peculiar effects, so usually one
            uses the same number of points in all xshapes.

            Note on 'value_min' and 'value_max' arrays: The same min and max
            apply to all points in an xview. At this time autoscaling has
            not been implemented, but this should be easy.

    Author:         Upi Bhalla Caltech Dec 93

    -----------------------------------------------------------------------------

    ELEMENT PARAMETERS

    DataStructure:  xview_type [in src/Xodus/draw/xview_struct.h]

    Size:           ?       Depends on number of associated shapes and number of
                            points being displayed.

    Fields:
            The following fields are the same as for xvar:
                    fg      Foreground color of view.
                    script  Script operation(s) to perform on a mouse
                            click. The script calls of the view are only made
                            if the draw determines that the view is the nearest
                            to the event and if the event occurred within the
                            bounding region of the view.
                    tx      Transposition distance in the x dimension. The
                            view is transposed (ie, displaced, offset) by this
                            amount.
                    ty      Transposition in y.
                    tz      Transposition in z.
                    pixflags        Set of flags specifying visibility,
                            refreshes, mouse sensitivity and many other options.
                            Use the 'pixflags' utility function to find out more.

                    viewmode        Specifies the mode of operation of the
                                    xview. Can be one of:
                            shape - Does interpolation between shapes
                            graph - draws a minigraph (Not yet implemented)
                            surface - Draws a plane in 3-d, specified by 3
                                            points in space (not yet implemented)
                            contour - Draws contour lines for a plane in 3-d. NYI.
                            colorview - Backwards compatibility hack. Uses 'shape'
                                      mode to display boxes of different color.
                            boxview - Backwards compatibility hack. Uses 'shape'
                                      mode to display boxes of different sizes.
                            colorboxview - Backwards compatibility hack. Default
                                      viewmode. Uses 'shape' mode to display VAL1
                                      using both the morph and color modes for
                                      a box.
                            fillboxview - Backwards compatibility hack. Uses
                                    'shape' mode to display filled boxes of
                                    different sizes.
                    value_min       1-d array with lower limits for shape
                                      parameters.
                    value_max       1-d array with upper limits for shape
                                      parameters.
                    values          2-d array with display values.
                    color_val       Specifies message to use for color
                                      display values. 0=disabled is default.
                                      If you wish to cause view to change
                                      colors, use color_val.
                    morph_val       Specifies message to use for morphing.
                                      If you wish to have the view change
                                      shape, use morph_val.
                    xoffset_val     Specifies message to use for xoffset.
                                      If you wish to cause a view to
                                      bounce around on the screen,
                                      use the offset_vals.
                    yoffset_val     Specifies message to use for yoffset.
                    zoffset_val     Specifies message to use for zoffset.
                    text_val        Specifies message whose value should
                                      be printed out.
                    textcolor_val   Specifies message which determines
                                      the color of the text.
                    linethickness_val  Specifies message determining the
                                      line thickness used in the view.
                    sizescale       Rescales all the shapes. The default
                                      shapes have a size of 1.

            The following fields are new for xview:
                    xpts            1-d array with x-coordinates of points.
                                    This is automatically set if the 'path' field
                                    is set, or if COORD messages are present.
                    ypts            1-d array with y-coordinates of points.
                                    This is automatically set if the 'path' field
                                    is set, or if COORD messages are present.
                    zpts            1-d array with z-coordinates of points.
                                    This is automatically set if the 'path' field
                                    is set, or if COORD messages are present.
                    ncoords         Number of points.
                                    This is automatically set if the 'path' field
                                    is set, or if COORD messages are present.
                    autoscale       Flag for determining if the xview should
                                    calculate value_min and max by itself. Options:
                                    0 = off. 1 = max ever reached. 2 = max current.
                                    (Not Yet Implemented)
                    undraw_by_blanking
                                    Flag for deciding if the xview should clear
                                    the whole display every step for redrawing.
                                    This may be faster in some cases, but may also
                                    leads to flicker.
                                    (Not Yet Implemented)
                    path            Wildcard path for elements specifying
                                    coordinates. (xpts, ypts and zpts)
                    relpath         Relative path for child elements off 'path',
                                    determining where the fields are located.
                    field           Name of field to display. Can have the
                                    special values "msgin" or "msgout".
                    field2          An extra field to display. Cannot have
                                    "msgin" or "msgout"
                    msgpath         Wildcard path for elements connected via
                                    msgs to 'path'. Only used for "msgin" or
                                    "msgout" modes of 'field'.
                    msgtype         Specifies type of msgs to display.
                    msgslotno       Specifies slot number of msgs to display.
                    value           Set by a click action, according to valuemode.
                    valuemode       Specifies how xview fills the 'value' field
                                    when a click event occurs on the view.
                                    Can be one of "path"; "index"; "lookup"
                                    Default = "path".
                                    path: Finds the path of the element represented
                                            at the click site
                                    index: Returns the internal xview
                                            index of the click site
                                    lookup: Returns the value displayed at
                                            the click site from values[0].

    ----------------------------------------------------------------------------

    SIMULATION PARAMETERS

    Function:       XVar [in src/Xodus/draw/xview.c]

    Classes:        gadget output

    Actions:        PROCESS: Redo interpolation and display.
                    RESET:  Required when changing child xshapes,
                            looks up coordinates.
                    CREATE: Automatically creates 2 child xshapes.
                    XUPDATE: update internal fields when
                            displayed widget is changed.
                    B1DOWN: Invoked when mouse Button 1 is pressed.
                    B2DOWN: Invoked when mouse Button 2 is pressed.
                    B3DOWN: Invoked when mouse Button 3 is pressed.
                    ANYBDOWN:       Invoked when any mouse button is pressed.
                    B1DOUBLE: Invoked on a double click on mouse button 1.
                    B2DOUBLE: Invoked on a double click on mouse button 2.
                    B3DOUBLE: Invoked on a double click on mouse button 3.
                    XOCOMMAND: an action that can invoke the functions
                            in the 'script' field
                    XODROP: Called when a another pix is dropped onto this one.
                    XODRAG: Called when the mouse is clicked on this pix, and
                            the mouse moves while the mouse button is held down.
                    XOWASDROPPED: Called after this pix has been dropped onto
                            another one.

    Messages:       VAL1 data
                    VAL2 data
                    VAL3 data
                    VAL4 data
                    VAL5 data

                    All messages can contain values for any display parameter.

    ----------------------------------------------------------------------------

    Notes:          Can only be displayed in a coredraw widget subclass.
                    The xview performs the interpolation between shapes and
                    redraws them on every clock tick.

    Examples:
    //=================================CUT HERE=================================

    //genesis
    //
    // This example demonstrates how xview can use the fields
    // 'path', 'field' and 'field2' to display a combination of message
    // values and field values. Note how the
    // color of the boxes (displaying msgin) in the view display is
    // related to the size of the boxes (displaying the 'output' field
    // of the tables) preceding them.
    //
    int side = 10

    xcolorscale rainbow2
    create xform /form [0,0,500,550]
    xshow /form
    create xdraw /form/draw [0,0,100%,500]
            setfield /form/draw xmin -1 xmax 11 ymin -1 ymax 11
    create xview /form/draw/view

    create xbutton /form/run -wgeom 50% -script "step 100"
    create xbutton /form/quit -ygeom 0:draw -xgeom 50% -wgeom 50% \
            -script quit

    /* Set up the connectivity that the view will look at */
    create table /tab
    call /tab TABCREATE 1 0 1
    setfield /tab \
            stepsize 1 \
            step_mode 0 \
            table->table[0] 0 \
            table->table[1] 1
    addobject tabobj /tab

    createmap tabobj /manytabs {side} {side}

    gen_3d_msg /manytabs/tab[] /manytabs/tab[] 0.5 1 INPUT output -o -1 0 0
    gen_3d_msg /manytabs/tab[] /manytabs/tab[] 0.5 1 INPUT output -o 9 -1 0

    call /manytabs/tab[99] TABCREATE 100 0 1
    setfield /manytabs/tab[99] \
            stepsize 0.01 \
            step_mode 1
    /* Set up some values for the tabs to display */
    int i
    for(i = 0 ; i < 100 ; i = i + 1)
            setfield /manytabs/tab[99] table->table[{i}] {{rand 0 100 }/100.0}
    end

    /* Set up the view widget */
    setfield /form/draw/view \
             path /manytabs/tab[] \
             field msgin \
             field2 output \
             morph_val 2 \
             relpath "" \
             msgpath "" \
             msgtype INPUT \
             msgslotno 0

    reset

    //=================================CUT HERE=================================

See also: xvar , xshape

Previous Next Table of Contents