marc tutorials

264
Marc ® Python 2010 Tutorial and Reference Manual

Upload: fkaram1965

Post on 23-Oct-2015

578 views

Category:

Documents


13 download

DESCRIPTION

marc tutorials

TRANSCRIPT

Page 1: MARC Tutorials

Marc® Python 2010

Tutorial and Reference Manual

Page 2: MARC Tutorials

CorporateMSC.Software Corporation2 MacArthur PlaceSanta Ana, CA 92707Telephone: (800) 345-2078FAX: (714) 784-4056

EuropeMSC.Software GmbHAm Moosfeld 1381829 MunichGERMANYTelephone: (49) (89) 43 19 87 0Fax: (49) (89) 43 61 71 6

Asia PacificMSC.Software Japan Ltd.Shinjuku First West 8F23-7 Nishi Shinjuku1-Chome, Shinjuku-Ku Tokyo 160-0023, JAPANTelephone: (81) (3)-6911-1200Fax: (81) (3)-6911-1201

Worldwide Webwww.mscsoftware.com

User Documentation: Copyright © 2010 MSC.Software Corporation. Printed in U.S.A. All Rights Reserved.This document, and the software described in it, are furnished under license and may be used or copied only in accordance with the terms of such license. Any reproduction or distribution of this document, in whole or in part, without the prior written authorization of MSC.Software Corporation is strictly prohibited.

MSC.Software Corporation reserves the right to make changes in specifications and other information contained in this document without prior notice. The concepts, methods, and examples presented in this document are for illustrative and educational purposes only and are not intended to be exhaustive or to apply to any particular engineering problem or design. THIS DOCUMENT IS PROVIDED ON AN “AS-IS” BASIS AND ALL EXPRESS AND IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS ARE HELD TO BE LEGALLY INVALID.

MSC.Software logo, MSC, MSC., MD Nastran, Adams, Dytran, Marc, Mentat, and Patran are trademarks or registered trademarks of MSC.Software Corporation or its subsidiaries in the United States and/or other countries.

NASTRAN is a registered trademark of NASA. Python is a trademark of the Python Software Foundation. LS-DYNA is a trademark of Livermore Software Technology Corporation. All other trademarks are the property of their respective owners.

This software may contain certain third-party software that is protected by copyright and licensed from MSC.Software suppliers.

METIS is copyrighted by the regents of the University of Minnesota. HP MPI is developed by Hewlett-Packard Development Company, L.P. MS MPI is developed by Microsoft Corporation. PCGLSS 6.0, copyright © 1992-2005 Computational Applications and System Integration Inc. MPICH Copyright 1993, University of Chicago and Mississippi State University. MPICH2 copyright © 2002, University of Chicago.

Use, duplication, or disclosure by the U.S. Government is subject to restrictions as set forth in FAR 12.212 (Commercial Computer Software) and DFARS 227.7202 (Commercial Computer Software and Commercial Computer Software Documentation), as applicable.

MA*V2010*Z*Z*Z*DC-PYTH

Page 3: MARC Tutorials

C O N T E N T SMarc Python Tutorial and Reference Manual

Contents

C O N T E N T SMarc Python Tutorial and Reference Manual

Marc Python Tutorial

Chapter Preface ■ Organization of this Manual . . . . . . . . . . . . . . . . . . . . . . . . i-xiv

■ Contents of the Chapters . . . . . . . . . . . . . . . . . . . . . . . . . . . i-xiv❑ PART I PyMentat Module . . . . . . . . . . . . . . . . . . . i-xiv❑ PART II PyPost Module . . . . . . . . . . . . . . . . . . . . . . i-xv❑ PART III Advanced Discussions . . . . . . . . . . . . . . . . i-xv

■ Documentation Conventions . . . . . . . . . . . . . . . . . . . . . . . . i-xvi

Chapter 1Introduction ■ The Basics of Using PyMentat . . . . . . . . . . . . . . . . . . . . . . . .1-2

■ The Basics of Using PyPost . . . . . . . . . . . . . . . . . . . . . . . . . .1-5

■ A Brief Look at Python Programming . . . . . . . . . . . . . . . . . .1-7❑ Python Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-8

Basic Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-8Extended Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-8

Chapter 2PyMentat: A Simple Example

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-2

■ Creating a Simple Python Script for Marc Mentat . . . . . . . . .2-3

■ Python Programming Hints . . . . . . . . . . . . . . . . . . . . . . . . . .2-5

■ Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-6

Page 4: MARC Tutorials

Marc Python Tutorial and Reference Manualiv

Chapter 3PyMentat: Obtaining Data from Marc Mentat

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-2

■ Creating a Simple Python Script for Marc Mentat . . . . . . . . .3-3

■ The py_get_int and py_get_float methods . . . . . . . . . . . . . . .3-5

■ Running the Scrip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-5

Chapter 4PyMentat: Building Complex Geometry

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-2

■ Background Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-3

■ Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-6

Chapter 5PyMentat: Adding Model Properties

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-2

■ Plate Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-3

■ Node and Element Id’s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-8

■ Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-10

■ Submitting the Job . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5-11

Chapter 6PyMentat: Processing a Post File

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-2

■ Postprocessing Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-3

■ Scalar Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-7

■ Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-7

Chapter 7PyMentat: Obtaining Model Data

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-2

■ Database Properties Basics . . . . . . . . . . . . . . . . . . . . . . . . . . .7-3

■ Set Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-4

■ A Sample Script to Extract Data . . . . . . . . . . . . . . . . . . . . . . .7-5

■ Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-12

Page 5: MARC Tutorials

vContents

■ Set Id’s and Set Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-16

Chapter 8PyPost: Reading a Post File

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-2

■ PyPost Basic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-3

■ Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-6

Chapter 9PyPost: Obtaining Element Data

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-2

■ Processing Element Data . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-3

■ Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-8

Chapter 10PyPost: Element Tensor Data

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10-2

■ Processing Element Tensor Data . . . . . . . . . . . . . . . . . . . . .10-3

■ Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10-7

Chapter 11PyMentat: Using the py_connect Method

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11-2

■ Creating a Simple Python Script for Marc Mentat . . . . . . . .11-3

■ The py_connect Method . . . . . . . . . . . . . . . . . . . . . . . . . . . .11-3

■ Handling Socket Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11-4

■ Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11-6

Chapter 12PyPost: Plotting ■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-2

■ Charting Script for Marc Mentat . . . . . . . . . . . . . . . . . . . . .12-3

■ The Gnuplot Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-7

■ The PyOpenGL Module . . . . . . . . . . . . . . . . . . . . . . . . . . .12-11

Page 6: MARC Tutorials

Marc Python Tutorial and Reference Manualvi

Chapter 13PyMentat: Menu System Lookup Functions

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-2

■ Menu System Lookup Functions . . . . . . . . . . . . . . . . . . . . .13-3

■ Integer Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-4

■ Double Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-5

■ String Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-6

■ Boolean Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-7

■ State Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13-8

Chapter 14MentatDCOM: Connecting to Mentat using a .NET Module

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-2

■ MentatDCOM Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-3

■ Running the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-7

■ MentatDCOM and PyMentat . . . . . . . . . . . . . . . . . . . . . . . .14-8

Chapter 15MarcPost: Reading a Post File using a .NET Module

■ Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15-2

■ MarcPost Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15-3

■ Running the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15-7

■ MarcPost and PyPost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15-8

Marc Python Reference

Introduction■ Using the Python Modules . . . . . . . . . . . . . . . . . . . . . . . . . . i-iv

■ Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i-ivString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i-vFloat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i-vInteger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i-vList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . i-v

Page 7: MARC Tutorials

viiContents

Chapter 1PyMentat References ■ PyMentat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-2

■ py_connect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-3

■ py_disconnect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-4

■ py_echo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-5

■ py_get_data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-6

■ py_get_float . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-7

■ py_get_int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-8

■ py_get_string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-9

■ py_prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-10

■ py_echo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1-11

Chapter 2PyPost References ■ PyPost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-4

■ close . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-10

■ cbody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-11

■ cbody_angle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-14

■ cbody_displacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-15

■ cbody_force . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-16

■ cbody_moment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-17

■ cbody_name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-18

■ cbody_rotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-19

■ cbody_transform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-20

■ cbody_velocity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-21

■ cbody_volume . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-22

■ cbodies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-23

■ domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-24

Page 8: MARC Tutorials

Marc Python Tutorial and Reference Manualviii

■ element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-25

■ elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-26

■ element_id . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-27

■ element_scalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-28

■ element_scalars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-29

■ element_scalar_label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-30

■ element_sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-31

■ element_tensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-32

■ element_tensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-33

■ element_tensor_label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-34

■ element_vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-35

■ element_vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-36

■ element_vector_label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-37

■ extrapolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-38

■ global_value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-39

■ global_values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-40

■ global_value_label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-41

■ increments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-42

■ moveto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-43

■ node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-44

■ nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-45

■ node_displacement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-46

■ node_displacements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-47

■ node_id . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-48

■ node_scalar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-49

■ node_scalars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-50

Page 9: MARC Tutorials

ixContents

■ node_scalar_label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-51

■ node_sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-52

■ node_vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-53

■ node_vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-54

■ node_vector_label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-55

■ post_open . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-56

■ set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-57

■ sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-58

■ title . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-59

■ version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-60

Appendix A■ Arithmetic and Database Functions . . . . . . . . . . . . . . . . . . . A-2

❑ Arithmetic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . A-2❑ Database Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-4❑ Utility Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-19❑ Post File Database Functions . . . . . . . . . . . . . . . . . . . A-21❑ Set Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-24

Page 10: MARC Tutorials

MSC.Marc Python Tutorialx

Page 11: MARC Tutorials

Python Tutorial

Marc Python Tutorial

Page 12: MARC Tutorials
Page 13: MARC Tutorials

Preface

The purpose of this manual is to introduce the user to the Python modules. The tutorial covers the basics of the modules and helps the novice Python user in becoming comfortable in programming with these modules through a number of examples that display some typical uses of creating and processing a model in various stages. This tutorial is not intended to be a Python programming manual. The book Programming Python by Mark Lutz should be used for this purpose. This manual does assume that the Python user is experienced in using Marc Mentat.

Preface

■ Organization of this Manual

■ Contents of the Chapters

■ Documentation Conventions

Page 14: MARC Tutorials

Marc Python Tutorialxiv

Organization of this ManualThis manual is divided into three parts:Part I introduces the user to the PyMentat module. This module interacts with Marc Mentat (which will be referred to as Marc Mentat) to create, modify, and post process models.Part II introduces the user to the PyPost module. This module functions independently of Marc Mentat to post process a Marc post file (results file).Part III introduces the user to more advanced uses of the PyMentat and PyPost modules.

Contents of the Chapters

Chapter 1 Introduction, provides information on the basics using PyMentat and of Python programming.

PART I PyMentat Module

Chapter 2 PyMentat: A Simple Example, describes a basic PyMentat script.

Chapter 3 PyMentat: Obtaining Data from Marc Mentat, expands on the common features of PyMentat and describes how a Python script can get data from Marc Mentat.

Chapter 4 PyMentat: Building Complex Geometry, displays how you can build complex geometry that cannot be done with procedure files alone.

Chapter 5 PyMentat: Adding Model Properties, shows how to add boundary conditions, material properties, geometric properties and job parameters to allow you to perform a complete linear elastic analysis of a rectangular strip with a series of holes subjected to compression loading.

Chapter 6 PyMentat: Processing a Post File, shows how to process a Marc post file.

Chapter 7 PyMentat: Sets, shows how to write PyMentat scripts to work with SETS.

Page 15: MARC Tutorials

xvPreface

PART II PyPost Module

Chapter 8 PyPost: Reading a Post File, introduces the basics of using the PyPost module to obtain post file data and find the maximum scalar values.

Chapter 9 PyPost: Obtaining Element Data, shows how to obtain element scalar data from a post file.

Chapter 10 PyPost: Element Tensor Data, expands on obtaining element data by showing how to obtain element tensor data from a post file. It also introduces the PyTensor class.

PART III Advanced Discussions

Chapter 11 PyMentat: Using the py_connect Method, introduces the basics of using the PyMentat module in a client/server environment.

Chapter 12 PyPost: Plotting Post File Data, shows some example of using third party modules to plot the results of a post file.

Page 16: MARC Tutorials

Marc Python Tutorialxvi

Documentation ConventionsListed below are some font and syntax conventions that are used to make the information in this manual easier to understand:

• Cross-references (Links) are highlighted in Blue.

• Names of buttons that appear on the Marc Mentat screen are in UPPER CASE. The command issued will appear in lower case, such as *add_nodes. Note that the "*" always precedes the command name to instruct Marc Mentat that a command is being issued.

• Literal user input and program prompts are in courier font.

• Names of processors are indicated in UPPER CASE.

• A carriage return keystroke is indicated by <CR>.

• The left mouse button is indicated by <ML>.

• The middle mouse button is indicated by <MM>.

• The right mouse button is indicated by <MR>.

• The mouse cursor is indicated by .

• A filename implies a concatenation of pathname and filename. The pathname may be omitted if the filename is in your current directory. You will note the patnames are specified with the forward slash character "/", as in examples/python/userguide. For those using Microsoft Windows, you will need to substitute the forward slashes with the backslash character "\".

< >

Page 17: MARC Tutorials

Chapter 1: Introduction

Welcome to Python – a set of API’s designed to be used by Python scripts to enhance the functionality of Marc Mentat.

CHAPTER

1 Introduction

■ The Basics of Using PyMentat

■ The Basics of Using PyPost

■ A Brief Look at Python Programming

Page 18: MARC Tutorials

Marc Python Tutorial1-2

The Basics of Using PyMentatWhen you select a menu item in Marc Mentat, it does one of two things:

1. You are presented with a new menu screen.

2. A command is issued.

The concept of using the PyMentat module uses Item 2. To build or modify models using the PyMentat module, a Python script sends a sequence of commands to Marc Mentat. These commands are the same commands that are issued when you select the appropriate menu item.

For example, if you select the menus:

MAINMESH GENERATION

grid ONnodes ADD

you will see that the command name of *add_nodes is issued in the dialogue area of Marc Mentat. Therefore, if you want your Python script to add a node, your script should send the command *add_nodes to Marc Mentat.

Unless you are a very experienced Marc Mentat user, you will most likely develop your PyMentat Python script using the technique outlined in Figure 1-1.

Page 19: MARC Tutorials

1-3CHAPTER 1Introduction

Figure 1-1 The Python Script Development Process

To aid in the development of converting the procedure files to Python scripts, the Python script shown in Figure 1-2 can be used to generate the Python code for any given Marc Mentat procedure file. To use the script, run it as follows:

python py_create.py mentat.proc my_script.py

This script simply reads the procedure file and wraps a py_send command around it. You will need to edit the resulting Python script to add PARAMETERS and other variables for conditional processing.

GENERATE TEST MODEL

RUN py_create.py USING

DEVELOP AND MODIFY

mentat.proc is createdMENTAT.PROC TO CREATE when Marc Mentat is run

TEST PYTHON SCRIPT

INITIAL PYTHON SCRIPT

PYTHON SCRIPTAdd new commands asneeded in the script

Page 20: MARC Tutorials

Marc Python Tutorial1-4

Figure 1-2 A Python Script to Convert a Marc Mentat Procedure File to a Python Script

#!/usr/bin/python

import sys

import string

def main(fnamei, fnameo):

i = open(fnamei,"r")

o = open(fnameo,"w")

o.write("from py_mentat import *\n")

o.write("def main():\n")

for line in i.readlines():

s = string.strip(line)

if s == "":

continue

st = " py_send(\"%s \")\n" % s

o.write(st)

o.write("\n")

o.write("if __name__ == '__main__':\n")

o.write(" main()\n")

if __name__ == "__main__":

main(sys.argv[1],sys.argv[2])

Page 21: MARC Tutorials

1-5CHAPTER 1Introduction

The Basics of Using PyPostThe PyPost module is used by a Python script to process a Marc post (results) file. It operates independently from Marc Mentat. The PyPost API provides a set of methods to be used to obtain the scalar, tensor or vector values stored in a post file.

Table 1-1

Function Description

close Closes a currently open post file and frees any allocated memory.

dies Returns the number of dies in the post file.

domains Returns the number of domains stored in the post file.

element Returns the element data for a particular element.

elements Returns the number of elements in the current increment.

element_id Returns the id of a particular element.

element_scalar Returns a list of a particular element scalar data for a particular element.

element_scalars Returns the number of element scalars available.

element_scalar_label Returns the name of a particular element scalar.

element_sequence Returns the index number of a particular element id.

element_tensor Returns a list of a particular element tensor for a particular element.

element_tensors Returns the number of element tensors available.

element_tensor_label Returns the name of a particular element tensor.

element_vector Returns a list of a particular element vector data for a particular element.

element_vectors Returns the number of element vectors available

element_vector_label Returns the name of a particular element vector.

extrapolation Sets the integration point extrapolation method.

increments Returns the number of increments available in the post file

moveto Move to a specified increment in the post file

Page 22: MARC Tutorials

Marc Python Tutorial1-6

node Returns the nodal data for a particular node.

nodes Returns the number of nodes for the current increment.

node_displacement Returns the nodal displacement values for a particular node.

node_displacements Returns a 1 if nodal displacements are present in the post file, 0 otherwise.

node_id Returns the id of a particular node

node_scalar Returns the value of a particular node scalar for a particular node.

node_scalars Returns the number of node scalars available.

node_scalar_label Returns the name of a particular node scalar.

node_sequence Returns the index number of a particular node id

node_vector Returns the value of a particular node vector at a particular node.

node_vectors Returns the number of node vectors available.

node_vector_label Returns the name of a particular node vector.

post_open Opens a post file and returns the PyPost object of it.

set Returns the data for a particular set.

sets Returns the number of sets in the post file.

title Returns the title of the post file.

Table 1-1 (Continued)

Function Description

Page 23: MARC Tutorials

1-7CHAPTER 1Introduction

A Brief Look at Python ProgrammingIn order to enhance your understanding of using PyMentat or PyPost, we will introduce you to the basics of programming with Python.

Python is an interpreted, interactive object-oriented programming language sometimes compared to Perl, Java, and Tcl. It has interfaces to IP networking, windowing systems, audio, and other technologies. Integrated with Marc Mentat, it provides a more powerful scripting language than procedure files since it contains conditional logic and looping statements such as if, while and for.

A Python script that will use the PyMentat module needs to import the py_mentat module using the following syntax:

from py_mentat import *

Similarly, a Python script that will use the PyPost module needs to import the py_post module using the following syntax

from py_post import *

One of the biggest differences between the Python language and other programming languages is that Python does not denote blocks of code with reserved words or symbols such as if..then..endif (FORTRAN) or if { ... } (curly braces in C). Instead, indenting is used for this purpose. For example, the take following block of FORTRAN code:

if(jtype.eq.49) then ladt=idt+lofrendif

The block of FORTRAN code would need to be coded as follows in Python:

if jtype == 49: ladt=idt+lofr

Python matches the amount of indenting to the block of code. The colon at the end of the if statement denotes that it is a compound statement. All the lines that are to be in that block of code need to be at the same indent level. The block of code is ended when the indenting level returns to the level of to the compound statement. The examples in the following chapters will show you more about the Python syntax.

Page 24: MARC Tutorials

Marc Python Tutorial1-8

Python Data Types

When programming in Python you don’t explicitly declare a variable’s data type. Python determines the "data type" by how the variable is used. Python supports the following implied data types:

Basic Data Types

string

A character string similar to the char data in C and character in FORTRAN. a string may be specified using either single or double quotes.

float

A floating point number similar to the double data type in C and the real*8 data type in FORTRAN.

integer

An integer or fixed point number similar to the long int data type in C and the integer*8 data type in FORTRAN.

Extended Data Types

List

A Python list is essentially a linked list that can be accessed like an array using the square bracket operators "[ ]". The list can be composed of strings, floats or integers to name a few.

The material covered in this tutorial is very basic and should be easy to access and understand for the first time Python user. Once you have worked through the sample sessions in Part II you should feel comfortable enough to do a complete analysis simply by extrapolating from what you have learned in the example problems.

A multi-dimension list is created by first creating a single dimensional list and then creating the other dimensions, as follows (a 3x2 array):

A = [None] * 3for i in range(3) A[i] = [None] * 2

Page 25: MARC Tutorials

Chapter 2: PyMentat: A Simple Example

CHAPTER

2 PyMentat: A Simple Example

■ Chapter Overview

■ Creating a Simple Python Script for Marc Mentat

■ Python Programming Hints

■ Running the Script

Page 26: MARC Tutorials

Marc Python Tutorial2-2

Chapter OverviewIn this section, it will be demonstrated how to create a basic Python script that sends commands to Marc Mentat. For this purpose, a rectangular grid of elements will be created. Upon completion of this chapter, you should have a clearer understanding of the following areas:

• The basics for a PyMentat script

• How a Python script communicates with Marc Mentat

• Python Menu layout

Page 27: MARC Tutorials

2-3CHAPTER 2PyMentat: A Simple Example

Creating a Simple Python Script for Marc MentatTo begin, we will examine a script that creates a simple element grid. This example is named chap2.py and can be found in the Marc Mentat directory examples/python/tutorial/c02. Note that the first Python statement contains.

1 from py_mentat import *

This statement will import the PyMentat module into the Python script. It must be used in all Python scripts that will need to access the PyMentat module.

The remaining code that creates the grid is as follows:

2 # Create the node grid

3 def make_nodes(s,t, xs, ys):

4 y= ys

5 z = 0.0

6 delx = 1.0/s

7 dely = 1.0/t

8 for i in range(0,t):

9 x = xs

10 for j in range(0,s):

11 str = "*add_nodes %f %f %f" % (x, y, z)

12 py_send(str)

13 x = x + delx

14 y = y + dely

15 return

16

17 # Create the element grid

18 def make_elements(n,m):

19 for i in range(1,m): # the "y" dir

20 n1 = (i-1) * (n) + 1

21 n2 = n1 + 1

22 n4 = n1 + (n)

23 n3 = n2 + (n)

24 for j in range(1,n): # the "x" dir

25 str = "*add_elements %d %d %d %d" %(n1,n2,n3,n4)

26 py_send(str)

Page 28: MARC Tutorials

Marc Python Tutorial2-4

27 n1 = n1 + 1

28 n2 = n2 + 1

29 n3 = n3 + 1

30 n4 = n4 + 1

31 return

32

33 def main():

34 n = 6

35 m = 8

36 xs = -1.0

37 ys = -1.0

38 make_nodes(n,m,xs,ys)

39 make_elements(n,m)

40 return

Lines 2-15 The make_nodes routine will create a grid of s x t nodes, starting in the lower left hand corner at the point (xs, ys, 0.0). The function range is a built-in Python function that builds a Python list of integers. Note line 11: This is where the Marc Mentat command string for adding a node is composed. The *add_nodes command is placed in a Python string, along with the x,y,z node coordinates. The statement uses Python’s % operator. It is used on string objects, and works much like C’s sprintf function. A “%f”, “%g”, or “%e” designates a floating point number, and a “%d” designates an integer. The objects on the right of the % symbol are paired with the conversion codes starting with the first % code inside the quoted string. The py_send routine is called with the string to send the command string to Marc Mentat, at which time it will run the command string just as if it was typed in the Marc Mentat dialogue area.

Lines 18-31 The make_elements routine will perform the element connectivity of the node grid using the Marc Mentat command *add_elements. The loop beginning in line 24 will build the elements moving across the node grid in the X-direction and up the grid in the Y-direction.

Lines 33-40 The main routine will set the size of the grid and the starting position.

Page 29: MARC Tutorials

2-5CHAPTER 2PyMentat: A Simple Example

Python Programming HintsIn this example, some Python functions (or routines) were created to build the grid. A Python function is defined with the compound statement def. The syntax is:

def NAME ’(’ [args] ’)’ ’:’

What follows after the colon is the code that comprises the function. The lines of Python code that define the function must be indented at least one space. To end the function definition, the code is "deindented".

The range function is used quite often in these examples. When the range function is used, Python builds a "list" of integers starting at the first value and ending at one less than the last value. For example, the statement:

for i in range(0,5):

is actually executed as

for i in [0,1,2,3,4]:

In the Python script shown, a string is created and sent to Marc Mentat using the py_send routine. The string could also be built in the calling argument for py_send, as shown below:

py_send("*add_nodes %f %f %f" % (x, y, z))

The command and the floating point values to be passed are specified in the calling argument.

Page 30: MARC Tutorials

Marc Python Tutorial2-6

Running the ScriptStart Marc Mentat, and from the main screen select the following menu buttons.

MAINUTILS

PYTHON

This will bring up the Python Menu screen as shown in Figure 2-1.

Figure 2-1 Python Menu Screen

Page 31: MARC Tutorials

2-7CHAPTER 2PyMentat: A Simple Example

To run the script, select the RUN button. The other menu items in Figure 2-1 will be discussed in a later chapter on sockets. When the RUN button is selected the browser window as shown in Figure 2-2 will appear.

Figure 2-2 The Python Browser Window

Page 32: MARC Tutorials

Marc Python Tutorial2-8

Note the button named RUN AS SEPARATE PROCESS. This will run the script in a separate window and communicate to Marc Mentat using a BSD socket connection. This item will be discussed in a later chapter. In order to use this option, a Python script would need to use the py_connect routine to complete the socket connection with Marc Mentat. This will be discussed in the next chapter. Do not select this option for this example. Browse to the examples/python/c02 directory and select the file chap2.py. Then select OK to run the script.

When the script completes, a mesh will be created as shown in Figure 2-3.

Figure 2-3 Python Menu Screen with a Created Mesh

In the next chapter, we will modify the script to use Marc Mentat PARAMETERS to create a variably sized grid.

Page 33: MARC Tutorials

Chapter 3: PyMentat: Obtaining Data from Mentat

CHAPTER

3 PyMentat: Obtaining Data from Marc Mentat

■ Chapter Overview

■ Creating a Simple Python Script for Marc Mentat

■ The py_get_int and py_get_float methods

■ Running the Script

Page 34: MARC Tutorials

Marc Python Tutorial3-2

Chapter OverviewIn this chapter, it will be demonstrated how to use Marc Mentat PARAMETERS in a Python script using the PyMentat module. It will also be shown how to run a Python script as a separate process. Upon completion of this chapter, you should have a clearer understanding of the following areas:

• The py_get_int and py_get_float methods

Page 35: MARC Tutorials

3-3CHAPTER 3PyMentat: Obtaining Data from Marc Mentat

Creating a Simple Python Script for Marc MentatTo continue with the example discussed in Chapter 2, we will examine a script that creates a simple element grid and uses Marc Mentat parameters to control the size of the grid. This example is named chap3.py and can be found in the Marc Mentat directory examples/python/tutorial/c03. The script is as follows:

1 from py_mentat import *

2 # Create the node grid

3 def make_nodes(s, t, xs, ys):

4 y= ys

5 z = 0.0

6 delx = 1.0/s

7 dely = 1.0/t

8 for i in range(0,t):

9 x = xs

10 for j in range(0,s):

11 str = "*add_nodes %f %f %f" % (x, y, z)

12 py_send(str)

13 x = x + delx

14 y = y + dely

15 return

16

17 # Create the element grid

18 def make_elements(n,m):

19 for i in range(1,m): # the "y" dir

20 n1 = (i-1) * (n) + 1

21 n2 = n1 + 1

22 n4 = n1 + (n)

23 n3 = n2 + (n)

24 for j in range(1,n): # the "x" dir

25 str = "*add_elements %d %d %d %d"(n1,n2,n3,n4)

26 py_send(str)

27 n1 = n1 + 1

28 n2 = n2 + 1

29 n3 = n3 + 1

Page 36: MARC Tutorials

Marc Python Tutorial3-4

30 n4 = n4 + 1

31 return

32

33 def main():

34 n = py_get_int("x_size")

35 m = py_get_int("y_size")

36 xs = py_get_float("x_start")

37 ys = py_get_float("y_start")

