# Session and Top-Level Functionality

- tecplot

- Version Information

- Session

- Configuration

- Miscellaneous

## tecplot

`tecplot` is the top-level module for PyTecplot and it provides access to the entire public API.

In this example, the tecplot dynamic library is loaded at import time. The Tecplot Engine is started and the text ‘Hello, World!’ is added to the center of the active frame. All logging messages are piped to the console which may be useful to debug any script:

    import sys
    import logging

    import tecplot

    log = logging.getLogger()
    log.setLevel(logging.DEBUG)

    frame = tecplot.active_frame()
    frame.add_text('Hello, World!', position=(35,50), size=35)
    tecplot.export.save_png('hello_world.png')

### TecUtil Layer

The interface used to access the Tecplot Engine is called “TecUtil” and is the same as that used by addons. There are many checks in place for validating calls into this layer. The vast majority of these are recoverable and are seen in Python as a raised exception of type `TecplotLogicError`.

In principle, a user’s script should never trigger a `TecplotLogicError` as it indicates the requested operation is invalid in the current engine state or that the parameters passed into the TecUtil layer (indices for example) are not valid. Here is a (contrived) example of a typical exception one might see:

    import tecplot as tp
    from tecplot.tecutil import lock

    '''
    The following will print out something like:

        Assertion trap in function call from an Add-on:
        Assertion Type: Pre-condition
        Assertion: ArgListIsValid(ArgList)
        Tecplot version: 2018.3.0.92441
        Function: TecUtilStateChangedX
        Explanation: Argument list must be valid.
    '''
    try:
        with tp.tecutil.lock():
            tp.tecutil._tecutil.StateChangedX(None)
    except tp.exception.TecplotError as e:
        print(e)

Note that `None` is an invalid input value for the `StateChangedX()` TecUtil method.

### Tecplot Version Compatibility

It is always recommended to use the most recent version of PyTecplot. However, doing so may require an update to the underlying Tecplot 360 installation. Out-of-date installations of Tecplot 360 may be used but features may be missing and care must be taken not to use such features in the Python scripts. On top of this, there is a minimum version of the installed Tecplot 360 required by PyTecplot and the Python library will fail to load if this is not satisfied.

## Version Information

### tecplot.version

Version information of the tecplot Python module can be obtained as a `string` of the form “Major.Minor.Patch”:

    tecplot.__version__

or as a `namedtuple` with attributes: “major”, “minor”, “patch”, “build” in that order:

    tecplot.version_info

The underlying Tecplot 360 installation has its own version which can be obtained as a `str`:

    tecplot.sdk_version

or as a `namedtuple`:

    tecplot.sdk_version_info

PyTecplot adheres to the semantic versioning as outlined in SemVer 2.0.0 with regard to backwards compatibility between releases. For this purpose, the public interface of PyTecplot is defined as all entities (functions, properties etc.) presented in the HTML documentation and does not include methods in the code-base which do not show up in the HTML documentation, even when a docstring is present. In short, we will maintain backwards compatibility of the public interface between all minor releases of the same major version with the exception of internal changes that fix incorrect behavior or bugs.

## Session

- tecplot.session

- session.suspend()

- session.suspend_enter()

- session.suspend_exit()

- session.clear_suspend()

- session.connect()

- session.connected()

- session.disconnect()

- session.stop()

- session.acquire_license()

- session.release_license()

- session.start_roaming()

- session.stop_roaming()

- session.license_expiration()

- session.tecplot_install_directory()

- session.tecplot_examples_directory()

### tecplot.session

Tecplot Engine State and Tecplot 360 License Management

The `session` module contains methods used to manipulate the Tecplot Engine such as notification of a State Changes that was done such as adding or modifying data. It also contains methods for acquiring and releasing the Tecplot 360 License.

#### State Changes

State changes are the method for propagating information when an event occurs. A state change can be triggered by many events. Examples include: loading a data file, changing the color of a mesh plot, creating a new zone, or changing the plot type.

