**[Summary of PTRANSP Client-Server Communications---Version 2.0, Based
on the Plasma State Software.]{.underline}**

As a part of the PTRANSP project, TRANSP has been modified to run in
server mode. In this mode, TRANSP acts as a server to a separate
predictive transport model, the "client" code. The services provided by
this PTRANSP server are: (a) computation of heating, current drive,
momentum and particle sources due to neutral beams, fusion product fast
ions, RF, and neutral gas inflow from the plasma periphery, and (b)
analysis of the results of the client predictive code, with output
produced in standard TRANSP archive format. The files produced by part
(b) are the same as those produced by a traditional TRANSP experimental
data analysis run, for which many useful physics post-processors exist.

This document describes work in progress -- D. McCune, 19-Jan-2007. It
has been evolved from the original document which described an
implementation based on the NTCC XPLASMA module. This version describes
the implementation using the SWIM SciDAC Plasma State software for
inter-component communications. The document is in two parts. The first
part describes the PTRANSP Client-Server communications scheme at a file
level without going into details about the plasma state; the second part
describes in detail how the client code will need to use the plasma
state in order to communicate with the PTRANSP server.

The client-server communications methods described have been tested
using a program "test_client.f90" in the TRANSP source distribution;
this source code contains examples of some of the methods described
herein.

A related working document \[1\] describes the plasma state software.

\[1\] <http://w3.pppl.gov/~dmccune/SWIM/Plasma_State_V0.2.doc>

**[Part I: TRANSP Client-Server Communication:]{.underline}**

The client and server processes are separate programs running
simultaneously on a common system. Client-server communication is
managed by files using tools developed in the earlier NTCC project.
Plasma equilibria and profiles are passed back and forth using *plasma
state* files. The plasma state software, layered over XPLASMA and other
NTCC libraries, has been developed as part of the SWIM SciDAC Fusion
Simulation Project as a means of exchange of plasma data between
independently coded simulation model components. In addition to plasma
state files, small ascii "signaling files" are used to coordinate and
serialize the computation. At any given point in time, either the client
is actively computing with the server waiting for a signal file, or, the
server is active and the client is waiting.

The client controls the time step advance. It is presumed that sources
will be updated on a fairly coarse time step (perhaps 5-25 msec) while
the client code advances fluid equations, poloidal field, and MHD
equilibrium on as fine a time step as it requires. A single coarse time
step is to be applied for all types of heating sources.

Shell script files fsp_runtr and fsp_rstr are provided to launch the
PTRANSP server for a new run, or to restart the server for an existing
run, respectively. These will be described below.

The following signal files are recognized and expected by the PTRANSP
server:

-   transp_init.dat is provided at the start of a run. It specifies a
    plasma state file containing the initial equilibrium, plasma
    profiles, start time and the first time step for sources.

-   transp_step.dat is provided as the run progresses. It specifies a
    sequence of one or more plasma state files defining the evolution of
    the plasma equilibrium and profiles.

-   transp_save.dat requests that PTRANSP save its internal state in a
    restart file.

-   transp_kill.dat requests that PTRANSP halt immediately with an error
    status code.

When these files are detected and acted upon, they are renamed, so that
attempts to repeat actions will not occur. Although the contents of the
transp_save.dat and transp_kill.dat files are immaterial, the PTRANSP
server does read the contents of the transp_init.dat and transp_step.dat
files. These files are expected to contain ascii text records of the
form:

\<time-value\> \<state-file-path\> \[\<keyword\>\]

Where:

-   \<time-value\> is the time associated the corresponding plasma state
    data;

