smtk documentation · (e.g., attribute, model, and mesh resources) into an input deck for a...

83
SMTK Documentation Release 3.3.0 Kitware, Inc. Sep 04, 2020

Upload: others

Post on 18-Jul-2020

15 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK DocumentationRelease 3.3.0

Kitware, Inc.

Sep 04, 2020

Page 2: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user
Page 3: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

CONTENTS

1 SMTK User’s Guide 31.1 Obtaining, Building, and Installing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 An Overview of SMTK’s Subsytems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.3 SMTK’s Resource System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

1.3.1 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.4 SMTK’s Geometry System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

1.4.1 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.4.1.1 Writing a geometry object for a resource . . . . . . . . . . . . . . . . . . . . . . . 61.4.1.2 Consuming geometry from a resource . . . . . . . . . . . . . . . . . . . . . . . . 81.4.1.3 Geometric queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

1.5 SMTK’s Attribute Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.5.1 General Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

1.5.1.1 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81.5.1.2 Interfaces to the attribute resource . . . . . . . . . . . . . . . . . . . . . . . . . . . 91.5.1.3 Example Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.5.1.4 Template File Syntax (Reference) . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

1.6 SMTK’s Operation System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221.6.1 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

1.6.1.1 Inputs and Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221.6.1.2 Registration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

1.7 SMTK’s Geometric Model Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231.7.1 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231.7.2 Model Entities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

1.7.2.1 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231.7.2.2 Organizing Principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

1.7.3 Filtering and Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241.7.4 Sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

1.7.4.1 Registration and initialization of Sessions and Operators . . . . . . . . . . . . . . . 261.7.5 Model Property System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

1.7.5.1 Reserved model properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271.7.5.2 Model properties of sessions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

1.7.6 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291.7.6.1 Inputs and Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291.7.6.2 Registration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

1.7.7 Presenting models in a user interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311.7.8 Session: Discrete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321.7.9 Session: Exodus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321.7.10 Session: Polygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

1.7.10.1 Meshing Boost.polygon models . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331.8 SMTK’s Graph-based Model Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

i

Page 4: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

1.8.1 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331.8.2 Nodes and Arcs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

1.8.2.1 Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341.8.2.2 Arcs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

1.8.3 Filtering and Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341.9 SMTK’s Mesh Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

1.9.1 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341.9.2 IO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

1.9.2.1 Serialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361.10 SMTK’s Simulation System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381.11 SMTK’s View System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

1.11.1 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381.11.2 Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

1.11.2.1 Attribute views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391.11.2.2 Phrase views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

1.11.3 Hierarchical Phrases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401.11.3.1 Phrase Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401.11.3.2 Phrase Content Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401.11.3.3 Subphrase Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411.11.3.4 Badges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

1.12 SMTK’s Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411.12.1 Qt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411.12.2 Visualization Tool Kit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411.12.3 ParaView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

1.12.3.1 Anatomy of ParaView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411.12.3.2 Integration with SMTK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421.12.3.3 Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421.12.3.4 Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431.12.3.5 Representations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431.12.3.6 Integrating ParaView and SMTK Selection . . . . . . . . . . . . . . . . . . . . . . 431.12.3.7 Panels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451.12.3.8 Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

1.13 SMTK’s Workflow System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481.13.1 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

1.14 SMTK’s Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491.14.1 Generating pybind11 bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491.14.2 Customizing pybind11 bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

1.15 SMTK’s Plugin System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501.15.1 Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

1.16 Administering SMTK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501.16.1 End-user tool installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511.16.2 Developer installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511.16.3 Configuration as a modeling and meshing server . . . . . . . . . . . . . . . . . . . . . . . . 51

1.16.3.1 Worker file search paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511.16.3.2 Creating a Remus worker file for solid modeling . . . . . . . . . . . . . . . . . . . 52

1.17 Contributing to SMTK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521.17.1 Source code organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531.17.2 Extending SMTK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531.17.3 Exposing SMTK for use in external projects . . . . . . . . . . . . . . . . . . . . . . . . . . 541.17.4 Code style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541.17.5 Documentation style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541.17.6 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

1.17.6.1 Unit tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561.17.6.2 Build-failure tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

ii

Page 5: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

1.17.6.3 Contract tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571.17.7 To-do list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

2 Tutorials 632.1 First steps in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

2.1.1 Including SMTK headers and calling methods . . . . . . . . . . . . . . . . . . . . . . . . . 632.1.2 Compiling the example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

2.2 First steps in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642.2.1 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642.2.2 Problem Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652.2.3 Simulation Preparation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

2.3 Bridge a new modeling kernel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672.3.1 Adding Entity UUIDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

2.3.1.1 Adding UUIDs by either technique . . . . . . . . . . . . . . . . . . . . . . . . . . 692.3.1.2 Adding UUIDs as attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702.3.1.3 Adding UUIDs as sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712.3.1.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

2.3.2 Creating a session subclass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712.3.3 Transcribing model entities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 722.3.4 Providing operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

2.4 Implementing an STMK operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 722.4.1 Subclassing smtk::model::Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732.4.2 Defining operator input parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742.4.3 Defining operator output parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742.4.4 Implementing the actual operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75

3 Indices and tables 77

iii

Page 6: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

iv

Page 7: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Version: 3.3.0

Contents:

CONTENTS 1

Page 8: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

2 CONTENTS

Page 9: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

CHAPTER

ONE

SMTK USER’S GUIDE

The Simulation Modeling Tool Kit, or SMTK, is a framework to help you (1) describe a model in enough detail that itcan be passed to a solver and (2) create input files for a variety of solvers in different simulation packages using yourdescription.

This process can involve any or all of the following:

• importing a geometric model of the simulation domain or the domain’s boundary;

• assigning sizing functions to specify mesh element size for analysis;

• submitting portions of the simulation domain to be meshed for analysis;

• assigning material properties to regions of the simulation domain;

• assigning boundary conditions to portions of the simulation domain’s boundary;

• assigning initial conditions to portions of the simulation domain or its boundary; and

• assigning global simulation properties such as convergence criteria.

SMTK provides an attribute resource that can represent arbitrarily structured data and a template system that can betailored to describe almost any simulation’s expected inputs without allowing spurious or invalid input specifications.Thus, in addition to the process above, SMTK provides a way for simulation packages to expose settings to domainexperts that makes preparing valid inputs simple.

SMTK also provides a uniform interface to several different solid modeling kernels for preparing discretizations ofyour simulation domain.

1.1 Obtaining, Building, and Installing

For instructions on obtaining, building, and installing SMTK, clone the repository:

git clone https://gitlab.kitware.com/cmb/smtk.git

and follow the instructions in the doc/dev/build.md file in the source code. Other files in that directory describeour development process and are relevant if you intend to contribute source code to SMTK. The rest of this user’sguide assumes you have built and installed SMTK according to these instructions.

In addition to cloning anonymously as mentioned above, you are also welcome to create an account on either git-lab.kitware.com or github.com and fork the repository. Forking the repository will allow you to submit contributionsback to SMTK for inclusion in later releases. See Contributing to SMTK for more on how to prepare and submitchanges to SMTK.

3

Page 10: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.2 An Overview of SMTK’s Subsytems

SMTK’s core library contains several subsystems, each of which is covered in depth in sections that follow this one.These subsystems are:

• The resource system holds a set of base classes used by the systems below to provide basic provenance informa-tion about versions of data on disk. Each file is a resource, which may hold a resource of resource components;the resource manager assembles resources together for processing into a simulation input.

• The attribute resource, which provides a way to specify how information should be organized for scientific andengineering workflows, accept that information from users, and ensure that it is consistent with the specification.

• The model resource, which provides geometric modeling and allows you to tie information from the attributeresource to geometric entities (e.g., assign boundary conditions in the attribute resource to particular boundarieson a CAD model).

• The mesh resource, which can manipulate meshes of geometric models; it provides a way to propagate simula-tion attribute information from model entities onto meshes. It also provides a way to run external mesh creationtools on the model.

• The operation system, which provides an interface to constructing and executing operators, which create,modify and delete resources.

• The simulation (also known as the export) system, which is a set of utilities that lets you convert resources(e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ ifyou wish).

• The view system provides user interface functionality that is independent of any particular operating system orplatform. It serves as a layer between the resource system and the visual layout of resources so that multipleviews of the same resources can exist in the same application.

• A common system holding utility classes.

• Python bindings that enable SMTK to be used by python scripts and SMTK to run python scripts as part of itsnormal operations.

• A set of extension libraries, which provide additional functionality but also introduce dependencies on softwarebeyond what the core smtk library already requires. These are used to create applications built on SMTK.

1.3 SMTK’s Resource System

Unlike the major subsystems that follow, the resource system does not store information directly relevant to simulationsitself; rather, it provides base classes holding metadata for each of the other systems so that the provenance of all theinputs to a simulation can be tracked.

1.3.1 Key Concepts

There are two base classes holding provenance metadata:

Resource instances correspond to files and thus have a URL. Each resource also has a UUID and a type. Resourcesmay also provide access to a resource of components (see below) present in the file, indexed by UUID.

Component instances are meaningful subsets of data present in a resource. An attribute resource presents its attributesas resource components. Similarly, geometric model entities (vertices, edges, faces, etc.) are components in themodel subsystem. Each component has a UUID and holds a weak reference to the resource which owns it.

In addition to these useful base classes,

4 Chapter 1. SMTK User’s Guide

Page 11: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Manager instances hold a resource of resources. How the resources are related to each other is determined by yourapplication, but a common use is holding all of the resources related to a simulation.

Links Resource links connect persistent objects via a unidirectional relationship that exists for a specific purpose,or role. Links are stored separately from the objects they connect, but each resource instance owns the linkthat holds all outgoing connections from the resource and its components. The smtk::resource::Link class isan abstract API provided on both resources and components; on the resource, the link subclass provides actualstorage, while on components, the subclass asks its parent resource for the links object in order to search forconnections. Roles are simply integers. Roles less than zero are reserved for internal SMTK use while positiveroles are available for user-specified (i.e., application-specific) roles.

Properties Resources and components contain a dictionary-like data structure that can hold any copyable type. If theproperty type has JSON bindings, it will be serialized to file along with the resource; otherwise, the propertycan still be stored, but will not be persistent. Currently enabled types include long, double, std::string, andstd::vectors of these three types.

Properties are stored separately from the objects they annotate, but each resource instance owns the propertiesinstance that holds all properties for the resource and its components. The smtk::resource::Properties class isan abstract API provided on both resources and components; on the resource, the properties subclass providesactual storage, while on components, the subclass asks its parent resource for the properties object to search forvalues.

Queries Resources hold a container of relevant Query objects. Queries prevent the resource or component classesfrom growing large APIs and internal state by splitting methods that perform queries — such as identifying thespatial bounds of a mesh or model object, finding the closest point on a mesh or model component to somelocation in space, etc. — into separate classes that are easy to create and invoke.

Furthermore, query objects can inherit their API from other queries, so it is possible to provide a uniform APIwith different implementations for each resource type.

Queries may also need to store state in order to be performed efficiently. A good example is closest-pointsearches; usually many queries of this type are performed in a batch and a point locator structure is built toaccelerate the query. The cache should outlive the query object, which is usually constructed on the fly by analgorithm, but also be marked dirty when the resource’s components are modified. The Queries object ownedby each resource provides a container for cache objects that individual Query objects may use. Multiple queryclasses can share the same cache object (e.g., ClosestPoint and ClosestCell might both use a PointLocator cacheobject).

1.4 SMTK’s Geometry System

The geometry system provides an extended Resource class that responds to queries for geometric data. It also providesa set of abstract classes that additional libraries can use to provide access to geometric data in multiple formats.

1.4.1 Key Concepts

A major role of model and mesh resources is visualization and interactive manipulation of a simulation’s domain. Ad-ditionally, some SMTK sessions may wish to perform analytical modeling tasks that require access to geometric data,such as approximating integrals over subsets of the simulation domain. These tasks require a geometric descriptionof resources and components. While SMTK’s core library does not provide direct support for geometry — since thatwould introduce unwanted dependencies for many use cases — it does include support (if plugins providing geometryare loaded) for querying what components and resources have geometric data and for querying the bounds of anyrelated geometry.

Furthermore, it is possible for a resource to provide support for multiple backends that represent geometry differently(e.g., VTK, VTK-m, vtk-js, Unity, Vulkan, PDF). It is even possible that multiple backends might be used simulta-

1.4. SMTK’s Geometry System 5

Page 12: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

neously; for example, an application might provide interaction using VTK but use a different backend like vtk-js topublish content to a cloud service.

Another constraint on geometry providers is the need for caching of geometry in order to efficiently respond to repeatedqueries for bounding boxes, picking, etc. Many times, these operations require expensive tessellation operations andthe result should be cached for re-use. Thus the interface that provides geometry should allow for a significant amountof state to be held; expecting each query for a bounding box to construct a new instance of some geometry providerwould complicate efficient caching for repeated queries.

Therefore, SMTK provides:

smtk::geometry::Backend which is a mostly-empty class to be inherited by actual rendering backends. It is used asa key so that each resource can own multiple geometry provider objects as needed, while providing type-safe ac-cess to specific subclasses needed by different renderers. Currently, only smtk::extension::vtk::source::Backendinherits it.

smtk::geometry::Geometry which is a base class for objects that can respond to geometric queries. This class doesnot provide methods that return any actual geometric data; subclasses must implement methods for queryingthe existence of renderable geometry and its bounds for all the persistent objects owned by the parent resourceof the geometry object. Thus, metadata such as existence and bounds are available to libraries linked only toSMTK’s core library.

smtk::geometry::GeometryForBackend which all concrete implementations should inherit since it can respond togeometric queries in a specific format (its template parameter). Backends will use the pure virtual data() methodit declares to return geometry in a format specific to the backend.

smtk::geometry::Cache which is a convenience class for writing Geometry subclasses that will maintain a cache ofgeometric data for each object. Concrete implementations of of GeometryForBackend<Format> may choose toinherit this class, which implements several virtual methods declared in Geometry and defines new methods youmust implement in order to populate the cache.

smtk::geometry::Generator is a subclass of smtk::common::Generator used to register and create instances of Ge-ometry subclasses on demand. Note that generators return unique pointers (i.e., std::unique_ptr<Geometry>)so that large caches are not duplicated or multiply-owned. This class is used internally bysmtk::geometry::Resource

1.4.1.1 Writing a geometry object for a resource

When you create a new resource type with renderable geometry, you must (1) create new geometry class(es) thatsubclass GeometryForBackend<Format> (one for each Backend you wish to support), and (2) register the geome-try class(es) so they will be created when needed. We’ll cover the latter task (registration) now and come back tosubclassing a geometry provider afterward.

Each geometric Resource contains a map from geometry backend IDs to Geometry instances. When asked for ge-ometry that it does not already have an instance for, the resource uses a Generator to query the application for one.There is no guarantee that geometry will exist; this may be because a particular backend is not supported or becausethe application has not been linked with a library that supports the backend.

For example, consider a lightweight, 2-D model resource that is used extensively by python scripts to do batch pro-cessing. You would probably not want the python module that registers this model resource to link to VTK since thatcould increase script runtimes adversely and the scripts do not need to provide renderings of your model. However,you probably want the modelbuilder application to be able to render components of your model. For this reason, youshould put the VTK-based geometry in a separate library from the resource’s core implementation. The library withVTK dependencies can then expose a geometry object by implementing

class RegisterResourceFooBackendBar: public smtk::geometry::Supplier<

(continues on next page)

6 Chapter 1. SMTK User’s Guide

Page 13: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Fig. 1: This figure shows how rendering code is split across 3 libraries (left: the core, which defines a basic interfacewith no external dependencies), a rendering extension (right: a plugin used by the application to allow geometryinteraction), and a session (center: a plugin loaded by the application to provide a new type of model, mesh, orattribute resource that has geometric components).

(continued from previous page)

RegisterResourceFooBackendBar>{public:

bool valid(const geometry::Specification& in) const override{// Only create providers for the "bar" backend:smtk::bar::Backend backend;return std::get<1>(in).index() == backend.index();

}

smtk::geometry::GeometryPtr operator()(const geometry::Specification& in) override

{// Only create providers for "foo" resources:auto rsrc = std::dynamic_pointer_cast<

smtk::foo::Resource>(std::get<0>(in));if (rsrc){

auto geom = new foo::BarGeometry(rsrc);return smtk::geometry::GeometryPtr(geom);

}return nullptr;

}};

Whenever an application needs to render a resource, it asks the resource for a geometry object compatible with agiven backend (such as VTK). If none already exists, a geometry::Generator is used to iterate over registered geome-try::Supplier instances like the one above until a match is found or the registered list is exhausted.

1.4. SMTK’s Geometry System 7

Page 14: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.4.1.2 Consuming geometry from a resource

Subclasses of smtk::geometry::Backend, should provide a method on the backend which accepts a geometry providerand a persistent object and returns its corresponding geometry. Internally, this method can cast the geometry providerit is passed into one or more smtk::geometry::GeometryForBackend<T> subclasses. When a match is identified, thatprovider’s geometry() method can be called to fetch geometry and convert it into something the rendering backend canuse.

In this way, it is possible for one backend to use providers originally written for different backends. As an example, aVTK-m backend might include an adaptor for dealing with providers that can supply VTK data objects.

1.4.1.3 Geometric queries

SMTK’s geometry system provides abstract Query objects that define consistent APIs for several common geometricqueries:

Bounding box which returns axis-aligned bounds for objects with geometry.

Closest point which identifies, for a provided (x,y,z) location, the closest modeled point on an object with geometry.This will always “snap” to the nearest point on the component’s discretization instead of choosing the absolutelyclosest point.

Distance to which computes the distance from a provided (x,y,z) location to the closest point on an object withgeometry. Unlike the closest-point query, this query will return points that are not points in the discretization ofthe objects.

Random point which computes random point on a geometric resource component.

Selection footprint which is used by the ParaView user-interface components of SMTK to determine what entitiesshould be highlighted when a selected entity does not have any renderable geometry itself (but has children thatdo have geometry).

1.5 SMTK’s Attribute Resource

1.5.1 General Description

SMTK’s first major component is its attribute modeling resource, which provides a way to model and represent non-geometric simulation data such as material properties, boundary conditions, and solver parameters.

1.5.1.1 Key Concepts

The attribute resource is composed of C++ classes, also accessible in Python, whose instances perform the followingfunctions:

Attribute instances represent a dictionary of named values. The values are all subclasses of the Item class. Theentries that may appear in an attribute’s dictionary are constrained by the attribute’s Definition. In addition toholding a set of Items, an attribute may optionally be attached to (or associated with in SMTK’s parlance) a setof geometric model entities from SMTK’s geometric modeling system.

Definition instances hold the set of possible key-value pairs that must be present in Attribute instances that referencethem. A definition may inherit another definition as a base type. For instance, deflection, temperature, andvoltage boundary condition definitions might all inherit a Dirichlet boundary condition definition. Even whenthe base class provides no requirements, this is useful for fetching attributes that meet a specific condition.

8 Chapter 1. SMTK User’s Guide

Page 15: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Item instances hold values in an attribute key-value pair. The particular subclass of Item determines the type ofstorage used to hold the value (e.g. Int, Double, String, RefItem, ModelEntityItem). Each item references anItemDefinition that constrains the values that may be held in storage, in much the same way that an Attributehas a Definition. Some items (those derived from ValueItem) can have other items as children; this is used toimplement conditional items, where the presence of children is predicated on the value taken on by their parentitem.

ItemDefinition instances constrain the number of values that an Item instance may contain as well as the particularvalues that are considered valid. For example, an ItemDefinition for temperature could specify that temperatureis a scalar (i.e., only a single value may be held in the Item), that it is a floating point value, and that it must bepositive.

Resource instances hold resources of attributes associated with a particular purpose such as

• defining a simulation’s input deck (see the simulation workflows repository for examples);

• specifying locations where input and output files are located during the export process (SMTK’s simulationsubsystem creates an attribute resource for this purpose); and

• defining operations that can be performed on a geometric model (SMTK’s geometric modeling systemuses an attribute resource to hold definitions for each modeling operation that can be performed by each ofits modeling kernels).

