Beispiel #1
0
    def extractCurrentModule(
        self, _editor, _moduleType, _moduleName
    ):  #editor,_moduleType='Plugin',_moduleName=['Name','Contact']

        moduleName = []
        try:
            if _moduleName[0] == '' and _moduleName[1] == '':
                moduleName = []
            else:
                moduleName = _moduleName
        except:
            moduleName = _moduleName

        # print 'ecm _moduleType,moduleName=',(_moduleType,moduleName)
        moduleBegin, moduleEnd = self.cc3dmlHelper.findModuleLine(
            _editor=_editor, _moduleType=_moduleType, _moduleName=moduleName)
        # moduleBegin,moduleEnd=self.cc3dmlHelper.findModuleLine(_editor=_editor,_moduleType=_moduleType,_moduleName=_moduleName)

        # print 'ecm moduleBegin,moduleEnd=',(moduleBegin,moduleEnd)
        snippet = self.extractSnippet(_editor, moduleBegin, moduleEnd)

        # print 'EXTRACT moduleBegin,moduleEnd=',(moduleBegin,moduleEnd)
        if moduleBegin < 0 and moduleEnd < 0:
            return None, moduleBegin, moduleEnd

        cc3dXML2ObjConverter = XMLUtils.Xml2Obj()
        try:
            root_element = cc3dXML2ObjConverter.ParseString(snippet)
        except xml.parsers.expat.ExpatError, e:
            QMessageBox.critical(self.__ui, "Error Parsing CC3DML String ",
                                 e.__str__())
            raise UserWarning(e.__str__())
Beispiel #2
0
    def readFromXML(self,_fileName):
        import XMLUtils    
        xml2ObjConverter = XMLUtils.Xml2Obj()
        root_element=xml2ObjConverter.Parse(_fileName)
        settingsElemList=XMLUtils.CC3DXMLListPy(root_element.getElements("Settings"))
        
        readType2executeType={'int':'setting.XML2Int',
        'float':'setting.XML2Float',
        'str':'setting.XML2Str',
        'bool':'setting.XML2Bool',
        'strlist':'setting.XML2Strlist',
        'dict':'setting.XML2Dict',
        'color':'setting.XML2Color',
        'size':'setting.XML2Size',
        'point':'setting.XML2Point',
        'bytearray':'setting.XML2ByteArray'
        }        
            
        for elem in settingsElemList:
            type = elem.getAttribute("Type")
            # print type
                
            if type in readType2executeType.keys():
            # ['int','float','str','color','size','point']:
                elementList = XMLUtils.CC3DXMLListPy(elem.getElements(""))
                for el in elementList:
                
                    setting = Setting(el.name,el.cdata,type)
                    setting.fromXML(el)
                    

                    self.setSetting(setting.name,setting.value,setting.type)             
Beispiel #3
0
    def saveAsXML(self, _fileName):
        print '_fileName=',_fileName
        import XMLUtils
        from XMLUtils import ElementCC3D
        import Version
        xml2ObjConverter = XMLUtils.Xml2Obj()
        plSetElem = ElementCC3D('PlayerSettings',{'version':Version.getVersionAsString()})
        # print '\n\n\nself.__typeSettingDictDict.keys() = ', self.__typeSettingDictDict.keys()
        # print '__typeSettingDictDict=',self.__typeSettingDictDict
        for typeName , settingDict in self.__typeSettingDictDict.iteritems():

            typeContainerElem = plSetElem.ElementCC3D( 'Settings', {'Type':typeName} )
            # print 'typeName=',typeName
            # if typeName =='FieldParams':
            #     print 'typeName=',typeName, ' settingDict=',settingDict

            for settingName, setting in sorted(settingDict.iteritems()):  # keys are sorted before outputting to XML
                # if settingName=='ShowPlotAxes':
                #
                #     try:
                #         print 'settingName=', settingName, ' setting=', setting, 'typeContainerElem=',typeName
                #     except:
                #         pass

                setting.toXML(typeContainerElem)

        fileFullPath = os.path.abspath(_fileName)
        plSetElem.CC3DXMLElement.saveXML(fileFullPath)
Beispiel #4
0
def loadSettings(filename):

    if os.path.isfile(filename):
        import XMLUtils
        xml2ObjConverter = XMLUtils.Xml2Obj()

        fileFullPath = os.path.abspath(filename)
        settings = CustomSettings()        
        settings.readFromXML(filename)
        
        return settings
        
    return None 
    def getCellTypeData(self):
        import XMLUtils
        import xml
        from XMLUtils import dictionaryToMapStrStr as d2mss
        editor = self.__ui.getCurrentEditor()

        cc3dXML2ObjConverter = XMLUtils.Xml2Obj()
        try:
            root_element = cc3dXML2ObjConverter.ParseString(str(editor.text()))
        except xml.parsers.expat.ExpatError, e:
            QMessageBox.critical(self.__ui, "Error Parsing CC3DML file",
                                 e.__str__())
            print 'GOT PARSING ERROR:', e
            return
