示例#1
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)             
示例#2
0
def getProjects( configDoc ):
    """
    get the projects that need publish
    """
    publishProjectsElement = XMLUtils.findAllElements( configDoc, "publishProjects/project/path")
    projectsDir = []
    for projectElement in publishProjectsElement:
        projectPath = XMLUtils.getElementValue( projectElement )
        projectsDir.append( projectPath )
    return projectsDir
示例#3
0
def getOutputIIDMInfo(filename):
    IIDM_objects_byID = {}
    (iidm_root, ns, prefix) = XMLUtils.ImportXMLFileExtended(filename)
    for voltageLevel in XMLUtils.FindAll(iidm_root, prefix, "voltageLevel",
                                         ns):
        for child in XMLUtils.FindAll(voltageLevel, prefix, "*", ns):
            if 'id' in child.attrib:
                myId = child.attrib['id']
                myObject = IIDMobject(myId)
                myObject.type = child.tag.replace("{" + ns[prefix] + "}", "")
                if myObject.type == 'bus':
                    set_values(child, 'v', myObject)
                    set_values(child, 'angle', myObject)
                elif myObject.type == 'generator' or myObject.type == 'load':
                    set_values(child, 'p', myObject)
                    set_values(child, 'q', myObject)
                    set_values(child, 'bus', myObject)
                elif myObject.type == 'switch':
                    set_values(child, 'open', myObject)
                elif myObject.type == 'line':
                    set_values(child, 'p1', myObject)
                    set_values(child, 'q1', myObject)
                    set_values(child, 'p2', myObject)
                    set_values(child, 'q2', myObject)
                    set_values(child, 'bus1', myObject)
                    set_values(child, 'bus2', myObject)
                elif myObject.type == 'danglineLine':
                    set_values(child, 'p', myObject)
                    set_values(child, 'q', myObject)
                    set_values(child, 'bus', myObject)
                elif myObject.type == 'twoWindingsTransformer':
                    set_values(child, 'p1', myObject)
                    set_values(child, 'q1', myObject)
                    set_values(child, 'p2', myObject)
                    set_values(child, 'q2', myObject)
                    set_values(child, 'bus1', myObject)
                    set_values(child, 'bus2', myObject)
                elif myObject.type == 'ratioTapChanger' or myObject.type == 'phaseTapChanger':
                    set_values(child, 'tapPosition', myObject)
                elif myObject.type == 'vscConverterStation' or myObject.type == 'lccConverterStation':
                    set_values(child, 'p', myObject)
                    set_values(child, 'q', myObject)
                    set_values(child, 'bus', myObject)
                elif myObject.type == 'shunt':
                    set_values(child, 'currentSectionCount', myObject)
                    set_values(child, 'sectionCount', myObject)
                    set_values(child, 'bus', myObject)
                    set_values(child, 'q', myObject)
                elif myObject.type == 'staticVarCompensator':
                    set_values(child, 'p', myObject)
                    set_values(child, 'bus', myObject)
                    set_values(child, 'q', myObject)
                    set_values(child, 'regulationMode', myObject)
                IIDM_objects_byID[myId] = myObject
    return IIDM_objects_byID
示例#4
0
	def _parseJsdl(self, fileName):
		doc = minidom.parse(fileName)
		jobDef = doc.documentElement
		jobDesc = jobDef.getElementsByTagNameNS(JSDL_NS, "JobDescription")[0]

		# Application element
		app = jobDesc.getElementsByTagNameNS(JSDL_NS, "Application")[0]
		self.applicationName = XMLUtils.getSingletonTextContents(app, JSDL_NS, "ApplicationName")
		self.applicationVersion = XMLUtils.getSingletonTextContents(app, JSDL_NS, "ApplicationVersion")
		
		jobId = jobDesc.getElementsByTagNameNS(JSDL_NS, "JobIdentification")
		if jobId.length > 0:
			self.jobName = XMLUtils.getSingletonTextContents(jobId[0], JSDL_NS, "JobName")
		
		# POSIXApplication element
		posix = app.getElementsByTagNameNS(JSDL_POSIX_NS, "POSIXApplication")
		if posix.length > 0:
			for node in posix[0].childNodes:
				if node.nodeType != Node.ELEMENT_NODE or node.namespaceURI != JSDL_POSIX_NS:
					continue
				data = XMLUtils.getElementTextContents(node)
				if node.localName == 'Argument':
					self.arguments.append(data)
				elif node.localName == 'Executable':
					self.executableName = data
					#platformUtils.formatCygwinPath(data)
				else:
					self.posixConstraints[node.localName] = data
		
		# Resources element
		resources = jobDesc.getElementsByTagNameNS(JSDL_NS, "Resources")
		if resources.length > 0:
			for node in resources[0].childNodes:
				if node.nodeType == Node.ELEMENT_NODE and node.namespaceURI == JSDL_NS:
					self._parseResourcesElement(node)
					
		# DataStaging element
		dataStaging = jobDesc.getElementsByTagNameNS(JSDL_NS, "DataStaging")
		if dataStaging.length > 0:
			dsIndex = 0
			for ds in dataStaging:
				dataStagingElement  =  DataStagingElement()
				for node in ds.childNodes:
					if node.nodeType == Node.ELEMENT_NODE and node.namespaceURI == JSDL_NS:
						self.parseDataStagingElement(node, dataStagingElement)
				self.dataStaging.append(dataStagingElement)	
				dsIndex = dsIndex + 1	
									
		# Application element
		application = jobDesc.getElementsByTagNameNS(JSDL_NS, "Application")
		for node in application[0].childNodes:
			if node.nodeType == Node.ELEMENT_NODE:
				self.parseApplicationElement(node)		