Because it can be tedious to programmatically create a bunch of instances of the classes above to represent a particularsimulation’s input deck, SMTK provides an XML file format for serializing and deserializing all of the attributes,definitions, items, and item-definitions stored in an attribute resource.

1.5.1.2 Interfaces to the attribute resource

The attribute resource has three interfaces:

1. An XML file syntax for specifying the kinds data to be modeled for individual simulation codes and problemdomains. This file syntax is used to specify the unique inputs for a simulation code, including, for example, data types,

1.5. SMTK’s Attribute Resource 9

Page 16: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

valid ranges, and default values. Specific data can be associated with geometric model entities, and structural featurescan be used to group and classify simulation data.

2. A set of user-interface panels for end users to create and edit simulation data. Using standard windows components(buttons, text boxes, selection lists, etc.), users can enter all of the detailed data needed to specify a desired simulation.These user-interface panels are automatically produced by SMTK at runtime, based on the XML file(s) provided tothe system.

3. An API for accessing the simulation data produced by end users. Once an end-user has completed specifying thesimulation, application software can be used to traverse that data and generate the simulation input files. The nativeSMTK API is C++, and python bindings are also included. In practice, python scripts are typically used to access thesimulation data and generate the simulation input files.

1.5.1.3 Example Workflow

SMTK can be used in a broad range of scientific and engineering simulation applications. In physics-based appli-cations, such as structural mechanics, computational fluid dynamics (CFD), and electromagnetic (EM) modeling,simulations are often performed relative to a geometric model. This model may be created using computer-aided de-sign (CAD), or computationally constructed/reconstructed from empirical data. In either case, a discretization processis typically performed with the model to generate geometric input suitable for the simulation code, often in the formof a finite element or finite volume mesh. To complete the simulation inputs, the non-geometric inputs are generatedto enumerate the specific boundary conditions, material properties, solver parameters, etc.

With SMTK, the process of generating simulation input data can be automated, providing the dual benefits of work-product reuse and error reduction. Once the simulation-specific data are defined in an XML template, domain expertsor other end users can create the simulation data, or attribute data, for specific problems using the SMTK user interfacepanels. Then simulation-specific python scripts can be used to traverse the attribute data and write the simulation inputfiles.

Fig. 2: The XML below is used to generate this user interface. The fields with yellow backgrounds show default valuesand white backgrounds indicate modified values.

10 Chapter 1. SMTK User’s Guide

Page 17: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

<Definitions><AttDef Type="Example1" Label="Example 1" BaseType="" Version="0"

Unique="true" Associations=""><ItemDefinitions>

<String Name="ExampleString" Label="String item:" Version="0"NumberOfRequiredValues="1">

<BriefDescription>Enter some string of import</BriefDescription><DefaultValue>Yellow denotes default value</DefaultValue>

</String><Int Name="ExampleInteger" Label="Integer item:" Version="0"

NumberOfRequiredValues="1"><BriefDescription>For some integer value</BriefDescription><DefaultValue>42</DefaultValue>

</Int><Double Name="ExampleDouble" Label="Double item:" Version="0"

NumberOfRequiredValues="1"><BriefDescription>For floating-point precision values</BriefDescription><DefaultValue>3.14159</DefaultValue>

</Double><Double Name="ExampleVector" Label="Double item w/3 values:" Version="0"

NumberOfRequiredValues="3"><BriefDescription>Number of components is set to 3</BriefDescription><ComponentLabels><Label>x</Label><Label>y</Label><Label>z</Label>

</ComponentLabels><DefaultValue>0</DefaultValue>

</Double><String Name="SecondString" Label="Another string item:" Version="0"

NumberOfRequiredValues="1"><BriefDescription>Enter some string of import</BriefDescription><DefaultValue>whatever</DefaultValue>

</String></ItemDefinitions>

</AttDef>

<!-- Remaining content not shown -->

Conditional items

One particular workflow SMTK supports is attributes that can be defined by multiple, distinct sets of values. Forexample, there are many ways to define a circle, four of which are: using 3 points on the circle, using a center andradius, using 2 points (a center plus a point on the circle), and by inscribing a circle inside a triangle. There are timeswhen you will want to represent an attribute that can accept any of these definitions instead of constraining the user towork with a single construction technique.

SMTK accommodates this by having you create an auxiliary item whose value enumerates the different possibledefinitions. This auxiliary item owns all of the items that are active depending on the auxiliary item’s value. For ourexample of a circle, the attribute definition would be

<Definitions><AttDef Type="circle" Label="Circle" BaseType="" Version="0"><ItemDefinitions>

<!-- Here is our auxiliary item -->

(continues on next page)

1.5. SMTK’s Attribute Resource 11

Page 18: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

(continued from previous page)

<Int Name="construction method"><!-- First we list *all* of the child items --><ChildrenDefinitions><Double Name="radius" NumberOfRequiredValues="1"><Min Inclusive="false">0</Min><DefaultValue>0.5</DefaultValue>

</Double><Double Name="center" NumberOfRequiredValues="3"><DefaultValue>0.0</DefaultValue>

</Double><Double Name="point 1" NumberOfRequiredValues="3"/><Double Name="point 2" NumberOfRequiredValues="3"/><Double Name="point 3" NumberOfRequiredValues="3"/>

</ChildrenDefinitions><!-- Now we enumerate the acceptable auxiliary values

along with the children used in each case.-->

<DiscreteInfo DefaultIndex="1"><Structure><Value Enum="3 points">0</Value><Items><Item>point 1</Item><Item>point 2</Item><Item>point 3</Item>

</Items></Structure><Structure><Value Enum="2 points">1</Value><Items><Item>center</Item><Item>point 1</Item>

</Items></Structure><Structure><Value Enum="center and radius">2</Value><Items><Item>center</Item><Item>radius</Item>

</Items></Structure><Structure><Value Enum="inscribe in triangle">3</Value><Items><Item>point 1</Item><Item>point 2</Item><Item>point 3</Item>

</Items></Structure>

</DiscreteInfo></Int>

</ItemDefinitions></AttDef>

</Definitions>

You can see that each “Structure” section describes a particular way to define the circle. Different subsets of the itemsare active depending on whether the auxiliary “construction method” value is 0, 1, 2, or 3.

When SMTK generates a user interface for the attribute above, the “construction method” value is represented as a

12 Chapter 1. SMTK User’s Guide

Page 19: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Fig. 3: The user interface generated for a conditional item definition.

tabbed widget with 1 tab for each of the “Structure” sections above. The default tab will be “2 points”.

1.5.1.4 Template File Syntax (Reference)

File Layout

All attribute template and instance files must contain the <SMTK_AttributeResource> XML element. The followingtable shows the XML Attributes that can be included in this XML Element.

Table 1: XML Attributes for <SMTK_AttributeResource> ElementXML Attribute DescriptionVersion Integer value that indicates the SMTK attribute format (Required)

Current value is 3 (latest version)

This element can contain the following optional children XML Elements:

• Includes : used for including additional attribute files (see Includes Section)

• AdvanceLevels : used to define various advance access levels used in GUIs (see Advance Level Section)

• Categories : used to define workflow specific categories (see Category Section)

• Analyses : used to define various analysis groups (see Analysis Section)

• Definitions : used to define attribute definitions (see Definitions Section)

• Attributes : used to define attributes

• Views : used to define various Views (used to create GUIs)

• ModelInfo

1.5. SMTK’s Attribute Resource 13

Page 20: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Includes Section

The attribute format supports the ability to include other attribute files. This allows designers to assemble a completeattribute description by referencing attribute files that represent specific aspects. For example a set of attribute defi-nitions may be referenced by several different simulation workflows. Below is an example of including two attributefiles both located in a subdirectory IncludeTest.

<Includes><File>includeTest/b.xml</File><File>includeTest/a.xml</File>

</Includes>

Each include file is contained within a File XML Element.

Advance Level Section

This is an optional section used to describe the various access levels used in GUIs created using SMTK’s QT Attributeclasses. For example a workflow could consist of the following advance levels:

• General

• Intermediate

• Expert

Using the <AdvanceLevels> element the following represents the above access levels.

<AdvanceLevels><Level Label="General" Color="0.0, 1.0, 0.0"> 0 </Level><Level Label="Intermediate" Color="1.0, 1.0, 0.0"> 1 </Level><Level Label="Expert" Color="1.0, 1.0, 0.0"> 2 </Level>

</AdvanceLevels>

The value of each Level XML Element determines the ordering of the access levels and are used by the items containedwithin Definitions (see xxx). Notice that in the GUI example, the upper left corner “Show Level” entry is based on theAdvance Levels.

Advance Level Element Format

Each advance level is represented by using a <Level> XML Element. The value of the element determines the absoluteaccess level and should not be repeated amoung sibling Level Elements. The higher the value the more “advance” thelevel.

The following table shows the XML Attributes that can be included in this XML Element.

Table 2: XML Attributes for <Level> ElementXML Attribute DescriptionLabel String value representing the access level name to be displayed in the GUI (Required)Color String value representing the color to be used when displaying items that are associated

with this access level. The format is “r, g, b” where r, g, and b are a value between 0 and 1inclusive (Optional)

14 Chapter 1. SMTK User’s Guide

Page 21: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Category Section

This is an optional section describing the set of categories used within the file. Items within Definitions can then beassociated with these categories. In addition, analyses are defined as sets of categories. For example, the followingxml would define the following categories:

• Constituent Transport

• Heat Transfer

• Flow

• Time

• General

<Categories><Cat>Constituent Transport</Cat><Cat>Heat Transfer</Cat><Cat>Flow</Cat><Cat>Time</Cat><Cat>General</Cat>

</Categories>

Each category is contained within a Cat XML Element.

The following table shows the XML Attributes that can be included in <Categories> Element.

Table 3: XML Attributes for <Categories> ElementXML Attribute DescriptionDefault String value representing the default categories a Definition’s Item belongs to when no

category is specified.

Analysis Section

This is an optional section that define analyses. An analysis is defined as a resource of categories. For example, usingthe categories defined in the‘Category Section‘_, the following XML would define two analyses (Ground Water Flow,and Ground Water with Heat Transfer).

<Analyses><Analysis Type="Groundwater Flow"><Cat>Flow</Cat><Cat>General</Cat><Cat>Time</Cat>

</Analysis><Analysis Type="Groundwater Flow with Heat Transfer"><Cat>Flow</Cat><Cat>General</Cat><Cat>Heat Transfer</Cat><Cat>Time</Cat>

</Analysis></Analyses>

Analysis Element Format

Each Analysis is defined within an <Analsyis> XML Tag.

1.5. SMTK’s Attribute Resource 15

Page 22: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

The following table shows the XML Attributes that can be included in this XML Element.

Table 4: XML Attributes for <Analysis> ElementXML Attribute DescriptionType String value representing the type analysis being defined. Note that the type should be

unique with respects to all other analyses being defined. (Required)

Each element contains a set of Cat XML Elements.

Definitions Section

This is an optional section that defines a set of attribute definitions used to generate attrubutes with a SMTK-basedprogram. This section is created using the <Definitions> XML Element. See the example XML for how to create a setof attribute definitions.

This element is composed of a set of AttDef XML Elements

AttDef Element Format

This element define an attribute definition.

This element can contain the following children XML Elements:

Table 5: XML Children Elements for <AttDef> ElementXML Child Ele-ment

Description

<ItemDefinitions> Defines the items contained within the attributes generated by this definition (Optional).See Item Definitions Format.

<BriefDescription> Provides a brief description of the definition (Optional).<DetailedDescription> Provides a detailed description of the definition (Optional).

The following table shows the XML Attributes that can be included in this XML Element.

16 Chapter 1. SMTK User’s Guide

Page 23: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Table 6: XML Attributes for <AttDef> ElementXML Attribute DescriptionType String value representing the attribute definition type being defined. (Required).

Note that this value should be unique with respects to all other definitions being definedwith this section as well as all definitions being included via the Includes XML Element(See Includes Section)

BaseType String value representing the attribute defintion that this definition is derived from. (Op-tional)Note that the base definition must be defined prior to this definition either in section or inthe Includes Section.

Label String value representing the name display in a GUI (Optional)Note that if not specified, the Type value is displayed.

Version Integer value representing the “version” of the definition. (Optional)This is used for versioning the definition. If not specified then 0 is assumed.

Abstract Boolean value used to indicate if the definition is abstract or not. (Optional)If not specified, the definition is not abstract. Note that abstract definitions can not generateattributes.

AdvanceLevel Integer value used to indicate the advance level associated with the definition and the at-tributes it generates. (Optional)This value should match one of the advance values defined in the Advance Level Section. Ifnot specified, 0 is assumed.

Unique Boolean value used to indicate if the attributes this definition generates are unique withrespects to the model entities it associated with. A model entity can only have one uniqueattribute of a given type associated with it. (Optional)If not specified, the definition is assumed to be non-unique.

Nodal Boolean value used to indicate if the attribute effects the nodes of the analysis mesh or theelements. (Optional)If not specified the definition’s attributes are not nodal.

Associations String value indicating what type of model entities this definition’s attributes can be associ-ated on. (Optional)The information is represented as a string consisting of a set of the following charactersseparated by vertical bars (|):v (vertices)e (edges)f (faces)r (volumetric regions)m (model)g (groups)An example would be “e|f” for an attribute which may be associated with both edges andfaces. If not specified, the definition’s attributes can not be associated with any modelentities.

NotApplicationColor String value representing the color to be used when coloring model entities that are notassociated with this definition’s attribute. (Optional)The format is “r, g, b” where r, g, and b are a value between 0 and 1 inclusive. If notspecified its value is 0, 0, 0.

Default Color String value representing the color to be used when coloring model entities that are associ-ated with this definition’s attribute by default. (Optional)The format is “r, g, b” where r, g, and b are a value between 0 and 1 inclusive. If notspecified its value is 0, 0, 0.

1.5. SMTK’s Attribute Resource 17

Page 24: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Item Definitions Format

This subsection of an AttDef Element contains the definitions of all the items to be created within the attributes createdby the attribute definition. The section is represented by the <ItemDefinitions> XML Element and can contain any ofthe elements decribed in the Item Definition Section.

Item Definition Section

All of the XML Elements described within this section can be added to the <ItemDefinitions> of an attribute defintion<AttDef>.

The types of items currently supported include:

• Basic Values: Doubles, Integers, and Strings

• Groups

• Attribute References

• Directories and Files

• Model Information

• Voids

All the elements can contain the following children XML Elements. Note that each element may have additional XMLChildren Elements that are specific to it.

Table 7: Common XML Children Elements for Item Definition ElementsXML Child Ele-ment

Description

<Categories> Defines the categories that the item belongs to. (Optional)This element contains at set of <Cat> elements with each containing a category defined isthe Category Section.See Category Section.

<BriefDescription> Provides a brief description of the item (Optional).<DetailedDescription> Provides a detailed description of the item (Optional).<DefaultValue> For Integer, String, and Double items, this element’s text contains the default value for the

item. This element is not allowed for other ItemDefinition types. (Optional)For items that are not discrete and not extensible but do have NumberOfRequiredValuesgreater than 1, it is possible to provide a different default value for each component. In thiscase, commas are assumed to separate the values. If you wish to use a different separator,specify the “Sep” attribute on the DefaultValue tag.For example, a String item with 3 components might use

<DefaultValue Sep=":">Oh, my!:Oh no!:Yes, please.</DefaultValue>

to specify different defaults for each component. You can also use the separator to prevent adefault value from having per-component values. For instance, the same String item mightuse<DefaultValue Sep=":">Commas, they are my style.</DefaultValue>

to force the default value to have a single entry used to initialize all components.

All of the elements support the following common XML Attributes. Note that each element may have additional XMLAttributes that are specific to it.

18 Chapter 1. SMTK User’s Guide

Page 25: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Table 8: Common XML Attributes for Item Definition ElementsXML Attribute DescriptionLabel String value representing the name of the item being defined. (Required)

Note that this value should be unique with respects to all other items contained within thisattribute definition (including its Base Type).

Version Integer value representing the “version” of the item. (Optional)This is used for versioning the item. If not specified then 0 is assumed.

Optional Boolean value indicating if the item is considered optional or required. (Optional)If not specified the item is considered to be required.

IsEnabledByDefault Boolean value indicating if the item is considered to be enabled by default. (Optional)Note this is only used when Optional=”true”. If not specified, the item is considered to bedisabled.

AdvanceLevel Integer value used to indicate the advance level associated with the item. (Optional)This value should match one of the advance values defined in the Advance Level Section. Ifnot specified, 0 is assumed.

AdvanceReadLevel Integer value used to indicate the advance read level associated with the item. (Optional)This value should match one of the advance values defined in the Advance Level Section.Note that this is ignored if the AdvanceLevel XML Attribute is used.If not specified, 0 is assumed.

AdvanceWriteLevel Integer value used to indicate the advance write level associated with the item. (Optional)This value should match one of the advance values defined in the Advance Level Section.Note that this is ignored if the AdvanceLevel XML Attribute is used.If not specified, 0 is assumed.

Basic Value Items

Attribute Section <Attributes>

Todo: Describe attributes and how they are serialized

XML attributes

Children elements

File Item Definition <File>

Todo: Describe file items and how they are serialized

Group Item Definition <Group>

Todo: Describe group items and how they are serialized

1.5. SMTK’s Attribute Resource 19

Page 26: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Integer Item Definition <Int>

Todo: Describe integer items and how they are serialized

String Item Definition <String>

Todo: Describe string items and how they are serialized

Ref Item Definition <Ref>

Todo: Describe attribute reference items and how they are serialized

Model Entity Item Definition <Model>

A ModelEntityItem, which appears in XML as a <Model> is an item belonging to an attribute stored as a UUID thatrefers to an SMTK model entity. These model entities may be regions, faces, edges, vertices, or even higher-levelconceptual entities such as models, groups, or instances (used in modeling scene graphs and assemblies).

Void Item Definition <Void>

Todo: Describe “void” items and how they are serialized

Views Section <Views>

The Views section of an SBT file contains multiple <View> items, one of which should be marked as a top-level viewby adding the TopLevel attribute to it. The top-level view is typically composed of multiple other views, each of whichmay be defined in the Views section.

Each <View> XML element has attributes and child elements that configure the view. The child elements may includeinformation about which attributes or classes of attributes to present as well as how individual items inside thoseattributes should be presented to the user.

20 Chapter 1. SMTK User’s Guide

Page 27: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Table 9: Common XML Attributes for View Definition ElementsXML Attribute DescriptionType An enumeration that specifies what information the view should present and dictates the

children XML elements it must or may contain. Acceptable values include: “Group” (aview that groups child views in tabs), “Instanced” (a view that displays attribute instancesspecified by their names), “Attribute” (a view that displays all attributes sharing a commondefinition and usually allows users to manage instances by adding and removing them),“ModelEntity” (a view that shows model entities and lets users choose an attribute to asso-ciate with each one, optionally creating instances as needed), “SimpleExpression”, “Cate-gory”, or “Selector”. (Required)

Title A string that summarizes the view to a user. When a view is tabbed inside another, the titlestring serves as the label for the tab. (Required)

TopLevel Boolean value indicating whether the view is the root view that should be presented to theuser or (if TopLevel is false or omitted) the view is a child that may be included by thetoplevel view.

Todo: Describe root views and how they are serialized

View configuration

Each view Type above may need configuration information specified by child XML elements of the <View>. Thesections below define those child element types: the first section covers how a view chooses what attributes to showwhile the second section covers ways to customize how those attributes’ items are presented.

Attribute selection

Todo: Describe <InstancedAttributes>, <Attributes>, . . . elements here.

Item Views

If you wish to customize how items of the chosen attributes are presented, you should add an <ItemViews> child tothe <Att> tags in the attribute selectors covered in the previous section. Inside <ItemViews> you can add a <View>tag for each item whose appearance you wish to customize.

Todo: Describe <ItemsViews> children

1.5. SMTK’s Attribute Resource 21