In general, state changes are already handled internally after each call to the PyTecplot API. This can cause a script that performs many operations, especially those that alter data, to run slowly since the Tecplot Engine must update it’s internal state every time a state change is received. To speed up such scripts, it may be necessary to use the `tecplot.session.suspend()` context. This will collect state changes for any operation performed and will emit the required state changes only upon exit of the context.

Using the `tecplot.session.suspend()` context in combination with Python’s “-OO” flag which removes many run-time checks in the PyTecplot API is the recommended way to run a PyTecplot script which requires faster execution time. The user should be aware that, when using the “-OO” flag, errors may not be recoverable by the Tecplot Engine.

### session.suspend()

`tecplot.session.``suspend`()

  Suspend the Tecplot engine and graphical interface.

  This context may speed up several types of operations including the creation of zones, filling or alterating the underlying data and the setup of complex styles. It will put Tecplot 360 into a “suspended” state such that the engine (in batch mode) or the graphical interface (in connected mode) will not try to keep up with the operations issued from Python. Upon exit of this context, the Tecplot 360 will be notified of any data alterations that have occured and the interface will be updated accordingly.

  See the State Changes section for more information about how the Tecplot 360 is updated when style or data is changed from a PyTecplot script.

  Example usage where `data` is some user-provided data – see the examples under `pytecplot/examples/working_with_datasets` folder within the Teplot 360 installation for more information.:

      fr = tp.active_frame()
      with tp.session.suspend():
          ds = fr.create_dataset('Data', ['x', 'y', 'z'])
          zn = ds.add_ordered_zone('Zone', (10, 10, 10))
          zn.values('x')[:] = data[0]
          zn.values('y')[:] = data[1]
          zn.values('z')[:] = data[2]
      fr.plot_type = tp.constant.PlotType.Cartesian3D

  New in version 2018.2: The suspend context, when used in connected mode, requires Tecplot 360 2018 R2 or later to realize the full performance benefits though this will still provide some performance improvements with older versions of Tecplot 360.

### session.suspend_enter()

`tecplot.session.``suspend_enter`()

  Free-function equivalent to entering the `suspend` context.

  This is an example of calling a previously defined function `do_work()` within a suspend context, using `try/finally` to ensure the context is properly cleared:

      >>> try:
      >>>     tp.session.suspend_enter()
      >>>     do_work()
      >>> finally:
      >>>     tp.session.suspend_exit()

### session.suspend_exit()

`tecplot.session.``suspend_exit`()

  Free-function equivalent to exiting the `suspend` context.

  This must only be used following a call to `tecplot.session.suspend_enter()` and cannot be used within a `tecplot.session.suspend()` context block.

### session.clear_suspend()

`tecplot.session.``clear_suspend`()

  Break out of suspended mode when connected to Tecplot 360.

  Forcibly clears the suspend state of the Tecplot 360 interface. This will cause the TecUtil Server to break out of a suspended state which may have been the result of a script not properly exiting from a `suspend()` context, possibly due to a segmentation fault. Example usage:

      tecplot.session.connect()
      tecplot.session.clear_suspend()

### session.connect()