示例#5
0
	def parseApplicationElement(self, node):
		if node.localName == "ApplicationName":
			applicationName = XMLUtils.getElementTextContents(node)	
		elif node.localName == "POSIXApplication":
			for posixNode in node.childNodes:
				if node.nodeType == Node.ELEMENT_NODE and node.namespaceURI == JSDL_POSIX_NS and not node.localName == None:
					self.parsePosixApplicationElement(posixNode)
示例#6
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)
示例#7
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__())
示例#8
0
	def parseDataStagingElement(self, node, dataStagingElement):
		if node.localName == "FileName":
			fileName = XMLUtils.getElementTextContents(node)	
			dataStagingElement.setFileName(fileName)
		elif node.localName == "DeleteOnTermination":
			deleteOnTermination = XMLUtils.getElementTextContents(node)
			dataStagingElement.setDeleteOnTermination(deleteOnTermination)
		elif node.localName == "CreationFlag":
			creationFlag = XMLUtils.getElementTextContents(node)
			dataStagingElement.setCreationFlag(creationFlag)
		elif node.localName == "Source":
			srcUriElement = node.getElementsByTagNameNS(JSDL_NS, "URI")
			srcUri = XMLUtils.getElementTextContents(srcUriElement[0])
			dataStagingElement.setSource(srcUri)
		elif node.localName == "Target":
			targetUriElement = node.getElementsByTagNameNS(JSDL_NS, "URI")
			targetUri = XMLUtils.getElementTextContents(targetUriElement[0])
			dataStagingElement.setTarget(targetUri)
示例#9
0
    def XML2Strlist(self,element):
        self.initNameType(element)

        import XMLUtils
        elementList = XMLUtils.CC3DXMLListPy(element.getElements(""))
        self.value = []        
        for el in elementList:                        
            s = Setting('e',None,'str')        
            s.fromXML(el)
            self.value.append(s.value)
示例#10
0
	def _parseResourcesElement(self, node):
		if node.localName == "FileSystem":
			node = node.getElementsByTagNameNS(JSDL_NS, "DiskSpace")[0]
		if node.localName == "CPUArchitecture":
			self.cpuArchitecture = XMLUtils.getSingletonTextContents(node, JSDL_NS, "CPUArchitectureName")
		elif node.localName == "OperatingSystem":
			osType = XMLUtils.getSingletonElement(node, JSDL_NS, "OperatingSystemType")
			self.operatingSystem = XMLUtils.getSingletonTextContents(osType, JSDL_NS, "OperatingSystemName")	
		elif node.localName == "CandidateHost":
			hostNames = node.getElementsByTagNameNS(JSDL_NS, "HostName")
			for hostName in hostNames:
				self.candidateHosts.append(XMLUtils.getElementTextContents(hostName))
		elif node.localName in SUPPORTED_RANGE_RESOURCES:
			name = node.localName
			value = self._parseRangeElement(node)
			
			self.rangeResources[name] = {
				"lower": value["lower"],
				"upper": value["upper"]
			}