Page 28: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Table 10: XML Attributes for Item View ElementsXML Attribute DescriptionType The name of a widget you would like the application to use to present the item (and poten-

tially its children as well) to users. SMTK provides “Box” (for showing a 3-D bounding boxwidget), “Point” (for showing a 3-D handle widget), “Line”, “Plane”, “Sphere”, “Cylinder”,“Spline”. These types usually only make sense for Group items, although “Box” can alsobe used for a Double item with 6 required values (xmin, xmax, ymin, ymax, zmin, zmax).Items may also have custom views provided by the application or external libraries; in thatcase, the Type specifier will be the string used to register the custom view.

ItemMemberIcon,ItemNonMemberI-con

These attributes are only used for ReferenceItem, ResourceItem, and ComponentItemclasses. They specify paths (either on disk or, with a leading colon, to Qt resource files) toimages to use as icons that display whether a persistent object is a member of the item ornot.

1.6 SMTK’s Operation System

Actions that create, modify and destroy resources and resource components are encapsulated within operators.

1.6.1 Operators

In SMTK, operations performed on resources are represented by instances of the Operator class. Each operation isa subclass that contains the code to perform the operation by overriding the operate() and ableToOperate() methods.These subclasses register themselves (via SMTK’s auto-init macros) with a Manager.

Todo: Describe SMTK’s auto-init macros.

The next sections describe in detail: first, how operators specify the inputs they require and outputs they produce; andsecond, how operators register themselves for introspection.

1.6.1.1 Inputs and Outputs

The inputs that an operator requires in order to run and the outputs that an operator may produce are each modeled asattribute definitions. These definitions reside in an attribute resource.

Each operator’s inputs are specified by a Definition that inherits a base attribute-definition named “operator” whilethe its outputs are specified by a Definition that inherits a base attribute-definition named “result”. Furthermore, if anoperator’s input specification is named “foo”, its output specification must be named “result(foo)”.

SMTK uses this naming convention to construct results automatically. Given an instance of an Operator subclass, youcan call its specification() method to obtain the Attribute which models its inputs. When the operator is executed, itreturns an Attribute instance that models its result.

Recall that the attribute.Resource holds Definitions which contain ItemDefinitions. When a Definition is instantiated asan Attribute, all its active ItemDefinitions are instantiated as Items. The Definitions themselves specify what types ofmodel-entities may be associated with their Attributes using a membership mask. Associations between an operator’sAttribute and model entities (i.e., subclasses of EntityRef) denote the entities that the operator will act upon. Theoperator-attribute’s Items specify input parameters such as point locations, geometric distances, etc.

The fact that inputs and outputs are specified using SMTK’s own attribute resource means that one need not constructan instance of the operator’s C++ class in order to obtain information about it; instead, simply call operatorSystem()on the session and ask for all the definitions which inherit “operator”.

22 Chapter 1. SMTK User’s Guide

Page 29: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.6.1.2 Registration

• How to enumerate operators: ask the session.

• Operators are registered with an operation manager via the operator’s use of the smtkDeclareOperator andsmtkImplementsOperator macros.

1.7 SMTK’s Geometric Model Resource

SMTK’s second major component is its geometric modeling resource, which allows you to interact with multiplemodeling sessions that may each interact with different solid modeling kernels.

1.7.1 Key Concepts

Like the attribute resource, the model resource is composed of C++ classes, also accessible in Python, whose instancesperform the following functions:

Resource instances contain model topology and geometry. All of the model entities such as faces, edges, and verticesare assigned a UUID by SMTK. You can think of the resource as a key-value store from UUID values to modelentities, their properties, their arrangement with other entities, their ties to the attribute resource, and theirtessellations.

Session instances relate entries in a model Resource to a solid modeling kernel. You can think of the entities in amodel Resource as being “backed” by a solid modeling kernel; the session provides a way to synchronize therepresentations SMTK keeps in a Resource and their native representation in the modeling kernel SMTK isinterfacing with.

Entity is a subclass of Component specific to the model resource. The resource holds an Entity record for each vertex,edge, face, etc. since the types of information stored for geometric entities is similar. Methods that are specificto the type of geometry embodied by the entity are defined via the EntityRef class and its subclasses below.

EntityRef instances are lightweight references into the Entity records held by a model Resource’s storage. Eachrepresents a single entity (e.g., a vertex, edge, face, or volume) and provide methods for easily accessing relatedentities, properties, tessellation data, and attributes associated with that entity. They also provide methodsfor manipulating the model Resource’s storage but these methods should not be used directly; instead use anOperation to modify the model so that the modeling kernel and model resource stay in sync. EntityRef subclassesinclude Vertex, Edge, Face, Volume, Model, Group, UseEntity, Loop, Shell, and so on. These are discussed indetail in Model Entities below.

1.7.2 Model Entities

This section covers two aspects of SMTK’s model entities: the implementation details such as the organization of theclass hierarchy; and the principles and governing philosophy that the model entities embody.

1.7.2.1 Implementation

As mentioned above, the model Resource class is the only place where model topology and geometry are stored inSMTK. However, there are EntityRef-like classes, all derived from smtk::model::EntityRef, that provide easier accessto model traversal. These classes are organized like so:

Each relationship shown in the figure above has a corresponding method in the EntityRef subclasses for accessing therelated entities.

1.7. SMTK’s Geometric Model Resource 23

Page 30: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.7.2.2 Organizing Principles

Model components are geometric entities; they represent geometric features that simulations use to specify the problemdomain and geometric constraints on the problem due to physical phenomena, natural conditions, engineered behavior,and variations over time. Most of the entities that SMTK provides are related to boundary-representation (B-Rep)models, where a domain is specified by its boundary (and the boundary entities are specified by their boundaries,decreasing in dimension to vertices). Thus B-Rep models specify volumes via bounding faces, faces via boundingedges, and edges by vertices. Not every entity necessarily has a lower-dimensional boundary: an edge may be periodicand thus not need a vertex as its boundary, or infinite in extent (although usually, those are represented by a vertexplaced “at infinity” via homogeneous coordinates). Similarly, faces and volumes may be unbounded due to periodicityor infinite extent.

The other common feature in most B-Rep models are use-records, which impart sense and orientation to geometricentities. Geometric entities such as faces are generally considered either topologically (i.e., an entity is a single thing(a set) given a name inside a collection of other things) or geometrically (i.e., an entity is a locus of points in space,and those points have features such as a measure that identifies the dimensionality of the locus). Neither of theseapproaches (topological or geometric) imply orientation or sense.

Orientation is a binary indicator (positive/negative, inside/outside, or forward/backward) associated with an entity.Occasionally, people may also consider it a tertiary indicator: inside/outside/on.

Similarly, the “sense” of an entity is the notion of how the entity is being employed to compose the model.

To understand how sense and orientation are distinct from one another, consider an edge in a 3-dimensional model thatbounds 2 or more faces. Edges have both an orientation, which is the direction along the edge considered forward. Thesense identifies which face a pair of oppositely-oriented “uses” bound. Since the same edge may bound arbitrarily-many faces in 3 dimensions, SMTK uses an integer to identify the sense.

Faces (in 3-dimensional models) always have 2 orientations and may partition volumes to either side. Because a faceonly has 2 sides, faces may bound at most two volume regions. This means that for faces, the sense may always betaken to be 0 without loss of generality.

Vertices are not considered to have an orientation but do have a non-trivial sense: consider the model vertex at thepoint where two conical surfaces meet. The vertex is used in a different sense by each cone; a different vertex-userecord (if vertex uses are tracked by the modeling kernel) will be created for each volume bounded by the vertex whenthose volumes share no other points in the immediate neighborhood of the vertex.

Beyond geometric entities and use-records, SMTK also offers model entities for less formal models: groups, auxiliarygeometry, geometric instances, models, and concepts.

1.7.3 Filtering and Searching

As with all classes that inherit smtk::resource::Resource, it is possible to ask the resource to filter its componentsusing a string that specifies some search criteria (i.e., a filter). Model resources accept an extended syntax comparedto other resource types since (1) model entities have so many types as described above and (2) in addition to thesetypes, users and SMTK workflows often mark up these model entities with properties (covered in the Model PropertySystem section) to provide high-level conceptual information that is useful in preparing simulations. For example, ageometric model of a motor will have many model faces that might each be marked with properties to indicate whichare bearing surfaces, which are fastener or alignment surfaces, which surfaces will be in contact with coolant or fuel,etc.

In order to allow user interface components to only show relevant model entities, the model resource’s queryOperationmethod accepts strings in the following format:

type-specifier [ property-type [ { property-name [ = property-value ] } ]

where

24 Chapter 1. SMTK User’s Guide

Page 31: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

• type-specifier is any model-entity type specifier string such as face, group, model. A full list can befound in smtk/model/Entity.cxx.

• property-type is one of the following string literals string, floating-point, integer.

• property-name is either a single-quoted name or a slash-quoted regular expression (i.e., a regular expressionsurrounded by forward slashes such as /(foo|bar)/).

• property-value is one of the following

– a single, single-quoted string value to match (when searching for string properties),

– a single, slash-quoted regular expression to match (when searching for string properties by regularexpression),

– a single, unquoted integer or floating point value to match (when searching for properties of thosetypes), or

– a tuple (indicated with parentheses) of values, as specified above, to match. Note that this implies theproperty must be vector-valued and the length must match the specified tuple’s length in order for amatch to be successful.

Whitespace is allowed anywhere but is treated as significant if it is inside any quoted string value or regular expression.

Note that single quotes are used because these filter strings will appear in XML and/or JSON serializations that usedouble-quotes to mark the start and end of the query string. The examples below include the double-quotes around thequery as a reminder.

For regular expressions, the c++11 standard library is used to search for matches; the syntax must be accepted by thestd::regex constructor and std::regex_search() must return true when passed property names or values in order for thecorresponding entity to be included in filtered results.

Table 11: Examples of valid query strings.Query string Results“model|3” Any model explicitly marked as 3-dimensional. (This example has no lim-

iting clause is here to be clear that existing query strings will continue to beaccepted.)

“vertex[string]” Vertices with any string properties at all (but not vertices without stringproperties).

“any[integer{'counter'}]” Any entity with an integer property named ‘counter’ (regardless of thevalue).

“face[string{'pedigree'='zz'}]”Faces with a string-property named pedigree whose value is “zz”“any[floating-point{/.*/=(0,0,0)}]”

An entity of any type with any floating-point property whose value is a 3-entry vector of zeros.

“group[string{'alphabet'=('abc','def')}]”

Any group with a string property named “alphabet” whose value is a vectorof 2 strings: one valued “abc” and the next valued “def”.

1.7. SMTK’s Geometric Model Resource 25

Page 32: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Table 12: Invalid non-examples of query strings that will not work.Query string Why This is Invalid“edge,face[integer{'pedigree'=23}]”

Multiple queries are not supported yet. Also, it is unclear whether the lim-iting clause applies to both types or just faces. For now, use multiple filtersto handle combination queries with different limiting clauses. Note that ifthis example had used edge|face instead of edge,face, it would havebeen valid; the filter would have apply to edges or faces.

“any[{'pedigree'}]” You must currently specify the property type.“any[integer{'lattice'=(0,*,*)'}]”

There is no way to search for properties with partially-matched array-valuedentries.

“any[integer{'counter'=(*,*,*)'}]”

There is no way to search for properties whose value is a given length yet.

1.7.4 Sessions

As mentioned above, Sessions link, or back SMTK model entities to a solid-modeling kernel’s representation of thosemodel entities. Not all of the model entities in a model manager need to be backed by the same session; SMTK cantrack models from multiple modeling kernels in the same model manager. However, in general you cannot performmodeling operations using entities from different sessions.

Sessions (1) transcribe modeling-kernel entities into SMTK’s storage and (2) keep a list of Operators that can beused to modify the model. As part of the transcription process, sessions track which entities have been incompletelytranscribed, allowing partial, on-demand transcription. SMTK’s opencascade and discrete session types use theirrespective attribute resource’s modeler to hold SMTK-generated universal, unique IDs (UUIDs) for each model entity;modeling-kernel sessions may also provide a list of UUIDs in an unambiguous traversal order. This is useful if UUIDscannot be stored in a model file but also in the event where you do not wish to modify the file by rewriting it withUUID attributes included.

When a model operation is performed, — depending on how much information the modeling kernel provides aboutaffected model entities — entities in SMTK’s storage are partially or totally marked as dirty and retranscribed ondemand.

Transcription involves mapping unique identifiers to Entity records, to Tessellation records, to Arrangement records,and to property dictionaries. A property dictionary maps a name to a vector of string, floating-point, and/or integervalues of arbitrary length per model entity. While property names are arbitrary, there are some special property namesused by the modeling system:

• SMTK_GEOM_STYLE_PROP marks models with a ModelGeometryStyle enum indicating whether the modelis discrete or parametric.

• SMTK_TESS_GEN_PROP marks cells that have tessellations with an integer “generation” number indicatingthe age of the tessellation.

• SMTK_MESH_GEN_PROP marks cells that have an analysis mesh with an integer “generation” number indi-cating the age of the mesh.

When a property value can be reliably determined by a session’s modeling kernel (independent of the model manager),the session should add that property name to the list reported to the model manager for erasure when a model entity isbeing deleted. (Other user-assigned properties are not deleted by default when an entity is erased.)

1.7.4.1 Registration and initialization of Sessions and Operators

Because sessions usually back SMTK model entities with representations in a solid modeling kernel, constructing asession (and thus initializing a modeling kernel) can be an expensive operation. This expense is even higher if theactual session must live in a separate process or even possibly on a remote machine.

26 Chapter 1. SMTK User’s Guide

Page 33: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Todo: Update how modeling sessions are exposed via plugins.

Todo: Discuss Remus and ParaView client/server sessions

1.7.5 Model Property System

In addition to associating modeling entities with attributes, SMTK’s model resource uses the resource’s propertiesmechanism to store string, integer, and floating-point properties on model entities. Unlike attributes that have a rigidformat imposed by definitions, properties are free-form: given any model entity UUID and a property name, you maystore any combination of string, integer, and floating-point values.

The intent of the model property system is two-fold:

1. Properties can be created by sessions to expose modeling-kernel data that cannot otherwise be expressed bySMTK. An example of this is the Exodus session, which stores the Exodus ID of each block and set it reads sothat exporters can refer to them as they exist in the file.

2. Properties can be created by applications built on SMTK to mark up model entities. This might include usermarkup such as entity names or application data such as whether an entity is currently selected, or which viewsan entity should be displayed in.

Despite being free-form, SMTK does use the property system itself and so some property names are reserved forparticular use. The list of these names is below and is followed by properties provided by existing sessions.

1.7.5.1 Reserved model properties

The following table lists the conventions that SMTK uses for property names. These names are used for the purposedescribed but the convention is not enforced programmatically.

Properties that applications will most commonly expose to users are summarized in the table below:

Propertyname

Prop-ertytype

Description

color Float A 3- or 4-tuple holding RGB or RGBA color values. Clamped to [0,1]. An example wouldbe [0., 0., 1., 1.] for blue. Color may be assigned to any entity with a visual representation.

embed-dingdimension

Integer The number of coordinates required to represent any point in the locus of all points con-tained in the entity’s underlying space.

name String The name for the entity as presented to the user.url String Assigned to model entities loaded from data at the specified location.

Properties used internally are in the following table:

1.7. SMTK’s Geometric Model Resource 27

Page 34: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Property name Property type Descriptioncell_counters Integer An array of 6 integers assigned to each model entity and used to generate

model-unique names that are easier to read than UUIDs.See Entity::defaultNameFromCounters() to understand how the array isused.

generate normals Integer When non-zero, this indicates that the given entity’s tessellation shouldhave surface normals added via approximation (because the modelingkernel does not provide any and the geometry has curvature). When notdefined, it is assumed to be zero. When defined, it should be a singlevalue.Most commonly this is stored on models and is applied to all of the tes-sellated entities belonging to the model. However, it may be stored onindividual entities as well.

group_counters Integer An array of 3 integers assigned to each model entity and used togenerate model-unique names that are easier to read than UUIDs.Three integers are used because groups with the MODEL_DOMAIN orMODEL_BOUNDARY bits set are numbered separately.See Entity::defaultNameFromCounters() to understand how the array isused.

instance_counters Integer A single integer assigned to each model entity and used to generatemodel-unique instance names that are easier to read than UUIDs.See Entity::defaultNameFromCounters() to understand how the counteris used.

invalid_counters Integer A single integer assigned to each model entity and used to number invalidchild entities in a way that is easier to read than UUIDs.See Entity::defaultNameFromCounters() to understand how the counteris used.

model_counters Integer A single integer assigned to each model entity and used to generate aunique name for each submodel of the given model.See Entity::defaultNameFromCounters() to understand how the counteris used.

session pedigree String or Integer A session-specific persistent identifier assigned to the associated entityfor use by the exporter and other tasks that need to refer to the entitywhen it is not possible to use UUIDs created by SMTK to do so. Thishappens when the original model file may not be modified and simulationinput decks must refer to entities in that original file.Sessions should provide 0 or 1 values for each entity.

shell_counters Integer An array of 5 integers assigned to each model entity and used to generatemodel-unique names that are easier to read than UUIDs.See Entity::defaultNameFromCounters() to understand how the array isused.

use_counters Integer An array of 6 integers assigned to each model entity and used to generatemodel-unique names that are easier to read than UUIDs.See Entity::defaultNameFromCounters() to understand how the array isused.

_tessgen Integer An integer used as a generation number for tessellation and boundingbox data; it is incremented each time the entity geometry changes.

_meshgen Integer An integer used as a generation number for mesh data; it is incrementedeach time a mesh is modified (e.g., by displacing it, not by remeshing).

_geomstyle Integer Indicates whether the modeling kernel represents geome-try discretely (smtk::model::DISCRETE) or parametrically(smtk::model::PARAMETRIC).

_boundingBox Float The world-coordinate, axis-aligned bounds of an entity, reported as a 6-vector: [xmin, xmax, ymin, ymax, zmin, zmax].

28 Chapter 1. SMTK User’s Guide

Page 35: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.7.5.2 Model properties of sessions

In general, sessions should choose a prefix for their property names so that developers can easily identify the source ofthe property, even when saved in a JSON model file. The exception to this rule is properties that should be universalacross sessions, such as pedigree ID.

Properties specific to the Exodus session are listed in the table below.

Prop-ertyname

Prop-ertytype

Description

cmbid

Inte-ger

A pedigree ID assigned to model entities in discrete sessions.

exo-dusid

Inte-ger

The block ID or set ID as stored in the Exodus file.

exo-dustype

String One of “block”, “side set”, or “node set”. This indicates how the group is represented in the exo-dus file. The group’s dimension bits can also be used to determine this information by comparingthem to the parent model’s parametric dimension.

1.7.6 Operators

In SMTK, operations performed on geometric or conceptual models are represented by instances of the Operator class.Each operation, such as creating an edge, is a subclass that contains the code to perform the operation by overridingthe operate() and ableToOperate() methods. These subclasses register themselves (via SMTK’s auto-init macros) in away that allows a list of applicable subclasses to be enumerated for any given type of model entity. Operators performwork on a model in situ: they modify the model in place. If you are familiar with VTK, this can be confusing, sinceVTK’s pipeline filters leave their input datasets untouched while SMTK’s operators do not. However, this in-placeoperation is a standard practice among solid modeling software.

Todo: Describe SMTK’s auto-init macros.

The next sections describe in detail: first, how operators specify the inputs they require and outputs they produce; andsecond, how operators register themselves for intropspection.

1.7.6.1 Inputs and Outputs

The inputs that an operator requires in order to run and the outputs that an operator may produce are each modeled asattribute definitions. These definitions reside in an attribute resource owned by an instance of a modeling session.

Each operator’s inputs are specified by a Definition that inherits a base attribute-definition named “operator” whilethe its outputs are specified by a Definition that inherits a base attribute-definition named “result”. Furthermore, if anoperator’s input specification is named “foo”, its output specification must be named “result(foo)”.

SMTK uses this naming convention to construct results automatically. Given an instance of an Operator subclass, youcan call its specification() method to obtain the Attribute which models its inputs. When the operator is executed, itreturns an Attribute instance that models its result.

Recall that the attribute.Resource holds Definitions which contain ItemDefinitions. When a Definition is instantiated asan Attribute, all its active ItemDefinitions are instantiated as Items. The Definitions themselves specify what types ofmodel-entities may be associated with their Attributes using a membership mask. Associations between an operator’sAttribute and model entities (i.e., subclasses of EntityRef) denote the entities that the operator will act upon. Theoperator-attribute’s Items specify input parameters such as point locations, geometric distances, etc.

1.7. SMTK’s Geometric Model Resource 29

Page 36: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

The fact that inputs and outputs are specified using SMTK’s own attribute resource means that one need not constructan instance of the operator’s C++ class in order to obtain information about it; instead, simply call operatorSystem()on the session and ask for all the definitions which inherit “operator”.

The next sections go over conventions that SMTK uses for its inputs and outputs.

Inputs

There are no naming conventions for input parameters, however:

• operators should use model-entity associations as the primary means for selecting geometry that an operator willact upon;

• also, by using the attribute resource to hold operator specifications, simply checking whether an attribute isin a valid state is usually enough to guarantee that the operator can run successfully. This is what the defaultimplementation of ableToOperate() does. Subclasses may override the method to provide additional checks (i.e.,whether a file is writable);

• when an operator needs only an associated set of model inputs, either because it has no parameters or they alltake on valid default values, it can be run without further user input and applications are encouraged to provide away to execute them immediately. However, when ableToOperate() returns false or applications wish to provideusers a chance to override default parameters, some interface must be provided. The qtOperatorView class isprovided for this purpose.

Outputs

Output attributes have several items with standard names used to tell applications what changes an operator has madeto the model:

• created (ModelEntityItem) An array of model entities that were created during the operation. These itemsmay have tessellations (meaning there are new renderable entities) or relationships to existing entities (meaningthere are new items to insert in the tree view).

• modified (ModelEntityItem) An array of model entities that were modified during the operation. This doesnot imply that an entity’s tessellation has changed; the tess_changed entry below is used for that.

• expunged (ModelEntityItem) An array of model entities that were removed entirely from the model managerduring the operation.

• tess_changed (ModelEntityItem) An array of model entities whose geometric tessellations changed duringthe operation. This is signaled separately from modified above to minimize the overhead in rendering whenonly topological changes have occurred.

• cleanse entities (VoidItem) When present and enabled, this operator marks the modified andcreated entities as “clean” (meaning that they do not need to be saved; they are at exactly the state present intheir owning-model’s URL).

• allow camera reset (VoidItem) When present and enabled, this operator will allow (but not force) thecamera of the active render view to be reset. A reset will actually occur when no renderable entities existedprior to the operation but at least one renderable entity exists afterward. Operators which load data from files areencouraged to include this item in their result attribute while operators which let users create or modify entitiesinteractively — especially through interaction in render-views — are discouraged from allowing camera resets.

1.7.6.2 Registration

• How to enumerate operators: ask the session.

30 Chapter 1. SMTK User’s Guide

Page 37: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

• Operators are registered with a particular session via the operator’s use of the smtkDeclareModelOperator andsmtkImplementsModelOperator macros.

• Operators registered with the base session are inherited unless the session’s constructor prevents it explicitly.

1.7.7 Presenting models in a user interface

SMTK provides several classes to help user-interface developers present hierarchical and/or list views of solid mod-eling entities to users. There are many different circumstances where these views are needed, so flexibility is a keyrequirement. Some of these use cases include:

• A tree view showing modeling entities to allow selection when entities are obscured in a 3-D rendering by othergeometry (e.g., a face inside a cavity) or not being illustrated (e.g., oriented shell uses are not usually explicitlyrendered but may be associated with boundary conditions rather than faces in some multiphysics simulations).

• A list view displaying group membership and allowing drag-and-drop modifications.

• A list view showing entities ordered by their intersection points along a ray fired through a rendered view (forselection of entities as input to operations or association with simulation attributes).

• A tree view illustrating relationships between entities and sizing functions and/or feature definitions used toconstrain meshers.

• A tree view showing relationships between model concepts or categories and model entities. For example,a simulation may be defined without reference to geometry, knowing only that a boundary condition existswherever solid material meets ambient air. A tree view can be used to assign geometric regions to materials(solid, air) and the tree view would allow selections that render where the boundary condition would be appliedwith those assignments.

In some instances (use cases that present list views), each entity should be displayed without any children.

In other instances it may be desirable for entities in a tree view to show an abbreviated hierarchy rather than the fullhierarchy; it is rare for users to interact directly with oriented use records (edge- or face-uses) or shells or loops. Ratherthan having cells present use-records as children and force users to open, for example, a face’s face-use and then theface-use’s loop and then one of the loop’s edge-uses to obtain an edge bounding the face, the face should present itsbounding edges as direct children.

Finally, there are circumstances when the full solid-model hierarchy should be presented.

Instead of writing a separate model or widget for each use case, SMTK provides a framework that can express any ofthese cases. The framework consists of two base classes plus some subclasses of each. The base classes are not tied toany particular user interface library so that they can be used in both desktop and web applications. An adaptor to theQt model-view-controller system is provided, named QEntityItemModel.

The first base class is DescriptivePhrase. Instances of DescriptivePhrase or its subclasses are arranged in a tree. Eachphrase has at most one parent and zero or more children. List views are expressed as one parent phrase with nograndchildren. A descriptive phrase may be asked for a solid modeling entity related to it, but the returned entity maybe invalid (such as the case when a phrase is used to group other phrases). Descriptive phrases also

• must provide a type which user interfaces may use to alter presentation style,

• must provide a textual title and may also provide a subtitle (as is commonly used in iOS table views),

• may provide an icon and/or a color,

• may mark elements such as the title, subtitle, or color as mutable (indicating that the user may change it).

The SubphraseGenerator class is the second base class in the user-interface presentation system. Descriptive phrasesstore a list of children but they are not responsible for computing that list, nor is the list computed except on demand.Instead, each phrase (or its parent, if it has one) stores a reference to an instance of a SubphraseGenerator that willcompute children when they are requested from a descriptive phrase.

1.7. SMTK’s Geometric Model Resource 31

Page 38: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

The SubphraseGenerator is separate from the DescriptivePhrase class so that different user-interface components canuse the same set of phrases but arrange them in different ways. For example, a widget for selecting a model mightsubclass the subphrase generator to only enumerate sub-model and sub-group children of a DescriptivePhrase; whilea model-detail widget might include volumes, faces, edges, and vertices as children. Another example is shown in thefigure at the top of this subsection.

Here, additional summary phrases are inserted in the lower figure to reduce clutter when a phrase has many children.The subphrase generator is completely programmable, so multiple summaries could be added to distinguish childrenof different types.

1.7.8 Session: Discrete

SMTK has a session type named discrete that sessions a VTK-based discrete modeling kernel. This kernel providesaccess to 2-D and 3-D polygonal and polyhedral models, with operators that allow model edges and faces to be splitor merged.

Models need not include a full topology (e.g., only volumes and faces may be represented, with edges implied; orgeometric entities may be modeled but not all of their oriented use-records). However, several operations such as“create edges” exist to generate a full topology from a self-consistent but incomplete model.

1.7.9 Session: Exodus

SMTK has a session type named exodus that is not technically a modeling kernel but does allow you to mark upmeshes saved in the Exodus-II file format for use in an existing simulation — assuming that element blocks and sidesets that segregate the model into one or more regions per material and one or more groups per boundary-conditionare already present in the exodus mesh.

Todo: Describe what blocks and sets are

Todo: Describe how blocks and sets are mapped to models and groups

Todo: Show simple example?

1.7.10 Session: Polygon

SMTK has a session type named polygon that sessions Boost.polygon’s modeling kernel. This kernel provides accessto 2-D polygonal models, with operators that allow model edges and faces to be split or merged as well as booleanoperations and Voronoi diagram computation.

Boost’s polygonal modeler uses integer arithmetic to achieve high performance with robust geometric predicates.SMTK converts 3-D floating-point coordinates into 2-D integer coordinates for you, but you must provide severalpieces of information for each model instance:

• A base point for the plane holding the polygon

• Either x- and y-axis vectors (in 3-D world coordinates) describing the planar coordinate system you wish to use,or an x-axis and the plane’s normal vector.

• Either a minimum feature size (in world coordinates) that your model should represent or an integer modelscaling factor that each world coordinate is multiplied by before rounding to an integer.

32 Chapter 1. SMTK User’s Guide

Page 39: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

This session does not allow model edges to have more than 2 model vertices. A model edge may have zero or onevertices when the edge is a periodic loop denoted with identical first and last points; in this case, the first and last pointmust also be the model vertex. A model edge must have two model vertices when it is not periodic, one at each endof the edge. Model edges may have any number of interior points that are not model vertices. These restrictions areimposed so that it is possible to quickly determine what model face lies adjacent to each model vertex. If model edgescould have interior vertices, the assumption that each edge may border at most 2 faces would be much more difficultto enforce and validate.

This decision regarding model vertices and edges has further implications. Edges may not have any self-intersectionsother than at points where segments meet. When edges are joined into loops to form a face, they are intersected withone another first; if any intersections are found, then the model edges are split when the face is created.

Note that SMTK is slightly more restrictive (in that it splits edges and creates model vertices) than Boost requiresbecause Boost does not model edges at all; instead it models polygons as sequences of points – optionally with a list ofholes which are themselves polygons. In Boost’s modeler, points are not shared between faces; each face is a model inits own right. Because of this, it is simple for Boost to use keyholed edges to represent holes in faces. Keyholed edgesare edges coincident along a portion of their length and effectively split a face with holes into a face with no holes butwith infinitesimal slivers connecting the region outside the face to each hole. SMTK can accept keyholed edges butthey must be broken into multiple model edges at intersections so that SMTK’s assumption that planar edges borderat most 2 different surface regions.

1.7.10.1 Meshing Boost.polygon models

Boost polygonal models are conforming piecewise-linear cell complexes (PLCs), and may thus be meshed by anySMTK mesh worker that accepts models in this form.

1.8 SMTK’s Graph-based Model Resource

An alternative to SMTK’s geometric model resource is the graph-based model resource. Unlike the geometric modelresource, which has a set of fixed component types, the graph-based resource has a user-defined set of componentsand relationships (arcs) between those components.

1.8.1 Key Concepts

Where the geometric model resource has a fixed set of component types, the graph-based model is intended to holdapplication-specific components. Furthermore, it uses modern C++ template metaprogramming techniques to offertype safety as well as programmable run-time component (graph node) and arc classes that can be configured fromPython scripts or even text files by applications or end users.

Resource instances contain graph nodes and arcs (which are traditionally called graph edges — but we wish to avoidconfusion with geometric edges). All of the model entities you create are owned by the resource, along with thearcs between them. Arcs are represented via a mechanism similar to the resource Links API. The resource classitself is templated. It requires a type-traits object as its template parameter that list the node and arc types theresource will accept. Thus it is not a concrete implementation but rather a base class for other resources.

Component is a subclass of Component that provides some methods for accessing connected arcs. As above, you areexpected to subclass this class with node types specific to your application.

Todo: Create runtime-configurable classes (ProgrammableResource, ProgrammableNode, ProgrammableArc) thatcan be python-wrapped and configured via a JSON serialization.

1.8. SMTK’s Graph-based Model Resource 33

Page 40: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.8.2 Nodes and Arcs

This section covers how to subclass SMTK’s graph entities to fit your application’s model.

1.8.2.1 Nodes

Nodes are intended to be lightweight subclasses of Component. Where possible, you should consider using SMTK’sproperty system instead of adding member data to a graph node; properties are serialized when reading and writingresources and the graph-based model resource provides queries to find components based on properties. By usingproperties for storage, you can take advantage of this work. Think of graph node classes as repositories of methodsthat query and modify the component’s properties.

Todo: Describe minimal subclass

1.8.2.2 Arcs

Similarly to graph nodes, think of arcs as repositories of methods that act on relationships between components. Arcsare directed graph-edges that restrict the two components at either endpoint to be of a specific type. For instance, ageometric face can be bounded by 0 or more edges. The arcs that connect a face to its bounding edges only accept aFace component for their origin and an Edge component for their destination.

The graph-model resource provides two templated arc classes that your arcs may inherit: Arcs and OrderedArcs. Thelatter can be used to preserve the ordering of arcs relative to one another. This is useful in solid modeling (CAD)where order is related to geometric arrangement. For example, the edges bounding a face can be ordered into loopswhose edges meet head-to-tail and always keep the face interior to the left when traversing edges in order.

Todo: Describe use of struct

1.8.3 Filtering and Searching

Todo: Describe filter/search syntax

1.9 SMTK’s Mesh Resource

SMTK’s third major component is its meshing resource, which allows you to interact with multiple mesh generatorsand associate one or more meshes with each geometric model entity.

1.9.1 Key Concepts

Like the model resource, the mesh resource is composed of C++ classes, also accessible in Python, and is based onconcepts from MOAB, which it uses internally. The paradigm we use facilitates an interaction with meshes and theircomponents in aggregate, avoiding granular queries whereever possible (e.g. favoring such set-theretical actions as“intersection” and “union”, rather than iterating over individual elements).

34 Chapter 1. SMTK User’s Guide

Page 41: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

To enforce the concept of interacting with mesh elements in aggregate, all mesh elements are represented as sets: thereare no classes that represent individual mesh elements (point, cell or mesh). A user can interact with individual meshelements via the MeshForEach interface, which iterates over single elements that may be represented as element setscontaining a single element. It should be noted that element-wise access to a mesh is usually not the correct approachfor most algorithms.

The class instances, listed hierarchically from the most granular to the most aggregate, are as follows:

Handle instances refer to a single smtk::mesh entity, which may be a single primitive mesh element (a point or a cell,e.g., a triangle or quadrilateral), a set of points (an PointSet), a set of cells (an CellSet), or a set of mesh elements(an MeshSet) grouped together for some purpose.

HandleRange instances refer to a range of mesh entities. A range is a run-length encoded list of mesh handles(which are opaque but internally represented by integers). By making HandleRanges a primitive type, mesheswith implicit connectivity can be compactly represented.

PointSet instances group HandleRange instances referring to points together so they can be marked with propertiessuch as a common association with a model entity, material, boundary condition, or initial condition. As aset, each PointSet supports set-theoretic actions (intersect, difference and union). Each PointSet instance holds areference to its parent resource (described below) and provides methods for setting attributes, computing subsets,and accessing individual points.

CellSet instances group HandleRange instances referring to cells together so they can be marked with properties suchas a common association with a model entity, material, boundary condition, or initial condition. As a set, eachCellSet supports set-theoretic actions (intersect, difference and union). Each CellSet instance holds a referenceto its parent resource (described below) and provides methods for setting attributes, computing subsets, andaccessing individual cells.

MeshSet instances group HandleRange instances referring to meshes together so that they can be marked with prop-erties such as a common association with a model entity, material, boundary condition, or initial condition. As aset, each MeshSet supports set-theoretic actions (intersect, difference and union). Each MeshSet instance holds areference to a parent resource (described below) and provides methods for setting attributes, computing subsets,and accessing individual meshes. A MeshSet also has access to its underlying CellSet and PointSet.

In general, a MeshSet will not contain elements that overlap spatially. Instead, a meshset usually has a boundarythat conforms to neighboring meshsets (or to empty space). Often, an SMTK modeling entity (correspondingto a CellEntity) will be associated with a meshset that approximates its point locus; however, not all MeshSetshave an associated model entity.

Collection instances hold related MeshSets together. Problem domains are often the union of several instances ofMeshSet in a Collection. Often, the problem domain may be decomposed in several ways, so that all of theMeshSet‘s in a resource may cover the problem domain several times over. For example, a ‘Collection may haveone MeshSet for each geometric model cell as well as a MeshSet for each material. Either of these alone wouldcover the entire problem domain; together, they cover it twice.

All of the cells in all of the MeshSet instances of a Collection have their connectivity defined by indices into thesame set of points.

Each Collection has a parent mesh Manager.

Manager instances contain Collections and provide an interface to an underlying mesh package, such as MOAB, thatimplements methods to access the mesh.

1.9.2 IO

WriteMesh Writes out a given Collection, or only the elements that match a given Domain, Dirichlet or Neumannproperty. This is a preserving process: all information relevant to the mesh is written to file, and subsequentreads from this file should restore the mesh exactly.

1.9. SMTK’s Mesh Resource 35

Page 42: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Supported formats:

• MOAB (h5m, mhdf)

• Exodus II (exo exoII exo2 g gen)

ReadMesh Load a given file in as a new Collection or part of an existing Collection. Also supports loading justelements that a given Domain, Dirichlet or Neumann property. This is a preserving process: all informationrelevant to the mesh should restore the mesh in the same state as when it was written.

Supported formats:

• MOAB (h5m, mhdf)

• Exodus II (exo exoII exo2 g gen)

ImportMesh Import a given file in as a new Collection or part of an existing Collection. Imports are not preservingprocesses: all mesh information contained in a file is not guaranteed to be read into the mesh database viaImportMesh.

Supported formats:

• MOAB (h5m, mhdf)

• Exodus II (exo exoII exo2 g gen)

• VTK (vtk)

• SLAC (slac)

• General Mesh Viewer (gmv)

• ANSYS (ans)

• Gmsh (msh gmsh)

• Stereolithography (stl)

ExportMesh Export a given Collection to file. Exports are not preserving processes: all mesh information containedin the mesh database is not guaranteed to be written to file via ExportMesh.

Supported formats:

• MOAB (h5m, mhdf)

• Exodus II (exo exoII exo2 g gen)

• VTK (vtk)

• SLAC (slac)

• General Mesh Viewer (gmv)

• ANSYS (ans)

• Gmsh (msh gmsh)

• Stereolithography (stl)

• XMS 2D/3D (2dm 3dm)

1.9.2.1 Serialization

SaveJSON Export all the Collection that have associations with the any model that is part of the passed in Resource.The exporter will save each Collection using WriteMesh with the file type MOAB and extension h5m.

The format of the created json is:

36 Chapter 1. SMTK User’s Guide

Page 43: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

"70ec982c-9562-44bd-a7e7-bd12b84a3271": {"formatVersion": 1,"name": "","fileType": "moab","location": "/tmp/output.0.h5m","nc": 40,"np": 28,"cell_types": "000000100","domains": [],"boundary_conditions": {"0": {

"value": 2,"type": "dirichlet"

},"1": {

"value": 2,"type": "neumann"

},},"modelEntityIds": ["0442f22c-26dc-4e6b-bdd8-1e77b75e5d36", "7d42284b-c7e0-4777-8836-

→˓3b77d6aed0e3", "8cdcf988-36bd-43ed-bb60-c76443907f16", "c7a90a24-f058-4d79-8b75-→˓bb58470547bf"],"meshes": {"0": {

"nc": 10,"np": 7,"cell_types": "000000100","domains": [],"boundary_conditions": {

"0": {"value": 2,"type": "neumann"

}},"modelEntityIds": ["0442f22c-26dc-4e6b-bdd8-1e77b75e5d36"]

},"1": {

"nc": 10,"np": 7,"cell_types": "000000100","domains": [],"boundary_conditions": { },"modelEntityIds": ["7d42284b-c7e0-4777-8836-3b77d6aed0e3"]

},"2": {

"nc": 10,"np": 7,"cell_types": "000000100","domains": [],"boundary_conditions": {

"0": {"value": 2,"type": "dirichlet"

}"1": {"value": 2,"type": "neumann"

(continues on next page)

1.9. SMTK’s Mesh Resource 37

Page 44: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

(continued from previous page)

}},"modelEntityIds": ["8cdcf988-36bd-43ed-bb60-c76443907f16"]

},"3": {

"nc": 10,"np": 7,"cell_types": "000000100","domains": [],"boundary_conditions": { },"modelEntityIds": ["c7a90a24-f058-4d79-8b75-bb58470547bf"]

}}

}

LoadJSON Imports all the Collection that are listed in the provided JSON string. Each Collection will be marked asbeing associated with the provided model Resource.

1.10 SMTK’s Simulation System

Once you have a model or mesh and an attribute resource describing a simulation, you are ready to create an inputdeck for the simulation.

One option is to have your simulation link directly to SMTK, load the saved information from SMTK’s native fileformats, and use SMTK to initialize the simulation.

Often this is not feasible, and so SMTK provides stubs for writing a file in the format a simulation expects, commonlyknown as an input deck1. We expect you will use python to write the input deck as it is much simpler and easier tomaintain a python script than a large C++ code base to write what is usually a flat text file.

The smtk::simulation::ExportSpec class aggregates all of the information you should need to write the input deck:

• an attribute resource holding simulation parameters

• an attribute resource holding locations of files involved in the export

• an object that provides methods for querying the analysis grid (be it a model or mesh).

Your python export script is expected to take a single argument (an instance of ExportSpec) and write whatever filesare needed to run the simulation.

1.11 SMTK’s View System

One of the main functions of SMTK is to present attributes, models, and meshes to users so that they can edit andannotate them. The view system provides classes that aid with this task without depending on any particular userinterface technology (Qt, HTML+JavaScript, VTK, etc.).

1.11.1 Key Concepts

There are 2 ways that presentation is abstracted in SMTK: views and trees of descriptive phrases.

1 This term is historical, as many of the first simulations were run on computers that used punch cards for offline storage; a deck of punch cardsholding simulation parameters was often kept as a way to reproduce results for a simulation run used in a report or journal article.

38 Chapter 1. SMTK User’s Guide

Page 45: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

View instances are containers that hold information used to configure a view. There are currently 2 types of views inSMTK: * attribute views, which allow users to inspect and edit an entire attribute resource; and * phrase views,which allow users to inspect and edit any resource by interacting with

a tree of one-line summary information related to a resource or component.

PhraseModel instances represent a tree of descriptive phrases that together summarize information about resourcesand/or components. Each entry in the tree is a descriptive phrase that represents a single piece of informationvia a title string, an optional subtitle string, and optionally a set of badge icons. Phrases may be queried for arelated resource or component, what badges (if any) apply to the phrase, and — most importantly — a list ofchild phrases that provide further details.

Consider an example where we wish to present information about a model face. The face itself could be a phrasewhose title is the user-provided name of the face, whose subtitle might indicate whether the face is planar orcurved, that might have a badge showing the face’s color, another badge showing its visibility in a 3-d view,and whose child phrases could include details about the face such as (1) a list of edges bounding the face,(2) properties defined on the face such as user annotation, and (3) attributes associated with the face such asboundary conditions. Developers may wish all or none of this information to be editable.

Configuration information specifying how phrases should be arranged and what portions should be editable isheld in a View instance, since a view will hold the top of the phrase tree.

Besides views and descriptive phrases, there are 2 important presentation tools that SMTK provides in its view system:

Selection instances hold a map from persistent objects to an integer value representing the “level” or “type” of selec-tion that the object is participating in. For example, an object may be highlighted as a pointer hovers over it orselected more permanently. Different integer values indicate which (or both, if the integer is interpreted as a bitvector) of these types of selections an object belongs to.

AvailableOperators instances provide a list of editing operations that a user may perform. This list may vary basedon the workflow as well as the current selection.

The following sections discuss portions of the view system in depth.

1.11.2 Views

As mentioned in the previous section, views may show editable attribute resources or trees of descriptive phrases.Configuration information is different for each of these types.

1.11.2.1 Attribute views

This view information is used to configure qtBaseView instances. Views of an attribute resource may need to displaymany attributes, some of which may be created upon user input (i.e., by adding a new material or boundary condition).However, there must be one view marked as the top-level view for any given attribute resource. This view may havechild views that it uses to organize (1) fixed, one-per-simulation attribute instances as well as (2) attribute instancesthat may vary in number to fit the needs of the simulation.

1.11.2.2 Phrase views

These views appear in 2 types of widgets in SMTK: panels holding tree views (such as the resource panel) and widgetsfor selecting components or resources, where only a flat list is presented (such as the reference item widget).

1.11. SMTK’s View System 39

Page 46: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.11.3 Hierarchical Phrases

Descriptive phrase trees may be flat or deeply nested. They are flexible and may be configured to present the sameresources and components in many different ways, while accommodating changes to those resources and componentsin response to editing operations.

In order to deal with this complexity, the duties of phrases are split across several classes:

• Phrase models are responsible for determining which descriptive phrases belong at the root of the tree. Theyalso provide utilities used to

– watch for events that may change the tree and

– determine how to notify user interfaces of those changes in terms of deleted, added, re-ordered, and modi-fied phrases.

– mark each descriptive phrase with optional, clickable badge icons.

• Descriptive phrases are only responsible for storing child phrases and, optionally, a reference to a subphrasegenerator that can create or update the list of child phrases on demand. They also own a reference to anotherclass responsible for the phrase’s content (i.e., title, subtitle, and other related information).

• Subphrase generators create or update a list of child phrases when given a reference to a potential parent phrase.

• Phrase content classes own a reference to a persistent object and determine what about that object should bepresented (i.e., they determine the topic of the phrase). One content class may hold a model face and present theface’s name as the phrase title/topic, while another class may hold the same face but present one of the face’sproperties as its topic.

1.11.3.1 Phrase Models

Todo: Describe the base phrase model class

There are several phrase model subclasses:

ReferenceItemPhraseModel, which lists components available for use in a ReferenceItem. The top-level phrases itpresents are persistent objects that either are or may be added to a ReferenceItem that you provide to the phrasemodel during configuration. It is used by the qtReferenceItem class to present components that may be selectedby a user in order to populate some item.

ResourcePhraseModel, which lists resources matching a given set of filters at its top level. It is used by thepqSMTKResourcePanel class to present a list of resources that have been loaded.

ComponentPhraseModel, which lists components matching a given set of filters at its top level.

SelectionPhraseModel, which lists objects held by a Selection <smtk::view::Selection> (which you provide at con-figuration time). By default, it will list all selected objects, regardless of the selection value. However, you mayoptionally specify a bit mask so that only objects whose selection values match the mask are shown.

1.11.3.2 Phrase Content Types

Todo: Describe the base phrase content class and its children

40 Chapter 1. SMTK User’s Guide

Page 47: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.11.3.3 Subphrase Generators

Todo: Describe the base subphrase generator class and its children

1.11.3.4 Badges

Each phrase model owns a BadgeSet used to decorate phrases. User interfaces that present phrases can ask the badgeset for an array of Badges that apply to a given phrase. The returned array of badges will be ordered consistently. Eachbadge has an SVG string to use as an icon, an optional tool tip, and an “action” method used to perform some taskwhen users click on the badge.

1.12 SMTK’s Extensions

The core SMTK library has few dependencies on external projects. However there are external projects that SMTKcan either make use of or can be of use to. The extension directory in SMTK provides additional libraries thatintroduce dependencies on external projects but which provide additional functionality.

1.12.1 Qt

SMTK provides Qt classes that allow users to edit attributes and inspect model and mesh resources.

1.12.2 Visualization Tool Kit

SMTK provides classes that act as VTK sources for model and mesh geometry, allowing visualization of models.

1.12.3 ParaView

SMTK provides ParaView plugins that, in concert with the VTK extensions, allow users to load models and meshesin ParaView; perform selections and filtering on model entities; run operations on models; and set attribute values byinteracting with 3-D widgets. These plugins form the core of the ModelBuilder application (version 6 and later).

1.12.3.1 Anatomy of ParaView

In order to use SMTK within ParaView, it is important to understand some of ParaView’s design. A core premise ofParaView is that the user interface will frequently be a separate process from rendering and I/O tasks, as these must berun in a distributed-memory parallel environment. Thus, ParaView has a client process and 1 or more server processes.Even when running in serial (i.e., non-parallel) mode, ParaView makes a distinction between tasks run on the clientand the server(s).

ParaView’s design has the client create and manage objects on the server. Nearly all objects on the server are subclassesof vtkObject and thus can be managed using wrappings created by VTK (similar to Python wrappers). These wrappersare called client-server wrappers and allow ParaView to serialize, deserialize, and remotely invoke methods on server-side objects.

Nearly all objects on the server have a matching instance on each server process. For example, if the client creates afile-reader and an actor to display data from the file, it will instruct each server to create a reader and an actor; and

1.12. SMTK’s Extensions 41

Page 48: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

have each server attach the reader and actor — even though some of the servers’ readers may not have data for thatactor to display because the data is unevenly distributed.

This pattern simplifies the work the client must do, however it also means that server-side objects should rarely (ifever) (1) send signals to the client or (2) perform blocking operations based on their local data; the reason for this isthat, (1) if every server process sent a signal when an action was performed, a large

number of servers would quickly overwhelm the client and

(2) since each server process holds a different portion of the data, not every server process would block at the sametime which can lead to deadlocks and race conditions.

So, although there are infrequent exceptions, be aware that ParaView takes great care to initiate all actions on theclient, even when it seems that the server should do so.

1.12.3.2 Integration with SMTK

In ParaView, there are 3 types of objects that SMTK frequently interacts with:

• Subclasses of vtkObject which live on each server process and are “wrapped” by C++ code that allows remoteinvocation of their methods across the client-server (CS) connection each server maintains with either the rank-0 server or the client. Several SMTK classes have instances owned by a “wrapper” class that inherits fromvtkObject to make this communication possible.

• Subclasses of vtkSMProxy, which live on the client process. Subclasses specific to SMTK are only requiredwhen the client needs to expose methods to manage SMTK data on the server that cannot be handled by Par-aView’s client-server wrapping. For example, methods that take non-primitive objects, such as pointers toSMTK classes as input, since these methods cannot be CS-wrapped.

• Subclasses of pqProxy, which live on the client process and reference an instance of vtkSMKProxy (or itssubclasses). Subclasses specific to SMTK exist to expose Qt signals and slots related to SMTK. If Qt is notrequired, then you should subclass vtkSMProxy instead.

1.12.3.3 Plugins

Some notes about the plugins:

• the server directory (which holds source for the smtkPVServerExtPlugin plugin) is for code that can be builtwithout Qt and will reside — at least in part — on the server. Some client-side proxy classes (that do notuse Qt) whose counterparts reside on the server are also included in this plugin. This is where the model(and eventually mesh) sources and their representations reside. Note that the representations display the SMTKselection, not the ParaView selection, although the two selections are generally kept in sync. Besides dealingwith SMTK selections in a consistent way, the model representation uses a glyph mapper to draw instanceprototype geometry at all instance placement points.

• the appcomponents plugin is dependent on the server plugin for the VTK-wrapped and CS-wrapped objects thatit creates proxies for on the client. Many of the components in this plugin are ParaView “behaviors.” A behavioris a QObject subclass that customizes the user interface of ParaView. In this case:

– the pqSMTKBehavior creates instances of vtkSMTKWrapper objects on the server and manages them viavtkSMSMTKWrapperProxy objects on the client. Each wrapper exposes an smtk::resource::Manager, ansmtk::operation::Manager, and an smtk::view::Selection to server-side VTK classes (such as the resourcereaders and representations).

– the pqSMTKSelectionFilterBehavior adds a toolbar to ParaView allowing users to specify what types ofresource components they want to select. It then installs a filter onto an SMTK selection manager to forcethe selection to match the specification.

42 Chapter 1. SMTK User’s Guide

Page 49: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

– the pqSMTKResourcePanel class adds a panel to ParaView that shows the resources and componentsavailable.

– the pqSMTKColorByToolBar class adds a tool bar to ParaView that allows users to choose how modelentities should be colored (e.g., by their assigned color, by the assigned color of the volume they bound,by field values such as simulation results).

– the pqSMTKSubtractUI class is a singleton that provides methods for removing ParaView UI components(and restoring them if needed). Your plugin may call methods on it to customize the application for aparticular workflow. Note that many user interface components can only be removed after the event loophas started; if you want to disable components from within a plugin’s start up, you should use a QTimerto schedule calls to the UI subtractor once the event loop has started. Dock-widget panels in particularrequire approximately a ~1 second delay in order to be removed at application startup.

1.12.3.4 Lifecycle

Below are some examples of the way objects are managed in ParaView-based SMTK applications. These exampleshelp describe the communication patterns in ParaView, which are constrained by the assumption that data is distributedin parallel on 1 or more server processes. One unintuitive implication of this assumption is that almost all commu-nication begins on the client and moves to the server(s). This makes some things difficult since events on the servercannot result in client-side actions.

1. Plugin initialization. SMTK registers, via CMake, an autostart plugin. This plugin’s startup method creates aninstance of pqSMTKBehavior which listens for ParaView servers attaching to/detaching from the client. Whenone attaches, it directs ParaView’s pqObjectBuilder to create an instance of vtkSMTKWrapper on the serverand vtkSMSMTKWrapperProxy on the client. The plugin also registers (again via CMake macros) a pqProxysubclass named pqSMTKWrapper to be created whenever a vtkSMSMTKWrapperProxy is instantiated.

2. Reading an SMTK file. SMTK registers, via an XML configuration file, a VTK-based reader (vtkSMTKModel-Reader) for the files which outputs a multi-block dataset. ParaView’s file-open dialog then constructs instancesof the reader on the server as well as proxies (pqSMTKResource) on the client. The client proxies connect tothe resource manager and register the resource with the SMTK resource manager instances owned by the clientand server. (At this point, the client does not own a separate instance but instead uses the server’s.)

3. Displaying an SMTK model. When an SMTK model resource is read (as described above), ParaView createsvtkPVDataRepresentation objects (on the servers) and a vtkSMRepresentationProxy and a pqRepresentationinstance on the client for each view. Instead of creating a pqRepresentation, SMTK’s XML configuration tellsParaView to create a subclass named pqSMTKModelRepresentation. Similarly, on the server, vtkSMTKModel-Representation instances are created instead of vtkPVDataRepresentation instances. The vtkSMTKModelRep-resentation instance looks for an instance of vtkSMTKResourceManagerWrapper. If one exists, then it uses theSMTK selection owned by the resource manager when rendering.

1.12.3.5 Representations

In ParaView, each view that a user creates may display datasets in the pipeline via a representation. Formally, a repre-sentation is a vtkAlgorithm subclass that adapts data for rendering based on the type of view: a spreadsheet view usesa different algorithm to prepare data for display than a 3-D render-view. Besides adaptations for different view types,representations may adapt different types of input datasets. SMTK provides a representation, vtkSMTKResourceRep-resentation, that adapts models, meshes, and other resources (any that provide tessllation data on their components)for display in 3-D render views.

1.12.3.6 Integrating ParaView and SMTK Selection

ParaView/VTK and SMTK have different models of selection:

1.12. SMTK’s Extensions 43

Page 50: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

• ParaView and VTK represent selections as a tree of selection nodes, each of which may use different criteria(such as IDs, frustum bounds, or field data thresholds) to select points or cells. The nodes of the tree are thencombined using boolean set-theoretic operations. The result is a set that may contain points and cells (but isusually either points or cells, not both). ParaView has a global, application-wide selection.

• SMTK represents a selection as a map (not a set) from persistent objects (usually components) to integer values.The integer values are usually treated as bit vectors — each bit in the value is reserved for a different purpose. Inmodelbuilder, we currently use bit 0 for the “primary” selection and bit 1 to indicate a “hover” or “secondary”selection. SMTK allows multiple instances of smtk::view::Selection, but the ParaView plugins that SMTKprovides create a single instance for use on each ParaView server in order to harmonize with ParaView’s globalselection. This single instance is owned by the vtkSMTKWrapper object on each server.

Because these are very different models, some care must be taken when selections are made. What follows is adescription of how selections are handled:

• SMTK resource representations render their data using only SMTK selections; they ignore the ParaView/VTKselection inputs that are provided. This is done in order to allow the different integer values in SMTK’s selectionto affect how components are rendered.

• When a user creates a selection in ParaView’s render window (or with ParaView’s other tools such as the FindData dialog), the VTK selection object is translated into an SMTK selection which replaces whatever value waspreviously present as SMTK’s selection.

• Also, user selections in ParaView are _filtered_ selections; this means that components indicated by VTK’sselection may not be directly added to SMTK’s selection but instead may suggest related components for se-lection. This is done so that users can click on rendered faces but select the volume contained by the faceswhen the workflow requires a volume. Other suggestions are possible as well (e.g., choosing an entire groupwhen a group member is selected, choosing an associated attribute when an associated component is selected).The pqSMTKSelectionFilterBehavior class provides a toolbar for users and workflows to adjust what filteringis performed.

• When SMTK widgets change the SMTK selection, ParaView views containing SMTK representations shouldbe re-rendered so that the updated selection is presented graphically.

Selection Translation

Because different resource types (e.g., mesh and model) may need to interpret VTK selection nodes differently, SMTKuses operations to translate VTK selections into SMTK selections. The process is initiated on ParaView’s client bythe vtkSMTKEncodeSelection class. This class inherits a ParaView class (vtkPVEncodeSelectionForServer) used totranslate VTK selections on the client into a set of selection objects to be sent to each server on which some portion ofthe selected data resides. SMTK’s application-components plugin registers a vtkObjectFactory override so that whenParaView’s selection changes and ParaView asks for a new instance of vtkPVEncodeSelectionForServer, an instanceof vtkSMTKEncodeSelection is provided instead.

So, each time a selection is made, vtkSMTKEncodeSelection is instantiated and its sole virtual method is called.This method invokes the parent method but also introspects the selection object passed to it before it is modified.When it finds SMTK representations, it loops over operations in the VTKSelectionResponderGroup of operations thatcan be associated to the representation’s resource until it finds one that succeeds, indicating it was able to parse theVTK selection and modify the SMTK selection accordingly. All operations in the VTKSelectionResponderGroup areexpected to be subclasses of RespondToVTKSelection. These operations should always modify the selection withoutnotifying observers (see the documentation for modifySelection for how to do this) so that a single signal can be sentto selection-observers after all operations have completed on all the affected resource selections.

The RespondToVTKSelection operation provides block-selection translation for any resource with tessellated orglyphed data.

44 Chapter 1. SMTK User’s Guide

Page 51: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.12.3.7 Panels

SMTK provides several panels for use in ParaView-based applications

• a resource tree panel that displays a configurable hierarchy of resources and their components.

• an attribute panel that displays and edits attribute resources.

• an operation panel that displays and edits operation parameters.

1.12.3.8 Widgets

SMTK provides special widgets for interacting with model and mesh resources inside ParaView. These qtItem sub-classes may be used by specifying them in an attribute’s View configuration.

Design

Because SMTK is using ParaView, which is an application built on top of VTK, designing new 3-d widgets for usewith SMTK involves several API boundaries and thus several classes.

VTK. The basic concept of a 3-d widget is implemented in VTK without any notion of a matching Qt user interface.VTK provides 2 classes that new widgets should inherit: a representation class which is responsible for gener-ating renderable data to provide the visual representation of the widget and a widget class, which is responsiblefor user interaction related to the visual appearance (i.e., translating mouse hover, click, drag, and even keyboardevents into parameter changes that affect the visual representation). For some widgets, a third class is used tohold parameters that define an implicit function which can be used to model related geometry.

A good example of these classes are vtkConeRepresentation and vtkConeWidget. The implicit function repre-senting the cone being modeled is the vtkImplicitConeFrustum class. Frequently, these implicit functions areused to select cells, trim geometry, or perform other editing actions as the user interacts with the widget.

ParaView. ParaView uses VTK 3-d widgets. These widgets are rendered on the server but must respond to userinteraction that takes place on a desktop client. ParaView uses its client-server protocol to distribute mouseand keyboard events to the server and its client-server property system to retrieve updated parameters from theserver as needed (e.g., a sphere’s center and radius might be updated by a VTK widget+representation on theserver and then transferred to the client via two DoubleVector properties). ParaView’s widgets have both a 3-dappearance (obtained via VTK) and a 2-d Qt user interface that allows users to inspect and enter exact numericvalues when needed. ParaView widgets inherit the pqInteractivePropertyWidget class.

A good example of a ParaView widget class is pqConePropertyWidget, which uses the VTK classes above,but indirectly via server-manager XML in the plugin named smtkPVServerExtPlugin; when a pqConeProper-tyWidget is created on the client process, it constructs a proxy object named ConeWidgetRepresentation. Thisproxy object has subproxies named ConeWidget and ConeRepresentation that are backed on the server processby the VTK classes above. When users interact with the VTK classes in the render window, changes to thoseclasses are mapped to ParaView server-manager proxy property objects and notifications are sent to the clientthat properties are updated. Similarly, changes on the client change proxy properties that are transmitted to theserver and used to update the VTK classes.

SMTK. SMTK maps ParaView properties back and forth between SMTK attribute items. For example, the conewidget in ParaView requires properties for a generic truncated cone (two points — to determine the axis —and two radii — to determine the radius perpendicular to that axis at each endpoint). However, an SMTK at-tribute may only want to accept cylinders (a single radius for each point). The SMTK qtItem subclass mapsbetween the items available in the attribute and the properties in ParaView. Each time a ParaView property isset, the updateItemFromWidgetInternal method is invoked. Likewise, when the attribute is modified externally(for example, by a Signal operation being performed), the updateWidgetFromItemInternal method is invoked.

1.12. SMTK’s Extensions 45

Page 52: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

These methods both generally invoke a protected method specific to each widget to fetch items from the at-tribute. Based on the items available, these two methods synchronize values between SMTK attribute items andParaView properties.

A good example of an SMTK item widget is pqSMTKConeItemWidget.

Gallery

SMTK’s existing widgets are listed below with instructions for their use.

Point

The pqSMTKPointItemWidget can be attached to an SMTK Double item with 3 entries: the x, y, and z coordinatesof a point in world coordinates. When the widget is in its fully enabled state, the ‘P’ and ‘Ctrl+P’ (or ‘Cmd+P’ onmacos) keys may be used to pick point placement in the render window (on any fully-opaque surface underneath themouse pointer when the key is pressed). The latter version will choose the nearest vertex in the dataset rather than thepoint on the pixel directly under the pointer.

Fig. 4: The Qt widget (left) and 3-D widget (right) for editing point locations.

Line

The pqSMTKLineItemWidget can be attached to an SMTK Group item 2 Double children holding 3 values each.Each Double item specifies one line endpoint’s coordinates. In the item’s view configuration, specify Point1 andPoint2 attributes naming the names of the Group’s children that represent these points.

Fig. 5: The Qt widget (left) and 3-D widget (right) for editing line segments.

Plane

The pqSMTKPlaneItemWidget can be attached to an SMTK Group item with 2 Double children holding 3 valueseach: one specifying an Origin point and the other specifying a Normal vector.

46 Chapter 1. SMTK User’s Guide

Page 53: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Fig. 6: The Qt widget (left) and 3-D widget (right) for editing (unbounded) planes.

Box

The pqSMTKBoxItemWidget can be attached to an SMTK Double item with 6 entries in the order (xmin, xmax, ymin,ymax, zmin, zmaz). It can also be attached to a group with Min, Max, and optionally Angles items representing twocorner points in space and a set of 3 Tait-Bryan rotation angles. Finally, the box widget also accepts a group containinga Center, Deltas, and optionally Angles items representing the box centroid, lengths along 3 orthogonal axes from thecenter to each face of the box, and rotation angles as above.

Fig. 7: The Qt widget (left) and 3-D widget (right) for editing boxes.

Cone (and Cylinder)

The pqSMTKConeItemWidget can be attached to an SMTK Group holding two Double items, each with 3 values,representing the bottom and top points of a truncated cone; plus two more Double items, each with a single valuerepresenting the radius at each point. Alternately, a single radius Double item may be provided to accept only cylinders.

Fig. 8: The Qt widget (left) and 3-D widget (right) for editing truncated cones.

1.12. SMTK’s Extensions 47

Page 54: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Sphere

The pqSMTKSphereItemWidget can be attached to an SMTK Group holding a Double item with 3 values representingthe Center of a sphere and another Double item with a single value representing the Radius.

Fig. 9: The Qt widget (left) and 3-D widget (right) for editing spheres.

Spline

The pqSMTKSplineItemWidget may represent a polyline or a cardinal spline, depending on whether its View config-uration has a Polyline attribute set to true or not. The widget must be attached to an SMTK Group holding a Doubleitem with 6 or more values representing the 3-D coordinates of handle points and an Int item interpreted as a booleanthat indicates whether the curve should be a closed loop or an open segment.

Fig. 10: The Qt widget (left) and 3-D widget (right) for editing polyline and spline curves.

1.13 SMTK’s Workflow System

SMTK’s workflow system is aimed at providing guidance to users on tasks required to complete the simulation prepa-ration process.

Simulations can require input from many people with different skill sets. People with backgrounds in engineering;physical modeling; geometric discretization; numerical analysis; visualization and data analysis; statistics; and projectmanagement may all be involved, each with different tasks to complete. SMTK accommodates this range of interestsand tasks by providing applications with ways to prompt users, especially infrequent or inexpert users, with suggestedactions.

1.13.1 Key Concepts

Internally, SMTK represents a workflow as a directed acyclic graph. Nodes in the graph may be

48 Chapter 1. SMTK User’s Guide

Page 55: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

• actions to take;

• conditions which must be met; or

• choices between acceptable actions or conditions.

Edges in the graph indicate dependencies between nodes.

Presenting a complete task DAG would be confusing to many users. Instead, we use SMTK’s view presentation modelto allow applications to tailor what is shown based on the current state.

1.14 SMTK’s Bindings

SMTK is written in C++ and uses pybind11 to generate python bindings.

1.14.1 Generating pybind11 bindings

SMTK’s pybind11 bindings are generated via python scripts that use pygccxml to construct a C++ header file corre-sponding to each header file in SMTK, and a C++ source file for each namespace in SMTK. Generally, python modulesare a reflection of C++ namespaces (which are generally contained within a subdirectory). The generated pybind11C++ files for each module are in the pybind subdirectory of the module.

To generate a C++ header file for a new SMTK class, use [smtk-root-directory]/utilities/python/cpp_to_pybind11.pywith the appropriate arguments for the header file, project root directory, include directories(e.g. -I "[smtk-build-directory] [smtk-root-directory]/thirdparty/cJSON path/to/vtk/include") and generated file prefix; the module’s binding source file (also located in the pybind subdirectoryof the module) must then be updated to call the functions defined in the generated header file. To generate all of the C++headers and the module C++ source file for a namespace at once, use [smtk-root-directory]/utilities/python/generate_pybind11_module.py with the appropriate arguments for the module directory, projectroot directory and include directories.

The generated bindings should be treated as a starting point for customization to create a more pythonic interface.

1.14.2 Customizing pybind11 bindings

One common shortcoming of the generated bindings is that templated methods are not wrapped. Sometimes, a tem-plated method is the only way to set or get the state of a C++ class instance and the template is used so that thevarious STL containers can be used. Consider the method smtk::resource::SelectionManager::modifySelection whichis templated on the type of container holding objects to replace, be added to, or be removed from the selection.Without wrapping this method, it is impossible to change the selection from Python. By adding this definition tosmtk/resource/pybind11/PybindSelectionManager.h:

PySharedPtrClass< smtk::resource::SelectionManager > instance(m, "SelectionManager");instance

.def("modifySelection",(bool (smtk::resource::SelectionManager::*)(const ::std::vector<smtk::resource::Component::Ptr,std::allocator<smtk::resource::Component::Ptr> >&,

const std::string&,int,smtk::resource::SelectionAction))

&smtk::resource::SelectionManager::modifySelection)

1.14. SMTK’s Bindings 49

Page 56: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

we cast the function pointer to be wrapped to a particular template type that we know pybind can handle (a vectorof shared pointers to components). While these casts of member functions can be verbose and sometimes difficult toread, they make it easy to expose templated member functions to pybind without changing the C++ class declaration,which is very desirable.

Todo: Explain how to make this robust against re-runs of the script that generates bindings.

1.15 SMTK’s Plugin System

SMTK’s functionality can be extended by consuming projects via the generation of plugins.

1.15.1 Plugins

SMTK plugins are extensions of ParaView plugins that allow for the definition of SMTK managers and the automaticregistration of components to these managers. They are created using the CMake function “add_smtk_plugin”, whichrequires the developer to explicitly list a registration class “known as a Registrar” and a list of SMTK manager typesto which the plugin registers. SMTK plugins can be introduced to a ParaView-based application in several ways. Theconsuming project can

1) list the plugins in a configuration file that is subsequently read at runtime, deferring the inclusion of plugins to theapplication’s runtime. This approach requires plugins to reside in certain locations that the application is expected tolook, but facilitates the presentation of a plugin to the user without automatically loading the plugin. For this approach,a consuming project can call “generate_smtk_plugin_config_file” to convert the list of smtk plugin targets (which canbe a part of the project or imported from another project) described by the global property “SMTK_PLUGINS” into aconfiguration file. The consuming project can also

2) directly link plugins into the application. This approach pushes the requirement of locating plugins to be a build-time dependency, which can be advantageous for packaging. Plugins that are directly linked to an application cannotbe disabled, however (i.e. the target property ENABLED_BY_DEFAULT is ignored, as it is true for all plugins).To use this approach, a consuming project can call “generate_smtk_plugin_library” to to use the list of smtk plu-gin targets (which can be a part of the project or imported from another project) described by the global property“SMTK_PLUGINS” to generate a library against which the application can link to directly incorporate the associatedplugins.

Managers are introduced to SMTK by registering them with the instance of smtk::common::Managers. Upon registra-tion, the singleton instance of smtk::plugin::Manager can be used to register additional plugins to the newly createdmanager. See smtk/resource/Registrar.cxx for an example of introducing a manager.

1.16 Administering SMTK

Previous sections covered the concepts and tools for using SMTK. This section is for system administrators who wishto make SMTK available to users

• as a Python module and command-line utilities for end users of SMTK,

• as a library for people developing SMTK-based applications, and/or

• as a remote model and mesh server for end users and applications.

50 Chapter 1. SMTK User’s Guide

Page 57: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.16.1 End-user tool installation

This type of installation should be as simple as downloading a binary package of SMTK and clicking install.

Todo: Expand on details of installation and configuration.

1.16.2 Developer installation

In addition to the binary installer, there should also be a development package that contains header and configurationfiles needed to build C++ applications using SMTK. Install this the same way you installed the binary above.

You can also download the source code from the git repostory and follow the instructions for building and installingSMTK in the toplevel ReadMe.md file.

Todo: Expand on details of installation and configuration.

1.16.3 Configuration as a modeling and meshing server

SMTK uses Remus to start model and mesh workers. In order for SMTK to discover available workers, you mustplace Remus worker files somewhere that SMTK is configured to search for them. These worker files identify theexecutable to run when a user requests a modeling or meshing operation to be performed. Their format is coveredfurther below, but first we focus on how the files are discovered.

1.16.3.1 Worker file search paths

The default locations that SMTK searches for these worker files varies by operating system:

Linux SMTK searches the current working directory of the process, followed by the var/smtk/workers subdi-rectory of the toplevel installation directory. For example, if SMTK is installed into /usr with the worker at/usr/bin/smtk-model-worker, then it will search /usr/var/smtk/workers.

If the SMTK_WORKER_DIR environment variable is set to a valid path, then it is searched as well.

Mac OS X SMTK searches the current working directory of the process, followed by the var/workers subdirec-tory of the toplevel installation directory if SMTK is not part of a bundle. For example, if SMTK is installedinto /usr with the worker at /usr/bin/smtk-model-worker, then it will search /usr/var/smtk/workers.

If an application built with SMTK is part of a bundle (such as an app), then SMTK will search the Contents/Resources/workers directory of the bundle.

If the SMTK_WORKER_DIR environment variable is set to a valid path, then it is searched as well.

Windows SMTK searches the current working directory of the process followed by the directory containing theprocess executable (when provided to SMTK by the application).

If the SMTK_WORKER_DIR environment variable is set to a valid path, then it is searched as well.

1.16. Administering SMTK 51

Page 58: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.16.3.2 Creating a Remus worker file for solid modeling

When SMTK is built with Remus support enabled, it will include a command-line utility namedsmtk-model-worker. This program can be run manually or directly by SMTK in order to perform modelingoperations in a different process. It is also the program you can run to generate a worker file that makes it discoverableto SMTK for direct use. You can run

smtk-model-worker -help

to obtain reference information on the command-line arguments. It will also print a list of available modeling kernels.

Each model worker exposes a single modeling kernel (via smtk::session::remote::Session on the client, which talks toa RemusRPCWorker in the worker process). Normally, the model worker executable expects to be given the followingcommand-line arguments:

• A Remus server to connect to as its first argument, formatted as a URL (e.g., tcp://cadserver.kitware.com:50510).

• A solid modeling kernel to advertise (e.g., -kernel=cgm).

• A default modeling engine for the kernel to use (e.g., -engine=OpenCascade).

• A Remus worker file to read (when invoked without -generate) or write (when invoked with -generate).

• A directory in the filesystem to make available to users for reading and writing CAD model files (e.g., -root=/usr/local/var/smtk/data). The root directory is not made available to end users for security purposes;all paths are relative to the root directory. SMTK does not currently prevent access to other portions of thefilesystem but it will in the future.

• A “site name” describing the combination of host and/or filesystem made available to SMTK by the modelworker. This label is presented to end users by applications so that users can differentiate between workersproviding the same modeling kernels but on different machines.

• A Remus worker file to read or write (e.g., -rwfile=/usr/local/var/smtk/workers/cgm-OCC.rw).

If you pass the -generate option to the model worker, then it will generate a model worker file which you can thencustomize. When you generate a model worker file, two files are normally written: the first, specified by the -rwfileargument is the actual Remus worker file and is formatted as a JSON object. The second has the same filename with a.requirements suffix appended and is formatted as an XML attribute resource describing the modeling operationsavailable.

You should generate a separate Remus worker file for each combination of modeling kernel, engine, and root directoryyou wish to make available. Once these files have been generated, you can edit the worker file and change them to suityour site’s needs. You may specifically wish to change the WorkerName setting to be more descriptive. Be carefulwhen editing the Tag data as it is used by SMTK to decide which engine and kernel combination may load a given file.

1.17 Contributing to SMTK

Contents

• Contributing to SMTK

The first step to contributing to SMTK is to obtain the source code and build it. The top-level ReadMe.md filein the source code includes instructions for building SMTK. The rest of this section discusses how the source anddocumentation are organized and provides guidelines for how to match the SMTK style.

52 Chapter 1. SMTK User’s Guide

Page 59: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1.17.1 Source code organization

To a first approximation, SMTK’s directory structure mirrors the namespaces used: classes in thesmtk::attribute namespace are mostly found in the smtk/attribute directory. Exceptions occur whereclasses that belong in a namespace depend on third-party libraries that should not be linked to SMTK’s core library.For example, Qt widgets for attributes are in smtk/extensions/qt, not in smtk/attribute because theydepend on Qt, which is optional when building SMTK (so that, for instance, solid modeling kernels like Cubit may besupported without issue).

With that in mind:

• smtk — this directory contains all of the source code for SMTK libraries and tests

– common — source for classes used throughout the smtkCore library

– resource — SMTK’s Resource System defines base resources (files) and components used elsewhere

– attribute — source for SMTK’s Attribute Resource in the smtkCore library

– model — source for SMTK’s Geometric Model Resource in the smtkCore library

– mesh — source for SMTK’s Mesh Resource in the smtkCore library

– operation — SMTK’s Operation System provides asynchronous operations that act on resources

– simulation — aids to exporting simulation input decks in the smtkCore library

– io — file and string I/O in the smtkCore library, a mix of XML and JSON

– view — source for providing views (user presentations) of resources in the smtkCore library

– session — source for additional libraries that session solid modeling kernels into SMTK

– extensions — source for additional libraries that expose SMTK to other software

* qt — widgets that allow presentation and editing of SMTK models and attributes

* vtk — VTK sources for displaying tessellations of model faces, edges, and vertices

* paraview - user interface components that embed SMTK into branded ParaView applications

• thirdparty

– cJSON — used to serialize geometric model information

– pugiXML — used to serialize attribute resources

• utilities — scripts to aid in the development of SMTK

Inside smtk/, subdirectories, there are testing/ directories that hold python/ and cxx/ directories for Pythonand C++ tests, respectively. These are discussed more in smtk-testing-sys.

1.17.2 Extending SMTK

As with all software, it is important to understand where functionality you wish to add belongs: in your project, inSMTK’s core library, or in an upstream dependency of SMTK.

The tutorials provide in-depth guides on how to extend SMTK in certain obvious directions,

• Writing an attribute resource template file to represent a solver’s input format.

• Writing an exporter to support a new solver’s input format.

• Adding a new solid-modeling operator

• Bridging SMTK to a new solid-modeling kernel

1.17. Contributing to SMTK 53

Page 60: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

These tasks are all examples of projects that might use SMTK as a dependency but not alter SMTK itself. On theother hand, if you are attempting to provide functionality that (a) does not introduce dependencies on new third-partylibraries; (b) will be useful to most projects that use SMTK; and (c) cannot be easily be factored into a separatepackage, then it may be best to contribute these changes to SMTK itself. In that case, the rest of this section discusseshow SMTK should be modified and changes submitted for consideration.

1.17.3 Exposing SMTK for use in external projects

SMTK generates a file named SMTKConfig.cmake that allows other projects to find and use SMTK. This file isinstalled to $CMAKE_INSTALL_PREFIX/lib/cmake/SMTK/. External projects can add SMTK with

find_package(SMTK)

Then, when building external projects, set CMake’s SMTK_DIR to the directory containing SMTKConfig.cmake.Note that you may point external projects to the top level of an SMTK build directory or an install tree’s lib/cmake/SMTK directory; both contain an SMTKConfig.cmake file suitable for use by external projects. The formeris suitable for development, since you may be modifying both SMTK and a project that depends on it — having tore-install SMTK after each change becomes tedious. The latter is suitable for creating packages and distributingsoftware.

If you add a new dependency to SMTK, CMake/smtkConfig.cmake.in (which is used to create SMTKConfig.cmake) should be configured to find the dependent package so that consumers of SMTK have access to it withoutadditional work.

If you add a new option to SMTK, it should be exposed in CMake/Options.h.in.

1.17.4 Code style

• No tabs or trailing whitespace are allowed.

• Indent blocks by 2 spaces.

• Class names should be camel case, starting with an uppercase.

• Class member variables should start with m_ or s_ for per-instance or class-static variables, respectively.

• Class methods should be camel case starting with a lowercase character (except acronyms which should beall-uppercase).

• Use shared pointers and a static create() method for classes that own significant storage or must be passedby reference to their superclass.

1.17.5 Documentation style

There are two types of documentation in SMTK: Doxygen documentation written as comments in C++ code andSphinx documentation written in reStructuredText files (and optionally Python documentation strings). The former isused to create reference documentation; the latter is used for the user’s guide and tutorials.

The following rules apply to writing documentation:

• Header files should contain the Doxygen documentation for the class as a whole plus any enums declared outsideclasses, however:

• Implementation files should contain the Doxygen documentation for class methods. This keeps the documen-tation next to the implementation (making it easier to keep up-to-date). It also makes the headers easier toread.

54 Chapter 1. SMTK User’s Guide

Page 61: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

• If a class provides high-level functionality, consider writing some user-guide-style documentation in the User’sGuide (in doc/userguide.rst) or a tutorial (in doc/tutorials/). Tutorials should include a workingexample that is run as a CTest test. The code in the example should be referenced indirectly by the tutorial sothat the the exact code that is tested appears as the text of the tutorial.

• In reStructuredText documents, you should use the doxylinks module to link to the Doxygen documentationwhen appropriate. Examples: :smtk:`UUID` produces this link: UUID while the :smtk:`Resource<smtk::attribute::Resource>` variant can produce links (Resource in this case) whose text variesfrom the classname or whose classnames are ambiguous because of namespaces. The leading :smtk: namesthe tag file holding the class and function definitions; other third-party-library tag files may be added in thefuture.

You will be tempted to make every word that is a classname into a Doxygen link; do not do this. Instead, providea Doxygen link at the first occurrence of the classname in a topic’s discussion — or at most in a few key places.Otherwise the documentation becomes difficult to read due to conflicting text styles.

• In reStructuredText, when you wish to show code in-line but it is inappropriate to link to Doxygen documenta-tion, use the :cxx: role for C++ (e.g., if (foo)), the :file: role for paths to files (e.g., doc/index.rst), and so on. See the documentation for roles in reStructuredText for more information.

• Note that the user’s guide and tutorials are both included in the top-level doc/index.rst file parsed bySphinx. Several extensions to Sphinx are used and these are configured in doc/conf.py.

To get started documenting your code, you should at least have doxygen and graphviz installed. These are availableusing Homebrew on Mac OS X, your Linux distribution’s package manager, or by binary installer from the sourcemaintainer on Windows.

Additionally there are a number of Python packages that provide Sphinx, docutils, and other packages required togenerate the user’s guide. These packages can all be installed with pip:

# The basic utilities for processing the user's guide:sudo pip install docutilssudo pip install Sphinx# For linking to external Doxygen docs:sudo pip install sphinxcontrib-doxylink# For creating inline class docs from Doxygen XML:sudo pip install breathe# For the default theme:sudo pip install sphinx-rtd-theme# For syntax highlighting:sudo pip install Pygments# For activity diagrams:sudo pip install sphinxcontrib-actdiag

If you are unfamiliar with the documentation packages here, see these links for examples of their use (or use SMTKby example):

• Sphinx Table of Contents

• Sphinx conf.py configuration

• reStructuredText primer

• Doxygen commands

1.17.6 Testing

Testing is important to keep SMTK functioning as development continues. All new functionality added to SMTKshould include tests. When you are preparing to write tests, consider the following

1.17. Contributing to SMTK 55

Page 62: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

• Unit tests should be present to provide coverage of new classes and methods.

• Build-failure tests provide coverage for template metaprogramming by attempting to build code that is expectedto cause static assertions or other compilation failures.

• Integration tests should be present to ensure features work in combination with one another as intended; thesetests should model how users are expected to exercise SMTK in a typical workflow.

• Regression tests should be added when users discover a problem in functionality not previously tested and whichfurther development may reintroduce.

• Contract tests should be added for downstream projects (i.e., those which depend on SMTK) which SMTKshould not break through API or behavioral changes. A contract test works by cloning, building, and testingan external project; if the external project’s tests all succeed, then the contract test succeeds. Otherwise, thecontract test fails.

1.17.6.1 Unit tests

SMTK provides a CMake macro named smtk_unit_tests that you should use to create unit tests. This macrowill create a single executable that runs tests in multiple source files; this reduces the number of executables in SMTKand makes tests more uniform. Because there is a single executable, you should make your test a function whose namematches the name of your source file (e.g., int TestResource(int, const char* [])) rather than intmain(int, const char* []). The CMake macro also allows a LABEL to be assigned to each of the tests inthe executable; this label can be used during development to run a subset of tests and during integration to identifyareas related to test failures or timings in CDash.

1.17.6.2 Build-failure tests

Build-failure tests verify that code which is expected to cause a compiler error does actually cause an error. A CMakemacro named smtk_build_failure_tests is provided in CMake/SMTKTestingMacros.cmake. Thismacro generates tests that succeed when they fail to compile code you provide, as a way to improve coverage oftemplate metaprogramming code.

You can attempt to build the same source file multiple times; each time, a compiler macro namedSMTK_FAILURE_INDEX is assigned an increasing integer so you can change what code is tested. Consider thisexample

int main(){#if SMTK_FAILURE_INDEX < 1

static_assert(false, "Failure mode 1");#elif SMTK_FAILURE_INDEX < 2

static_assert(false, "Failure mode 2");//...

#endif

return 0;}

If this file was named simple.cxx, you could add tests for it with

smtk_build_failure_tests(LABEL SomeLabelTESTSsimple.cxx 2

(continues on next page)

56 Chapter 1. SMTK User’s Guide

Page 63: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

(continued from previous page)

LIBRARIES smtkCore)

This would create 2 tests that each try to compile simple.cxx with different SMTK_FAILURE_INDEX values (0 and 1).

1.17.6.3 Contract tests

Contract tests can be added by appending a URL to the SMTK_PLUGIN_CONTRACT_FILE_URLS CMake variable.You can see an example of this in SMTK’s top-level CMakeLists.txt:

1 if (SMTK_ENABLE_PARAVIEW_SUPPORT)2 set(local_url_prefix "file://")3 if (WIN32)4 string(APPEND local_url_prefix "/")5 endif()6 list(APPEND SMTK_PLUGIN_CONTRACT_FILE_URLS7 "${local_url_prefix}${CMAKE_CURRENT_SOURCE_DIR}/CMake/resource-manager-state.

→˓cmake")8 endif()

Each URL listed in the CMake variable must be a CMake script; typically, this script will declare a new projectconsisting of an external project dependent on SMTK.

1 # This file is provided with SMTK as an example of how to configure a plugin2 # contract file. In general, SMTK should not contain these files. Instead, the3 # dashboard computer that runs SMTK tests should be passed a list of URLs for4 # plugin contract test files during its configuration.5

6 cmake_minimum_required(VERSION 2.8)7 project(resource-manager-state)8

9 include(ExternalProject)10

11 ExternalProject_Add(resource-manager-state12 GIT_REPOSITORY "https://gitlab.kitware.com/cmb/plugins/read-and-write-resource-

→˓manager-state.git"13 GIT_TAG "origin/master"14 PREFIX plugin15 STAMP_DIR plugin/stamp16 SOURCE_DIR plugin/src17 BINARY_DIR plugin/build18 CMAKE_ARGS19 -DBUILD_SHARED_LIBS:BOOL=${BUILD_SHARED_LIBS}20 -DENABLE_TESTING=ON21 -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}22 -Dsmtk_DIR=${smtk_DIR}23 ${response_file}24 INSTALL_COMMAND ""25 TEST_BEFORE_INSTALL True26 )

When the script is run, the external project’s source is downloaded, the project configured, and tests are run. If theyall complete with success, then the contract test succeeds.

This pattern of appending URLs was chosen so that machines used to test merge requests which happen to have accessto closed-source downstream projects could be configured with additional URLs to contract tests. That way, even

1.17. Contributing to SMTK 57

Page 64: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

closed-source downstreams can cause test failures in SMTK; this informs developers of SMTK merge requests thatadditional work may be required on downstream projects before the merge can succeed.

1.17.7 To-do list

Finally, if you are looking for a way to contribute, helping with the documentation would be great. A list of incompletedocumentation (or incomplete features) is below. You can also look on the SMTK issue tracker for things to do.

Todo: Expand on details of installation and configuration.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/administration.rst,line 27.)

Todo: Expand on details of installation and configuration.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/administration.rst,line 41.)

Todo: Describe attributes and how they are serialized

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/attribute/file-syntax.rst, line 506.)

Todo: Describe file items and how they are serialized

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/attribute/file-syntax.rst, line 520.)

Todo: Describe group items and how they are serialized

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/attribute/file-syntax.rst, line 526.)