38 make_nodes(n,m,xs,ys)

39 make_elements(n,m)

40

41 if __name__ == ’__main__’:

42 py_connect("",40007)

43 main()

44 py_disconnect()

Lines 2-31 The make_nodes and make_elements routines are the same as in the previous chapter.

Lines 33-39 The main routine will obtain the values for the size of the grid and the starting point from Marc Mentat using parameters. The py_get_int method will evaluate a formula and return an integer (fixed point) result similar to the *calculator command. The py_get_float method will evaluate a formula and return a floating point number. In this case these methods obtain the values for these parameters.

Lines 41-44 If the script is invoked as a separate process, (such as “python chap3.py”), then the Python interpreter sets the Python variable __name__ to the string ‘__main__’. If this is the case, then the Python script should attempt to make a socket connection to Marc Mentat. The py_connect method will be discussed in more detail in a later chapter.

Page 37: MARC Tutorials

3-5CHAPTER 3PyMentat: Obtaining Data from Marc Mentat

The py_get_int and py_get_float methodsThe py_get_int and py_get_float methods provide access to Marc Mentat PARAMETERS and Arithmetic or Database functions. Using Marc Mentat parameters is the method to pass variables from Marc Mentat to a PyMentat script. These variables are obtained through PyMentat by specifying the name of the parameter or function in the string passed to the py_get_int or py_get_float method. These parameters may be combined with any of the Arithmetic or Database functions described in the Marc Python Reference Manual.

When using the py_get_int or py_get_float methods, they must be used on a system of the same byte architecture. The values are not converted to a machine independent format before being transmitted.

Running the ScriptFirst, start Marc Mentat. Before running this example, some PARAMETERS need to be defined. The values for these parameters will be obtained by the Python script to control the size and the position of the grid.

Select the following menus:

MAINUTILS

PARAMETERSNEW PARAMETER

x_size10y_size8x_start-1.0y_start-1.0

Remember to press the carriage <CR> after typing in each of the numbers to create the parameters. The procedure file chap3.proc may be executed to perform the above commands for you if you wish.

Page 38: MARC Tutorials

Marc Python Tutorial3-6

You may also type the *define command in Marc Mentat’s command prompt window to create or edit the parameter. For example, to create the parameter x_size you would type

*define x_size 10

As in the previous chapter, bring up the Python browser window with the menus:

MAINUTILS

PYTHONRUN

When the script completes, a mesh will be created the same as in the previous chapter.

Page 39: MARC Tutorials

Chapter 4: PyMentat: Building Complex Geometry

CHAPTER

4 PyMentat: Building Complex Geometry

■ Chapter Overview

■ Background Information

■ Running the Script

Page 40: MARC Tutorials

Marc Python Tutorial4-2

Chapter OverviewIn this chapter, it will be demonstrated how to build more complex geometry using Python. To continue with the example discussed in Chapter 3, we will examine a script that creates a more complex model. This example uses Marc Mentat’s User-defined menu to present a simple menu for controlling the model’s properties.

Upon completion of this chapter, you should have a clearer understanding of the following areas:

• Adding points, curves, and lines

• Become more familiar with Python programming

Page 41: MARC Tutorials

4-3CHAPTER 4PyMentat: Building Complex Geometry

Background InformationA rectangular plate of user defined width and height contains a varying number of holes of user defined diameter d, equally spaced by a user defined distance s. It is desired that the Python script determine how many holes can be placed in the plate, and center the array of holes in the plate with the distance from any edge to the nearest hole to be at least the distance s.

Figure 4-1 Plate with varying Number of Holes

width

heig

ht

t=.75

X

Y

d d

dd

dd

d

d

d

s

Page 42: MARC Tutorials

Marc Python Tutorial4-4

This example is named chap4.py and can be found in the Marc Mentat directory examples/python/tutorial/c04. The following is the Python script:

1 from py_mentat import *

2 def add_plate(xs,ys,width, height):

3 py_send("*set_curve_type line")

4 py_send("*add_points")

5 py_send("%f %f 0" % (xs, ys))

6 py_send("%f %f 0" % (xs+width, ys))

7 py_send("%f %f 0" % (xs+width, ys+height))

8 py_send("%f %f 0" % (xs, ys+height))

9 py_send("*set_curve_type line")

10 py_send("*add_curves")

11 py_send("1 2")

12 py_send("2 3")

13 py_send("3 4")

14 py_send("4 1")

15 py_send("*fill_view")

16 return

17

18 def build_plate(xstart,ystart,width, height, diameter,spacing):

19 f = diameter+spacing

20 nx = int((width-spacing)/f)

21 ny = int((height-spacing)/f)

22 if (nx < 1 or ny < 1 ):

23 print "Holes are too big!"

24 return 1

25 print "creating hole grid of ",nx, " by ",ny

26

27 add_plate(xs,ys,width,height)

28 xs = .5 * (width - f * (nx - 1)) + xstart

29 ys = .5 * (height - f * (ny - 1)) + ystart

30 py_send("*set_curve_type circle_cr")

31 py_send("*add_curves")

32 r = diameter / 2

Page 43: MARC Tutorials

4-5CHAPTER 4PyMentat: Building Complex Geometry

33 for i in range(0, ny) :

34 y = ys + i * f

35 for j in range(0, nx) :

36 x = xs + j * f

37 py_send("%f %f 0 %f" % (x, y, r))

38 return 0

39

40 def main():

41 width = py_get_float("width")

42 height = py_get_float("height")

43 diameter = py_get_float("diameter")

44 spacing = py_get_float("spacing")

45 xstart = -width/2

46 ystart = -height/2

47 build_plate(xstart,ystart,width, height, diameter,spacing)

48 return

49

50 if __name__ == ’__main__’:

51 py_connect("127.0.0.1",40007)

52 main()

Lines 2-16 The add_plate routine will create the plate using 4 connected curves. It first generates the end points of the curve using the *add_points command and then creates the curves by connecting the points with the *add_curves commands. In line 15, the *fill_view command is issued to center and fill the plate properly on the screen.

Lines 18-38 The build_plate routine will calculate the number of holes that can be placed in the plate and create them in their proper position. The variables nx and ny in lines 20 and 21 are the number of holes to be placed in the x and y direction, respectively. The Python int function is used to force the values to be an integer. Once it has been determined that the plate is big enough to contain at least one hole, the add_plate routine is called in line 27 to create the plate itself. The initial x and y position for the first hole is calculated in lines 28-29. The loop in lines 38-44 controls the

Page 44: MARC Tutorials

Marc Python Tutorial4-6

vertical (height) placement, and the inner loop in lines 35-37 controls the horizontal (width) placement.

Lines 40-48 The main routine will obtain the values for the size of the plate, the diameter of the holes, and the spacing between holes from Marc Mentat. The lower left corner of the plate is calculated in lines 45-46 so that the plate has its center at (0,0). The build_plate routine is then called to create the geometry.

Lines 50-52 If run in a separate process, make a socket connection to Marc Mentat.

Running the ScriptStart Marc Mentat and use the FILES menu SET DIRECTORY button to specify examples/python/tutorial/c04 as the current directory. The parameters used in this model may be specified with the USER DEFINED menu HOLES IN PLATE (Python). Enter the following values for this example:

WIDTH12.0

HEIGHT8.0

DIAMETER.75

SPACING0.4

MESH SIZE0.2

Remember to press the carriage return <CR> after typing in the numbers. Note that the MESH SIZE parameter is not used in this example. When you specify these values, the menu creates these parameters in Marc Mentat, and the values for these parameters will be obtained by the Python script to control the number of holes in the plate. Select the BUILD button to create the model.

Page 45: MARC Tutorials

4-7CHAPTER 4PyMentat: Building Complex Geometry

When the script completes, a plate will be created as shown in Figure 4-2.

.

Figure 4-2 Resulting Plate with Holes

In the next chapter, we will mesh the plate and add the geometric and material properties, boundary conditions, and job parameters.

Page 46: MARC Tutorials

Marc Python Tutorial4-8

Page 47: MARC Tutorials

Chapter 5: PyMentat: Adding Model Properties

CHAPTER

5 PyMentat: Adding Model Properties

■ Chapter Overview

■ Plate Properties

■ Node and Element Id’s

■ Running the Script

■ Submitting the Job

Page 48: MARC Tutorials

Marc Python Tutorial5-2

Chapter OverviewIn this chapter, it will be demonstrated how to add properties to the geometry create in the previous chapter.

Upon completion of this chapter, you should have a clearer understanding of the following areas:

• Using the Database functions

• Node and Element id’s

Page 49: MARC Tutorials

5-3CHAPTER 5PyMentat: Adding Model Properties

Plate PropertiesAs shown in the previous chapter, a rectangular plate of user defined width and height contains a varying number of holes of user defined diameter d, equally spaced by a distance s specified by the user. The array of holes will be centered in the plate, with the distance from any edge to the nearest hole to be at least the distance s.

Figure 5-1 Plate with Varying Number of Holes

In this chapter, we will update the Python script to apply the properties described in Figure 5-1 to the plate. The material behavior is linear elastic with Young’s modulus E = 30e6 and Poisson’s ratio ν = 0.3. A compression load with magnitude p = 1000

Lb/in2 will be applied to the top of the plate.

width

heig

ht

t=.75

X

Y

d d

dd

dd

d

d

d

s

1000 Lb/in2

fixed

Page 50: MARC Tutorials

Marc Python Tutorial5-4

This example is named chap5.py and can be found in the Marc Mentat directory examples/python/tutorial/c05. The following Python code has been added to the code shown in the previous chapter:

79 # check if f1 == f2 within tolerance of tol

80 def check_tol(f1, f2, tol):

81 if f1 == f2:

82 return 1

83 if f1 + tol < f2:

84 if f1 - tol > f2:

85 return 1

86 return 0

87

88 def mesh_plate(width, height, diameter, spacing):

89 py_send("*set_curve_div_type_fix_avgl")

90 l = spacing/2.0

91 py_send("*set_curve_div_avgl %f" % l)

92 py_send("*apply_curve_divisions all_existing")

93 py_send("*dt_planar_trimesh all_existing")

94 return

95

96 def add_bc(xs,ys,width,height):

97 py_send("*renumber_all")

98 n = py_get_int("nnodes()")

99 # add fixed bc at left edge

100 py_send("*apply_type fixed_displacement")

101 py_send("*apply_dof x")

102 py_send("*apply_dof y")

103 py_send("*apply_dof z")

104

105 node_list = []

106 for i in range(1,n+1):

107 str = "node_x(%d)" % i

108 f = py_get_float(str)

109 if check_tol(f, xs, .001):

110 node_list.append(i)

Page 51: MARC Tutorials

5-5CHAPTER 5PyMentat: Adding Model Properties

111

112 py_send("*add_apply_nodes ")

113 for i in range(0,len(node_list)):

114 str = "%d " % node_list[i]

115 py_send(str)

116 py_send(" # ")

117 # add edge load at top

118 py_send("*new_apply")

119 py_send("*apply_type edge_load")

120 py_send("*apply_value p 1000.0 ")

121 py_send("*add_apply_curves 3 #")

122 return

123

124 def add_matl():

125 py_send("*material_type mechanical:isotropic")

126 py_send("*material_value isotropic:youngs_modulus3e7 .3")

127 py_send("*add_material_elements all_existing")

128 return

129

130 def add_job():

131 py_send("*loadcase_type static")

132 py_send("*job_class mechanical")

133 py_send("*job_option dimen:pstress")

134 py_send("*add_post_tensor stress")

135 py_send("*add_post_var von_mises")

136 py_send("*element_type 6 all_existing")

137 py_send("*element_type 6 all_existing")

138 return

139

140 def add_geom_prop():

141 py_send("*geometry_type mech_planar_pstress ")

142 py_send("*geometry_value thick .75")

143 py_send("*add_geometry_elements all_existing")

144 return

Page 52: MARC Tutorials

Marc Python Tutorial5-6

145

146 def main():

147 xs = 0.0

148 ys = 0.0

149 width = py_get_float("width")

150 height = py_get_float("height")

151 diameter = py_get_float("diameter")

152 spacing = py_get_float("spacing")

153 build_plate(xs,ys,width, height, diameter, spacing)

154 mesh_plate(width, height, diameter, spacing)

155 add_bc(xs,ys,width, height)

156 add_matl()

157 add_geom_prop()

158 add_job()

159 py_send("save_as_model chap5.mfd yes")

160 return

161

162 if __name__ == ’__main__’:

163 py_connect("",40007)

164 main()

165 py_disconnect()

166

Lines 2-8 The check_tol routine is a convenience function to compare two floating point number for equality within a certain tolerance.

Lines 10-17 The mesh_plate routine will generate a 2-D planar Delaunay triangle mesh. To generate the curve divisions, the spacing between the holes is used to control the average length of the segments.

Lines 19-46 The add_bc routine will create the boundary conditions for the plate. The left edge of the plate is fixed, and the top edge of the plate has an edge load. We first obtain the number of nodes using the Database function nnodes in line 3. In line 11, we renumber all the nodes in the database so that the node index is the same as the node id. This will be discussed more in detail later in this chapter. We set the displacement type to be fixed in lines 6-12. The code in lines 14-20 will search through

Page 53: MARC Tutorials

5-7CHAPTER 5PyMentat: Adding Model Properties

the entire node list looking for a node that lies on the left edge of the plate by examining it’s position in the X direction. If a match is found, we obtain the node id (which may be different from it’s index position in the database) and store that in our node_list. In lines 21-25, the command *add_apply_nodes is used to apply the fixed boundary conditions. We loop through the node_list and send the id’s, and then "#" symbol to signal the "End List" command. Lines 28-31 is where the top edge load is created. Here we simply apply the load to the curve at the top of the plate (curve number 3).

Lines 48-52 The add_matl routine will apply the material properties to all the elements of the plate.

Lines 54-61 The add_job routine will create the necessary job parameters.

Lines 63-67 The add_geom_prop routine will apply the necessary geometric properties.

Lines 69-83 The main routine is similar to that of Chapter 4, however, the additional routines are called to add the boundary conditions, the material properties, the geometric properties and the job parameters.

Page 54: MARC Tutorials

Marc Python Tutorial5-8

Node and Element Id’sThe Database functions use node and element id’s (similar to labels) as their arguments. In the add_bc routine of our Python script we issue the renumber_all command. This command will renumber all of the entities in the model. This ensures that the index value passed to the database function node_x is the same as that of the loop value. We need to do this because the entities (nodes in this case) are stored in the database as a linked list as shown in Figure 5-2.

Figure 5-2 A Linked List of Nodes

x = -1.0y = -1.0z = 0.0id = 1

x = 1.0y = -1.0z = 0.0id = 2

x = 1.0y = 1.0z = 0.0id = 3

x = -1.0y = 1.0z = 0.0id = 4

Page 55: MARC Tutorials

5-9CHAPTER 5PyMentat: Adding Model Properties

The linked list of nodes in Figure 5-2 shows a square grid of nodes 1,2,3,4. If node 2 is deleted, then the list would become 1,3,4 as shown in Figure 5-3.

Figure 5-3 A Linked List of Nodes with Node 2 Deleted

If the database function node_id is now called with the value of 2, it will return 3, since the second item in the list is node 3. If the command renumber_all is issued, then the nodes will be renumbered to the sequence 1,2,3 and node_id(2) will return 2.

If we did not issue the renumber_all command, then the code sequence in lines 20-24 would need to be:

for i in range(1,n+1): str = "node_id(%d)" % i j = py_get_int(str) str = "node_x(%d)" % j f = py_get_float(str) if check_tol(f, xs, .001):

node_list.append(j)

We want to avoid using the node_id function as much as possible because it needs to search the entire database to find the node.

x = -1.0y = -1.0z = 0.0id = 1

x = 1.0y = 1.0z = 0.0id = 3

x = -1.0y = 1.0z = 0.0id = 4

Page 56: MARC Tutorials

Marc Python Tutorial5-10

Running the ScriptYou may run the procedure file chap5.proc to set the parameters or you may specify them using the UTIL submenu PARAMETERS as follows:

UTILPARAMETERS

NEW PARAMETERWIDTH

8.0HEIGHT

4.0DIAMETER

1.0SPACING

0.5

Remember to press the carriage return <CR> after typing in each of the numbers. Select the BUILD button to create the model.

When the script completes, a mesh will be created as shown in Figure 5-4.

Page 57: MARC Tutorials

5-11CHAPTER 5PyMentat: Adding Model Properties

Figure 5-4 Resulting Mesh with Boundary Conditions Applied

Submitting the JobYou may run the job by using the following menus:

MAINJOBS

RUNSUBMIT 1

In the next chapter, we will examine postprocessing using the PyMentat module.

Page 58: MARC Tutorials

Marc Python Tutorial5-12

Page 59: MARC Tutorials

Chapter 6: PyMentat: Processing a Post File

CHAPTER

6 PyMentat: Processing a Post File

■ Chapter Overview

■ Postprocessing Basics

■ Scalar Values

■ Running the Script

Page 60: MARC Tutorials

Marc Python Tutorial6-2

Chapter OverviewIn this chapter, it will be demonstrated how to use the Postprocessing commands of Marc Mentat in a Python script. This example will use the post file of the example created in the previous chapter.

Upon completion of this chapter, you should have a clearer understanding of the following areas:

• The basics of using PyMentat for Postprocessing

• How to write an efficient PyMentat postprocessing PyMentat script

• Selecting nodes for display

Page 61: MARC Tutorials

6-3CHAPTER 6PyMentat: Processing a Post File

Postprocessing BasicsPyMentat may also be used to post process a post file.

In this example, we will obtain all of the nodal scalar values on the post file generated by running the example in the previous chapter.

This example is named chap6.py and can be found in the Marc Mentat directory examples/python/tutorial/c06. The following is the Python code:

1 from py_mentat import *

2

3 def main():

4 py_send("*post_close")

5 py_send("*post_open chap6_job1.t16")

6 py_send("*post_next")

7 py_send("*fill_view")

8 py_send("*post_contour_lines")

9

10 n = py_get_int("nnodes()") # get number of nodes

11 label = []

12 label.append("*post_value Displacement x")

13 label.append("*post_value Displacement y")

14 label.append("*post_value External Force x")

15 label.append("*post_value External Force y")

16 label.append("*post_value Reaction Force x")

17 label.append("*post_value Reaction Force y")

18

19 max_scalars = []

20 max_nodes = []

21 for i in range(0,6):

22 max_scalars.append(0.0)

23 max_nodes.append(0)

24 str = "*post_value " + label[i]

25 py_send(str)

26

27 j = 1

28 while j <= n:

Page 62: MARC Tutorials

Marc Python Tutorial6-4

29 str = "node_id(%d)" % j

30 n_id = py_get_int(str)

31 str = "post_node_extra(%d)" % n_id

32 flag = py_get_int(str)

33 if flag == 0: # check for valid post node

34 str = "scalar_1(%d)" % n_id

35 f = py_get_float(str)

36 if f < 0.0:

37 f = -f

38 if f > max_scalars[i]

39 max_scalars[i] = f

40 max_nodes[i] = n_id

41 j = j + 1

42

43 py_send("*draw_legend off")

44 py_send("*unpost_nodes all_existing")

45 py_send("*post_nodes ")

46

47 print " Label node scalar"

48 print " ------------------------------------------"

49 for i in range(0,nns):

50 j = max_nodes[i]

51 str = " %18s %10i %g" % (label[i],p.py_node_id(j),max_scalars[i])

52 print str

53 py_send( max_nodes[i] )

54 py_send(" #")

55 py_send("*post_numerics")

56 return

57# Use database functions to find max/min

58 print " "

59 print " Label node scalar"

60 print " ------------------------------------------"

61 for i in range(0,len(label)):

62 str = "*post_value " + label[i]

Page 63: MARC Tutorials

6-5CHAPTER 6PyMentat: Processing a Post File

63 py_send(str)

64 str = "node_id(%d)" % j

65 n_id = py_get_int("scalar_max_node()")

66 str = "scalar_1(%d)" % n_id

67 d = py_get_float(str)

68 n_id2 = py_get_int("scalar_min_node()")

69 str = "scalar_1(%d)" % n_id

70 f = py_get_float(str)

71 if d < -f:

72 d = -f

73 n_id = n_id2

74 str = " %18s %10i %g" % (label[i],n_id, d)

75 print str

76 return

77

78 if __name__ == '__main__':

79 py_connect('',40007)

80 main()

81 py_disconnect()

Lines 4-7 These statements open the post file and setup some options. We need to do a *post_next in line 6 so that we are at "increment 0" in Marc terminology.

Line 8 We need to tell Marc Mentat that we are working with scalar values, so one of the SCALAR PLOT commands need to be sent.

Line 10 This statement will get the number of nodes in the model. Note that this number may change at different increments due to rezoning.

Lines 11-17 A Python list is used to store the names of the nodal scalars that are in the post file. This is a convenient way of storing the names for use later. A Python list has an append method, and it is used to add the desired string to the list. Note that a Python list can be a list of anything, integers, floating points values, Python dictionaries or other lists.

Page 64: MARC Tutorials

Marc Python Tutorial6-6

Lines 19-20 The max_scalars and max_nodes variables are declared as Python Lists. The index of the list will be each of the scalars in the post file. The maximum scalar value will be stored in the max_scalars list. The node associated with the max_scalar value will be stored in the max_nodes list.

Lines 21 The loop for all of the scalars in our list.

Lines 22-23 We append initial values to our list. Remember that max_scalars and max_nodes are linked lists, so we must have the item added to the list before we access it.

Lines 24-25 Specify the scalar name to use.

Lines 28 Loop through all the nodes. Note that we use a while loop for this. We had been using the Python range function, however, for the range function Python builds a list of all the values in the range. If we had 100,000 nodes, Python would build a list with that many items.

Lines 29-30 Obtain the node id for this node.

Lines 31-32 Not all nodes in the post file are visible nodes. Some are nodes used explicitly by Marc to perform special functions and are considered "extra" nodes. The Database function post_node_extra will return 0 if a node is not an extra node, 1 if it is. This check is required to verify that the values obtained are true post file values at a node.

Lines 33-34 Obtain the scalar value using the Database function scalar_1.

Lines 35-36 We will use only positive values. If it is negative, then change it to positive.

Lines 37-39 Check the current value against the highest value in our list.

Line 43 Turn off the legend.

Lines 44-45 We need to remove all nodes from the post nodes list and then start the *post_nodes selection. Note that once the *post_nodes selection process has begun, we cannot call any of the py_get routines.

Line 43 Start the *select_node command.

Page 65: MARC Tutorials

6-7CHAPTER 6PyMentat: Processing a Post File

Lines 47-52 Print out the results for each scalar.

Line 53 Send this node as one of the nodes to select. Note that we use the Python backquote operator which converts an integer for a float into a string.

Line 54 Send the "#" symbol to signify "End of List".

Line 55 Turn on NUMERICS.

Line 58-76 This section uses the database functions to find the node with the maximum (or minimum) value. It loops through all the post values in the list, and then calls scalar_max_node and scalar_min_node to obtain the node number at which the largest and smallest values occur. It then calls the function scalar_1 to obtain the value associated with that node.

Scalar ValuesUsing the PyMentat module for postprocessing is somewhat complex: you have to know what the scalar labels are, check for valid nodes, etc. The PyPost module avoids this by providing methods to obtain what these items are.

Running the ScriptThis script runs the same way as in the previous examples. Bring up the Python browser and browse to the Marc Mentat directory examples/python/tutorial/c06 and run the Python script chap6.py. The output will appear as shown in Figure 6-1 for both runs where it searches the node list and using the Database functions.

Figure 6-1 Resulting Output from chap6.py

Label node scalar ------------------------------------------- Displacement x 53 0.00128282 Displacement y 49 0.00565143 External Force x 0 0 External Force y 50 187.5 Reaction Force x 82 2866.6 Reaction Force y 81 921.814

Page 66: MARC Tutorials

Marc Python Tutorial6-8

Figure 6-2 Resulting Post Plot from chap6.py

In the next chapter, we will examine the post file using the Python module PyPost.

Page 67: MARC Tutorials

Chapter 7: PyMentat: Sets

CHAPTER

7 PyMentat: Obtaining Model Data

■ Chapter Overview

■ Database Properties Basics

■ A Sample Script to Extract Data

■ Running the Script

■ Set Id’s and Set Names

Page 68: MARC Tutorials

Marc Python Tutorial

7-2

Chapter OverviewIn this chapter, it will be demonstrated how to obtain information regarding sets and to how to extract database properties in a Python script . This example will use a simple model containing various sets and database properties.

Upon completion of this chapter, you should have a clearer understanding of the following areas:

• The basics of sets in Mentat

• How to query set information in a Python script

• How to obtain database properties

• How to obtain element data

Page 69: MARC Tutorials

CHAPTER 7PyMentat: Obtaining Model Data

7-3

Database Properties BasicsDatabase properties can be obtained using a number of methods that return the data stored in Mentat’s database. Mentat has functions that supports the following items:

• adapg Global adaptive remeshing criteria.

• apply Boundary condition properties.

• cbody Contact body data.

• ctable Contact table data

• geom Geometric properties.

• icond Initial condition properties.

• material Material properties.

• lcases Loadcase data.

• jobs Job data.

Specific element properties may also be obtained using a number of methods that return the name of the item for each element. Mentat provides the following element property methods:

• element_cbody Name of contact body that the element belongs.

• element_geom Name of the geometric property that the element belongs.

• element_material Name of the material property that the element belongs.

• element_orient Name of the orientation property that the element belongs.

Page 70: MARC Tutorials

Marc Python Tutorial

7-4

Set BasicsThe use of sets help to group items together to make it easier to reference them later. Mentat supports the following set types:

• node The set contains the node id’s of its entries.

• element The set contains the element id’s of its entries.

• point The set contains the point id’s of its entries.

• curve The set contains the curve id’s of its entries.

• surface The set contains the surface id’s of its entries.

• edge The set contains the element id’s and the edge number of its entries.

• face The set contains the element id’s and the face number of its entries.

A number of database functions are available in Mentat to support sets. The list of functions may be found in the Marc Python Reference Manual, Appendix A, Table A-2 on page 4.

A Mentat model may contain any number of sets. The database function nsets is used to obtain the number of sets in a model. Sets are referenced by its set id. The set id is obtained using the database function set_id, which takes an index number as its only argument. The remaining set functions use the set id to refer to the set, however, Mentat refers to sets by name. The set name is obtained using the set_name function, and the set type is obtained using the set_type function.

Each set in turn may contain multiple entries. The number of entries can be obtained using the function nset_entries. The values for the entries are obtained using the set_entry function, which returns a single value. If the set type is an edge set or a face set, the second value, the edge, or face number is obtained by calling the set_edge or set_face function, respectively.

Page 71: MARC Tutorials

CHAPTER 7PyMentat: Obtaining Model Data

7-5

A Sample Script to Extract DataIn this example, we will obtain some database and set information in a simple Mentat model.

This example is named chap7.py and can be found in the Mentat directory examples/python/tutorial/c07. The following is the Python code:

1 from py_mentat import *

2 def main():

3 py_send("*new_model yes *open_model sets.mfd")

4

5 m = py_get_int("nsets()")

6 print "Found ",m," sets"

7

8 for i in range(1,m+1):

9 id = py_get_int("set_id(%d)" % i)

10 sn = py_get_string("set_name(%d)" % id)

11 st = py_get_string("set_type(%d)" % id)

12 n = py_get_int("nset_entries(%d)" % id)

13

14 if stype not in ("icond","apply","lcase"):

15 print "Set ",sn,"is a ",stype," set with ",n,"entries"

16 for j in range(1,n+1):

17 k = py_get_int("set_entry(%d,%d)" % (id, j))

18 print " entry ",j," is ",k,

19 if (stype == 'face'):

20 l = py_get_int("set_edge(%d,%d)" % (id, j))

21 print " face number ",l

22 elif(stype == 'edge'):