Beispiel #6
0
    def saveAsXML(self, _fileName):
        import XMLUtils
        from XMLUtils import ElementCC3D
        import Version
        xml2ObjConverter = XMLUtils.Xml2Obj()
        plSetElem = ElementCC3D('PlayerSettings',
                                {'version': Version.getVersionAsString()})
        # print '\n\n\nself.__typeSettingDictDict.keys() = ', self.__typeSettingDictDict.keys()
        for typeName, settingDict in self.__typeSettingDictDict.iteritems():

            typeContainerElem = plSetElem.ElementCC3D('Settings',
                                                      {'Type': typeName})

            for settingName, setting in sorted(settingDict.iteritems(
            )):  # keys are sorted before outputting to XML
                setting.toXML(typeContainerElem)

        fileFullPath = os.path.abspath(_fileName)
        plSetElem.CC3DXMLElement.saveXML(fileFullPath)
    def getPottsData(self):
        import XMLUtils
        import xml
        from XMLUtils import dictionaryToMapStrStr as d2mss
        editor = self.__ui.getCurrentEditor()

        gpd = {}
        # default values
        gpd['Dim'] = [0, 0, 0]
        gpd['Temperature'] = 0
        gpd['NeighborOrder'] = 1
        gpd['MCS'] = 10000
        gpd['SimulationName'] = 'PLEASE_PUT_SIMULATION_FILE_NAME_HERE'
        gpd['LatticeType'] = 'Square'

        cc3dXML2ObjConverter = XMLUtils.Xml2Obj()
        try:
            root_element = cc3dXML2ObjConverter.ParseString(str(editor.text()))
        except xml.parsers.expat.ExpatError, e:
            QMessageBox.critical(self.__ui, "Error Parsing CC3DML file",
                                 e.__str__())
            print 'GOT PARSING ERROR:', e
            return gpd
    def __insertSnippet(self, _snippetName):
        # print "GOT REQUEST FOR SNIPPET ",_snippetName
        snippetNameStr = str(_snippetName)

        self.handlerDict = self.snippetUtils.getHandlersDict()

        text = self.snippetDictionary[str(_snippetName)]

        editor = self.__ui.getCurrentEditor()
        curFileName = str(self.__ui.getCurrentDocumentName())

        basename, ext = os.path.splitext(curFileName)
        if ext != ".xml" and ext != ".cc3dml":
            QMessageBox.warning(
                self.__ui, "CC3DML files only",
                "CC3DML code snippets work only for xml/cc3dml files")
            return

        # here we parse cell type plugin if found
        import XMLUtils
        cc3dXML2ObjConverter = XMLUtils.Xml2Obj()

        # root_element=cc3dXML2ObjConverter.ParseString(str(editor.text()))
        # print 'root_element=',root_element
        cellTypeData = self.getCellTypeData()
        gpd = self.getPottsData()

        print 'cellTypeData=', cellTypeData

        # self.findModuleLine(editor,_moduleType='Plugin',_moduleName=['Name','CellType'])
        # self.findModuleLine(editor,_moduleType='Steppable',_moduleName=['Type','PIFInitializer'])
        # self.findModuleLine(editor,_moduleType='Potts',_moduleName=[])
        # self.findModuleLine(editor,_moduleType='Plugin',_moduleName=['Name','CenterOfMass'])

        if cellTypeData is None:  # could not obtain data by parsing xml file - most likely due to parsing error
            return

        if not len(cellTypeData):
            print 'self.handlerDict=', self.handlerDict
            print 'self.handlerDict[str(_snippetName)]=', self.handlerDict[
                "Plugins CellType"]

            pottsBegin, pottsEnd = self.findModuleLine(editor,
                                                       _moduleType='Potts',
                                                       _moduleName=[])

            if pottsEnd < 0:
                editor.setCursorPosition(0, 0)
            else:
                editor.setCursorPosition(pottsEnd + 1, 0)

            self.handlerDict["Plugins CellType"](data=cellTypeData,
                                                 editor=editor,
                                                 generalPropertiesData=gpd)
            QMessageBox.warning(
                self.__ui, "Fresh Cell Type Plugin",
                "Please check newly inserted code and call %s again" %
                snippetNameStr)
            return
            #read freshly inseerted cell type plugin
        else:
            self.handlerDict[snippetNameStr](data=cellTypeData,
                                             editor=editor,
                                             generalPropertiesData=gpd)
        return