Todo: Describe integer items and how they are serialized

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/attribute/file-syntax.rst, line 532.)

Todo: Describe string items and how they are serialized

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/attribute/file-syntax.rst, line 538.)

Todo: Describe attribute reference items and how they are serialized

58 Chapter 1. SMTK User’s Guide

Page 65: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/attribute/file-syntax.rst, line 544.)

Todo: Describe “void” items and how they are serialized

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/attribute/file-syntax.rst, line 560.)

Todo: Describe root views and how they are serialized

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/attribute/file-syntax.rst, line 612.)

Todo: Describe <InstancedAttributes>, <Attributes>, . . . elements here.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/attribute/file-syntax.rst, line 629.)

Todo: Describe <ItemsViews> children

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/attribute/file-syntax.rst, line 642.)

Todo: Explain how to make this robust against re-runs of the script that generates bindings.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/bindings/customizing-pybind11-bindings.rst, line 38.)

Todo: Create runtime-configurable classes (ProgrammableResource, ProgrammableNode, ProgrammableArc) thatcan be python-wrapped and configured via a JSON serialization.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/graph/concepts.rst,line 28.)

Todo: Describe minimal subclass

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/graph/concepts.rst,line 49.)

Todo: Describe use of struct

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/graph/concepts.rst,line 69.)