23 l = py_get_int("set_edge(%d,%d)" % (id, j))

24 print " edge number ",l

25 else:

26 print " "

Page 72: MARC Tutorials

Marc Python Tutorial

7-6

27

28 print " "

29 m = py_get_int("ncbodys()")

30 print "Found ",m," Contact Bodys"

31 for i in range(1,m+1):

32 sn = py_get_string("cbody_name_index(%d)" % i)

33 id = py_get_int("cbody_id(%s)" % sn)

34 print " Contact Body ", i, " Id ",id, " Name ", sn

35

36 m = py_get_int("nmaterials()")

37 print "\n Materials ",m

38 for i in range(1,m+1):

39 sn = py_get_string("material_name_index(%d)" % i)

40 st = py_get_string("material_type(%s)" % sn)

41 p = py_get_float("material_par (%s,isotropic:youngs_modulus)" % sn)

42 str = " Material %14s Type %19s Young's Mod %g" % (sn,st,p)

43 print str

44 mt = py_get_string("material_opt( %s,plasticity:method)" % sn)

45 st = py_get_string("material_opt( %s,plasticity:yield)" % sn)

46 str = " Plasticity method %9s Yield Surface %s" % (mt, st)

47 print str

48

49 m = py_get_int("napplys()")

50 print "\n Boundary Conditions ",m

51 for i in range(1,m+1):

52 sn = py_get_string("apply_name_index(%d)" % i)

53 st = py_get_string("apply_type(%s)" % sn)

54 so = py_get_string("apply_opt(%s,dof_values)"% sn)

Page 73: MARC Tutorials

CHAPTER 7PyMentat: Obtaining Model Data

7-7

55 str = " Boundary Cond %14s Type %19s Values by: %s" % (sn,st,so)

56 print str

57

58 m = py_get_int("ngeoms()")

59 print "\n Geometric Properties ",m

60 for i in range(1,m+1):

61 sn = py_get_string("geom_name_index(%d)" % i)

62 st = py_get_string("geom_type(%s)" % sn)

63 p = py_get_float("geom_par(%s,thick)" % sn)

64 str = " Geometric Prop %12s Type %19s Thick %g" % (sn,st,p)

65 print str

66

67 m = py_get_int("niconds()")

68 print "\n Initial Conditions ",m

69 for i in range(1,m+1):

70 sn = py_get_string("icond_name_index(%d)" % i)

71 st = py_get_string("icond_type(%s)" % sn)

72 so = py_get_string("icond_opt(%s,dof_values)" % sn)

73 str = " Initial Cond %14s Type %12s Values by: %s" % (sn,st,so)

74 print str

75

76 print ""

77 sn = py_get_string("material_name()")

78 print " Current material data: ", sn

79 st = py_get_string("material_type(%s)" % sn)

80 print " Type : ", st

81 e = py_get_data( "material:isotropic:youngs_modulus")

82 print " Youngs Modulus : ", e

83 p = py_get_data("material:isotropic:poissons_ratio")

84 print " Poissons Ratio : ", p

Page 74: MARC Tutorials

Marc Python Tutorial

7-8

85 ys = py_get_data("material:plasticity:yield_stress")

86 print " Yield Stress : ", ys

87

88 print ""

89 sn = py_get_string("ctable_name()")

90 print " Contact Table ", sn

91 sn = "contact_table:the_mesh:refined_mesh:dist_tol"

92 dt = py_get_data(sn)

93 print " Contact Dist Tol : ", dt

94

95 print ""

96 sn = py_get_string("geom_name()")

97 print " Current geometry data: ", sn

98 thick = py_get_data("geometry:thick")

99 print " Thickness : ", thick

100

101 print ""

102 m = py_get_int("nelements()")

103 max_eid = py_get_int("max_element_id( )")

104 print " Elements ", m, " Maximum id ", max_eid

105 for i in range(1,m+1):

106 id = py_get_int("element_id(%d)" % i)

107 print ""

108 sn = "element_class(%d)" % id

109 e_class = py_get_int(sn)

110 sn = "element_family(%d)" % id

111 e_fam = py_get_int(sn)

112 e_ty = py_get_int(sn)

113 print " Element ", id, " Class ",e_cl," Family ",e_fam,", Type ",e_ty

114 cbn = py_get_string("element_cbody(%d)" % id)

115 gmn = py_get_string("element_geom(%d)" % id)

116 orn = py_get_string("element_orient(%d)" % id)

117 mtn = py_get_string("element_material(%d)"% id)

Page 75: MARC Tutorials

CHAPTER 7PyMentat: Obtaining Model Data

7-9

118 print " Contact Body : ", cbn

119 print " Geometry Property : ", gmn

120 print " Orientation : ", orn

121 print " Material Property : ", mtn

122

123 return

124

125 if __name__ == '__main__':

126 py_connect('',40007)

127 main()

128 py_disconnect()

Lines 3 Open the model to examine the set information.

Lines 5-6 Obtain and print the number of sets found. This uses the nsets Database function.

Line 8 Loop through all the sets in the model. The sets begin at 1.

Line 9 Obtain the set id. All of the set database functions will use the "Set Id" to locate the set information.

Line 10 Obtain the set name using the set_name database function.

Line 11 Obtain the set type using the set_type database function.

Line 12 Obtain the number of entries in his set.

Line 14 Ignore the loadcase, boundary condition (apply) and initial condition (icond) set types. These are associated with the loadcase data.

Line 15 Print the set header information.

Line 16 Loop through all the entries in this set.

Line 17 Using the set_entry database function, obtain each item, and print out the results.

Line 18-26 Depending on the set type, obtain the edge number or the face number if it is an edge or face set.

Page 76: MARC Tutorials

Marc Python Tutorial

7-10

Line 28-34 Obtain the number of contact bodies. For each contact body, get the contact body name based on its index, 1 - ncbodys using the cbody_name_index database function. Supplying an index of 0 will return the current contact body name. Also obtained is the contact body index. Note from the output that the index and id are not identical.

Line 36-74 In a manner similar to that for contact bodies, obtain the number of materials, boundary conditions, geometric properties and initial conditions. For each item, obtain the name using the index based name functions, xxx_name_index. Valid index values are from 1...m, where a value of 0 indicates the current item name. Note that in line 40 the function material_par is used to obtain a material parameter using a syntax similar to that used for py_get_data as described below. However, in the xxx_par methods the class token is not used.

Line 76-99 This code displays how to obtain some values of the current material and contact table using the py_get_data function. The syntax for this function is basically the same that is used in the command that sets the value. In this example, the value obtained is Young’s modulus. The command that sets the value is:

*material_value isotropic:youngs_modulus

The argument to the function will use the same parameter to obtain the value, with the first token specifying the class:

py_get_data(‘material:isotropic:youngs_modulus’)

sn=’contact_table::the_mesh:refined_mesh:dist_tol’)py_get_data(sn))

This function supports materials (material), contact bodies (contact_body), contact tables (contact_table), boundary conditions (apply), geometric properties (geometry), global remeshing (adapg), local adaptivity, (adapt) initial conditions (icond), loadcases (loadcase) and jobs (job). It provides multi-level data retrieval which is also supported in the function material_par. However, the py_get_data function only operates on the current item class.

Page 77: MARC Tutorials

CHAPTER 7PyMentat: Obtaining Model Data

7-11

Line 101-121 Obtain specific element information such as its class, type and familty. Also obtain the material, geometric property, orientation property and contact body in which it belongs.

Page 78: MARC Tutorials

Marc Python Tutorial

7-12

Running the ScriptTo run this script, bring up the Python browser and browse to the Mentat directory examples/python/tutorial/c07 and run the Python script chap7.py. However, do not select the RUN AS SEPARATE PROCESS button since the Python console/terminal window will exit when it is finished and the resulting print statements will not be seen.

When the script completes, the output will appear as shown in Figure 7-1 and Figure 7-2.

Found 16 setsSet TOP is a node set with 2 entries entry 1 is 3 entry 2 is 4Set BOTTOM is a node set with 2 entries entry 1 is 1 entry 2 is 2Set LITTLE_EL is a element set with 1 entries entry 1 is 2Set RIGHT_ELEMENT is a element set with 1 entries entry 1 is 3Set RULED_SURF is a surface set with 1 entries entry 1 is 1Set BEZIER_CURVE is a curve set with 2 entries entry 1 is 1 entry 2 is 2Set EDGES is a edge set with 4 entries entry 1 is 1 edge number 2 entry 2 is 2 edge number 1 entry 3 is 3 edge number 1 entry 4 is 3 edge number 2

Page 79: MARC Tutorials

CHAPTER 7PyMentat: Obtaining Model Data

7-13

Figure 7-1 Set output from chap7.py

The database output is shown in Figure 7-2.

Set FACES is a face set with 2 entries entry 1 is 4 face number 0 entry 2 is 2 face number 0Set icond_velo_nodes is a node set with 1 entries entry 1 is 5Set icond_mass_nodes is a node set with 4 entries entry 1 is 17 entry 2 is 18 entry 3 is 19 entry 4 is 20Set icond_usersub_nodes is a node set with 1 entries entry 1 is 15Set apply_usersub_nodes is a node set with 1 entries entry 1 is 16

Page 80: MARC Tutorials

Marc Python Tutorial

7-14

Contact Bodys 4 Contact Body 1 , Id 1 Name surface Contact Body 2 , Id 2 Name the_mesh Contact Body 3 , Id 3 Name refined_mesh Contact Body 4 , Id 5 Name empty_cbodyMaterials 2 Material steel Type mechanical/isotropic Young's Mod 3e+007 Plasticity method default Yield Surface general_plasticity Material stainless Type mechanical/isotropic Young's Mod 2.9e+007 Plasticity method chaboche Yield Surface von_mises

Boundary Conditions 3 Boundary Cond apply1 Type point_load Values by: entered Boundary Cond apply2 Type point_load Values by: entered Boundary Cond apply_usersub Type fixed_displacement Values by: usersubGeometric Properties 2 Geometric Prop th_shell Type mech_three_shell Thick 0.7 Geometric Prop membrane Type mech_three_membrane Thick 0.2Initial Conditions 3 Initial Cond icond_velo Type velocity Values by: entered Initial Cond icond_mass Type point_mass Values by: entered Initial Cond icond_usersub Type displacement Values by: usersub

Current material : steel Type : mechanical/isotropic Youngs Modulus : 30000000.0 Poissons Ratio : 0.3 Yield Stress : 32000000.0

Contact Table : ctable1 Contact Dist Tol : 0.01

Page 81: MARC Tutorials

CHAPTER 7PyMentat: Obtaining Model Data

7-15

Figure 7-2 Database output from chap7.py

Current geometry : th_shell Thickness : 0.7

Contact Table Contact Dist Tol : 0.01

Elements 4 Maximum id 4

Element 1 Class 4 Family 3 , Type 18

Contact Body : the_mesh Geometry Property : th_shell Orientation : Material Property : steel

Element 2 Class 4 Family 3 , Type 18 Contact Body : refined_mesh Geometry Property : th_shell Orientation : Material Property : steel

Element 3 Class 4 Family 3 , Type 3 Contact Body : the_mesh Geometry Property : membrane Orientation : Material Property : stainless

Element 4 Class 4 Family 3 , Type 3 Contact Body : refined_mesh Geometry Property : membrane Orientation : Material Property : stainless

Loadcase : forge_align , Type static ArcLength Method : advanced_crisf

Job : forging_analysis , Type mechanical Follower Force : begin_inc

Page 82: MARC Tutorials

Marc Python Tutorial

7-16

Set Id’s and Set NamesIn most cases, it is desirable to reference sets using their names. However, all of the database functions for sets use the "set id". The following piece of Python code will take a set name and search for the set id.

Figure 7-3 Python Code to Find the Set ID of a Given Set Name

def find_set_id(name):n = py_get_int("nsets()")for i in range(1,n+1):

id = py_get_int("set_id(%d)" % i)sname = py_get_string("set_name(%d)" %

id)if( sname == name):

return idreturn -1

Page 83: MARC Tutorials

Chapter 8: PyPost: Reading a Post File

CHAPTER

8 PyPost: Reading a Post File

■ Chapter Overview

■ PyPost Basics

■ Running the Script

Page 84: MARC Tutorials

Marc Python Tutorial8-2

Chapter OverviewIn this chapter, it will be demonstrated the basics of using PyPost to read a Marc post file. This example will use the post file of the example created in the previous chapter.

Upon completion of this chapter, you should have a clearer understanding of the following areas:

• The basics of using PyPost

• How to use PyPost to read nodal data

Page 85: MARC Tutorials

8-3CHAPTER 8PyPost: Reading a Post File

PyPost BasicsIn the previous chapter it was shown how to use PyMentat to post process a post file. The PyMentat module depends on interacting with Marc Mentat. Sometimes it is more convenient to work in a non-GUI environment, such as an X-Term window or a Microsoft Windows command prompt window. The PyPost module works in this manner.

PyPost is an API used in a Python script to obtain the results from a Marc post file. The PyPost module contains one routine that is used to open a post file, post_open. This routine returns a PyPost object. This PyPost object contains the methods that are used to access various data items in the post file.

When using the PyPost module, you will import the module in the same way as importing the PyMentat module, using the statement:

from py_post import *

To begin accessing a post file, you must call the PyPost routine post_open, such as:pObj = post_open("chap5_job1.t16")

This statement opens the post file named chap5_job1.t16 and returns a PyPost object, storing it in the variable pObj.

This example is named chap8.py and can be found in the Marc Mentat directory examples/python/tutorial/c08. The following Python code obtains the nodal scalar values from the post file used in the previous chapter:

1 from py_post import *

2 def main(fname):

3 p = post_open(fname)

4 try:

5 p.moveto(1)

6 except:

7 print ‘Error opening post file: ‘,fname

8 return

9

10 max_scalars = []

11 max_nodes = []

12

13 nns = p.node_scalars()

Page 86: MARC Tutorials

Marc Python Tutorial8-4

14 print "Found ", nns, " node scalars "

15 for i in range(0,nns):

16 max_scalars.append(-1.0e20)

17 max_nodes.append(0)

18

19 # find maximum nodal scalars

20 for j in range(0, nns):

21 k= 0

22 numnodes = p.nodes()

23 while k < numnodes:

24 d = p.node_scalar(k,j)

25 if d < 0.0:

26 d = -d

27 if d > max_scalars[j] :

28 max_scalars[j] = d

29 max_nodes[j] = p.node_id(k)

30 k = k + 1

31

32 print " Label node scalar"

33 print " ---------------------------------------"

34

35 for i in range(0,nns):

36 str = " %18s %10i %g" %(p.node_scalar_label(i),max_nodes[i],max_scalars[i])

37 print str

38 return

39

40 if __name__ == '__main__':

41 main("../c06/chap5_job1.t16")

Line 3 The post_open routine is called with the post file name chap5_job1.t16. It returns the PyPost object that is stored in the variable p. All subsequent PyPost methods called will be members of this PyPost object.

Page 87: MARC Tutorials

8-5CHAPTER 8PyPost: Reading a Post File

Lines 4-5 The max_scalars and max_nodes variables are declared as Python Lists. The index of the list will be each of the scalars in the post file. The maximum scalar value will be stored in the max_scalars list. The node associated with the max_scalar value will be stored in the max_nodes list.

Line 7 Go to the first increment.

Lines 4-8 We call the moveto method to go to the first increment using the try/except statements to check for an error. When the post file is opened it is at increment 0. Increment 0 contains only the model data. We need to explicitly go to the first increment even though there is only one increment of data in the post file.

Lines 10-11 The max_scalars and max_nodes variables are declared as Python Lists. The index of the list will be each of the scalars in the post file.

Line 13 This statement will call the node_scalars method to obtain the total number of nodal scalars stored in the post file.

Lines 15-17 The lists are initialized.

Line 20 This begins the main loop for the scalars.

Line 22 Obtain the number of nodes. If this post file had multiple increments, we would have to call the nodes method every increment, since rezoning will change the number of nodes.

Line 23 Loop through all the nodes. Note that we use a while loop for this. We had been using the range function, however, Python builds a list of all the values in the range for this function. If we had 100,000 nodes, Python would build a list that large.

Line 24 Get the scalar value for this scalar (k) and node (j).

Lines 25-26 Ignore the sign of the values and only work with magnitudes.

Lines 27-29 Check the current value against the current maximum value. Convert the node sequence number to the node id using the node_id method.

Lines 35-37 Print out the results for each scalar.

Page 88: MARC Tutorials

Marc Python Tutorial8-6

Running the ScriptThis script is intended to be run outside of Marc Mentat. In an X-terminal window or a Microsoft Windows command prompt window, change your directory to the Marc Mentat directory examples/python/tutorial/c08. Run the Python script chap8.py as:

python chap8.py

When the script completes, the output will printed as shown in Figure 8-1.

Figure 8-1 Resulting Output from chap8.py

In the next chapter, we will begin working with element data.

Found 6 node scalars Label node scalar ------------------------------------------- Displacement x 53 0.00128282 Displacement y 49 0.00565143 External Force x 1 0 External Force y 50 187.5 Reaction Force x 82 2866.6 Reaction Force y 81 921.814

Page 89: MARC Tutorials

Chapter 9: PyPost: Obtaining Element Data

CHAPTER

9 PyPost: Obtaining Element Data

■ Chapter Overview

■ Processing Element Data

■ Running the Script

Page 90: MARC Tutorials

Marc Python Tutorial9-2

Chapter OverviewIn this chapter, it will be demonstrated how to obtain element data from a post file. This example will use the post file of that created in Chapter 6.

Upon completion of this chapter you should have a clearer understanding of the following areas:

• Obtaining the element data from a post file

• The element extrapolation methods available

Page 91: MARC Tutorials

9-3CHAPTER 9PyPost: Obtaining Element Data

Processing Element DataIn the previous chapter, you saw how to use the Pypost module to process nodal data. In this chapter, we will process element data.

Processing the element data is more complex since elements contain multiple nodes and integration points. The values obtained at the nodes are obtained by extrapolating the values at the integration points. There are 3 extrapolation methods available through the extrapolation method:

linear Extrapolate by averaging the integration points to the centroid of the element and then doing a linear extrapolation from the centroid through the integration point to the node.

translate Do not extrapolate, but rather copy the data at each integration point to its corresponding node. In those cases where there are fewer integration points than nodes, some averaging of neighboring integration points may be done.

average The average of all the integration points is computed and assigned to the nodes. Therefore, all nodes have an equal value assigned to them.

Consider the quadrilateral element shown Figure 9-1.

Figure 9-1 Element Class 8: Eight Noded Isoparametric Quadrilateral Elements

34

1 2

7

8 6

5

34

1 2

7

8 6

5

4

2

3

1

Eight node quadrilateral Four Gaussian integration points

Node

Integration pt

Page 92: MARC Tutorials

Marc Python Tutorial9-4

The quadrilateral element of Figure 9-1 contains 8 nodes and 4 integration points. For this element the PyPost method of element_scalar will return a list of eight nodes and eight scalar values. If the extrapolation method is average, all eight nodes will have the same value. If the extrapolation method is translate, then node 5 would be calculated by averaging integration points 1 and 2. If the integration method is linear, then all four integration points are averaged together and computed for the centroid of the element. The values for the nodes are linearly extrapolated from the centroid to their position on the element.

This example is named chap8.py and can be found in the Marc Mentat directory examples/python/tutorial/c08. The following is the Python code:

1 from py_post import *

2 def main(fname):

3 p = post_open(fname)

4 try:

5 p.moveto(1)

6 except:

7 print ‘Error opening post file: ‘,fname

8 return

9

10 max_scalars = []

11 max_nodes = []

12 max_incs = []

13 nns = p.node_scalars()

14 nes = p.element_scalars()

15

16 ninc = p.increments()

17 print " Increments = ",ninc,", Nodal scalars =",nns, ", Element scalars ",nes

18

19 for i in range(0,nns+nes):

20 max_scalars.append(-1.0)

21 max_nodes.append(0)

22 max_incs.append(0)

23

24 for i in range(1, ninc):

Page 93: MARC Tutorials

9-5CHAPTER 9PyPost: Obtaining Element Data

25 p.moveto(i)

26 print "scanning increment ",i," post filenumber ",p.increment

27

28 # find maximum nodal scalars

29 j = 0

30 while j < nns:

31 k = 0

32 numnodes = p.nodes()

33 while k < numnodes:

34 d = p.node_scalar(k,j)

35 if d < 0.0:

36 d = -d

37 if d > max_scalars[j] :

38 max_scalars[j] = d

39 max_nodes[j] = p.node_id(k)

40 max_incs[j] = p.increment

41 k = k + 1

42 j = j + 1

43

44 # find maximum element scalars

45 j = 0

46 while j < nes:

47 k = 0

48 numelems = p.elements()

49 while k < numelems:

50 sca = p.element_scalar(k,j)

51 l = len(sca)

52 m = 0

53 while m < l :

54 val = sca[m]

55 if val < 0.0:

56 val = -val

57 if val > max_scalars[nns+j] :

58 max_scalars[nns+j] = val

Page 94: MARC Tutorials

Marc Python Tutorial9-6

59 max_nodes[nns+j] = nod[m]

60 max_incs[nns+j] = p.increment

61 m = m + 1

62 k = k + 1

63 j = j + 1

64

65 print " Item Label increment node scalar"

66 print " ------------------------------------------"

67

68 for i in range(0,nns+nes):

69 if i < nns:

70 s = p.node_scalar_label(i)

71 else:

72 s = p.element_scalar_label(i-nns)

73 str = "%7i %36s %7i %10i %g" % ((i+1),s,max_incs[i], max_nodes[i],max_scalars[i])

74 print str

75

76 return

77

78 if __name__ == '__main__':

79 main("../c06/chap5_job1.t16")

Line 3 The post_open routine is called with the post file name chap5_job1.t16. It returns the PyPost object that is stored in the variable p. All subsequent PyPost calls will be members of this PyPost object.

Lines 4-8 We call the moveto method to go to the first increment using thetry/except statements to check for an error. When the post file is opened it is at increment 0. Increment 0 contains only the model data. We need to explicitly go to the first increment even though there is only one increment of data in the post file.

Lines 10-12 The max_scalars, max_nodes, and max_incs variables are declared as Python Lists. The index of the list will be each of the scalars in the post file. The maximum scalar value will be stored in the max_scalars list. The node associated with the max_scalar value will be stored in the

Page 95: MARC Tutorials

9-7CHAPTER 9PyPost: Obtaining Element Data

max_nodes list and the associated increment will be stored in the max_incs list.

Lines 13-14 The node_scalars method is called to obtain the total number of nodal scalars and the element_scalars method is called to obtain the total number of element scales stored in the post file.

Lines 19-22 The lists are initialized. Note that the lists contain both the nodal and element scalar data.

Line 24 The outer loop is the one for the increments.

Lines 25-26 We call the moveto method with the current index number to step through the increments. Remember that the index number passed in the moveto method is not the same number as that which appears in the post file. In line 21, we print out the current index number, and the increment number as it appears in the post file.

Lines 29-42 This is the nodal scalars section, which is the same as that of the previous chapter.

Lines 45 Begin the loop for the element scalars.

Lines 48-49 Obtain the number of elements in the current increment. Rezoning may cause the number of elements to change between increments. Loop through all the elements.

Line 50 Obtain the element scalars. The element_scalar method will return a list of PyScalar values. A PyScalar has two members: an id and a value. The id represents the node id, and value represents the scalar value.

Line 53 Loop over every node in the list.

Line 54 The PyScalar list returned is "read-only". This means that the values in the list cannot be changed.

Lines 55-60 Check each value in the PyScalar list and compare them to the maximum values.

Lines 65-74 Print out the results for each scalar.

Page 96: MARC Tutorials

Marc Python Tutorial9-8

Running the ScriptThis script is run similar to that of the previous chapter. In an X-terminal window or Microsoft Windows command prompt window, change your directory to the Marc Mentat directory examples/python/tutorial/c09. Run the Python script chap9.py as:

python chap9.py

When the script completes, the output will be appear as shown in Figure 9-2.

Figure 9-2 Resulting Output from chap8.py

In the next chapter, we will write a simple script to find the stresses greater than a given value.

Increments = 26 , Nodal scalars = 9 , Element scalars 6

Item Label increment node scalar--------------------------------------------------------------------------- 1 Displacement x 240 1 0.829858 2 Displacement y 190 23 0.0844004 3 Displacement z 240 75 1.83052 4 External Force x 240 60 216.668 5 External Force y 240 66 357.812 6 External Force z 0 1 0 7 Reaction Force x 240 18 4017.09 8 Reaction Force y 220 98 111.656 9 Reaction Force z 240 18 1.24391 10 Equivalent Von Mises Stress Layer 1 240 52 106931 11 Equivalent Von Mises Stress Layer 3 240 83 77594.8 12 Equivalent Von Mises Stress Layer 5 240 25 103107 13 Equivalent Plastic Strain Layer 1 240 53 0.181767 14 Equivalent Plastic Strain Layer 3 240 84 0.0871299 15 Equivalent Plastic Strain Layer 5 240 25 0.211298

Page 97: MARC Tutorials

Chapter 10: PyPost: Element Tensor Data

CHAPTER

10 PyPost: Element Tensor Data

■ Chapter Overview

■ Processing Element Tensor Data

■ Running the Script

Page 98: MARC Tutorials

Marc Python Tutorial10-2

Chapter OverviewIn this chapter, it will be demonstrated how to use the PyPost module to examine the element tensors. This example will use the post file of that created in Chapter 6.

Upon completion of this chapter, you should have a clearer understanding of the following areas:

• Obtaining the element tensors

• Working with elements tensor data in a Python script

Page 99: MARC Tutorials

10-3CHAPTER 10PyPost: Element Tensor Data

Processing Element Tensor DataIn the previous chapter, you saw how to use the PyPost module to process nodal and element scalar data. In this chapter, we will process the element tensor data and use the PyTensor data type.

This example is named chap10.py and can be found in the Marc Mentat directory examples/python/tutorial/c10. The Python code is as follows:

1 from py_post import *

2 import sys

3 class TensorData:

4 def __init__(self, v, n, i):

5 self.Value = v

6 self.Node = n

7 self.Inc = i

8

9 def set_data(self, v,n,i):

10 self.Value = v

11 self.Node = n

12 self.Inc = i

13

14 def increment(self):

15 return self.Inc

16

17 def value(self):

18 return self.Value

19

20 def node(self):

21 return self.Node

22

23 def get_tensors(fname):

24 p = post_open(fname)

25 try:

26 p.moveto(1)

27 except:

28 print ‘Error opening post file: ‘,fname

Page 100: MARC Tutorials

Marc Python Tutorial10-4

29 return

30

31 max_values = []

32

33 net = p.element_tensors()

34 ninc = p.increments()

35 print "Found ", net, " element tensors "

36 print ninc, " increments "

37

38 if net == 0 :

39 print "Did not find element tensors"

40 return

41

42 for i in range(0,net):

43 max_values.append(TensorData(0.0, 0, 0))

44

45 i = 1

46 while i < ninc:

47 print "Scanning increment ",i

48 p.moveto(i)

49

50 j = 0

51 while j < net:

52 k = 0

53 num = p.elements()

54 while k < num:

55 el = p.element_tensor(k,j)

56 l = len(el)

57 m = 0

58 while m < l :

59 d = el[m].intensity

60 if d > max_values[j].value() :

61 max_values[j].set_data(d, el[m].id, i)

62 m = m + 1

Page 101: MARC Tutorials

10-5CHAPTER 10PyPost: Element Tensor Data

63 k = k + 1

64 j = j + 1

65

66 i = i + 1 # next increment

67

68 print " Item Label increment node tensor"

69 print " ------------------------------------------"

70

71 for i in range(0,net):

72 j = max_value[i].node()

73 s = p.element_tensor_label(i)

74 str = "%7i %16s %7i %10i %g" % ((i+1),s,max_values[i].increment(), j,max_values[i].value())

