<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ansys Developer on Medium]]></title>
        <description><![CDATA[Stories by Ansys Developer on Medium]]></description>
        <link>https://medium.com/@ansysdevelopers?source=rss-3f7b5fd24139------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*063uNot0gXtnJ_0byg2OXA.png</url>
            <title>Stories by Ansys Developer on Medium</title>
            <link>https://medium.com/@ansysdevelopers?source=rss-3f7b5fd24139------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 15:45:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ansysdevelopers/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Examples of Python Results for Mechanical — Part 2]]></title>
            <link>https://medium.com/ansys-developer/examples-of-python-results-for-mechanical-part-2-54f73eb8814a?source=rss-3f7b5fd24139------2</link>
            <guid isPermaLink="false">https://medium.com/p/54f73eb8814a</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[mechanical-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[physics]]></category>
            <dc:creator><![CDATA[Ansys Developer]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 13:45:03 GMT</pubDate>
            <atom:updated>2022-12-02T13:45:03.636Z</atom:updated>
            <content:encoded><![CDATA[<h3>Examples of Python Results for Mechanical — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETOXVp5OovWb46Ka4LtKHw.jpeg" /></figure><p>Today’s script tip comes from <a href="https://www.linkedin.com/in/pernellemaronehitz/">Pernelle Marone-Hitz</a>, Lead Applications Engineer, Structural Mechanics — EMEA Field Engineering and Services at Ansys.</p><p>The Python Result object enables you to evaluate output quantities by executing an Iron-python script based on the Data Processing Framework (DPF) post-processing toolbox.</p><p>A previous post showed two examples of Python Results:</p><p><strong>Example 1: Get the maximum over time of the total deformation.</strong></p><p><strong>Example 2: Get the average total deformation on all time steps.</strong></p><p>In this new post, we will create four different Python Results of growing complexity.</p><h4>Example 1: Equivalent Stress</h4><p>The method here is quite simple, as we will only need to use the</p><pre>dpf.operators.result.stress_von_mises() operator</pre><p>We simply have to provide the following inputs:</p><p>The data sources: this is simply the result file.</p><p>The time scoping : here we will use the first result set.</p><p>The complete script is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*nwfUQSweoq-Ips6wY40umA.png" /></figure><p>Connect the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*9_CMUgbWUmMPOhdne6tcGA.png" /></figure><p>and then evaluate it. We can then verify that the plot :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*cAgTnx3TOdAHMN_1iIsApw.png" /></figure><p>matches the one obtained in a standard Mechanical Equivalent Stress Result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*JCUu_ZivaBM_tzBs87mNqg.png" /></figure><h4>Example 2: Equivalent Stress on Named Selection</h4><p>Let’s imagine we have a named selection in the model to identify some specific elements. We’d like to plot the Equivalent Stress again, but only on this Named Selection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*YzxDClASB8HCmj-Afs15RA.png" /></figure><p>This can be done natively in Mechanical by inserting an Equivalent Stress Result and changing the scoping to the Named Selection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*_bpYTTBJ_eqqssWz0Szw6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*CkWzvKSZ6sHKk1lYmq2NEw.png" /></figure><p>However, we’d like to do the same with a Python Result. The only thing we’ll have to modify from our code in Example 1 is limit the mesh scoping to the nodes in this named selection. This is easily done by adding these two lines of code:</p><pre>zone1_mesh_region = model.GetNamedSelection(&#39;NS1&#39;)<br>s_eqv_op.inputs.mesh_scoping.Connect(zone1_mesh_region)</pre><p>Note: all named selections defined in Mechanical will be sent to the solver with their names in capital letters. So if a named selection is called ‘my_ns’, the result file will know it as ‘MY_NS’.</p><p>The complete code is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*XGTbEiuDleT0_8ViDNoOeQ.png" /></figure><p>And this is what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*3a_3k9bHjbYFiefkdE4uAg.png" /></figure><h4>Example 3: Scaled Equivalent Stress on Named Selection</h4><p>Now we’d like to use the result created in Example 2 but also scale the values by a specified amount.</p><p>Again, this can be done natively in Mechanical through inserting a User-Defined Result scoped to the Named Selection and with the following expression: SEQV*Val where Val is the scale value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*aNJbWgcATlShjewj-RgzLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*ox-9dMmA9ekiWybtXaYOpA.png" /></figure><p>To obtain a similar result through a Python Result, we’ll need two additional things compared to Python Result n°2:</p><ul><li>Use the math.scale() operator to scale the results</li><li>Add a section in the detail’s view of the Python Result so that the user can define the scale value.</li></ul><p>Let’s start with the second point. This is done by opening the Property Provider tab and by adding a property as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*YsACmrYlbVIP2sFrAqI_qQ.png" /></figure><p>The properties need to be reloaded:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*uN8Ms4PHLglUMDSvLs3Yaw.png" /></figure><p>and then we get the line where the scale value can be defined:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*B5rk1tkbXyrw7HMCwQqXZg.png" /></figure><p>In the script of the Python Code, the value defined as Scale Value can be retrieved by:</p><pre>this.GetCustomPropertyByPath(&quot;Group 1/Scale Value&quot;)</pre><p>As for the scale operator, we just need to connect it both to the scale value and to the output field of the equivalent stress operator.</p><p>The script is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*YovcVNPviR9QxQjIFNNbHg.png" /></figure><p>The Python Result can then be evaluated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*lmS_7Onv8DkEYOIh-uP75g.png" /></figure><h4>Example 4: Scaled Equivalent Stress on two Named Selections with two different scale values</h4><p>Here we’d like to get on the same plot the following result :</p><ul><li>For nodes belonging to Named Selection n°1, scale the equivalent stress result by value N1</li><li>For nodes belonging to Named Selection n°2, scale the equivalent stress result by value N2</li></ul><p>This is where we get all the added value of the Python Result object as such a result cannot be obtained in Mechanical.</p><p>First, we’ll have to change the Property Provider so that the user can input two different scale values (one for NS1, one for NS2). This is easily done by adapting the code created in Example 3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*gWarPjKOTCPEEauoXZKuSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*8MsnlaiAfD_7YMZ-OnXKEw.png" /></figure><p>The code created for Example 3 is easily adapted so that we get two output fields:</p><ul><li>Scaled stress for NS1</li><li>Scaled stress for NS2.</li></ul><p>The only remaining task is to combine both fields into a unique field so that the result can be plotted on the model. The</p><pre>dpf.operators.utility.merge_fields_containers()</pre><p>operator is the operator we need for that.</p><p>The complete code is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*41BMOm_k769jDPEAyPU3Xw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*cQmg-uA-5BjspNYoXiry1g.png" /></figure><p>The result then can be evaluated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*91JQcSvGIUA4W43vHWJ1Sw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54f73eb8814a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ansys-developer/examples-of-python-results-for-mechanical-part-2-54f73eb8814a">Examples of Python Results for Mechanical — Part 2</a> was originally published in <a href="https://medium.com/ansys-developer">Ansys Developer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plot Design Point (DP) results]]></title>
            <link>https://medium.com/ansys-developer/plot-design-point-dp-results-1d8919b6e26e?source=rss-3f7b5fd24139------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d8919b6e26e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[plot]]></category>
            <dc:creator><![CDATA[Ansys Developer]]></dc:creator>
            <pubDate>Fri, 18 Nov 2022 14:01:49 GMT</pubDate>
            <atom:updated>2022-11-18T14:01:49.773Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETOXVp5OovWb46Ka4LtKHw.jpeg" /></figure><p>Today’s special guest script tip comes from <a href="https://www.linkedin.com/in/christoffer-eriksson-472a21182/">Christoffer Eriksson</a>, Application Developer at EDRMedeso (Elite Channel Partner to ANSYS).</p><p>When running parametric simulations it can often be of value to examine result(s) from each DP to validate the inputs from a graphical point of view, i.e. to get a quick overview. This PyDPF example shows a simple way to plot a deformation result for 4 DPs in the same window.</p><p>The plot below shows the displacement result on the named selection ‘MYBODY’ for DP0. The aim here is to plot the displacement result on ‘MYBODY’ for all 4 DPs (dp0,dp1,dp2,dp3) and line up the results next to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0aZR2nUMun-h_x6KDSyQxQ.png" /></figure><p>Import the DPF-Core module and the Dpf-Plotter.</p><pre>from ansys.dpf import core as dpf <br><br>from ansys.dpf.core.plotter import DpfPlotter <br><br>import os <br><br>plotter = DpfPlotter() </pre><p>Then, extract DP folders from project_files and place in dictionary.</p><pre>projectFolder = &quot;C:\\Temp\\dpresultsDPF_files\\&quot; <br><br>fileList = os.listdir(projectFolder) <br><br>dp_dict = {} <br><br>for fileName in fileList: <br><br>    if &#39;dp&#39; in fileName:  <br><br>        dp_dict[fileName] = projectFolder + fileName + &quot;\\SYS\\MECH\\file.rst&quot; </pre><p>Next, loop over all DPs</p><pre>for i, dp in enumerate(dp_dict.keys()): </pre><p>Extract current DP and read the corresponding result file.</p><pre>rstFilePath = dp_dict[dp] <br><br>model = dpf.Model(rstFilePath) </pre><p>Named Selection scoping to ‘MYBODY’.</p><pre>ns_op=dpf.operators.scoping.on_named_selection(requested_location=&#39;Element&#39;,named_selection_name=&#39;MYBODY&#39;,data_sources=model) </pre><p>Extract Global mesh.</p><pre>myGlobalMesh = model.metadata.meshed_region </pre><p>Create ‘skin mesh’ to reduce computational time (more necessary when plotting results from different time steps since we then need to copy the mesh)</p><pre>mesh_skin = dpf.operators.mesh.skin() <br><br>mesh_skin.inputs.mesh.connect(myGlobalMesh) <br><br>mesh_skin.inputs.mesh_scoping.connect(ns_op) <br><br>result_mesh = mesh_skin.outputs.mesh() </pre><p>Get displacement field for current DP from displacement fields container</p><pre>displacement_operator = model.results.displacement() <br><br>displacement_operator.inputs.data_sources.connect(model) <br><br>displacement_operator.inputs.mesh.connect(result_mesh) <br><br>displacement_set = displacement_operator.outputs.fields_container()[0] </pre><p>Translate the mesh (here in 100*i * (-Y) direction). The mesh from DP0 (the first DP) will be kept in its original place since i = 0. DP1 will be translated -100*1 = -100 mm in negative Y, DP2 will be translated -100*2 = -200 mm in negative Y,…</p><pre>overall_field = dpf.fields_factory.create_3d_vector_field(1, dpf.locations.overall) <br><br>overall_field.append([0.0, -100*i, 0.0], 1) <br><br>coordinates_to_update = result_mesh.nodes.coordinates_field <br><br>add_operator = dpf.operators.math.add(coordinates_to_update, overall_field) <br><br>coordinates_updated = add_operator.outputs.field() <br><br>coordinates_to_update.data = coordinates_updated.data </pre><p>Add current DP field result (displacement_set,result_mesh) to plotter.</p><pre>plotter.add_field( <br><br>        displacement_set,  <br><br>        result_mesh, <br><br>        show_max = False,  <br><br>        show_min = False, <br><br>        label_text_size = 15, <br><br>        label_point_size = 1, <br><br>        ) </pre><p>Place a label on any node (here, the first node in the result_mesh.nodes list) with text = str(dp)</p><pre>node = [result_mesh.nodes[0]] <br><br>label = [dp] <br><br>plotter.add_node_labels( <br><br>    node, <br><br>    result_mesh, <br><br>    label, <br><br>    italic=True, <br><br>    bold=True, <br><br>    font_size=26, <br><br>    text_color=&quot;white&quot;, <br><br>    font_family=&quot;courier&quot;, <br><br>    shadow=True, <br><br>    point_color=&quot;grey&quot;, <br><br>    point_size=1, <br><br>    ) </pre><p>Plot the final solution</p><pre>plotter.show_figure(show_axes=True) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPN6KvfMlT7bjph1abwiLA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d8919b6e26e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ansys-developer/plot-design-point-dp-results-1d8919b6e26e">Plot Design Point (DP) results</a> was originally published in <a href="https://medium.com/ansys-developer">Ansys Developer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Examples of Python Results for Mechanical]]></title>
            <link>https://medium.com/ansys-developer/examples-of-python-results-for-mechanical-a5c0dc20a79d?source=rss-3f7b5fd24139------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5c0dc20a79d</guid>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ansys]]></category>
            <category><![CDATA[mechanical-engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Ansys Developer]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 14:47:41 GMT</pubDate>
            <atom:updated>2022-11-11T14:47:41.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETOXVp5OovWb46Ka4LtKHw.jpeg" /></figure><p>Today’s script tip comes from <a href="https://www.linkedin.com/in/pernellemaronehitz/">Pernelle Marone-Hitz</a>, Lead Applications Engineer at Ansys.</p><p>The Python Result object enables you to evaluate output quantities by executing an Iron-python script based on the Data Processing Framework (DPF) post-processing toolbox.</p><p>In this post, we will cover two examples of Python Results:</p><ul><li>Example 1: Get the maximum over time of the total deformation.</li><li>Example 2: Get the average total deformation on all time steps.</li></ul><h4>Example 1: Maximum over time of the total deformation.</h4><p>Please note that this result is already available natively in Mechanical: Insert a Total Deformation result and change the “Definition/By” section to “Maximum Over Time”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*sYRJrTswtCQ97n4Te59hFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*q-gFD9ppQOleX2gwvSiMHA.png" /></figure><p>In this example, we will “recode” this functionality and show that DPF can be used to create the same result. First, insert a Python Result object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*Fu_b381l6E9X0rVP5aw2Zw.png" /></figure><p>The chain of operators will be relatively simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZFYbCdNyJv0LlRT2_btIog.png" /></figure><p>The Data Source will be the result file: dataSource = dpf.DataSources(analysis.ResultFileName)</p><p>It is important to define the Time Scoping appropriately: by default, DPF will operate on the last time step only, and here we want to make sure all the time steps are considered so that for each node we get the maximum value on all the time steps. This can be achieved by checking the number of results sets and selecting them all.</p><p>For some operators such as the max_over_time_by_entity that is used here, the result will be a field container without any label. That would cause the Python Result to raise an error. To overcome this, a ‘time’ label should be added to the fields container.</p><p>Finally, to plot the results back on the model, the forward_field() method should be used to send the field to an operator to be able to plot it.</p><p>The complete script is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*4ANVmDx-WLRrNnr9RKfbpA.png" /></figure><p>And we can check that the plot obtained through this method is the same as the one obtained in the standard Mechanical result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*EzUscXkA_Oe78bpCUV9kdA.png" /></figure><h4>Example 2: Average total deformation on all time steps.</h4><p>Again, the chain of operators will be quite simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8tpr2D2OWT0UpcZvGIh1Q.png" /></figure><p>The complete script is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*72ycYWFaxUl7p2QPzvdowA.png" /></figure><p>And the values are plotted back on the model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*jMBAp7vC0MpMu00Q5VeUqw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5c0dc20a79d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ansys-developer/examples-of-python-results-for-mechanical-a5c0dc20a79d">Examples of Python Results for Mechanical</a> was originally published in <a href="https://medium.com/ansys-developer">Ansys Developer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Script Tip: argparse (How to make your own CLI)]]></title>
            <link>https://medium.com/ansys-developer/script-tip-argparse-how-to-make-your-own-cli-178034126376?source=rss-3f7b5fd24139------2</link>
            <guid isPermaLink="false">https://medium.com/p/178034126376</guid>
            <category><![CDATA[argparse]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Ansys Developer]]></dc:creator>
            <pubDate>Fri, 04 Nov 2022 13:01:48 GMT</pubDate>
            <atom:updated>2022-11-04T13:01:48.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETOXVp5OovWb46Ka4LtKHw.jpeg" /></figure><p>Today’s script tip comes from <a href="https://www.linkedin.com/in/james-derrick-435b3589/">James Derrick</a>, Developer Advocate at Ansys.</p><p>A huge part of any Python developer’s arsenal is the ability to link your Python program with “other stuff”. “other stuff” meaning everything from other programs to other humans to other developers. As your careers develop you learn how to write more something-Is. The most common ones will be:</p><ul><li>APIs — “Application Programming Interface”s (let programs talk to each other)</li><li>GUIs — “Graphical User Interface”s (let humans talk to the program)</li><li>CLIs — “Command Line Interface”s (let humans talk to the program but its easy to develop)</li></ul><p>Of the three, CLIs are by far the easiest to build conceptually and programmatically. Crafting good GUIs and APIs is very hard and is a fine art that requires many years of training. As you’ll find going through life, <a href="https://youtu.be/S-3wEC6Fj_8?t=3404">most people aren’t very good at it</a>.</p><p>CLIs on the other hand are <em>fine</em>; it’s hard to deliberately mess one up, so long as it’s not too complicated. And that’s where this script tip comes in! In this article I’ll explain how the builtin Python CLI-builder argparse works. The perfect tool for building a quick and easy interface with your Python script.</p><h3>Introducing argparse</h3><p>argparse is the builtin library to create CLIs with in Python. It is not the best, nor the simplest, but it is <em>always</em> there, and as such it is useful to know about this one because you may occasionally find yourself unable to install external packages for some reason and be forced to use it (this happens a lot commercially in my experience; usually for licensing reasons).</p><p>If you are open to 3rd parties then I suggest checking out the following options:</p><ul><li><a href="https://click.palletsprojects.com/en/latest/why/">click</a></li><li><a href="http://docopt.org/">docopt</a></li><li><a href="https://www.pyinvoke.org/">invoke</a></li></ul><p>If this is a bit overwhelming Real Python has written a very nice article comparing all three AND argparse, which you should check out <a href="https://realpython.com/comparing-python-command-line-parsing-libraries-argparse-docopt-click/">here</a>.</p><p>This article, however, will focus on argparse and is aimed at people coming across it for the first time.</p><h3>What does a CLI “look like”?</h3><p>A CLI has the following components: “the command” (python in Python, or some other alias like py2 or py3 are common), &quot;the option(s)&quot; (flags that indicate what you want to do. The most common being the --help flag.), and &quot;the argument(s)&quot; (information you want to insert into the script, like the path to a file, for example). In vanilla Python there is one &quot;command&quot;, the call to python and at least one argument every time, the script name/path.</p><pre>python my_script.py</pre><p>The command here is python and the argument is my_script.py.</p><h3>sys.argv</h3><p>OK but that’s all on the command line. How does Python access this information inside a script? Well, in Python, the builtin sys package has the property argv, which is a list of all the input arguments as strings. The delimiter separating the arguments is the space character, although substrings within the CLI command are preserved (strings contained within a pair of double quotes &quot;...&quot;).</p><p>If you have a script (script.py) containing</p><pre>import sys</pre><pre>print(sys.argv)</pre><p>and run it, you get the following output.</p><pre>&gt;&gt;&gt; python script.py<br>[&#39;.\\script.py&#39;]</pre><blockquote><em>Note: the double backslash is because I’m on Windows, which uses backslashes in paths, and backslash is also the escape character in Python strings, so it has to be escaped to be used in a path. As such, path visualisations in Python on Windows will be positively FULL of </em><em>\\. Try to use </em><a href="https://realpython.com/python-pathlib/"><em>pathlib</em></a><em> where you can to get around this somewhat!</em></blockquote><p>If we add more arguments to our command line we can see just how argv works.</p><pre>&gt;&gt;&gt; python script.py new set-of &quot;test args&quot;<br>[&#39;script.py&#39;, &#39;new&#39;, &#39;set-of&#39;, &#39;test args&#39;]</pre><blockquote><em>Why is the backslash gone? Honestly, I’m not sure and I couldn’t find any info after a cursory google. If you have any idea why, please leave a comment! Although the reason is not important for this article because for the CLI the only argument we don’t care about is the first one because it is always the same!</em></blockquote><p>So, argparse is essentially a package that parses sys.argv and makes sense of it, turning it into options and arguments for the CLI.</p><blockquote><em>Note: All input on the command line are </em>command line arguments<em> but in the CLI, only some of those are </em>CLI arguments<em>. Some are what I’m calling </em>options<em> or </em>flags<em>.</em></blockquote><h3>Nitty-gritty of CLI</h3><p>Generally CLIs make use of option-argument pairs. You provide some sort of option or flag and then the input corresponding to it, like --density 3.4 or --path .\\Program\\Python\\, and this makes sense. For example</p><pre>&gt;&gt;&gt; python script2.py --factorial 9<br>362880</pre><p>the option is --factorial and its corresponding argument is 9. Providing additional args throws an error, unless we were to modify the programn to handle it.</p><p>Scripts are not just limited to single pair either. We can write one to have multiple pairs as well:</p><pre>&gt;&gt;&gt; python .\script3.py --base 2 --exponent 3  <br>8.0</pre><p>In fact, you can have multiple pairs that are <em>optional</em>.</p><pre>&gt;&gt;&gt; python .\script4.py --num1 3. --num2 4.<br>1.0<br>1.3333333333333333<br>&gt;&gt;&gt; python .\script4.py --num1 5.          <br>1.6666666666666667</pre><blockquote><em>Note: the </em><em>-- is a convention. Generally </em><em>-- is used before full words and a single </em><em>- is used for the same argument but with a single character alias. This is most easily demonstrated with the example that </em><em>--help and </em><em>-h are the same.</em></blockquote><blockquote><em>&gt;&gt;&gt; python .\script4.py -h usage: script4.py [-h] [--num1 NUM1] [--num2 NUM2] Divide by 3 options: -h, --help show this help message and exit --num1 NUM1 Option 1 --num2 NUM2 Option 2 &gt;&gt;&gt; python .\script4.py --help usage: script4.py [-h] [--num1 NUM1] [--num2 NUM2] Divide by 3 options: -h, --help show this help message and exit --num1 NUM1 Option 1 --num2 NUM2 Option 2</em></blockquote><h3>Constructing a CLI with argparse</h3><p>OK so we’re ready to tackle the main topic of this tip now; apologies if you already knew all of the above. I like to cover all my bases in an article because one’s work may well be someone’s first exposure to any number of concepts, so it always pays to be thorough.</p><p>Anyway! How do we use argparse? It’s pretty simple, but requires a bit of mental gymnastics if you aren’t used to thinking about programming this way.</p><p>Your program executes in the following way:</p><ol><li>You smash that Enter button on the command line</li><li>The arguments you added are all stored in sys.argv</li><li>The program enters your script and starts executing things</li></ol><p>You need to build the parser into the program so your program has actually already parsed the args, but the parser hasn’t been executed? Argh!</p><p>It’s OK. The program actually stores your args in sys.argv as I said before, and then your parser parses <em>that</em>.</p><p>So your program’s execution order should be structured like so</p><ol><li>Perform your imports (imports should always be at the top of the file in Python)</li><li>Construct the parser</li><li>Parse the args</li><li>Perform logic based on the parsed args</li><li>Other stuff</li></ol><h3>How do I construct the parser?</h3><p>First of all you create an instance of argparse.ArgumentParser.</p><pre>parser = ArgumentParser(description=&#39;Demo program&#39;)</pre><p>The description is purely for documentation purposes and you can leave it out if you want, though why would you?! Writing docs is fun!</p><p>Next we add arguments to our parser. We tell the parser what it should expect to see on the command line and how to treat those inputs. For this tutorial though we’re just keeping it as simple as possible and not worrying about the many things you can do.</p><pre>parser.add_argument(&#39;--density&#39;, help=&#39;density provided as a float&#39;)</pre><p>this adds the “option” --density which is a point of entry for the &quot;argument&quot; associated with it.</p><p>Now we parse the args, which stores all the supplied arguments in the returned namespace object that I always call args.</p><pre>args = parser.parse_args()</pre><blockquote><em>Note: If no arguments are provided to </em><em>parse_args then it will use </em><em>sys.argv, but if you </em>do<em> provide a string it will actually parse that instead! It&#39;s a neat little trick you can make use of when building argparse in non-standard locations like jupyter notebooks.</em></blockquote><p>Now we have args we can get at all the inputs! For now let&#39;s just print the density.</p><pre>print(args.density)</pre><blockquote><em>Note: </em><em>argparse does some magic behind the scenes and strips away the </em><em>--, so we don&#39;t have to worry about that.</em></blockquote><p>OK so what happens if we run our program?</p><pre>&gt;&gt;&gt; python script5.py --density 4.0<br>4.0</pre><p>And what if we run it without arguments?</p><pre>&gt;&gt;&gt; python script5.py<br>None</pre><p>This happens because if we don’t provide density the namespace with it is still created. In fact, we can use argparse to specify the default value should nothing be supplied. Which we would do by changing the add_argument line to</p><pre>parser.add_argument(&#39;--density&#39;, default=0., help=&#39;density provided as a float&#39;)</pre><p>which specifies the default as 0.0 if nothing else is supplied.</p><p>And that’s pretty much it!</p><h3>Some tips ’n’ tricks about argparse</h3><ul><li>You do not need to add an argument for --help. This comes with argparse, and will always be present when creating a CLI with it.</li><li>When you add an argument in argparse you can specify the type that argument should be converted to, like float or int. If no type is provided the output type will always be a string unless it was not provided, which case the result will be None of the NoneType.</li><li>By specifying the action of an argument as &quot;store_true&quot; you can create an option that is parsed as True if it is present and False if it is not. If the action is set to &quot;store_false&quot; instead the reverse is achieved!</li></ul><pre>parser.add_argument(&#39;--flag&#39;, action=&#39;store_true&#39;, help=&#39;if provided, set to True, otherwise False&#39;)</pre><pre>&gt;&gt;&gt; python script6.py --flag --reverse-flag<br>True<br>False<br>&gt;&gt;&gt; python script6.py<br>False<br>True</pre><ul><li>You can add an easy versioning return with the &quot;version&quot; action, and the version to be printed can be specified with the version kwarg. Like using the builtin --help option, the program will print the version and auto-quit afterward.</li></ul><pre>parser.add_argument(&#39;--version&#39;, action=&#39;version&#39;, version=&#39;script6 v1.0&#39;)</pre><pre>&gt;&gt;&gt; python script6.py --version<br>script6 v1.0</pre><ul><li>When developing programs with argparse it is best practice to group your code into functions, often in a separate file. In script7.py I&#39;ve grouped things as they commonly are.</li></ul><pre>from argparse import ArgumentParser<br></pre><pre>def create_parser():<br>    parser = ArgumentParser(description=&#39;Demo program&#39;)<br>    parser.add_argument(&#39;--flag&#39;,<br>                        action=&#39;store_true&#39;,<br>                        help=&#39;when provided sets to True, otherwise False&#39;)<br>    parser.add_argument(&#39;--reverse-flag&#39;,<br>                        action=&#39;store_false&#39;,<br>                        help=&#39;when provided sets to False, otherwise True&#39;)</pre><pre>    parser.add_argument(&#39;--version&#39;, action=&#39;version&#39;, version=&#39;script6 v1.0&#39;)<br>    return parser<br></pre><pre>def cli():<br>    p = create_parser()<br>    args = p.parse_args()<br>    return args.flag, args.reverse_flag<br></pre><pre>def main():<br>    flag, reverse_flag = cli()<br>    print(flag)<br>    print(reverse_flag)<br></pre><pre>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>This sort of structure is ideal for developing argparse CLIs.</p><h3>Closing Comments</h3><p>This article should serve as a pretty good primer for getting started with argparse. I have also included all the scripts used here in my GitHub script tip repo, if you&#39;re interested in playing around with them. That can be found <a href="https://github.com.mcas.ms/jgd10/ScriptTipFriday?McasCtx=4&amp;McasTsid=15600">here</a>. Finally, I hope you enjoy making your own CLIs! The skill is ever a &quot;tool for the box&quot;.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=178034126376" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ansys-developer/script-tip-argparse-how-to-make-your-own-cli-178034126376">Script Tip: argparse (How to make your own CLI)</a> was originally published in <a href="https://medium.com/ansys-developer">Ansys Developer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Determining an Optimal Location for Components on a PCB]]></title>
            <link>https://medium.com/ansys-developer/determining-an-optimal-location-for-components-on-a-pcb-f2ea41466359?source=rss-3f7b5fd24139------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2ea41466359</guid>
            <category><![CDATA[script]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[ansys]]></category>
            <category><![CDATA[sherlock]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ansys Developer]]></dc:creator>
            <pubDate>Fri, 28 Oct 2022 13:01:53 GMT</pubDate>
            <atom:updated>2022-10-28T13:01:53.902Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETOXVp5OovWb46Ka4LtKHw.jpeg" /></figure><p>For this week’s Script Tip Friday, <a href="https://www.linkedin.com/feed/hashtag/?keywords=ansys">Ansys</a> Lead R&amp;D Engineer <a href="https://www.linkedin.com/in/ACoAAAEwDssBihbAbmicCnV-X-25OsZ_qpCdF24">Miu Lin Edson</a> shows us how to use APIs available in Ansys Sherlock to easily set a component’s locations properties, mount point configurations and run an analysis to determine component reliability.</p><p>What is the optimal location to place a component on a Printed Circuit Board (PCB), in terms of its reliability under shock, vibration, and other environmental conditions? And how do the mount point configurations affect the relative performance of the PCB?</p><p>For many Ansys Sherlock users, this involves repeating the steps of editing the part location using the Part Editor, updating the mount point configuration in the layer viewer, running an analysis, and viewing the results.</p><p>However, this can become cumbersome and time consuming if a user wants to test out many different locations and mount point configurations.</p><p>Do you know you can automate this by using Sherlock APIs? Sherlock APIs are written using Google’s gRPC framework and there are Sherlock APIs that would let you easily set a component’s location properties, the mount point configurations, and run an analysis.</p><p>In this article, we will show you how you can set a component’s location properties and edit the mount point configurations for a PCB. In a future article, we will show you how to automate running of an analysis.</p><p>For information on how to setup your computer to run Sherlock’s APIs, please refer to the Sherlock User Guide.</p><p>At the start of your Python script, import the generated gRPC client and server interfaces.</p><pre>import SherlockPartsService_pb2<br>import SherlockPartsService_pb2_grpc<br>import SherlockLayerService_pb2<br>import SherlockLayerService_pb2_grpc</pre><p>Create a gRPC channel to communicate with the server.</p><pre>channel = grpc.insecure_channel(&#39;localhost:9090&#39;)</pre><p>The below code sets the location properties for a component using the setPartLocation() API. As you can see, it uses variables for the x and y locations for the API, so they can be dynamically updated during the script runtime by either looping through a list of values or provided as inputs when the script is executed.</p><pre># Initialize the variables for the input parameter<br>project_name = “Tutorial Project”<br>cca = “Main Board”<br>my_component = “U6”<br>x = -0.25<br>y = 0.45<br></pre><pre># Create a stub for the SherlockPartsService<br>stub = SherlockPartsService_pb2_grpc.SherlockPartsServiceStub(channel)<br></pre><pre># Sets up the input parameters<br>message = SherlockPartsService_pb2.SetPartLocationRequest()<br>message.project = project_name<br>message.ccaName = cca<br>message.refDes = my_component<br>message.x = str(x)<br>message.y = str(y)<br>message.rotation = &quot;0&quot;<br>message.locationUnits = &quot;IN&quot;<br></pre><pre># Executes the API<br>response = stub.setPartLocation(message)</pre><p>In the below code, it first deletes all the mount points on the PCB using the deleteAllMountPoints() API, then it adds a list of mount points using the updateMountPoints() API by importing a CSV file that contains all the mount points and their configurations.</p><pre># Create a stub for the SherlockLayerService<br>stub = SherlockLayerService_pb2_grpc.SherlockLayerServiceStub(channel)<br></pre><pre># Deletes all mount points from the CCA<br>message = SherlockLayerService_pb2.DeleteAllMountPointsRequest()<br>message.project = project_name<br>message.ccaName = cca<br>response = stub.deleteAllMountPoints(message)<br></pre><pre># Add Mount Points from file (filename can be dynamically generated to use different configurations)<br>num_mount_points = 6<br>mount_point_directory = &quot;C:\\Temp\\”<br>filename = “mount_points_” + str(int(num_mount_points)) + “.csv”<br></pre><pre>message = SherlockLayerService_pb2.UpdateMountPointsRequest()<br>message.project = project_name<br>message.ccaName = cca<br>message.filePath = mount_point_directory + filename<br></pre><pre># Please note that starting in 23.1 this API will be renamed to updateMountPointsByFile()<br>response = stub.updateMountPoints(message)</pre><p>The Sherlock Layer Viewer below shows the board layout after executing the above snippets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*uMX2MJpWv32MHQpvAP3ExA.png" /></figure><p>You can see the table of reliability results in Sherlock:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*GcrWH7tPuYA4jhE2x4-FKA.png" /></figure><p>The above script example can be easily integrated with Ansys optiSLang to perform a sensitivity study. If you are interested in learning more about this, please register and attend Ansys Level Up 3.0 on October 25, 2022. The presentation “Enhancing Electronics Reliability Studies with APIs and Ansys optiSLang” will showcase how to couple optiSLang with Sherlock APIs to optimize designs in less time, perform more robust reliability studies and reduce overall turnaround time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*FPov8shLakGz1cEqHdbIBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*yxayFiWYCbsh-DzY8zuG4Q.png" /></figure><p>To learn more <a href="https://www.ansys.com/events/level-up">register for Level Up 3.0</a> and attend the “Enhancing Reliability Studies with APIs and Ansys OptiSLang” under the Electronics Reliability Track.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2ea41466359" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ansys-developer/determining-an-optimal-location-for-components-on-a-pcb-f2ea41466359">Determining an Optimal Location for Components on a PCB</a> was originally published in <a href="https://medium.com/ansys-developer">Ansys Developer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do I Plot Stress Gradient on a Path Normal to the Selected Face at the Selected Node Using…]]></title>
            <link>https://medium.com/ansys-developer/how-do-i-plot-stress-gradient-on-a-path-normal-to-the-selected-face-at-the-selected-node-using-ad19e6995785?source=rss-3f7b5fd24139------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad19e6995785</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pydpf]]></category>
            <category><![CDATA[plot]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[mechanical-engineering]]></category>
            <dc:creator><![CDATA[Ansys Developer]]></dc:creator>
            <pubDate>Fri, 07 Oct 2022 13:01:56 GMT</pubDate>
            <atom:updated>2022-10-07T13:01:56.248Z</atom:updated>
            <content:encoded><![CDATA[<h3>How do I Plot Stress Gradient on a Path Normal to the Selected Face at the Selected Node Using PyDPF?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETOXVp5OovWb46Ka4LtKHw.jpeg" /></figure><p>Today’s Script Tip comes from <a href="https://www.linkedin.com/in/ayush-kumar-5aa2a144/">Ayush Kumar</a>, Senior Applications Engineer at Ansys.</p><p>Sometimes for a better engineering decision, it is important to analyze results along the normal to a face. This PyDPF example shows you how to plot a stress gradient normal at a selected node on a face.</p><pre># Import necessary modules: <br>############################################################################### <br># First, import the DPF-Core module as ``dpf`` and import the <br># included examples file and ``DpfPlotter``<br> <br>import matplotlib.pyplot as plt <br>from ansys.dpf import core as dpf <br>from ansys.dpf.core import operators as ops <br>from ansys.dpf.core.plotter import DpfPlotter <br>from ansys.dpf.core import examples <br>############################################################################### </pre><pre># Next, link your result file(.rst) and print out the ``model`` object. The <br># :class:`Model &lt;ansys.dpf.core.model.Model&gt;` class helps to organize access <br># methods for the result by keeping track of the operators and data sources <br># used by the result file. </pre><pre>path = r”\Path\to\file.rst” <br>model = dpf.Model(path) <br>print(model) <br> <br> <br> <br>############################################################################### <br># Define the `node_id` normal to which a stress gradient should be plotted. </pre><pre>node_id = 1928 <br>###############################################################################</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad19e6995785" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ansys-developer/how-do-i-plot-stress-gradient-on-a-path-normal-to-the-selected-face-at-the-selected-node-using-ad19e6995785">How do I Plot Stress Gradient on a Path Normal to the Selected Face at the Selected Node Using…</a> was originally published in <a href="https://medium.com/ansys-developer">Ansys Developer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do I Convert Nodal Coordinates Field to Local Coordinate System Using PyDPF?]]></title>
            <link>https://medium.com/ansys-developer/how-do-i-convert-nodal-coordinates-field-to-local-coordinate-system-using-pydpf-f86e377b0508?source=rss-3f7b5fd24139------2</link>
            <guid isPermaLink="false">https://medium.com/p/f86e377b0508</guid>
            <category><![CDATA[global-coordinate-system]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[local-coordinate-system]]></category>
            <category><![CDATA[mechanical-engineering]]></category>
            <category><![CDATA[pydpf]]></category>
            <dc:creator><![CDATA[Ansys Developer]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 13:02:26 GMT</pubDate>
            <atom:updated>2022-09-30T13:02:26.344Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETOXVp5OovWb46Ka4LtKHw.jpeg" /></figure><p>Today’s Script Tip comes from <a href="https://www.linkedin.com/in/ayush-kumar-5aa2a144/">Ayush Kumar</a>, Senior Applications Engineer at Ansys.</p><p>GCS: Global Coordinate System<br>LCS: Local Coordinate System</p><p>In 3D simulations, local coordinate systems play a crucial role. Therefore, conversion of nodal coordinates from GCS to LCS is often needed.</p><p>The operator</p><pre>:class: `rotate &lt;ansys.dpf.core.operators.geo.rotate.rotate&gt;`</pre><p>rotates the input field in GCS as per the input rotation matrix. If the LCS is at the same origin as the GCS, only one operation using the `rotate` operator gives the desired output. But for an LCS with a transformed origin, after rotation, a transformation along the rotated position vector of the LCS’s origin is also needed to get the correct coordinates in LCS. Below is a PyDPF example to achieve that.</p><pre># Import necessary modules: <br>from ansys.dpf import core as dpf <br>from ansys.dpf.core import examples <br> <br>############################################################################### <br># Create a model object to establish a connection with an example result file: <br>model = dpf.Model(r&quot;\Path\to\my\file.rst&quot;) <br> <br>############################################################################### <br># Get the property `coordinates_field` from :class: nodes ansys.dpf.core.nodes` <br>ncoord_f = model.metadata.meshed_region.nodes.coordinates_field <br> <br>############################################################################### <br># Get the rotation matrix of the LCS ID 12 <br># The first 9 values in the `cs` output is the rotation matrix <br>cs = model.operator(r&quot;mapdl::rst::CS&quot;) <br>cs.inputs.cs_id.connect(12) <br>cs_rot_mat = cs.outputs.field.get_data().data.T[0:9] <br> <br>############################################################################### <br># Create a 3x3 rotation matrix field - `rot_mat_f` <br>rot_mat_f = dpf.fields_factory.create_scalar_field(1) <br>rot_mat_f.data = cs_rot_mat <br> <br>############################################################################### <br># Create a 3D vector field for the position vector of the LCS&#39;s origin and <br># rotate the origin as per the rotation matrix of the LCS. <br># The last 3 entries of `cs` output is the LCS&#39;s origin in GCS. <br>pos_vec = dpf.fields_factory.create_3d_vector_field(1) <br>pos_vec.data = cs.outputs.field.get_data().data.T[-3:] <br>pos_vec_rot = dpf.operators.geo.rotate(field=pos_vec, <br> field_rotation_matrix=rot_mat_f) <br> <br>############################################################################### <br># Get rotated nodal coordinates field. <br>ncoord_rot_f = dpf.operators.geo.rotate(field=ncoord_f, <br> field_rotation_matrix=rot_mat_f) <br> <br>############################################################################### <br># Transform rotated nodal coordinates field along rotated position vector - <br># `pos_vec_rot`, <br>pos_vec_rot_neg_f = dpf.operators.math.scale(field=pos_vec_rot, <br> ponderation=-1.0) <br>pos_vec_rot_neg = pos_vec_rot_neg_f.outputs.field.get_data().data_as_list <br>nccord_translated = dpf.operators.math.add_constant(field=ncoord_rot_f, <br> ponderation=pos_vec_rot_neg) <br> <br> <br>############################################################################### <br># Get the nodal coordinates field `ncoord_lcs_f` in LCS <br>ncoord_lcs_f = nccord_translated.outputs.field.get_data() <br> <br>############################################################################### <br># Coordinates of NID 1 in GCS <br>print(ncoord_f.get_entity_data_by_id(1)) <br> <br>############################################################################### <br># Coordinates of NID 1 in LCS <br>print(ncoord_lcs_f.get_entity_data_by_id(1))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f86e377b0508" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ansys-developer/how-do-i-convert-nodal-coordinates-field-to-local-coordinate-system-using-pydpf-f86e377b0508">How Do I Convert Nodal Coordinates Field to Local Coordinate System Using PyDPF?</a> was originally published in <a href="https://medium.com/ansys-developer">Ansys Developer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating images and plots using a Python Code object (Cpython)]]></title>
            <link>https://medium.com/ansys-developer/integrating-images-and-plots-using-a-python-code-object-cpython-6defcdaf8e51?source=rss-3f7b5fd24139------2</link>
            <guid isPermaLink="false">https://medium.com/p/6defcdaf8e51</guid>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[mechanical-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ansys Developer]]></dc:creator>
            <pubDate>Fri, 23 Sep 2022 13:01:39 GMT</pubDate>
            <atom:updated>2022-09-23T13:01:39.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETOXVp5OovWb46Ka4LtKHw.jpeg" /></figure><p>Today’s script tip comes from Mark Capellaro, <a href="https://www.linkedin.com/in/markcapellaro/">Application Engineer </a>at Ansys.</p><p>Python Code objects in Ansys 2022R2 allow the user to change the engine to Cypthon. This opens the door to using more modern python libraries and modules. One command python library that is now available is matplotlib, the default plotter for python. So it is already installed with your Ansys 2022R2. This functionality allows you to plot, plot to file and bring images into the Mechanical tree that might not be included natively in Mechanical.</p><p>Below is a trivial example of how to use matplotlib and a Python Code object in your Ansys Mechanical analysis. Naturally you would want to use others scripts like dpf to grab the data you want to plot.</p><ul><li>In any 2022R2 Ansys Mechanical Solution right click and Insert — Python Code</li><li>Set the Target Callback to After Solve</li><li>Under Advanced, set the Engine Type to Cpython.</li><li>Copy and paste the script below into the Python Code window (overwrite the default text):</li></ul><pre>def after_post(this, solution):# Do not edit this line</pre><pre>import matplotlib.pyplot as plt</pre><pre>import os</pre><pre>plt.plot([1,2,3,4,5],[5,10,15,20,25],color=’red’)</pre><pre>plt.ylabel(‘hello [unit]’)</pre><pre>plt.xlabel(‘kitty [unit]’)</pre><pre>plt.grid()</pre><pre>wd = solution.Parent.WorkingDir</pre><pre>myPath = os.path.join(wd,’myFig.png’)</pre><pre>plt.savefig(myPath)</pre><pre>image = solution.AddImage(myPath)</pre><pre>pass</pre><ul><li>Right click on your Python Code object and Connect</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*vdKNonURJRzY76colW59uQ.png" /></figure><ul><li>Resolve your model.</li></ul><p>A simple plot will appear in your Mechanical Tree under the Python Code object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSzR_1MfHrIz-Yc8pTGKoA.png" /></figure><p>The plot is also saved to the working directory.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6defcdaf8e51" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ansys-developer/integrating-images-and-plots-using-a-python-code-object-cpython-6defcdaf8e51">Integrating images and plots using a Python Code object (Cpython)</a> was originally published in <a href="https://medium.com/ansys-developer">Ansys Developer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do I find the time-varying center of gravity location of my deforming model using DPF in…]]></title>
            <link>https://medium.com/ansys-developer/how-do-i-find-the-time-varying-center-of-gravity-location-of-my-deforming-model-using-dpf-in-9389604fc961?source=rss-3f7b5fd24139------2</link>
            <guid isPermaLink="false">https://medium.com/p/9389604fc961</guid>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[mechanical-engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[scripting]]></category>
            <dc:creator><![CDATA[Ansys Developer]]></dc:creator>
            <pubDate>Fri, 16 Sep 2022 13:02:22 GMT</pubDate>
            <atom:updated>2022-09-16T13:02:22.035Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How do I find the time-varying center of gravity location of my deforming model using DPF in mechanical?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETOXVp5OovWb46Ka4LtKHw.jpeg" /></figure><p>Today’s script tip comes from <a href="https://www.linkedin.com/in/vishnram/">Vishnu Venkataraman</a>, Application Engineer at Ansys.</p><p>The COG of a body might vary with time as the body deforms and you might be interested in knowing how to compute the time varying COG.</p><p>This example also highlights on how you can create your own mesh with DPF.</p><p>Methodology followed:</p><ul><li>Get the time varying deformation vectors for all nodes using: dpf.operators.displacement</li><li>Create a mesh region based on existing mesh using dpf.MeshedRegion</li><li>Update the node locations of the created mesh based on the deformation vectors at each time point.</li><li>Find the COG using dpf.operators.geo.center_of_gravity by feeding in the mesh regions at every time point .</li></ul><p>Function to find the time varying COG of your model:</p><p>Use the below function like:</p><pre>body_named_selection = ‘MYBODY’</pre><pre>timepoint = 3</pre><pre>find_COG_at_time (body_named_selection, timepoint)</pre><p>Please remember to create a body named selection called ‘MYBODY’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*IpJF80kHcPdyYeTNY9nvPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*iasy84acaxVJpAmKZX6okg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9389604fc961" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ansys-developer/how-do-i-find-the-time-varying-center-of-gravity-location-of-my-deforming-model-using-dpf-in-9389604fc961">How do I find the time-varying center of gravity location of my deforming model using DPF in…</a> was originally published in <a href="https://medium.com/ansys-developer">Ansys Developer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Plot Spring Force as a Contour Plot Using DPF]]></title>
            <link>https://medium.com/ansys-developer/how-to-plot-spring-force-as-a-contour-plot-using-dpf-749f9b7ebcaa?source=rss-3f7b5fd24139------2</link>
            <guid isPermaLink="false">https://medium.com/p/749f9b7ebcaa</guid>
            <category><![CDATA[ansys]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[plotting]]></category>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ansys Developer]]></dc:creator>
            <pubDate>Fri, 09 Sep 2022 13:02:35 GMT</pubDate>
            <atom:updated>2022-09-09T13:17:31.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETOXVp5OovWb46Ka4LtKHw.jpeg" /></figure><p>Today’s Script Tip comes from <a href="https://www.linkedin.com/in/ayush-kumar-5aa2a144/">Ayush Kumar</a> and <a href="https://www.linkedin.com/in/vishnram/">Vishnuram V</a>, Senior Applications Engineers at Ansys.</p><p>Sometimes you might be interested in plotting contours on elements or nodes that are not available in mechanical and are created during the solve phase.</p><p>Examples:</p><p>Spring elements</p><p>Contact elements etc …</p><p>The methodology uses scoping.on_mesh_property operator to extract the COMBIN14(spring element) mesh and uses mapdl.smisc operator to extract the MAPDL smisc results for spring forces. We also pass the result mesh to workflow operator to plot the contours.</p><p>The below example shows how you can plot a contour on spring elements</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*7Av4eFAd0dge5gj86dmRJg.png" /><figcaption>dfp workflow code</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rv1HryiWIVS7pXiyP1vyCw.png" /><figcaption>dpf workflow result</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=749f9b7ebcaa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ansys-developer/how-to-plot-spring-force-as-a-contour-plot-using-dpf-749f9b7ebcaa">How To Plot Spring Force as a Contour Plot Using DPF</a> was originally published in <a href="https://medium.com/ansys-developer">Ansys Developer</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>