Beispiel #9
0
    def readScreenshotDescriptionFile(self, _fileName):
        import XMLUtils

        xml2ObjConverter = XMLUtils.Xml2Obj()
        root_element = xml2ObjConverter.Parse(_fileName)
        scrList = XMLUtils.CC3DXMLListPy(
            root_element.getElements("ScreenshotDescription"))
        for scr in scrList:
            if scr.getFirstElement("Dimension").getText() == "2D":
                print MODULENAME, "GOT 2D SCREENSHOT"
                scrData = ScreenshotData()
                scrData.spaceDimension = "2D"

                plotElement = scr.getFirstElement("Plot")
                scrData.plotData = (plotElement.getAttribute("PlotName"),
                                    plotElement.getAttribute("PlotType"))

                projElement = scr.getFirstElement("Projection")
                scrData.projection = projElement.getAttribute(
                    "ProjectionPlane")
                scrData.projectionPosition = int(
                    projElement.getAttribute("ProjectionPosition"))

                sizeElement = scr.getFirstElement("Size")
                scrSize = [
                    int(sizeElement.getAttribute("Width")),
                    int(sizeElement.getAttribute("Height"))
                ]

                # scrData initialized now will initialize graphics widget
                (scrName, scrCoreName) = self.produceScreenshotName(scrData)
                if not scrName in self.screenshotDataDict:
                    scrData.screenshotName = scrName
                    scrData.screenshotCoreName = scrCoreName
                    scrData.screenshotGraphicsWidget = self.screenshotGraphicsWidget
                    self.screenshotDataDict[scrData.screenshotName] = scrData
                else:
                    print MODULENAME, "Screenshot ", scrName, " already exists"

            elif scr.getFirstElement("Dimension").getText() == "3D":
                scrData = ScreenshotData()
                scrData.spaceDimension = "3D"
                plotElement = scr.getFirstElement("Plot")
                scrData.plotData = (plotElement.getAttribute("PlotName"),
                                    plotElement.getAttribute("PlotType"))
                sizeElement = scr.getFirstElement("Size")
                scrSize = [
                    int(sizeElement.getAttribute("Width")),
                    int(sizeElement.getAttribute("Height"))
                ]

                (scrName, scrCoreName) = self.produceScreenshotName(scrData)
                print MODULENAME, "(scrName,scrCoreName)=", (scrName,
                                                             scrCoreName)
                okToAddScreenshot = True

                # extracting Camera Settings
                camSettings = []

                clippingRangeElement = scr.getFirstElement(
                    "CameraClippingRange")
                camSettings.append(
                    float(clippingRangeElement.getAttribute("Min")))
                camSettings.append(
                    float(clippingRangeElement.getAttribute("Max")))

                focalPointElement = scr.getFirstElement("CameraFocalPoint")
                camSettings.append(float(focalPointElement.getAttribute("x")))
                camSettings.append(float(focalPointElement.getAttribute("y")))
                camSettings.append(float(focalPointElement.getAttribute("z")))

                positionElement = scr.getFirstElement("CameraPosition")
                camSettings.append(float(positionElement.getAttribute("x")))
                camSettings.append(float(positionElement.getAttribute("y")))
                camSettings.append(float(positionElement.getAttribute("z")))

                viewUpElement = scr.getFirstElement("CameraViewUp")
                camSettings.append(float(viewUpElement.getAttribute("x")))
                camSettings.append(float(viewUpElement.getAttribute("y")))
                camSettings.append(float(viewUpElement.getAttribute("z")))

                for name in self.screenshotDataDict:
                    scrDataFromDict = self.screenshotDataDict[name]
                    if scrDataFromDict.screenshotCoreName == scrCoreName and scrDataFromDict.spaceDimension == "3D":
                        print MODULENAME, "scrDataFromDict.screenshotCoreName=", scrDataFromDict.screenshotCoreName, " scrCoreName=", scrCoreName

                        if scrDataFromDict.compareExistingCameraToNewCameraSettings(
                                camSettings):
                            print MODULENAME, "CAMERAS ARE THE SAME"
                            okToAddScreenshot = False
                            break
                        else:
                            print MODULENAME, "CAMERAS ARE DIFFERENT"
                print MODULENAME, "okToAddScreenshot=", okToAddScreenshot

                if (not scrName
                        in self.screenshotDataDict) and okToAddScreenshot:
                    scrData.screenshotName = scrName
                    scrData.screenshotCoreName = scrCoreName

                    scrData.screenshotGraphicsWidget = self.screenshotGraphicsWidget

                    scrData.extractCameraInfoFromList(camSettings)
                    self.screenshotDataDict[scrData.screenshotName] = scrData

            else:
                print MODULENAME, "GOT UNKNOWN SCREENSHOT"
    def readCC3DFileFormat(self, _fileName):
        """
        This function reads the CompuCell3D (.cc3d -XML)file. Which contains the file paths to
        all the resources in used in the project. 'cc3dSimulationData' object in this class holds
        all file paths and read data.

        :param _fileName: file path for the
        :return:
        """
        # Import XML utils to read the .cc3d xml file
        import XMLUtils
        xml2ObjConverter = XMLUtils.Xml2Obj()

        # Get the full file path .cc3d xml file
        fileFullPath = os.path.abspath(_fileName)
        self.cc3dSimulationData.basePath = os.path.dirname(fileFullPath)
        self.cc3dSimulationData.path = fileFullPath
        bp = self.cc3dSimulationData.basePath

        # Read the .cc3d xml and get the root element
        root_element = xml2ObjConverter.Parse(fileFullPath)  # this is simulation element

        version = '0'

        # Check if custom settings file (Simulation/_settings.xml) exists.
        # customSettingsFlag = os.path.isfile(os.path.join(self.cc3dSimulationData.basePath,'Simulation/_settings.xml'))
        customSettingsFlag = os.path.isfile(
            os.path.join(self.cc3dSimulationData.basePath, 'Simulation', settings_data.SETTINGS_FILE_NAME))

        if customSettingsFlag:
            # If setting file is there load it to resources as PlayerSettings
            self.cc3dSimulationData.playerSettingsResource = CC3DResource()
            # self.cc3dSimulationData.playerSettingsResource.path = os.path.abspath(os.path.join(self.cc3dSimulationData.basePath,'Simulation/_settings.xml'))
            self.cc3dSimulationData.playerSettingsResource.path = os.path.abspath(
                os.path.join(self.cc3dSimulationData.basePath, 'Simulation', settings_data.SETTINGS_FILE_NAME))

            self.cc3dSimulationData.playerSettingsResource.type = "PlayerSettings"
            print 'GOT SUSTOM SETTINGS : ', self.cc3dSimulationData.playerSettingsResource.path

        # Get the version of the file
        if root_element.findAttribute('version'):
            version = root_element.getAttribute('version')
            self.cc3dSimulationData.version = version

        # Get the model xml file
        if root_element.getFirstElement("XMLScript"):
            # If XML file exists load in resources as XMLScript
            xmlScriptRelative = root_element.getFirstElement("XMLScript").getText()
            self.cc3dSimulationData.xmlScriptResource.path = os.path.abspath(
                os.path.join(bp, xmlScriptRelative))  # normalizing path to xml script
            self.cc3dSimulationData.xmlScriptResource.type = "XMLScript"

        # Get the python script for the model
        if root_element.getFirstElement("PythonScript"):
            # If python file exists load in resources as PythonScript
            pythonScriptRelative = root_element.getFirstElement("PythonScript").getText()
            self.cc3dSimulationData.pythonScriptResource.path = os.path.abspath(
                os.path.join(bp, pythonScriptRelative))  # normalizing path to python script
            self.cc3dSimulationData.pythonScriptResource.type = "PythonScript"

        # Get the PIF file resource for the model
        if root_element.getFirstElement("PIFFile"):
            # If PIF file exists load in resources as PIFFile
            pifFileRelative = root_element.getFirstElement("PIFFile").getText()
            self.cc3dSimulationData.pifFileResource.path = os.path.abspath(
                os.path.join(bp, pifFileRelative))  # normalizing path
            self.cc3dSimulationData.pifFileResource.type = "PIFFile"

        """
        QUESTION: What is WindowScript? How is it used?
        """
        if root_element.getFirstElement("WindowScript"):
            windowScriptRelative = root_element.getFirstElement("WindowScript").getText()
            self.cc3dSimulationData.windowScriptResource.path = os.path.abspath(
                os.path.join(bp, windowScriptRelative))  # normalizing path
            self.cc3dSimulationData.windowScriptResource.type = "WindowScript"

            """
            Reading the WinScript XML file
            """
            winRoot = winXml2ObjConverter.Parse(self.cc3dSimulationData.windowScript)
            winList = XMLUtils.CC3DXMLListPy(winRoot.getElements("Window"))

            #  The following is pretty ugly; there's probably a more elegant way to parse this, but this works
            for myWin in winList:
                attrKeys = myWin.getAttributes().keys()
                winName = myWin.getAttribute("Name")
                locElms = myWin.getElements("Location")
                elms = XMLUtils.CC3DXMLListPy(locElms)
                for elm in elms:
                    xpos = elm.getAttributeAsInt("x")
                    ypos = elm.getAttributeAsInt("y")

                sizeElms = myWin.getElements("Size")
                elms = XMLUtils.CC3DXMLListPy(sizeElms)
                for elm in elms:
                    width = elm.getAttributeAsInt("width")
                    height = elm.getAttributeAsInt("height")

                self.cc3dSimulationData.windowDict[winName] = [xpos, ypos, width, height]

            print MODULENAME, '  -------- self.cc3dSimulationData.windowDict= ', self.cc3dSimulationData.windowDict

        """
        Read the SerializeSimulation element which have the data on serialization of the resources.
        """
        if root_element.getFirstElement("SerializeSimulation"):
            serializeElem = root_element.getFirstElement("SerializeSimulation")
            self.cc3dSimulationData.serializerResource = CC3DSerializerResource()
            if serializeElem:
                if serializeElem.findAttribute("OutputFrequency"):
                    self.cc3dSimulationData.serializerResource.outputFrequency = serializeElem.getAttributeAsInt(
                        "OutputFrequency")

                if serializeElem.findAttribute("AllowMultipleRestartDirectories"):
                    self.cc3dSimulationData.serializerResource.allowMultipleRestartDirectories = serializeElem.getAttributeAsBool(
                        "AllowMultipleRestartDirectories")

                if serializeElem.findAttribute("FileFormat"):
                    self.cc3dSimulationData.serializerResource.fileFormat = serializeElem.getAttribute("FileFormat")

        if root_element.getFirstElement("RestartSimulation"):
            restartElem = root_element.getFirstElement("RestartSimulation")
            if not self.cc3dSimulationData.serializerResource:
                self.cc3dSimulationData.serializerResource = CC3DSerializerResource()

            if restartElem.findAttribute("RestartDirectory"):
                self.cc3dSimulationData.serializerResource.restartDirectory = restartElem.getAttribute(
                    "RestartDirectory")

        # Reading parameter scan resources in the .cc3d file
        if root_element.getFirstElement("ParameterScan"):
            psFile = root_element.getFirstElement("ParameterScan").getText()
            self.cc3dSimulationData.parameterScanResource = CC3DParameterScanResource()
            self.cc3dSimulationData.parameterScanResource.path = os.path.abspath(
                os.path.join(bp, psFile))  # normalizing path to python script
            self.cc3dSimulationData.parameterScanResource.type = 'ParameterScan'
            self.cc3dSimulationData.parameterScanResource.basePath = self.cc3dSimulationData.basePath  # setting same base path for parameter scan as for the project - necessary to get relative paths in the parameterSpec file
            # reading content of XML parameter scan specs
            # ------------------------------------------------------------------ IMPORTANT IMPOTRANT ------------------------------------------------------------------
            # WE HAVE TO CALL MANUALLYreadParameterScanSpecs because if it is called each time CC3DSiulationDataHandler calls readCC3DFileFormat it may cause problems with parameter scan
            # namely one process will attempt to read parameter scan specs while another might try to write to it and error will get thrown and synchronization gets lost
            # plus readCC3DFileFormat should read .cc3d only , not files which are included from .cc3d
            # ------------------------------------------------------------------ IMPORTANT IMPOTRANT ------------------------------------------------------------------            
            # # # self.cc3dSimulationData.parameterScanResource.readParameterScanSpecs()

        # Reading the remaining resources in the .cc3d file
        resourceList = XMLUtils.CC3DXMLListPy(root_element.getElements("Resource"))
        for resourceElem in resourceList:
            cc3dResource = CC3DResource()
            cc3dResource.path = os.path.abspath(os.path.join(bp, resourceElem.getText()))

            if resourceElem.findAttribute("Type"):
                cc3dResource.type = resourceElem.getAttribute("Type")

            if resourceElem.findAttribute("Module"):
                cc3dResource.module = resourceElem.getAttribute("Module")

            if resourceElem.findAttribute("Origin"):
                cc3dResource.origin = resourceElem.getAttribute("Origin")

            if resourceElem.findAttribute("Copy"):
                copyAttr = resourceElem.getAttribute("Copy")
                if copyAttr.lower() == "no":
                    cc3dResource.copy = False

            self.cc3dSimulationData.resources[cc3dResource.path] = cc3dResource