75 print str

76 return 1

77

78 def main(fname):

79 get_tensors(fname)

80 return

81

82 if __name__ == '__main__':

83 main(sys.argv[1])

Line 2 The system module sys is imported to provide access to the command line arguments.

Lines 3-21 A Python class is created to hold and retrieve the data.

Line 24 The post_open routine is called with the post file name passed in as the first command line argument.

Lines 25-29 We call the moveto method to go to the first increment using the try/except statements to check for an error. When the post file is opened it is at increment 0. Increment 0 contains only the model data. We need to explicitly go to the first increment even though there is only one increment of data in the post file. This must be performed before we

Page 102: MARC Tutorials

Marc Python Tutorial10-6

attempt to get any data from the post file, such as the number of element scalars available.

Lines 33-34 The number of element tensors and the number of increments in the post file are obtained.

Line 46 Begin the increment loop.

Line 53 Obtain the number of elements in this increment. Rezoning may cause the number of elements to change between increments.

Lines 55-58 Obtain the list of PyTensors, and find the length of the list.

Lines 58-61 For each item in the list, compare it to the maximum value. The set_data method of the TensorData class is used to set the values.

Lines 71-75 Print the results. In line 69, the node method of the TensorData class is called to obtain the node id.

Line 83 The filename is specified as the first argument to the script.

Page 103: MARC Tutorials

10-7CHAPTER 10PyPost: Element Tensor Data

Running the ScriptThis script is run similar to that of the previous chapter. In an X-terminal window or Microsoft Windows command prompt window, change your directory to the Marc Mentat directory examples/python/tutorial/c10. Run the Python script chap10.py as:

python chap10.py chap10.t16

When the script completes, the output will appear shown in Figure 10-1.

Figure 10-1 Resulting Output from chap10.py

Found 2 element tensors12 incrementsScanning increment 1Scanning increment 2Scanning increment 3Scanning increment 4Scanning increment 5Scanning increment 6Scanning increment 7Scanning increment 8Scanning increment 9Scanning increment 10Scanning increment 11 Item Label increment node tensor ---------------------------------------------------------- 1 Stress 4 15 58564.1 2 Plastic Strain 6 9 0.103661

Page 104: MARC Tutorials

Marc Python Tutorial10-8

Page 105: MARC Tutorials

Chapter 11: PyMentat: Using the py_connect Method

CHAPTER

11 PyMentat: Using the py_connect Method

■ Chapter Overview

■ Creating a Simple Python Script for Marc Mentat

■ The py_connect Method

■ Handling Socket Errors

■ Running the Script

Page 106: MARC Tutorials

Marc Python Tutorial11-2

Chapter OverviewIn this chapter, it will be demonstrated how to use Marc Mentat PARAMETERS in a Python script using the PyMentat module. It will also be shown how to run a Python script as a separate process. Upon completion of this chapter, you should have a clearer understanding of the following areas:

• The py_connect method

• Handling socket errors

Page 107: MARC Tutorials

11-3CHAPTER 11PyMentat: Using the py_connect Method

Creating a Simple Python Script for Marc MentatWe will use the Python script shown in Chapter 3 which will create a simple element grid and use Marc Mentat PARAMETERS to control the size of the grid. This example is named chap3.py and can be found in the Marc Mentat directory examples/python/tutorial/c03. The code is shown completely in Chapter 3, however, what we are interested in now is at lines 41-44 as follows:

41 if __name__ == ’__main__’:

42 py_connect("",40007)

43 main()

44 py_disconnect()

If the script is invoked as a separate process, (such as “python chap3.py”), then the Python interpreter sets the Python variable __name__ to the string ’__main__’. If this is the case, then the Python script should attempt to make a socket connection to Marc Mentat. The first argument to py_connect is the hostname, and if it is NULL it will use the local host. The second argument is the port number.

The py_connect MethodThe py_connect method provides a method in which a Python script performs a BSD socket connection to Marc Mentat to send commands and obtain parameters. It allows Marc Mentat to be fully interactive while the Python script is executing.

When the RUN command in the Python menu is selected, it will bring up the Python browser window. An option in the Python browser window is RUN AS SEPARATE PROCESS. If this is enabled, then Marc Mentat will initiate a socket connection using the command for the INITIATE CONNECTION menu item, and then the Python script is run using the python interpreter (python.exe on Microsoft Windows) program located in Marc Mentat’s bin directory. The Python script will need to complete the connection using a call to the PyMentat method py_connect, specifying the hostname and the port number to be used. The port number used in the Python script must be the same as specified in Marc Mentat, and may be changed by selecting the PORT button. The hostname may be blank (an empty string), in which case the connection will be attempted on the local host.

Page 108: MARC Tutorials

Marc Python Tutorial11-4

All output from the Python script will appear in Marc Mentat’s XTerm window on Unix or the Command Prompt window on Microsoft Windows. When Python scripts ends it should call the py_disconnect method to complete the termination of the socket connection.

Handling Socket ErrorsSometimes a socket may become unusable and Marc Mentat cannot make a connection to a certain port. A port number may be described as "in use", even though it appears that no Python script is running. You should check that no "zombie" Python process is running in the background (using the ’ps’ command on Unix or the Task Manager on Microsoft Windows). If a Python process is running and it has a connection to the port, it must terminate before another process can make a connection to that port.

The error "Specified address in use" may occur in the following scenario on a Unix system:

1. Marc Mentat is started and the INITIATE CONNECTION button is selected.

2. In a separate window, a Python script makes a successful socket connection to Marc Mentat.

3. Marc Mentat exits before the Python script completes or calls the py_disconnect method.

4. Marc Mentat is started again, and the INITIATE CONNECTION button is selected. The error "Specified address in use" may occur. To resolve the problem, use a different port number or wait for the socket timeout to occur (about 4-5 minutes).

If all else fails, try using a different port number. You may also want to specify the port number as an argument to the Python script. You may do this as shown in the following code example:

1 import sys

2 if __name__ == ’__main__’:

3 port = 40007

4 if len(sys.argv) > 1:

5 port = sys.argv[1]

6 py_connect("",port)

Page 109: MARC Tutorials

11-5CHAPTER 11PyMentat: Using the py_connect Method

7 main()

8 py_disconnect()

The sys module is used to obtain the "command line arguments", which contains the Python list attribute named argv. The first item in the argv list in the name of the script being run, and is therefore sys.argv[0]. If the length of this list is greater than 1, then extra arguments were passed to the Python script. In this example, you would run the script on the command line as:

python chap3.py 40008

The script would use the port number of 40008 and attempt to make the socket connection with Marc Mentat. The script could also be run using the Python browser window, shown in Figure 11-1. In this case, the RUN AS SEPARATE PROCESS button would be selected, and you would also specify the port number in the CALL ARGUMENTS text box.

Figure 11-1 The Python Browser Window

Page 110: MARC Tutorials

Marc Python Tutorial11-6

Running the ScriptFirst, start Marc Mentat. Before running this example, some PARAMETERS need to be defined. The values for these parameters will be obtained by the Python script to control the size and the position of the grid.

Select the following menus:

MAINUTILS

PARAMETERSNEW PARAMETER

x_size10

y_size8

x_start-1.0

y_start-1.0

Remember to press the carriage <CR> after typing in each of the numbers to create the parameters. The procedure file chap3.proc may be executed to perform the above commands for you if you wish.

You may also type the *define command in Marc Mentat’s command prompt window to create or edit the parameter. For example, to create the parameter x_size you would type

*define x_size 10

As in the previous chapter, bring up the Python browser window with the menus:

MAINUTILS

PYTHONRUN

When the script completes, a mesh will be created the same as in Chapter 3.

Page 111: MARC Tutorials

Chapter 12: PyPost: Plotting

CHAPTER

12 PyPost: Plotting

■ Chapter Overview

■ Charting Script for Marc Mentat

■ The Gnuplot Module

■ The PyOpenGL Module

Page 112: MARC Tutorials

Marc Python Tutorial12-2

Chapter OverviewIn this chapter, it will be demonstrated how to use third party Python modules in a Python script to plot the results from a post file. Three examples of plotting will be shown:

• Using the gdchart module to create a GIF plot

• Using the gnuplot module to create charts with Gnuplot.

• Using the OpenGL module to display 3-D models with PyOpenGL.

The examples shown here were developed only for Microsoft Windows. See the readme.txt file in the examples/python/tutorial/c12 directory for information regarding what needs to be installed to run these examples.

Page 113: MARC Tutorials

12-3CHAPTER 12PyPost: Plotting

Charting Script for Marc MentatIn this first example, we will use a simple charting module that creates a JPEG file. We will use it here to create a plot of the Y displacements for 4 nodes. Note that this module is somewhat limited since it does not support annotations and has no support for legends. However, it can be useful for creating quick and simple plots. We will use a post file which displays a simple contact example. This example is named chap12a.py and can be found in the Marc Mentat directory examples/python/tutorial/c12. The output from this example is a JPEG file name chap12a.jpg.

The following is the Python code to use the gdchart module to create a JPEG plot.

1 from py_post import *

2 import gdchart

3 opt = gdchart.option

4

5 opt(set_color=(0xff8080, 0x8080ff, 0x80ff80))

6 opt(bg_color=0xaaaaaa, plot_color=0x0000cd, line_color=0x000000)

7 size = (450, 450)

8

9 def do_plot(fname, t, Incs, dta):

10 opt(set_color=(0xff8080, 0x8080ff, 0x80ff80))

11 opt(bg_color=0xaaaaaa, plot_color=0x0000cd,

12 line_color=0x000000,format=gdchart.GDC_JPEG)

13 opt(title=t, xtitle='Increment', ytitle='Y-Displ',grid=1)

14 f=open(fname,’wb’)

15 gdchart.chart(gdchart.GDC_LINE, size, f,

16 Incs, dta[0], dta[1], dta[2], dta[3])

17 f.close()

18

19 def main(fname):

20 p = post_open(fname)

21 p.moveto(1)

22 nns = p.node_scalars()

23 ninc = p.increments()

24 print " Increments = ",ninc

Page 114: MARC Tutorials

Marc Python Tutorial12-4

25

26 # The list of nodes to plot

27 check_nodes = (42, 66, 78, 86)

28

29 # Create an array for the displacements of

30 # the nodes in the list

31 displacements = [None]*len(check_nodes)

32 for i in range(0,len(check_nodes)):

33 displacements[i] = [0.0] * ninc

34

35 Incs = [' '] * ninc

36

37 nlocy = 0

38 for i in range(0,nns):

39 s = p.node_scalar_label(i)

40 if s == "Displacement Y" :

41 nlocy = i

42

43 for i in range(1, ninc):

44 p.moveto(i)

45 print "scanning post file increment",p.increment

46 Incs[i] = `p.increment`

47

48 # get the Y displacements for specified nodes

49 for k in range(0,len(check_nodes)):

50 j = p.node_sequence(check_nodes[k])

51 displacements[k][i] = p.node_scalar(j,nlocy)

52

53 title = "Nodes "

54 for k in range(0,len(check_nodes)-1):

55 title = title + `check_nodes[k]` + ","

56 title = title + `check_nodes[len(check_nodes)-1]`

57

Page 115: MARC Tutorials

12-5CHAPTER 12PyPost: Plotting

58 do_plot("chapt12a.gif", title, Incs ,displacements)

59

60 if __name__ == '__main__':

61 main("../c09/chap9.t16")

Line 2 The chart module gdchart is imported.

Lines 9-17 The do_plot routine is a convenient wrapper function to the plotting routine chart in the gdchart module. We pass in the filename for the plot, the title, and the X and Y values to plot.

Line 27 Create the list of nodes id’s to plot.

Lines 31-33 Create a two-dimensional array for the displacements. The list is the size [number of nodes to plot] x [number of increments].

Line 35 Create a string array for the increments.

Line 38-41 Find the index to the displacements for the node scalars.

Line 43 Loop through all the increments.

Lines 49-51 Loop over the list of nodes to plot. Use the node_sequence routine to get the sequence number for the id’s in the check_nodes list.

Lines 53-56 Create the title for the plot. It will contain the list of the nodes used in the plot.

In this example, you would run the script on the command line as:python chap12a.py

The output from the script is shown in Figure 12-1.

Page 116: MARC Tutorials

Marc Python Tutorial12-6

Figure 12-1 The Resulting JPEG File from chap12a.py

Page 117: MARC Tutorials

12-7CHAPTER 12PyPost: Plotting

The Gnuplot ModuleThe gnuplot module interfaces with the Gnuplot program to create PostScript plots. It does not create plots on its own. Instead, it communicates with the Gnuplot program in much the same way as the PyMentat module communicates with Marc Mentat. The gnuplot module will send commands to the Gnuplot program, and plots will appear in the Gnuplot window. This module is more robust than the gdchart module because it supports annotations and provides much more control over the plot.

1 from py_post import *

2 import os

3

4 try:

5 # Check if the package has been installed correctly

6 import Gnuplot

7 except:

8 print "Gnuplot has not been installed"

9

10 def gnu_plot(fname, title, Incs, dta, check_nodes):

11 import time

12 g = Gnuplot.Gnuplot(debug=1)

13

14 g.title(title)

15 g('set data style linespoints')

16 g('set size .6,.6')

17 d = [None] * len(check_nodes)

18 for i in range(0,len(check_nodes)):

19 d[i] = Gnuplot.Data(Incs, dta[i], title="Node "+ `check_nodes[i]`, with='lines ' + `i+3`+ ' ' + `i+3`)

20 g.xlabel('Increments')

21 g.ylabel('Y-Displ')

22 g.plot(d[0], d[1], d[2], d[3])

23 if os.name == "nt" :

24 raw_input('Please press return tocontinue...\n')

25 else :

Page 118: MARC Tutorials

Marc Python Tutorial12-8

26 time.sleep(5)

27

28 g.hardcopy(fname, color=1) # enhanced = 1

29 print '**** Saved plot to postscript file "%s"****\n' % fname

30 time.sleep(1)

31 return

32

33 def main(fname):

34 p = post_open(fname)

35

36 p.moveto(1)

37 nns = p.node_scalars()

38 ninc = p.increments()

39 print " Increments = ",ninc

40

41 check_nodes = (42,66,78, 86)

42 displacements = [None]*len(check_nodes)

43 for i in range(0,len(check_nodes)):

44 displacements[i] = [0.0] * ninc

45

46 Incs = [0] * ninc

47 nlocy = 0

48

49 # find the index for the displacements

50 for i in range(0,nns):

51 s = p.node_scalar_label(i)

52 if s == "Displacement Y" :

53 nlocy = i

54

55 for i in range(1, ninc):

56 p.moveto(i)

57 print "scanning post file increment",p.increment

58 Incs[i] = p.increment

Page 119: MARC Tutorials

12-9CHAPTER 12PyPost: Plotting

59

60 # find all y displacements for specified nodes

61 for k in range(len(check_nodes)):

62 j = p.node_sequence(check_nodes[k])

63 dy = p.node_scalar(j,nlocy) # k

64 displacements[k][i] = dy

65

66 gnu_plot("chap12b.ps", "Node Displacements", Incs,displacements, check_nodes)

67

68 if __name__ == '__main__':

69 main("chap12.t16")

Lines 4-8 Use the try/except statement to trap an error if the module gnuplot is not available.

Line 10 The gnu_plot routine is a convenient wrapper function to the plotting routine Gnuplot in the gnuplot module.

Line 12 Create the Gnuplot object.

Lines 14-15 Set the title, the linestyle, and the size of the plot.

Line 16 Create an array to store the Gnuplot Data objects.

Line 18-19 Loop through each node in the ccheck_nodes list and create a title containing the node number and set the line color to a different color for each line.

Lines 20-21 Set the x and y axis labels.

Line 22 Call the plot routine to generate the plot. When the plot routine is called, the data is sent to the gnuplot program and the plot is displayed.

Line 23-26 If the platform is Microsoft Windows, pause the display. Otherwise wait for 5 seconds and then exit.

Line 28 Create the postscript file.

Page 120: MARC Tutorials

Marc Python Tutorial12-10

Line 30 Sleep (or pause) the program. If this is not done, a file will not be generated.

Lines 33-66 The main routine is similar to that of the chap12a.py example.

When the script completes, a plot as shown in Figure 12-2 will be displayed in the Gnuplot program, and will be saved as a PostScript plot in the file chap12b.ps.

Figure 12-2 The Resulting PostScript File from chap12b.py

Page 121: MARC Tutorials

12-11CHAPTER 12PyPost: Plotting

The PyOpenGL ModuleThe OpenGL module is an interface to the PyOpenGL API that can be used by Python scripts to draw 3-D graphics. It is useful to create 3-D graphs, plots, or to display the model itself which will be shown in this example. The original model and the final displaced model will be displayed.

The post file model is a 2-D model from the Chapter 9 example. It requires the PyOpenGL module and the Numeric extensions from LLNL.

1 from py_post import *

2 from Numeric import *

3 from OpenGL.GL import *

4 from OpenGL.Tk import *

5 from OpenGL.GLUT import *

6

7 # list of the nodes to label

8 check_nodes = [1,4,7,45]

9

10 class Displ:

11 def __init__(self, i, xv, yv, dxv, dyv):

12 self.Id = i

13 self.X = xv

14 self.Y = yv

15 self.dX = dxv

16 self.dY = dyv

17 def x(self):

18 return self.X

19 def y(self):

20 return self.Y

21 def dx(self):

22 return self.dX

23 def dy(self):

24 return self.dY

25 def id(self):

26 return self.Id

27

Page 122: MARC Tutorials

Marc Python Tutorial12-12

28 class Win:

29 def __init__(self, left, right, bottom, top, w, h):

30 self.Left = left

31 self.Right = right

32 self.Bottom = bottom

33 self.Top = top

34 self.Width = w

35 self.Height = h

36 def left(self):

37 return self.Left

38 def right(self):

39 return self.Right

40 def bottom(self):

41 return self.Bottom

42 def top(self):

43 return self.Top

44 def width(self):

45 return self.Width

46 def height(self):

47 return self.Height

48

49 def width():

50 return 400

51

52 def height():

53 return 400

54

55 def mode_3d():

56 global win

57 glMatrixMode(GL_PROJECTION)

58 glLoadIdentity()

59 glOrtho(win.left(), win.right(), win.bottom(),win.top(), -1.0,1.0)

60 glMatrixMode(GL_MODELVIEW)

61

Page 123: MARC Tutorials

12-13CHAPTER 12PyPost: Plotting

62 BMfonts = ( "glut9by15", "glut8by13",

63 "glutTimesRoman10", "glutTimesRoman24",

64 "glutHelvetica10", "glutHelvetica12","glutHelvetica18" )

65

66 # draw a symbol for the node

67 def draw_dot(x,y):

68 dot = array([0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,0xFFFFFFFF,

69 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,0xFFFFFFFF])

70 glPixelStorei(GL_UNPACK_ALIGNMENT, 1)

71

72 wid = 3

73 hei = 3

74 glRasterPos3f(x,y,0.0)

75 t=dot.tostring()

76 glDrawPixels(wid, hei, GL_RGBA, GL_UNSIGNED_BYTE, t)

77 return

78

79 def draw_string(str,x,y):

80 glRasterPos3f(x,y,0.0)

81 for i in range(len(str)):

82 glutBitmapCharacter("glut9by15", ord(str[i]));

83 return

84

85 def draw_element(i):

86 # draw the original shape

87 glColor3f(1,0,0)

88 glBegin(GL_LINE_STRIP)

89 glVertex2f(nodex[i], nodey[i])

90 glVertex2f(nodex[i+1], nodey[i+1])

91 glVertex2f(nodex[i+2], nodey[i+2])

92 glEnd()

93 # draw the deformed shape

94 glColor3f(0,1.0,0.0)

Page 124: MARC Tutorials

Marc Python Tutorial12-14

95 glBegin(GL_LINE_STRIP)

96 glVertex2f(nodedx[i], nodedy[i])

97 glVertex2f(nodedx[i+1], nodedy[i+1])

98 glVertex2f(nodedx[i+2], nodedy[i+2])

99 glEnd()

100 return

101

102 def plot_nodes(lst):

103 global p

104 glColor3f(1,1,1)

105 for i in range(len(lst)):

106 j = p.node_sequence(lst[i])

107 k=lst[i]

108 draw_string(`k`,nod[j].x(), nod[j].y())

109 draw_dot(nod[j].x(), nod[j].y())

110 dx = nod[j].x()+nod[j].dx()

111 dy = nod[j].y()+nod[j].dy()

112 draw_string(`k`,dx, dy)

113 draw_dot(dx,dy)

114 return

115

116 def draw_legend():

117 global win

118 glColor3f(1,0,0)

119 glBegin(GL_LINE_STRIP)

120 x1 = win.left() + .1

121 x2 = x1 + (win.right()-win.left())/5.0

122 y = win.bottom() +.15

123 glVertex2f(x1, y)

124 glVertex2f(x2, y)

125 glEnd()

126 draw_string("undeformed", x2+.05, y)

127 glColor3f(0,1.0,0.0)

128 glBegin(GL_LINE_STRIP)

129 glVertex2f(x1, y-.1)

Page 125: MARC Tutorials

12-15CHAPTER 12PyPost: Plotting

130 glVertex2f(x2, y-.1)

131 glEnd()

132 draw_string("deformed",x2+.05, y-.1)

133 return

134

135 def redraw(o):

136 glClearColor(0.1, 0.1, 0.1, 0)

137 glColor3f(1,0,0)

138 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

139 mode_3d()

140

141 glDisable(GL_LIGHTING)

142 for i in range(0,len(nodex),3):

143 draw_element(i)

144 plot_nodes(check_nodes)

145 draw_legend()

146 glEnable(GL_LIGHTING)

147 return

148

149 def find_node(n,nod):

150 for i in range(0,len(nod)):

151 if nod[i].id() == n:

152 return i

153 return -1

154

155 def find_maxmin(x, y):

156 global maxx, maxy, minx, miny

157 if maxx < x : maxx = x

158 if maxy < y : maxy = y

159 if minx > x : minx = x

160 if miny > y : miny = y

161

162 def main(fname):

163 global nodex, nodey, nodedx, nodedy

164 global maxx, maxy, minx, miny

Page 126: MARC Tutorials

Marc Python Tutorial12-16

165 global nod # List of Displ objects

166 global win

167 global o, p

168

169 p = post_open(fname)

170 p.moveto(1)

171 nns = p.node_scalars()

172

173 ninc = p.increments()

174 print " Increments = ",ninc

175

176 # find the index ih the scalar label list for thedisplacements

177 for i in range(0,nns):

178 s = p.node_scalar_label(i)

179 if s == "Displacement X" :

180 nlocx = i

181 if s == "Displacement Y" :

182 nlocy = i

183

184 # go to the last increment

185 p.moveto(p.increments()-1)

186 k = 0

187

188 # get nodes

189 nod = [Displ] * p.nodes()

190 while k < n:

191 j = p.node_id(k)

192 i = k

193 np = p.node(k)

194 dx = p.node_scalar(k,nlocx)

195 dy = p.node_scalar(k,nlocy)

196 nod[k] = Displ(j,np.x, np.y,dx,dy)

197 k = k + 1

198

Page 127: MARC Tutorials

12-17CHAPTER 12PyPost: Plotting

199 k = 0

200 n = p.elements()

201

202 # Create the x and y coordinate arrays for plotting.

203 # We should check the element list to find out how many

204 # nodes are in each element.

205 # We know for this model all elements have 3 nodes.

206 nodex = [0.0]*(n*3)

207 nodey = [0.0]*(n*3)

208 nodedx = [0.0]*(n*3)

209 nodedy = [0.0]*(n*3)

210 maxx = maxy = -10000.0

211 minx = miny = 10000.0

212

213 cnt=0

214 # build the x and y coordinate arrays

215 while k < p.elements():

216 el = p.element(k)

217 for m in range(0,el.len):

218 id=find_node(el.items[m],nod)

219 if id >=0 :

220 nodex[cnt] = nod[id].x()

221 nodey[cnt] = nod[id].y()

222 nodedx[cnt] = nod[id].x() +nod[id].dx()

223 nodedy[cnt] = nod[id].y() +nod[id].dy()

224 find_maxmin(nodex[cnt], nodey[cnt])

225 find_maxmin(nodedx[cnt], nodedy[cnt])

226 cnt = cnt+1

227 k = k +1

228

229 # Generate the Win object containing the viewport info

230 minx = minx - .25*(maxx-minx)

231 maxx = maxx + .25*(maxx-minx)

Page 128: MARC Tutorials

Marc Python Tutorial12-18

232 miny = miny - .25*(maxy-miny)

233 maxy = maxy + .25*(maxy-miny)

234 win = Win(minx, maxx,miny, maxy, width(), height())

235

236 f = Frame()

237 f.pack(side='top',expand=1)

238 quit=Button(f,text = 'Quit',command =sys.exit).grid(row = 0, column = 0, sticky =W)

239

240 t = "Increments " + `p.increments()`

241 lbl = Label(f, text=" ").grid(row=0, col=2,sticky=W)

242 lbl = Label(f, text=t).grid(row=0, col=3, sticky=W)

243 o = Opengl(width = width(), height = height(),double = 1)

244 o.redraw = redraw

245 o.pack(side = 'top', expand = 1, fill = 'both')

246 o.focus_set()

247 o.mainloop()

248

249 if __name__ == '__main__':

250 main("../c09/chap9.t16")

251

Line 2 Import the Numeric (NumPy) extension.

Lines 3-5 Import the OpenGL, OpenGL toolkit (Tkinter), and the OpenGL GLUT modules.

Lines 10-26 Create a class for storing the displacement data.

Lines 28-47 Create a class for storing information about the window.

Lines 49-53 The width and height function to return the desired size. Change the values here to change the size of the window.

Lines 55-60 The mode_3d routine will set the OpenGL parameters for a 3-D window.

Page 129: MARC Tutorials

12-19CHAPTER 12PyPost: Plotting

Lines 62-64 The BMfonts list contains the available fonts for displaying in the 3-D window.

Lines 66-77 The drawdot routine will draw a 3x3 block of pixels. This is used to identify the nodes we wish to see labelled.

Lines 79-83 The draw_string routine will draw a string of characters at the specified position in the 3-D window

Lines 85-100The draw_element routine will draw both the deformed and the undeformed elements.

Lines 102-114The plot_nodes routine will draw the "dot" to represent the node location and will label the node for both the deformed and undeformed elements.

Lines 116-133The draw_legend routine will draw a legend in the lower left corner reflecting the color of the lines used for the deformed and undeformed shape.

Lines 135-147The redraw routine is called by the Tkinter toolkit (which is registered at line 247) to redraw the window. It calls the mode_3d routine to setup the 3-D window, and then draws the elements, plots the nodes, and draws the legend. If the window is resized or receives an expose event, the toolkit will call this routine.

Lines 149-153The find_node routine will find the index of a node id in the nod array.

Lines 155-160The find_maxmin routine will find the maximum and minimum x and y values in the model. This is used to determine the values to specify when creating the 3-D window.

Lines 163-167Declare some global variables.

Lines 176-182Determine the index of the X and Y displacements in the post file.

Lines 188-197Create an array of Displ objects to store the displacement data. Loop over all of the nodes and create an object.

Lines 206-209Create the arrays to store the actual x and y coordinates to plot.

Page 130: MARC Tutorials

Marc Python Tutorial12-20

Line 215 Loop through all the elements.

Lines 217-226For each node in the element, get the index of the node in the nod array and store the data in the undeformed x and y arrays (nodex and nodey), and also in the deformed x and y arrays (nodedx and nodedy). The find_maxmin routine is called to find the maximum and minimum values so that the window may be scaled appropriately.

Lines 229-234Find the minimum and maximum values for the data so that the window can be created with the proper limits.

Lines 236-237Create the window frame using the Tkinter toolkit.

Lines 238-242Create a quit button and a label that specifies the number of increments.