1.17. Contributing to SMTK 59

Page 66: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Todo: Describe filter/search syntax

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/graph/concepts.rst,line 74.)

Todo: Describe SMTK’s auto-init macros.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/model/operators.rst,line 16.)

Todo: Describe what blocks and sets are

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/model/session-exodus.rst, line 10.)

Todo: Describe how blocks and sets are mapped to models and groups

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/model/session-exodus.rst, line 11.)

Todo: Show simple example?

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/model/session-exodus.rst, line 12.)

Todo: Update how modeling sessions are exposed via plugins.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/model/sessions.rst,line 53.)

Todo: Discuss Remus and ParaView client/server sessions

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/model/sessions.rst,line 58.)

Todo: Describe SMTK’s auto-init macros.

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/operation/operators.rst,line 11.)

Todo: Describe the base phrase model class

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/view/phrases.rst,line 43.)

60 Chapter 1. SMTK User’s Guide

Page 67: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

Todo: Describe the base phrase content class and its children

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/view/phrases.rst,line 74.)

Todo: Describe the base subphrase generator class and its children

(The original entry is located in /home/docs/checkouts/readthedocs.org/user_builds/smtk/checkouts/latest/doc/userguide/view/phrases.rst,line 79.)

1.17. Contributing to SMTK 61