Beispiel #11
0
    def extractLatticeDescriptionInfo(self, _fileName):
        import os
        import os.path
        import CompuCell
        import CompuCellSetup

        ldsFile = os.path.abspath(_fileName)
        self.ldsDir = os.path.dirname(ldsFile)

        import XMLUtils
        from XMLUtils import CC3DXMLListPy
        xml2ObjConverter = XMLUtils.Xml2Obj()
        root_element = xml2ObjConverter.Parse(ldsFile)
        dimElement = root_element.getFirstElement("Dimensions")
        self.fieldDim = CompuCell.Dim3D()
        self.fieldDim.x = int(dimElement.getAttribute("x"))
        self.fieldDim.y = int(dimElement.getAttribute("y"))
        self.fieldDim.z = int(dimElement.getAttribute("z"))
        outputElement = root_element.getFirstElement("Output")
        self.ldsCoreFileName = outputElement.getAttribute("CoreFileName")
        self.frequency = int(outputElement.getAttribute("Frequency"))
        self.numberOfSteps = int(outputElement.getAttribute("NumberOfSteps"))

        # obtaining list of files in the ldsDir
        latticeElement = root_element.getFirstElement("Lattice")
        self.latticeType = latticeElement.getAttribute("Type")

        #getting information about cell type names and cell ids. It is necessary during generation of the PIF files from VTK output
        cellTypesElements = root_element.getElements("CellType")
        listCellTypeElements = CC3DXMLListPy(cellTypesElements)
        for cellTypeElement in listCellTypeElements:
            typeName = ""
            typeId = 0
            typeName = cellTypeElement.getAttribute("TypeName")
            typeId = cellTypeElement.getAttributeAsInt("TypeId")
            self.typeIdTypeNameDict[typeId] = typeName
        # now will convert python dictionary into C++ map<int, string>
        import CC3DXML
        self.typeIdTypeNameCppMap = CC3DXML.MapIntStr()
        for typeId in self.typeIdTypeNameDict.keys():
            self.typeIdTypeNameCppMap[int(
                typeId)] = self.typeIdTypeNameDict[typeId]