Lines 243-247Create the OpenGL object and specify the width, height and whether double buffering is needed. Specify the redraw routine (line 244) and get the window focus. Then start the main loop event processing (line 247).

Page 131: MARC Tutorials

12-21CHAPTER 12PyPost: Plotting

Figure 12-3 The Resulting Plot from chap12c.py

Page 132: MARC Tutorials

Marc Python Tutorial12-22

Page 133: MARC Tutorials

Chapter 13: PyMentat: Menu System Lookup Functions

CHAPTER

13 PyMentat: Menu System Lookup Functions

■ Chapter Overview

■ Menu System Lookup Functions

■ Integer Function

■ Double Function

■ String Function

■ Boolean Function

■ State Function

Page 134: MARC Tutorials

Marc Python Tutorial13-2

Chapter OverviewIn this chapter the basics of obtaining database values using the menu system lookup functions will be demonstrated.

Upon completion of this chapter, you should have a clearer understanding of the following areas:

• The fundamentals of the menu system lookup functions.

• How to use the lookup functions in a Python script to obtain database values.

Page 135: MARC Tutorials

13-3CHAPTER 13PyMentat: Menu System Lookup Functions

Menu System Lookup FunctionsThis chapter describes how to obtain database value by accessing them using the menuing system lookup functions supported by Marc Mentat. Each function has two arguments: the first argument is the name of the database (menu) item, the second argument is the index of the item (base 0). The index value is non-zero where lists of items are used, such as obtaining values of post time on a post file for each increment or a list of contact body names, otherwise the index will be zero.

The lookup functions supported are:

Integer py_ms_int

Double py_ms_double

String py_ms_string

Boolean py_ms_bool

State py_ms_state

The list of possible database item names are quite long and are not listed here - the name of the item should be obtained via the menu file. To obtain the name of a database item, run Marc Mentat, and when viewing the required item on a menu screen place the cursor over the desired menu item and press the F2 function key to view/edit the menu file. On a Unix system the cursor will go directly to the menu item, however on Microsoft Windows you will need to do a search to get to the proper location. For example, open a model file or a post file and go to the UTILS->SIZES menu. Place the cursor over the COUNT item in the ELEMENTS row and press the F2 button. On a Unix system the cursor will be brought to the proper location which displays an integer database item displaying db_count_elements. For this case the function call will use the py_ms_int function to retrieve the value:

nelems = py_ms_int(‘db_count_elements’,0)

For Microsoft Windows users that are using the default editor, you will need to do a search of “COUNT” (that is, search for part of the table’s title) to get to the proper menu text. If you have a ‘vi’ editor for Microsoft Windows, you can use that instead by modifying the bin\edit_window.bat script.

The names of some items may require spaces to be used in the text, however this is not allowed in the Python text strings. Substitute a ‘&’ or a ‘@’ symbol for any embedded spaces.

Page 136: MARC Tutorials

Marc Python Tutorial13-4

Integer FunctionThe database values for integer items may be obtained using the py_ms_int function. The first argument is the name of the database item, the second argument is the index of the item. Any item in a menu file that is represented as an integer may be obtained, such as:

integer {position +10 =size 10 4display ‘db_count_nodes’

}

The Python code for this example would be:

nnodes = py_ms_int(‘db_count_nodes’,0)

The index value is non-zero where lists of items are used, such as the values on a post file for each increment. An example would be post_size: The following obtains the post file size data for the 6th increment on the post file:

n = py_ms_int(‘post_size’,5)

Page 137: MARC Tutorials

13-5CHAPTER 13PyMentat: Menu System Lookup Functions

Double FunctionThe database values for floating point (float or double) items may be obtained using the py_ms_double function. The database may store items either as a double or a float, hence for float items the value will be cast as a double and returned. The first argument is the name of the database item, the second argument is the index of the item. Any item in a menu file that is represented as a float may be obtained, for example:

float {position +26 =size 12 4display lcase_time_step

}

The Python code for this example would be:

tstep = py_ms_double(‘lcase_time_step’,0)

An example of a menu item that uses a non-zero index would be post_time: The following obtains the post file time value for the 6th increment on the post file:

n = py_ms_double(‘post_time’,5)

Page 138: MARC Tutorials

Marc Python Tutorial13-6

String FunctionThe database values for string or text items may be obtained using the py_ms_string function. The first argument is the name of the database item, the second argument is the index of the item. Any item in a menu file that is represented as a text item (character string) may be obtained, for example:

text {position +1 +4size 30 4display post_filecommand ‘*post_open’

}

The Python code for this example would be:

tstep = py_ms_string(‘post_file’,0)

In some cases a text value of an integer or floating point value are displayed. In these cases the string will appear as

display d_gmodel_data_defmag

display i_geomdist_grid_div

The first character denotes the data type, such as i for integer or d for double (float).

The index value is non-zero where lists of items are used, such as the values on a post file for each increment. An example would be post_time: The following obtains the name of the 2nd contact body in a model file:

str = py_ms_string(‘cbody_list_name’, 1)

Page 139: MARC Tutorials

13-7CHAPTER 13PyMentat: Menu System Lookup Functions

Boolean FunctionThe database values for boolean items may be obtained using the py_ms_bool function. The first argument is the name of the database item, the second argument is the index of the item. Any item in a menu file that is represented as a toggle or a oneonly may be obtained, for example:

toggle {position +15 =size 8 4text ‘GRID’true_command ‘*set_grid on’false_command ‘*set_grid off’toggle set_grid

}

oneonly {position 1 +4size 10 4text ‘FOLLOWER FORCE’commands ‘*job_option follow:on’oneonly ‘*job_option follow:on’

}

The Python code for the examples shown above would be:

bGrid = py_ms_bool(‘set_grid’,0)

bFollow = py_ms_bool(‘*job_option&follow:on’,0)

The grid example will return 1 if the grid is on, false if it is off. The job_option example will return true if the follower force option is on, false if not. If an option has multiple states, then the State function is used. The job_option of follower force actually has 4 states, so the state function should be used to get the active state.

Page 140: MARC Tutorials

Marc Python Tutorial13-8

State FunctionThe database values for state items may be obtained using the py_ms_state function. State items are similar to boolean items, except that in most cases they have multiple conditions, but not in all cases (such as acis_file_check). The first argument is the name of the database item, the second argument is the index of the item.

There are much fewer state items than integer, double, string or booleans, and the return values may not be clear, hence they are listed in the following table. A state item is generally represented in a menu file that is defined as a roller item, however it may also appear as a oneonly. Note that in some cases the name will include the preceding asterisk, simliar to that of the actual command. A menu example for a roller button is as follows:

roller {position 1 1size 36 4nvalues 4texts ‘NO FOLLOWER FORCE’

‘FOLLOWER FORCE’‘FOLLOWER FORCE/STIFFNESS’‘FOLLOWER FORCE/(BEGIN INC)’

commands ‘*job_option follow:off’‘*job_option follow:on’‘*job_option follow:stiffness’‘*job_option follow:begin_inc’

roller ‘job_option follow’}

The Python code for this example would be:

bType = py_ms_state(‘job_option&follow’,0)

The state values will generally (but not always) begin at 0 for the first item listed and increment by one for each item in the texts list. Note that functions that end with option or param will have a space after the name and will be followed by the name of the option. The possible arguments for the option or param types are numerous - when the item you require is found in a menu file, view the file to obtain the required argument. For an example, consider job_option. The best way to verify the correct state value is to use py_send to send the command and then obtain the state value:

py_send(‘*job_option style:single’)bOpt = py_ms_state(‘job_option&style’,0)print ‘ job style single has state ’, bOpt

Page 141: MARC Tutorials

13-9CHAPTER 13PyMentat: Menu System Lookup Functions

Table B-1 State Functions

Function Description

acis_file_type *set_acis_formatted command state: returns 0 if Acis file type is formatted, 1 if binary.

acis_file_check *set_acis_entity_check command state: returns 0 if entity check is off, 1 if on.

adapg_option

adapg_param

apply_option

bsect_grid_type Returns 0 for rectangular, 1 for cylindrical

bsect_option

carea_option

cavity_option

connect_option

coord_system Coordinate system type: 0 for rectalngular, 1 for cylindrical, 2 for sphereical.

crdsyst_option

crdsyst_type Coordinate system type: 0 for rectalngular, 1 for cylindrical, 2 for sphereical.

ctable_bodies_option

ctable_entry

curve_div_applyrest_state *set_curve_div_applyrest_<cvs|lps> command state: 0 = individual cuirves (cvs), 1 = detected loops (lps).

curve_div_tol_state State of *set_curve_div_tol_(rel, abs) commands: 0=relative, 1=absolute.

geometry_option

job_option

job_post_eq_layers Post layers: 0 for default, 1 for All, 2 for out&mid, 3 for list.

match_mesh_dir *set_match_mesh_dir state: 0 = from side a to b, 1 = from side b to a.

mesh_parameter_ SuperForm mesh parameter settings.

mesh_split_method_1d Match split method 1D: 0=element base, 1 = plane

Page 142: MARC Tutorials

Marc Python Tutorial13-10

mesh_split_method_2d Match split method 2D: 0=element base, 1 = plane, 3 = smooth

mesh_split_method_3d Match split method 3D: 0=element base, 1 = plane

numerics_format Numerics format: 0 for automatic, 1 for exponential, 2 for floating, 3 for integer

save_file_type Formatted file type returns 0, binary type returns 1

select_filter 0=none, 1=outline, 2=surface, 3=top, 4=bottom

select_method 0=single, 1=path, 2=box, 3=user_box, 4=plane, 5=flood, 6=assiciate, 7=point_dist, 8=curve_dist, 9=surface_dist

select_mode 0=and, 1=except, 2=invert, 3=intersect

servo_match_rtype 0=side a, 1=side b, 2=external, 3=create new

servo_match_ttype 0=side a, 1 = side b

set_curve_type Curve type: 0=line, 1=circle_cr, 2=bezier, 3=nurb, 4=arc_craa, 5=polyline, 6=cubic_spline, 7=circle_cp, 8=arc_cpp, 9=arc_cpa, 10=arc_ppp, 11=arc_tra, 12=composite, 13=interpolate, 14=tangent, 15=fillet, 16=sampled, 17=circle_ppp

set_element_class Element class: 0=line2, 1=line3, 2=tria3, 3=tria6, 4=quad4, 5=quad6, 6=quad8, 7=quad9, 8=hex8, 9=hex12, 10=hex20, 11=hex27, 12=tetra4, 13=tetra10, 14=penta6, 15=penta16

set_solid_type Solid type: 0=block, 1=cylinder, 2=prism, 3=sphere, 4=torus

set_surface_type Surface type: 0=quad, 1=sphere, 2=bezier, 3=nurb,4=ruled,5=driven,6=cylinder,7=swept, 8=interpolate, 9=coons,10=skin,11=sampled

set_insert_embedded_type 0 for elements, 1 for nodes.

set_insert_host_type 0 for elements, 1 for contact bodies‘

set_insert_create Flag for insert generation during rebar remeshing: 0 is off, 1 is on.

set_view_repeat Flag for *set_view_repeat command: 0 is off, 1 is on.

set_xy_draw_type_histplot 0=curve, 1=bar, 2=scatter

set_xy_draw_type_pathplot 0=curve, 1=bar, 2=scatter

set_xy_draw_type_table 0=curve, 1=bar, 2=scatter

set_xy_draw_type_xcurve 0=curve, 2=scatter

set_xy_draw_type_xy_plot 0=curve, 1=bar, 2=scatter

Page 143: MARC Tutorials

13-11CHAPTER 13PyMentat: Menu System Lookup Functions

set_import_space State of DXF file import for model/paper space: 0 is model, 1 is paper, 2 is both.

srfprop_option

strline_option

table_indep_vars State of current table’s number of independent variables. Returns : 0 is 1 indep var, 1 is 2 indep var, 2 is3 indep var, 3 is4 indep var,

table_xvar State of current table x axis variables (V1-V4): Returns: 0 is V1, 1 is V2, 2 is V3, 3 is V4.

table_yvar State of current table y axis variables (V1-V4): Returns: 0 is V1, 1 is V2, 2 is V3, 3 is V4.

tform_option

weldpath_option

xcv_discontinuous State of *xcv_discontinuous command: 0 is off, 1 is on.

xcv_err_abs State of *xcv_err_abs command: 0 is off, 1 is on.

xcv_hyp_tc State of *xcv_hyp_tc command: 0 is tensile, 1 is compressive.

Page 144: MARC Tutorials

Marc Python Tutorial13-12

Page 145: MARC Tutorials

Chapter 14: MentatDCOM: Connecting to Mentat using a .NET Module

CHAPTER

14 MentatDCOM: Connecting to Mentat using a .NET Module

■ Chapter Overview

■ MentatDCOM Basics

■ Running the Program

■ MentatDCOM and PyMentat

Page 146: MARC Tutorials

Marc Python Tutorial14-2

Chapter OverviewIn this chapter it will be demonstrated the basics of using the MentatDCOM module to connect to Marc Mentat using programs created with Microsoft Visual Studio 2005 or later. An example will be shown which uses code similar to that of the example discussed in Chapter 2.

Upon completion of this chapter, you should have a clearer understanding of the following areas:

• The basics of using MentatDCOM

• How to use MentatDCOM to send data to Mentat

Page 147: MARC Tutorials

14-3CHAPTER 14MentatDCOM: Connecting to Mentat using a .NET Module

MentatDCOM BasicsIn chapter 2 it was shown how to use PyMentat to connect to Marc Mentat and build a simple model. The MentatDCOM module is a .NET assembly module built with Microsoft Visual Studio 2005 to provide an API simliar to that of PyMentat to send and receive data from Marc Mentat. As a .NET assembly module, it allows any .NET module to access the members functions, using languages such as VB.NET, C#, J#, etc. It connects using a DCOM interface which must be initiated in Marc Mentat using the *dcom_init command. The MentatDCOM module contains a class named MentatData which must be instantiated by the client. This MentatData object contains the methods that are used to send commands and retrieve various data items. The first method that must be called is used to start the connection, connect and returns either 0 for a successfull connection or non-zero if there was an error. Note that the MentatDCOM module (DLL) must be in the same directory as your executable, otherwise it will not be found.

When using the MentatDCOM module, you will import the module in a similar way as importing the PyMentat module, using the appropriate language syntax:

C++/CLIusing namespace MentatDCOM;

C#using MentatDCOM;

VB.NetImports MentatDCOM

In the main program the MentatData object is created which provides acces to the member functions:

C++/CLIMentatData p = gcnew MentatData();

C#MentatData p = new MentatData();

VB.NetDim p as New MentatData()

Page 148: MARC Tutorials

Marc Python Tutorial14-4

The program example discussed in this chapter will be a C# program performing the same functions as shown in chapter 2.

1 using System;

2 using MentatDCOM;

3 namespace MentatTest

4 {

5 class Chap14

6 {

7 static MentatData p;

8 static void make_nodes(int s, int t, double xs, double ys)

9 {

10 int i, j;

11 double x, y, z, delx, dely;

12 y = ys;

13 z = 0.0;

14 delx = 1.0/(double)s;

15 dely = 1.0/(double)t;

16 string str;

17 for(i = 0; i < t; i++)

18 {

19 x = xs;

20 for(j = 0; j < s; j++)

21 {

22 str = "*add_nodes " + x.ToString()

23 + " " + y.ToString() + " " + z.ToString();

24

25 p.send(str);

26 x = x + delx;

27 }

28 y = y + dely;

29 }

30 return;

31 }

32

Page 149: MARC Tutorials

14-5CHAPTER 14MentatDCOM: Connecting to Mentat using a .NET Module

33 static void make_elements(int n, int m)

34 {

35 int i, j, n1, n2, n3, n4;

36 string str;

37 for(i = 1; i < m; i++) // the "y" dir

38 {

39 n1 = (i-1) * (n) + 1;

40 n2 = n1 + 1;

41 n4 = n1 + (n);

42 n3 = n2 + (n);

43 for(j = 1; j < n; j++ ) // the "x" dir

44 {

45 str = "*add_elements "+n1.ToString()+" " +

46 n2.ToString() + " " + n3.ToString() + " " + n4.ToString();

47 p.send(str);

48 n1++;

49 n2++;

50 n3++;

51 n4++;

52 }

53 }

54 return;

55 }

56

57 static void Main(string[] args)

58 {

59 string host = "local";

60 if (args.Length > 0){

61 host = args[0];

62 }

63 Console.WriteLine("chap14 {0}", host);

64 p = new MentatData();

65 if (p.connect(host) > 0)

66 {

Page 150: MARC Tutorials

Marc Python Tutorial14-6

67 Console.WriteLine("Failed to connect to {0}", host);

68 return;

69 }

70 int n = 6;

71 int m = 8;

72 double xs = -1.0;

73 double ys = -1.0;

74 make_nodes(n, m, xs, ys);

75 make_elements(n, m);

76 p.disconnect();

77 return;

78 } // end Main

79 } // end class

80 }

Lines 1-2 Import the modules to be used. The System module is required for using the WriteLine method, the MentatDCOM module provides access to the MentatData class.

Lines 7 Declare the MentatData object member.he argument list passed to the main function is checked for the post file name.

Lines 8-55 This code is similar to the Python code of chapter 2.

Lines 60-62 The argument list passed to the main function is checked for the host name.

Line 64 The MentatData Object class is initialized. It creates the MentatData object and is stored in the variable p. All subsequent MentatDCOM methods called will be members of this object.

Lines 65-69 The connect method is called with the hostname of the computer.

Lines 70-75 This code is similar to the Python code of chapter 2.

Line 76 The disconnect method is called to close the connection.

Page 151: MARC Tutorials

14-7CHAPTER 14MentatDCOM: Connecting to Mentat using a .NET Module

Running the ProgramThis script is intended to be run outside of Marc Mentat. In a Microsoft Windows command prompt window, change your directory to the Marc Mentat directory examples/python/tutorial/c14. Compile and run the C# program chap14.cs as:

csc /r:MentatDCOM.dll chap14.cs /out:chap14_cs.exe

The buildit.bat script will compile the program for you. Start Marc Mentat (from either the shortcut on the desktop or another command prompt window) and enter the command:

*dcom_init

Run the DCOM program as:chap14_cs

When the script completes, a mesh will be created as shown in Figure 14-1.

Figure 14-1 Resulting Mentat from chap14.cs

Page 152: MARC Tutorials

Marc Python Tutorial14-8

MentatDCOM and PyMentatThe MentatDCOM module methods are very similar to those in PyMentat, however thre are some minor changes.

connect(String ^host)

This method is called py_connect in PyMentat. It initializes the connection to Marc Mentat. Note that the port number has been removed. It returns zero on success, non-zero on failure. The host string is currently ignored.

int ret = p.connect(‘localhost’); // C# syntax

int ret = p->connect(‘localhost’); // C++ syntax

ret = p.connect(‘localhost’); ‘ VB syntax

disconnect()

This method is called py_disconnect in PyMentat and closes the DCOM connection.

p.disconnect();

send()

This method is called py_send in PyMentat and sends a command string:p.send(‘*set_grid on’);

get_string()

This method is called py_get_string in PyMentat and returns a string:String ^nm = p.get_string(‘model_name()’);

Console::WriteLine(‘{0}’, nm);

get_double()

This method is called py_get_float in PyMentat. It returns a type of double.

string s = ‘element_mass(-1)’;

double f = p.get_double(s);

Console::WriteLine(‘Mass {0}’, f);

get_int()

This method is called py_get_int in PyMentat. It returns a type of integer.

string s = ‘nnodes()’;

Page 153: MARC Tutorials

14-9CHAPTER 14MentatDCOM: Connecting to Mentat using a .NET Module

int n = p.get_int(s);

Console::WriteLine(‘Node count {0}’, n);

update()

This method is called py_update in PyMentat. It forces a graphics update to allow the image_save routines to function properly.

p.send(‘*image_save_rgb 1 test.rgb yes’);

p.update();

Note that graphics updates will not function properly when running the OpenGL version of Mentat. The OopenGL graphics engine reports a ‘ERROR_BUSY’ error for the OpenGL calls when a separate process accesses Mentat via DCOM.

NOTE: The Mentat DCOM module (MentatDCOM.dll) must be in the same directory as your executable, otherwise it will not be found.

Page 154: MARC Tutorials

Marc Python Tutorial14-10

Page 155: MARC Tutorials

Chapter 15: MarcPost: Reading a Post File using a .NET Module

CHAPTER

15 MarcPost: Reading a Post File using a .NET Module

■ Chapter Overview

■ MarcPost Basics

■ Running the Program

■ MarcPost and PyPost

Page 156: MARC Tutorials

Marc Python Tutorial15-2

Chapter OverviewIn this chapter it will be demonstrated the basics of using the MarcPost module to read a Marc post file using programs created with Microsoft Visual Studio 2005 or later. This example will use the post file of the example used in chapter 6.

Upon completion of this chapter, you should have a clearer understanding of the following areas:

• The basics of using MarcPost

• How to use MarcPost to read nodal data

Page 157: MARC Tutorials

15-3CHAPTER 15MarcPost: Reading a Post File using a .NET Module

MarcPost BasicsIn Chapter 8 it was shown how to use PyPost to post process a Marc post file. The MarcPost module is a .NET assembly module built with Microsoft Visual Studio 2005 to provide an API simliar to that of PyPost to obtain the results from a Marc post file. As a .NET assembly module, it allows any .NET module to access the members functions, using languages such as VB.NET, C#, J#, etc. The MarcPost module contains a method that is used to open a post file, open (or post_open) and return a PostData object. This PostData object contains the methods that are used to access various data items in the post file. Note that the MarcPost module (MarcPost.dll) must be in the same directory as your executable, otherwise it will not be found.

When using the MarcPost module, you will import the module in a similar way as importing the PyPost module, using the appropriate language syntax:

C++/CLIusing namespace MarcPost;

C#using MarcPost;

VB.NetImports MarcPost

In the main program the PostData object is created which provides acces to the member functions:

C++/CLIPostData p = gcnew PostData();

C#PostData p = new PostData();

VB.NetDim p as New PostData()

The program example discussed in this chapter will be a C# program performing the same functions as shown in chapter 8.

1 using System;

2 using MarcPost;

Page 158: MARC Tutorials

Marc Python Tutorial15-4

3 namespace MarcTest

4 {

5 class Chap15

6 {

7 static void Main(string[] args)

8 {

9 if (args.Length < 1){

10 Console.WriteLine("CSPost requires filename");

11 return 1;

12}

13 Console.WriteLine("CPost {0}", args[0]);

14 PostData p = new PostData();

15 if (p.open(args[0]) > 0)

16 {

17 Console.WriteLine("Failed to open {0}", args[0]);

18 return;

19 }

20 p.moveto(1);

21 int nns = p.node_scalars();

22 Console.WriteLine("Found {0} node scalars", nns);

23 double[] max_scalars = new double[nns];

24 int[] max_nodes = new int[nns];

25 int j, k, numnodes;

26 double d;

27 for(j=0;j<nns;j++) max_scalars[j] = -1.0e20;

28 for(j=0;j<nns;j++)

29 {

30 numnodes = p.nodes();

31 for(k=0;k<numnodes;k++)

32 {

33 d = p.node_scalar(k,j);

34 if(d < 0.0) d = -d;

35 if(d > max_scalars[j])

36 {

37 max_scalars[j] = d;

Page 159: MARC Tutorials

15-5CHAPTER 15MarcPost: Reading a Post File using a .NET Module

38 max_nodes[j] = p.node_id(k);

39 }

40 }

41 }

42 Console.WriteLine(" Label node scalar");

43 Console.WriteLine(" ---------------------------------------------------");

44 for(j=0;j<nns;j++)

45 {

46 Console.WriteLine(" {0,20} {1,10:d} {2,-24:g}",p.node_scalar_label(j),

47 max_nodes[j], max_scalars[j]);

48 }

49 } // end Main

50 } // end class

51 }

Lines 1-2 Import the modules to be used. The System module is required for using the WriteLine method, the MarcPost module provides access to the PostData class.

Lines 9-12 The argument list passed to the main function is checked for the post file name.

Line 14 The PostData class is initialized. It created the PostData object and is stored in the variable p. All subsequent MarcPost methods called will be members of this object

Lines 15-19 The open method is called with the post file name chap5_job1.t16.

Line 20 Call the moveto method to go to the first increment. When the post file is opened it is at increment 0 which contains only the model data. We need to explicitly go to the first increment even though there is only one increment of data in the post file.

Lines 23-25 The max_scalars and max_nodes variables are declared as arrays. The index of the list will be each of the scalars in the post file. The maximum scalar value will be stored in the max_scalars list.

Page 160: MARC Tutorials

Marc Python Tutorial15-6

The node associated with the max_scalar value will be stored in the max_nodes list.

Line 27 The max_scalars array is initialized.

Line 28 This begins the main loop for the scalars.

Line 22 Obtain the number of nodes. If we were processing multiple increments, we would have to call the nodes method every increment, since rezoning will change the number of nodes.

Line 28 Loop through all the nodes.

Line 33 Get the scalar value for this scalar (k) and node (j).

Lines 25-26 Ignore the sign of the values and only work with magnitudes.

Lines 35-39 Check the current value against the current maximum value. Convert the node sequence number to the node id using the node_id method.

Lines 44-48 Print out the results for each scalar.

Page 161: MARC Tutorials

15-7CHAPTER 15MarcPost: Reading a Post File using a .NET Module

Running the ProgramThis script is intended to be run outside of Marc Mentat. In a Microsoft Windows command prompt window, change your directory to the Marc Mentat directory examples/python/tutorial/c15. Compile and run the C# program chap15.cs as:

csc /r:..\..\..\..\shlib\MarcPost.dll chap15.cs \/out:chap15_cs.exe

The buildit.bat script will compile the program for you. Run the program as:chap15_cs ..\c06\chap5_job1.16

When the program completes the output will printed as shown in Figure 15-1.

Figure 15-1 Resulting Output from chap15.cs

Found 6 node scalarsLabel node scalar

-------------------------------------------Displacement X 53 0.00128282303921878Displacement Y 49 0.00565143441781402

External Force X 1 0External Force Y 50 187.5Reaction Force X 82 2866.59521484375Reaction Force Y 81 921.813659667969

Page 162: MARC Tutorials

Marc Python Tutorial15-8

MarcPost and PyPostThe MarcPost module methods are very similar to those in PyPost, however there are some differences.

position()

In PyPost, position is an attribute, however in MarcPost position is a member function. This change is necessary since it could be changed by the user however the position in the file will not be updated (use the moveto method instead). Example use:

int pos = p.position();

version()

This method returns the MarcPost module version information:String ^ver = p.version();

Console::WriteLine(‘{0}’,ver);

Example output:Assembly name MarcPost, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

Page 163: MARC Tutorials

Marc Python Reference

Marc Python Reference

Page 164: MARC Tutorials

MSC.Marc Python Reference

i-ii

Page 165: MARC Tutorials

Introduction

Introduction

■ Using the Python Modules

■ Variable Types

Page 166: MARC Tutorials

Marc Python Referenceiv

Using the Python ModulesThis document describes the routines available to Python scripts that use PyMentat or PyPost interface modules.

PyMentat is the interface module for Python scripts to communicate to Marc Mentat and the PyPost Module is used by a Python script to read data from a Marc post file.

All Python scripts that need access to the PyMentat module must import the module as:

from py_mentat import *

Similarly, all Python scripts that need access to the PyPost module must import the module as:

from py_post import *

These modules are shared libraries, and hence the exact names of the PyMentat and PyPost modules are platform dependent. The PyMentat module on most Unix machines is named py_mentat.so, and it is named py_mentat.pyd on Microsoft Windows, and the PyPost module on most Unix machines is named py_post.so, and it is named py_post.pyd on Microsoft Windows.