示例#11
0
def get_xml_constraints_info(filename):
    constraints_by_id = {}
    (cstr_root, ns, prefix) = XMLUtils.ImportXMLFileExtended(filename)
    for child in XMLUtils.FindAll(cstr_root, prefix, "constraint", ns):
        my_object = ConstraintsObject()
        my_object.model_name = child.attrib['modelName']
        my_object.description = child.attrib['description']
        my_object.time = child.attrib['time']
        if "type" in child.attrib:
            my_object.type = child.attrib['type']
        if "kind" in child.attrib:
            my_object.kind = child.attrib['kind']
        if "limit" in child.attrib:
            my_object.limit = child.attrib['limit']
        if "value" in child.attrib:
            my_object.value = child.attrib['value']
        if "side" in child.attrib:
            my_object.side = child.attrib['side']
        if "acceptableDuration" in child.attrib:
            my_object.acceptable_duration = child.attrib['acceptableDuration']
        constraints_by_id[my_object.get_unique_id()] = my_object
    return constraints_by_id
示例#12
0
	def _parseRangeElement(self, rangeElement):
		lower = None
		upper = None
		for node in rangeElement.childNodes:
			if node.nodeType != Node.ELEMENT_NODE or node.namespaceURI != JSDL_NS:
				continue
			if node.localName == "LowerBoundedRange":
				val = float(XMLUtils.getElementTextContents(node))
				lower = _min(val, lower)
			elif node.localName == "UpperBoundedRange":
				val = float(XMLUtils.getElementTextContents(node))
				upper = max([val, upper])
			elif node.localName == "Exact":
				val = float(XMLUtils.getElementTextContents(node))
				lower = _min(val, lower)
				upper = max([val, upper])
			elif node.localName == "Range":
				val = float(XMLUtils.getSingletonTextContents(node, JSDL_NS, "LowerBound"))
				lower = _min(val, lower)
				val = float(XMLUtils.getSingletonTextContents(node, JSDL_NS, "UpperBound"))
				upper = max([val, upper])
		return {"lower": lower, "upper": upper}
示例#13
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 
示例#14
0
    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
示例#15
0
 def XML2Dict(self,element):
     # # # # Dictionaries are stored Settings (name, {...}, type = 'pythondict') in self.value
     # # # self.initNameType(element)
     # # # self.value = Setting('pythondict',{},'pythondict')
     
     self.initNameType(element)              
     self.value = {}
     dictionary = self.value
     
     import XMLUtils
     elementList = XMLUtils.CC3DXMLListPy(element.getElements(""))
     
     for el in elementList:            
         s = Setting(el.getAttribute('Name'),None,el.getAttribute('Type'))
         s.fromXML(el)
         dictionary [el.getAttribute('Name')] = s
示例#16
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)
示例#17
0
	def parsePosixApplicationElement(self, node):
		if node.localName == "Executable":
			execName = XMLUtils.getElementTextContents(node)
		elif node.localName == "Argument":
			argument = XMLUtils.getElementTextContents(node)
		elif node.localName == "Input":
			argument = XMLUtils.getElementTextContents(node)
		elif node.localName == "Output":
			argument = XMLUtils.getElementTextContents(node)
		elif node.localName == "Error":
			argument = XMLUtils.getElementTextContents(node)
		elif node.localName == "Environment":
			envVariableValue = XMLUtils.getElementTextContents(node)
			envVariableName = node.getAttribute('name')
示例#18
0
    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
示例#19
0
def removeFiles( configDoc ):
    projectsElement = XMLUtils.findAllElements( configDoc, "publishProjects/project" )
    for projectElement in projectsElement:
        projectName = XMLUtils.findSubElementValue( projectElement, "path" )
        projectPath = os.path.join( sys.argv[2], projectName )
        
        # remove the dir 
        dirsElement = XMLUtils.findAllElements( projectElement, "removeFiles/dirs/dir" )
        for dirElement in dirsElement:
            dirName = XMLUtils.getElementValue( dirElement )
            if dirName is None:
                continue
            dirPath = os.path.join( projectPath, dirName )
            XFileUtil.rmTree( dirPath )
        
        #remove files 
        filesElement = XMLUtils.findAllElements( projectElement, "removeFiles/files/file" )
        for fileElement in filesElement:
            fileName = XMLUtils.getElementValue( fileElement )
            if fileName is None:
                continue
            filePath = os.path.join( projectPath, fileName )
            XFileUtil.deleteFile( filePath )
    pass
示例#20
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
示例#22
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
示例#23
0
def getDocument():
    configPath = os.path.join( os.path.dirname(__file__), Constants.CONFIG_NAME )
    configDoc = XMLUtils.getDocument( configPath )
    return configDoc
import CompuCellSetup
if not CompuCellSetup.simulationFileName == "":
    CompuCellSetup.setSimulationXMLFileName(CompuCellSetup.simulationFileName)