#        print "self.typeIdTypeNameCppMap=",self.typeIdTypeNameCppMap

        ldsFileList = os.listdir(self.ldsDir)
        import re
        for fName in ldsFileList:
            if re.match(".*\.vtk$", fName):
                self.ldsFileList.append(fName)
        self.ldsFileList.sort()
        # print " got those files: ",self.ldsFileList

        # extracting information about fields in the lds file
        fieldsElement = root_element.getFirstElement("Fields")
        if fieldsElement:
            fieldList = XMLUtils.CC3DXMLListPy(
                fieldsElement.getElements("Field"))
            #            print MODULENAME,"   fieldList=",fieldList
            #            print MODULENAME,"   dir(fieldList)=",dir(fieldList)  # ['__doc__', '__init__', '__iter__', '__module__', 'elementList', 'getBaseClass']
            ##            print MODULENAME,"   fieldList.getAttributes()=",fieldList.getAttributes()   # doesnt exist
            #            print MODULENAME,"   fieldList.elementList=",fieldList.elementList

            for fieldElem in fieldList:
                #                print MODULENAME,"  dir(fieldElem) = ",dir(fieldElem)
                #                print MODULENAME,"  fieldElem.getAttributes() = ",fieldElem.getAttributes() # <CC3DXML.MapStrStr; proxy of <Swig Object of type 'std::map< std::string,std::string,std::less< std::string >,std::allocator< std::pair< std::string const,std::string > > > *' at 0x1258e0b70> >
                fieldName = fieldElem.getAttribute("Name")
                #                print MODULENAME,"  fieldsUsed key = fieldElem.getAttribute('Name') =",fieldName   # e.g. 'my_field1' w/ a script
                #                print MODULENAME,"  fieldsUsed value = fieldElem.getAttribute('Type') =",fieldElem.getAttribute("Type")
                self.fieldsUsed[fieldElem.getAttribute(
                    "Name")] = fieldElem.getAttribute("Type")
                if fieldElem.findAttribute(
                        "Script"):  # True or False if present
                    # ToDo:  if a "CustomVis" Type was provided, require that a "Script" was also provided; else warn user
                    customVisScript = fieldElem.getAttribute("Script")
                    #                    print MODULENAME,"  fieldElem.getAttribute('Script') =",customVisScript
                    #                    self.fieldsUsed['Script'] = fieldElem.getAttribute("Script")
                    #                    self.customVisScriptDict[fieldName] = customVisScript

                    self.customVis = CompuCellSetup.createCustomVisPy(
                        fieldName)
                    self.customVis.registerVisCallbackFunction(
                        CompuCellSetup.vtkScriptCallback)
                    #                    print MODULENAME,' customVis.addActor:  fieldName (->vtkActor) =',fieldName
                    self.customVis.addActor(fieldName, "vtkActor")
                    #                    self.customVis.addActor(customVisScript,"customVTKScript")
                    self.customVis.addActor(
                        "customVTKScript",
                        customVisScript)  # we'll piggyback off the actorsDict