`tecplot.session.``connect`(host='localhost', port=7600, timeout=10, quiet=False)

  Connect this PyTecplot to a running instance of Tecplot 360.

  Parameters

    - host (`str`, optional) – The host name or IP address of the machine running Tecplot 360 with the TecUtil Server addon loaded and listening. (default: localhost)

    - port (`int`, optional) – The port used by the running Tecplot 360 instance. (default: 7600)

    - timeout (`int`, optional) – Number of seconds to wait before giving up. (default: 10)

    - quiet (`bool`, optional) – Suppress status messages sent to the console. Exception messages will still be presented on errors. (default: `False`)

  This will connect the running python script to Tecplot 360, sending requests over the network. The TecUtil Server addon must be loaded and the server must be accepting requests. To turn on the server in Tecplot 360, go to the main menu, click on “Scripting -> PyTecplot Connections…”, and finally check the option to “Accept connections.” Make sure the same port is used in both Tecplot 360 and the python script. For more information, see Requirements for Connecting to Tecplot 360 GUI Example usage:

      >>> tecplot.session.connect(port=7600)
      Connecting to Tecplot 360 TecUtil Server on:
          tcp://localhost:7600
      Connection established.

  To activate the TecUtil Server addon in Tecplot 360 on start-up, first create a macro file, named something like: startTecUtilServer.mcr, with the following content:

      #!MC 1410
      $!EXTENDEDCOMMAND
          COMMANDPROCESSORID = "TecUtilServer"
          COMMAND = R"(
              AcceptRequests = Yes
              ListenOnAddress = localhost
              ListenOnPort = 7600
          )"

  Then run Tecplot 360 from a command console with this file as one of the arguments:

      > tec360 startTecUtilServer.mcr

  Warning

  Adding the macro command above may cause a port binding conflict when using multiple instances of Tecplot 360. A single port can only be bound to one instance of the TecUtil Server. You may still add this to the `tecplot.add` file which will be run everytime, but it must only be activated when Tecplot 360 is running interactively, i.e. not in batch mode. To do this, check the value of `|INBATCHMODE|`:

      $!IF |INBATCHMODE| == 0
          $!EXTENDEDCOMMAND
              COMMANDPROCESSORID = "TecUtilServer"
              COMMAND = R"(
                  AcceptRequests = Yes
                  ListenOnAddress = localhost
                  ListenOnPort = 7600
              )"
      $!ENDIF

  New in version 2017.3: PyTecplot connections requires Tecplot 360 2017 R3 or later.

### session.connected()

`tecplot.session.``connected`(timeout=5)

  Check if PyTecplot is connected to a running instance of Tecplot 360.

  This method sends a handshake message to the TecUtil Server and waits for a successful reply, timing out in the number of seconds specified.

  Parameters

    timeout (`int`, optional) – Number of seconds to wait before giving up. (default: 5)

  New in version 2017.3: of Tecplot 360 PyTecplot connections requires Tecplot 360 2017 R3 or later.

### session.disconnect()

`tecplot.session.``disconnect`(quit=False)

  Disconnect from a running instance of Tecplot 360.

  Parameters

    quit (`bool`, optional) – Attempt to quit and close the instance of Tecplot 360 before disconnecting.

  New in version 2017.3: PyTecplot connections requires Tecplot 360 2017 R3 or later.

### session.stop()

`tecplot.session.``stop`()

  Releases the Tecplot 360 License and shuts down Tecplot Engine.

  This shuts down the Tecplot Engine and releases the Tecplot 360 License. Call this function when your script is finished using PyTecplot. Calling this function is not required. If you do not call this function, it will be called automatically when your script exists. However, the Tecplot 360 License will not be released until you call this function.

  This method is silently ignored when connected to a running instance of Tecplot 360 (see `tecplot.session.connect()`).

  Note that stop() may only be called once during the life of a Python session. If it has already been called, subsequent calls do nothing:

      >>> # Shutdown tecplot and release license
      >>> tecplot.session.stop()

  See also: `tecplot.session.acquire_license()`, `tecplot.session.release_license()`.

### session.acquire_license()

