5.1. Python interface¶
SMITER Python interface classes are used for storing input data and parameters.
Note
GUI provides Python view editor that can be used for editing scripts. The editor can be opened by Alt+Y or through . Python scripts can then be loaded by or Ctrl+T.
Classes powcal
, hdsgen
and geoq
all
contain default parameters and functions for retrieving and editing the
parameters. Every function also has the function createCTL()
function
for writing the parameters in a FORTRAN
namelist file.
The class geoq
is used for storing the information about the mesh
used when computing a SMITER case. For convenience it contains a function that
writes a mesh in VTK
format. For each mesh used in a SMITER computation, a
type has to be specified: whether the mesh is used as wall
, target
or
shadow
.
The class eqdsk
is used for saving the plasma equilibrium
data.
The function EQDSK.eqdsk.readEQDSKstring()
reads the G EQDSK
format and saves all the quantities in attributes. For visualization there are
functions that returns array in correct units (meter) for plotting or creating
geometry/mesh objects.
The class SMITERcase
is used as a glue for the previous mentioned to
form a SMITER case. It contains set and get functions for each required input
object. The function case.SMITERcase.setInputParameters()
function
properly sets the input parameters of objects that require output or input data
from other objects in the same case.
The class SMITER_API.ComputeCase
runs the calculation by preparing a
run directory with the input data from the SMITERcase
and running the
SMARDDA executables to perform the calculation.
5.1.1. POWCAL¶
powcal
contains the parameters for the SMARDDA module powcal
. The
parameters of a POWCAL object can be set with the function
POWCAL.setVariable()
and retrieved by POWCAL.getVariable()
.
Example of usage:
import powcal
x = powcal.POWCAL('nameOfObject')
x.setVariable('power_loss', '7.5e+06')
x.getVariable('power_loss')
# Prints 7.5e+06
x.createCTL()
# Prints the string of the CTL input file.
-
class
SMITER.
POWCAL
(name='')[source]¶ Powcal interface implementation
-
clearVariable
(name: str)¶ Because CORBA disallows passing empty string as parameters, this is used instead. Strange though, retrieving empty string gives no errors.
-
createCTL
()¶ Creates a string in the form of CTL.
Returns: Parameters stored in the form of FORTRAN namelist. Return type: ctl (str)
-
getName
()¶ Returns the name.
Returns: String which has whites-paces replaced with _. Return type: name (str)
-
getVariable
(name: str)¶ Returns the value of parameter. If the parameter is not in the self.variables attribute, then we can try to get the default Value.
-
modified
()¶ Returns true if there are non-default values stored.
-
returnListOfChangedVariables
()¶ Returns a list of parameters that have non-default values.
-
setName
(name)¶ Set the name for object. Usually it should be the same as the name of the Salome Object that references to the object.
-
setVariable
(name: str, val: str)¶ Sets the new value to variable name. If the value is the same as the one in the default options, then the value is not changed or in other words no actual change has been added.
-
5.1.2. GEOQ¶
GEOQ
is used for storing information about which mesh in SMITER is
used as input data and for setting parameters for running the computation
Example of usage:
import geoq
x = geoq.GEOQ(name='name of mesh', type='type of usage in smiter case')
# The name and type keywords are not necessary, you can still create the
# object as
x = geoq.GEOQ()
# Then set the name of the mesh and type with the following functions
x.setName('name of mesh in SALOME')
x.setMeshEntry('entry of mesh in the study')
x.setType('wall or shadow or target')
# Each have different default parameter values.
# Same functions to set or get variables as in powcal.POWCAL
x.setVariable('parameter', 'value')
x.getVariable('parameter')
x.createCTL()
# To create the CTL input file.
# SMARDDA GEOQ requires mesh in the form of a VTK file. So geoq.GEOQ
# contains the createVTK function.
# Get the mesh object
import salome
from salome.smesh import smeshBuilder
sb = smeshBuilder.New()
# Get the study entry from the GEOQ x object.
meshSalomeObject = salome.myStudy.FindObjectID(x.getMeshEntry())
# Fetch the mesh data from the meshSalomeObject
meshObject = meshSalomeObject.GetObject()
x.createVTK(meshObject)
# Prints the contents of the mesh in VTK format.
-
class
SMITER.
GEOQ
(name='', type='')[source]¶ GEOQ interface implementation. .. attribute:: name
string – Name for the geoq instance-
type
¶ string – Type of geoq instance. Either target or shadow.
-
variables
¶ dict – A dictionary for non default values for parameters
-
_defaultValueModified
¶ bool – Is true if nondefault values are present
-
meshVTK
¶ string – VTK format of mesh. It is generated on instance
-
clearVariable
(name: str)¶ Because CORBA disallows passing empty string as parameters, this is used instead. Strange though, retrieving empty string gives no errors.
-
createCTL
()¶ Creates a string in the form of CTL.
Returns: Parameters stored in the form of FORTRAN namelist. Return type: ctl (str)
-
getName
()¶ Returns the name.
Returns: String which has whites-paces replaced with _. Return type: name (str)
-
getVariable
(name: str)¶ Returns the value of parameter. If the parameter is not in the self.variables attribute, then we can try to get the default Value.
-
modified
()¶ Returns true if there are non-default values stored.
-
returnListOfChangedVariables
()¶ Returns a list of parameters that have non-default values.
-
setMeshEntry
(entry)[source]¶ If used with SALOME study, then the entry is the SObject from Object browser that represents the mesh we wish to use for GEOQ.
-
setName
(name)¶ Set the name for object. Usually it should be the same as the name of the Salome Object that references to the object.
-
setType
(type)[source]¶ Refers to the type to be used when running SMARDA case. Target means that the mesh will be later used for power calculation. Shadow means that it will be used by hdsgen and powcal.
-
setVariable
(name: str, val: str)¶ Sets the new value to variable name. If the value is the same as the one in the default options, then the value is not changed or in other words no actual change has been added.
-
5.1.3. HDSGEN¶
HDSGEN
contains parameters for SMARDDA module hdsgen
.
Example of usage:
import hdsgen
x = hdsgen.HDSGEN('nameOfObject')
x.setVariable('limit_geobj_in_bin', '2000')
x.getVariable('limit_geobj_in_bin')
# Prints 2000
x.createCTL()
# Prints the string of the CTL input file.
-
class
SMITER.
HDSGEN
(name='')[source]¶ HDSGEN interface implementation
-
clearVariable
(name: str)¶ Because CORBA disallows passing empty string as parameters, this is used instead. Strange though, retrieving empty string gives no errors.
-
createCTL
()¶ Creates a string in the form of CTL.
Returns: Parameters stored in the form of FORTRAN namelist. Return type: ctl (str)
-
getName
()¶ Returns the name.
Returns: String which has whites-paces replaced with _. Return type: name (str)
-
getVariable
(name: str)¶ Returns the value of parameter. If the parameter is not in the self.variables attribute, then we can try to get the default Value.
-
modified
()¶ Returns true if there are non-default values stored.
-
returnListOfChangedVariables
()¶ Returns a list of parameters that have non-default values.
-
setName
(name)¶ Set the name for object. Usually it should be the same as the name of the Salome Object that references to the object.
-
setVariable
(name: str, val: str)¶ Sets the new value to variable name. If the value is the same as the one in the default options, then the value is not changed or in other words no actual change has been added.
-
5.1.4. EQDSK¶
EQDSK
is a module for reading EQDSK G
files. It parses all the
quantities in the EQDSK G
which are then accessible through the attributes
of the module, described bellow.
An example is also written into the file on how to use the module.
Note
This module can be used standalone if you remove the
SMITER_ORB__POA.EQDSK
from the inheritance in the class definition.
-
class
SMITER.
EQDSK
(name='')[source]¶ EQDSK interface implementation
The following quantities are read from a
EQDSK G
.-
PSIRZ
¶ arr – Array of plasma psi values in units WEBER.
-
CURRENT
¶ float – Plasma current in Ampere
-
RDIM
¶ float – Horizontal dimension in meter of computational box
-
ZDIM
¶ float – Vertical dimension in meter of computational box
-
NW
¶ int – Number of horizontal R grid points
-
NH
¶ int – Number of vertical Z grid points
-
LIMITR
¶ int – Number of limiter points
-
RLIM
¶ arr – R of surrounding limiter contour in meter
-
ZLIM
¶ arr – Z of surrounding limiter contour in meter
-
NBBBS
¶ int – Number of boundary points
-
RBBBS
¶ arr – R of boundary points in meter
-
ZBBBS
¶ arr – Z of boundary points in meter
-
RMAXIS
¶ arr – R of magnetic axis in meter
-
ZMAXIS
¶ arr – Z of magnetic axis in meter
-
FPOL
¶ arr – Poloidal current function in m-T, F=RB_T on flux grid
-
PRES
¶ arr – Plasma pressure in nt/m^2 on uniform flux grid
-
FFPRIM
¶ arr – FF’(Psi) in (mT)^2/(Weber /rad) on uniform flux grid
-
PPRIME
¶ arr – P’(Psi) in (nt/m^2) / (Weber /rad) on uniform flux grid
-
QPSI
¶ arr – q values on uniform flux grid from axis to boundary
-
SIMAG
¶ arr – poloidal flux at magnetic axis in Weber /rad
-
SIBRY
¶ arr – poloidal flux at the plasma boundary in Weber /rad
-
RCENTR
¶ float – R in meter of vacuum toroidal magnetic field BCENTR
-
BCENTR
¶ float – Vacuum toroidal magnetic field in Tesla at RCENTR
-
RLEFT
¶ float – Minimum R in meter of rectangular computational box
-
ZMID
¶ float – Z of center of computational box in meter
Note
The quantity FPOL is poloidal current function in m-T (r Bt). It’s domain is the flux region from SIMAG to SIBRY.
They are all accessible with the following example
import eqdsk x = eqdsk.EQDSK() eqdskFile = '/path/to/eqdsk/format/file' # If SMITER is located on your machine x.openAndRead(eqdskFile) # If SMITER is used remotely you have to manually pass the contents # of the EQDSK file. In this case: with open(eqdskFile) as f: data = f.read() ok = x.read(data) # Then set the name of the eqdsk file if ok: # Reading Successful eqdskName = eqdskFile.rpslit('/', 1)[-1] # Get the name of the file x.setName(eqdskFile) else: print('Trouble reading EQDSK file %s' % eqdskFile) # If the file was read without a problem, you can access, i.e, the # geometry of the limiter x.RLIM x.ZLIM
-
5.1.5. SMITERCase¶
SMITERcase
is a glue for all the previous objects, which together
creates a SMITER case.
An example of empty objects:
import geoq
import hdsgen
import powcal
import eqdsk
target = geoq.GEOQ('targetName', 'target')
wall = geoq.GEOQ('wallNme', 'wall')
shadow = geoq.GEOQ('shadowName', 'shadow')
hdsgen = hdsgen.HDSGEN('hdsgenName')
powcal = powcal.POWCAL('powcalName')
eq = eqdsk.EQDSK('eqdskName')
import case
x = case.SMITERcase('caseName')
x.setWall(wall._this())
x.setTarget(target._this())
x.setShadow(shadow._this())
x.setHDSGEN(hdsgen._this())
x.setPOWCAL(powcal._this())
x.setEQDSK(eqdsk._this())
# The following function sets the parameters of objects which needs output
# or input data from other objects. (i.e., POWCAL requires the input mesh
# of TARGET GEOQ)
x.setInputParameters()
-
class
SMITER.
CASE
(caseName='')[source]¶ Case object for running SMARDDA. It contains references to all input objects for easier use. Accordingly there are set and get functions for each object holding the input data.
The function
setInputParameters
sets the parameters of the control CTL files, which requires the input or output data from other input objects.-
wall
¶ GEOQ
– GEOQ object that contains parameters for wall
-
wallEntry
¶ str – Entry for wall GEOQ Salome Object. If no Salome Object is present then an empty string is placed in.
-
target
¶ GEOQ
– GEOQ object that contains parameters for target
-
targetEntry
¶ str – Entry for target GEOQ Salome Object. If no Salome object is present then an empty string is placed in.
-
shadow
¶ GEOQ
– GEOQ object that contains parameters for shadow
-
shadowEntry
¶ str – Entry for shadow GEOQ Salome Object. If no Salome Object is present then an empty string is placed in.
-
hdsgen
¶ HDSGEN
– HDSGEN object, HDS means Hierarchical Data Structure
-
hdsgenEntry
¶ str – Entry for target HDSGEN Salome Object. If no Salome object is present then an empty string is placed in.
-
powcal
¶ POWCAL
– POWCAL object
-
powcalEntry
¶ str – Entry for target POWCAL Salome Object. If no Salome object is present then an empty string is placed in.
-
eqdsk
¶ EQDSK
– EQDSK object, that contains information about equilibrium.
-
eqdskEntry
¶ str – Entry for target EQDSK Salome Object. If no Salome object is present then an empty string is placed in.
-
generateSaveString
() → str[source]¶ Create a dictionary containing all information of the case and then output it as a string.
-
getEQDSK
()[source]¶ Returns the
EQDSK
object of the eqdsk.Returns: EQDSK object for the eqdsk. Return type: eqdsk ( EQDSK
)
-
getEQDSKEntry
()[source]¶ Returns the Salome Object entry referencing to the eqdsk “py:mod:EQDSK object.
Returns: Entry for the Salome Object. Return type: eqdskEntry (str)
-
getHDSGEN
()[source]¶ Returns the
HDSGEN
object of the hdsgen.Returns: HDSGEN object for the hdsgen. Return type: hdsgen ( HDSGEN
)
-
getHDSGENEntry
()[source]¶ Returns the Salome Object entry referencing to the hdsgen “py:mod:HDSGEN object.
Returns: Entry for the Salome Object. Return type: hdsgenEntry (str)
-
getName
()[source]¶ Returns the name.
Returns: String which has whites-paces replaced with _. Return type: name (str)
-
getPOWCAL
()[source]¶ Returns the
POWCAL
object of the powcal.Returns: POWCAL object for the powcal. Return type: powcal ( POWCAL
)
-
getPOWCALEntry
()[source]¶ Returns the Salome Object entry referencing to the powcal “py:mod:POWCAL object.
Returns: Entry for the Salome Object. Return type: powcalEntry (str)
-
getShadow
()[source]¶ Returns the
GEOQ
object of the shadow. :returns: GEOQ object for the shadow. :rtype: shadow (GEOQ
)
-
getShadowEntry
()[source]¶ Returns the Salome Object entry referencing to the shadow “py:mod:GEOQ object.
Returns: Entry for the Salome Object. Return type: shadowEntry (str)
-
getTarget
()[source]¶ Returns the
GEOQ
object of the target.Returns: GEOQ object for the target Return type: target ( GEOQ
)
-
getTargetEntry
()[source]¶ Returns the Salome Object entry referencing to the target “py:mod:GEOQ object.
Returns: Entry for the Salome Object. Return type: targetEntry (str)
-
getWall
()[source]¶ Returns the
GEOQ
object of the wall.Returns: GEOQ object for the wall. Return type: wall ( GEOQ
)
-
getWallEntry
()[source]¶ Returns the Salome Object entry referencing to the wall “py:mod:GEOQ object.
Returns: Entry for the Salome Object. Return type: wallEntry (str)
-
loadString
(jsonString: str) → bool[source]¶ Take a json string containing dictionary with all paremeters for the case.
-
setEQDSK
(equilibrium, entry='')[source]¶ Sets the eqdsk
EQDSK
object.Parameters: eqdsk ( EQDSK
) – EQDSK object for shadow.
-
setHDSGEN
(hdsgen, entry='')[source]¶ Sets the hdsgen
HDSGEN
object.Parameters: hdsgen ( HDSGEN
) – HDSGEN object.
-
setInputParameters
()[source]¶ After you set the GEOQ target, GEOQ shadow, HDSGEN hdsgen and POWCAL powcal, this function properly sets the input parameters.
If the input parameters are changed after the case is created, then this can be called again manually, or just run the ComputeCase, which always call this before computing.
-
setMAGTFM
(magtfm)[source]¶ Sets the magtfm
MAGTFM
object.Parameters: magtfm ( MAGTFM
) – MAGTFM object.
-
setName
(caseName)[source]¶ Set a name for the case. It should be the same as the name displayed to the Salome Object in Object browser.
Parameters: caseName (str) – Name for the case.
-
setPOWCAL
(powcal, entry='')[source]¶ Sets the powcal
POWCAL
object.Parameters: powcal ( POWCAL
) – POWCAL object.
-
setShadow
(shadow, entry='')[source]¶ Sets the shadow
GEOQ
object.Parameters: shadow ( GEOQ
) – GEOQ object for shadow.
-
5.1.6. SMITER_API¶
ComputeCase
starts the computation of the SMITER case. It requires
a SMITER case object and settings such as SMITER directory location.
The following example typed in Python console inside SMITER GUI works when Smiter module is activated and case is selected by mouse in Object Browser. Case can then be computed with all settings active.
>>> import SMITERGUI
>>> case = SMITERGUI.getComputeObject()
>>> case.compute()
To change a parameter in a loop use the following non-blocking script
that calls loop()
when computation finishes. This is done by
connecting signal.
import os
import SMITERGUI
from salome.gui import dockwidgets
pythonDock = dockwidgets.findDockWidgetByTitle('Python Console')
batch = SMITERGUI.getComputeObject()
global count
count = 0
def console_print(text):
pythonDock.widget().layout().itemAt(0).widget().append(text + '\n')
def loop():
global count, batch, os
powcalPath = os.path.join(batch.caseDirectory, batch.smiterCase.getName(),
'P', 'Powcal_powx')
os.rename(powcalPath + '.vtk', powcalPath + str(count) + '.vtk')
powerLoss = (1 + count) * 1e6
batch.smiterCase.getPOWCAL().setVariable('power_loss', '%d' % powerLoss)
count += 1
if count < 3:
console_print('count = ' + str(count))
batch.computePOWCAL()
else:
batch.caseComputeFinished.disconnect()
console_print("Open the resulting VTK files in %s/%s/P directory." %
(batch.caseDirectory, batch.smiterCase.getName()))
batch.caseComputeFinished.connect(loop)
print("Computing complete case and then loop POWCAL ...")
batch.compute()
5.1.7. SMITER_BATCH_API¶
SMITER_BATCH_API is a main module that does not use PyQt5 modules or any GUI modules, to access SMITER functionality without active X11 connection, for running in cluster batch submission queues.
The following example script runs an already prepared study file
from deck examples under directory pointed by environment variable
SMITER_STUDY_EXAMPLES_DIR
.
import salome
import SMITER_BATCH_API
import SMITER_utils
import sys
import os
# Path to the study file, in this case absolute.
studyFileName = os.path.join(os.getenv('SMITER_STUDY_EXAMPLES_DIR'),
'deck', 'Test-EQ3-inrshad1-inres1.hdf')
# Open and initialize the study.
salome.salome_init(studyFileName)
# Activate module SMITER and activate CORBA
SMITER_utils.activateSmiterModule(salome.myStudy)
# Get the list of cases in the study file.
listOfCaseNames = SMITER_BATCH_API.getAvailableCases()
print('List of cases: ', listOfCaseNames)
caseName = listOfCaseNames[0]
print("Creating compute instance.")
batch = SMITER_BATCH_API.ComputeCase() # Create the compute case instance.
batch.setSmiterDir(os.getenv('SMITER_DIR', os.path.expanduser('~/smiter')))
batch.setCaseDir(os.getenv('HOME'))
print("Setting case")
batch.findAndSetCase(caseName)
print("Starting compute")
batch.compute()
print("Open the resulting VTK file %s/P/Powcal_powx.vtk in ParaView." %
batch.caseDirectory)
API for running a SMITER case. This is meant to be used in SALOME batch mode or script mode. This will run the SMITER computation and perform basically the same as the GUI SMITER_API.ComputeCase, except it is not using PyQt5, to avoid raising the complexity when writing batch scripts.
-
class
SMITER_BATCH_API.
ComputeCase
[source]¶ The attributes are the same of SMITER_API.ComputeCase
-
compute
()[source]¶ Computes the whole case, starting with the GEOQ for wall, target and shadow, then HDSGEN and finally POWCAL.
-
computeHDSGEN
()[source]¶ Runs the case ONLY for HDSGEN. Means only the HDSGEN for the case will be run.
- Requirements:
- computeTarget
- computeShadow
-
computePOWCAL
()[source]¶ Runs the case ONLY for POWCAL. Means only the POWCAL for the case will be run.
- Requirements:
- computeTarget
- computeShadow
- computeHdsgen
-
findAndSetCase
(caseName)[source]¶ Function that searches a case with the name
caseName
under the SMITER component. Works only when GUI is enabled!Parameters: caseName (str) – Name of the case. A Salome object holds the name of the case and the reference to the CORBA object SMITER_ORB__POA.SMITERcase
.
-
getSettings
()[source]¶ Does nothing since batch mode is run in non-GUI mode and thus no settings can be retrieved from SMITER-GUI preferences
-
initialCheck
()[source]¶ Checks whether the computeLock is set and if there is a CORBA instance of SMITER case.
-
prepareRunDirectory
()[source]¶ Runs the QThread to first prepare the directory for the case. Then it goes through the
commands
-
5.1.8. SMITER dialog¶
This is a base class for writing simple dialogs.
-
class
base_dialog.
Dialog
(parent=None)[source]¶ A base widget for creating menu dialogs. It makes creating custom widgets easier by having prepared widgets for basic widget types.
It uses ObjectBrowser signals for automatic selection of salome objects, that are accepted by the dialog via it’s localID.
-
addDropDown
(labelText, args=[])[source]¶ This function adds a drop down button of passed arguments.
If args contain list of pairs, it will set the first element as the text and second as the data.
I.e.: if args == [‘text1’, ‘text2’]: Populate QComboBox with strings
if args == [(‘text1’, ‘data1’), (‘text2’, ‘data2’)]: Populate the QComboBox with text as displayed text and data as data value
Parameters: - labelText (str) – Labeling the widget
- args (arr) – Elements to show in the drop down button.
Returns: A dropdown widget.
Return type: dropDown (QComboBox)
-
addLineEdit
(labelText='', editText='', fileDialog=False, dirDialog=False, saveToFileDialog=False, filter='', selectWidget=False)[source]¶ This function adds a QLinEdit widget with the possibility of a tool button for opening file/directory browsers.
Parameters: - text (str) – Default string for QLineEdit.
- fileDialog (bool) – If True a QToolButton is along QLineEdit that opens a file or directory browser.
- dirDialog (bool) – If true the browser is a directory browser, else it’s a file browser.
Returns: Returns the QLineEdit to retrieve text, etc…
Return type: edit (QLineEdit)
-
addMultiSelectionTreeView
(headers, items)[source]¶ Creates a QTreeView with multi selection mode.
Parameters: - headers (list) – List of strings serving as the headers
- items (list) – List of data to display
-
addSelectDropDown
(labelText='')[source]¶ Function that adds a QComboBox, which shows all the selected objects in the object browser.
Parameters: labelText (str) – Display text
-
addSelectEdit
(labelText='', objectID=[], fileDialog=False, dirDialog=False, saveToFileDialog=False, filter='')[source]¶ Function that adds a QLineEdit that shows the current selected object.
Parameters: - labelText (str) – Display text
- objectID (list) – A list of acceptable IDs Type int..
-
5.2. Getting objects from objects browser via python console¶
For inspecting certain objects there is a quick way of getting the object in the python terminal via salome session:
>>> # First select an object by clicking on it in the object browser
>>> import salome
>>> o = salome.myStudy.FindObjectID(salome.sg.getSelected(0))
The salome.myStudy contains functions for searching objects, either by name
or its entry
. Since entries
are unique, it is better to
programmatically get the object
we want via its entry
and not by its
name
.
The function salome.sg.getSelected(0) returns the first selected or
highlighted object from the object browser
. For convenience there is also a
salome.sg.getAllSelected which returns a list of entries for all selected
objects
in the object manager
.
5.3. Salome Object or SObject attributes¶
Attributes are containers for data or visual settings for objects in the
objects manager
.
An SObject can contain the following list of attributes:
- AttributeName
- Attribute that has the name of the object stored.
- AttributeString
- Attribute for storing a string.
- AttributePixMap
- Attribute that has the name of the .png icon stored. You can see the names of the icons if you go to the resource folder of the module source code. If the string name for the PixMap is correct, a new icon should be seen besides the object in the objects manager.
- AttributeParameter
- This is a container for dictionaries for almost all types. Integers, Reals, Strings, Integer arrays, Real arrays, String array… For storing various data in an object this is the way to go, since you need fewer lines of codes and is thus better to read.
There are other attributes, so for more reading, go to SALOME documentation. The section is called SALOME KERNEL Developer Documentation.
5.4. Assigning attributes to an object¶
In SALOME every Salome object or SObject have a set of attributes. You have integer or real attribute, then sequence of reals or integers, etc. To assign attributes to these attributes there are several ways.
The first way is only for attributes that have string values [AttributeName, AttributePixMap, AttributeString,…]. Objects have a method called SetAttrString:
>>> # First you have to get a handle to an object by using the previous
>>> # howto on getting object from object browser
>>> import salome
>>> # Select an object in the object browser by clicking it, resulting a
>>> # highlight on the object
>>> o = salome.myStudy.FindObjectID(salome.sg.getSelected(0))
>>> # If the previous name was i.e. "case1" we can change it by
>>> o.SetAttrString('AttributeName', "new_name")
>>> # Then the objects browser needs to be visually updated by
>>> salome.sg.updateObjBrowser()
>>> # The new name "new_name" should be visible in the objects browser
The second way is using the study builder to find or create attributes for an object, with the FindOrCreateAttribute method:
>>> import salome
>>> b = salome.myStudy.NewBuilder()
>>> # Click on an object in the objects browser
>>> o = salome.myStudy.FindObjectID(salome.sg.getSelected(0))
>>> # Find the attribute and get the handle to it
>>> name_attribute = b.FindOrCreateAttribute(o, 'AttributeName')
>>> # We get an object, which has a get and set method.
>>> name_attribute.SetValue('new_name')
>>> # Update objects browser
>>> salome.sg.updateObjBrowser()
>>> # To get the value storred in the object
>>> value = name_attribute.Value()
Note
Attributes, as in types, do not have the same names for set and get methods
The third way is finding attributes from salome objects, by using the FindAttribute method:
>>> import salome
>>> o = salome.myStudy.FindObjectID(salome.sg.getSelected(0))
>>> status, name_attribute = o.FindAttribute('AttributeName')
>>> # If the attribute exists then the status, which is a boolean will be
>>> # true, otherwise it will be false.
>>> if status:
>>> name_attribute.SetValue('new_name')
>>> salome.sg.updateObjBrowser()
With this way, you cannot create attributes, you can only find them in an object if the object contains it.
5.5. Attribute parameter¶
Since this attribute contains dictionaries for different types, there is a separate section for it.
First we get the attribute parameter from the object:
>>> import salome
>>> b = salome.myStudy.NewBuilder()
>>> o = salome.myStudy.FindObjectID(salome.sg.getSelected(0))
>>> attribute = b.FindOrCreateAttribute(o, 'AttributeParameter')
>>> # If you wish to assign a value, you assign it as a pair of
>>> # (key, value)
>>> # For example with the usage of SetInt
>>> attribute.SetInt('a', 5)
>>> # Now if we wish to get the value we use the GetInt method
>>> attribute.GetInt('a')
5
>>> # One important rule is that you should first check if there actually is
>>> # an integer value stored under the key 'a'. To get an array of keys ,
>>> # for example, integers, use the method GetID( enumerator )
>>> # The enumerator for int is 0
>>> attribute.GetIDs(0)
['a']
>>> # Other enumerators are:
>>> # 0 for integer, 1 for real, 2 for boolean, 3 for string,
>>> # 4 for real array, 5 for integer array, 6 for string array
For more informations read the SALOME KERNEL Developer Documentation.