Beispiel #12
0
    def readScreenshotDescriptionFile_XML(self, _fileName):
        import XMLUtils

        xml2ObjConverter = XMLUtils.Xml2Obj()
        root_element = xml2ObjConverter.Parse(_fileName)
        scrList = XMLUtils.CC3DXMLListPy(root_element.getElements("ScreenshotDescription"))
        for scr in scrList:
            scrData = ScreenshotData()

            self.parseAndAssignBoolChildElement(parent_elem=scr, elem_label='CellBorders', obj=scrData,
                                                attr='cell_borders_on')
            self.parseAndAssignBoolChildElement(parent_elem=scr, elem_label='Cells', obj=scrData,
                                                attr='cells_on')
            self.parseAndAssignBoolChildElement(parent_elem=scr, elem_label='ClusterBorders', obj=scrData,
                                                attr='cluster_borders_on')
            self.parseAndAssignBoolChildElement(parent_elem=scr, elem_label='CellGlyphs', obj=scrData,
                                                attr='cell_glyphs_on')
            self.parseAndAssignBoolChildElement(parent_elem=scr, elem_label='FPPLinks', obj=scrData,
                                                attr='fpp_links_on')

            self.parseAndAssignBoolChildElement(parent_elem=scr, elem_label='BoundingBox', obj=scrData,
                                                attr='bounding_box_on')
            self.parseAndAssignBoolChildElement(parent_elem=scr, elem_label='LatticeAxes', obj=scrData,
                                                attr='lattice_axes_on')
            self.parseAndAssignBoolChildElement(parent_elem=scr, elem_label='LatticeAxesLabels', obj=scrData,
                                                attr='lattice_axes_labels_on')

            try:
                types_invisible_elem_str = scr.getFirstElement("TypesInvisible").getText()
                if types_invisible_elem_str:
                    scrData.invisible_types = map(lambda x: int(x), types_invisible_elem_str.split(','))
                else:
                    scrData.invisible_types = []
            except:
                pass

            # borders_elem = scr.getFirstElement("CellBorders1")
            # if borders_elem:
            #     on_flag = int(borders_elem.getAttribute("On"))
            #
            #     scrData.cell_borders_on = bool(on_flag)
            plotElement = scr.getFirstElement("Plot")
            scrData.plotData = (plotElement.getAttribute("PlotName"), plotElement.getAttribute("PlotType"))

            sizeElement = scr.getFirstElement("Size")
            scrSize = [int(sizeElement.getAttribute("Width")), int(sizeElement.getAttribute("Height"))]

            if scr.getFirstElement("Dimension").getText() == "2D":
                print MODULENAME, "GOT 2D SCREENSHOT"

                scrData.spaceDimension = "2D"
                projElement = scr.getFirstElement("Projection")
                scrData.projection = projElement.getAttribute("ProjectionPlane")
                scrData.projectionPosition = int(projElement.getAttribute("ProjectionPosition"))

                # sizeElement = scr.getFirstElement("Size")
                # scrSize = [int(sizeElement.getAttribute("Width")), int(sizeElement.getAttribute("Height"))]

                # scrData initialized now will initialize graphics widget
                (scrName, scrCoreName) = self.produceScreenshotName(scrData)
                if not scrName in self.screenshotDataDict:
                    scrData.screenshotName = scrName
                    scrData.screenshotCoreName = scrCoreName
                    # scrData.screenshotGraphicsWidget = self.screenshotGraphicsWidget
                    self.screenshotDataDict[scrData.screenshotName] = scrData
                else:
                    print MODULENAME, "Screenshot ", scrName, " already exists"

            elif scr.getFirstElement("Dimension").getText() == "3D":

                scrData.spaceDimension = "3D"
                # plotElement = scr.getFirstElement("Plot")
                # scrData.plotData = (plotElement.getAttribute("PlotName"), plotElement.getAttribute("PlotType"))
                # sizeElement = scr.getFirstElement("Size")
                # scrSize = [int(sizeElement.getAttribute("Width")), int(sizeElement.getAttribute("Height"))]

                (scrName, scrCoreName) = self.produceScreenshotName(scrData)
                print MODULENAME, "(scrName,scrCoreName)=", (scrName, scrCoreName)
                okToAddScreenshot = True

                # extracting Camera Settings
                camSettings = []

                clippingRangeElement = scr.getFirstElement("CameraClippingRange")
                camSettings.append(float(clippingRangeElement.getAttribute("Min")))
                camSettings.append(float(clippingRangeElement.getAttribute("Max")))

                focalPointElement = scr.getFirstElement("CameraFocalPoint")
                camSettings.append(float(focalPointElement.getAttribute("x")))
                camSettings.append(float(focalPointElement.getAttribute("y")))
                camSettings.append(float(focalPointElement.getAttribute("z")))

                positionElement = scr.getFirstElement("CameraPosition")
                camSettings.append(float(positionElement.getAttribute("x")))
                camSettings.append(float(positionElement.getAttribute("y")))
                camSettings.append(float(positionElement.getAttribute("z")))

                viewUpElement = scr.getFirstElement("CameraViewUp")
                camSettings.append(float(viewUpElement.getAttribute("x")))
                camSettings.append(float(viewUpElement.getAttribute("y")))
                camSettings.append(float(viewUpElement.getAttribute("z")))

                for name in self.screenshotDataDict:
                    scrDataFromDict = self.screenshotDataDict[name]
                    if scrDataFromDict.screenshotCoreName == scrCoreName and scrDataFromDict.spaceDimension == "3D":
                        print MODULENAME, "scrDataFromDict.screenshotCoreName=", scrDataFromDict.screenshotCoreName, " scrCoreName=", scrCoreName

                        if scrDataFromDict.compareExistingCameraToNewCameraSettings(camSettings):
                            print MODULENAME, "CAMERAS ARE THE SAME"
                            okToAddScreenshot = False
                            break
                        else:
                            print MODULENAME, "CAMERAS ARE DIFFERENT"
                print MODULENAME, "okToAddScreenshot=", okToAddScreenshot

                if (not scrName in self.screenshotDataDict) and okToAddScreenshot:
                    scrData.screenshotName = scrName
                    scrData.screenshotCoreName = scrCoreName

                    # scrData.screenshotGraphicsWidget = self.screenshotGraphicsWidget

                    scrData.extractCameraInfoFromList(camSettings)
                    self.screenshotDataDict[scrData.screenshotName] = scrData

            else:
                print MODULENAME, "GOT UNKNOWN SCREENSHOT"