sim, simthread = CompuCellSetup.getCoreSimulationObjects()
import CompuCell  #notice importing CompuCell to main script has to be done after call to getCoreSimulationObjects()

#Create extra player fields here or add attributes or plugin:
#PUT YOUR CODE HERE
#PUT YOUR CODE HERE
#PUT YOUR CODE HERE

import XMLUtils

steppableList = CompuCellSetup.cc3dXML2ObjConverter.root.getElements("Plugin")
steppableListPy = XMLUtils.CC3DXMLListPy(steppableList)

for element in steppableListPy:
    print "Element", element.name
#     ," name", element.getNumberOfChildren()

CompuCellSetup.initializeSimulationObjects(sim, simthread)

steppableRegistry = CompuCellSetup.getSteppableRegistry()
#Add Python steppables here
#PUT YOUR CODE HERE
#PUT YOUR CODE HERE
#PUT YOUR CODE HERE

# sim.ps.steppableCC3DXMLElementVector()
CompuCellSetup.mainLoop(
示例#25
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
示例#26
0
def treeNode(itemNode, _superParent=None):
    import XMLUtils
    import CC3DXML
    # itemNode can only be Element!
    # itemNode is of type CC3DXMLElement
    if not itemNode:
        return None

    node = itemNode
    #    print MODULENAME," treeNode(): creating TreeItem ",node.name," cdata=",node.cdata
    #    if node.name == 'Plugin':
    #      print MODULENAME,'     rwh: exception here', foo

    tNode = TreeItem(node.name, node.cdata)

    # Setting item values for Potts, Metadata,  Plugins and Steppables. Those settings are for display purposes only and do not affect CC3DXML element that Compucell3d uses to configure the data
    # all we do is to label Potts tree element as Posst and Plugin and Steppables are named using their names extracted from xml file.
    # we are using _itemValue to label label those elements and do not change cdata of the CC3DXMLelement

    if node.name == "Potts":
        tNode.setItemValueOnly("Potts")

    if node.name == "Metadata":
        tNode.setItemValueOnly("Metadata")

    # handling opening elements for Plugin and Steppables
    if node.name == "Plugin":
        tNode.setItemValueOnly(node.getAttribute("Name"))
    if node.name == "Steppable":
        tNode.setItemValueOnly(node.getAttribute("Type"))

    tNode.setCC3DXMLElement(
        node)  # domNode holds reference to current CC3DXMLElement

    # setting superParents -they are either Potts, Plugin or Steppable. SuperParents are used in steering. Essentially when we change any TreeItem in the TreeView
    # we can quickly extract name of the superParent and tell CC3D to reinitialize module that superParent describes. Otherwise if we dont keep track of super parents we would either have to do:
    # 1. time consuming and messy tracking back of which module needs to be changed in response to change in one of the parameter
    # or
    # 2. reinitialize all modules each time a single parameter is changed

    superParent = _superParent
    if not _superParent:
        if node.name in ("Plugin", "Steppable", "Potts", "Metadata"):
            superParent = tNode

    tNode.setSuperParent(superParent)

    # FOR AN UNKNOWN REASON "regular" map iteration does not work so i had to implement by hand iterators in C++ and Python to walk thrugh all the elementnts in the map<string,string> in python

    attribList = XMLUtils.MapStrStrPy(node.attributes)
    # # # print "attributes=",attribList
    for attr in attribList:
        attributeName = attr[0]
        attributeValue = attr[1]
        if node.name == "Plugin" and attributeName == "Name":
            continue
        if node.name == "Steppable" and attributeName == "Type":
            continue
        # print "attributeName ",attributeName, " value=",node.attributes[attributeName]
        treeChild = TreeItem(
            attributeName,
            attributeValue)  #attribute name, attribute value pair
        treeChild.setCC3DXMLElement(node)
        treeChild.setSuperParent(superParent)
        treeChild.setElementType("attribute")
        # if superParent is not None:
        # print MODULENAME,"treeChild.domNode().getName()=",treeChild.domNode().getName()
        # ," parentName=",treeChild.parent().name()," super parent=",treeChild.getSuperParent().name()
        tNode.addChild(treeChild)

    children = XMLUtils.CC3DXMLListPy(node.children)
    for child in children:
        # # # print "element=",child
        tChild = treeNode(child, superParent)
        tNode.addChild(tChild)

        # # # if tChild.getSuperParent() is not None:
        # # # print MODULENAME,"tChild.domNode().getName()=",tChild.domNode().getName()," parentName=",tChild.parent().name()," super parent=",tChild.getSuperParent().name()

    return tNode
示例#27
0
    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
示例#28
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"