`tecplot.session.``acquire_license`()

  Attempts to acquire the Tecplot 360 License

  Call this function to attempt to acquire a Tecplot 360 License. If Tecplot Engine is not started, this function will start the Tecplot Engine before attempting to acquire a license.

  This function can be used to re-acquire a license that was released with `tecplot.session.release_license`.

  If the Tecplot Engine is currently running, and a Tecplot 360 License has already been acquired, this function has no effect.

  Licenses may be acquired and released any number of times during the same Python session.

  Raises `TecplotLicenseError` if a valid license could not be acquired.

  Note

  Warning emitted when close to expiration date.

  A warning is emitted using Python’s built-in `warnings` module if you are within 30 days of your TecPLUS subscription expiration date. The message will look like this:

      $ python
      >>> import tecplot
      >>> tecplot.session.acquire_license()
      /path/to/tecutil_connector.py:458: UserWarning:
      Your Tecplot software maintenance subscription
      (TecPLUS) will expire in **13 days**, after which you
      will no longer be able to use PyTecplot. Contact
      sales@tecplot.com to renew your TecPLUS subscription.

        warn(warning_msg)

  These warnings can be suppressed by using the `-W ignore` option when invoking the python interpreter:

      $ python -W ignore
      >>> import tecplot
      >>> tecplot.session.acquire_license()

  See also: `tecplot.session.release_license()`

  Example:

      >>> import tecplot
      >>> # Do useful things
      >>> tecplot.session.release_license()
      >>> # Do time-consuming things not related to |PyTecplot|
      >>> tecplot.session.acquire_license()  # re-acquire the license
      >>> # Do useful |PyTecplot| related things.

### session.release_license()

`tecplot.session.``release_license`()

  Attempts to release the Tecplot 360 License

  Call this to release a Tecplot 360 License. Normally you do not need to call this function since `tecplot.session.stop()` will call it for you when your script exists and the Python interpreter is unloaded.

  This function can be used to release a license so that the license is available to other instances of Tecplot 360.

  If the Tecplot 360 License has already been released, this function has no effect.

  Licenses may be acquired and released any number of times during the same Python session. This method is silently ignored when connected to a running instance of Tecplot 360 (see `tecplot.session.connect()`).

  See also: `tecplot.session.acquire_license()`

  Example usage:

      >>> import tecplot
      >>> # Do useful things
      >>> tecplot.session.release_license()
      >>> # Do time-consuming things not related to |PyTecplot|
      >>> tecplot.session.acquire_license()  # re-acquire the license
      >>> # Do useful |PyTecplot| related things.

### session.start_roaming()

`tecplot.session.``start_roaming`(days)

  Check out a roaming license.

  Parameters

    days (`int`) – Number of days to roam.

  This will acquire a PyTecplot license and then attempt to set it up for roaming. The maximum number of days one may roam is typically 90. This function can be called in an interactive terminal and will affect all subsequent uses of PyTecplot on the local machine. Do not forget to `release` the roaming license to the server if you are finished roaming before the expiration date.

  See also: `tecplot.session.stop_roaming()`

  Example usage where `YYYY-MM-DD` will be the date 10 days from when this code was executed:

      >>> tecplot.session.start_roaming(10)
      You have successfully checked out a roaming license of
      PyTecplot. This will be valid for 10 days until
      midnight of YYY-MM-DD.
      >>> tecplot.session.stop_roaming()
      Your PyTecplot roaming license has been checked in.

### session.stop_roaming()

`tecplot.session.``stop_roaming`(force=False)

  Check in (release) a roaming license.

  This will check in and make available to others on the network a license that you previously checked out for roaming.

  See also: `tecplot.session.start_roaming()`

  Example usage:

      >>> tecplot.session.stop_roaming()
      Your PyTecplot roaming license has been checked in.

### session.license_expiration()

`tecplot.session.``license_expiration`()

  Expiration date of the current license.

  Returns: `datetime.date`

  Example usage:

      >>> print(tecplot.session.license_expiration())
      1955-11-05

### session.tecplot_install_directory()

`tecplot.session.``tecplot_install_directory`()

  Tecplot 360 installation directory.

  Top-level installation directory for Tecplot 360. This will typically contain configuration files and the examples directory.

  This directory is platform-dependent and will contain configuration files and the examples directory:

      import os
      import tecplot

      install_dir = tecplot.session.tecplot_install_directory()
      infile = os.path.join(install_dir, 'examples', 'SimpleData', 'SpaceShip.lpk')

      tecplot.load_layout(infile)
      tecplot.export.save_png('spaceship.png', 600, supersample=3)