Page 68: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

62 Chapter 1. SMTK User’s Guide

Page 69: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

CHAPTER

TWO

TUTORIALS

While the user’s guide covers the operational theory of SMTK in a meaningful way, sometimes it helps to have a morepractical guide to getting a simple task done without reading the entire manual. These tutorials provide quick formulasfor simple tasks without requiring much theory.

2.1 First steps in C++

Contents

• First steps in C++

– Including SMTK headers and calling methods

– Compiling the example

To get started with SMTK, let’s create a project that does the bare minimum; we’ll just print the SMTK version numberand exit.

2.1.1 Including SMTK headers and calling methods

The code to do this just calls a static method on smtk::common::Version:

1 #include <iostream>2

3 #include "smtk/common/Version.h"4

5 int main()6 {7 std::cout << "Compiled with SMTK version " << smtk::common::Version::number() << "\n

→˓";8 return 0;9 }

All of SMTK’s headers are prefixed by “smtk,” and because the version number is useful across all of SMTK andnot just particular subsystems, it is put in the “common” directory. Usually — but not always — the subdirectoriesindicate the C++ namespace that a class lives in. Exceptions to this rule are classes in the extension directory, whichare grouped separately because they appear in other libraries that have additional dependencies.

63

Page 70: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

2.1.2 Compiling the example

To compile the program above, we need to link to SMTK’s main library, named smtkCore. The followingCMakeLists.txt will set up a project for us:

1 cmake_minimum_required(VERSION 3.5)2 project(smtk_version)3

4 find_package(smtk)5 add_executable(print_version print_version.cxx)6 target_link_libraries(print_version smtkCore)

The find_package directive tells CMake to find SMTK on your system and import its settings. SMTK providessettings in a file named SMTKConfig.cmake and it is usually stored in /usr/local/lib/cmake/SMTK onUnix and Mac OS X systems or C:\SMTK\lib\cmake\SMTK on Windows. When CMake asks for SMTK_DIR,you should provide it with the directory containing SMTKConfig.cmake.

Then, the target_link_libraries directive tells CMake not only to link to smtkCore, but also to add compilerdirectives to all source code in the executable specifying the location of header files. This directive also adds anytransitive dependencies of smtkCore to the print_version program.

2.2 First steps in Python

Contents

• First steps in Python

– Setup

– Problem Definition

– Simulation Preparation

To demonstrate the basic workflow in Python, we’ll cover how to:

• create attribute and model managers;

• create an attribute resource to hold simulation information;

• populate the attribute resource with definitions for a particular simulation run;

• generate an ensemble of input decks whose attributes use these definitions with different values as part of asensitivity study;

• load a geometric model that has side sets used to hold boundary conditions;

• relate the side sets to boundary condition attributes in the ensemble; and

• write an input deck for each entry in the ensemble.

Our running example will be a fluid mechanics problem where we run an ensemble of simulations to characterize thesensitivity of pump work to viscosity and inlet velocity at our expected operating conditions.

2.2.1 Setup

The first part of our script imports SMTK and creates managers:

64 Chapter 2. Tutorials

Page 71: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

1 import smtk2 from smtk import attribute3 from smtk import io4 from smtk import model5

6 ares = smtk.attribute.Resource.create()7 mmgr = smtk.model.Resource.create()8

This will almost always be the first thing your Python scripts do.

2.2.2 Problem Definition

Now that the environment is set up, we can define the attribute system that our simulation expects as its problemdefinition.

Everything in this entire section is usually replaced by creating an XML file describing the problem definition. How-ever, the purpose of this tutorial is to demonstrate how to implement your simulation workflow in Python and therecan be times when you wish to programmatically create a problem definition, or template file.

The first thing we do is create attribute Definitions for the basic types of simulation inputs we must provide:

1 bcDef = ares.createDefinition('boundary condition')2 icDef = ares.createDefinition('initial condition')3 matDef = ares.createDefinition('material properties')4

5 # Our material is defined by a viscosity6 viscosity = smtk.attribute.DoubleItemDefinition.New('viscosity')7 matDef.addItemDefinition(viscosity)

Once we’ve created the material definition, we can add all the individual properties required to specify a material.More complicated definitions that allow materials of widely different types — each with its own unique parameters— is a topic for another day. Here, we just indicate that viscosity is the only parameter required to define our fluid,perhaps because the simulation assumes incompressibility.

The definitions for boundary and initial conditions are more complex because we might have different combinationsof Dirichlet, Neumann, or Cauchy conditions for different variables over different portions of the domain. Rather thantry to use a single Definition for all of these, we can use SMTK’s inheritance system to create derived Definitions:

1 # We have one initial condition for the interior of the domain:2 fluidICDef = ares.createDefinition('fluid ic', icDef)3

4 # The specific types of BCDefs our example must define:5 # At the outlet, pressure must be given.6 # At the inlet, fluid velocity and temperature must be given.7 # On the wall, heat flux must be specified.8 outletBCDef = ares.createDefinition('outlet bc', bcDef)9 inletBCDef = ares.createDefinition('inlet bc', bcDef)

10 wallBCDef = ares.createDefinition('wall bc', bcDef)11

12 # Each ICDef/BCDef holds a different type of value:13 temperature = smtk.attribute.DoubleItemDefinition.New('temperature')14 pressure = smtk.attribute.DoubleItemDefinition.New('pressure')15 velocity = smtk.attribute.DoubleItemDefinition.New('velocity')16 heatflux = smtk.attribute.DoubleItemDefinition.New('heatflux')17

(continues on next page)

2.2. First steps in Python 65

Page 72: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

(continued from previous page)

18 # Add the values to the appropriate BCDef:19 fluidICDef.addItemDefinition(temperature)20 fluidICDef.addItemDefinition(velocity)21

22 outletBCDef.addItemDefinition(pressure)23

24 inletBCDef.addItemDefinition(velocity)25 inletBCDef.addItemDefinition(temperature)26

27 wallBCDef.addItemDefinition(heatflux)

We could also have created a definition to hold global simulation parameters such as convergence criteria, haltingcriteria, and desired accuracy; but for simplicity, we will assume the simulation package has reasonable defaults.

Now that we have quantities of interest specified for each attribute definition, we can provide hints to make data entryless error-prone. For instance:

• SMTK accepts units for items that store continuous or discrete numeric values. These are presented to the userduring entry to avoid confusion.

• Viscosity, temperature, and pressure have absolute minimum values. Items that store quantitative values acceptminimum and maximum values; a boolean argument passed with the minimum or maximum indicates whetherthe limit value is attainable.

• Items store a single value in their given primitive type by default. But arrays of values may be accepted andthese arrays may be fixed in size (as our 2-dimensional velocity requires exactly 2 components) or extensiblebetween a minimum and maximum array length.

• It is also possible to mark an Item so that its entries should come from an enumerated set of acceptable values,but we do not illustrate that here.

1 viscosity.setMinRange(0, True)2 viscosity.setUnits('Pa * s') # or Poise [P]3

4 temperature.setMinRange(-273.15, True)5 temperature.setUnits('deg C')6

7 pressure.setMinRange(0, True)8 pressure.setUnits('Pa')9

10 heatflux.setUnits('W / m^2 / K')11

12 velocity.setNumberOfRequiredValues(2)13 velocity.setUnits('m / s')14 velocity.setDefaultValue(0.)

Now that our item definitions are constrained, we can create attributes from the definitions.

2.2.3 Simulation Preparation

The previous steps prepared a template that we can now use to create input decks for multiple simulations. The firststep in creating input decks is to instantiate attributes based on the definitions above:

1 fluidIC = ares.createAttribute('fluidIC', fluidICDef)2 wallBC = ares.createAttribute('wallBC', wallBCDef)3 inletBC = ares.createAttribute('inletBC', inletBCDef)

(continues on next page)

66 Chapter 2. Tutorials

Page 73: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

(continued from previous page)

4 outletBC = ares.createAttribute('outletBC', outletBCDef)5 matProp = ares.createAttribute('fluid', matDef)

When you ask the Resource to create an Attribute, it provides an Item to match every ItemDefinition in the attribute’sunderlying Definition. These items are initialized to their default values (when a default has been provided) and keeptrack of whether they have been changed or not. We will change the values of these attributes soon, but first let’sconsider their relationship to the model geometry.

In the simplest workflow, you will already have a geometric model of the simulation domain(s) and the domainboundaries with the relevant groups of vertices, edges, faces, and/or volumes named for use in applying boundary andinitial conditions. Here, we read in an SMTK model session assuming that these groups already exist with names thatwe know:

1 # Read in an SMTK-native B-Rep model:2 # TODO: Replace with resource.readModel()3 jsonFile = open(modelFileName, 'r')4 json = jsonFile.read()5 smtk.model.SessionIOJSON.loadModelRecords(json, mmgr)6

7 # Now find groups corresponding to IC/BCs:8 models = mmgr.findEntitiesByProperty('name', 'Test Model')9 model = smtk.model.Model(models[0])

10 groups = model.groups()11 if groups and len(groups):12 wallGroup = (g for g in groups if g.name() == 'wall').next()13 inletGroup = (g for g in groups if g.name() == 'inlet').next()14 outletGroup = (g for g in groups if g.name() == 'outlet').next()15 fluidGroup = (g for g in groups if g.name() == 'fluid').next()16

17 fluidIC.associateEntity(fluidGroup)18 outletBC.associateEntity(outletGroup)19 inletBC.associateEntity(inletGroup)20 wallBC.associateEntity(wallGroup)

Now we can loop over the parameters we wish to study and create an ensemble for sensitivity analysis.

1 # FIXME: Actually put this inside a loop that exports input decks.2 matProp.findDouble('viscosity').setValue(1.002e-3) # [Pa * s]3

4 fluidIC.findDouble('temperature').setValue(25) # [C]5 fluidIC.findDouble('velocity').setValue(0, 0.) # [m / s]6 fluidIC.findDouble('velocity').setValue(1, 0.) # [m / s]7

8 outletBC.findDouble('pressure').setValue(101300) # [Pa]9

10 inletBC.findDouble('velocity').setValue(0, 0.25) # [m / s]11 inletBC.findDouble('velocity').setValue(1, 0.00) # [m / s]12 inletBC.findDouble('temperature').setValue(50) # [C]13

14 wallBC.findDouble('heatflux').setValue(1.0) # [W / m^2 / K]

2.3 Bridge a new modeling kernel

This tutorial covers how to session a solid modeling kernel to SMTK. The details will vary according to the capabilitiesof the modeling kernel you wish to use via SMTK, but the overall process of bridging the kernel involves

2.3. Bridge a new modeling kernel 67

Page 74: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

• subclassing SMTK’s Session class — which is used as a session between the modeling kernel and SMTK’smodel manager;

• defining a map between your kernel’s modeling entities and SMTK UUIDs;

• transcribing information about kernel modeling entities into an SMTK model manager; and

• providing SMTK operators which perform modeling operations. The only mandatory operator is a “read” oper-ator used to load a file native to your modeling kernel into your native kernel’s modeling session.

This tutorial will add a simplistic session type that presents an Exodus mesh as a model composed only of groups(element blocks, side sets, and node sets). A session like this is useful for cases where the geometry for a simulationhas been completely prepared and SMTK is only being used to attach attributes to pre-existing subsets of the geometricmodel. The groups themselves have a tessellation (i.e., a graphical representation) based on the cells they contain butthe groups do not expose any of these cells to SMTK.

Our example session uses VTK’s Exodus reader to load files and obtain a tessellation for each element block, side set,and node set.

2.3.1 Adding Entity UUIDs

The first step in adapting foreign modeling kernels to SMTK, which you should do before you start subclassingSession, is deciding how to assign UUIDs to entities in the foreign modeling kernel so that

• entities can persist across SMTK modeling sessions and

• SMTK can identify entities to the modeling kernel given only a UUID (for instance, to specify inputs to amodeling kernel operation).

There are two ways to go about storing and maintaining this bidirectional map between modeling kernel entities andSMTK UUIDs:

1. If the modeling kernel provides an attribute resource, then the UUIDs can be stored as attributes on entities.Note that it is important to verify that attributes can be stored on all the entities you wish SMTK to be able totrack. For instance, OpenCASCADE does not provide a way to store attributes on “use” records or on loops andshells. This means we must use another method if we want to preserve UUIDs assigned to these entities.

2. If the modeling kernel provides a “stable” order for traversing model entities, the mapping can be reduced tostoring one or more sequences of UUIDs in an SMTK model file. If you construct this file so that it also savessession information, it can be used to “restore” a modeling session so that the same files are loaded on the serverand the UUIDs preserved.

The VTK session follows the first approach and expects UUIDs to be saved as field-data on each data object to berepresented in SMTK. To accelerate lookups of UUIDs, the VTK session stores the UUID as a string value on eachvtkDataObject’s information object using the SMTK_UUID_KEY key. It uses a method provided by SMTK’sVTK-based rendering support to fetch and store UUIDs so that picking can be coordinated with VTK.

smtk::common::UUID Session::uuidOfHandleObject(vtkDataObject* obj) const{

smtk::common::UUID uid;if (!obj){return uid;

}

uid = vtkResourceMultiBlockSource::GetDataObjectUUID(obj->GetInformation());if (!uid){ // We have not assigned a UUID yet. Do so now.uid = smtk::common::UUIDGenerator::instance().random();

(continues on next page)

68 Chapter 2. Tutorials

Page 75: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

(continued from previous page)

vtkResourceMultiBlockSource::SetDataObjectUUID(obj->GetInformation(), uid);}return uid;

}

The advantage to the first approach is that modeling kernels with attribute resources generally provide a way to preserveattributes across modeling operations. When using the latter method, there is no robust way to track entities acrossmodeling operations that change the topology of the model.

2.3.1.1 Adding UUIDs by either technique

Regardless of the path you take above, your session should provide public methods to map both directions. Thefunction mapping UUIDs to foreign entities will have a return type that is specific to your modeling kernel, as will theinput parameter of the inverse method that returns a UUID given a foreign entity; for our example, we’ve created anew type named EntityHandle.

/// The types of entities in a VTK "model"enum EntityType{

EXO_MODEL = 0x01, //!< An entire VTK dataset (a file).EXO_BLOCK = 0x02, //!< VTK BLOCKs are groups of cells inside a MODEL.EXO_SIDE_SET = 0x03, //!< VTK SIDE_SETs are groups of cell boundaries in a MODEL.EXO_NODE_SET = 0x04, //!< VTK NODE_SETs are groups of points in a MODEL.

EXO_BLOCKS = 0x05, //!< A group of VTK BLOCKs.EXO_SIDE_SETS = 0x06, //!< A group of VTK SIDE_SETs.EXO_NODE_SETS = 0x07, //!< A group of VTK NODE_SETs.

EXO_LABEL_MAP = 0x08, //!< A dataset with a label-map arrayEXO_LABEL = 0x09, //!< A dataset representing one label in a label-map array

EXO_INVALID = 0xff //!< The handle is invalid};

SMTKVTKSESSION_EXPORT std::string EntityTypeNameString(EntityType etype);

/// A "handle" for a VTK entity (file, block, side set, or node set)struct SMTKVTKSESSION_EXPORT EntityHandle{

intm_modelNumber; //!< An offset in the vector of models (m_models) owned by the

→˓session, whose model owns m_object.vtkSmartPointer<vtkDataObject> m_object; //!< The dataset being presented as this

→˓entity.SessionPtr m_session; //!< The session owning this entity.

EntityHandle();EntityHandle(int emod, vtkDataObject* obj, SessionPtr sess);EntityHandle(int emod, vtkDataObject* obj, vtkDataObject* parent, int idxInParent, SessionPtr

→˓sess);

bool isValid() const;

EntityType entityType() const;(continues on next page)

2.3. Bridge a new modeling kernel 69

Page 76: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

(continued from previous page)

std::string name() const;int pedigree() const;bool visible() const;

int modelNumber() const { return this->m_modelNumber; }

EntityHandle parent() const;

template <typename T>T* object() const;

template <typename T>T childrenAs(int depth) const{T container;this->appendChildrenTo(container, depth);return container;

}

template <typename T>void appendChildrenTo(T& container, int depth) const;

bool operator==(const EntityHandle& other) const{return this->m_session == other.m_session && this->m_object == other.m_object &&this->m_modelNumber == other.m_modelNumber;

}bool operator!=(const EntityHandle& other) const{return this->m_session != other.m_session || this->m_object != other.m_object ||this->m_modelNumber != other.m_modelNumber;

}};