Beispiel #13
0
    def readCC3DFileFormat(self,_fileName):        
#        print MODULENAME,'  readCC3DFileFormat()'
        import XMLUtils
        xml2ObjConverter = XMLUtils.Xml2Obj()

        fileFullPath = os.path.abspath(_fileName)
        self.cc3dSimulationData.basePath = os.path.dirname(fileFullPath)
        self.cc3dSimulationData.path = fileFullPath
        bp = self.cc3dSimulationData.basePath
        root_element = xml2ObjConverter.Parse(fileFullPath) # this is simulation element
        
        version='0'
        
        # checking for custom player settings    
        customSettingsFlag = os.path.isfile(os.path.join(self.cc3dSimulationData.basePath,'Simulation/_settings.xml'))
        if customSettingsFlag:
            self.cc3dSimulationData.playerSettingsResource = CC3DResource()
            self.cc3dSimulationData.playerSettingsResource.path = os.path.abspath(os.path.join(self.cc3dSimulationData.basePath,'Simulation/_settings.xml'))
            self.cc3dSimulationData.playerSettingsResource.type = "PlayerSettings"
            print 'GOT SUSTOM SETTINGS : ',self.cc3dSimulationData.playerSettingsResource.path
        
        
        
        if root_element.findAttribute('version'):
            version = root_element.getAttribute('version')
            self.cc3dSimulationData.version=version
        
        if root_element.getFirstElement("XMLScript"):
            xmlScriptRelative = root_element.getFirstElement("XMLScript").getText()            
# # #             self.cc3dSimulationData.xmlScript = root_element.getFirstElement("XMLScript").getText()
#            print MODULENAME,'  readCC3DFileFormat():  found XMLScript, getText=',self.cc3dSimulationData.xmlScript
# # #             self.cc3dSimulationData.xmlScript = os.path.abspath(os.path.join(bp,self.cc3dSimulationData.xmlScript)) #normalizing path to xml script
# # #             self.cc3dSimulationData.xmlScriptResource.path = self.cc3dSimulationData.xmlScript
            self.cc3dSimulationData.xmlScriptResource.path = os.path.abspath(os.path.join(bp,xmlScriptRelative)) #normalizing path to xml script
            self.cc3dSimulationData.xmlScriptResource.type = "XMLScript"
            
        if root_element.getFirstElement("PythonScript"):
            pythonScriptRelative = root_element.getFirstElement("PythonScript").getText()
            self.cc3dSimulationData.pythonScriptResource.path = os.path.abspath(os.path.join(bp,pythonScriptRelative)) #normalizing path to python script
            
            
# # #             self.cc3dSimulationData.pythonScript = root_element.getFirstElement("PythonScript").getText()
# # # #            print MODULENAME,'  readCC3DFileFormat():  found PythonScript, getText=',self.cc3dSimulationData.pythonScript
# # #             self.cc3dSimulationData.pythonScript = os.path.abspath(os.path.join(bp,self.cc3dSimulationData.pythonScript)) #normalizing path to python script
# # #             self.cc3dSimulationData.pythonScriptResource.path = self.cc3dSimulationData.pythonScript
            self.cc3dSimulationData.pythonScriptResource.type = "PythonScript"

        if root_element.getFirstElement("PIFFile"):
            
            pifFileRelative = root_element.getFirstElement("PIFFile").getText()            
            self.cc3dSimulationData.pifFileResource.path = os.path.abspath(os.path.join(bp,pifFileRelative)) #normalizing path
            
            
# # #             self.cc3dSimulationData.pifFile = root_element.getFirstElement("PIFFile").getText()
# # # #            print MODULENAME,'  readCC3DFileFormat():  found PIFFile'
# # #             self.cc3dSimulationData.pifFile = os.path.abspath(os.path.join(bp,self.cc3dSimulationData.pifFile)) #normalizing path
# # #             self.cc3dSimulationData.pifFileResource.path = self.cc3dSimulationData.pifFile
            self.cc3dSimulationData.pifFileResource.type = "PIFFile"
            
        if root_element.getFirstElement("WindowScript"):
            
            windowScriptRelative = root_element.getFirstElement("WindowScript").getText()
            self.cc3dSimulationData.windowScriptResource.path = os.path.abspath(os.path.join(bp,windowScriptRelative)) #normalizing path            
            
            
# # #             self.cc3dSimulationData.windowScript = root_element.getFirstElement("WindowScript").getText()
# # # #            print MODULENAME,'  readCC3DFileFormat():  found WindowScript, getText=',self.cc3dSimulationData.windowScript
# # #             self.cc3dSimulationData.windowScript = os.path.abspath(os.path.join(bp,self.cc3dSimulationData.windowScript)) #normalizing path
# # #             self.cc3dSimulationData.windowScriptResource.path = self.cc3dSimulationData.windowScript
            self.cc3dSimulationData.windowScriptResource.type = "WindowScript"
#                    if playerSettingsElement:
#            windowsXml2Obj = XMLUtils.Xml2Obj()
            winXml2ObjConverter = XMLUtils.Xml2Obj()
            winRoot = winXml2ObjConverter.Parse(self.cc3dSimulationData.windowScript)