These modules are located in the Marc Mentat bin directory, and the Python interpreter finds these modules via the environment variable PYTHONPATH. This environment variable is set in the run_python (run_python.bat on Microsoft Windows) script located in the Marc Mentat bin directory. You should use this script when running a Python script, however as long as you set PYTHONPATH to the correct location you may simply run the Python interpreter (python) directly. It is also located in the Marc Mentat bin directory.

The definition of each routine is listed in alphabetical order.

See the Marc Python Tutorial, Chapter 2 for examples on the use of these modules.

Variable TypesThe type definitions for functions and methods used in this manual are as follows:

Page 167: MARC Tutorials

vIntroductionIntroduction

String

A character string. This type is similar to the C type of char, and the FORTRAN type of character*(*)”. A string may be specified by using either single quotes or double quotes.

Float

A floating point value. This is similar to the C type of double and the FORTRAN type of real*8.

Integer

An integer (or fixed point) value. This is similar to the C type of long int and the FORTRAN type of integer*8.

List

A Python List object. A Python list is essentially a linked list that can be accessed as an array.

Page 168: MARC Tutorials

Marc Python Referencevi

Page 169: MARC Tutorials

Chapter 1: PyMentat References

CHAPTER

1 PyMentat References

■ PyMentat

■ py_connect

■ py_disconnect

■ py_echo

■ py_get_data

■ py_get_float

■ py_get_int

■ py_get_string

■ py_prompt

■ py_echo

Page 170: MARC Tutorials

Marc Python Reference1-2

PyMentatThis chapter describes the PyMentat routines.

PyMentat is the interface module for Python scripts to communicate to Marc Mentat. Marc Mentat must be running prior to invoking any PyMentat routine.

A Python script using PyMentat can be run either in “embedded” mode or run as a separate process. If invoked as a separate process, the py_port/py_connect routines must be the first PyMentat routines called.

All Python scripts that need access to the PyMentat module must import the module as:

from py_mentat import *

Page 171: MARC Tutorials

1-3CHAPTER 1PyMentat References

py_connect

Name

py_connect

Summary

Establishes a socket connection with Marc Mentat.

Synopsis

py_connect(String hostname, Integer nPort)

Arguments

hostname Hostname of system to make connection with

nPort Port number

Description

This routine will attempt to establish a socket connect with Marc Mentat on the host specified by hostname, using port number nPort. The hostname can be an IP address or a DNS name. If hostname is an empty string (“”), then the local host will be used.

A Python script executed as a separate process would use this routine to enable it to communicate with Marc Mentat. It must be the first PyMentat function called. In addition, Marc Mentat should be waiting for a connection (the Marc Mentat command *py_connect should have been issued).

Example

if __name__ == ”__main__”: py_connect(”127.0.0.1”, 40007) main()

Page 172: MARC Tutorials

Marc Python Reference1-4

py_disconnect

Name

py_disconnect

Summary

Terminates a socket connection with Marc Mentat.

Synopsis

py_disconnect()

Arguments

None

Description

This routine will terminate a socket connect with Marc Mentat after a successful connection with the py_connect routine.

Example

if __name__ == ”__main__”: py_connect(”127.0.0.1”, 40007) ... py_disconnect() main()

Page 173: MARC Tutorials

1-5CHAPTER 1PyMentat References

py_echo

Name

py_echo

Summary

Enables/disables commands to be printed in Marc Mentat’s dialogue area using py_send.

Synopsis

py_echo(int flag)

Arguments

flag An integer used to enable/disable echo.

Description

This routine affects command echoing in Marc Mentat’s dialogue area. If flag is set to true (a nonzero value), then the commands will be echoed. If flag is set to false (zero), then commands sent to Marc Mentat will not be echoed. This routine is most helpful in debugging Python scripts. The default setting is on. Note that enabling echo will slightly affect performance.

Marc Mentat command echoing for Python scripts may also be enabled in Marc Mentat using the button:

UTILS->PYTHON->SCRIPT ECHO

Example

py_echo(0) # disables echopy_echo(1) # enables echo

Page 174: MARC Tutorials

Marc Python Reference1-6

py_get_data

Name

py_get_data

Summary

Returns a floating point value from the database from the current data class.

Synopsis

Float py_get_data(String name)

Arguments

name A string representing the database value to be returned.

Description

This routine will parse the string specified in name and return a floating point result. It has the form:

Dataclass:param_name

where Dataclass is one of:

adapg, adaptg, apply, contact_body, contact_table, geometry, icond, job, loadcase, material

The Dataclass used is the currently selected item. The naming convention for param_name is consistent with that used in the menu files for displaying floating point values.

Examples

a = py_get_data(‘material:isotropic:young_modulue’)b = py_get_data(‘job:singularity_thresh’) c = py_get_data(‘geometry:cont_radius’) d = py_get_data(‘icond:base_vec1_x’) e = py_get_data(‘apply:apply_dof_value_x’) f = py_get_data(‘contact_body:friction’)f = py_get_data(‘contact_table:ctable1:ctable2:friction’)

Page 175: MARC Tutorials

1-7CHAPTER 1PyMentat References

py_get_float

Name

py_get_float

Summary

Evaluates an expression and returns a floating point value.

Synopsis

Float py_get_float(String name)

Arguments

name A string representing the expression to be evaluated.

Description

This routine will evaluate the expression specified in name and return a floating point result. Any Arithmetic or Database function combination may be used in the expression.

Note: The variables created and used in the Python script are not stored by Marc Mentat and are not available to be used directly in the expression. Marc Mentat parameters may be defined and used for this purpose.

Example

s = py_get_float(‘point_u1(npoints())’)str = ‘curve_length(0)/curve_ndiv(0)’d = py_get_float(str)f = py_get_float(‘node_x(0)*d’) # is invalidstr = ‘node_x(0)*%g’ % df = py_get_float(str) # is correct

Page 176: MARC Tutorials

Marc Python Reference1-8

py_get_int

Name

py_get_int

Summary

Evaluates an expression and returns an integer value.

Synopsis

Integer py_get_int(String name)

Arguments

name A string representing the expression to be evaluated.

Description

This routine will evaluate the expression specified in name and return an integer result. Only Database functions may be used in the expression since the Arithmetic functions are floating point routines.

Note: The variables created and used in the Python script are not stored by Marc Mentat and are not available to be used directly in the expression. Marc Mentat parameters may be defined and used for this purpose.

Example

str = ‘npoints()’i = py_get_int(‘npoints()’)j = py_get_int(‘node_id(i)’) # is invalidstr = ‘node_id(%d)’” % ij = py_get_int(str) # is correct

Page 177: MARC Tutorials

1-9CHAPTER 1PyMentat References

py_get_string

Name

py_get_string

Summary

Evaluates a function or parameter and returns a string.

Synopsis

String py_get_string(String name)

Arguments

name A string representing the function or parameter to be returned.

Description

This routine will evaluate the function or parameter specified in name and return a string result. Any database function that returns a string may be used in the expression, such as set_name() or job_title(). If name is a string that begins with ‘$’, then it will interpreted as being the name of a PARAMETER that is currently defined and its expression will be returned.

Note: The variables created and used in the Python script are not stored by Marc Mentat and are not available to be used directly in the name argument. Marc Mentat PARAMETERS may be defined and used for this purpose.

Example

id = py_get_int(‘set_id(1)‘)nam = py_get_string(‘set_name(%d)’ % id)typ = py_get_string(‘set_type(%d)’ % id)print ‘Set ‘,nam, ‘ is type ‘,typpy_send(‘*define filename myfile.mfd’)s = py_get_string(‘$filename’)print ‘Filename: ‘,s

Page 178: MARC Tutorials

Marc Python Reference1-10

py_prompt

Name

py_prompt

Summary

Prints a string in the Marc Mentat dialogue area.

Synopsis

py_prompt(String name)

Arguments

name The string to print in the dialogue area.

Description

This routine will print the string name in the Marc Mentat dialogue area.

Example

py_prompt(”Evaluating Mesh”)

Page 179: MARC Tutorials

1-11CHAPTER 1PyMentat References

py_echo

Name

py_echo

Summary

Enables/disables commands to be printed in Marc Mentat’s dialogue area using py_send.

Synopsis

py_echo(int flag)

Arguments

flag An integer used to enable/disable echo.

Description

This routine affects command echoing in Marc Mentat’s dialogue area. If flag is set to true (a nonzero value), then the commands will be echoed. If flag is set to false (zero), then commands sent to Marc Mentat will not be echoed. This routine is most helpful in debugging Python scripts. The default setting is on. Note that enabling echo will slightly affect performance.

Marc Mentat command echoing for Python scripts may also be enabled in Marc Mentat using the button:

UTILS->PYTHON->SCRIPT ECHO

Example

py_echo(0) # disables echopy_echo(1) # enables echo

Page 180: MARC Tutorials

Marc Python Reference1-12

Page 181: MARC Tutorials

Chapter 2: PyPost References

CHAPTER

2 PyPost References

■ PyPost

■ close

■ cbody

■ cbody_angle

■ cbody_displacement

■ cbody_force

■ cbody_moment

■ cbody_name

■ cbody_rotation

Page 182: MARC Tutorials

Marc Python Reference2-2

■ cbody_transform

■ cbody_velocity

■ cbody_volume

■ cbodies

■ domain

■ element

■ elements

■ element_id

■ element_scalar

■ element_scalars

■ element_scalar_label

■ element_sequence

■ element_tensor

■ element_tensors

■ element_tensor_label

■ element_vector

■ element_vectors

■ element_vector_label

■ extrapolation

■ global_value

■ global_values

Page 183: MARC Tutorials

2-3CHAPTER 2PyPost References

■ global_value_label

■ increments

■ moveto

■ node

■ nodes

■ node_displacement

■ node_displacements

■ node_id

■ node_scalar

■ node_scalars

■ node_scalar_label

■ node_sequence

■ node_vector

■ node_vectors

■ node_vector_label

■ post_open

■ set

■ sets

■ title

■ version

Page 184: MARC Tutorials

Marc Python Reference2-4

PyPostThis chapter describes the PyPost routines and methods.

The PyPost module is used by a Python script to read data from a Marc post file.

All Python scripts that need access to the PyPost module must import the module as:

from py_post import *

The PyPost object contains attributes that are accessible after opening a post file. For example:

from py_post import *p = post_open(‘chap19.t16’)p.moveto(11)print ‘increment number ‘,p.increment

The PyPost object contains the following attributes:

General Description

cutback The total number of cutbacks

cycles The number of recycles for this increment

extrapolate The current extrapolation method

filename The postfile name associated with this object

increment The current increment

position The current position (as supplied to moveto())

revision The post file revision

separation The total number of separation recycles

split The total number of increment splittings

soltype The dynamic response flag: 0=Normal, 1=Modal, 2=Buckle, 3=Harmonic, 4=Complex.

subinc The current sub-increment. Non-zero for dynamic analysis.

Energy Description (from block 5180n)

creepenergy The total creep strain energy

dampenergy The total damping energy

Page 185: MARC Tutorials

2-5CHAPTER 2PyPost References

elasticenergy The total elastic strain energy

energy The total energy

kineticenergy The total kinetic energy

plasticenergy The total plastic strain energy

thermalenergy The total thermal energy

strainenergy The total strain energy

Variables

buckle The buckling factor (for a buckling analysis)

frequency The frequency (for a modal or harmonic analysis). This value is zero for the static increments of the analysis and non-zero for the dynamic increments. The following code segment will search all increments to find the first dynamic increment. firstdyn = 0 for i in range(1,ninc): p.moveto(i) if p.frequency != 0: firstdyn = iNote that soltype can also be check for being non-zero.

machangle The machine angle (SuperForm only)

pressure The process pressure

time The transient time

mass The total mass

volume The total volume

Work Description (from block 5180n)

appliedwork The total work done by applied force or displacement

contactwork The total work done by contact or external forces

foundwork The total work done by foundations

frictionwork The total work due to friction

springwork The total work done by springs

work The total work

Page 186: MARC Tutorials

Marc Python Reference2-6

The PyPost module uses the following special types:

PyNode Nodal Data

id the node id

x, y, z the x, y, z coordinates of the node

PyElement Element Data

type the element type

len number of nodes in the element

items the list of node id’s for the element

PySet Set Data

name string representing the set name

type the set type, either “node” or “element”

len the number of items in the ‘items’ list

items the list of nodes or elements

PyTensor Tensor Data

id The node id of the tensor, if applicable

t11, t12, t13 First row of tensor matrix. These values in matrix notation would be t(1,1), t(1,2), and t(1,3) respectively.

t22, t23 Second row of tensor matrix. Since the tensor matrix is symmetric, only the “top right” values of the matrix are returned. These values in matrix notation would be t(2,2) and t(2,3) respectively.

t33 Third row of tensor matrix. This value in matrix notation would be t(3,3).

intensity The tensor intensity

PyVector Vector Data

id The node id of the vector, if applicable

x,y,z The x, y, z vector values

PyCurve Curve Data

Page 187: MARC Tutorials

2-7CHAPTER 2PyPost References

npoints Number of points

norder Order of curve

points List of points that describe the curve (PyNode)

knots Knot vector. The number of items is npoints+norder.

w Weight values. The number of items is npoints.

PySurface Surface Data

npoints_u Number of points in “u” direction.

npoints_v Number of points in “v” direction.

norder_u Order of surface in “u” direction.

norder_v Order of surface in “v” direction.

points List of points that describe the surface (PyNode). There are npoints_u*npoints_v number of points. They are arranged in “v” major order, such that:for i in range(0,npoints_v):for j in range(0,npoints_u):

print ‘point[%i][%j].x=%12g‘ % (point[i*npoints_u+j].x)

w List of weight values (floats). They are arranged in “v” major order similar to the points array.

knots_u List of knot values (floats) in “u” direction. There are npoints_u+order_u items.

knots_v List of knot values (floats) in “v” direction. There are npoints_v+order_v items.

ntrim Number of trimming curves

trim List of trimming curves (PyCurve).

PyContactBody Contact Body Data

id The id of the contact body

name The name of the contact body

Page 188: MARC Tutorials

Marc Python Reference2-8

type The type of the contact body:0 - deformable1 - 2d line elements (type 9)2 - 3d patch elements (type 18)3 - 2d curves4 - 3d surfaces

bodytype The physical type of the contact body:1 - rigid2 - deformable structural3 - symmetry4 - deformable heat-rigid5 - workpiece (AutoForge)6 - deformable acoustic

center_xcenter_ycenter_z

The center of the contact body

axis_xaxis_yaxis_z

The axis of the contact body

npoints The number of points in the point array that describe the contact body. This value is nonzero if the contact body type is 1 or 2.

points Array of PyNode’s that describe the contact body

nelements Number of items in the elements array. This is set if the contact body type is 0. This value may also be obtained by using len(cb.elements) where cb is the PyContactBody object.

elements List of element id’s that describe the contact body.

npatches Number of items in the patches array. This is set if the contact body type is 2. This value may also be obtained by using len(cb.patches) where cb is the PyContactBody object.

patches List of PyPatch’s that describe the contact body.

ncurves The number of curves that describe the contact body. This is nonzero if the contact body is type 3. This value may also be obtained by using len(cb.curves) where cb is the PyContactBody object.

Page 189: MARC Tutorials

2-9CHAPTER 2PyPost References

curves List of PyCurve’s that describe the contact body.

nsurfaces The number of surfaces that describe the contact body. This is nonzero if the contact body is type 4. This value may also be obtained by using len(cb.surfaces) where cb is the PyContactBody object.

surfaces List of PySurface’s that describe the contact body.

Page 190: MARC Tutorials

Marc Python Reference2-10

close

Name

close

Summary

Closes a currently open post file and frees any allocated memory.

Synopsis

close()

Arguments

None

Description

This method closes the post file associated with the PyPost object.

Example

p = post_open(‘c08_job1.t19’)p.close()

Page 191: MARC Tutorials

2-11CHAPTER 2PyPost References

cbody

Name

cbody

Summary

Returns a PyContactBody object for a particular contact body.

Synopsis

PyContactBody cbody(Integer index)

Arguments

index Contact body index number

Description

Return a PyContactBody object for contact body index. The cbodies method should be called prior to calling the cbody method to obtain the total number of contact bodies that are available. The PyContactBody object contains the geometry for the contact body if the revision of the post file is 8 or higher (member revision of the PyPost object).

This method returns a PyContactBody object.

PyContactBody Membersid - contact body idname - name of the contact body (string)type - contact body type

0 - deformable1 - 2d line elements (line type 9)2 - 3d patch elements (elem type 18)3 - 2d curves4 - 3d surfaces

bodytype - physical type of contact body1 - rigid2 - deformable structure3 - symmetry

Page 192: MARC Tutorials

Marc Python Reference2-12

4 - deformable heat-rigid5 - workpiece (SuperForm only)6 - deformable acoustic

If the contact body type is 0 the following are set:nelements - number of element itemselements - array of element id’s that comprise the contact body.

If the contact body type is 1 the following are set:nlines - number of lines that comprise the contact bodylines - array of lines (PyPatch’s) that comprise the contact body.

The point1 and point2 members of PyPatch are indices into the points array.

If the contact body type is 2 the following are set:npatches - number of patches that comprise the contact bodypatches - array of patches (PyPatch’s) that comprise the contact body.

The point1, point2, point3 and point4 members of PyPatch are indices into the points array.

If the contact body type is 1 or 2 the following are set:npoints - number of point itemspoints - array of points (PyNode’s) that comprise the contact body.

If the contact body type is 3 the following are set:ncurves - number of curve itemscurves - array of curves (PyCurve’s) that comprise the contact body.

If the contact body type is 4 the following are set:nsurfaces - number of surface itemssurfaces - array of surfaces (PySurface’s) that comprise the contact body.

Prior to post revision 8, only rigid contact bodies have the following set:center_x, center_y, center_z

- center of the contact bodyaxis_x, axis_y, axis_z

- axis of the contact body

See Also

cbodies, cbody_name

Page 193: MARC Tutorials

2-13CHAPTER 2PyPost References

Example

p = post_open(‘ch03_job1.t16’)p.moveto(0)n = p.cbodies()for i in range(0,n):

d = p.cbody(i)print ‘contact body id ‘,d.id,’ name ‘,d.name,’ Type ‘,d.typeprint ‘Physical type ‘,d.bodytype

Page 194: MARC Tutorials

Marc Python Reference2-14

cbody_angle

Name

cbody_angle

Summary

Returns the angle for a particular contact body.

Synopsis

Float cbody_angle(Integer index)

Arguments

index cbody index number

Description

Return the value of the contact body angle at contact body index if available. The cbodies method should be called prior to calling the cbody_angle method to obtain the total number of cbodies that are available.

This method returns a float.

See Also

cbodies, cbody_name

Example

p = post_open(‘ch03_job1.t16’)p.moveto(0)n = p.cbodies()for i in range(0,p.increments())

p.moveto(i)for j in range(0,n):

a = p.cbody_angle(i)

Page 195: MARC Tutorials

2-15CHAPTER 2PyPost References

cbody_displacement

Name

cbody_displacement

Summary

Returns the displacement for a particular contact body.

Synopsis

Float, Float, Float cbody_displacement(Integer index)

Arguments

index Contact body index number

Description

Return the values of the contact body displacement at contact body index. The cbodies method should be called prior to calling the cbody_displacement method to obtain the total number of contact bodies that are available.

This method returns three floats.

See Also

cbodies, cbody_name

Example

p = post_open(‘ch03_job1.t16’)p.moveto(0)n = p.cbodies()for i in range(0,p.increments())

p.moveto(i)for j in range(0,n):

x,y,z = p.cbody_displacement(i)

Page 196: MARC Tutorials

Marc Python Reference2-16

cbody_force

Name

cbody_force

Summary

Returns the x, y, and z force for a particular contact body.

Synopsis

Float, Float, Float cbody_force(Integer index)

Arguments

index Contact body index number

Description

Return the values of the contact body force at contact body index. The cbodies method should be called prior to calling the cbody_force method to obtain the total number of contact bodies that are available.

This method returns three floats.

See Also

cbodies, cbody_name

Example

p = post_open(‘ch03_job1.t16’)p.moveto(0)n=p.cbodies()n = p.cbodies()for i in range(0,p.increments())

p.moveto(i)for j in range(0,n):

x,y,z = p.cbody_force(i)

Page 197: MARC Tutorials

2-17CHAPTER 2PyPost References

cbody_moment

Name

cbody_moment

Summary

Returns the moment for a particular contact body.

Synopsis

Float, Float, Float cbody_moment(Integer index)

Arguments

index Contact body index number

Description

Return the values of the moment for contact body index. The cbodies method should be called prior to calling the cbody_moment method to obtain the total number of contact bodies that are available.

This method returns three floats.

See Also

cbodies, cbody_name

Example

p = post_open(‘ch03_job1.t16’)p.moveto(0)n = p.cbodies()for i in range(0,p.increments())

p.moveto(i)for j in range(0,n):

x,y,z = p.cbody_moment(i)

Page 198: MARC Tutorials

Marc Python Reference2-18

cbody_name

Name

cbody_name

Summary

Returns the name of a particular contact body.

Synopsis

String cbody_name(Integer index)

Arguments

index Contact body index number

Description

Return the name contact body index. The cbodies method should be called prior to calling the cbody_name method to obtain the total number of contact bodies that are available.

This method returns a string.

See Also

cbodies

Example

p = post_open(‘ch03_job1.t16’)p.moveto(0)n = p.cbodies()for i in range(0,n):

print ‘ contact body ‘,p.cbody_id(), ‘ is named ‘, p.cbody_name(i)

Page 199: MARC Tutorials

2-19CHAPTER 2PyPost References

cbody_rotation

Name

cbody_rotation

Summary

Returns the rotation for a particular contact body.

Synopsis

Float cbody_rotation(Integer index)

Arguments

index Contact body index number

Description

Return the value of the contact body rotation for contact body index. The cbodies method should be called prior to calling the cbody_rotation method to obtain the total number of contact bodies that are available.

This method returns a float.

See Also

cbodies, cbody_name

Example

p = post_open(‘ch03_job1.t16’)p.moveto(1)n = p.cbodies()for i in range(0,p.increments())

p.moveto(i)for j in range(0,n):

r = p.cbody_rotation(i)

Page 200: MARC Tutorials

Marc Python Reference2-20

cbody_transform

Name

cbody_transform

Summary

Returns the transform for a particular contact body.

Synopsis

List Float cbody_transform(Integer index)

Arguments

index Contact body index number

Description

Return the values of the transform for contact body index. The cbodies method should be called prior to calling the cbody_transform method to obtain the total number of contact bodies that are available.

A transform is actually a 4x4 array of floats, however this method returns an array of 16 floats. They are arranged as follows:

See Also

cbodies, cbody_name

Example

p = post_open(‘ch03_job1.t16’)p.moveto(1)print cbody_transform(p.cbodies()-1)

T

t 0( ) t 1( ) t 2( ) t 3( )t 4( ) t 5( ) t 6( ) t 7( )t 8( ) t 9( ) t 10( ) t 11( )t 12( ) t 13( ) t 14( ) t 15( )

=

Page 201: MARC Tutorials

2-21CHAPTER 2PyPost References

cbody_velocity

Name

cbody_velocity

Summary

Returns the velocity of a particular contact body.

Synopsis

Float cbody_velocity(Integer index)

Arguments

index Contact body index number

Description

Return the value for the velocity of the contact body index. The cbodies method should be called prior to calling the cbody_velocity method to obtain the total number of contact bodies that are available.

This method returns a float.

See Also

cbodies, cbody_name

Example

p = post_open(‘ch03_job1.t16’)p.moveto(0)n = p.cbodies()for i in range(0,p.increments())

p.moveto(i)for j in range(0,n):

v = p.cbody_velocity(i)

Page 202: MARC Tutorials

Marc Python Reference2-22

cbody_volume

Name

cbody_volume

Summary

Returns the volume of a particular contact body.

Synopsis

Float cbody_volume(Integer index)

Arguments

index Contact body index number

Description

Return the value for the volume of the contact body index. The cbodies method should be called prior to calling the cbody_displacement method to obtain the total number of cbodies that are available.

This method returns a float.

See Also

cbodies, cbody_name

Example

p = post_open(‘ch03_job1.t16’)p.moveto(0)n = p.cbodies()for i in range(0,p.increments())

p.moveto(i)for j in range(0,n):

v = p.cbody_volume(i)

Page 203: MARC Tutorials

2-23CHAPTER 2PyPost References

cbodies

Name

cbodies

Summary

Returns the number of contact bodies.

Synopsis

Integer cbodies()

Arguments

None

Description

Returns the number of contact bodies.

Example

p = post_open(‘c07_job1.t19’)p.moveto(0)n = p.cbodies()

Page 204: MARC Tutorials

Marc Python Reference2-24

domain

Name

domains

Summary

Returns the number of domains in the post file.

Synopsis

Integer domains()

Arguments

None

Description

Returns the number of domains in the post file.

Example

p = post_open(‘c07_job1.t19’)n = p.domains()

Page 205: MARC Tutorials

2-25CHAPTER 2PyPost References

element

Name

element

Summary

Returns the element data for a particular element.

Synopsis

PyElement element(int nelem)

Arguments

nelem The element index number

Description

Returns a PyElement object containing the element data for element nelem in the current increment. This data may change for each increment due to rezoning.

PyElement Memberstype - element typelen - number of nodes in the elementitems - list of node id’s that comprise the element

Example

p = post_open(‘c08_job1.t19’)p.moveto(0)n = p.elements()for i in range(0,n): el = p.element(i) print el

Page 206: MARC Tutorials

Marc Python Reference2-26

elements

Name

elements

Summary

Returns the number of elements in the current increment.

Synopsis

Integer elements()

Arguments

None

Description

Returns the number of elements in the current increment. This may change for each increment due to rezoning.

Example

p = post_open(‘c08_job1.t19’)p.moveto(0)n = p.elements()

Page 207: MARC Tutorials

2-27CHAPTER 2PyPost References

element_id

Name

element_id

Summary

Returns id of a particular element.

Synopsis

Integer element_id(Integer nelem)

Arguments

nelem The element index number

Description

Returns id of element at index number nelem.

Example

p = post_open(‘c08_job1.t19’)# print the id’s of each elementp.moveto(0)n = p.elements()for i in range(0,n): print ‘Element ‘,i,’ has id ‘, p.element_id(i)

Page 208: MARC Tutorials

Marc Python Reference2-28

element_scalar

Name

element_scalar

Summary

Get a list of a particular element scalar for a particular element.

Synopsis

List PyScalar element_scalar(Integer nelem, Integer ns)

Arguments

nelem Element index number

ns Scalar index number

Description

Returns a PyScalar list for element scalar nscalar for element at index nelem. A scala is returned for each node in the element.

This PyScalar list contains the node id and the scalar value. The list returned is read-only, meaning that the values in the list cannot be changed.

Example

P = post_open(‘c08_job1.t19’)p.moveto(1)ne = p.element_scalars()n = p.elements()for i in range(0,ne): for j in range(0,n): slist = p.element_scalar(j,i) print ‘Element ‘,j for k in range(0,len(slist)): print ‘ Node ‘,slist[k].id, ‘Scalar ‘, ,slist[k].value slist[k].value = -slist[k].value # Causes Error

Page 209: MARC Tutorials

2-29CHAPTER 2PyPost References

element_scalars

Name

element_scalars

Summary

Returns the number of element scalars available.

Synopsis

Integer element_scalars()

Arguments

None

Description

Returns the number of element scalars available. This method returns an integer.

Example

P = post_open(‘c08_job1.t19’)# print the element scalar labelsp.moveto(1)n = p.element_scalars()for i in range(0,n): print p.element_scalar_label(i)

Page 210: MARC Tutorials

Marc Python Reference2-30

element_scalar_label

Name

element_scalar_label

Summary

Returns the name of a particular element scalar.

Synopsis

String element_scalar_label(Integer nscalar)

Arguments

nscalar Scalar index number

