marc 2013.1 python

220
Marc ® Python 2013.1 Tutorial and Reference Manual

Upload: shahnewaz-bhuiyan

Post on 19-Oct-2015

111 views

Category:

Documents


7 download

TRANSCRIPT

  • Marc Python 2013.1

    Tutorial and Reference Manual

  • Worldwide Webwww.mscsoftware.com

    User Documentation: Copyright 2013 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*V2013.1*Z*Z*Z*DC-PYTH

    Corporate Europe, Middle East, AfricaMSC.Software Corporation MSC.Software GmbH4675 MacArthur Court, Suite 900 Am Moosfeld 13Newport Beach, CA 92660 81829 Munich, GermanyTelephone: (714) 540-8900 Telephone: (49) 89 431 98 70Toll Free Number: 1 855 672 7638 Email: [email protected]: [email protected]

    Japan Asia-PacificMSC.Software Japan Ltd. MSC Software (S) Pte. Ltd.Shinjuku First West 8F 100 Beach Road23-7 Nishi Shinjuku #16-05 Shaw Tower1-Chome, Shinjuku-Ku Singapore 189702Tokyo 160-0023, JAPAN Telephone: 65-6272-0082Telephone: (81) (3)-6911-1200 Email: [email protected]: [email protected]

  • C o n t e n t sMarc Python Tutorial and Reference Manual

    Marc Python Tutorial

    Marc Python Tutorial

    PrefaceIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

    Organization of this Manual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

    Contents of the Chapters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

    Documentation Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

    1 IntroductionWelcome. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    The Basics of Using PyMentat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

    The Basics of Using PyPost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

    A Brief Look at Python Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Python Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

    2 PyMentat: A Simple Example

    Chapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    Creating a Simple Python Script for Mentat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    Python Programming Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

    Running the Script. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

  • Marc Python Tutorial and Reference Manual43 PyMentat: Obtaining Data from MentatChapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    Creating a Simple Python Script for Mentat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

    The py_get_int and py_get_float Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

    Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

    4 PyMentat: Building Complex GeometryChapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

    Background Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

    Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

    5 PyMentat: Adding Model PropertiesChapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

    Plate Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

    Node and Element IDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

    Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

    Submitting the Job . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

    6 PyMentat: Processing a Post FileChapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

    Postprocessing Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

    Scalar Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

    Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

    7 PyMentat: Obtaining Model DataChapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52Database Properties Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

  • 5ContentsSet Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

    A Sample Script to Extract Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

    Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

    Set IDs and Set Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

    8 PyPost: Reading a Post FileChapter Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

    PyPost Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

    Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

    9 PyPost: Obtaining Element DataChapter Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

    Processing Element Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

    Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

    10 PyPost: Element Tensor DataChapter Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

    Processing Element Tensor Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

    Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

    11 PyMentat: Using the py_connect MethodChapter Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

    Creating a Simple Python Script for Marc Mentat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

    The py_connect Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

    Handling Socket Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

    Running the Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

  • Marc Python Tutorial and Reference Manual612 PyPost: PlottingChapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

    Charting Script for Mentat. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

    The Gnuplot Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

    The PyOpenGL Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

    13 PyMentat: Menu System Lookup FunctionsChapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

    Menu System Lookup Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

    Integer Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

    Double Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

    String Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105

    Boolean Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

    State Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

    14 MentatDCOM: Connecting to Mentat using a .NET ModuleChapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

    MentatDCOM Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

    Running the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

    MentatDCOM and PyMentat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

    15 MarcPost: Reading a Post File using a .NET ModuleChapter Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

    MarcPost Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

    Running the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

    MarcPost and PyPost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

  • 7ContentsMarc Python Reference

    IntroductionUsing the Python Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

    Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

    1 PyMentat ReferencesPyMentat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

    2 PyPost ReferencesPyPost . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

    A Arithmetic and Database FunctionsIntroduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

    Arithmetic Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

    Database Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

    Utility Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98

    Post File Database Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

    Set Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

  • Marc Python Tutorial Marc Python

    Marc Python Tutorial

  • Preface

    Preface

  • 10 Marc Python TutorialIntroductionThe 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 Mentat.

    Organization of this ManualThis manual is divided into three parts:

    Contents of the Chapters

    Part I introduces the user to the PyMentat module. This module interacts with Mentat to create, modify, and post process models.

    Part II introduces the user to the PyPost module. This module functions independently of Mentat to postprocess a Marc post file (results file).

    Part III introduces the user to more advanced uses of the PyMentat and PyPost modules.

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

    PART I PyMentat ModulePyMentat: A Simple Example describes a basic PyMentat script.PyMentat: Obtaining Data from Mentat expands on the common features of PyMentat and describes how a

    Python script can get data from Mentat.PyMentat: Building Complex Geometry displays how you can build complex geometry that cannot be done with

    procedure files alone.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.

    PyMentat: Processing a Post File shows how to process a Marc post file.PyMentat: Sets shows how to write PyMentat scripts to work with SETS.

  • 11

    Preface

    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 Mentat screen are in Initial Caps. The command issued will appear in

    lower case, such as *add_nodes. Note that the "*" always precedes the command name to instruct 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 . The left mouse button is indicated by . The middle mouse button is indicated by . The right mouse button is indicated by .

    The mouse cursor is indicated by . A filename implies a concatenation of pathname and filename. The pathname may be omitted if the file name

    is in your current directory. You will note the path names 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 "\".

    PART II PyPost ModulePyPost: Reading a Post File introduces the basics of using the PyPost module to obtain post file data

    and find the maximum scalar values.PyPost: Obtaining Element Data shows how to obtain element scalar data from a post file.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 DiscussionsPyMentat: Using the py_connect Method introduces the basics of using the PyMentat module in a client/server

    environment.PyPost: Plotting Post File Data shows some example of using third party modules to plot the results of a

    post file.

    < >

  • 12 Marc Python Tutorial

  • Chapter 1: Introduction

    1 Introduction Welcome 14 The Basics of Using PyMentat 14 The Basics of Using PyPost 16 A Brief Look at Python Programming 17

  • 14 Marc Python TutorialWelcomeWelcome to Python a set of APIs designed to be used by Python scripts to enhance the functionality of Mentat.

    The Basics of Using PyMentatWhen you select a menu item in 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 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 Mentat. Therefore, if you want your Python script to add a node, your script should send the command *add_nodes to Mentat.

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

  • 15CHAPTER 1

    Introduction

    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 Mentat procedure file. To use the script, run it as follows:

    python py_create.py mentat.proc my_script.pyThis script simply reads the procedure file and wraps a py_send command around it. You 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 Mentat is run

    TEST PYTHON SCRIPT

    INITIAL PYTHON SCRIPT

    PYTHON SCRIPTAdd new commands asneeded in the script

  • 16 Marc Python TutorialFigure 1-2 A Python Script to Convert a Marc Mentat Procedure File to a Python Script

    The Basics of Using PyPostThe PyPost module is used by a Python script to process a Marc post (results) file. It operates independently from 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.

    Function Descriptionclose 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.

    #!/usr/bin/pythonimport sysimport stringdef 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])element_tensors Returns the number of element tensors available.

  • 17CHAPTER 1

    Introduction

    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 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.

    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 availableelement_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 filemoveto Move to a specified increment in the post filenode 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 nodenode_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 IDnode_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.

    Function Description

  • 18 Marc Python TutorialA 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.

    Python Data TypesWhen programming in Python, you dont explicitly declare a variables data type. Python determines the data type by how the variable is used. Python supports the following implied data types:

    Basic Data Types

    Extended 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.

    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.

  • 19CHAPTER 1

    Introduction

    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

  • Chapter 2: PyMentat: A Simple Example

    2 PyMentat: A Simple Example Chapter Overview 21 Creating a Simple Python Script for Mentat 21 Python Programming Hints 23 Running the Script 23

  • 21CHAPTER 2

    PyMentat: A Simple Example

    Chapter OverviewIn this section, it will be demonstrated how to create a basic Python script that sends commands to 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 Mentat Python Menu layout

    Creating a Simple Python Script for 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 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 grid3.def make_nodes(s,t, xs, ys):4. y= ys5. z = 0.06. delx = 1.0/s7. dely = 1.0/t8. 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 + delx14. y = y + dely15. return16.

  • 22 Marc Python Tutorial17.# Create the element grid18.def make_elements(n,m):19. for i in range(1,m): # the "y" dir20. n1 = (i-1) * (n) + 121. n2 = n1 + 122. n4 = n1 + (n)23. n3 = n2 + (n)24. for j in range(1,n): # the "x" dir25. str = "*add_elements %d %d %d %d" %

    (n1,n2,n3,n4)26. py_send(str)27. n1 = n1 + 128. n2 = n2 + 129. n3 = n3 + 130. n4 = n4 + 131. return32.33.def main():34. n = 635. m = 836. xs = -1.037. ys = -1.038. make_nodes(n,m,xs,ys)39. make_elements(n,m)40. return

  • 23CHAPTER 2

    PyMentat: 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 unindented.

    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 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.

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

    MAINUTILS

    PYTHON

    Lines 2-15 The make_nodes routine creates 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 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 Pythons % operator. It is used on string objects, and works much like Cs 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 Mentat, at which time it runs the command string just as if it was typed in the Mentat dialogue area.

    Lines 18-31 The make_elements routine performs the element connectivity of the node grid using the Mentat command *add_elements. The loop beginning in line 24 builds 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 sets the size of the grid and the starting position.This brings up the Python Menu screen as shown in Figure 2-1.

  • 24 Marc Python TutorialFigure 2-1 Python Menu Screen

    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 appears.

    Figure 2-2 The Python Browser Window

    Note the button named RUN AS SEPARATE PROCESS. This will run the script in a separate window and communicate to Mentat using a BSD socket connection. This item is 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 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 is created as shown in Figure 2-3.

  • 25CHAPTER 2

    PyMentat: A Simple Example

    Figure 2-3 Python Menu Screen with a Created Mesh

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

  • Chapter 3: PyMentat: Obtaining Data from Mentat

    3 PyMentat: Obtaining Data from Mentat Chapter Overview 27 Creating a Simple Python Script for Mentat 27 The py_get_int and py_get_float Methods 28 Running the Script 29

  • 27CHAPTER 3

    PyMentat: Obtaining Data from Mentat

    Chapter OverviewIn this chapter, it will be demonstrated how to use 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

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

    1.from py_mentat import *2.# Create the node grid3.def make_nodes(s, t, xs, ys):4. y= ys5. z = 0.06. delx = 1.0/s7. dely = 1.0/t8. 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 + delx14. y = y + dely15. return16.17.# Create the element grid18.def make_elements(n,m):19. for i in range(1,m): # the "y" dir20. n1 = (i-1) * (n) + 121. n2 = n1 + 122. n4 = n1 + (n)23. n3 = n2 + (n)

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

  • 28 Marc Python Tutorial25. str = "*add_elements %d %d %d %d"(n1,n2,n3,n4)

    26. py_send(str)27. n1 = n1 + 128. n2 = n2 + 129. n3 = n3 + 130. n4 = n4 + 131. return32.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()

    The py_get_int and py_get_float MethodsThe py_get_int and py_get_float methods provide access to Mentat PARAMETERS and Arithmetic or Database functions. Using Mentat parameters is the method to pass variables from 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

    Lines 2-31 The make_nodes and make_elements routines are the same as in the previous chapter.Lines 33-39 The main routine obtains the values for the size of the grid and the starting point from Mentat using

    parameters. The py_get_int method evaluates a formula and returns an integer (fixed point) result similar to the *calculator command. The py_get_float method evaluates a formula and returns 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 Mentat. The py_connect method is discussed in more detail in a later chapter.

  • 29CHAPTER 3

    PyMentat: Obtaining Data from Mentat

    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 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 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 Mentats command prompt window to create or edit the parameter. For example, to create the parameter x_size you would type

    *define x_size 10As 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.

  • Chapter 4: PyMentat: Building Complex Geometry

    4 PyMentat: Building Complex Geometry Chapter Overview 31 Background Information 31 Running the Script 34

  • 31CHAPTER 4

    PyMentat: Building Complex Geometry

    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 Mentats user-defined menu to present a simple menu for controlling the models 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

    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

    height

    t=.75

    X

    Y

    d d

    dd

    dd

    d

    d

    d

    s

  • 32 Marc Python TutorialThis example is named chap4.py and can be found in the 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. return17.18.def build_plate(xstart,ystart,width, height, diameter, spacing):19. f = diameter+spacing20. 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 125. print "creating hole grid of ",nx, " by ",ny26.27. add_plate(xs,ys,width,height)28. xs = .5 * (width - f * (nx - 1)) + xstart29. ys = .5 * (height - f * (ny - 1)) + ystart30. py_send("*set_curve_type circle_cr")31. py_send("*add_curves")

    32. r = diameter / 2

  • 33CHAPTER 4

    PyMentat: Building Complex Geometry

    33. for i in range(0, ny) :34. y = ys + i * f35. for j in range(0, nx) :36. x = xs + j * f37. py_send("%f %f 0 %f" % (x, y, r))38. return 039.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/246. ystart = -height/247. 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 creates the plate using four 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 calculates the number of holes that can be placed in the plate and creates 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 vertical (height) placement, and the inner loop in lines 35-37 controls the horizontal (width) placement.

    Lines 40-48 The main routine obtains the values for the size of the plate, the diameter of the holes, and the spacing between holes from 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 Mentat.

  • 34 Marc Python TutorialRunning the ScriptStart 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 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 Mentat, and the values for these parameters are obtained by the Python script to control the number of holes in the plate. Select the BUILD button to create the model.

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

  • 35CHAPTER 4

    PyMentat: Building Complex Geometry

    .

    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.

  • Chapter 5: PyMentat: Adding Model Properties

    5 PyMentat: Adding Model Properties Chapter Overview 37 Plate Properties 37 Node and Element IDs 41 Running the Script 42 Submitting the Job 44

  • 37CHAPTER 5

    PyMentat: Adding Model Properties

    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 IDs

    Plate PropertiesAs shown in Chapter 4, 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.

    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 Youngs modulus E = 30e6 and Poissons ratio = 0.3. A compression load with magnitude p = 1000 Lb/in2 will be applied to the top of the plate.

    Figure 5-1 Plate with Varying Number of Holes

    width

    heig

    ht

    t=.75

    X

    Y

    d d

    dd

    dd

    d

    d

    d

    s

    1000 Lb/in2

    fixed

  • 38 Marc Python TutorialThis example is named chap5.py and can be found in the 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 tol80.def check_tol(f1, f2, tol):81. if f1 == f2:82. return 183. if f1 + tol < f2:84. if f1 - tol > f2:85. return 186. return 087.88.def mesh_plate(width, height, diameter, spacing):89. py_send("*set_curve_div_type_fix_avgl")90. l = spacing/2.091. 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. return95.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)" % i108. f = py_get_float(str)109. if check_tol(f, xs, .001):

    110. node_list.append(i)

  • 39CHAPTER 5

    PyMentat: 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 top118. 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. return123.124.def add_matl():125. py_send("*material_type mechanical:isotropic")126. py_send("*material_value isotropic:youngs_modulus 3e7 .3")127. py_send("*add_material_elements all_existing")128. return129.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. return139.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

  • 40 Marc Python Tutorial145.146.def main():147. xs = 0.0148. ys = 0.0149. 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 generates 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 creates 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 searches through the entire node list looking for a node that lies on the left edge of the plate by examining its position in the X direction. If a match is found, we obtain the node ID (which may be different from its 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 IDs, 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).

  • 41CHAPTER 5

    PyMentat: Adding Model Properties

    Node and Element IDsThe Database functions use node and element IDs (similar to labels) as their arguments. In the add_bc routine of our Python script, we issue the renumber_all command. This command renumbers 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

    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.

    Lines 48-52 The add_matl routine applies the material properties to all the elements of the plate.Lines 54-61 The add_job routine creates the necessary job parameters.Lines 63-67 The add_geom_prop routine applies 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.

    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

  • 42 Marc Python TutorialFigure 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 returns with 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.

    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.0

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

    x = 1.0y = 1.0z = 0.0ID = 3

    x = -1.0y = 1.0z = 0.0ID = 4HEIGHT

  • 43CHAPTER 5

    PyMentat: Adding Model Properties

    4.0DIAMETER

    1.0SPACING

    0.5

    Remember to press the carriage return 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.

    Figure 5-4 Resulting Mesh with Boundary Conditions Applied

  • 44 Marc Python TutorialSubmitting 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.

  • Chapter 6: PyMentat: Processing a Post File

    6 PyMentat: Processing a Post File Chapter Overview 46 Postprocessing Basics 46 Scalar Values 50 Running the Script 50

  • 46 Marc Python TutorialChapter OverviewIn this chapter, it will be demonstrated how to use the Postprocessing commands of 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

    Postprocessing BasicsPyMentat may also be used to postprocess 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 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 nodes11. 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 = []

  • 47CHAPTER 6

    PyMentat: Processing a Post File

    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 = 128. while j max_scalars[i]39. max_scalars[i] = f40. max_nodes[i] = n_id41. j = j + 142.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

  • 48 Marc Python Tutorial53. py_send( max_nodes[i] )54. py_send(" #")55. py_send("*post_numerics")56. return 57.# Use database functions to find max/min58. print " "59. print " Label node scalar"60. print " ------------------------------------------"61. for i in range(0,len(label)):62. str = "*post_value " + label[i]63. py_send(str)64. str = "node_id(%d)" % j65. n_id = py_get_int("scalar_max_node()")66. str = "scalar_1(%d)" % n_id67. d = py_get_float(str)68. n_id2 = py_get_int("scalar_min_node()")69. str = "scalar_1(%d)" % n_id70. f = py_get_float(str)71. if d < -f:72. d = -f73. n_id = n_id274. str = " %18s %10i %g" % (label[i],n_id, d) 75. print str76. 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 Mentat that we are working with scalar values, so one of the SCALAR PLOT commands need to be sent.

  • 49CHAPTER 6

    PyMentat: Processing a Post File

    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.

    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 returns a zero if a node is not an extra node, one 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.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.

  • 50 Marc Python TutorialScalar 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 Mentat directory examples/python/tutorial/c06 and run the Python script chap6.py. The output appears as shown in Figure 5-1 for both runs where it searches the node list and using the Database functions.

    Figure 5-1 Resulting Output from chap6.py

    Figure 5-2 Resulting Post Plot 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.814In the next chapter, we will examine the post file using the Python module PyPost.

  • Chapter 7: PyMentat: Sets

    7 PyMentat: Obtaining Model Data Chapter Overview 52 Database Properties Basics 52 Set Basics 53 A Sample Script to Extract Data 53 Running the Script 58 Set IDs and Set Names 62

  • 52 Marc Python TutorialChapter 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

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

    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:

    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.

    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.

  • 53CHAPTER 7

    PyMentat: Obtaining Model Data

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

    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.

    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.

    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.

    node The set contains the node IDs of its entries. element The set contains the element IDs of its entries. point The set contains the point IDs of its entries. curve The set contains the curve IDs of its entries. surface The set contains the surface IDs of its entries. edge The set contains the element IDs and the edge number of its entries. face The set contains the element IDs and the face number of its entries.

  • 54 Marc Python Tutorial8. 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 ",l22. elif(stype == 'edge'):23. l = py_get_int("set_edge(%d,%d)" % (id, j))24. print " edge number ",l25. else:26. print " "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 ", sn35.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)

  • 55CHAPTER 7

    PyMentat: Obtaining Model Data

    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 str44. 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 str48.49. m = py_get_int("napplys()")50. print "\n Boundary Conditions ",m51. 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)55. str = " Boundary Cond %14s Type %19s Values by: % s" % (sn,st,so)56. print str57.58. m = py_get_int("ngeoms()")59. print "\n Geometric Properties ",m60. 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 str66.67. m = py_get_int("niconds()")68. print "\n Initial Conditions ",m69. 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)

  • 56 Marc Python Tutorial74. print str75.76. print ""77. sn = py_get_string("material_name()")78. print " Current material data: ", sn79. st = py_get_string("material_type(%s)" % sn)80. print " Type : ", st81. e = py_get_data( "material:isotropic:youngs_modulus")82. print " Youngs Modulus : ", e83. p = py_get_data("material:isotropic:poissons_ratio")84. print " Poissons Ratio : ", p85. ys = py_get_data("material:plasticity:yield_stress")86. print " Yield Stress : ", ys87.88. print ""89. sn = py_get_string("ctable_name()")90. print " Contact Table ", sn91. sn = "contact_table:the_mesh:refined_mesh:dist_tol"92. dt = py_get_data(sn)93. print " Contact Dist Tol : ", dt94.95. print ""96. sn = py_get_string("geom_name()")97. print " Current geometry data: ", sn98. 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_eid105. for i in range(1,m+1):106. id = py_get_int("element_id(%d)" % i)

    107. print ""

  • 57CHAPTER 7

    PyMentat: Obtaining Model Data

    108. sn = "element_class(%d)" % id109. e_class = py_get_int(sn)110. sn = "element_family(%d)" % id111. 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_ty114. 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)118. print " Contact Body : ", cbn119. print " Geometry Property : ", gmn120. print " Orientation : ", orn121. print " Material Property : ", mtn122.123. return124.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 this 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.

  • 58 Marc Python TutorialRunning 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 appears as shown in Figures 7-1 and 7-2.

    Line 18-26 Depending on the set type, obtain the edge number or the face number if it is an edge or face set.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 Youngs 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.

    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.

  • 59CHAPTER 7

    PyMentat: Obtaining Model Data

    Figure 7-1 Set output from chap7.py

    The database output is shown in 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

    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

  • 60 Marc Python TutorialContact 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

  • 61CHAPTER 7

    PyMentat: Obtaining Model Data

    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

  • 62 Marc Python TutorialSet IDs 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

  • Chapter 8: PyPost: Reading a Post File

    8 PyPost: Reading a Post File Chapter Overview 64 PyPost Basics 64 Running the Script 66

  • 64 Marc Python TutorialChapter 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

    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 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 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: ,fname8. return9.

    10. max_scalars = []

    11. max_nodes = []

  • 65CHAPTER 8

    PyPost: Reading a Post File

    12.13. nns = p.node_scalars()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 scalars20. 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 = -d27. if d > max_scalars[j] :28. max_scalars[j] = d29. max_nodes[j] = p.node_id(k)30. k = k + 131.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 str38. return 39.40.if __name__ == '__main__':41. main("../c06/chap5_job1.t16")

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

    python chap8.pyWhen the script completes, the output is printed as shown in Figure 8-1.

    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.

    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.

  • 67CHAPTER 8

    PyPost: Reading a Post File

    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

  • Chapter 9: PyPost: Obtaining Element Data

    9 PyPost: Obtaining Element Data Chapter Overview 69 Processing Element Data 69 Running the Script 73

  • 69CHAPTER 9

    PyPost: Obtaining Element Data

    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: PyMentat: Processing a Post File.

    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

    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 three extrapolation methods available through the extrapolation method:

    Consider the quadrilateral element shown Figure 9-1.

    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.

  • 70 Marc Python TutorialFigure 9-1 Element Class 8: Eight Noded Isoparametric Quadrilateral Elements

    The quadrilateral element of Figure 9-1 contains eight nodes and four 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 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: ,fname8. return9.

    10. max_scalars = []11. max_nodes = []12. max_incs = []13. nns = p.node_scalars()

    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

  • 71CHAPTER 9

    PyPost: Obtaining Element Data

    14. nes = p.element_scalars()15.16. ninc = p.increments()17. print " Increments = ",ninc,", Nodal scalars = ",nns, ",

    Element scalars ",nes18.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):25. p.moveto(i)26. print "scanning increment ",i," post file number ",p.increment27.28.# find maximum nodal scalars29. j = 030. 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 = -d37. if d > max_scalars[j] :38. max_scalars[j] = d39. max_nodes[j] = p.node_id(k)40. max_incs[j] = p.increment41. k = k + 142. j = j + 143.44.# find maximum element scalars45. j = 046. while j < nes:

  • 72 Marc Python Tutorial47. k = 0 48. numelems = p.elements()49. while k < numelems:50. sca = p.element_scalar(k,j)51. l = len(sca)52. m = 053. while m < l :54. val = sca[m]55. if val < 0.0:56. val = -val57. if val > max_scalars[nns+j] :58. max_scalars[nns+j] = val59. max_nodes[nns+j] = nod[m]60. max_incs[nns+j] = p.increment61. m = m + 162. k = k + 163. j = j + 164.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 str75.76. return 77.78.if __name__ == '__main__':79. main("../c06/chap5_job1.t16")

  • 73CHAPTER 9

    PyPost: Obtaining Element 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 Mentat directory examples/python/tutorial/c09. Run the Python script chap9.py as:

    python chap9.py

    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 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-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 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

    PyS