Each EntityHandle instance stores information about a model or group that should be presented in SMTK:

1. m_session, a pointer to the session owning the model or group;

2. m_modelNumber, an integer offset into the session’s list of top-level models (this indicates the model thatowns the data object); and

3. m_object, a pointer to a VTK dataset holding the corresponding model geometry.

The session also holds a map to identify the parent model or group of each VTK data object since multiblock datasetsin VTK do not provide a way to discover the parent of a dataset (only its children).

2.3.1.2 Adding UUIDs as attributes

Although we do not provide example code in this tutorial, it should be straightforward to add UUIDs to a modelingkernel’s attribute resource either as a 16-byte binary blob or an ASCII string per entity.

For example, if we wished to make VTK points and cells available via a session, we could store UUIDs onVTK grids as point and cell data arrays. It would be more space-efficient to store these in a 2-componentvtkTypeUInt64Array (2 components for a total of 128 bits per UUID), but much easier to debug if we storeUUIDs in vtkStringArray instances (one for points, one for cells).

VTK provides the concept of pedigree IDs for mapping points and cells from inputs to corresponding outputs, so (forfilters that support pedigree IDs) VTK behaves much like an attribute resource in a geometric modeling kernel.

70 Chapter 2. Tutorials

Page 77: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

If we ever expose individual points and cells in the SMTK VTK session, we could search for point- and cell-dataarrays containing UUIDs. Currently, we only search for field data specifying the UUID of a dataset as shown above.

Although not required by this example, you should be aware that you may store information about a particular sessioninstance in an SMTK JSON file by subclassing the SessionIOJSON class.

2.3.1.3 Adding UUIDs as sequences

If you must store UUIDs in an SMTK JSON file according to some stable traversal order, then you should

1. store the arrays in your session class in the proper order and use them to perform the lookups.

2. write from_json and to_json functions for your resource that serialize information beyond what native file for-mats can accommodate, including UUIDs. The VTK session illustrates how to do this but does not currentlyexport any session information.

2.3.1.4 Summary

You should now have a way to map a foreign entity to its SMTK UUID and vice-versa. If there is any possibilitythat the model could change, then you are responsible for maintaining this mapping (or at least marking it dirty andrebuilding as required).

Note that with either approach it is possible to incrementally assign UUIDs to entities as the need arises (thoughnot very efficiently when storing UUIDs by traversal order). Future versions of SMTK will focus on incrementaltranscription of model entities to avoid significant waits the first time a model is read.

Now that you understand how UUIDs will be stored and related to foreign modeling kernel entities, it is possible tosubclass the SMTK model session class.

2.3.2 Creating a session subclass

Sessions exist to link foreign modeling entities to SMTK modeling entities, in a bidirectional way:

• we transcribe foreign modeling entities into an SMTK model resource, and

• we perform operations in SMTK that make changes in the foreign modeling kernel (and then result in moretranscriptions to update SMTK’s model resource).

Only the first of these is needed for read-only access so we will cover it first and then describe the interactions betweensessions and operators. Implementing operators is the topic of a separate tutorial.

The first thing you must do when creating your own session is to implement a subclass of smtk::model::Session:

In the example above, some methods override the base class in order to provide required functionality while othersjust illustrate useful ways to divide tasks that should be common to most session types.

The first block of methods near the top of the declaration are required in order for instances of the session to be createdand introspected by SMTK.

• The typedef smtk::shared_ptr<Session> Ptr is useful for referencing shared pointers to the ses-sion internally.

• The typedef smtk::model::SessionInfoBits SessionInfoBits is not required but will makeimplementing methods dealing with transcription of entities easier to type.

• The smtkCreateMacro macro is required in order for instances of the object to be created.

• The virtual destructor should always be implemented so that the base class destructor is called.

2.3. Bridge a new modeling kernel 71

Page 78: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

• Finally, the allSupportedInformation method exists so that SMTK can discover what types of infor-mation the session can provide to SMTK. The returned integer should be a bitwise OR of entries from theSessionInformation enum. For now, it is fine to return SESSION_EVERYTHING.

The next step is to provide methods to access the maps between SMTK and foreign entities (in this case, Exoduselement blocks, side sets, and node sets). The toEntity and toEntityRef methods do this and will be discussedin more detail in the next section. Depending on your modeling kernel, you may use an existing type from the foreignmodeler (like the OpenCASCADE session does) or a new class like the EntityHandle class in our example.

Now that we have defined a mapping between UUIDs and model entities, the next step is to have the session transcribeinformation about foreign model entities into a model resource instance.

2.3.3 Transcribing model entities

The main purpose of the session is to provide the SMTK model Manager which owns it with information about theentities in some foreign modeler and the Session::transcribeInternal() method is where your session must do this.

The first thing you should do is verify that the entity being requested actually exists:

One trick you’ll see in most sessions is the construction of a “mutable” entityref from the const version that passed totranscribeInternal:

The const version does not provide access to methods that alter the model manager’s storage. Constructing a mutableversion of the entityref is legitimate inside the session — we are pretending that the entity to be transcribed has existedin the manager ever since it existed in the foreign modeler. Since transcription should not change the entity in theforeign modeler, creating a mutable entityref is acceptable.

Once you know that the UUID has a matching entity in the foreign modeler, you should create an Entity instancein the model manager’s map from UUIDs to entities. Make sure that the entity’s flags properly define the typeof the entity at this point but don’t worry about filling in the list of relations to other entities unless the SES-SION_ENTITY_RELATIONS bit is set in the request for transcription.

If SESSION_ENTITY_RELATIONS is set, then you not only need to ensure that the relations are listed but that theyare also at least partially transcribed. You are always welcome to transcribe more than is requested, but be awarethat this can slow things down for large models. Because this is an example and because the Exodus session does notexpose individual cells as first-class entities, we transcribe the entire model recursively.

Now you should check other bits in SessionInformation that are present in your Session::allSupportedInformation()method and ensure that information is transcribed properly before returning the bits which were actually transcribedfor the given entity.

The Session::transcribe() method uses the return value to update its list of dangling (partially transcribed) entities.

2.3.4 Providing operators

Finally, if you wish to allow modeling operations, your session must provide Operator definitions that invoke theunderlying modeling kernel.

2.4 Implementing an STMK operator

Contents

• Implementing an STMK operator

72 Chapter 2. Tutorials

Page 79: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

– Subclassing smtk::model::Operator

– Defining operator input parameters

– Defining operator output parameters

– Implementing the actual operation

SMTK allows you to write operators that expose those provided by an underlying modeling kernel as well as operatorsthat provide new functionality.

This tutorial will cover writing an operator that provides new functionality: specifically, we will create an operatorthat counts the number of top-level cells in a model. Given a non-default option, it may instead count the number oftop-level groups in a model.

Operators in SMTK consist of 3 components:

• a class that implements the action of the operator, as a subclass of smtk::model::Operator.

• an SMTK attribute definition that describes the parameters the operator accepts (both required and optional)

• an SMTK attribute definition that describes information returned by the operator.

The sections below detail each of these.

2.4.1 Subclassing smtk::model::Operator

We will name our example operator the CounterOperator and place it in the “ex” example namespace.

1 namespace ex2 {3

4 class CounterOperation : public smtk::operation::XMLOperation5 {6 public:7 smtkTypeMacro(ex::CounterOperation);8 smtkCreateMacro(CounterOperation);9 smtkSharedFromThisMacro(smtk::operation::XMLOperation);

10 smtkSuperclassMacro(Operation);11 // ...

Our operator is a subclass of smtk::model::Operator, which is managed using shared pointers (it uses the smtkEnable-SharedPtr macro to inherit enable_shared_from_this), so we use the smtkCreateMacro() to provide a staticmethod for creating a shared pointer to a new instance and the smtkSharedFromThisMacro to override the base class’shared_from_this() method.

Beyond these basic requirements, an operator should implement two inherited virtual methods

• ableToOperate which is an opportunity for an operator to perform checks on the validity of input parametersthat cannot be easily encoded using the attribute resource; and

• operateInternal which implements the actual behavior of the operator.

Because our operator is simple, we implement smtk::operation::Operation::ableToOperate in the class header file. Weonly declare smtk::operation::Operation::operateInternal:

1 protected:2 Result operateInternal() override;3 const char* xmlDescription() const override;

2.4. Implementing an STMK operator 73

Page 80: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

By calling Operator::ensureSpecification in Operator::ableToOperate, we force the attribute resource to build an at-tribute instance which holds specifications for each parameter of this instance of the Operator. Then in Opera-tor::operateInternal we can refer to the specification without having to verify that it is non-null; an operator’s Op-erator::operateInternal method will never be called unless Operator::ableToOperate returns true.

The attribute constructed by Operator::ensureSpecification is built using XML definitions we provide. We will coverthe format of the XML definitions immediately below and then continue with the implementation of the operation.

2.4.2 Defining operator input parameters

The XML we used to declare the operator’s parameters and results uses SMTK’s attribute definition system. Alloperators should be derived definitions whose base definition (BaseType) is “operator”:

1 <include href="smtk/operation/Operation.xml"/>2 <AttDef Type="counter" BaseType="operation">3 <ItemDefinitions>4 <Component Name="model" NumberOfRequiredValues="1">5 <Accepts><Resource Name="smtk::model::Resource" Filter="model|anydim"/></

→˓Accepts>6 </Component>7 <Int Name="count groups" NumberOfRequiredValues="1">8 <DefaultValue>0</DefaultValue>9 </Int>

10 </ItemDefinitions>11 </AttDef>

Inheriting the base definition allows us to use to attribute system to easily enumerate the list of all operators.

Also, you can see in the example that our operator takes a single integer parameter named “count groups”. Its defaultvalue is 0, indicating that top-level cells (not groups) will be counted by default. We could also have made “countgroups” a VoidItem and tested for whether the attribute was enabled instead of testing its value.

In the future, operators will have their “primary” operand expressed as an association: model topology to serve asthe primary operand will be associated with an instance of the operator rather than declared as an item owned by theoperator attribute. This will simplify use cases where an active selection exists and the user wishes to perform anoperation on it; operators that can be associated with the selection will be enabled (while others will be disabled). Anyfurther parameters may be specified after the user initiates the operation.

2.4.3 Defining operator output parameters

The XML description of an operator is not complete until both the input and output parameters have been specified.The output parameters are expressed as another smtk::attribute::Attribute instance, this time defined as by inheritingthe “result” BaseType. The result base type includes an integer item named “outcome” use to store one of the valuesin the OperatorOutcome enum. The outcome indicates whether the operation was successful or not.

1 <!-- Result -->2 <include href="smtk/operation/Result.xml"/>3 <AttDef Type="result(counter)" BaseType="result">4 <ItemDefinitions>5 <Int Name="count" NumberOfRequiredValues="1">6 </Int>7 </ItemDefinitions>8 </AttDef>

74 Chapter 2. Tutorials

Page 81: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

In addition to the outcome, our edge-counting operator also returns the number of edges it counted. Often, SMTKoperators will return lists of new, modified, or removed model entities in one or more smtk::attribute::ModelEntityIteminstances.

Both the input and output XML are typically maintained together in a single XML file.

2.4.4 Implementing the actual operation

Now that we have input and output parameters specified, the implementation of Operator::operateInternal can simplyfetch items from an instance of an attribute defined by the XML:

1 smtk::operation::XMLOperation::Result CounterOperation::operateInternal()2 {3 // Get the attribute holding parameter values:4 auto params = this->parameters();5

6 // Get the input model to be processed:7 Model model = params->findComponent("model")->valueAs<smtk::model::Entity>();8

9 // Decide whether we should count cells or groups10 // of the model:11 int countGroups = params->findInt("count groups")->value();12

13 // Create the attribute holding the results of14 // our operation using a convenience method15 // provided by the Operation base class.16 // Our operation is simple; we always succeed.17 auto result = this->createResult(smtk::operation::Operation::Outcome::SUCCEEDED);18

19 // Fetch the item to store our output:20 smtk::attribute::IntItemPtr cellCount = result->findInt("count");21

22 cellCount->setValue(23 countGroups ? static_cast<int>(model.groups().size()) : static_cast<int>(model.

→˓cells().size()));24

25 return result;26 }

Note that the base class provides a method to create a result attribute for you with the “outcome” parameter set to avalue you specify.

In addition to implementing the operation, the only other thing you must do is register the operator with the propersession. This is done using the smtkImplementsModelOperator macro:

1 // Implement virtual overrides from base class to handle registration.2 const char* CounterOperation::xmlDescription() const3 {4 return implement_an_operator_xml;5 }

Warning: This macro must always be invoked in the global namespace and your operator’s class name fullyqualified with the namespace in which it lives.

This macro is very important because it ties several names together:

2.4. Implementing an STMK operator 75

Page 82: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

SMTK Documentation, Release 3.3.0

• the C++ class name (ex::CounterOperator),

• the names and XML descriptions of the attribute definitions for input parameters (“counter”) and result param-eters “result(counter)”, and

• the SMTK component name used by the autoinitialization facility to force components (such as this operator) tobe registered when initializing static variables. In this case the component name “ex_counter” can be used withthe smtkComponentInitMacro() by adding this line:

smtkComponentInitMacro(smtk_ex_counter_operator)

to a compilation unit containing code that will be run by your application. Whenever the compilation unit’sstatic variables are initialized, the operator will be registered with the session class and any sessions constructedafterwards will provide the operator.

Note that “smtk_” and “_operator” wrap the name you pass to the smtkImplementsModelOperator macro.

To make maintaining the XML simpler, SMTK provides a macro for encoding an XML file as a variable in a C++header. The variable implement_an_operator_xml is generated in CMakeLists.txt by

and then used by including the resulting file in your C++ implementation:

1 // Include the encoded XML describing the operator class.2 // This is generated by CMake.3 #include "implement_an_operator_xml.h"

76 Chapter 2. Tutorials

Page 83: SMTK Documentation · (e.g., attribute, model, and mesh resources) into an input deck for a simulation using Python scripts (or C++ if you wish). •The view system provides user

CHAPTER

THREE

INDICES AND TABLES

• genindex

• modindex

• search

77