# $Id$
#
-import traceback
-import os
import logging
+import traceback
from PyQt5 import QtCore, QtGui, QtWidgets
-
-import salome
+from salome.kernel import termcolor
+from salome.kernel.logger import Logger
+from salome.kernel.parametric import study_exchange_vars
+from salome.kernel.studyedit import getStudyEditor
import SALOME
import SALOME_TYPES
-from salome.kernel.studyedit import getStudyEditor
-from salome.kernel.parametric import study_exchange_vars
+import salome
-# Get SALOME PyQt interface
import SalomePyQt
+
+
+# Get SALOME PyQt interface
sgPyQt = SalomePyQt.SalomePyQt()
-from salome.kernel.logger import Logger
-from salome.kernel import termcolor
-logger = Logger("GENERICSOLVERGUI", color = termcolor.RED_FG)
-logger.setLevel(logging.INFO)
+logger = Logger("GENERICSOLVERGUI", color=termcolor.RED_FG)
salome.salome_init()
# Used to store actions, menus, toolbars, etc...
################################################
+
class GUIcontext:
# module name
- MODULE_NAME = "GENERICSOLVER"
+ MODULE_NAME = "GENERICSOLVER"
# module icon
- MODULE_PIXMAP = "GENERICSOLVER_small.png"
+ MODULE_PIXMAP = "GENERICSOLVER_small.png"
# data objects IDs
- MODULE_ID = 1000
- CASE_ID = 1020
- VARIABLE_ID = 1030
+ MODULE_ID = 1000
+ CASE_ID = 1020
+ VARIABLE_ID = 1030
# menus/toolbars/actions IDs
- GENERICSOLVER_MENU_ID = 90
- SOLVER_ID = 941
- OPTIONS_ID = 943
- OPTION_1_ID = 944
- OPTION_2_ID = 945
- OPTION_3_ID = 946
- DELETE_ALL_ID = 951
- CREATE_CASE_ID = 955
- SET_VALUE_ID = 956
+ GENERICSOLVER_MENU_ID = 90
+ SOLVER_ID = 941
+ OPTIONS_ID = 943
+ OPTION_1_ID = 944
+ OPTION_2_ID = 945
+ OPTION_3_ID = 946
+ DELETE_ALL_ID = 951
+ CREATE_CASE_ID = 955
+ SET_VALUE_ID = 956
# default object name
- DEFAULT_CASE_NAME = "Case"
+ DEFAULT_CASE_NAME = "Case"
# constructor
- def __init__( self ):
+ def __init__(self):
# create top-level menu
- mid = sgPyQt.createMenu( "Genericsolver", -1, GUIcontext.GENERICSOLVER_MENU_ID,
- sgPyQt.defaultMenuGroup() )
+ mid = sgPyQt.createMenu("Genericsolver", -1, GUIcontext.GENERICSOLVER_MENU_ID,
+ sgPyQt.defaultMenuGroup())
# create toolbar
- tid = sgPyQt.createTool( "Genericsolver" )
+ tid = sgPyQt.createTool("Genericsolver")
# create actions and fill menu and toolbar with actions
- a = sgPyQt.createAction( GUIcontext.CREATE_CASE_ID, "Create case", "Create case",
- "Create a new case", "CaseGENERICSOLVER.png" )
- sgPyQt.createMenu( a, mid )
- sgPyQt.createTool( a, tid )
+ a = sgPyQt.createAction(GUIcontext.CREATE_CASE_ID, "Create case", "Create case",
+ "Create a new case", "CaseGENERICSOLVER.png")
+ sgPyQt.createMenu(a, mid)
+ sgPyQt.createTool(a, tid)
a = sgPyQt.createSeparator()
- sgPyQt.createMenu( a, mid )
- ag = sgPyQt.createActionGroup( GUIcontext.OPTIONS_ID )
- ag.setText( "Creation mode" )
+ sgPyQt.createMenu(a, mid)
+ ag = sgPyQt.createActionGroup(GUIcontext.OPTIONS_ID)
+ ag.setText("Creation mode")
ag.setUsesDropDown(True)
- a = sgPyQt.createAction( GUIcontext.OPTION_1_ID, "Default name", "Default name",
- "Use default name for the objects" )
- a.setCheckable( True )
- ag.add( a )
- a = sgPyQt.createAction( GUIcontext.OPTION_2_ID, "Generate name", "Generate name",
- "Generate name for the objects" )
- a.setCheckable( True )
- ag.add( a )
- a = sgPyQt.createAction( GUIcontext.OPTION_3_ID, "Ask name", "Ask name",
- "Request object name from the user" )
- a.setCheckable( True )
- ag.add( a )
- sgPyQt.createMenu( ag, mid )
- sgPyQt.createTool( ag, tid )
- default_mode = sgPyQt.integerSetting( "GENERICSOLVER", "creation_mode", 0 )
- sgPyQt.action( GUIcontext.OPTION_1_ID + default_mode ).setChecked( True )
+ a = sgPyQt.createAction(GUIcontext.OPTION_1_ID, "Default name", "Default name",
+ "Use default name for the objects")
+ a.setCheckable(True)
+ ag.add(a)
+ a = sgPyQt.createAction(GUIcontext.OPTION_2_ID, "Generate name", "Generate name",
+ "Generate name for the objects")
+ a.setCheckable(True)
+ ag.add(a)
+ a = sgPyQt.createAction(GUIcontext.OPTION_3_ID, "Ask name", "Ask name",
+ "Request object name from the user") # , "", 0, True)
+ a.setCheckable(True)
+ ag.add(a)
+ sgPyQt.createMenu(ag, mid)
+ sgPyQt.createTool(ag, tid)
+ default_mode = sgPyQt.integerSetting("GENERICSOLVER", "creation_mode", 0)
+ sgPyQt.action(GUIcontext.OPTION_1_ID + default_mode).setChecked(True)
# the following action are used in context popup
- a = sgPyQt.createAction( GUIcontext.DELETE_ALL_ID, "Delete all", "Delete all",
- "Delete all objects" )
- a = sgPyQt.createAction( GUIcontext.SET_VALUE_ID, "Set value", "Set Value",
- "Set a new value to variable" )
- a = sgPyQt.createAction( GUIcontext.SOLVER_ID, "Run Solver", "Run Solver",
- "Run Solver on selected case", "ExecGENERICSOLVER.png" )
+ a = sgPyQt.createAction(GUIcontext.DELETE_ALL_ID, "Delete all", "Delete all",
+ "Delete all objects")
+ a = sgPyQt.createAction(GUIcontext.SET_VALUE_ID, "Set value", "Set Value",
+ "Set a new value to variable")
+ a = sgPyQt.createAction(GUIcontext.SOLVER_ID, "Run Solver", "Run Solver",
+ "Run Solver on selected case", "ExecGENERICSOLVER.png")
################################################
# Global variables
################################################
# study-to-context map
-__study2context__ = {}
+__study2context__ = {}
# current context
__current_context__ = None
# object counter
# Internal methods
################################################
-###
+
+# ##
# get active study ID
-###
+# ##
def getStudyId():
return sgPyQt.getStudyId()
-###
+
+# ##
# get active study
-###
+# ##
def getStudy():
studyId = getStudyId()
- study = salome.myStudyManager.GetStudyByID( studyId )
+ study = salome.myStudyManager.GetStudyByID(studyId)
return study
-###
+
+# ##
# returns True if object has children
-###
-def hasChildren( sobj ):
+# ##
+def hasChildren(sobj):
if sobj:
study = getStudy()
- iter = study.NewChildIterator( sobj )
- while iter.More():
- name = iter.Value().GetName()
+ iterator = study.NewChildIterator(sobj)
+ while iterator.More():
+ name = iterator.Value().GetName()
if name:
return True
- iter.Next()
+ iterator.Next()
pass
pass
return False
-###
+
+# ##
# get current GUI context
-###
+# ##
def getContext():
global __current_context__
return __current_context__
-###
+
+# ##
# set and return current GUI context
# study ID is passed as parameter
-###
-def setContext( studyID ):
+# ##
+def setContext(studyID):
global __study2context__, __current_context__
- if not __study2context__.has_key(studyID):
+ if studyID not in __study2context__:
__study2context__[studyID] = GUIcontext()
pass
__current_context__ = __study2context__[studyID]
# Callback functions
################################################
+
# called when module is initialized
# perform initialization actions
def initialize():
logger.debug("GENERICSOLVERGUI.initialize() : study : %d" % getStudyId())
# set default preferences values
- if not sgPyQt.hasSetting( "GENERICSOLVER", "def_case_name"):
- sgPyQt.addSetting( "GENERICSOLVER", "def_case_name", GUIcontext.DEFAULT_CASE_NAME )
- if not sgPyQt.hasSetting( "GENERICSOLVER", "creation_mode"):
- sgPyQt.addSetting( "GENERICSOLVER", "creation_mode", 0 )
+ if not sgPyQt.hasSetting("GENERICSOLVER", "def_case_name"):
+ sgPyQt.addSetting("GENERICSOLVER", "def_case_name", GUIcontext.DEFAULT_CASE_NAME)
+ if not sgPyQt.hasSetting("GENERICSOLVER", "creation_mode"):
+ sgPyQt.addSetting("GENERICSOLVER", "creation_mode", 0)
pass
+
# called when module is initialized
# return map of popup windows to be used by the module
def windows():
logger.debug("GENERICSOLVERGUI.windows() : study : %d" % getStudyId())
wm = {}
wm[SalomePyQt.WT_ObjectBrowser] = QtCore.Qt.LeftDockWidgetArea
- wm[SalomePyQt.WT_PyConsole] = QtCore.Qt.BottomDockWidgetArea
+ wm[SalomePyQt.WT_PyConsole] = QtCore.Qt.BottomDockWidgetArea
return wm
+
# called when module is initialized
# return list of 2d/3d views to be used ny the module
def views():
logger.debug("GENERICSOLVERGUI.views() : study : %d" % getStudyId())
return []
+
# called when module is initialized
# export module's preferences
def createPreferences():
logger.debug("GENERICSOLVERGUI.createPreferences() : study : %d" % getStudyId())
- gid = sgPyQt.addPreference( "General" )
- gid = sgPyQt.addPreference( "Object creation", gid )
- pid = sgPyQt.addPreference( "Default case name", gid, SalomePyQt.PT_String,
- "GENERICSOLVER", "def_case_name" )
- pid = sgPyQt.addPreference( "Default creation mode", gid, SalomePyQt.PT_Selector,
- "GENERICSOLVER", "creation_mode" )
- strings = QtCore.QStringList()
- strings.append( "Default name" )
- strings.append( "Generate name" )
- strings.append( "Ask name" )
- indexes = []
- indexes.append( QtCore.QVariant(0) )
- indexes.append( QtCore.QVariant(1) )
- indexes.append( QtCore.QVariant(2) )
- sgPyQt.setPreferenceProperty( pid, "strings", QtCore.QVariant( strings ) )
- sgPyQt.setPreferenceProperty( pid, "indexes", QtCore.QVariant( indexes ) )
+ gid = sgPyQt.addPreference("General")
+ gid = sgPyQt.addPreference("Object creation", gid)
+ sgPyQt.addPreference("Default case name", gid, SalomePyQt.PT_String,
+ "GENERICSOLVER", "def_case_name")
+ pid = sgPyQt.addPreference("Default creation mode", gid, SalomePyQt.PT_Selector,
+ "GENERICSOLVER", "creation_mode")
+ strings = ["Default name", "Generate name", "Ask name"]
+ indexes = [0, 1, 2]
+ sgPyQt.setPreferenceProperty(pid, "strings", strings)
+ sgPyQt.setPreferenceProperty(pid, "indexes", indexes)
pass
+
# called when module is activated
# returns True if activating is successfull and False otherwise
def activate():
logger.debug("GENERICSOLVERGUI.activate() : study : %d" % getStudyId())
- ctx = setContext( getStudyId() )
+ setContext(getStudyId())
return True
+
# called when module is deactivated
def deactivate():
logger.debug("GENERICSOLVERGUI.deactivate() : study : %d" % getStudyId())
pass
+
# called when active study is changed
# active study ID is passed as parameter
-def activeStudyChanged( studyID ):
+def activeStudyChanged(studyID):
logger.debug("GENERICSOLVERGUI.activeStudyChanged(): study : %d" % studyID)
- ctx = setContext( getStudyId() )
+ setContext(getStudyId())
pass
+
# called when popup menu is invoked
# popup menu and menu context are passed as parameters
-def createPopupMenu( popup, context ):
+def createPopupMenu(popup, context):
logger.debug("GENERICSOLVERGUI.createPopupMenu(): context = %s" % context)
ed = getStudyEditor()
- ctx = setContext(ed.studyId)
- if salome.sg.SelectedCount() == 1: # one object is selected
+ setContext(ed.studyId)
+ if salome.sg.SelectedCount() == 1: # one object is selected
typeId = ed.getTypeId(ed.study.FindObjectID(salome.sg.getSelected(0)))
if typeId == GUIcontext.MODULE_ID:
# menu for component
- popup.addAction( sgPyQt.action( GUIcontext.DELETE_ALL_ID ) )
+ popup.addAction(sgPyQt.action(GUIcontext.DELETE_ALL_ID))
elif typeId == GUIcontext.CASE_ID:
# menu for case
- popup.addAction( sgPyQt.action( GUIcontext.SOLVER_ID ) )
+ popup.addAction(sgPyQt.action(GUIcontext.SOLVER_ID))
elif typeId == GUIcontext.VARIABLE_ID:
# menu for case
- popup.addAction( sgPyQt.action( GUIcontext.SET_VALUE_ID ) )
+ popup.addAction(sgPyQt.action(GUIcontext.SET_VALUE_ID))
+
# called when GUI action is activated
# action ID is passed as parameter
-def OnGUIEvent( commandID ):
+def OnGUIEvent(commandID):
logger.debug("GENERICSOLVERGUI.OnGUIEvent(): command = %d" % commandID)
- if dict_command.has_key( commandID ):
+ if commandID in dict_command:
try:
dict_command[commandID]()
except:
traceback.print_exc()
elif commandID in (GUIcontext.OPTION_1_ID, GUIcontext.OPTION_2_ID, GUIcontext.OPTION_3_ID):
- pass # Option selection does not trigger a method
+ pass # Option selection does not trigger a method
else:
logger.error("The command is not implemented: %d" % commandID)
pass
+
# called when module's preferences are changed
# preference's resources section and setting name are passed as parameters
-def preferenceChanged( section, setting ):
- logger.debug("GENERICSOLVERGUI.preferenceChanged(): %s / %s" % ( section, setting ))
+def preferenceChanged(section, setting):
+ logger.debug("GENERICSOLVERGUI.preferenceChanged(): %s / %s" % (section, setting))
pass
+
# called when active view is changed
# view ID is passed as parameter
-def activeViewChanged( viewID ):
+def activeViewChanged(viewID):
logger.debug("GENERICSOLVERGUI.activeViewChanged(): %d" % viewID)
pass
+
# called when active view is cloned
# cloned view ID is passed as parameter
-def viewCloned( viewID ):
+def viewCloned(viewID):
logger.debug("GENERICSOLVERGUI.viewCloned(): %d" % viewID)
pass
+
# called when active view is viewClosed
# view ID is passed as parameter
-def viewClosed( viewID ):
+def viewClosed(viewID):
logger.debug("GENERICSOLVERGUI.viewClosed(): %d" % viewID)
pass
# GUI actions implementation
################################################
-###
+
+# ##
# Create a deterministic case
-###
+# ##
def CreateCase():
logger.debug("GENERICSOLVERGUI.CreateCase : enter")
- default_case_name = str( sgPyQt.stringSetting( "GENERICSOLVER", "def_case_name",
- GUIcontext.DEFAULT_CASE_NAME ).strip() )
+ default_case_name = sgPyQt.stringSetting("GENERICSOLVER", "def_case_name",
+ GUIcontext.DEFAULT_CASE_NAME).strip()
global __id__
try:
- if sgPyQt.action( GUIcontext.OPTION_3_ID ).isChecked():
+ if sgPyQt.action(GUIcontext.OPTION_3_ID).isChecked():
# request object name from the user
- name, ok = QtGui.QInputDialog.getText(sgPyQt.getDesktop(),
- "Create case",
- "Enter case name:",
- QtWidgets.QLineEdit.Normal,
- default_case_name )
- if not ok: return
- name = str( name.strip() )
- elif sgPyQt.action( GUIcontext.OPTION_2_ID ).isChecked():
+ name, ok = QtWidgets.QInputDialog.getText(sgPyQt.getDesktop(),
+ "Create case",
+ "Enter case name:",
+ QtWidgets.QLineEdit.Normal,
+ default_case_name)
+ if not ok:
+ return
+ name = name.strip()
+ elif sgPyQt.action(GUIcontext.OPTION_2_ID).isChecked():
# generate object name
- __id__ = __id__ + 1
- name = "%s %d" % ( default_case_name, __id__ )
+ __id__ = __id__ + 1
+ name = "%s %d" % (default_case_name, __id__)
else:
name = default_case_name
pass
pass
- except:
+ except Exception as e:
+ logger.debug(e)
# generate object name
- __id__ = __id__ + 1
- name = "%s %d" % ( default_case_name, __id__ )
+ __id__ = __id__ + 1
+ name = "%s %d" % (default_case_name, __id__)
pass
- if not name: return
+ if not name:
+ return
ed = getStudyEditor()
- father = ed.findOrCreateComponent(GUIcontext.MODULE_NAME, icon = GUIcontext.MODULE_PIXMAP)
+ father = ed.findOrCreateComponent(GUIcontext.MODULE_NAME,
+ icon=GUIcontext.MODULE_PIXMAP)
ed.setTypeId(father, GUIcontext.MODULE_ID)
case = ed.findItem(father, name)
if case is None:
- case = ed.createItem(father, name, typeId = GUIcontext.CASE_ID)
- varE = ed.createItem(case, "E", typeId = GUIcontext.VARIABLE_ID)
+ case = ed.createItem(father, name, typeId=GUIcontext.CASE_ID)
+ varE = ed.createItem(case, "E", typeId=GUIcontext.VARIABLE_ID)
ed.setAttributeValue(varE, "AttributeReal", 210.e9)
- varF = ed.createItem(case, "F", typeId = GUIcontext.VARIABLE_ID)
+ varF = ed.createItem(case, "F", typeId=GUIcontext.VARIABLE_ID)
ed.setAttributeValue(varF, "AttributeReal", 1000.)
- varL = ed.createItem(case, "L", typeId = GUIcontext.VARIABLE_ID)
+ varL = ed.createItem(case, "L", typeId=GUIcontext.VARIABLE_ID)
ed.setAttributeValue(varL, "AttributeReal", 1.5)
- varI = ed.createItem(case, "I", typeId = GUIcontext.VARIABLE_ID)
+ varI = ed.createItem(case, "I", typeId=GUIcontext.VARIABLE_ID)
ed.setAttributeValue(varI, "AttributeReal", 2.e-6)
inputVarList = [study_exchange_vars.Variable("E"),
study_exchange_vars.Variable("I")]
outputVarList = [study_exchange_vars.Variable("dev")]
exchVars = study_exchange_vars.ExchangeVariables(inputVarList, outputVarList)
- study_exchange_vars.createSObjectForExchangeVariables(case, exchVars, icon = VARS_ICON)
+ study_exchange_vars.createSObjectForExchangeVariables(case, exchVars, icon=VARS_ICON)
- salome.sg.updateObjBrowser( True )
+ salome.sg.updateObjBrowser(True)
logger.debug("GENERICSOLVERGUI.CreateCase : exit")
-###
+
+# ##
# Run the SOLVER
-###
+# ##
def RunSOLVER():
ed = getStudyEditor()
# Get selected case
# Initialize and run the solver
solver_engine = salome.lcc.FindOrLoadComponent("FactoryServer", SOLVER_ENGINE_NAME)
+ assert solver_engine
solver_engine.Init(getStudyId(), entry)
- param_input = SALOME_TYPES.ParametricInput(inputVarList = [],
- outputVarList = ["dev"],
- inputValues = [[[]]],
- specificParameters = [])
+ param_input = SALOME_TYPES.ParametricInput(inputVarList=[],
+ outputVarList=["dev"],
+ inputValues=[[[]]],
+ specificParameters=[])
error = None
try:
param_output = solver_engine.Exec(param_input)
- except SALOME.SALOME_Exception, exc:
+ except SALOME.SALOME_Exception as exc:
error = exc.details.text
solver_engine.Finalize()
if error is not None:
- QtGui.QMessageBox.critical(sgPyQt.getDesktop(), "Error", error)
+ QtWidgets.critical(sgPyQt.getDesktop(), "Error", error)
elif param_output.returnCode != 0:
- QtGui.QMessageBox.critical(sgPyQt.getDesktop(), "Error", param_output.errorMessage)
+ QtWidgets.critical(sgPyQt.getDesktop(), "Error", param_output.errorMessage)
else:
# Add result to deterministic case in object browser
var = ed.findOrCreateItem(sobj, "Deviation")
ed.setAttributeValue(var, "AttributeReal", param_output.outputValues[0][0][0][0])
- salome.sg.updateObjBrowser(0)
+ salome.sg.updateObjBrowser(False)
+
-###
+# ##
# Delete all objects
-###
+# ##
def DeleteAll():
study = getStudy()
- father = study.FindComponent( GUIcontext.MODULE_NAME )
+ father = study.FindComponent(GUIcontext.MODULE_NAME)
if father:
- iter = study.NewChildIterator( father )
+ iterator = study.NewChildIterator(father)
builder = study.NewBuilder()
- while iter.More():
- sobj = iter.Value()
- iter.Next()
- builder.RemoveObjectWithChildren( sobj )
+ while iterator.More():
+ sobj = iterator.Value()
+ iterator.Next()
+ builder.RemoveObjectWithChildren(sobj)
pass
- salome.sg.updateObjBrowser( True )
+ salome.sg.updateObjBrowser(True)
pass
pass
-###
+
+# ##
# Set value to variable
-###
+# ##
def SetValue():
ed = getStudyEditor()
entry = salome.sg.getSelected(0)
assert sobj
oldvalue = ed.getAttributeValue(sobj, "AttributeReal", 0.0)
name, ok = QtWidgets.QInputDialog.getText(sgPyQt.getDesktop(),
- "Set a value",
- "Enter new value:",
- QtWidgets.QLineEdit.Normal,
- str(oldvalue) )
- value = float( name.strip() )
- if not ok or not value: return
+ "Set a value",
+ "Enter new value:",
+ QtWidgets.QLineEdit.Normal,
+ '%f' % oldvalue)
+ try:
+ value = float(name.strip())
+ except ValueError:
+ value = None
+ if not ok or value is None:
+ return
ed.setAttributeValue(sobj, "AttributeReal", value)
- salome.sg.updateObjBrowser(0)
+ salome.sg.updateObjBrowser(False)
-###
+# ##
# Commands dictionary
-###
+# ##
dict_command = {
- GUIcontext.SOLVER_ID : RunSOLVER,
- GUIcontext.CREATE_CASE_ID : CreateCase,
- GUIcontext.DELETE_ALL_ID : DeleteAll,
- GUIcontext.SET_VALUE_ID : SetValue,
+ GUIcontext.SOLVER_ID: RunSOLVER,
+ GUIcontext.CREATE_CASE_ID: CreateCase,
+ GUIcontext.DELETE_ALL_ID: DeleteAll,
+ GUIcontext.SET_VALUE_ID: SetValue,
}