### session.tecplot_examples_directory()

`tecplot.session.``tecplot_examples_directory`()

  Tecplot 360 examples directory.

  Examples directory that is typically installed with Tecplot 360. This may be overridden with the TECPLOT_EXAMPLES environment variable.

  This directory is platform-dependent and by default contains the various examples shipped with Tecplot 360:

      import os
      import tecplot

      examples_dir = tecplot.session.tecplot_examples_directory()
      infile = os.path.join(examples_dir, 'SimpleData', 'F18.lay')

      tecplot.load_layout(infile)
      tecplot.export.save_png('load_example.png', 600, supersample=3)

## Configuration

`tecplot.session.``configuration`()

  Run-time configuration parameters can be accessed and changed through the configuration instance returned by `tecplot.session.configuration()`:

      >>> conf = tecplot.session.configuration()
      >>> print(conf.latex.command)
      pdflatex -interaction=batchmode -output-directory=@OUTDIR @INFILE
      >>> conf.latex.preamble = '\usepackage{amsmath}'

The default settings have been tested with MiKTeX and TeXLive engines and should work without the need for any changes to the session configuration. However, you may wish to change the LaTeX packages which are loaded by default or use a different LaTeX engine. See the Tecplot user manual for guidance in changing your LaTeX configuration file so changes persist across sessions.

Available configuration parameters:

- `latex.command`

- `latex.dvipng_command`

- `latex.preamble`

### `latex.command`

The system command used to compile LaTeX text objects. Parameters `@OUTDIR` and `@INFILE` are replaced with appropriate strings to coordinate the creation of the final rendered text.

Type:

  `str`

Default:

  “latex -interaction=batchmode -output-directory=@OUTDIR @INFILE”

### `latex.dvipng_command`

The system command used to convert the output from the LaTeX command from DVI to PNG. The parameters `@DPI`, `@PAGERANGE`, `@OUTFILE` and `@INFILE` are replaced with appropriate strings to coordinate the creation fo the final rendered text.

Type:

  `str`

Default:

  “dvipng -bg Transparent -D @DPI -pp @PAGERANGE -T tight -o @OUTFILE @INFILE”

### `latex.preamble`

Code that will be placed before the `\begin{document}` section of the LaTeX source to be compiled. This primarily used for loading LaTeX packages.

Type:

  `str`

Default:

  “\usepackage{amsfonts}\usepackage{amsmath}\usepackage{amssymb}\usepackage{amsthm}”

## Miscellaneous

class `tecplot.tecutil.``Index`

  Position identifier type.

  This type is used internally to represent a position in a list. It is used to indicate that a change between zero-based indexing and one-based indexing must occur at the TecUtil boundary.

  This type can be treated exactly like a Python native `int` and is only meaningful internally to the tecplot Python module.

class `tecplot.session.``IndexRange`(parent, *svargs)

  Index range specification along some axis.

  This is similar to Python’s `slice` object except that `max` is included in the evaluated indexes. Here are some things to note:

  > - All indices start with 0 and go to some maximum index `m`.

  > - Negative values represent the indexes starting with the maximum at -1 and continuing back to the beginning of the range.

  > - A step of `None`, 0 and 1 are all equivalent and mean that no elements are skipped.

  > - A negative step indicates a skip less than the maximum.

  Changed in version 1.1: (Bug fix) `IndexRange` max value of zero is now interpreted as the first index in the range instead of the last index. Prior to version 1.1, the `max` parameter interpreted zero to be the end of the range instead of the first element. This meant that an `IndexRange` of `(0, 0, 1)` would represent the whole range instead of just the first item. The standard way to represent the entire index