#            print MODULENAME,'  readCC3DFileFormat():  type(winRoot)=',type(winRoot)
#            winList = winRoot.getElements("Window")

            winList = XMLUtils.CC3DXMLListPy(winRoot.getElements("Window"))
#            print MODULENAME,'  readCC3DFileFormat():  type(winList)=',type(winList)
            #  The following is pretty ugly; there's probably a more elegant way to parse this, but this works 
            for myWin in winList:
#                print MODULENAME,'  readCC3DFileFormat():  dir(myWin)=',dir(myWin)
#                print MODULENAME,'  readCC3DFileFormat():  myWin.getAttributes()=',myWin.getAttributes()
#                print MODULENAME,'  readCC3DFileFormat():  Element=',myWin.name
                attrKeys = myWin.getAttributes().keys()
#                print MODULENAME,'  readCC3DFileFormat():  attrKeys=',attrKeys
                winName = myWin.getAttribute("Name")
#                print MODULENAME,'  readCC3DFileFormat():  got Name= ',winName
                locElms = myWin.getElements("Location")
                elms = XMLUtils.CC3DXMLListPy(locElms)
                for elm in elms:
                    xpos = elm.getAttributeAsInt("x")
                    ypos = elm.getAttributeAsInt("y")
#                    print MODULENAME,'  readCC3DFileFormat():  Location x,y= ',xpos,ypos
                
                sizeElms = myWin.getElements("Size")
                elms = XMLUtils.CC3DXMLListPy(sizeElms)
                for elm in elms:
                    width = elm.getAttributeAsInt("width")
                    height = elm.getAttributeAsInt("height")
#                    print MODULENAME,'  readCC3DFileFormat():  Size width,height= ',width,height
                    
                self.cc3dSimulationData.windowDict[winName] = [xpos,ypos,width,height]
                
            print MODULENAME,'  -------- self.cc3dSimulationData.windowDict= ',self.cc3dSimulationData.windowDict
                

                
                
        if root_element.getFirstElement("SerializeSimulation"):
            serializeElem = root_element.getFirstElement("SerializeSimulation")
            self.cc3dSimulationData.serializerResource = CC3DSerializerResource()
            if serializeElem:
                if serializeElem.findAttribute("OutputFrequency"):
                    self.cc3dSimulationData.serializerResource.outputFrequency = serializeElem.getAttributeAsInt("OutputFrequency")
                    
                if serializeElem.findAttribute("AllowMultipleRestartDirectories"):                        
                    self.cc3dSimulationData.serializerResource.allowMultipleRestartDirectories = serializeElem.getAttributeAsBool("AllowMultipleRestartDirectories")

                if serializeElem.findAttribute("FileFormat"):
                    self.cc3dSimulationData.serializerResource.fileFormat = serializeElem.getAttribute("FileFormat")
                    
        if root_element.getFirstElement("RestartSimulation"):
            restartElem = root_element.getFirstElement("RestartSimulation")
            if not self.cc3dSimulationData.serializerResource:
                self.cc3dSimulationData.serializerResource = CC3DSerializerResource()
            
            if restartElem.findAttribute("RestartDirectory"):                        
                self.cc3dSimulationData.serializerResource.restartDirectory = restartElem.getAttribute("RestartDirectory")
        

        if root_element.getFirstElement("ParameterScan"):
            psFile = root_element.getFirstElement("ParameterScan").getText()
            self.cc3dSimulationData.parameterScanResource= CC3DParameterScanResource()
            self.cc3dSimulationData.parameterScanResource.path=os.path.abspath(os.path.join(bp,psFile)) #normalizing path to python script
            self.cc3dSimulationData.parameterScanResource.type = 'ParameterScan'
            self.cc3dSimulationData.parameterScanResource.basePath=self.cc3dSimulationData.basePath # setting same base path for parameter scan as for the project - necessary to get relative paths in the parameterSpec file
            #reading content of XML parameter scan specs
            # ------------------------------------------------------------------ IMPORTANT IMPOTRANT ------------------------------------------------------------------
            # WE HAVE TO CALL MANUALLYreadParameterScanSpecs because if it is called each time CC3DSiulationDataHandler calls readCC3DFileFormat it may cause problems with parameter scan
            # namely one process will attempt to read parameter scan specs while another might try to write to it and error will get thrown and synchronization gets lost
            # plus readCC3DFileFormat should read .cc3d only , not files which are included from .cc3d
            # ------------------------------------------------------------------ IMPORTANT IMPOTRANT ------------------------------------------------------------------            
            # # # self.cc3dSimulationData.parameterScanResource.readParameterScanSpecs()
        
        resourceList = XMLUtils.CC3DXMLListPy(root_element.getElements("Resource"))
#        print MODULENAME,'  readCC3DFileFormat():  resourceList=',resourceList
        for resourceElem in resourceList:
            cc3dResource = CC3DResource()
            cc3dResource.path = os.path.abspath(os.path.join(bp,resourceElem.getText()))
            
            if resourceElem.findAttribute("Type"):
                cc3dResource.type = resourceElem.getAttribute("Type")
#                print MODULENAME,'  readCC3DFileFormat():  cc3dResource.type=',cc3dResource.type  # e.g. "Python" or "XML"
            if resourceElem.findAttribute("Module"):
                cc3dResource.module = resourceElem.getAttribute("Module")
            if resourceElem.findAttribute("Origin"):
                cc3dResource.origin = resourceElem.getAttribute("Origin")
            if resourceElem.findAttribute("Copy"):
                copyAttr = resourceElem.getAttribute("Copy")
                if copyAttr.lower()=="no":
                    cc3dResource.copy=False

            self.cc3dSimulationData.resources[cc3dResource.path] = cc3dResource