X-Git-Url: http://git.salome-platform.org/gitweb/?a=blobdiff_plain;f=src%2FGENERICSOLVERGUI%2FGENERICSOLVERGUI.py;h=e49856a9810dea94df1482b9e07747d912f4e4da;hb=139f89180bcee1113e5406e485016fa018417451;hp=3ccc72c5e72b11e21fe873fae2a5b675a6030a00;hpb=4a890ef78d8733d7a2b57ecc2012f7b0d8a63ea4;p=samples%2Fgenericsolver.git diff --git a/src/GENERICSOLVERGUI/GENERICSOLVERGUI.py b/src/GENERICSOLVERGUI/GENERICSOLVERGUI.py index 3ccc72c..e49856a 100644 --- a/src/GENERICSOLVERGUI/GENERICSOLVERGUI.py +++ b/src/GENERICSOLVERGUI/GENERICSOLVERGUI.py @@ -1,798 +1,482 @@ -# Copyright (C) 2009-2010 EDF R&D +# Copyright (C) 2009-2024 EDF # -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License. +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. # -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. # -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # # $Id$ # +import logging import traceback -import os -from PyQt4.QtGui import * -from PyQt4.QtCore import * +from PyQt5 import QtCore, QtGui, QtWidgets +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 import salome -import SALOMEDS -import GENERICSOLVER_ORB + +import SalomePyQt + + +# Get SALOME PyQt interface +sgPyQt = SalomePyQt.SalomePyQt() + +logger = Logger("GENERICSOLVERGUI", color=termcolor.RED_FG) salome.salome_init() +VARS_ICON = "icon_variables.png" +SOLVER_ENGINE_NAME = "DEVIATION" + ################################################ # GUI context class # 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 - OBJECT_ID = 1010 - CASE_ID = 1020 - VARIABLE_ID = 1030 - FOREIGN_ID = -1 + MODULE_ID = 1000 + CASE_ID = 1020 + VARIABLE_ID = 1030 # menus/toolbars/actions IDs - GENERICSOLVER_MENU_ID = 90 - SOLVER_ID = 941 - CREATE_OBJECT_ID = 942 - OPTIONS_ID = 943 - OPTION_1_ID = 944 - OPTION_2_ID = 945 - OPTION_3_ID = 946 - GENERICSOLVER_TB_ID = 90 - DELETE_ALL_ID = 951 - SHOW_ME_ID = 952 - DELETE_ME_ID = 953 - RENAME_ME_ID = 954 - 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_NAME = "Object" - 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.SOLVER_ID, "Run Solver", "Run Solver", "Run Solver on selected case", "ExecGENERICSOLVER.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 ) - #a = sgPyQt.createAction( GUIcontext.CREATE_OBJECT_ID, "Create object", "Create object", "Create object" ) - #sgPyQt.createMenu( a, mid ) - #a = sgPyQt.createAction( GUIcontext.CREATE_CASE_ID, "Create case", "Create case", "Create case" ) - #sgPyQt.createMenu( a, mid ) - a = sgPyQt.createSeparator() - sgPyQt.createMenu( a, mid ) - try: - 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 ) - except: - pass + 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") # , "", 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.SHOW_ME_ID, "Show", "Show", "Show object name" ) - a = sgPyQt.createAction( GUIcontext.DELETE_ME_ID, "Delete", "Delete", "Remove object" ) - a = sgPyQt.createAction( GUIcontext.RENAME_ME_ID, "Rename", "Rename", "Rename object" ) - a = sgPyQt.createAction( GUIcontext.SET_VALUE_ID, "Set value", "Set Value", "Set a new value to variable" ) - pass - pass + 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 -global __id__ __id__ = 0 -################################################ - -# Get SALOME PyQt interface -import SalomePyQt -sgPyQt = SalomePyQt.SalomePyQt() - -# Get SALOME Swig interface -import libSALOME_Swig -sg = libSALOME_Swig.SALOMEGUI_Swig() - ################################################ # Internal methods ################################################ -### -# Check verbose mode -### -__verbose__ = None -def verbose(): - global __verbose__ - if __verbose__ is None: - try: - __verbose__ = int( os.getenv('SALOME_VERBOSE', 0) ) - except: - __verbose__ = 0 - pass - pass - return __verbose__ - -### -# get GENERICSOLVER engine -### -def getEngine(): - engine = salome.lcc.FindOrLoadComponent( "FactoryServerPy", GUIcontext.MODULE_NAME ) - return engine -### +# ## # 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 -### -# finds or creates component object -### -def findOrCreateComponent(): - study = getStudy() - father = study.FindComponent( GUIcontext.MODULE_NAME ) - if father is None: - builder = study.NewBuilder() - father = builder.NewComponent( GUIcontext.MODULE_NAME ) - attr = builder.FindOrCreateAttribute( father, "AttributeName" ) - attr.SetValue( GUIcontext.MODULE_NAME ) - attr = builder.FindOrCreateAttribute( father, "AttributePixMap" ) - attr.SetPixMap( GUIcontext.MODULE_PIXMAP ) - attr = builder.FindOrCreateAttribute( father, "AttributeLocalID" ) - attr.SetValue( GUIcontext.MODULE_ID ) - try: - builder.DefineComponentInstance( father, getEngine() ) - pass - except: - pass - pass - return father -### +# ## # 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] return __current_context__ -### -# increment object counter in the map -### -def _incObjToMap( m, id ): - if id not in m: m[id] = 0 - m[id] += 1 - pass - -### -# analyse selection -### -def getSelection(): - selcount = sg.SelectedCount() - seltypes = {} - study = getStudy() - for i in range( selcount ): - entry = sg.getSelected( i ) - if entry: - sobj = study.FindObjectID( entry ) - if sobj is not None: - test, anAttr = sobj.FindAttribute( "AttributeLocalID" ) - if test: - ID = anAttr._narrow( SALOMEDS.AttributeLocalID ).Value() - if ID >= 0: - _incObjToMap( seltypes, ID ) - continue - pass - pass - pass - _incObjToMap( seltypes, GUIcontext.FOREIGN_ID ) - pass - return selcount, seltypes - ################################################ # Callback functions ################################################ + # called when module is initialized # perform initialization actions def initialize(): - if verbose() : print "GENERICSOLVERGUI.initialize() : study : %d" % getStudyId() + logger.debug("GENERICSOLVERGUI.initialize() : study : %d" % getStudyId()) # set default preferences values - if not sgPyQt.hasSetting( "GENERICSOLVER", "def_obj_name"): - sgPyQt.addSetting( "GENERICSOLVER", "def_obj_name", GUIcontext.DEFAULT_NAME ) - 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(): - if verbose() : print "GENERICSOLVERGUI.windows() : study : %d" % getStudyId() + logger.debug("GENERICSOLVERGUI.windows() : study : %d" % getStudyId()) wm = {} - wm[SalomePyQt.WT_ObjectBrowser] = Qt.LeftDockWidgetArea - wm[SalomePyQt.WT_PyConsole] = Qt.BottomDockWidgetArea + wm[SalomePyQt.WT_ObjectBrowser] = QtCore.Qt.LeftDockWidgetArea + 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(): - if verbose() : print "GENERICSOLVERGUI.views() : study : %d" % getStudyId() + logger.debug("GENERICSOLVERGUI.views() : study : %d" % getStudyId()) return [] + # called when module is initialized # export module's preferences def createPreferences(): - if verbose() : print "GENERICSOLVERGUI.createPreferences() : study : %d" % getStudyId() - gid = sgPyQt.addPreference( "General" ) - gid = sgPyQt.addPreference( "Object creation", gid ) - pid = sgPyQt.addPreference( "Default object name", gid, SalomePyQt.PT_String, "GENERICSOLVER", "def_obj_name" ) - 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 = QStringList() - strings.append( "Default name" ) - strings.append( "Generate name" ) - strings.append( "Ask name" ) - indexes = [] - indexes.append( QVariant(0) ) - indexes.append( QVariant(1) ) - indexes.append( QVariant(2) ) - sgPyQt.setPreferenceProperty( pid, "strings", QVariant( strings ) ) - sgPyQt.setPreferenceProperty( pid, "indexes", QVariant( indexes ) ) + logger.debug("GENERICSOLVERGUI.createPreferences() : study : %d" % getStudyId()) + 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(): - if verbose() : print "GENERICSOLVERGUI.activate() : study : %d" % getStudyId() - ctx = setContext( getStudyId() ) + logger.debug("GENERICSOLVERGUI.activate() : study : %d" % getStudyId()) + setContext(getStudyId()) return True + # called when module is deactivated def deactivate(): - if verbose() : print "GENERICSOLVERGUI.deactivate() : study : %d" % getStudyId() + logger.debug("GENERICSOLVERGUI.deactivate() : study : %d" % getStudyId()) pass + # called when active study is changed # active study ID is passed as parameter -def activeStudyChanged( studyID ): - if verbose() : print "GENERICSOLVERGUI.activeStudyChanged(): study : %d" % studyID - ctx = setContext( getStudyId() ) +def activeStudyChanged(studyID): + logger.debug("GENERICSOLVERGUI.activeStudyChanged(): study : %d" % studyID) + setContext(getStudyId()) pass + # called when popup menu is invoked # popup menu and menu context are passed as parameters -def createPopupMenu( popup, context ): - if verbose() : print "GENERICSOLVERGUI.createPopupMenu(): context = %s" % context - ctx = setContext( getStudyId() ) - study = getStudy() - selcount, selected = getSelection() - print selcount, selected - if selcount == 1: - # one object is selected - if GUIcontext.MODULE_ID in selected: +def createPopupMenu(popup, context): + logger.debug("GENERICSOLVERGUI.createPopupMenu(): context = %s" % context) + ed = getStudyEditor() + 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 ) ) -## elif GUIcontext.OBJECT_ID in selected: -## # menu for object -## popup.addAction( sgPyQt.action( GUIcontext.SHOW_ME_ID ) ) -## popup.addAction( sgPyQt.action( GUIcontext.RENAME_ME_ID ) ) -## popup.addSeparator() -## popup.addAction( sgPyQt.action( GUIcontext.DELETE_ME_ID ) ) - elif GUIcontext.CASE_ID in selected: + popup.addAction(sgPyQt.action(GUIcontext.DELETE_ALL_ID)) + elif typeId == GUIcontext.CASE_ID: # menu for case - popup.addAction( sgPyQt.action( GUIcontext.SOLVER_ID ) ) - elif GUIcontext.VARIABLE_ID in selected: + 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.RENAME_ME_ID ) ) - pass - pass - elif selcount > 1: - # several objects are selected - if len( selected ) == 1: - if GUIcontext.MODULE_ID in selected: - # menu for component - popup.addAction( sgPyQt.action( GUIcontext.DELETE_ALL_ID ) ) -## elif GUIcontext.OBJECT_ID in selected: -## # menu for list of objects -## popup.addAction( sgPyQt.action( GUIcontext.DELETE_ME_ID ) ) -## pass - pass - pass - pass + popup.addAction(sgPyQt.action(GUIcontext.SET_VALUE_ID)) + # called when GUI action is activated # action ID is passed as parameter -def OnGUIEvent( commandID ): - if verbose() : print "GENERICSOLVERGUI.OnGUIEvent(): command = %d" % commandID - if dict_command.has_key( commandID ): +def OnGUIEvent(commandID): + logger.debug("GENERICSOLVERGUI.OnGUIEvent(): command = %d" % 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 else: - if verbose() : print "The command is not implemented: %d" % commandID + 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 ): - if verbose() : print "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 ): - if verbose() : print "GENERICSOLVERGUI.activeViewChanged(): %d" % 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 ): - if verbose() : print "GENERICSOLVERGUI.viewCloned(): %d" % 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 ): - if verbose() : print "GENERICSOLVERGUI.viewClosed(): %d" % viewID +def viewClosed(viewID): + logger.debug("GENERICSOLVERGUI.viewClosed(): %d" % viewID) pass ################################################ # GUI actions implementation ################################################ -### -# 'SOLVER' dialog box -### -##class MyDialog( QDialog ): -## # constructor -## def __init__( self, parent = None, modal = 0): -## QDialog.__init__( self, parent ) -## self.setObjectName( "MyDialog" ) -## self.setModal( modal ) -## self.setWindowTitle( "SOLVER!" ) -## vb = QVBoxLayout( self ) -## vb.setMargin( 8 ) - -## hb0 = QHBoxLayout( self ) -## label = QLabel( "Prenom: ", self ) -## hb0.addWidget( label ) -## self.entry = QLineEdit( self ) -## self.entry.setMinimumWidth( 200 ) -## hb0.addWidget( self.entry ) -## vb.addLayout( hb0 ) - -## hb1 = QHBoxLayout( self ) -## bOk = QPushButton( "&OK", self ) -## self.connect( bOk, SIGNAL( 'clicked()' ), self, SLOT( 'accept()' ) ) -## hb1.addWidget( bOk ) - -## hb1.addStretch( 10 ) - -## bCancel = QPushButton( "&Cancel", self ) -## self.connect( bCancel, SIGNAL( 'clicked()' ), self, SLOT( 'close()' ) ) -## hb1.addWidget( bCancel ) - -## vb.addLayout( hb1 ) -## pass - -## # OK button slot -## def accept( self ): -## name = str( self.entry.text() ) -## if name != "": -## inPoint = [1, 2, 3] -## outPoint = [0, 0] -## print "GENERICSOLVERGUI.accept (1): inPoint = ", inPoint -## print "GENERICSOLVERGUI.accept (1): outPoint = ", outPoint -## (ok,outPoint) = getEngine().Exec( inPoint, outPoint ) -## QMessageBox.information( self, 'Info', "Exec() method returned %d" % ok ) -## print "GENERICSOLVERGUI.accept (2): inPoint = ", inPoint -## print "GENERICSOLVERGUI.accept (2): outPoint = ", outPoint -## self.close() -## else: -## QMessageBox.warning( self, 'Error!', 'Please, enter the name!' ) -## pass - -### -# Plays with study -### -def addObjectInStudy( builder, father, objname, objid ): - obj = getSubSObjectByName( father, objname ) - if obj is None: - obj = builder.NewObject( father ) - attr = builder.FindOrCreateAttribute( obj, "AttributeName" ) - attr.SetValue( objname ) - attr = builder.FindOrCreateAttribute( obj, "AttributeLocalID" ) - attr.SetValue( objid ) - return obj - -def setValueToVariable( builder, varobj, value ): - attr = builder.FindOrCreateAttribute( varobj, "AttributeLocalID" ) - objid = attr.Value() - if (objid == GUIcontext.VARIABLE_ID): - attr = builder.FindOrCreateAttribute( varobj, "AttributeReal" ) - attr.SetValue( value ) - else: - attr = builder.FindOrCreateAttribute( varobj, "AttributeName" ) - QMessageBox.information( sgPyQt.getDesktop(), 'Info', "Object '%s' isn't a variable. Can't set value." % attr.Value() ) - pass - -def getValueOfVariable( builder, varobj ): - attr = builder.FindOrCreateAttribute( varobj, "AttributeLocalID" ) - objid = attr.Value() - if (objid == GUIcontext.VARIABLE_ID): - attr = builder.FindOrCreateAttribute( varobj, "AttributeReal" ) - return attr.Value() - else: - attr = builder.FindOrCreateAttribute( varobj, "AttributeName" ) - QMessageBox.information( sgPyQt.getDesktop(), 'Info', "Object '%s' isn't a variable. Can't set value." % attr.Value() ) - return 0. - -def getSubSObjectByName( sobjFather, childName ): - study = getStudy() - iter = study.NewChildIterator( sobjFather ) - #builder = study.NewBuilder() - while iter.More(): - sobj = iter.Value() - if sobj.GetName() == childName: - return sobj - iter.Next() - pass - return None -### +# ## # Create a deterministic case -### +# ## def CreateCase(): - print "GENERICSOLVERGUI.CreateCase : enter" - default_case_name = str( sgPyQt.stringSetting( "GENERICSOLVER", "def_case_name", GUIcontext.DEFAULT_CASE_NAME ).trimmed() ) + logger.debug("GENERICSOLVERGUI.CreateCase : enter") + 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 = QInputDialog.getText( sgPyQt.getDesktop(), - "Create case", - "Enter case name:", - QLineEdit.Normal, - default_case_name ) - if not ok: return - name = str( name.trimmed() ) - 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 - global __id__ - __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 - global __id__ - __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 - study = getStudy() - builder = study.NewBuilder() - father = findOrCreateComponent() - case = addObjectInStudy( builder, father, name, GUIcontext.CASE_ID ) - varE = addObjectInStudy( builder, case, "E", GUIcontext.VARIABLE_ID ) - setValueToVariable( builder, varE, 210.e9 ) - varF = addObjectInStudy( builder, case, "F", GUIcontext.VARIABLE_ID ) - setValueToVariable( builder, varF, 1000. ) - varL = addObjectInStudy( builder, case, "L", GUIcontext.VARIABLE_ID ) - setValueToVariable( builder, varL, 1.5 ) - varI = addObjectInStudy( builder, case, "I", GUIcontext.VARIABLE_ID ) - setValueToVariable( builder, varI, 2.e-6 ) - sg.updateObjBrowser( True ) - print "GENERICSOLVERGUI.CreateCase : exit" - pass - -### -# Get the selected deterministic case -### -def GetSelectedCase(): - entry = sg.getSelected( 0 ) - if entry != '': - study = getStudy() - sobj = study.FindObjectID( entry ) - if ( sobj ): - test, attr = sobj.FindAttribute( "AttributeLocalID" ) - print "GENERICSOLVERGUI.GetSelectedCase : test=%d attr=%d" % (test,attr.Value()) - if attr.Value() == GUIcontext.CASE_ID: # This is a case entry - if hasChildren( sobj ): - return entry - else: - print "GENERICSOLVERGUI.GetSelectedCase : ERROR! no child for case" - pass - else: - print "GENERICSOLVERGUI.GetSelectedCase : ERROR! not a case" - pass - else: - print "GENERICSOLVERGUI.GetSelectedCase : ERROR! selected object not found in study" - pass - else: - print "GENERICSOLVERGUI.GetSelectedCase : ERROR! no selection" - return None - -### -# Retrieve data from selected case -### -def GetDataFromCase( caseEntry ): - theCase = [] - study = getStudy() - case = study.FindObjectID( caseEntry ) - builder = study.NewBuilder() - # Get the values of the variables and make them a list - for name in ("E", "F", "L", "I"): - var = getSubSObjectByName( case, name ) - if var == None: - print "GENERICSOLVERGUI.GetDataFromCase : ERROR! no variable '%s'" % name - break - theCase.append( getValueOfVariable( builder, var ) ) - return theCase - -### -# Add some variable to the case -### -def AddDataToCase( caseEntry, varName, varValue ): - study = getStudy() - case = study.FindObjectID( caseEntry ) - builder = study.NewBuilder() - var = addObjectInStudy( builder, case, varName, GUIcontext.VARIABLE_ID ) - setValueToVariable( builder, var, varValue ) - sg.updateObjBrowser( True ) - pass - -### + if not name: + return + ed = getStudyEditor() + 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) + ed.setAttributeValue(varE, "AttributeReal", 210.e9) + varF = ed.createItem(case, "F", typeId=GUIcontext.VARIABLE_ID) + ed.setAttributeValue(varF, "AttributeReal", 1000.) + varL = ed.createItem(case, "L", typeId=GUIcontext.VARIABLE_ID) + ed.setAttributeValue(varL, "AttributeReal", 1.5) + 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("F"), + study_exchange_vars.Variable("L"), + 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) + + salome.sg.updateObjBrowser(True) + logger.debug("GENERICSOLVERGUI.CreateCase : exit") + + +# ## # Run the SOLVER -### +# ## def RunSOLVER(): - case = GetSelectedCase() - getEngine().Init( getStudyId(), case, "" ) - - inPoint = GetDataFromCase( case )[:2] - print "GENERICSOLVERGUI.RunSOLVER (1): inPoint = ", inPoint - (ok, outPoint) = getEngine().Exec(inPoint) - print "GENERICSOLVERGUI.RunSOLVER (2): inPoint = ", inPoint - print "GENERICSOLVERGUI.RunSOLVER (2): outPoint = ", outPoint - AddDataToCase( case, "Deviation", outPoint[0] ) - - getEngine().Finalize() - pass + ed = getStudyEditor() + # Get selected case + entry = salome.sg.getSelected(0) + assert entry is not None + sobj = ed.study.FindObjectID(entry) + assert sobj + assert ed.getTypeId(sobj) == GUIcontext.CASE_ID + assert hasChildren(sobj) + + # 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=[]) + error = None + + try: + param_output = solver_engine.Exec(param_input) + except SALOME.SALOME_Exception as exc: + error = exc.details.text + solver_engine.Finalize() -### -# Create new object -### -##def CreateObject(): -## default_name = str( sgPyQt.stringSetting( "GENERICSOLVER", "def_obj_name", GUIcontext.DEFAULT_NAME ).trimmed() ) -## try: -## if sgPyQt.action( GUIcontext.OPTION_3_ID ).isChecked(): -## # request object name from the user -## name, ok = QInputDialog.getText( sgPyQt.getDesktop(), -## "Create Object", -## "Enter object name:", -## QLineEdit.Normal, -## default_name ) -## if not ok: return -## name = str( name.trimmed() ) -## elif sgPyQt.action( GUIcontext.OPTION_2_ID ).isChecked(): -## # generate object name -## global __id__ -## __id__ = __id__ + 1 -## name = "%s %d" % ( default_name, __id__ ) -## else: -## name = default_name -## pass -## pass -## except: -## # generate object name -## global __id__ -## __id__ = __id__ + 1 -## name = "%s %d" % ( default_name, __id__ ) -## pass -## if not name: return -## study = getStudy() -## builder = study.NewBuilder() -## father = findOrCreateComponent() -## obj = addObjectInStudy( builder, father, name, GUIcontext.OBJECT_ID ) -## sg.updateObjBrowser( True ) -## pass - -### + if error is not None: + QtWidgets.critical(sgPyQt.getDesktop(), "Error", error) + elif param_output.returnCode != 0: + 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(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 ) - pass - sg.updateObjBrowser( True ) - pass - pass - -### -# Show object's name -### -def ShowMe(): - study = getStudy() - entry = sg.getSelected( 0 ) - if entry != '': - sobj = study.FindObjectID( entry ) - if ( sobj ): - test, attr = sobj.FindAttribute( "AttributeName" ) - if test: - QMessageBox.information( sgPyQt.getDesktop(), 'Info', "My name is '%s'" % attr.Value() ) - pass - pass - pass - pass - -### -# Delete selected object(s) -### -def Delete(): - study = getStudy() - builder = study.NewBuilder() - if sg.SelectedCount() <= 0: return - for i in range( sg.SelectedCount() ): - entry = sg.getSelected( i ) - if entry != '': - sobj = study.FindObjectID( entry ) - if ( sobj ): - builder.RemoveObject( sobj ) - pass + while iterator.More(): + sobj = iterator.Value() + iterator.Next() + builder.RemoveObjectWithChildren(sobj) pass + salome.sg.updateObjBrowser(True) pass - sg.updateObjBrowser( True ) pass -### -# Rename selected object -### -def Rename(): - study = getStudy() - builder = study.NewBuilder() - entry = sg.getSelected( 0 ) - if entry != '': - sobj = study.FindObjectID( entry ) - if ( sobj ): - name, ok = QInputDialog.getText( sgPyQt.getDesktop(), - "Object name", - "Enter object name:", - QLineEdit.Normal, - sobj.GetName() ) - name = str( name.trimmed() ) - if not ok or not name: return - attr = builder.FindOrCreateAttribute( sobj, "AttributeName" ) - attr.SetValue( name ) - sg.updateObjBrowser( True ) - pass - pass - pass -### +# ## # Set value to variable -### +# ## def SetValue(): - study = getStudy() - builder = study.NewBuilder() - entry = sg.getSelected( 0 ) - if entry != '': - sobj = study.FindObjectID( entry ) - if ( sobj ): - name, ok = QInputDialog.getText( sgPyQt.getDesktop(), - "Set a value", - "Enter new value:", - QLineEdit.Normal, - str(getValueOfVariable( builder, sobj)) ) - value = float( name.trimmed() ) - if not ok or not value: return - setValueToVariable( builder, sobj, value ) - sg.updateObjBrowser( True ) - pass - pass - pass - -### + ed = getStudyEditor() + entry = salome.sg.getSelected(0) + assert entry is not None + sobj = ed.study.FindObjectID(entry) + 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, + '%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(False) + +# ## # Commands dictionary -### +# ## dict_command = { - GUIcontext.SOLVER_ID : RunSOLVER, - GUIcontext.CREATE_CASE_ID : CreateCase, -## GUIcontext.CREATE_OBJECT_ID : CreateObject, - GUIcontext.DELETE_ALL_ID : DeleteAll, - GUIcontext.SHOW_ME_ID : ShowMe, - GUIcontext.DELETE_ME_ID : Delete, - GUIcontext.RENAME_ME_ID : Rename, - GUIcontext.SET_VALUE_ID : SetValue, + GUIcontext.SOLVER_ID: RunSOLVER, + GUIcontext.CREATE_CASE_ID: CreateCase, + GUIcontext.DELETE_ALL_ID: DeleteAll, + GUIcontext.SET_VALUE_ID: SetValue, }