Description

Return the name of element scalar nscalar.

This method returns a string.

Example

p = post_open(‘c08_job1.t19’)# print the element scalar labelsp.moveto(1)n = p.element_scalars()for i in range(0,n): print p.element_scalar_label(i)

Page 211: MARC Tutorials

2-31CHAPTER 2PyPost References

element_sequence

Name

element_sequence

Summary

Returns index number of a particular element id.

Synopsis

Integer element_sequence(Integer nelem)

Arguments

nelem The element id

Description

Returns the index number of element with id nelem. This is the inverse of the element_id method.

Example

p = post_open(‘c08_job1.t19’)# print the id’s of each elementp.moveto(0)n = p.elements()for i in range(0,n): print ‘Element Id ‘,i,’ index ‘,p.element_sequence(i)

Page 212: MARC Tutorials

Marc Python Reference2-32

element_tensor

Name

element_tensor

Summary

Get a list of a particular element tensors for a particular element.

Synopsis

List PyTensor element_tensor(Integer nelem, Integer ntens)

Arguments

nelem Element index number

ntens Tensor index number

Description

Returns a list of nodes and nodal tensor values for element tensor ntens for element a index nelem. A scalar is returned for each node in the element.

This PyTensor list contains the node id and the tensor values. The list returned is read-only, meaning that the values in the list cannot be changed. This method returns a Python list of PyTensor values.

Example

P = post_open(‘c08_job1.t19’)p.moveto(1)ne = p.element_tensors()n = p.elements()for i in range(0,ne): for j in range(0,n): tlist = p.element_tensor(j,i) print ‘Element ‘,j for k in range(0,len(tlist)): print ‘ Tensor ‘,tlist[k]

Page 213: MARC Tutorials

2-33CHAPTER 2PyPost References

element_tensors

Name

element_tensors

Summary

Returns the number of element tensors available.

Synopsis

Integer element_tensors()

Arguments

None

Description

Returns the number of element tensors available. This method returns an integer.

Example

P = post_open(‘c08_job1.t19’)# print the element tensor labelsp.moveto(1)n = p.element_tensors()for i in range(0,n): print p.element_tensor_label(i)

Page 214: MARC Tutorials

Marc Python Reference2-34

element_tensor_label

Name

element_tensor_label

Summary

Returns the name of a particular element tensor.

Synopsis

String element_tensor_label(Integer ntens)

Arguments

ntens Tensor index number

Description

Return the name of element tensor ntens.

This method returns a string.

Example

p = post_open(‘c08_job1.t19’)# print the element tensor labelsp.moveto(1)n = p.element_tensors()for i in range(0,n): print p.element_tensor_label(i)

Page 215: MARC Tutorials

2-35CHAPTER 2PyPost References

element_vector

Name

element_vector

Summary

Get a list of a particular element vector for a particular element.

Synopsis

List PyVector element_vector(Integer nelem, Integer nv)

Arguments

nelem Element index number

nv Vector index number

Description

Returns a list of nodes and values for element vector nv for element at index nelem. A scalar is returned for each node in the element.

This PyVector list contains the node id and the vector values. The list returned is read-only, meaning that the values in the list cannot be changed.

This method returns a Python list of PyVector values.

Example

P = post_open(‘c08_job1.t19’)p.moveto(1)ne = p.element_vectors()n = p.elements()for i in range(0,ne): for j in range(0,n): vlist = p.element_vector(j,i) print ‘Element ‘,j for k in range(0,len(vlist)): print ‘ Vector ‘,vlist[k]

Page 216: MARC Tutorials

Marc Python Reference2-36

element_vectors

Name

element_vectors

Summary

Returns the number of element vectors available.

Synopsis

Integer element_vectors()

Arguments

None

Description

Returns the number of element vectors available. This method returns an integer.

Example

P = post_open(‘c08_job1.t19’)# print the element vector labelsp.moveto(1)n = p.element_vectors()for i in range(0,n): print p.element_vector_label(i)

Page 217: MARC Tutorials

2-37CHAPTER 2PyPost References

element_vector_label

Name

element_vector_label

Summary

Returns the name of a particular element vector.

Synopsis

String element_vector_label(Integer nscalar)

Arguments

nvec Vector index number

Description

Return the name of element vector nvec. This method returns a string.

Example

p = post_open(‘c08_job1.t19’)# print the element vector labelsp.moveto(1)n = p.element_vectors()for i in range(0,n): print p.element_vector_label(i)

Page 218: MARC Tutorials

Marc Python Reference2-38

extrapolation

Name

extrapolation

Summary

Sets the integration point extrapolation method.

Synopsis

extrapolation(String type)

Arguments

type A string representing the integration method to use

Description

This method controls the manner in which element integration point data is extrapolated to the nodes of an element. In addition, they control the inter-element averaging of the nodal data after it has been extrapolated. The available methods are:

linear Extrapolate by averaging the integration points to the centroid of the element and then doing a linear extrapolation from the centroid through the integration point to the node.

translate Do not extrapolate, but rather copy the data at each integration point to its corresponding node. In those cases where there are fewer integration points than nodes, some averaging of neighboring integration points may be done.

average The average of all the integration points is computed and assigned to the nodes. Therefore, all nodes have an equal value assigned to them.

Example

P = post_open(‘c08_job1.t19’)p.extrapolation(‘linear’)print ‘Extrapolation method is ‘, p.extrapolate

Page 219: MARC Tutorials

2-39CHAPTER 2PyPost References

global_value

Name

global_value

Summary

Returns the value of a particular global value.

Synopsis

Float global_value(Integer index)

Arguments

index Global value index number

Description

Return the value of a particular global value index.

This method returns a float.

Example

# Post file from Userguide Example 3.5p = post_open(‘airspring_axito3d_wcav_job1.t16’)ninc = p.increments()p.moveto(ninc-1)n = p.global_values() for i in range(0,n): print p.global_value_label(i), ‘: ‘, p.global_value(i)

Resulting Output:

Volume Cavity 1 : 0.00172809232026Pressure Cavity 1 : 1904785.625Mass Cavity 1 : 0.0363396443427Temperature Cavity 1 : 300.0Loadcase Percentage Completion : 0.0

Page 220: MARC Tutorials

Marc Python Reference2-40

global_values

Name

global_values

Summary

Returns the number of global values available.

Synopsis

Integer global_values()

Arguments

None

Description

Returns the number of global values available. This method returns an integer.

Example

P = post_open(‘airspring_axito3d_wcav_job1.t16’)# print the global value labelsn = p.global_values()for i in range(0,n): print p.global_value_label(i)

Page 221: MARC Tutorials

2-41CHAPTER 2PyPost References

global_value_label

Name

global_value_label

Summary

Returns the name of a particular global value.

Synopsis

String global_value_label(Integer index)

Arguments

index Global value index number

Description

Return the name of global value index.

This method returns a string.

Example

p = post_open(‘airspring_axito3d_wcav_job1.t16’)# print the global value labelsn = p.global_values()for i in range(0,n): print p.global_value_label(i)

Page 222: MARC Tutorials

Marc Python Reference2-42

increments

Name

increments

Summary

Returns the number of increments.

Synopsis

Integer increments()

Arguments

None

Description

The number of increments in the post file is returned. Note that increment 0 contains the model data. All scalar values are zero. Increment number 1 is the first increment in the post file that contains scalar data. For example, even if a post file only contains one increment, the increments method will return 2.

Example

p = post_open(‘c08_job1.t19’)n = p.increments()

Page 223: MARC Tutorials

2-43CHAPTER 2PyPost References

moveto

Name

moveto

Summary

Moves to the specified increment in the post file.

Synopsis

moveto(Integer i)

Arguments

i increment number

Description

Moves to the specified increment in the post file. Increment number 0 only contains the model itself. There is no scalar data for increment 0. The first increment with data is increment 1.

When the moveto method is called, the following members of the PyPost object are available:

increment increment number

time time of this increment

frequency frequency value of this increment

Example

p = post_open(‘c07_job1.t19’)p.moveto(4)print ‘increment ‘,p.increment,’ Time ‘,p.timeprint ‘Frequency ‘,p.frequency

Page 224: MARC Tutorials

Marc Python Reference2-44

node

Name

node

Summary

Returns the nodal data for a particular node.

Synopsis

PyNode node(int nnode)

Arguments

nnode The node index number

Description

Returns a PyNode object containing the nodal data for node at index nnode in the current increment. This data may change for each increment due to rezoning.

PyNode Membersid - node idx - x coordinatey - y coordinatez - z coordinate

Example

p = post_open(‘c08_job1.t19’)p.moveto(0) n = p.nodes()for i in range(0,n): nod = p.node(i) print "Node index number ",i, " Id ",nod.id print " x = ",nod.x, " y = ",nod.y," z = ",p.z

Page 225: MARC Tutorials

2-45CHAPTER 2PyPost References

nodes

Name

nodes

Summary

Returns the number of nodes in the current increment.

Synopsis

Integer nodes()

Arguments

None

Description

Returns the number of nodes in the current increment. This may change for each increment due to rezoning.

Example

p = post_open(‘c07_job1.t19’)p.moveto(0) n = p.nodes()

Page 226: MARC Tutorials

Marc Python Reference2-46

node_displacement

Name

node_displacement

Summary

Returns the nodal displacement values at a particular node.

Synopsis

Float, Float, Float node_displacement(Integer index)

Arguments

index Node index number

Description

Return the values of the nodal displacement at node index if available. The node_displacements method should be called prior to calling the node_displacement method to make sure that nodal displacements are available.

This method returns three floats.

See Also

node_displacements

Example

p = post_open(‘c07_job1.t19’)p.moveto(1)n = p.nodes()have_disp = p.node_displacements()if have_disp: for i in range(0,n): x,y,z = p.node_displacement(i)

Page 227: MARC Tutorials

2-47CHAPTER 2PyPost References

node_displacements

Name

node_displacements

Summary

Returns a 1 if nodal displacements available, 0 otherwise.

Synopsis

Integer node_displacements()

Arguments

None

Description

This method should be used prior to calling the node_displacement method to determine if nodal displacements are available. Returns 1 if nodal displacements are available, 0 otherwise.

Example

# print the name of each scalar labelp = post_open(’c07_job1.t19’)p.moveto(1)if p.node_displacements() : print "Nodal displacements available"

Page 228: MARC Tutorials

Marc Python Reference2-48

node_id

Name

node_id

Summary

Returns the id of a particular node.

Synopsis

Integer node_id(Integer node)

Arguments

node The node index number

Description

Returns id of node at index node.

Example

p = post_open(‘c08_job1.t19’)# print the id’s of each nodep.moveto(0)n = p.nodes()for i in range(0,n): print ‘Node ‘,i,’ has id ‘, p.node_id(i)

Page 229: MARC Tutorials

2-49CHAPTER 2PyPost References

node_scalar

Name

node_scalar

Summary

Returns the value of a particular node scalar at a particular node.

Synopsis

Float node_scalar(Integer index, Integer scalar)

Arguments

index Node index number

scalar Scalar index number

Description

Return the value of a particular node scalar scalar at a particular node index.

This method returns a float.

Example

# get each scalar for node at index 4f = [ ]p = post_open(‘c07_job1.t19’)p.moveto(1)n = p.node_scalars() id = node_id(4)print ‘node scalars for node id ‘,idfor i in range(0,n): f.append(p.node_scalar(4, i)) print ‘scalar ‘,f[i]

Page 230: MARC Tutorials

Marc Python Reference2-50

node_scalars

Name

node_scalars

Summary

Returns the number of node scalars available.

Synopsis

Integer node_scalars()

Arguments

None

Description

Returns the number of node scalars available.

Example

# print the name of each scalar labelp = post_open(‘c07_job1.t19’)p.moveto(1)n = p.node_scalars()for i in range(0, n): print p.node_scalar_label(i)

Page 231: MARC Tutorials

2-51CHAPTER 2PyPost References

node_scalar_label

Name

node_scalar_label

Summary

Returns the name of a particular scalar.

Synopsis

String node_scalar_label(Integer index)

Arguments

index Scalar index number

Description

Return the name of node scalar index.

This method returns a string.

Example

# print the name of each scalar labelp = post_open(‘c07_job1.t19’)p.moveto(1)n = p.node_scalars()for i in range(0, n): print p.node_scalar_label(i)

Page 232: MARC Tutorials

Marc Python Reference2-52

node_sequence

Name

node_sequence

Summary

Returns index number of a particular node id.

Synopsis

Integer node_sequence(Integer node)

Arguments

node The node id

Description

Returns the index number of node with id node. This is the inverse of the node_id method.

Example

p = post_open(‘c08_job1.t19’)p.moveto(0)# print the index of each noden = p.nodes()for i in range(0,n): print ‘Node Id ‘,i,’ has index ‘, p.node_sequence(i)

Page 233: MARC Tutorials

2-53CHAPTER 2PyPost References

node_vector

Name

node_vector

Summary

Return the value of a particular node vector at a particular node.

Synopsis

PyVector node_vector(Integer index, Integer nv)

Arguments

index Node index number

nv Vector index number

Description

Return the vector of a particular node vector nv at a particular node index.

This method returns a PyVector.

Example

# get each vector for node 4p = post_open(‘c07_job1.t19’)p.moveto(1)n = p.node_vectors()for i in range(0,n): v = p.node_vector(4, i) print ‘Vector ‘,i,’ is ‘, v.x, v.y, v.z

Page 234: MARC Tutorials

Marc Python Reference2-54

node_vectors

Name

node_vectors

Summary

Returns the number of node vectors available.

Synopsis

Integer node_vectors()

Arguments

None

Description

Returns the number of node vectors available.

Example

# print the name of each vector labelp = post_open(‘c07_job1.t19’)p.moveto(1)n = p.node_vectors()for i in range(0, n): print p.node_vector_label(i)

Page 235: MARC Tutorials

2-55CHAPTER 2PyPost References

node_vector_label

Name

node_vector_label

Summary

Returns the name of a particular node vector.

Synopsis

String node_vector_label(Integer index)

Arguments

index Vector index number

Description

Return the name of node vector index.

This method returns a string.

Example

# print the name of each vector labelp = post_open(‘c07_job1.t19’)p.moveto(1)n = p.node_vectors()for i in range(0, n): print p.node_vector_label(i)

Page 236: MARC Tutorials

Marc Python Reference2-56

post_open

Name

post_open

Summary

Open a postfile and return the PyPost object.

Synopsis

PyPost post_open(String filename)

Arguments

filename Post file name.

Description

This method opens the specified post file and returns a PyPost object. This is the first PyPost routine that a Python script should call. A call to moveto() should follow to force a reading of the increment data at the first increment on the post file.

Members

position - current increment positionfilename - the post file namerevision - the revision of the post file

The following members are updated when the moveto method is called:increment - the increment number of post filetime - the time for the current incrementfrequency - the frequency of this increment

Example

p1 = post_open(‘e7x14_solver0.t19’)p1.moveto(0)p2 = post_open(‘e7x14_solver1.t19’)p2.moveto(0)print ‘Comparing ‘,p1.filename, ‘ to ‘,p2.filename

Page 237: MARC Tutorials

2-57CHAPTER 2PyPost References

set

Name

set

Summary

Returns the data for a particular set.

Synopsis

PyPostSet set(int nset)

Arguments

nset The set index number

Description

Returns a PyPostSet object containing the set data for set nset in the models.

Members

name - set nametype - set typelen - number of items in the setitems - list of data that comprise the set

Example

p = post_open(‘c08_job1.t19’)p.moveto(0)n = p.sets()for i in range(0,n): s = p.set(i) print ‘Name:’,s.name, ‘Type: ‘,s.type

for j in range(0,s.len): print ‘Item:’,j, ‘Value: ‘,s.items[j]

Page 238: MARC Tutorials

Marc Python Reference2-58

sets

Name

sets

Summary

Returns the number of sets in the post file.

Synopsis

Integer sets()

Arguments

None

Description

Returns the number of sets in the post file.

Example

p = post_open(‘c07_job1.t19’)p.moveto(0)n = p.sets()

Page 239: MARC Tutorials

2-59CHAPTER 2PyPost References

title

Name

title

Summary

Returns the title of the post file.

Synopsis

String title()

Arguments

None

Description

Returns the title of the model stored in the post file.

This method returns a string.

Example

# print the titlep = post_open(‘c08_job1.t19’)print ‘Title: ‘,p.title()

Page 240: MARC Tutorials

Marc Python Reference2-60

version

Name

version

Summary

Returns the version of the PyPost module.

Synopsis

String version()

Arguments

None

Description

Return the version string of the PyPost module.

This method returns a string.

Example

print ‘PyPost version is ‘,version()p = post_open(‘c08_job1.t19’)

Page 241: MARC Tutorials

Appendix A

A Appendix A

■ Arithmetic and Database Functions

❏ Arithmetic Functions

❏ Database Functions

❏ Utility Functions

❏ Set Functions

Page 242: MARC Tutorials

Marc Python ReferenceA-2

Arithmetic and Database FunctionsThis chapter describes the Arithmetic and Database function supported by Marc Mentat. If the argument to any function is shown in capital letters (such as ARGn), then the argument is an index and may be negative in which case the entities are counted in reverse order (i.e., ARGn = -1 would refer to the last item). A good example of the usage of these functions can be found in the Marc User’s Guide, Chapter 31 procedure file. If the argument to a database function is in lower case (such as argn) then the value is an id, such as a node id or an element id unless otherwise described.

Arithmetic Functions

The following are the Marc Mentat Arithmetic Functions which can be used in the py_get_float or py_get_int functions or in a formula.

Table A-1 Arithmetic Functions

Function Description

cos(arg1) Cosine of arg1 radians

sin(arg1) Sine of arg1 radians

tan(arg1) Tangent of arg1 radians

dcos(arg1) Cosine of arg1 degrees

dsin(arg1) Sine of arg1 degrees

dtan(arg1) Tangent of arg1 degrees

acos(arg1) Arccosine of arg1 radians

asin(arg1) Arcsine of arg1 radians

atan(arg1) Arctangent of arg1 radians

atan2(arg1,arg2) Arctangent of (arg1/arg2) radians

dacos(arg1) Arccosine of arg1 degrees

dasin(arg1) Arcsine of arg1 degrees

datan(arg1) Arctangent of arg1 degrees

datan2(arg1,arg2) Arctangent of (arg1/arg2) degrees

log(arg1) Base-10 logarithm of arg1

ln(arg1) Natural logarithm of arg1

exp(arg1) E to the power arg1

Page 243: MARC Tutorials

A-3Appendix AArithmetic and Database Functions

cosh(arg1) Hyperbolic cosine of arg1

sinh(arg1) Hyperbolic sine of arg1

tanh(arg1) Hyperbolic tangent of arg1

acosh(arg1) Inverse hyperbolic cosine of arg1

asinh(arg1) Inverse hyperbolic sin of arg1

atanh(arg1) Inverse hyperbolic tangent of arg1

sqrt(arg1) Square root of arg1

rad(arg1) Angle in radians of arg1 degrees

deg(arg1) Angle in degrees of arg1 radians

abs(arg1) Absolute value of arg1

int(arg1) Largest integral value not greater than arg1

frac(arg1) Fractional part of arg1

max(arg1,arg2) Maximum of arg1 and arg2

min(arg1,arg2) Minimum of arg1 and arg2

dist2d(arg1,arg2,arg3,arg4) Distance in 2-D space between a point with coordinates (arg1,arg2) and a point with coordinates (arg3,arg4)

dist3d(arg1,arg2,arg3,arg4,arg5,arg6)

Distance in 3-D space between a point with coordinates (arg1,arg2,arg3) and a point with coordinates (arg4,arg5,arg6)

Table A-1 Arithmetic Functions (Continued)

Page 244: MARC Tutorials

Marc Python ReferenceA-4

Database Functions

The following are the Marc Mentat Database Functions which can be used in the py_get_float, py_get_int or py_get_string functions.

Note that the database functions may also be used as the argument to many commands. For example:

*remove_elements element_id(-1)

would remove the last element of the model. To use numeric values in a string based command (such as *job_title) a PARAMETER will need to be created from the database function and then used in the string command. For example:

*eval_define num nnodes()

*job_title Model with $num nodes

will create an evaluated parameter named num using the nnodes() database function, and then use that in the *job_title command (note the use of the $ to signify it is the name of a parameter). The job title for the CONTACT demo would appear as:

Model with 72 nodes

Table A-2 Database Functions

Function Description

filename() Returns the name of the model file without the path.

getcwd() Returns the current directory.

model_name() Returns the current model name.

revision Returns the string for the base version (such as 2010).

version Returns the string for the version (same as for *version command).

points() Number of points in database

point_id(ARG1) Id of ARG1-th point in database

max_point_id() Largest point id in database

point_surface_id(arg1) Id of surface trimmed by point arg1

point_x(arg1) Global X-coordinate of point arg1

point_y(arg1) Global Y-coordinate of point arg1

point_z(arg1) Global Z-coordinate of point arg1

point_u1(arg1) First user coordinate of point arg1

Page 245: MARC Tutorials

A-5Appendix AArithmetic and Database Functions

point_u2(arg1) Second user coordinate of point arg1

point_u3(arg1) Third user coordinate of pointarg1

point_s1(arg1) First surface parametric coordinate of point arg1

point_s2(arg1) Second surface parametric coordinate of point arg1

ncurves() Number of curves in database

curve_id(ARG1) Id of ARG1-th curve in database

max_curve_id() Largest curve id in database

ncurve_points(arg1) Number of points of curve arg1

curve_point_id(arg1,ARG2) Id of ARG2 -th point of curve arg1

curve_surface_id(arg1) Id of surface trimmed by curve arg1

curve_length(arg1) Length of curve arg1

curve_ndiv(arg1) Number of divisions of curve arg1

ncurve_seedpoints(arg1) Number of seed points of a curve. It is identical to curve_ndiv(arg1)+1.

curve_seedpoint(arg1,ARG2) Returns the curve coordinate (between 0 and 1) of the ARG2-th seedpoint. If ARG2 is negative, seed points are counted in reverse order (ARG2 = -1 would return the last seed point).

nsurfaces() Number of surfaces in database

surface_id(ARG1) Id of ARG1-th surface in database

max_surface_id() Largest surface id in database

nsurface_curves(arg1) Number of trimming curves of surface arg1

surface_curve_id(arg1,ARG2)

Id of ARG2-th curve in database that trims surface arg1

nsurface_points_x(arg1) Number of defining points in first parametric direction of surface arg1

nsurface_points_y(arg1) Number of defining points in second parametric direction of surface arg1

surface_point_id(arg1,ARG2,ARG3)

Id of (ARG2, ARG3) -the defining point of surface arg1

nsolids() Number of solids in database

solid_id(ARG1) Id of ARG1-th solid in database

nsolid_lumps(arg1) Number of lumps of solid arg1

nsolid_faces(arg1) Number of faces of solid arg1

nsolid_edges(arg1) Number of edges of solid arg1

nsolid_vertices(arg1) Number of vertices of solidarg1

Table A-2 Database Functions (Continued)

Page 246: MARC Tutorials

Marc Python ReferenceA-6

solid_area(arg1) Surface area of solid arg1

solid_volume(arg1) Volume of solid arg1

nnodes() Number of nodes in database

node_id(ARG1) Id of ARG1-th node in database

max_node_id() Largest node id in database

node_x(arg1) Global X-coordinate of node arg1

node_y(arg1) Global Y-coordinate of node arg1

node_z(arg1) Global Z-coordinate of node arg1

node_u1(arg1) First user coordinate of node arg1

node_u2(arg1) Second user coordinate of node arg1

node_u3(arg1) Third user coordinate of node arg1

node_tform(arg1) Transform name of node arg1.

nelements() Number of elements in database

element_id(ARG1) Id of ARG1-th element in database

max_element_id() Largest element id in database

element_node_id(arg1,ARG2)

Id of ARG2-th node of element arg1

job_name() Name of the job

job_title() Title of the job

element_class(arg1) Class of element arg1. Returns an integer:LINE2 = 0LINE3 = 1TRIA3 = 2TRIA6 = 3QUAD4 = 4QUAD6 = 5QUAD8 = 6QUAD9 = 7HEX8 = 8HEX12 = 9HEX20 = 10HEX27 = 11TETRA4 = 12TETRA10 = 13PENTA6 = 14PENTA15 = 15

element_dimension(arg1) Dimension of element arg1 (returns either 2 or 3)

Table A-2 Database Functions (Continued)

Page 247: MARC Tutorials

A-7Appendix AArithmetic and Database Functions

element_family(arg1) Family of element arg1. Returns an integer:LINE = 1TRIA = 2QUAD = 3HEX = 4TETRA = 5PENTA = 6

element_edges(arg1) Number of edges for element arg1

element_edge_area(arg1,ARG2)

Edge area of the ARG2-th face of element arg1. If the edge id ARG2 is -1, then it returns the total edge area of the element. If the element number arg1 is -1, then it returns the total edge area of all elements. If the element number arg1 is zero, then it returns the total edge area of the selected elements.

element_edge_length(arg1,ARG2)

Edge length of the ARG2-th face of element arg1. If the edge id ARG2 is -1, then it returns the total edge length of the element. If the element number arg1 is -1, then it returns the total edge length of all elements. If the element number arg1 is zero, then it returns the total edge length of the selected elements.

element_faces(arg1) Number of faces for element arg1

element_face_area(arg1,ARG2)

Face area of the ARG2-th face of element arg1. If the face id ARG2 is -1, then it returns the total face area of the element.If the element number arg1 is -1, then it returns the total face area of all elements. If the element number arg1 is zero, then it returns the total face area of the selected elements.

element_face_volume(arg1,ARG2)

Face volume of the ARG2-th face of element arg1. If the face id ARG2 is -1, then it returns the total face volume of the element. If the element number arg1 is -1, then it returns the total face volume of all elements. If the element number arg1 is zero, then it returns the total face volume of the selected elements.

element_mass(arg1) Mass of element arg1. If the element number arg1 is -1, then it returns the total mass of all elements. If the element number arg1 is zero, then it returns the total mass of the selected elements.

element_nodes(arg1) Number of nodes for element arg1

element_volume(arg1) Volume of element arg1. If the element number arg1 is -1, then it returns the total volume of all elements. If the element number arg1 is zero, then it returns the total volume of the selected elements.

element_type(arg1) Element type associated with element id arg1. For example, obtain type of last element:

element_type(element_id(-1))

element_cbody(arg1) Contact body name associated with element id arg1

Table A-2 Database Functions (Continued)

Page 248: MARC Tutorials

Marc Python ReferenceA-8

element_geom(arg1) Geometric property name associated with element id arg1

element_material(arg1) Material name associated with element id arg1

element_orient(arg1) Orientation property name associated with element id arg1

nadapgs() Number of global remeshing criterion in the database

adapg_par(arg1,arg2) Parameter value named arg2 for the global remeshing criteria named arg1. If arg1 is empty, then it uses the current global remeshing criteria.Example:

adapg_par(adapg1,nelems)

adapg_name_index(ARG1) Global remeshing criterion name of ARG1-th global remeshing criterion in database.

adapg_opt(arg1,arg2) Option string for option arg2 for the current global remeshing criterion named arg1. If arg1 is empty, then it uses the current global remeshing criterion.Example:

adapg_opt(adapg1,immediate_crit)

adapg_type(arg1) Global remeshing criterion type for global remeshing criterion arg1. If arg1 is empty, then it uses the current global remeshing criterion.

napplys() Number of boundary conditions in the database

apply_name_index(ARG1) Boundary condition name of ARG1-th boundary condition criterion in database.

apply_opt(arg1,arg2) Option string for option named arg2 for the apply named arg1. If arg1 is empty, then it uses the current apply. Parameter values use same syntax as in the *apply_option command.Example:

apply_opt(apply1,ref_position)

apply_par_table(apply1,x) Parameter table name parameter named arg2 for the apply named arg1. If arg1 is empty, then it uses the current apply. Parameter values use same syntax as in the *apply_dof_table commandExample:

apply_par_table(apply1,x)

apply_type(arg1) Boundary condition type for boundary condition named arg1. If arg1 is empty, then it uses the current boundary condition.

Table A-2 Database Functions (Continued)

Page 249: MARC Tutorials

A-9Appendix AArithmetic and Database Functions

apply_par(arg1,arg2) Parameter value named arg2 for the apply (boundary condition) named arg1. If arg1 is empty, then it uses the current boundary condition.Example:

apply_par(apply1,temp_inf)

Valid parameters:ambient_pressure, cavity_id, convection_coef, current_<x|y|z>, diff_h_<1..10>, diff_z_e_<1..10>, diff_z_s_<1..10, diffusion_coef, drag_coef, emp_corr_fl_fac, emp_corr_fl_nfthp,emp_corr_fl_temp1, emp_corr_fl_temp2, emp_corr_rr_fac, enth_ablation, enth_froz_comp, enth_pyr_twall, enth_recovery, enth_wall_gas, flm_eff_view_fac, flm_emissivity, flm_ext_dist_flux, flm_nat_conv_coef, flm_nat_conv_exp, fluid_drag_factor, glocal_ext_tol, glocal_timeshift, gradient_<x|y|z>, gravity_const, in_mass_density, in_surf_elev, inertia_coef, init_weld_pos_<x|y|z>, liq_ph_enth_<1..10>, liq_ph_massrt_<1..10>,nfam_particles, nliq_phases, nterm_diffusion, out_mass_density, out_surf_elev, part_correl_f_<1..10>, part_diameter_<1..10>, part_enth_react_<1..10>, part_incid_ang_<1..10>, part_massrt_<1..10>, part_velocity_x_<1..10>, part_velocity_y_<1..10>, part_velocity_z_<1..10>, post_file_inc, post_file_steps, pump_pressure, pyr_recession, rho_v_wall, rot_axis_<x|y|z>1, rot_axis_<x|y|z>2, rot_axis_v<x|y|z>,

sea_bed_elev, sol_abl_gas, sol_abl_liq_part, sol_abl_part_imp, sol_massrt_eros, sol_massrt_gas, sol_massrt_part, srf_nrg_diffusion, state_var_id, temp_inf, temp_inf_bot, transpiration_f, view_fac_rec_inc, view_fac_rec_motion, wave_dir_cos<1|2>, wave_height, wave_period, wave_phase, weld_depth, weld_efficiency, weld_fwd_length, weld_max_distance, weld_power, weld_rear_length, weld_scale_factor, weld_surf_radius, weld_velocity, weld_width, weldpath_offset_<x|y>

Table A-2 Database Functions (Continued)

Page 250: MARC Tutorials

Marc Python ReferenceA-10

apply_dof_val(arg1,arg2) Dof value named arg2 for the boundary condition named arg1. If arg1 is empty, then it uses the current boundary condition.Example:

icond_dof_val(apply1,x)icond_dof_val(,x)

Valid parameters:hkfqpsuwx1xyz

apply_name() Returns the name of the current boundary condition.

ncbodys() Number of contact bodies in the database.

cbody_name_index(ARG1) Contact body name of ARG1-th global contact body in database.

cbody_par(arg1,arg2) Parameter value for param named arg2 for contact body named arg1. If arg1 is empty, then it uses the current contact body. Parameter values use same syntax as in the *contact_value command. Example:

cbody_par(cbody1,surf_div_u)

cbody_par_table(arg1,arg2) Parameter table name for param named arg2 for contact body named arg1. If arg1 is empty, then it uses the current contact body. Parameter values use same syntax as in the *cbody_param_table command. Example:

cbody_par_table(cbody1,filmk)

cbody_type(arg1) Contact body type for contact body named arg1. If arg1 is empty, then it uses the current contact body.

Table A-2 Database Functions (Continued)

Page 251: MARC Tutorials

A-11Appendix AArithmetic and Database Functions

cbody_par(arg1,arg2) Parameter value named arg2 for the contact body named arg1. If arg1 is empty, then it uses the current contact body.Example:

cbody_par(cbody1,friction)

Valid parameters:ac_bound_c1_inv, ac_bound_k1_inv, ax, ay, az, body_pressure, body_voltage, brot, bx, by, bz, conductivity, contact, contact_conductivity, contact_mass_flow_rate, cr, curve_div, cx, cy, cz, dist_dep_conductivity, dist_dep_heat, dist_dep_mass_flow_rate, film, friction, friction_class, growth_factor_<x|y|z>, initvrot, initv<x|y|z>, mass_flow_rate, natural_conv_coef, natural_conv_exp, near_contact_conductivity, near_contact_heat, near_contact_mass_flow_rate, prot, px, py, pz, sink_pressure, sink_voltage, spring_force, spring_lmax, spring_lmin, spring_stiff, surf_div_u, surf_div_v, surface_emissivity, tsink, tsurf, vrot, vx, vy, vz

ctable_name() Returns the name of the current contact table.

nctables() Number of contact tables in the database

ctable_name_index(ARG1) Contact table name of ARG1-th contact table in database.

niconds() Number of initial conditions in the database

icond_name_index(ARG1) Initial condition name of ARG1-th initial condition in database.

icond_opt(arg1,arg2) Option string for option named arg2 for the initial condition named arg1. If arg1 is empty, then it uses the current initial condition. Option strings use same syntax as in the *icond_option command. Example:

icond_opt(icond1,dof_values)

icond_type(arg1) Initial condition type for icond arg1. If arg1 is empty, then it uses the current initial condition.

icond_dof_val(arg1,arg2) Dof value named arg2 for the initial condition named arg1. If arg1 is empty, then it uses the current initial condition.Example:

icond_dof_val(icond1,x)

icond_name() Returns the name of the current initial condition.

icond_par(arg1,arg2) Parameter value named arg2 for the initial condition named arg1. If arg1 is empty, then it uses the current initial condition.Example:

icond_par(icond1,trans_x)

ngeoms() Number of geometric properties in the database

geom_name() Returns the name of the current geometric property

geom_name_index(ARG1) Geometic property name of ARG1-th geometry in database.

Table A-2 Database Functions (Continued)

Page 252: MARC Tutorials

Marc Python ReferenceA-12

geom_opt(arg1,arg2) Option string for option named arg2 for geometry named arg1. If arg1 is empty, then it uses the current geometry. Option strings use same syntax as in the *geometry_option command. Example:

geom_opt(material3,cdilatation)

geom_par(arg1,arg2) Parameter value for param named arg2 for geometry named arg1. If arg1 is empty, then it uses the current geometry. Parameter values use same syntax as in the *geometry_param command. Example:

geom_par(material3,thick)

geom_par_table(arg1,arg2) Parameter table name for value named arg2 for geometry named arg1. If arg1 is empty, then it uses the current geometry. Parameter values use same syntax as in the *geometry_param_table command. Example:

geom_par_table(material3,thick)

geom_type(arg1) Geometric property type for geometry arg1. If arg1 is empty, then it uses the current geometry.

job_par(arg1,arg2) Parameter value named arg2 for job arg1. If arg1 is empty, then it uses the current job.Example:

job_par(lcase1,trans_x)Valid parameters:adapg_frequency, adapt_frequency, ambient_pressure, bcond_pen_mp, bi_maxit, bi_tol, bm_bm_files_freq, condition, conversion, cutoff, cycs_rot_axis_dir_<x|y|z>, cycs_rot_axis_point_<x|y|z>, cycs_rot_nrepetitions, cycs_tolerance, ddm_precond_level, ddm_sort_direction_<x|y|z>, ddm_sort_point_<x|y|z>, ddm_tolerance, decomp_elweight_coeff, des_act_cons, des_crit_cons, des_opt_cycles, disttol, disttolbias, dyn_contact_pro_fact, ebe_heat_tol, ebe_maxit, ebe_stress_tol, elec_heat_conv, fl_hardw_sparse_thresh, flowl_grid_num_<x|y|z>, flowl_grid_pnt_<x|y|z>, flowl_grid_siz_<x|y|z>, fluid_incomp_pen, fric_coeff_mult, fric_force_tol, fric_heat_conv, hardw_sparse_thresh, hemi_cube_axi_div, hemi_cube_pixels, hyper_post, id_post, inc_strn_pred_mp, init_frict_stiff, instrain, layers, limit_angle_<2d | 3d>, lmax, max_cont_nod, max_cont_seg, max_el, max_fixed_dof, max_groups, max_it_disp_comp, max_nod, maxsep, mean_strs_subtr, memory, mi_high, mi_initshift mi_low, mi_maxfreq, mi_maxit, mi_nmodes, mi_shiftmodes, mi_shiftpar, mi_tol, naggregates_domain, nbmodes, ndomains, newm_beta_beta, newm_beta_gamma, nmodes, npbmodes, pct_in_core, planck_radiation_2, polytropic_proc_exp, post, reauto_end,

Table A-2 Database Functions (Continued)

Page 253: MARC Tutorials

A-13Appendix AArithmetic and Database Functions

reauto_maxstep, reauto_percent, reauto_reassem, reauto_recycles, reauto_steps, reauto_time, recess_file_freq, rel_disp_threshold, rel_sepstress, restart, restart_time, rp_incomp_pen, rstrt_ninc_bef_last, sepforce, sepstress, shell_drill, si_st_hou_gamma, si_st_hou_gamma1, singularity_thresh, slip_stick_trans, solver_preallocation, sparse_maxit, sparse_tol, specific_weight_<x|y|z>, speed_light_vacuum, spline_files_freq, ss_roll_corn_axis_<dir|point>_<x|y|z>,ss_roll_corn_axis_<dir|point>_<x|y|z>, ss_roll_rot_axis_<dir|point>_<x|y|z>, start, state_variables, stef_boltz, strline_file_freq, temp_offset, thermal_prop_eval_fac, throat_axial_coord, throat_circumf_div, throat_radial_coord, univ_gas_const, usdata_alloc, user_nod_vects, view_fac_implic_ctff_frac, view_fac_implic_thresh, view_fac_use_ctff_frac, view_fac_use_thresh, vsliding

njobs() Number of jobs in the database.

job_class(arg1) Job class for job named arg1. If arg1 is empty, then it uses the current job.

job_name_index(ARG1) job name of ARG1-th job in database.

job_opt(arg1,arg2) Option string for option named arg2 for the job named arg1. If arg1 is empty, then it uses the current job. Option strings use same syntax as in the *job_option command. Example:

job_opt(job1,frictype)

nlcases() Number of loadcases in the database

lcase_opt(arg1,arg2) Option string for option named arg2 for the loadcase named arg1. If arg1 is empty, then it uses the current loadcase. Option strings use same syntax as in the *loadcase_option command. Example:

loadcase_opt(job1,stepping)

lcase_name_index(ARG1) Loadcase name of ARG1-th loadcase in database.

lcase_type(arg1) Loadcase type for loadcase named arg1. If arg1 is empty, then it uses the current loadcase.

lcase_name() Returns the name of the current loadcase.

lcase_par(arg1,arg2) Parameter value named arg2 for loadcase arg1. If arg1 is empty, then it uses the current loadcase.Example:

lcase_par(lcase1,trans_x)Valid parameters:abscurrent, angle<0..5>, anneal_temp, bcond_pen_mp, before_bdc_<x|y|z>, beta, buckle_tol, charge, cooling_time,

Table A-2 Database Functions (Continued)

Page 254: MARC Tutorials

Marc Python ReferenceA-14

cornering_velocity, crank_length, creeptime, current, cutoff_stress, cutter_rapid_speed, cycle_time, d_epot_allowed, d_srec_allowed, d_xsic_allowed, d_xsip_allowed, d_xsiv_allowed, damping_ratio, desired, displacement, dp_allowed, dp_assemble, dp_error, dt_allowed, dt_assemble, dt_error, duplicate_nrep, dyn_contact_pro_fact, eccentricity, efficiency, elec_pot, finish_nds_contact, fluid_force, fluid_incomp_pen, fluid_maxforce, fluid_maxvelo, fluid_minforce, fluid_minvelo, fluid_velo, force, friction_force, gamma, ground_velocity_<x|y|z>, high, inc_assemble, inc_strain, inc_strn_pred_mp, init_frict_stiff, initfraction, initshift, inittime, limit_angle_<2|3>d, low, magn_pot, mass, max_it_disp_comp, max_num_adjustments, max_step_ratio, maxcharge, maxcurrent, maxdisp, maxelec_pot, maxforce, maxfraction, maxinc, maxit, maxjobinc, maxmagn_pot, maxmoment, maxmultiplier, maxnsteps, maxrec, maxrotation, maxsubinc, maxtime, mc_dely<1..4>_<1..12>, mc_xmax<1|2|3_<1..12>, mean_strs_subtr, membr_pre_strs_<incs|val>, min_arcl_ratio, min_step_ratio, mincharge, mincurrent, mindisp, minelec_pot, minforce, minfraction, minmagn_pot, minmoment, minmultiplier, minrec, minrotation, mintstep, moment, motion_cbody_<x|y|z><0..5>, motion_cbody_rot<0..5>, multiblow, nfreq, ngsteps, nmodes, npmodes, nsteps, ntime_cuts, num_post, post_increment, press_dir_<x|y|z>, press_finish, press_max_force, process_in1_<min|max>, process_out1_max_ctff, process_out1_smpl_ctff, process_out1_tgt, pshigh, ref_point_<x|y|z>, relcurrent, rod_length, rotate_<x|y|z>, rotation, rp_ctff_strn_rt, rp_incomp_pen, rp_init_strn_rt, scale_step, sequence, shell_drill, shiftmodes,shiftpar, si_st_hou_gamma, si_st_hou_gamma1, singularity_thresh, spinning_velocity, ss_rolling_tolerance, state_var_id, strain, strain_change, stress_change, symmetry_norm_<x|y|z>, t_dist, t_dist_bodys, t_force, t_nodes, t_stroke, temp_change, temp_finish, thermal_prop_eval_fac, time, time<1..5>, tolerance, torque, tot_energy, translate_<x|y|z>, transport_time, univ_gas_const, vel_def, vel_in, vel_out, weight_d<x|y|z>, weight_r<x|y|z>

lcase_title() Returns the title of the current loadcase.

nmaterials() Number of materials in the database.

material_name_index(ARG1) Material name of ARG1-th material in database.

material_par(arg1,arg2) Parameter value for param named arg2 for material named arg1. If arg1 is empty, then it uses the current material. Parameter values use same syntax as in the *material_value command. Example:

material_par(material3,isotropic:youngs_ modulus)

Table A-2 Database Functions (Continued)

Page 255: MARC Tutorials

A-15Appendix AArithmetic and Database Functions

material_par_table(arg1,arg2) Parameter table name for value named arg2 for material named arg1. If arg1 is empty, then it uses the current material. Parameter values use same syntax as in the *material_param_table command. Example:

material_par_table(material3,isotropic: youngs_modulus)

material_opt(arg1,arg2) Option string for option named arg2 for material named arg1. If arg1 is empty, then it uses the current material. Option strings use same syntax as in the *material_option command. Example:

material_opt(material3,plasticity:method)

material_type(arg1) Material type for material named arg1. If arg1 is empty, then it uses the current material.

material_name() Returns the name of the current material.

mesh_par(arg1) Meshing parameter value named arg1.Example:

mesh_par(qt_max_elements)Valid parameters:

angle_cylindrical_partattemptsaxis_orientationbase_element_size_<x|y|z>boundary_refine_levelboundary_refine_tolerancebox_<1...10>_max_<x|y|z>box_<1...10>_min_<x|y|z>box_<1...10>_activebox_<1...10>_typebox_<1...10>_levelcritical_ring_anglecoarsening_levelcoon_representationcurvature_toleranceedge_detectionedge_angleedge_lengthel_gapedge_toleranceenhance_modehex_elementsgapgrid_typein_rat

Table A-2 Database Functions (Continued)

Page 256: MARC Tutorials

Marc Python ReferenceA-16

mesher_typeself_contactshrink_factortieswrite_extended

pm_par(arg1) Returns parameter string named arg1. Example:

pm_par(arg1)

Example:*define aa MyTextpm_par(aa)

pr_par(arg1) Program data parameter value named arg1. Example:

pr_par(curve_div_maxl)Valid parameters:

curve_div_<maxl|minl|type|ndiv|tol|rest>curve_div_tol_absmesh_cv_div_avglmesh_<min|max|param>_tolintersect_tolrelative_tolsweep_tolerance, overlay_ndiv_<x|y>

nlinks() Number of links of any class in the database

nservos() Number of links of class 'servo" in the database

nsprings() Number of links of class 'spring" in the database

nties() Number of links of class 'tie" in the database

link_class(arg1) Link type name for link arg1. One of: servo, spring, tie. If arg1 is empty, then it uses the current link.

tie_type(arg1) Tie type name for tie arg1. If arg1 is empty, then it uses the current tie.

link_name_index(ARG1) Link name of ARG1-th link in database.

link_name() Returns the name of the current link.

tie_name() Returns the name of the current tie.

servo_name() Returns the name of the current servo.

spring_name() Returns the name of the current spring.

Table A-2 Database Functions (Continued)

Page 257: MARC Tutorials

A-17Appendix AArithmetic and Database Functions

spring_par(arg1) Spring parameter value named arg1 for the current spring.Example:

spring_par(damping)

Valid parameters:conductivitycurrentdampingdynamic_forcefluxheatinit_forcestatic_forcetstiffness

spring_par_table(arg1,arg2) Spring table name for value named arg2 for lin named arg1. If arg1 is empty, then it uses the current spring. Parameter values use same syntax as in the *spring_param_table command. Example:

spring_par_table(link2,stiffness)

spring_opt(arg1,arg2) Option string for option named arg2 for spring named arg1. If arg1 is empty, then it uses the current spring. Option strings use same syntax as in the *spring_option command. Example:

geom_opt(link2,spring_type)

norients() Number of orientations in the database

orient_name() Returns the name of the current orientation.

orient_name_index(ARG1) Orientation name of ARG1-th orientation in database.

orient_type(arg1) Orientation type for orientation arg1. If arg1 is empty, then it uses the current orientation.

ntforms() Number of transforms in the database

tform_name() Returns the name of the current transform.

tform_name_index(ARG1) Transform name of ARG1-th transform in database.

tform_opt(arg1,arg2) Option string for option named arg2 for transform named arg1. If arg1 is empty, then it uses the current transform. Option strings use same syntax as in the *transform_option command. Example:

tform_opt(tform2,method)

table_name() Returns the name of the current table.

Table A-2 Database Functions (Continued)

Page 258: MARC Tutorials

Marc Python ReferenceA-18

wz_par(arg1 SuperForm Wizard parameter value named arg1. Example:

wz_par(length)

Valid parameters:anglediamelmaxelminfricfric_classheatcoefheightlengthmvxmvymvz

numreprotxrotyrotxtempthicktype1type2type3type4width

wz_str(arg1) SuperForm Wizard string value named arg1. Example:

wz_str(tool_name)

Valid parameters:diecat_stringtool_nameworkpiecewp_name

Table A-2 Database Functions (Continued)

Page 259: MARC Tutorials

A-19Appendix AArithmetic and Database Functions

Utility Functions

The following are the Marc Mentat Utility Functions which can be used in the py_get_float, py_get_int or py_get_string functions.

Table A-3 Utility Functions

Function Description

range(arg1,arg2,arg3) Generates a string list of integer items that can be used as a pick list. Definitions:

arg1 - start numberarg2 - end numberarg3 - increment

If arg1 < arg2, then the list is generated in reverse.For example:

range(10,26, 4)will return “10 14 18 22 26”.Example usage:

*add_nodes 3 4 range(10,26,4)

range2(arg1,arg2) Same as range except that arg3 (the increment value) is set as 1.

element_aspect_ratio(arg1) Aspect ratio of element arg1 as computed by the *check_aspect command

element_distortion(arg1) Distortion factor of element arg1 as computed by the *check_distorted command

element_inside_out(arg1) Returns 1 if element arg1 is inside out, 0 otherwise

element_upside_down(arg1) Returns 1 if element arg1 is upside down, 0 otherwise

element_attach_curve(arg1, ARG2) Returns the id of the curve to which the ARG2-th edge of element arg1 is attached, 0 otherwise

element_attach_surface(arg1, ARG2) Returns the id of the surface to which the ARG2-th face of element arg1 is attached, 0 otherwise

node_point_id(arg1) Returns the id of the point to which the node arg1 is attached, 0 otherwise

curve_x(arg1, u) X coordinate of a point on curve arg1 with natural coordinate u

curve_y(arg1, u) Y coordinate of a point on curve arg1 with natural coordinate u

curve_z(arg1, u) Z coordinate of a point on curve arg1 with natural coordinate u

Page 260: MARC Tutorials

Marc Python ReferenceA-20

surface_x(arg1, u, v) X coordinate of a point on surface arg1 with natural coordinates <u>,<v>

surface_x(arg1, u, v) Y coordinate of a point on surface arg1 with natural coordinates <u>,<v>

surface_x(arg1, u, v) Z coordinate of a point on surface arg1 with natural coordinates <u>,<v>

global_x(ux, uy, uz) Transform the user coordinates (<ux>,<uy>,uz>) to the global coordinate system and return the X coordinate.

global_y(ux, uy, uz) Transform the user coordinates (<ux>,<uy>,uz>) to the global coordinate system and return the Y coordinate.

global_z(ux, uy, uz) Transform the user coordinates (<ux>,<uy>,uz>) to the global coordinate system and return the Z coordinate.

user_def(arg1) Returns the user defined data at the specified index arg1 that was set with the user_defined_data command.

user_x(gx, gy, gz) Transform the global coordinates (<gx>,<gy>,gz>) to the current user coordinate system and return the X coordinate.

user_x(gx, gy, gz) Transform the global coordinates (<gx>,<gy>,gz>) to the current user coordinate system and return the Y coordinate.

user_x(gx, gy, gz) Transform the global coordinates (<gx>,<gy>,gz>) to the current user coordinate system and return the Z coordinate.

Table A-3 Utility Functions (Continued)

Page 261: MARC Tutorials

A-21Appendix AArithmetic and Database Functions

Post File Database Functions

The following are the Marc Post File Database Functions which can be used in the py_get_float, py_get_int or py_get_string functions.

Table A-4 Post File Database Functions

Function Description

displace_x(arg1) Global X displacement of node arg1.

displace_y(arg1) Global Y displacement of node arg1.

displace_z(arg1) Global Z displacement of node arg1.

post_data(name) Returns the value for name, which is a string argument. It can be the name of any PyPost attribute except for filename or extrapolate. For example:

post_data(time)post_data(work)

post_increments() If a post file is opened, it returns the number of increments in the post file.

post_node_extra(arg1) Returns 1 if node arg1 is an extra (dummy) node, 0 if a valid node.

scalar_1(arg1) First scalar component of node arg1

scalar_2(arg1) Second scalar component of node arg1

scalar_max_element() Returns the first element in which the scalar quantity is the maximum value.

scalar_min_element() Returns the first element in which the scalar quantity is the minimum value.

scalar_max_node() Returns the first node in which the scalar quantity is the maximum value.

scalar_min_node() Returns the first node in which the scalar quantity is the minimum value.

scalar_pos(x,y,z) Returns the value of the scalar quantity that is being postprocessed at position (x,y,z), if that position is located somewhere in the finite element mesh or 0 if the position is outside the finite element mesh. The value is obtained by interpolating the closest element.

vector_x(arg1) Vector X value of node arg1. This can be a post file value or a value calculated from *geomdist_surfaces or other vector creation commands.

Page 262: MARC Tutorials

Marc Python ReferenceA-22

vector_y(arg1) Vector Y value of node arg1. This can be a post file value or a value calculated from *geomdist_surfaces or other vector creation commands.

vector_z(arg1) Vector Z value of node arg1. This can be a post file value or a value calculated from *geomdist_surfaces or other vector creation commands.

add_disp(arg1, arg2) Increments (adds to) the global X,Y,Z displacement of node arg1 by arg2. If the node number arg1 is -1, then it increments the global displacement X,Y,Zof all the nodes. If the node number arg1 is zero, then it increments the global X,Y,Z displacement of the selected nodes.

add_displ_x(arg1, arg2) Increments the global X displacement of node arg1 by arg2. If the node number arg1 is -1, then it increments the global displacement X of all the nodes. If the node number arg1 is zero, then it increments the global X displacement of the selected nodes.

add_displ_y(arg1, arg2) Increments the global Y displacement of node arg1 by arg2. If the node number arg1 is -1, then it increments the global displacement Y of all the nodes. If the node number arg1 is zero, then it increments the global Y displacement of the selected nodes.

add_displ_z(arg1, arg2) Increments the global Zdisplacement of node arg1 by arg2. If the node number arg1 is -1, then it increments the global displacement Zof all the nodes. If the node number arg1 is zero, then it increments the global Z displacement of the selected nodes.

scale_disp(arg1, arg2) Scales the global X,Y,Z displacement of node arg1 by arg2. If the node number arg1 is -1, then it scales the global displacement X,Y,Zof all the nodes. If the node number arg1 is zero, then it scales the global X,Y,Z displacement of the selected nodes.

scale_displ_x(arg1, arg2) Scales the global X displacement of node arg1 by arg2. If the node number arg1 is -1, then it scales the global displacement X of all the nodes. If the node number arg1 is zero, then it scales the global X displacement of the selected nodes.

Table A-4 Post File Database Functions

Function Description

Page 263: MARC Tutorials

A-23Appendix AArithmetic and Database Functions

scale_displ_y(arg1, arg2) Scales the global Y displacement of node arg1 by arg2. If the node number arg1 is -1, then it scales the global displacement Y of all the nodes. If the node number arg1 is zero, then it scales the global Y displacement of the selected nodes.

scale_displ_z(arg1, arg2) Scales the global Zdisplacement of node arg1 by arg2. If the node number arg1 is -1, then it scales the global displacement Zof all the nodes. If the node number arg1 is zero, then it scales the global Z displacement of the selected nodes.

set_displace_x(arg1, arg2) Sets the global X displacement of node arg1 to arg2.

set_displace_y(arg1, arg2) Sets the global Y displacement of node arg1 to arg2.

set_displace_x(arg1, arg2) Sets the global Z displacement of node arg1 to arg2.

Table A-4 Post File Database Functions

Function Description

Page 264: MARC Tutorials

Marc Python ReferenceA-24

Set Functions

The following are the Marc Mentat Set functions which can be used in a call to the py_get_float or py_get_int functions. The set_name and set_type functions return a string and must be used in a call to the py_get_string function.

Table A-5 Set Functions

Function Description

is_curve_set(arg1) Returns 1 if set arg1 is a curve set, 0 otherwise.

is_edge_set(arg1) Returns 1 if set arg1 is a edge set, 0 otherwise.

is_element_set(arg1) Returns 1 if set arg1 is a element set, 0 otherwise.

is_face_set(arg1) Returns 1 if set arg1 is a face set, 0 otherwise.

is_node_set(arg1) Returns 1 if set arg1 is a node set, 0 otherwise.

is_point_set(arg1) Returns 1 if set arg1 is a point set, 0 otherwise.

is_surface_set(arg1) Returns 1 if set arg1 is a surface set, 0 otherwise.

nsets() Number of sets in database

nset_entries(arg1) Number of set entries for set arg1

set_edge(arg1, ARG2) The id of the ARG2-th edge set entry in edge set arg1.

set_entry(arg1, ARG2) The value of the ARG2-th set entry in set arg1.

set_face(arg1, ARG2) The id of the ARG2-th face set entry in face set arg1.

set_id(ARG1) Id of ARG1-th set in database

set_name(arg1) Name of set arg1. This is a string value, and can only be used in py_get_string.

set_type(arg1) Type of set arg1. This is a string value, and can only be used in py_get_string. Returned values will be one of the following strings: node, element, point, edge, curve, face, surface.