-   \<state-file-path\> gives the plasma state filename (relative paths
    are resolved from the client's working directory);

-   \[\<keyword\>\] (optional) can specify an additional request. At
    present, and only in the transp_step.dat file, the \<keyword\> "END"
    means: end the TRANSP run, shut down the server, and archive the run
    results. (*Note dmc June 2006: Additional keywords are likely to be
    added later, e.g. to specify events such as sawteeth or pellet
    injection*).

The transp_init.dat file contains exactly one such record;
transp_step.dat can contain multiple such records in ascending order of
time---with the last time matching the end of the previous source time
step and the last state file containing a list specifying the next
source time step (details on state file contents will be explained
below).

A technical note is in order. To avoid a race condition when writing
either transp_init.dat or transp_step.dat, it is recommended to first
write the entire file contents in a temporary file, and then rename the
file with such a call such as:

istat=jsystem("mv "//trim(tmpfile)//" transp_step.dat")

only when the file contents are complete. It has been observed that
writing data records directly into transp_init.dat or transp_step.dat is
hazardous, as the PTRANSP server may attempt to read the file before it
has been completely written.

When the server is active, the client code is expected to wait for:

-   transp_ready.dat which will contain either the path to a modified
    plasma state file containing source calculation results, or the
    single word "ERROR".

(PTRANSP follows the procedure of writing a temporary file and renaming
it on completion).

The PTRANSP server uses subroutines wait_for_file or wait_for_file_list
which are available in the portlib NTCC library; it is recommended that
the client do the same. The routine includes a timeout argument which
makes it possible for the client or server code to exit if too much time
passes without the expected file or files being received.

**Invocation of the PTRANSP Server**:

In the past, use of TRANSP required a separately prepared namelist with
identification of time dependent data inputs from an experimental
database. Now, in server mode, PTRANSP instead receives all of its time
dependent input data from the client code via the plasma state
interface. In fact, the entire control of the PTRANSP server can be
driven from a named "standard configuration namelist template" which
will vary from tokamak to tokamak but not from run to run when dealing
with simulations of the same tokamak configuration. The namelist
template contains such information as neutral beam geometries and RF
antenna information for a specific tokamak experiment. The client code
need only know the namelist template filename and be able to provide a
time series of plasma states, in order to use the PTRANSP server. The
client code controls the evolution of powers and voltages on the various
neutral beams, powers and frequencies on RF antennas; the PTRANSP server
provides the resulting heating, fueling, momentum and current drive
source profiles. The client also has access to PTRANSP namelist
numerical controls which are likely to need to vary from run to
run---indeed a flexible mechanism for PTRANSP namelist modifications is
provided.

The client and server codes will launch from a script in a controlling
process which must include an environment sufficient for both the client
code and the PTRANSP server to run. Launching the PTRANSP server
requires three steps: (1) selection of a TRANSP run identifier
{\<tokamak\>, \<yy\>, \<runid\>} (\<yy\> denotes a 2 digit "year" code;
all fields are explained below); (2) adaptation of the PTRANSP namelist
template to create a full TRANSP namelist, and augmentation of plasma
state with basic auxiliary heating and fast ion species information, and
(3) actually starting the PTRANSP server process. After launch, the
PTRANSP server can be halted and restarted. Each of these steps is
described in detail.

**1. TRANSP Run Identifier:**

The TRANSP run identifier controls the disposition of TRANSP output
data---names of files produced by TRANSP and the directory in which they
will be archived. The server process itself runs in the subdirectory
\<runid\> of the directory in which the client is run; \<runid\> is a
prefix for all files produced by the TRANSP run. The two fields
\<tokamak\> and 2-digit year code \<yy\> determine the directory in
which the completed run results will be archived. The \<tokamak\> ID is
a 3- or 4-character identifier selected from an extensible list of known
tokamaks; the most commonly used tokamak identifiers (as of January
2007) are: AUGD, CMOD, D3D, HL2A, ITER, JET, JT60, KSTR, MAST, NHTX,
NSTX and TFTR. New tokamak identifiers can readily be added by a TRANSP
maintainer. The two digit year code \<yy\> is one of {"00", "01", ... ,
"99"}.

In experimental analysis TRANSP runs, \<runid\> is usually a shot-try
combination, with user-defined semantics, e.g. TFTR experimentalist
practice was that the runid 37065A06 would indicate the 6^th^ analysis
of TFTR shot number 37065. The \<yy\> would then be the last two digits
of the calendar year of the shot, e.g. "88" in the case of TFTR 37065.

For predictive simulations, there is no shot year nor is there a set
shot numbering scheme. Therefore, it is recommended to use an
alternative available \<runid\> format---simply a four digit number. The
\<yy\> instead should be the calendar year of the start of a predictive
study, i.e. a series of related runs involving the PTRANSP server.

The client must provide a \<tokamak\> and \<yy\> code, but the \<runid\>
selection can be made automatic. The PTRANSP environment defines an
executable shell script:

get_4digit_runid_file \<tokamak\> \<yy\> \[\<base_id\>\]

This produces a file runid.dat containing a single record specifying the
first 4 digit integer \<runid\> greater than \<base_id\> that has not
already been archived in the TRANSP results directory associated with
the given \<tokamak\> and \<yy\>. If \<base_id\> is omitted, a value of
"5000" is assumed.

This procedure can be used from fortran code as follows. The fortran
code needs to be linked against the NTCC portlib library:

integer :: jsystem,istat

character\*4 :: tok ! \<tokamak\>

character\*2 :: yy ! 2-digit-year-code in ascii

character\*10 :: runid ! PTRANSP \<runid\> (generated)

character\*100 :: cmd ! shell script command

integer :: lunio = 99 ! LUN for fortran file i/o

... ! client code gets tok

... ! client code gets yy

cmd = "get_4digit_runid_file "//tok//" "//yy

istat = jsystem(cmd) ! execute shell script

if(istat.ne.0) then

write(6,\*) " ? automatic RUNID fetch failed "

exit

endif

open(unit=lunio,file="runid.dat",status="old")

read(unit=lunio,'(A)') runid ! read generated RUNID

close(unit=lunio)

Upon successful completion, the PTRANSP server will archive its results.
If the normal PPPL TRANSP run production facility is used, this archive
will also cause an MDS+ tree to be written, allowing the TRANSP data to
be accessible over the network at:
MDS+::transpgrid.pppl.gov:TRANSP(\<tokamak\>.\<yy\>,\<runid\>) via the
MDS+ data service. There are many useful physics post-processors that
know how to access TRANSP data stored in this form.

**2. Creation of TRANSP Namelist with Augmentation of Plasma State:**

The TRANSP namelist must be adapted from a template namelist, because
certain time invariant plasma state data, such as plasma species lists,
can only be entered into the PTRANSP server through the namelist. In
addition, certain critical numerical controls that strongly affect
PTRANSP server performance will need to be controlled by the client on a
run-by-run basis--- number of model particles for Monte Carlo fast ion
simulation for example. Because of these requirements, a *namelist
adaptor* is provided with the PTRANSP server. The adaptor takes as input
(1) a namelist template filename; (2) the name of a file containing
run-specific namelist modifications; and (3) an initial plasma state to
be generated by the client code, from which the PTRANSP server can take
the thermal plasma species list and into which it can write neutral beam
and RF antenna information. For output it writes *both* an augmented
version of the plasma state and a complete namelist ready for use by the
PTRANSP server.

The client will need to execute the following program to invoke the
namelist adaptor:

namelist_adapt \<template-file\> \\

\<modifications-file\> \<state-file\> \<runid\>TR.DAT

The program can be invoked from fortran code by the same method as shown
for generating a \<runid\> in the previous section. It reads the first 3
files, writes a modified version of \<state-file\>, and creates and
writes the full PTRANSP server namelist \<runid\>TR.DAT.

The plasma state can be built up in stages---details are given in the
section "Creation of Plasma States", below. The initial plasma state
provided by the client at this stage should be very simple, containing
only the species lists for thermal electrons and ions and possibly a
list of RF minority species.

When namelist_adapt executes, it *augments* the state by inserting the
number and "name" for each neutral beam and each RF antenna available to
the tokamak configuration described in the \<template-file\>; it also
creates the complete fast ion species list and merged list of all plasma
species. It checks that the thermal species list meets PTRANSP
requirements---for example, each beam injected species needs to be
included on the thermal ion species list.

The client code will likely have to know in advance about the number of
beams and RF antennas, since it will be responsible for controlling
their powers, voltages, and frequencies time dependently throughout the
simulation. The client will need to read back the augmented state and
verify that the number of neutral beams, etc., match its own internally
specified data.

The \<modifications-file\> contains critical numerical controls for the
PTRANSP server that vary from run to run and need to be set by the
client code. Such controls determine the resolution and computational
cost of the PTRANSP server simulation. Examples are: numbers of Monte
Carlo model ions to use for fast species simulations, numbers of radial
and/or poloidal zones to use in various heating models, numbers of
Fourier modes to use in RF full wave solvers, etc., etc., depending on
the models being invoked.

*Editorial note (Jan. 2007): At this stage in the project, neither a
library of template files, nor a document describing common
modifications exist. Early users will have to work with PTRANSP experts
to define and create these resources. Also, it may be that certain types
of error detection will need to be added to namelist_adapt.*

There is separate documentation \[1\] (from the SciDAC SWIM project)
describing plasma state files \<state-file\> and the means for their
creation (also, more information below).

**3. Activation of the PTRANSP Server.**

The client script will start the PTRANSP server for a new run by
invoking the command:

fsp_runtr \<runid\> \<tok\> \<yy\> \<runid\>TR.DAT \[\<cmt-path\>\]

set fstat = \$status

This script can also be run from inside a fortran program, using the
method shown in a preceding section. The script arguments have the
following interpretation:

-   \<runid\> \-- TRANSP runid (see section on TRANSP run identifiers).

-   \<tok\> \-- a 3- or 4- character "tokamak id" (see TRANSP
    identifiers section).

-   \<yy\> \-- a 2 digit "shot-year code" (see TRANSP identifiers
    section).

-   \<runid\>TR.DAT \-- specifies the path to the namelist used to
    control the server job. This is the namelist file produced by
    namelist_adapt as described in the preceding section.

-   \[\<cmt-path\>\] -- (optional) path to an ascii text file containing
    a few comments describing the run, comments which will be inserted
    in the TRANSP archives.

This script should execute in the directory where the client code will
execute. It will create a subdirectory \<runid\> in which the PTRANSP
server will execute. The PTRANSP server will initialize itself. The
client script *must* check the status code returned; any value other
than zero indicates that the TRANSP server failed to start. The
fsp_runtr script will write summary information (including error
messages) to stdout and/or stderr; in addition, files \*.log in the
\<runid\> subdirectory may be left with useful debugging information.
Also, generally, sufficient files are left in place so that a PTRANSP
expert can debug the server without requiring the client code to run.

If fsp_runtr exits with normal status, the TRANSP server is running, and
waiting for the appearance of transp_init.dat, in either the parent
directory (working directory of the client) or in the \<runid\>
subdirectory.

**4. Halting and Restarting the PTRANSP Server.**

In predictive simulations, it is not unusual for calculations to be
halted and restarted with modified input data. The PTRANSP server can
also be shut down and restarted at any time; data modifications would be
passed through subsequent exchanges of plasma state.

To shut the TRANSP server down cleanly for restart, the client code
should first write the transp_save.dat file followed by transp_kill.dat.
The content of these files is immaterial; it is merely their existence
that is tested by the server. So, simple NTCC portlib calls could be
used by the client (fortran-90 example):

integer :: istat, jsystem

istat = jsystem("date \> transp_save.dat") ! save state

call gosleep(1) ! 1 second pause

istat = jsystem("date \> transp_kill.dat") ! kill

When TRANSP sees transp_kill.dat, it exits with a status code, so that
its controlling script keeps all temporary files and does not attempt to
archive run results files---i.e. leaving the server in a restartable
state.

When all is ready, the PTRANSP server can be restarted by invoking the
script:

fsp_rstr \<runid\>

set fstat = \$status

This can also be launched from fortran with a portlib jsystem call. The
client driver should check the exit status---a non-zero value indicates
a failure of TRANSP to restart, which would need to be debugged.

To halt the TRANSP server at the very end of a run, the keyword "END"
should be appended to the record in a transp_step.dat file specifying
the halt time and the final equilibrium of the run. Although not
strictly required for the client to complete its calculation, the TRANSP
server expects the client to tell it when to shut down cleanly. This is
necessary to signal the archival of TRANSP output. The transp_kill.dat
signal file should *not* be used for this purpose.

**[Part II: Detailed description of use of Plasma State]{.underline}**

**Access to Plasma State Softaware:**

The Plasma State software consists of three fortran-95 libraries:
plasma_state.a, ps_xplasma2.a, and plasma_state_kernel.a---the API,
XPLASMA implementation, and the "kernel" routines and state derived data
type definition, respectively. These libraries are available in TRANSP
binary distributions and in the NTCC binaries as well. At PPPL as of
Jan. 2007, the "pshare" production version TRANSP binary libraries are
located on cluster file systems in:

/p/transpgrid/transp_platform/RHEL/lib (Linux, lf95 fortran)

/p/transpgrid/transp_platform/SGI/lib (SGI, ifc fortran)

and public modules are located in:

/p/transpgrid/transp_platform/RHEL/mod (Linux, lf95 fortran)

/p/transpgrid/transp_platform/SGI/mod (SGI, ifc fortran)

Codes which load in the plasma state libraries will also need to load in
its dependencies---the xplasma software, NetCDF, etc. An up-to-date list
of dependencies can be provided by a PTRANSP expert.

Source codes which use plasma state modules will need to be compiled
with the appropriate directory included in their module path. To import
the plasma state interface and data type definition, such source codes
should:

use plasma_state_mod.

This module instantiates several plasma state data structures as
summarized in table 1:

  ------------------ -------------------- --------------------------------
  *Name of state     *Default filename*   *Usage*
  object*                                 

  ps                 cur_state.cdf        Current working plasma state

  psp                prev_state.cdf       Committed prior working plasma
                                          state

  saw0               saw0_state.cdf       State at start of sawtooth event

  saw1               saw1_state.cdf       State at end of sawtooth event

  pel0               pel0_state.cdf       State at start of pellet event

  pel1               pel1_state.cdf       State at end of pellet event
  ------------------ -------------------- --------------------------------

**Table 1: Names of state objects and associated files.**

The client code will interact primarily with the ps state. Generally,
state member data elements are publicly accessible. For example, ps%t0
and ps%t1 will define the time step for heating sources; these are
directly settable by the client code. The client and server codes
exchange plasma states as disk files.

The elements of the plasma state are created by a python *code
generator*. The state specification file (input to the code generator)
defines all of the state elements. An alphabetized list of all plasma
state elements can be found in plasma_state_index.txt, a file written by
the code generator. As of January 2007 copies of these files could be
found at PPPL on:

/p/pshare/codesys/source/plasma_state/swim_state_spec.dat

/p/pshare/codesys/source/plasma_state/plasma_state_index.txt

The following sections describe the plasma state elements and calls that
will need to be used in order to provide input data to the PTRANSP
server, and receive output. This involves procedures both for
initialization of state at the start of a new simulation, and, updates
to an established state which will be carried out as the simulation
advances in time.

**The Initial Plasma State for the PTRANSP Namelist Adaptor.**

As described in a separate document \[1\], plasma state arrays can be
built up incrementally. An empty state contains a set of unallocated
arrays and corresponding array dimension sizes all set to zero. As array
dimension sizes are given non-zero values,

call ps_alloc_plasma_state(ier)

results in allocation of the ps state arrays for which *all* dimension
sizes have non-zero values. Note, however, that array dimension sizes
can only be set *once*. Once an array has been allocated to a certain
size, an attempt to reallocate with any changed dimension size will be
reported (by ps_alloc_plasma_state) as an error. Therefore, this routine
is generally used only during the *initialization* of a simulation, and
"dynamic resizing" of state arrays is not presently supported by the
plasma state software.

The call to ps_alloc_plasma_state does not specify the state object
explicitly---there is an implicit reference to the ps state. Although
some routines allow the state object to be named, others (including this
one) can only refer to the ps state. States other than ps will be
created by copying the ps state and then applying modifications.

When using the PTRANSP server, the first initialization step is to
define the list of thermal plasma species (including electrons and
impurities), and a separate list of RF minority species if applicable.

The PTRANSP namelist_adapt program will build the complete list of fast
ion species based on the namelist template data provided. To be
compatible with PTRANSP, the fast ion species list has to be built in a
specific order; therefore it is necessary to leave completion of the
fast ion species list to PTRANSP.

Species lists can *only* be defined *once* at the start of the
simulation. Although species with zero density can be created and
maintained, adding an entirely new specie part way through a simulation
is not supported. Therefore, all "possible" thermal species for a
simulation should be specified at initialization of the simulation.

The Plasma state contains 4 species lists, dimensions for which are
shown in table 2:

  ------------------ --------------------- -------------------------------
  *State Elements*   *Description*         *Procedure...*

  ps%nspec_th        Number of thermal     Set directly by client code
                     ions                  

  ps%nrfmin          No. of RF minority    Set directly by client code
                     ions                  

  ps%nspec_nonMax    Total no. all fast    Set by PTRANSP namelist_adapt
                     ions                  

  ps%nspec           Total no. all ions    Set by PTRANSP namelist_adapt
  ------------------ --------------------- -------------------------------

**Table 2: Species List Sizes.**

Table 3 shows the actual state elements which constitute the species
lists. For each specie there are: atomic charge (C), ion charge
![](media/image1.wmf) (C), mass ![](media/image2.wmf) (kg),
CHARACTER\*32 label, and INTEGER type code. Except for label and type,
these items are stored as arrays of 64 bit floating point real numbers.
For all *fully stripped* ions, the atomic charge and the ion charge are
the same. The thermal species list and the "all" species list include
electrons at index 0; RF and fast ion lists do not include electrons and
their 1^st^ element index is 1. As with the list sizes, the list
elements for the thermal species and RF minority species should be set
by the client code; the complete fast ion list and combined list of all
species will be set by namelist_adapt.

  ----------------- ---------------- --------------------- --------------
  Thermal species   RF minority ions All fast ions         All species
  (0:ps%nspec_th)   (1:ps%nrfmin)    (1:ps%nspec_nonMax)   (0:ps%nspec)

  ps%qatom_s        ps%qatom_rfmin   ps%qatom_nonMax       ps%qatom_all

  ps%q_s            ps%q_rfmin       ps%q_nonMax           ps%q_all

  ps%m_s            ps%m_rfmin       ps%m_nonMax           ps%m_all

  ps%s_name         ps%rfmin_name    ps%nonMax_name        ps%all_name

  ps%s_type         ps%rfmin_type    ps%nonMax_type        ps%all_type
  ----------------- ---------------- --------------------- --------------

**Table 3: Species List Contents---singly dimensioned arrays with the
dimensioning as indicated: atomic charge (C), ion charge (C), mass (kg),
CHARACTER\*32 name, and INTEGER type code.**

The plasma­­\_state module defines a number of fortran-90 PARAMETER
constants (these can be found in the state specification file
swim_state_spec.dat). Among these are the floating point constants ps_xe
(unit electron charge in C), and ps_mp (proton mass in kg). Thus, the
following expressions find the atomic number and mass (AMU) of element j
of the "all species" list:

Z = ps%qatom_all(j)/ps_xe

A = ps%m_all(j)/ps_mp.

Species type codes are defined by a set of integer constants:

  ------------------ --------- ---------------------------------------------
  *Name*             *Value*   *Interpretation*

  ps_electron        -1        Electrons

  ps_therm_ion       1         Thermal ions

  ps_impurity        2         Impurites with set charge and mass

  ps_tokamakium      3         Tokamakium impurity, radially varying charge
                               and mass

  ps_beam_ion        4         Beam ions

  ps_rf_minority     5         RF Minority ions

  ps_fusion_ion      6         Fusion Product ions
  ------------------ --------- ---------------------------------------------

**Table 4: Species Type Codes.**

It is recommended to use a plasma_state module subroutine to set species
list elements. This insures that appropriate and unique labels are
generated for each species, as is required by the software (arguments
are integer input scalars except as noted):

SUBROUTINE ps_label_spectype( &

iZatom, & ! atomic number (-1 for electrons)

iZcharge, & ! atomic charge (-1 for electrons)

iAMU, & ! atomic weight (2 for Deuterium)

itype, & ! plasma_state species type code

label, & ! label (character\*32, output)

qatom, & ! atomic charge (real\*8, C, output)

qcharge, & ! ion charge (real\*8, C, output)

mass) ! mass (real\*8, kg, output)

The proper use of this routine is shown in the client sample code,
below. For the "Tokamakium" impurity put iZatom = iZcharge = iAMU = 0;
for electrons put iAMU = 0; the correct mass will be output. As will be
shown in the sample code below, it is recommended to explicitly set
elements of the array specifying the species type, and use the
subroutine to set all other species list array elements.

Concerning the species definitions to be set by the client code, the
following rules should be noted (and are checked by namelist_adapt):

-   Thermal species specification order: electrons, then non-impurity
    ions, then impurity ions. Non-impurities are isotopes of H and He.

-   If the *tokamakium* impurity is present, it must be the *only*
    impurity present. *But:* it is recommended to use multiple
    conventional fixed A and Z impurities instead.

-   Any specie in the RF minority ion list must *not* be in the thermal
    species list. RF minority species can only be specified as a
    fraction of the total electron density.

Tokamakium is the name for an optional model impurity with a variable
average charge and mass. It is used in some simulations as a simple and
efficient way to represent an amalgam of multiple impurities and charge
state distributions. *(Note: as of Jan 15, 2007, the PTRANSP server
allows time dependent non-integer values of Tokamakium A and Z, but
radial variation is not supported. Therefore, it is recommended to use
multiple fixed A and Z impurities instead)*.

Putting it all together, the client code will need a subroutine to
initialize the plasma state species lists, which will look something
like this:

subroutine init_species

use client_mod

! client input data (hypothetical):

! nmain = #non-impurity thermal ion species

! nrfmin= #minorities

! nimp = #impurity thermal ions

! mass(...), mass_rf(...), ... -- ion masses, kg

! charge(...), charge_rf(...), ... -- ion charges, C

! frac_rf(...) -- minority ion density fractions

use plasma_state_mod

implicit NONE

integer :: j,imp,ierr,iZ,iZatom,iA

ps%nspec_th= nmain+nimp ! no. of thermal ions

ps%nrfmin= nrfmin ! no. of RF minority species

call ps_alloc_plasma_state(ierr) ! allocate lists

if(ierr.ne.0) \<handle error...\>

! electrons:

ps%s_type(0)= ps_electron

call ps_label_spectype(-1,-1,0,ps%s_type(0), &

ps%s_label(0), ps%qatom_s(0), &

ps%q_s(0), ps%m_s(0))

! main plasma ions:

do j = 1,nmain

iZ = charge(j)/ps_qe + 0.01  ! integer Z

iA = mass(j)/ps_mp + 0.01 ! integer A

ps%s_type(j)= ps_therm_ion

call ps_label_spectype(iZ,iZ,iA,ps%s_type(j), &

ps%s_label(j), ps%qatom_s(j), &

ps%q_s(j), ps%m_s(j))

end do

! impurities

Do j = nmain+1, nmain+nimp

imp = j -- nmain ! impurity index

! \*\* partially stripped impurity: iZ \< iZatom

iZ = charge_imp(imp)/ps_qe + 0.01  ! integer Z

iZatom = charge_imp_atom(imp)/ps_qe + 0.01

iA = mass_imp(imp)/ps_mp + 0.01 ! integer A

ps%s_type(j)= ps_impurity

call ps_label_spectype(iZatom, &

iZ,iA,ps%s_type(j), &

ps%s_label(j), ps%qatom_s(j), &

ps%q_s(j), ps%m_s(j))

end do

! RF minority ions:

ps%kdens_rfmin = 1 ! Minority density =

! frac\*\[electron density\]

do j = 1,nrfmin

iZ = charge_rf(j)/ps_qe + 0.01  ! integer Z

iA = mass_rf(j)/ps_mp + 0.01 ! integer A

ps%rfmin_type(j)= ps_rf_minority

call ps_label_spectype(iZ,iZ,iA,ps%s_type(j), &

ps%rfmin_label(j), ps%qatom_rfmin(j), &

ps%q_rfmin(j), ps%m_rfmin(j))

ps%fracmin(j)= frac_rf(j) !\*\* density fraction

end do

! write "ps" state in file "cur_state.cdf":

call ps_store_plasma_state(ierr)

if(ierr.ne.0) \<handle error...\>

end subroutine init_species

Note that the plasma state allows specification of minority ion specie
densities as fixed fractions of electron density (ps%kdens_rfmin = 1).
At present (*Jan. 15 2007*) this is the *only* option for specification
of minority RF ion density.

Note also that the initial plasma state (just the species lists) is
written to cur_state.cdf; this file name will be provided as an argument
to namelist_adapt. A different file name could have been chosen by using
the optional filename argument of the ps_store_plasma_state
subroutine---see the next section.

**A Note on File Names and State I/O Subroutines.**

(*D. McCune 16 Jan 2007 -- this section under development, subject to
change*).

Since the PTRANSP server (as currently configured) executes in a
subdirectory of the client code, the client and server have different
paths to shared disk files.

Each state object has associated with it a default filename, as shown in
table 1 above. However, each code runs with its own copy (in memory) of
the plasma state module:

use plasma_state_mod

The module contains a public variable (character\*256) state_path which
allows each executable code to set its own default path to all state
files---as needed to reflect the fact of two programs running from
separate directories sharing files.

The default value of state_path is blank, denoting the executing
program's current working directory. The PTRANSP client code can leave
this value unmodified, in which case it will write all state files into
its own current working directory. PTRANSP, running in a subdirectory of
the client, will set this variable to "..", UNIX syntax for the path to
the parent of its current working directory.

The plasma state module's main I/O routines provide an optional argument
filename that allow the state object's default filename and file path to
be overridden. If this is used, it is the caller's responsibility to
provide a full path to the correct state file.

The main I/O routines (with optional arguments shown) are as follows:

SUBROUTINE ps_store_plasma_state(ierr, filename, state)

INTEGER, INTENT(OUT) :: ierr ! completion code (0=OK)

CHARACTER\*256, INTENT(IN), OPTIONAL :: filename

! if specified: full file path

! if omitted: state_path/(default filename) used.

TYPE (plasma_state), OPTIONAL :: state

! if specified, state object to be WRITTEN

! if omitted: call refers to current state (ps)

SUBROUTINE ps_get_plasma_state(ierr, filename, state)

INTEGER, INTENT(OUT) :: ierr ! completion code (0=OK)

CHARACTER\*256, INTENT(IN), OPTIONAL :: filename

! if specified: full file path

! if omitted: state_path/(default filename) used.

TYPE (plasma_state), OPTIONAL :: state

! if specified, state object to be READ from file

! if omitted: call refers to current state (ps)

SUBROUTINE ps_commit_plasma_state(ierr, filename)

INTEGER, INTENT(OUT) :: ierr ! completion code (0=OK)

CHARACTER\*256, INTENT(IN), OPTIONAL :: filename

! if specified: full file path to WRITE

! if omitted: state_path/(default filename) used.

! current state copied to prior state: ps  psp

! psp is written (no optional state argument).

**Plasma State Data Input for PTRANSP Time Steps.**

The most crucial information that PTRANSP needs to find is the plasma
MHD equilibrium geometry, field, and plasma boundary location. If the
client code computes a free boundary tokamak equilibrium and is able to
generate an EFIT-style g-eqdsk file describing this equilibrium, then, a
plasma state dataset containing the equilibrium can be easily generated.

The first time this is done, the client code needs to decide on the
number of radial and poloidal grid points needed to adequately represent
the inverse representation of the equilibrium, which is used by the
PTRANSP heating and current drive source calculations. This resolution
can only be set once, and will be determined by considerations of the
resolution of the client code's equilibrium solver, possibly balanced
with the (fairly modest) resolution requirements of PTRANSP source
calculations. Plasma state data exchanges will be more efficient, if
overly fine grid resolutions are avoided. The following code, for
example, specifies a radial grid of 51 points and a poloidal angle grid
of 101 points:

use plasma_state_mod

integer :: ierr ! status code

... ...

! initialize equilibrium (inverse representation)

! grid sizes (first time only):

ps%nrho_eq = 51

ps%nth_eq = 101

Then, the following code actually updates the plasma state equilibrium
data from the g-eqdsk file:

! g-eqdsk file should be placed in the same directory

! as the plasma state file itself...

! R & Z grids, grid sizes, and Psi(R,Z) will be read...

ps%eqdsk_filename = \<EFIT g-eqdsk filename\>

call ps_update_equilibrium(ierr)

if(ierr.ne.0) \<handle error\> ! important to check \*\*\*

To explain the equilibrium data generated in the plasma state as a
result of this powerful call, it is necessary to introduce some
notation. Both PTRANSP and portions of the plasma state software use a
normalized radial coordinate defined in terms of the enclosed *toroidal*
flux of an axisymmetric tokamak equilibrium:

![](media/image3.wmf)

where ![](media/image4.wmf) designates toroidal magnetic flux.
Generally, the plasma state specification allows a separate
![](media/image5.wmf) grid for each major simulation "component". All
![](media/image6.wmf) grids span the range ![](media/image7.wmf)
precisely. The ![](media/image8.wmf) grid values need not be evenly
spaced, but for each grid a fixed grid *size* needs to be selected, and
the grid point *values* can only be set *once* at the start of the
simulation, and cannot subsequently be changed. (*Note D. McCune 16 Jan
2007: complexity of handling of time dependent quantities will be
considerably increased if these restriction are removed; it is not
impossible, but I recommend avoiding these complications at least for
the early phases of the SWIM SciDAC effort*).

Plasma state equilibrium representations contain a sizable number of
data items, grids and profiles of data and metric information,
summarized in the following table 5. This is a partial list; the
complete list can be found in swim_state_spec.dat:

  ------------------------ -------------- --------------------------------------------
  *Symbol*                 *Element name  *Description*
                           in Plasma      
                           State*         

  ![](media/image9.wmf)    rho_eq         Equilibrium![](media/image10.wmf)grid,
                                          nrho_eq grid points.

  ![](media/image11.wmf)   th_eq          Equilibrium ![](media/image12.wmf)grid,
                                          nth_eq grid points, equal arc definition,
                                          ![](media/image13.wmf) on outer half
                                          midplane.

  ![](media/image14.wmf)   R_grid         Major radius grid (![](media/image15.wmf));
                                          nR grid points from g-eqdsk.

  ![](media/image16.wmf)   Z_grid         Vertical coordinate grid
                                          (![](media/image17.wmf)); nZ grid points
                                          from g-eqdsk file.

  ![](media/image18.wmf)   PsiRZ          Poloidal flux function (bicubic spline,
                                          ![](media/image19.wmf));
                                          ![](media/image20.wmf); see
                                          ![](media/image21.wmf)for sign of poloidal
                                          field![](media/image22.wmf).

  ![](media/image23.wmf)   R_geo          R of flux surfaces (bicubic spline,
                                          ![](media/image24.wmf)).

  ![](media/image25.wmf)   Z_geo          Z of flux surfaces (bicubic spline,
                                          ![](media/image26.wmf)).

  ![](media/image27.wmf)   Psipol         Poloidal flux function (cubic spline,
                                          ![](media/image28.wmf)).

  ![](media/image29.wmf)   g_eq           Toroidal field function (cubic spline,
                                          ![](media/image30.wmf)); see
                                          ![](media/image31.wmf) for sign of
                                          ![](media/image32.wmf).

  ![](media/image33.wmf)   P_eq           Equilibrium scalar pressure, (cubic spline,
                                          *Pascals*).

  ![](media/image34.wmf)   q_eq           Rotational transform (cubic spline,
                                          *dimensionless*).

  ![](media/image35.wmf)   kccw_Bphi      Orientation\* of toroidal field (integer,
                                          +/- 1)

  ![](media/image36.wmf)   kccw_Jphi      Orientation\* of toroidal current (integer,
                                          +/- 1).

  ![](media/image37.wmf)   vol            Enclosed plasma volume (cubic spline,
                                          ![](media/image38.wmf)).

  ![](media/image39.wmf)   area           Enclosed plasma cross section area (cubic
                                          spline, ![](media/image40.wmf)).

  ![](media/image41.wmf)   surf           Surface area of plasma flux surface (cubic
                                          spline, ![](media/image42.wmf)).

  ![](media/image43.wmf)   Lpol           Poloidal path length (cubic spline,
                                          ![](media/image44.wmf)).

  ![](media/image45.wmf)   gr2            Differential volume flux surface average of
                                          ![](media/image46.wmf)(cubic spline,
                                          ![](media/image47.wmf)).

  ![](media/image48.wmf)   gr2i           Differential volume flux surface average of
                                          ![](media/image49.wmf)(cubic spline,
                                          ![](media/image50.wmf)).

  ![](media/image51.wmf)   B_axis         ![](media/image52.wmf) at magnetic axis of
                                          plasma (scalar, ![](media/image53.wmf).)

  ![](media/image54.wmf)   B_axis_vac     Vacuum field ![](media/image55.wmf) at
                                          magnetic axis (scalar,
                                          ![](media/image56.wmf).)

  ![](media/image57.wmf)   R_axis         Major radius of magnetic axis (scalar,
                                          ![](media/image58.wmf)).

  ![](media/image59.wmf)   Z_axis         Elevation of magnetic axis (scalar,
                                          ![](media/image60.wmf)).
  ------------------------ -------------- --------------------------------------------

**Table 5. MHD equilibrium data elements in the plasma state (partial
list). Elements are public members of the plasma state object, e.g.
ps%R_axis is the major radius of the magnetic axis. \*Interpretation of
orientation signs: +1 means "counter-clockwise viewed from above the
tokamak".**

*(Note -- D. McCune Jan. 19, 2007:* ps_update_equilibrium(ier) *is
suitable for mapping an evolving equilibrium into the state on an*
occasional *basis, using* ![](media/image61.wmf) *only, for
communication with codes external to the client. BUT: it will be too
slow to use to evolve the state equilibrium on a fine time scale, and
also, this code selects a boundary for the inverse equilibrium
representation that may not match exactly a corresponding boundary that
may already have been chosen in the client code. If it becomes necessary
to evolve the state equilibrium on a fine time scale, a method which
makes more direct use of the client code's own inverse equilibrium
representation will need to be invented. This may raise other issues, as
the* ps_update_equilibrium *boundary selection method is "tuned" to meet
requirements of source models used in PTRANSP, whereas the client code's
boundary selection method might not be).*

In addition to setting up the equilibrium data, the client code needs to
provide profiles giving the temperatures, densities, and flow velocities
of the thermal plasma species, the time step over which PTRANSP heating
sources are to be computed, and, certain scalar quantities such as
plasma surface voltage.

A separate ![](media/image62.wmf) grid needs to be specified for plasma
profiles. This can be the same as the equilibrium ![](media/image63.wmf)
grid, but it doesn't have to be. But as with the equilibrium grid, the
size of the grid and the grid point values can only be specified once at
the start of the simulation:

use plasma_state_mod

integer :: irho,ierr

ps%nrho = \<plasma grid size\>

! allocate plasma grid and profile arrays:

call ps_alloc_plasma_state(ierr)

if(ierr.ne.0) \<handle error\>

do irho = 1, ps%nrho

ps%rho(irho) = \<irho'th grid point value\>

end do

Any ![](media/image64.wmf) grid must be in strict ascending order and
the first grid value must be zero and the last grid value one exactly.
This requirement, and the requirement that grid values not change in
time, is enforced on each ps_store_plasma_state or
ps_update_plasma_state call.

In a plasma state with species lists, the call to ps_alloc_plasma_state,
after definition of the plasma ![](media/image65.wmf) grid size,
allocates the plasma parameter profile arrays ps%ns, ps%Ts, and
ps%v_pars, which will contain the evolving thermal plasma densities,
temperatures, and flux surface averaged parallel velocities,
respectively. All profile values are initialized to zero at allocation
time. Note that these are defined in the plasma state specification as
*step functions*, i.e. zone-oriented quantities, which means that the
profile arrays' radial grid dimensions are actually ps%nrho - 1, and
that e.g. ps%Ts(7,0) is the electron temperature in *zone* 7, spanning
ps%rho(7) to ps%rho(8).

The following table lists the profile data items to be set by the client
as *input* for the PTRANSP server:

  ------------------------ ----------------- -------------------------------------------
  *Symbol*                 *Element name in  *Description*
                           Plasma State*     

  ![](media/image66.wmf)   ps%ns(:,is)       Electron density and thermal ion density
                                             profiles, ![](media/image67.wmf).

  ![](media/image68.wmf)   ps%Ts(:,is)       Electron and thermal ion temperature
                                             profiles, *keV*.

  ![](media/image69.wmf)   ps%v_pars(1:is)   Flux surface averaged parallel ion
                                             velocities, ![](media/image70.wmf).

  ![](media/image71.wmf)   ps%Zeff_in(:)     ![](media/image72.wmf); *dimensionless*.
                                             The summation also covers fast specie
                                             densities, set by PTRANSP.

  ![](media/image73.wmf)   ps%prad(:)        Total radiated power, *Watts per zone.*

  ![](media/image74.wmf)   ps%prad_br(:),    (Optional) Bremsstrahlung, Cyclotron, and
                           ps%prad_cy(:),    Line Radiation contributions to radiated
                           ps%prad_li(:)     power, *Watts per zone*.
  ------------------------ ----------------- -------------------------------------------

**Table 6. Profile inputs to PTRANSP. The index is denotes species
index; is=0 for electrons.**

Some explanatory notes are appropriate here: (1) ![](media/image75.wmf)
is used by PTRANSP to renormalize the impurity density, preserving
quasineutrality while taking account fast ion specie densities. The
client code is not required to take thermal ion depletion due to
presence of fast ion species into account, although it would be
desirable for it to do so. (2) PTRANSP uses a single toroidal angular
velocity, assumed constant on flux surfaces, to approximate the plasma
flow. This is converted by PTRANSP from a density weighted average
![](media/image76.wmf) by the formula:

![](media/image77.wmf)

The profile ![](media/image78.wmf) and numerical flux surface average
![](media/image79.wmf) are available from the equilibrium component.

In addition to the above, there are several time dependent scalar inputs
expected by PTRANSP:

  ------------------------ ----------------- ---------------------------------------
  *Symbol*                 *Element name in  *Description*
                           Plasma State*     

  ![](media/image80.wmf)   ps%t0             Start of time step for PTRANSP sources,
                                             *sec.*

  ![](media/image81.wmf)   ps%t1             End of time step for PTRANSP sources,
                                             *sec*.

  ![](media/image82.wmf)   ps%vsur           Surface voltage (in toroidal
                                             direction), *Volts*.

  ![](media/image83.wmf)   ps%gasfl(is)      Time averaged plasma source due to gas
                                             puffing, for each ion species\*,
                                             *ions/sec*.

  ![](media/image84.wmf)   ps%recyc(is)      Time averaged plasma source due to
                                             recycling neutral gas, for each ion
                                             species\*, ions/sec.
  ------------------------ ----------------- ---------------------------------------

**Table 7. Scalar inputs to PTRANSP. The index is denotes species index;
is=1 for the first thermal ion specie. \*Integrated sources time
averaged since the prior call to PTRANSP; not required on first call;
not required for electrons nor impurities.**

All of the above scalar and profile quantities are provided to PTRANSP
via the plasma state. The quantities provided should all be associated
with time ps%t0; PTRANSP is going to compute the sources and evolution
of fast ion profiles for the time period ps%t0 to ps%t1. To do this,
PTRANSP will be advancing its plasma simulation from the time ps%t0 of a
*preceding* plasma state to the ps%t0 of the new state.

Finally, the client code must specify the powers and related quantities
for each neutral beam and each RF antenna, which are to be applied over
the time step ps%t0 to ps%t1. The PTRANSP server will compute heating,
fueling, and current drive sources based on these specifications:

+------------+-----------------+--------------------------------------+
| *Symbol*   | *Element name   | *Description*                        |
|            | in Plasma       |                                      |
|            | State*          |                                      |
+------------+-----------------+--------------------------------------+
| ![         | p               | Injected power on neutral beam       |
| ](media/im | s%power_nbi(ik) | \#*k*, *Watts*.                      |
| age85.wmf) |                 |                                      |
+------------+-----------------+--------------------------------------+
| ![         | p               | Lab frame full energy of injected    |
| ](media/im | s%kvolt_nbi(ik) | neutrals, *keV*.                     |
| age86.wmf) |                 |                                      |
|            |                 | Many neutral beams inject fractions  |
|            |                 | of neutrals at                       |
|            |                 | ![](media/image87.wmf) and           |
|            |                 | ![](media/image88.wmf)as well. These |
|            |                 | fractions are set in the PTRANSP     |
|            |                 | namelist template.                   |
+------------+-----------------+--------------------------------------+
| ![         | ps%power_ic(ik) | Power at ICRF antenna #k, *Watts*.   |
| ](media/im |                 |                                      |
| age89.wmf) |                 |                                      |
+------------+-----------------+--------------------------------------+
| ![         | ps%freq_ic(ik)  | Frequency at ICRF antenna #k, *MHz*. |
| ](media/im |                 |                                      |
| age90.wmf) |                 |                                      |
+------------+-----------------+--------------------------------------+
| ![         | ps%power_ec(ik) | Power at ECRF antenna #k, *Watts*.   |
| ](media/im |                 |                                      |
| age91.wmf) |                 |                                      |
+------------+-----------------+--------------------------------------+
| ![         | ps%freq_ec(ik)  | Frequency at ECRF antenna #k, *MHz*. |
| ](media/im |                 |                                      |
| age92.wmf) |                 |                                      |
+------------+-----------------+--------------------------------------+
| ![         | ps%power_lh(ik) | Power at Lower Hybrid antenna #k,    |
| ](media/im |                 | *Watts*.                             |
| age93.wmf) |                 |                                      |
+------------+-----------------+--------------------------------------+
| ![         | ps%freq_lh(ik)  | Frequency at Lower Hybrid antenna    |
| ](media/im |                 | #k, *MHz*.                           |
| age94.wmf) |                 |                                      |
+------------+-----------------+--------------------------------------+

**Table 8. Neutral beam and RF antenna powers, and related quantities
input to PTRANSP. The index (ik) refers to a specific neutral beam or RF
antenna as required.**

After setting the time step, the client code need only fill in the
appropriate plasma state array values as indicated in the tables shown
above, then call ps_store_plasma_state(ierr) to write the state file
cur_state.cdf. Then, the client code writes the file transp_init.dat
(first call) or transp_step.dat (subsequent calls) containing the
simulation time and state filename, in order to invoke a time step of
the PTRANSP server, as described in Part I above. When PTRANSP is
called, the plasma profiles and equilibrium and ![](media/image95.wmf)
should correspond to ps%t0. The gas flow and recycling sources should be
time averaged from the time of the preceding call to the time ps%t0 of
the current call. The beam and RF powers, voltages, and frequencies
apply for the upcoming time step ps%t0 to ps%t1.

**Plasma State Output Data Returned from PTRANSP Time Steps;
Interpolation (General Information).**

The PTRANSP server will compute heating, fueling, and current drive
source profiles that will apply throughout the time step ps%t0 to ps%t1,
and it will compute fast ion densities and information related to the
fast ion pressures that are to apply at time ps%t1. It is expected that
the sources will be treated by the client as step functions in time, and
that the density and pressure information will be linearly interpolated
in time, using data from current and prior plasma states, as illustrated
in figure 1:

![](media/image1.wmf)

**Figure 1. Basic time interpolation scheme for PTRANSP output
profiles.**

Codes that use plasma_state_mod can create a prior state object (psp)
from a completed current state object (ps) by executing call
ps_state_commit(ierr). This is to be done when the current step is
complete, i.e. everything being maintained in the state has been updated
to the time ps%t1. The call *copies* the current state ps to psp; the
current state structure ps is then ready to be used for the next time
step cycle. The time step variables in the current state are updated and
PTRANSP is called. After the call, profiles from both the current state
and the prior state can be referenced (i.e. interpolated). In the time
range ps%t0 (equal to psp%t1) to ps%t1, fast ion density can be linearly
interpolated between states, creating a strictly continuous 1^st^ order
time interpolation of these quantities, as would be needed to
continuously evolve thermal species densities (partially depleted w.r.t.
electron density by fast ions), and fast ion contributions to plasma
pressure as needed for input to the MHD equilibrium component.

The effects of sources, on the other hand, are time integrated in the
advance of fluid equations, and can therefore be treated simply as step
functions, to be taken from the current state (ps) after the PTRANSP
call, without the need for interpolation in time.

The radial flux coordinate (![](media/image2.wmf)) grid used by PTRANSP
sources will not be identical to the grid on which the plasma thermal
fluid equations are solved. Therefore, radial interpolation or rezoning
is needed. The sources are stored as binned step functions on a radial
grid that is likely to be coarse compared with the grid used by the
client code. (The client code can set nzones in the PTRANSP namelist to
control the resolution PTRANSP source profiles, but, for Monte Carlo
models, finer grids require more particles and therefore more
computational expense to control temporal noise in the simulation
output). If the data is interpolated or rezoned directly, the step
function structure of the source profiles will be manifested if the
target grid is finer than the source grid. If this is undesirable, a
smoothing option can be used during rezoning. The smoothing option
preserves total power (or other volume- or area-integrable source
quantity) while rearranging power density locally with a spatial effect
on integrated power guaranteed to be less (usually much less) than half
a zone width of the coarse grid of the original source calculation.

PTRANSP sources are binned and written into the state in "un-normalized"
units---*Watts*/zone for powers, (*ptcls/sec*)/zone for fueling sources,
(*Nt-m*)/zone for torques, and *Amps*/zone for driven currents. The
values on the PTRANSP grids are directly visible in the state object,
e.g. ps%pbi(j) is the beam heating to thermal ions, in Watts, in
PTRANSP's j'th radial zone. Interpolation or rezoning is readily done
with subroutine calls in the plasma state module, using the target
profile's interpolation *handle*: e.g. ps%id_pbi, in the case of the
beam ion heating profile. For sources, a rezoning call is usually the
best choice. By default, rezoning converts to "normalized" units, e.g.
![](media/image3.wmf), but this can be controlled by means of the
optional argument nonorm. Routines exist to rezone a single profile, a
"vector" of profiles, or a 2d array of profiles:

interface ps_rho_rezone

module procedure ps_rho_rezone1, &

ps_rho_rezone_arr1, ps_rho_rezone_arr2

end interface

! the name ps_rho_rezone can be used for all 3 routines

subroutine ps_rho_rezone1(rho, id, ansv, ierr, &

state, curdens, nonorm, zonesmoo, zonediff)

real\*8, dimension(:), intent(in) :: rho ! target grid\*

integer, intent(in) :: id ! profile handle (1 profile)

real\*8, dimension(:), intent(out) :: ansv ! the result

integer, intent(out) :: ierr ! exit status code (0=OK)

Type (plasma_state), OPTIONAL :: state ! source state

! for interpolation (default is ps, the current state)

logical, intent(in), OPTIONAL :: curdens ! T to apply

! area normalization for current density (default F)

logical, intent(in), OPTIONAL :: nonorm ! T to suppress

! density normalization (default F)

logical, intent(in), OPTIONAL :: zonesmoo ! T to invoke

! (1/2) zone width integral smoothing operator---may be

! desirable going from coarse to fine grids (default F)

real\*8, dimension(:), intent(out), OPTIONAL :: zonediff

! if present, the zone volumes (or areas if curdens=T)

! \*NOTE: size(rho) = size(ansv) + 1 = size(zonediff) + 1

! the input target rho grid gives zone boundaries;

! the data returned is oriented to zone centers.

! rho(:) MUST be monotonic increasing and MUST span

! span \[0:1\] precisely.

subroutine ps_rho_rezone_arr1(rho, id, ansv, ierr, &

state, curdens, nonorm, zonesmoo, zonediff)

...

integer, dimension(:), intent(in) :: id ! profile

! handle vector (vector of profiles)

real\*8, dimension(:,:), intent(out) :: ansa ! the result

! ansa(:,1) for id(1), ansa(:,2) for id(2), etc.

...

... (other arguments as above)

subroutine ps_rho_rezone_arr2(rho, id, ansv, ierr, &

state, curdens, nonorm, zonesmoo, zonediff)

...

integer, dimension(:,:), intent(in) :: id ! profile

! handle 2d array (2d array of profiles)

real\*8, dimension(:,:,:), intent(out) :: ansa ! the result

! ansa(:,1,1) for id(1,1), ansa(:,1,2) for id(1,2), etc.

...

... (other arguments as above)

The state object provides handle ids (and handle vectors and 2d handle
arrays) to enable easy rezoning not just of individual profiles but of
such vectors and arrays of profiles as are defined by the state.
However, most of the profiles being returned from PTRANSP are just
singletons. The rezoning calls have been described in terms of their use
for remapping step function profiles, but, they can in fact be applied
to any profile function of ![](media/image4.wmf) for which rezoning
based on conservation of a volume- or area-integral makes sense, whether
the profile is defined as a step function, piecewise linear function,
Hermite, or cubic spline.

The following section lists the specific profiles output by PTRANSP for
the client code.

**Catalog of PTRANSP Output Profiles.**

The following tables list the PTRANSP output profiles, grouped according
to type: electron heating, ion heating, current drive, torques, and
particle sources. These profiles cover sources due to neutral beams,
fusion products, and RF.

Then, the table of profiles on fast ion densities and average lab frame
energies is given.

Finally, for technical reasons, sources due to low energy edge fluxes of
neutral atoms require special handling and are considered separately at
the end of this section.

  ------------------------ ----------------------- ---------------------------------------
  *Symbol*                 *Interpolation Handle*  *Description -- all in Watts/zone*

  ![](media/image5.wmf)    ps%id_pbe               Electron heating by beam ions.

  ![](media/image6.wmf)    ps%id_pfuse             Electron heating by fusion product
                                                   ions.

  ![](media/image7.wmf)    ps%id_picrf_totals(0)   Direct electron heating by ICRF wave
                                                   field.

  ![](media/image8.wmf)    ps%id_pmine             Electron heating by ICRF minority ions.

  ![](media/image9.wmf)    ps%id_peech             Electron heating by ECRF wave field.

  ![](media/image10.wmf)   ps%id_pelh              Electron heating by Lower Hybrid wave
                                                   field.
  ------------------------ ----------------------- ---------------------------------------

**Table 9. Electron Heating Profiles.**

  ------------------------ ---------------- ----------------------------------------------
  *Symbol*                 *Interpolation   *Description -- all in Watts/zone*
                           Handle*          

  ![](media/image11.wmf)   ps%id_pbi        Thermal ion heating by beam ions.

  ![](media/image12.wmf)   ps%id_pfusi      Thermal ion heating by fusion product ions.

  ![](media/image13.wmf)   ps%id_picth      Direct heating of all thermal ions by ICRF
                                            wave field.

  ![](media/image14.wmf)   ps%id_pmini      Thermal ion heating by ICRF minority ions.

  ![](media/image15.wmf)   ps%id_pilh       Thermal ion heating by Lower Hybrid wave
                                            field.

  ![](media/image16.wmf)   ps%id_pbth       Heat carried in beam ion thermalization
                                            source.

  ![](media/image17.wmf)   ps%id_pfth       Heat carried in fusion product ion
                                            thermalization source.

  ![](media/image18.wmf)   ps%id_psc_halo   Heat sink/source due to beam neutral driven
                                            charge exchange neutralization of thermal
                                            ions, and recapture.

  ![](media/image19.wmf)   ps%id_pcx_halo   Heat loss due to beam driven charge exchange
                                            (not associated with a net ion source).
  ------------------------ ---------------- ----------------------------------------------

**Table 10. Ion heating profiles.**

  ---------- ---------------- ---------------------------------------------------
  *Symbol*   *Interpolation   *Description -- all in Nt-m/zone*
             Handle*          

                              (Torque profiles not yet defined in plasma state).
  ---------- ---------------- ---------------------------------------------------

**Table 11. Torques (toroidal angular momentum source profiles).**

  ------------------------ -------------------- -----------------------------------------
  *Symbol*                 *Interpolation       *Description -- all in (Ptcls/sec)/zone*
                           Handle*              

  ![](media/image20.wmf)   ps%id_scfuel(0)      Cold electron source due to neutral beam
                                                deposition.

  ![](media/image21.wmf)   ps%id_scfuel(1:ng)   Thermal ion sources due to thermalization
                                                of beam and fusion product ions; ng =
                                                number of non-impurity thermal ions.
  ------------------------ -------------------- -----------------------------------------

**Table 12. Fueling profiles (particle source profiles).**

  ------------------------ ---------------- -----------------------------------------------
  *Symbol*                 *Interpolation   *Description -- all in Amps/zone*
                           Handle*          

  ![](media/image22.wmf)   ps%id_curbeam    Beam ion driven current.

  ![](media/image23.wmf)   ps%id_curfusn    Fusion product ion driven current (small).

  ![](media/image24.wmf)   ps%id_curmino    RF minority ion driven current (currently zero,
                                            i.e. -- not calculated).

  ![](media/image25.wmf)   ps%id_curich     Current driven directly by ICRF wave field.

  ![](media/image26.wmf)   ps%id_curech     Current driven by ECRF wave field.

  ![](media/image27.wmf)   ps%id_curlh      Current driveh by Lower Hybrid wave field.
  ------------------------ ---------------- -----------------------------------------------

**Table 13. Current drive sources.**

The following profiles describe the parameters of the fast ions
themselves. As described in the preceding section, these are associated
with the time ps%t1 at the end of the source time step, and will need to
be linearly interpolated in time using data from the prior time state
state object. When the average energies are rezoned to the client code's
![](media/image28.wmf) grid, a density weighted averaging procedure is
applied.

  ------------------------ ---------------------------- -----------------------------------
  *Symbol*                 *Interpolation Handle*       *Description -- densities*
                                                        ![](media/image29.wmf)*; energies
                                                        keV.*

  ![](media/image30.wmf)   ps%id_n_nonMaxs(1:nf)        Fast ion densities: beam ions,
                                                        fusion ions, RF minority ions.

  ![](media/image31.wmf)   ps%id_eperp_nonMaxs(1:nf)    Perpendicular energy per ion,
                                                        averaged over the distribution (lab
                                                        frame).

  ![](media/image32.wmf)   ps%id_epll_nonMaxs(1:nf)     Parallel (to **B**) energy per ion,
                                                        averaged over the distribution (lab
                                                        frame).
  ------------------------ ---------------------------- -----------------------------------

**Table 14. Fast ion densities and average lab frame perpendicular and
parallel energies. The symbol nf represents the total number of
non-Maxwellian ion species.**

Another category of data provided by TRANSP relates to recycling or
injection of low energy neutral atoms across the plasma boundary, and
the charge exchange enhanced penetration of such neutrals into the
plasma. This data is prepared by a neutral gas model (The NTCC FRANTIC
module). Although this data is prepared on the same source time step as
the heating data from the beams, fusion products, and RF sources, the
treatment is modified. The reason is that (particularly in density
prediction applications) the client code may need to vary the neutral
flux on a timescale finer than that of the source time step. Therefore,
the sources are given as normalized to neutral fluxes---a separate set
of normalized sources for each (recycling) thermal plasma species.
Furthermore, for stability reasons between steps, charge exchange losses
are expressed in terms of a coupling to a neutral population with an
effective "charge exchange temperature" that is held constant through
each source time step. Table 15 shows the provided data. The symbol
![](media/image33.wmf) denotes the number of non-impurity recycling ion
species. Generally, cross-species charge exchange reactions imply that
if ![](media/image34.wmf) neutral sources are present, there are
![](media/image35.wmf) ion source/sink profiles. The symbol *th0\**
denotes the set of recycling neutral species; the symbol *th\** denotes
the species of ion sources driven from the edge neutral sources due to
charge exchange. Formulas for converting these edge neutral gas model
profiles into physical particle and energy sources are given below.

  ------------------------ ------------------------ -------------------------- ------------------------------
  *Symbol*                 *Count*                  *Interpolation Handle*     *Description*

  ![](media/image36.wmf)   ![](media/image37.wmf)   ps%id_qioniz(1:ig0)        Ionization source power per
                                                                               unit influx, *Watts/(n/sec)*.

  ![](media/image38.wmf)   ![](media/image39.wmf)   ps%id_t0cx(1:ig0)          Effective charge exchange
                                                                               neutral temperature, *keV*.

  ![](media/image40.wmf)   ![](media/image41.wmf)   ps%id_qqcx(1:ig0)          Charge exchange loss power per
                                                                               unit influx per unit
                                                                               temperature difference,
                                                                               *Watts/(n/sec)/keV.*

  ![](media/image42.wmf)   ![](media/image43.wmf)   ps%id_sflx0(0,1:ig0)       Electron source per unit
                                                                               influx, *(n/sec)/(n/sec)* or
                                                                               dimensionless.

  ![](media/image44.wmf)   ![](media/image45.wmf)   ps%id_sflx0(1:ig,1:ig0)    Ion source per unit influx,
                                                                               *(n/sec)/(n/sec)* or
                                                                               dimensionless.
  ------------------------ ------------------------ -------------------------- ------------------------------

**Table 15: Neutral gas model profiles from TRANSP. Index symbols ig0:
neutral species; ig: ion species.**

It should be noted that the neutral gas sources are defined in such a
way that each unit of neutral influx results in a full unit of ion
source. Charge exchange neutrals that escape across the plasma boundary
are "reflected" back into the plasma at low energy. This allows the
client code to define the magnitude of neutral influxes in a simple way
from global particle balance considerations. However, such procedures
may need to be modified when coupling to a realistic scrape off plasma
model.

To construct physical sources from the TRANSP neutral gas data, the
client code must specify the set of edge neutral fluxes
![](media/image46.wmf)for all species, in units of atoms/second. Then,
the following formulas can be used:

-   Electron source: ![](media/image47.wmf);

-   Ion sources {*th\**}: ![](media/image48.wmf);

-   Ionization power source: ![](media/image49.wmf);

-   Charge exchange power loss: ![](media/image50.wmf).

Although these profiles are normalized to unit neutral influxes, the
same rezoning procedures are available as are for other source profiles.
When the ![](media/image51.wmf)are rezoned, the rezoning average is
weighted using ![](media/image52.wmf).

Note that the charge exchange power also depends on the current ion
temperature![](media/image53.wmf); therefore, it may require implicit
treatment by the client predictive model. (*Note: dmc Jan 2007: data
exists for the momentum source carried by neutral ionization, and for
the momentum loss associated with charge exchange, but it has not yet
been placed in the Plasma State*).

D. McCune -- last update Jan 2007

Pending work: (1) inclusion of torque profiles in TRANSP output; (2)
definition and documentation of state file exchanges needed to
accommodate sawtooth events.