ansys / pyensight

Python API for EnSight
http://ensight.docs.pyansys.com
MIT License
6 stars 2 forks source link

making a 2010 python script working with pyensight #427

Closed amscosta closed 1 month ago

amscosta commented 1 month ago

Hi All, I found this python script for converting xyz_value in ensight format. Unfortunatelly is not working inside ensight 2023R1, following the macro procedure. Can some knowledgeable expert know the trick for making it run ? (Maybe calling pyensight csv2point_n.txt inside a jupyter notebook) Thanks .

ENSIGHT_USER_DEFINED_BEGIN

FACTORY=ctor

ENSIGHT_USER_DEFINED_END

#

Python Script to convert from a comma separated 5 column file (X,Y,Z,Var1,Var2) to

EnSight Case format

Assume temperature as Var1

and strain_rate as Var2

Kevin Colburn

CEI

June, 2010

#

# import math,ensight from cei.qtgenericdlg import from ensight.objs import from ensight.core.tool_extension import * #

This routine converts a float value to a % 12.5e string with two places for the exponent.

Microsoft has decided to defy the C Standards and write out three values in the

exponent [-]m.ddddde+xxx rather than only two per the C STANDARD [-]m.ddddde+xx

# def float_to_exponent_string(float_val):

converts a float to a 12-character string with three-character exponent (windows)

#   or a two-character exponent on all other platforms.
# First, get positives and negatives printed out with 13 characters
#  (positives get padded with a space on left)
if (os.name == 'nt'):
    out_str = " %12.5e" % float(float_val)
    # first digit of three-digit exponent should be a zero; remove it
    # else round to exponent of 99
    for i in range(len(out_str)):
        if out_str[i] == 'e':
            first_ex = i+2
            break
    #print("\npreconvert: '",out_str,"'"
    #print("out_str[",first_ex,"]: '",out_str[first_ex],"'"
    #print("out_str[0:",first_ex,"]: '",out_str[0:first_ex],"'"
    #print("out_str[",first_ex+1,":13]: '",out_str[first_ex+1:first_ex+3],"'"
    if (out_str[first_ex] != '0'):
        out_str = out_str[0:first_ex] + '99'
    else:
        out_str = out_str[0:first_ex] + out_str[first_ex+1:first_ex+3]
else:
    out_str = " %12.5e" % float(float_val)

# if out_str[1] == '-' or (out_str[0]==' ' and out_str[1]==' '): out_str = out_str[1:]

#print("length out_str = ",len(out_str)
#print("postconvert: '",out_str,"'"

return(out_str) 

# def runkevincode(): #

create a user interface where the user selects the file for conversion

#    
items = []
items.append(['text_val',ITEM_TEXT,"Python routine to convert Excel CSV \ndata to EnSight Case Format\n",""])
items.append(['text_val',ITEM_TEXT,"Routine expects X,Y,Z,Variable1,Variable2\n",""])
in_out_flag = 0
items.append(['infile_val',ITEM_FILE,"Input CSV File:","Input CSV filename:","file.csv",in_out_flag])
items.append(['text_val',ITEM_TEXT,"Output File will be Point.case, .geo, .var1, .var2\n",""])
d = CeiQtGenericDialog(items,None,"Python Excel CSV to Case Tool","Ok","Cancel")
#
# If the user hits ok we can go on.  If he hit Cancel  then we're out of here 
#
if(d.doit()):
    infile_val = d.getValue('infile_val')
    # ###############################################
    # MAIN CODE
    # ###############################################
    #
    # Open Input file
    in_file = open(infile_val,"r")
    #in_file = open("file.csv","r")
    #
    # Open Output file
    temp = sys.stdout
    sys.stdout = open("point.geo","w")
    #
    # Step 1 : Start writing EnSight files, place header information into .geo file
    print("EnSight Model Geometry File")
    print("EnSight 9.0 ")
    print("node id assign")
    print("element id assign") 
    print("part") 
    print("         1") 
    print("Point field")
    print("coordinates")

    # Step 2 : Load in the Coordinates and two variables.
    data = in_file.readlines()
    cnt = len(data)
    word = [line.split(',') for line in data]
    print ('%10d' % cnt) 

    # On windows, 12e5 format yeilds e+000 format, when we need e+00 so that negative values
    # do not run over the 12 column width.
    # Therefore, we have to convert the e+000 to e+00 by taking anything over e+100 and changing to e+99
    # And for all with a zero in the first e+XXX statement, just stripping off the leading zero.
    # Therefore, in the calls below to float_to_exponent_string

    # Step 3: Put the Coordinates into the geo file (X, then Y, then Z)
    for i in range(cnt):
        out_str = float_to_exponent_string(word[i][0])
        print(out_str)
    for i in range(cnt):
        out_str = float_to_exponent_string(word[i][1])
        print(out_str)
    for i in range(cnt):
        out_str = float_to_exponent_string(word[i][2])
        print(out_str)
    #
    # Step 4: Create the Variable 1 file
    sys.stdout = open("point.var1","w")
    print("Temperature")
    print("part")
    print("         1")
    print("coordinates")
    for i in range(cnt):
        out_str = float_to_exponent_string(word[i][3])
        print(out_str)
    # Step 5 : Create the variable 2 file
    sys.stdout = open("point.var2","w")
    print("Strain_Rate") 
    print("part")
    print("         1")
    print("coordinates")
    for i in range(cnt):
        tmp = word[i][4]
        out_str = float_to_exponent_string(tmp.strip())
        print(out_str)
    # Step 6 : Create the EnSight .case file
    sys.stdout = open("point.case","w")
    print("FORMAT")
    print("type: ensight gold")
    print("GEOMETRY")
    print("model: point.geo")
    print("VARIABLE")
    print("scalar per node: temperature point.var1")
    print("scalar per node: strain_rate point.var2")
    #
    sys.stdout = temp

#

Extension class

# class convert_csv(tool_extension): def init(self): tool_extension.init(self,"convert_csv",file,1.0) self.setText("Convert Excel CSV to EnSight Format") self.setDesc("Convert Excel CSV to EnSight Format") self.setTooltip("Select Excel CSV and Convert to EnSight Case Format") dir = os.path.dirname(file) self.setIcon(os.path.join(dir,"csv2en.png"))

self.cmdClear()

#

Execute the tool from the gui

# def run(self): runkevincode() #

Construct the extension instance

# def ctor(parent): list = [] obj = convert_csv() if (parent): parent.addChild(obj) list.append(obj) return list

kecolburn commented 1 month ago

There are newer versions of that script which are more compliant and robust with more recent versions of EnSight and python usage. Please reach out directly to kevin.colburn@ansys.com for direct assistance.

mariostieriansys commented 1 month ago

Hi @amscosta , I would like also to point out that converting EnSight scripts into PyEnSight scripts, while it is usually simple, has some implications because of the different nature between the "ensight" module in EnSight, and the session "ensight" class instance.

The do share the same API, though they are completely different objects

Things like "from ensight.objs import " cannot work since in PyEnSight "ensight" is not a module, but a class instance. Also in PyEnSight the "EnSight Extensions" are not exposed, being, indeed, EnSight extensions and not PyEnSight extension (hence "from ensight.core.tool_extension import " cannot work in PyEnSight).

Finally, the "cei" module is not exposed in PyEnSight, and the same applies for any Qt application available in the EnSight Python. These are all features that, given their nature, are only available in EnSight.

For guidance on converting EnSight scripts into PyEnSight scripts, please refer to https://ensight.docs.pyansys.com/version/stable/user_guide/api_differences.html and https://ensight.docs.pyansys.com/version/stable/user_guide/cmdlang_native.html