How add python module in mechanical environnement pyMechanical

PierreLCV
PierreLCV Member Posts: 35
10 Comments Name Dropper
**

Dear All,
I am currently working on code which allows me to specify the thermal boundary conditions for a steady state thermal anaylsis. For that, I use pyMechanical and more precisely, i launch a python script from file. Unfortunately, i need to use some modules (numpy, scipy...) in the python script executed with pymechanical and it appears that these modules are not found by pymechanical...
Any idea how can I fix this issue ? This is my very first python script so sorry if this question sounds ...

Thank you for your help !

Pierre

Answers

  • PierreLCV
    PierreLCV Member Posts: 35
    10 Comments Name Dropper
    **

    I managed to add the module I was missing but I still get an error code :

    _MultiThreadedRendezvous: <_MultiThreadedRendezvous of RPC that terminated with:
    status = StatusCode.UNKNOWN
    details = "unexpected token 'from'"
    debug_error_string = "UNKNOWN:Error received from peer {grpc_message:"unexpected token \'from\'", grpc_status:2, created_time:"2024-01-16T15:18:29.6661243+00:00"}"

    It seems that it is not possible to import the module i need to define my boundary condition in pymechanical. It is very weird because i have tried my module which works very wel outside the pymechanical...

    any idea ?

    Thank you !

  • Landon Mitchell Kanner
    Landon Mitchell Kanner Member, Employee, GitHub-issue-creator Posts: 322
    50 Answers 100 Comments Second Anniversary 25 Likes
    ✭✭✭✭
    edited January 2024

    Hi Pierre. It is not clear to me what you are doing or trying to do. PyMechanical is used to run Mechanical from outside of Mechanical. PyMechanical is not available from within Mechanical. This is because, for historical reasons, Mechanical Scripting within Mechanical is implemented with IronPython. But PyMechanical runs is compatible with CPython (same as numpy and scipy).

    Here is how to run a Mechanical Scripting (IronPython) script from an instance of CPython using PyMechanical (see the PyMechanical Cheat Sheet:

    import ansys.mechanical.core as pymechanical
    mechanical = pymechanical.launch_mechanical()
    mechanical.run_python_script_from_file(file_path)
    

    If instead you want to run CPython modules from within Mechanical Scripting, see these two posts. The first is about ACT but applies to Mechanical Scripting as well:
    https://discuss.ansys.com/discussion/2827/is-there-a-method-for-importing-external-cpython-modules-like-numpy-or-scipy-to-use-them-with-act
    https://discuss.ansys.com/discussion/2760/how-to-use-numpy-in-mechanical-scripting

  • PierreLCV
    PierreLCV Member Posts: 35
    10 Comments Name Dropper
    **

    Dear Landon,
    THANK YOU VERY MUCH for your answer ! Really appreciate, it is not easy to start scripting so it is very appreciable to have someone to help.
    Regarding what i am trying to do :
    I am still trying to implement my python code which contains some empirical correlations directly in Ansys Mechanical. For that i followed the link you sent me :
    https://discuss.ansys.com/discussion/comment/2933#Comment_2933

    So I have two files i took from this last link (sorry i do not know how import code...) :

    import os
    import ansys.mechanical.core as pymechanical
    from ansys.mechanical.core import find_mechanical

    wb_exe = find_mechanical(232)[0]

    UserDir = r"C:\Users...\Documents\Python\pyNukiNical"
    commandFileName = r"commandFile.py"
    commandFilePath = os.path.join(UserDir,commandFileName)

    mechanical = pymechanical.launch_mechanical(exec_file=wb_exe, batch=False)
    print(mechanical)

    mechanical.run_python_script_from_file(commandFilePath)

    AND

    a longer one (commandFile.py) which start by some import package and a "home made" python package which define a class (pyNukiyama) for which i need to define my boundary conditions in commandFile.py.

    import sys
    import os
    import csv
    sys.path.append(r"C:\Users...\Documents\Python\pyNukiNical")
    import pyNukiyama

    And this pyNukiyama start like this:

    from sys import path
    path.append("pyXSteam")
    from pyXSteam.XSteam import XSteam
    from math import pi, exp
    path.append(r"C:\ProgramData\anaconda3\Lib\site-packages")
    from numpy import arange, array, append
    from scipy.optimize import fminbound
    from scipy.interpolate import interp1d
    import matplotlib.pyplot as plt

    I had to specify the location of numpy as when i run the script it said "numpy is not known". But when i enter a path for this last, i obtain the mistake specified in my previous message.

    I am not sure to understand. numpy and scipy is not available in Ansys Mechanical. So i am not supposed to use these two packages from a script executed in Ansys Mechanical from pyMechanical (with mechanical.run_python_script_from_file(file_path)), we agree ?
    Maybe should I execute my packages involving numpy/scipy in pymechanical in the first script and send to Ansys Mechanical through a script already containing the data i need to define my boundary conditions... (do not know if it possible and how to do...)
    I will also try to dig in the subprocess use for my case.

    THANK YOU ONCE AGAIN FOR YOUR HELP !

    best regards,
    Pierre

  • Landon Mitchell Kanner
    Landon Mitchell Kanner Member, Employee, GitHub-issue-creator Posts: 322
    50 Answers 100 Comments Second Anniversary 25 Likes
    ✭✭✭✭
    edited January 2024

    numpy and scipy is not available in Ansys Mechanical. So i am not supposed to use these two packages from a script executed in Ansys Mechanical from pyMechanical (with mechanical.run_python_script_from_file(file_path)), we agree ?

    This is exactly correct

    Maybe should I execute my packages involving numpy/scipy in pymechanical in the first script and send to Ansys Mechanical through a script already containing the data i need to define my boundary conditions... (do not know if it possible and how to do...)

    This is a good option. Here is an example:

    value = CalculationUsingSciPy()
    mechanical.run_python_script(f'MyLoad = {value}')
    

    Alternatively, you could try to run everything in CPython using embedded pyMechanical (see 3rd column on pyMechanical cheat sheet). This may require some changes to commandFile.py to migrate it from IronPython2 to CPython3

  • PierreLCV
    PierreLCV Member Posts: 35
    10 Comments Name Dropper
    **

    Dear Landon,
    Thank you very much for your answer !
    I have found two ways to make my script working:
    1) Keep the pyMechanical in remote session but i have to define my boundary conditions using numpy and scipy in the first script. It works very well and allows use to keep an eye on the simulation as Ansys Mechanical is open and is automatically filled. However, this it not very optimal to have to define the boundary conditions in the first script, store them in a temporary .csv file and reload these data in the Ansys Mechanical Script
    2) The second option you mentionned using embedded pyMechanical appears to me obvious this morning and... it works very well...

    So THANK YOU VERY MUCH for your help, i think i achieved what i was looking for !

    Have a nice evening and maybe speak you soon.

    THANK YOU once again

  • Landon Mitchell Kanner
    Landon Mitchell Kanner Member, Employee, GitHub-issue-creator Posts: 322
    50 Answers 100 Comments Second Anniversary 25 Likes
    ✭✭✭✭

    Glad you figured it out @PierreLCV :smile: You now understand the pros and cons of the 2 different "flavors" of PyMechanical. We are working hard to find a "best of both worlds" solution. Stay tuned...

  • PierreLCV
    PierreLCV Member Posts: 35
    10 Comments Name Dropper
    **

    Dear landon,
    Once again, thank you for your help ! I will work again on this today. Indeed, it thought about that this weekend and even though it works very well with pyMechanical embedded, it would be great to make it work in Ansys Mechanical. For that, i will try to adapt my current code to make it compatible with Mechanical scripting. I will also try with CPython beta and subprocess...
    Keep you in touch if I find a way to make it work properly :)

    Best regards,
    Pierre

  • PierreLCV
    PierreLCV Member Posts: 35
    10 Comments Name Dropper
    **

    Dear Landon,
    I have tried different ways to use subprocess to execute my Cpython in IronPython (Ansys Mechanical) and for now it is not working... see just after my code:

    import subprocess
    Python312 = r"C:\Users...\AppData\Local\Programs\Python\Python312\python.exe"
    subprocess.call([Python312,'pyNukiyama.py',args])

    Basically, my code is in pyNukiyama.py and i try to launch it with python 3.12 which is install on my computer...
    Does this code appears correct to you ? When i launch it, i obtain "2" as results so I think there is a mistake...

    Any idea welcome...

    Best regards,
    Pierre

  • PierreLCV
    PierreLCV Member Posts: 35
    10 Comments Name Dropper
    **
    edited January 2024

    Dear Landon,
    Finally, it works ! I can call my Cpython code in IronPython, see just after my code:

    import os
    import subprocess
    os.chdir(r"My_code_location")
    Python312 = r"C:\Users...\AppData\Local\Programs\Python\Python312\python.exe"
    subprocess.call([Python312,'pyNukiyama.py'])

    So now, the code executes well in the Ansys Mechanical console, now I'll have to find a way to retrieve the output data...

    keep you in touch !

    best regards,
    Pierre

  • PierreLCV
    PierreLCV Member Posts: 35
    10 Comments Name Dropper
    **

    Dear landon,
    I have worked all the day on that but for now I am blocked. As said before, i can "call" my pyNukiyama.py from Ansys Mechanical with the subprocess tricks.
    However, I need to be able to send input data in pyNukiyama.py (basically, the boundary condition that the script needs to calculate the convective heat transfer) but i do not know how to do that... I can execute a script but how change the input values in the script executed...

    Thank you for your help !
    Best regards,
    Pierre

  • Landon Mitchell Kanner
    Landon Mitchell Kanner Member, Employee, GitHub-issue-creator Posts: 322
    50 Answers 100 Comments Second Anniversary 25 Likes
    ✭✭✭✭

    A quick Google search will give you lots of options for running subprocesses with arguments. Personally, I like to create a modified version of my template script with inputs appended to the top and I like to create a .bat file "on the fly" to run it. There are disadvantages to this technique, but the major advantage is it makes it easy to debug your overall process, as well as debug your subprocess without running the main process. Here is an example:

    release = Ansys.Utilities.ApplicationConfiguration.DefaultConfiguration.VersionInfo.VersionString
    pythonEXE = r'%AWP_ROOT{}%\commonfiles\CPython\3_7\winx64\Release\python\python.exe'.format(release)
    
    pyscriptTemplate = os.path.join(installDir,'my_template.py')
    pyscriptLocal = os.path.join(TempDir,'my_script.py')
    cmds =  'Input1= {}\n'.format(Diameter)
    with open(pyscriptTemplate,'r') as f:
            cmds += "".join(f.readlines()) 
    with open(pyscriptLocal,'w') as f:
            f.write(cmds)
    
    BatFile = os.path.join(TempDir, "run.bat")
    OutFile = os.path.join(TempDir, "log.txt")
    with open(BatFile, "w") as f:
            cmd = '"{}" "{}"'.format(pythonEXE,pyscriptLocal)
            f.write(cmd)
    os.system(BatFile+" > "+OutFile)
    
  • PierreLCV
    PierreLCV Member Posts: 35
    10 Comments Name Dropper
    **

    Dear Landon,
    Thank you VERY MUCH for your answer !
    It appears that I finally found a way to make my script working with CPython directly in Ansys Mechanical. Of course, I know that this is a BETA version so maybe should i expect some troubles in the future...
    Do you know if it's planned, in the long term, to have CPython stable in Ansys Mechanical?
    Thank you !
    Best regards,
    Pierre

  • Landon Mitchell Kanner
    Landon Mitchell Kanner Member, Employee, GitHub-issue-creator Posts: 322
    50 Answers 100 Comments Second Anniversary 25 Likes
    ✭✭✭✭

    Yes, this is the long-term plan. CPython-based Mechanical scripting is a large effort, and its full timeline is not known yet, but you can expect incremental improvements at each release. To help us achieve our goal, please report any issues through your Tech Support provider.