Beispiel #1
0
    def open(self, file_name):
        """
        Loads the content from XML file to Project instance.
        """

        # Create the network
        self.network = Network()

        try:
            project = eval(open(file_name, 'r').read())
        except:
            QtWidgets.QMessageBox.warning(None, "Warning", "Cannot read the project file (" + file_name + ")!", QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, QtWidgets.QMessageBox.NoButton)
            project = {}

        self.file_name = file_name
        self.name = project['name']
        self.author = project['author']
        self.description = project['description']
        for node_dict in project['nodes']:
            node = self.readNode(node_dict)
            self.network.nodes.append(node)
        for link_dict in project['links']:
            link = self.readLink(link_dict)
            self.network.links.append(link)
        self.network.preparePhases()
Beispiel #2
0
  def open(self, fileName):
    """
    Loads the content from XML file to Project instance.
    """

    # Create the network
    self.network = Network()

    self.fileName = fileName
    file = QtCore.QFile(self.fileName)
    if (file.open(QtCore.QIODevice.ReadOnly)):
      xmlReader = QtCore.QXmlStreamReader()
      xmlReader.setDevice(file)
      while (not xmlReader.isEndDocument()):
        if xmlReader.isStartElement():
          if xmlReader.name().toString() == 'MetaData':
            self.name = self.__getStringAttribute(xmlReader.attributes(), 'name')
            self.author = self.__getStringAttribute(xmlReader.attributes(), 'author')
            self.description = self.__getStringAttribute(xmlReader.attributes(), 'description')
          elif xmlReader.name().toString() == 'Net':
            while xmlReader.readNextStartElement():
              if xmlReader.name().toString() == 'Node':
                node = self.__readNode(xmlReader)
                self.network.nodes.append(node)
              elif xmlReader.name().toString() == 'Link':
                link = self.__readLink(xmlReader)
                self.network.links.append(link)

        xmlReader.readNext()
      if (xmlReader.hasError()):
        QtGui.QMessageBox.critical(self, "Critical", "Ocurred a XML error: " + xmlReader.errorString().data(), QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default, QtGui.QMessageBox.NoButton)
    else:
      QtGui.QMessageBox.critical(self, "Critical", "Cannot read the project file!", QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default, QtGui.QMessageBox.NoButton)

    self.network.preparePhases()
Beispiel #3
0
    def open(self, fileName):
        """
    Loads the content from XML file to Project instance.
    """

        # Create the network
        self.network = Network()

        self.fileName = fileName
        file = QtCore.QFile(self.fileName)
        if (file.open(QtCore.QIODevice.ReadOnly)):
            xmlReader = QtCore.QXmlStreamReader()
            xmlReader.setDevice(file)
            while (not xmlReader.isEndDocument()):
                if xmlReader.isStartElement():
                    if xmlReader.name().toString() == 'MetaData':
                        self.name = self.__getStringAttribute(
                            xmlReader.attributes(), 'name')
                        self.author = self.__getStringAttribute(
                            xmlReader.attributes(), 'author')
                        self.description = self.__getStringAttribute(
                            xmlReader.attributes(), 'description')
                    elif xmlReader.name().toString() == 'Net':
                        while xmlReader.readNextStartElement():
                            if xmlReader.name().toString() == 'Node':
                                node = self.__readNode(xmlReader)
                                self.network.nodes.append(node)
                            elif xmlReader.name().toString() == 'Link':
                                link = self.__readLink(xmlReader)
                                self.network.links.append(link)

                xmlReader.readNext()
            if (xmlReader.hasError()):
                QtGui.QMessageBox.critical(
                    self, "Critical",
                    "Ocurred a XML error: " + xmlReader.errorString().data(),
                    QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default,
                    QtGui.QMessageBox.NoButton)
        else:
            QtGui.QMessageBox.critical(
                self, "Critical", "Cannot read the project file!",
                QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default,
                QtGui.QMessageBox.NoButton)

        self.network.preparePhases()
Beispiel #4
0
    def new(self):
        """
    Initializes a new instance of this class.
    """

        # Initialize metadata
        self.fileName = ''
        self.name = "Untitled"
        self.author = ""
        self.description = ""

        # Create the top region
        topRegion = Region("TopRegion")

        # Create the network and add topRegion as its starting node
        self.network = Network()
        self.network.nodes.append(topRegion)
        self.network.preparePhases()
Beispiel #5
0
    def __init__(self):
        """
        Initializes a new instance of this class.
        """

        # Project file
        self.file_name = ''

        # Name of the project.
        self.name = "Untitled"

        # Author of the project.
        self.author = ""

        # Description of the project.
        self.description = ""

        # The network created for the project.
        self.network = Network()
Beispiel #6
0
    def __init__(self):
        """
    Initializes a new instance of this class.
    """

        #region Instance fields

        self.fileName = ''
        """Project file"""

        self.name = "Untitled"
        """Name of the project."""

        self.author = ""
        """Author of the project."""

        self.description = ""
        """Description of the project."""

        self.network = Network()
        """The network created for the project."""
Beispiel #7
0
  def new(self):
    """
    Initializes a new instance of this class.
    """

    # Initialize metadata
    self.fileName = ''
    self.name = "Untitled"
    self.author = ""
    self.description = ""

    # Create the top region
    topRegion = Region("TopRegion")

    # Create the network and add topRegion as its starting node
    self.network = Network()
    self.network.nodes.append(topRegion)
    self.network.preparePhases()
Beispiel #8
0
  def __init__(self):
    """
    Initializes a new instance of this class.
    """

    #region Instance fields

    self.fileName = ''
    """Project file"""

    self.name = "Untitled"
    """Name of the project."""

    self.author = ""
    """Author of the project."""

    self.description = ""
    """Description of the project."""

    self.network = Network()
    """The network created for the project."""
Beispiel #9
0
class Project:
  """
  Loads and saves the Elements of the Project file, that contains user entries for Network configuration
  Provides loaded elements as a structure to return.
  """

  #region Constructor

  def __init__(self):
    """
    Initializes a new instance of this class.
    """

    #region Instance fields

    self.fileName = ''
    """Project file"""

    self.name = "Untitled"
    """Name of the project."""

    self.author = ""
    """Author of the project."""

    self.description = ""
    """Description of the project."""

    self.network = Network()
    """The network created for the project."""

    #endregion

  #endregion

  #region Methods

  def new(self):
    """
    Initializes a new instance of this class.
    """

    # Initialize metadata
    self.fileName = ''
    self.name = "Untitled"
    self.author = ""
    self.description = ""

    # Create the top region
    topRegion = Region("TopRegion")

    # Create the network and add topRegion as its starting node
    self.network = Network()
    self.network.nodes.append(topRegion)
    self.network.preparePhases()

  def open(self, fileName):
    """
    Loads the content from XML file to Project instance.
    """

    # Create the network
    self.network = Network()

    self.fileName = fileName
    file = QtCore.QFile(self.fileName)
    if (file.open(QtCore.QIODevice.ReadOnly)):
      xmlReader = QtCore.QXmlStreamReader()
      xmlReader.setDevice(file)
      while (not xmlReader.isEndDocument()):
        if xmlReader.isStartElement():
          if xmlReader.name().toString() == 'MetaData':
            self.name = self.__getStringAttribute(xmlReader.attributes(), 'name')
            self.author = self.__getStringAttribute(xmlReader.attributes(), 'author')
            self.description = self.__getStringAttribute(xmlReader.attributes(), 'description')
          elif xmlReader.name().toString() == 'Net':
            while xmlReader.readNextStartElement():
              if xmlReader.name().toString() == 'Node':
                node = self.__readNode(xmlReader)
                self.network.nodes.append(node)
              elif xmlReader.name().toString() == 'Link':
                link = self.__readLink(xmlReader)
                self.network.links.append(link)

        xmlReader.readNext()
      if (xmlReader.hasError()):
        QtGui.QMessageBox.critical(self, "Critical", "Ocurred a XML error: " + xmlReader.errorString().data(), QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default, QtGui.QMessageBox.NoButton)
    else:
      QtGui.QMessageBox.critical(self, "Critical", "Cannot read the project file!", QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default, QtGui.QMessageBox.NoButton)

    self.network.preparePhases()

  def __getStringAttribute(self, attributes, attributeName):
    if attributes.value(attributeName).toString() != "":
      attributeValue = str(attributes.value(attributeName).toString())
    else:
      attributeValue = ""
    return attributeValue

  def __getIntegerAttribute(self, attributes, attributeName):
    attributeValue = 0
    if attributes.value(attributeName).toString() != "":
      attributeValue = int(attributes.value(attributeName).toString())
    return attributeValue

  def __getFloatAttribute(self, attributes, attributeName):
    attributeValue = 0.0
    if attributes.value(attributeName).toString() != "":
      attributeValue = float(attributes.value(attributeName).toString())
    return attributeValue

  def __getBooleanAttribute(self, attributes, attributeName):
    attributeValue = False
    if attributes.value(attributeName).toString() == "True":
      attributeValue = True
    return attributeValue

  def __readNode(self, xmlReader):

    # Read type of node
    name = self.__getStringAttribute(xmlReader.attributes(), 'name')
    type = self.__getStringAttribute(xmlReader.attributes(), 'type')

    # Create a node from parameters
    node = None
    if type == 'Region':
      node = Region(name)
    elif type == 'Sensor':
      node = Sensor(name)
    node.width = self.__getIntegerAttribute(xmlReader.attributes(), 'width')
    node.height = self.__getIntegerAttribute(xmlReader.attributes(), 'height')

    # Read specific parameters according to node type
    if type == 'Region':
      node.enableSpatialLearning = self.__getBooleanAttribute(xmlReader.attributes(), 'enableSpatialLearning')
      node.potentialRadius = self.__getIntegerAttribute(xmlReader.attributes(), 'potentialRadius')
      node.potentialPct = self.__getFloatAttribute(xmlReader.attributes(), 'potentialPct')
      node.globalInhibition = self.__getBooleanAttribute(xmlReader.attributes(), 'globalInhibition')
      node.localAreaDensity = self.__getFloatAttribute(xmlReader.attributes(), 'localAreaDensity')
      node.numActiveColumnsPerInhArea = self.__getFloatAttribute(xmlReader.attributes(), 'numActiveColumnsPerInhArea')
      node.stimulusThreshold = self.__getIntegerAttribute(xmlReader.attributes(), 'stimulusThreshold')
      node.proximalSynConnectedPerm = self.__getFloatAttribute(xmlReader.attributes(), 'proximalSynConnectedPerm')
      node.proximalSynPermIncrement = self.__getFloatAttribute(xmlReader.attributes(), 'proximalSynPermIncrement')
      node.proximalSynPermDecrement = self.__getFloatAttribute(xmlReader.attributes(), 'proximalSynPermDecrement')
      node.minPctOverlapDutyCycle = self.__getFloatAttribute(xmlReader.attributes(), 'minPctOverlapDutyCycle')
      node.minPctActiveDutyCycle = self.__getFloatAttribute(xmlReader.attributes(), 'minPctActiveDutyCycle')
      node.dutyCyclePeriod = self.__getIntegerAttribute(xmlReader.attributes(), 'dutyCyclePeriod')
      node.maxBoost = self.__getFloatAttribute(xmlReader.attributes(), 'maxBoost')
      node.spSeed = self.__getIntegerAttribute(xmlReader.attributes(), 'spSeed')
      node.enableTemporalLearning = self.__getBooleanAttribute(xmlReader.attributes(), 'enableTemporalLearning')
      node.numCellsPerColumn = self.__getIntegerAttribute(xmlReader.attributes(), 'numCellsPerColumn')
      node.learningRadius = self.__getIntegerAttribute(xmlReader.attributes(), 'learningRadius')
      node.distalSynInitialPerm = self.__getFloatAttribute(xmlReader.attributes(), 'distalSynInitialPerm')
      node.distalSynConnectedPerm = self.__getFloatAttribute(xmlReader.attributes(), 'distalSynConnectedPerm')
      node.distalSynPermIncrement = self.__getFloatAttribute(xmlReader.attributes(), 'distalSynPermIncrement')
      node.distalSynPermDecrement = self.__getFloatAttribute(xmlReader.attributes(), 'distalSynPermDecrement')
      node.minThreshold = self.__getIntegerAttribute(xmlReader.attributes(), 'minThreshold')
      node.activationThreshold = self.__getIntegerAttribute(xmlReader.attributes(), 'activationThreshold')
      node.maxNumNewSynapses = self.__getIntegerAttribute(xmlReader.attributes(), 'maxNumNewSynapses')
      node.tpSeed = self.__getIntegerAttribute(xmlReader.attributes(), 'tpSeed')
    elif type == 'Sensor':
      dataSourceType = self.__getStringAttribute(xmlReader.attributes(), 'dataSourceType')
      if dataSourceType == "File":
        node.dataSourceType = DataSourceType.file
        node.fileName = self.__getStringAttribute(xmlReader.attributes(), 'fileName')
      elif dataSourceType == "Database":
        node.dataSourceType = DataSourceType.database
        node.databaseConnectionString = self.__getStringAttribute(xmlReader.attributes(), 'databaseConnectionString')
        node.databaseTable = self.__getStringAttribute(xmlReader.attributes(), 'databaseTable')
      node.predictionsMethod = self.__getStringAttribute(xmlReader.attributes(), 'predictionsMethod')
      if node.predictionsMethod == PredictionsMethod.classification:
        node.enableClassificationLearning = self.__getBooleanAttribute(xmlReader.attributes(), 'enableClassificationLearning')
        node.enableClassificationInference = self.__getBooleanAttribute(xmlReader.attributes(), 'enableClassificationInference')

      # If still is not end of element it's because this node has encodings
      token = xmlReader.readNext()
      if not xmlReader.isEndElement():
        while xmlReader.readNextStartElement():
          encoding = self.__readEncoding(xmlReader)
          node.encodings.append(encoding)

    token = xmlReader.readNext()

    return node

  def __readEncoding(self, xmlReader):

    # Create a encoding from parameters
    encoding = Encoding()
    encoding.dataSourceFieldName = self.__getStringAttribute(xmlReader.attributes(), 'dataSourceFieldName')
    encoding.dataSourceFieldDataType = self.__getStringAttribute(xmlReader.attributes(), 'dataSourceFieldDataType')
    encoding.enableInference = self.__getBooleanAttribute(xmlReader.attributes(), 'enableInference')
    encoding.encoderModule = self.__getStringAttribute(xmlReader.attributes(), 'encoderModule')
    encoding.encoderClass = self.__getStringAttribute(xmlReader.attributes(), 'encoderClass')
    encoding.encoderParams = self.__getStringAttribute(xmlReader.attributes(), 'encoderParams')
    encoding.encoderFieldName = self.__getStringAttribute(xmlReader.attributes(), 'encoderFieldName')
    encoding.encoderFieldDataType = self.__getStringAttribute(xmlReader.attributes(), 'encoderFieldDataType')
    token = xmlReader.readNext()

    return encoding

  def __readLink(self, xmlReader):

    # Read link parameters
    outNodeName = self.__getStringAttribute(xmlReader.attributes(), 'outNode')
    inNodeName = self.__getStringAttribute(xmlReader.attributes(), 'inNode')
    token = xmlReader.readNext()

    # Find output node instance
    outNode = None
    for node in self.network.nodes:
      if node.name == outNodeName:
        outNode = node
        break

    # Find input node instance
    inNode = None
    for node in self.network.nodes:
      if node.name == inNodeName:
        inNode = node
        break

    # Create a link from parameters
    link = Link()
    link.outNode = outNode
    link.inNode = inNode

    return link

  def save(self, fileName):
    """
    Saves the content from Project instance to XML file.
    """

    self.fileName = fileName
    file = QtCore.QFile(self.fileName)
    file.open(QtCore.QIODevice.WriteOnly)
    xmlWriter = QtCore.QXmlStreamWriter(file)
    xmlWriter.setAutoFormatting(True)
    xmlWriter.writeStartDocument()
    xmlWriter.writeStartElement('Project')

    xmlWriter.writeStartElement('MetaData')
    xmlWriter.writeAttribute('name', self.name)
    xmlWriter.writeAttribute('author', self.author)
    xmlWriter.writeAttribute('description', self.description)
    xmlWriter.writeEndElement()

    xmlWriter.writeStartElement('Net')
    for node in self.network.nodes:
      self.__writeNode(node, xmlWriter)
    for link in self.network.links:
      self.__writeLink(link, xmlWriter)
    xmlWriter.writeEndElement()

    xmlWriter.writeEndElement()
    xmlWriter.writeEndDocument()
    file.close()

  def __writeNode(self, node, xmlWriter):

    # Write common parameters
    xmlWriter.writeStartElement('Node')
    xmlWriter.writeAttribute('name', node.name)

    # Write specific parameters according to node type
    if node.type == NodeType.region:
      xmlWriter.writeAttribute('type', 'Region')
      xmlWriter.writeAttribute('width', str(node.width))
      xmlWriter.writeAttribute('height', str(node.height))
      xmlWriter.writeAttribute('enableSpatialLearning', str(node.enableSpatialLearning))
      xmlWriter.writeAttribute('potentialRadius', str(node.potentialRadius))
      xmlWriter.writeAttribute('potentialPct', str(node.potentialPct))
      xmlWriter.writeAttribute('globalInhibition', str(node.globalInhibition))
      xmlWriter.writeAttribute('localAreaDensity', str(node.localAreaDensity))
      xmlWriter.writeAttribute('numActiveColumnsPerInhArea', str(node.numActiveColumnsPerInhArea))
      xmlWriter.writeAttribute('stimulusThreshold', str(node.stimulusThreshold))
      xmlWriter.writeAttribute('proximalSynConnectedPerm', str(node.proximalSynConnectedPerm))
      xmlWriter.writeAttribute('proximalSynPermIncrement', str(node.proximalSynPermIncrement))
      xmlWriter.writeAttribute('proximalSynPermDecrement', str(node.proximalSynPermDecrement))
      xmlWriter.writeAttribute('minPctOverlapDutyCycle', str(node.minPctOverlapDutyCycle))
      xmlWriter.writeAttribute('minPctActiveDutyCycle', str(node.minPctActiveDutyCycle))
      xmlWriter.writeAttribute('dutyCyclePeriod', str(node.dutyCyclePeriod))
      xmlWriter.writeAttribute('maxBoost', str(node.maxBoost))
      xmlWriter.writeAttribute('spSeed', str(node.spSeed))
      xmlWriter.writeAttribute('enableTemporalLearning', str(node.enableTemporalLearning))
      xmlWriter.writeAttribute('numCellsPerColumn', str(node.numCellsPerColumn))
      xmlWriter.writeAttribute('learningRadius', str(node.learningRadius))
      xmlWriter.writeAttribute('distalSynInitialPerm', str(node.distalSynInitialPerm))
      xmlWriter.writeAttribute('distalSynConnectedPerm', str(node.distalSynConnectedPerm))
      xmlWriter.writeAttribute('distalSynPermIncrement', str(node.distalSynPermIncrement))
      xmlWriter.writeAttribute('distalSynPermDecrement', str(node.distalSynPermDecrement))
      xmlWriter.writeAttribute('minThreshold', str(node.minThreshold))
      xmlWriter.writeAttribute('activationThreshold', str(node.activationThreshold))
      xmlWriter.writeAttribute('maxNumNewSynapses', str(node.maxNumNewSynapses))
      xmlWriter.writeAttribute('tpSeed', str(node.tpSeed))
    elif node.type == NodeType.sensor:
      xmlWriter.writeAttribute('type', 'Sensor')
      xmlWriter.writeAttribute('width', str(node.width))
      xmlWriter.writeAttribute('height', str(node.height))
      if node.dataSourceType == DataSourceType.file:
        xmlWriter.writeAttribute('dataSourceType', "File")
        xmlWriter.writeAttribute('fileName', node.fileName)
      elif node.dataSourceType == DataSourceType.database:
        xmlWriter.writeAttribute('dataSourceType', "Database")
        xmlWriter.writeAttribute('databaseConnectionString', node.databaseConnectionString)
        xmlWriter.writeAttribute('databaseTable', node.databaseTable)
      xmlWriter.writeAttribute('predictionsMethod', node.predictionsMethod)
      if node.predictionsMethod == PredictionsMethod.classification:
        xmlWriter.writeAttribute('enableClassificationLearning', str(node.enableClassificationLearning))
        xmlWriter.writeAttribute('enableClassificationInference', str(node.enableClassificationInference))

      # Tranverse all encodings
      for encoding in node.encodings:
        self.__writeEncoding(encoding, xmlWriter)

    xmlWriter.writeEndElement()

  def __writeEncoding(self, encoding, xmlWriter):

    # Write encoding parameters
    xmlWriter.writeStartElement('Encoding')
    xmlWriter.writeAttribute('dataSourceFieldName', encoding.dataSourceFieldName)
    xmlWriter.writeAttribute('dataSourceFieldDataType', encoding.dataSourceFieldDataType)
    xmlWriter.writeAttribute('enableInference', str(encoding.enableInference))
    xmlWriter.writeAttribute('encoderModule', encoding.encoderModule)
    xmlWriter.writeAttribute('encoderClass', encoding.encoderClass)
    xmlWriter.writeAttribute('encoderParams', encoding.encoderParams)
    xmlWriter.writeAttribute('encoderFieldName', encoding.encoderFieldName)
    xmlWriter.writeAttribute('encoderFieldDataType', encoding.encoderFieldDataType)
    xmlWriter.writeEndElement()

  def __writeLink(self, link, xmlWriter):

    # Write encoding parameters
    xmlWriter.writeStartElement('Link')
    xmlWriter.writeAttribute('outNode', link.outNode.name)
    xmlWriter.writeAttribute('inNode', link.inNode.name)
    xmlWriter.writeEndElement()
Beispiel #10
0
class Project:
    """
  Loads and saves the Elements of the Project file, that contains user entries for Network configuration
  Provides loaded elements as a structure to return.
  """

    #region Constructor

    def __init__(self):
        """
    Initializes a new instance of this class.
    """

        #region Instance fields

        self.fileName = ''
        """Project file"""

        self.name = "Untitled"
        """Name of the project."""

        self.author = ""
        """Author of the project."""

        self.description = ""
        """Description of the project."""

        self.network = Network()
        """The network created for the project."""

        #endregion

    #endregion

    #region Methods

    def new(self):
        """
    Initializes a new instance of this class.
    """

        # Initialize metadata
        self.fileName = ''
        self.name = "Untitled"
        self.author = ""
        self.description = ""

        # Create the top region
        topRegion = Region("TopRegion")

        # Create the network and add topRegion as its starting node
        self.network = Network()
        self.network.nodes.append(topRegion)
        self.network.preparePhases()

    def open(self, fileName):
        """
    Loads the content from XML file to Project instance.
    """

        # Create the network
        self.network = Network()

        self.fileName = fileName
        file = QtCore.QFile(self.fileName)
        if (file.open(QtCore.QIODevice.ReadOnly)):
            xmlReader = QtCore.QXmlStreamReader()
            xmlReader.setDevice(file)
            while (not xmlReader.isEndDocument()):
                if xmlReader.isStartElement():
                    if xmlReader.name().toString() == 'MetaData':
                        self.name = self.__getStringAttribute(
                            xmlReader.attributes(), 'name')
                        self.author = self.__getStringAttribute(
                            xmlReader.attributes(), 'author')
                        self.description = self.__getStringAttribute(
                            xmlReader.attributes(), 'description')
                    elif xmlReader.name().toString() == 'Net':
                        while xmlReader.readNextStartElement():
                            if xmlReader.name().toString() == 'Node':
                                node = self.__readNode(xmlReader)
                                self.network.nodes.append(node)
                            elif xmlReader.name().toString() == 'Link':
                                link = self.__readLink(xmlReader)
                                self.network.links.append(link)

                xmlReader.readNext()
            if (xmlReader.hasError()):
                QtGui.QMessageBox.critical(
                    self, "Critical",
                    "Ocurred a XML error: " + xmlReader.errorString().data(),
                    QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default,
                    QtGui.QMessageBox.NoButton)
        else:
            QtGui.QMessageBox.critical(
                self, "Critical", "Cannot read the project file!",
                QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default,
                QtGui.QMessageBox.NoButton)

        self.network.preparePhases()

    def __getStringAttribute(self, attributes, attributeName):
        if attributes.value(attributeName).toString() != "":
            attributeValue = str(attributes.value(attributeName).toString())
        else:
            attributeValue = ""
        return attributeValue

    def __getIntegerAttribute(self, attributes, attributeName):
        attributeValue = 0
        if attributes.value(attributeName).toString() != "":
            attributeValue = int(attributes.value(attributeName).toString())
        return attributeValue

    def __getFloatAttribute(self, attributes, attributeName):
        attributeValue = 0.0
        if attributes.value(attributeName).toString() != "":
            attributeValue = float(attributes.value(attributeName).toString())
        return attributeValue

    def __getBooleanAttribute(self, attributes, attributeName):
        attributeValue = False
        if attributes.value(attributeName).toString() == "True":
            attributeValue = True
        return attributeValue

    def __readNode(self, xmlReader):

        # Read type of node
        name = self.__getStringAttribute(xmlReader.attributes(), 'name')
        type = self.__getStringAttribute(xmlReader.attributes(), 'type')

        # Create a node from parameters
        node = None
        if type == 'Region':
            node = Region(name)
        elif type == 'Sensor':
            node = Sensor(name)
        node.width = self.__getIntegerAttribute(xmlReader.attributes(),
                                                'width')
        node.height = self.__getIntegerAttribute(xmlReader.attributes(),
                                                 'height')

        # Read specific parameters according to node type
        if type == 'Region':
            node.enableSpatialLearning = self.__getBooleanAttribute(
                xmlReader.attributes(), 'enableSpatialLearning')
            node.potentialRadius = self.__getIntegerAttribute(
                xmlReader.attributes(), 'potentialRadius')
            node.potentialPct = self.__getFloatAttribute(
                xmlReader.attributes(), 'potentialPct')
            node.globalInhibition = self.__getBooleanAttribute(
                xmlReader.attributes(), 'globalInhibition')
            node.localAreaDensity = self.__getFloatAttribute(
                xmlReader.attributes(), 'localAreaDensity')
            node.numActiveColumnsPerInhArea = self.__getFloatAttribute(
                xmlReader.attributes(), 'numActiveColumnsPerInhArea')
            node.stimulusThreshold = self.__getIntegerAttribute(
                xmlReader.attributes(), 'stimulusThreshold')
            node.proximalSynConnectedPerm = self.__getFloatAttribute(
                xmlReader.attributes(), 'proximalSynConnectedPerm')
            node.proximalSynPermIncrement = self.__getFloatAttribute(
                xmlReader.attributes(), 'proximalSynPermIncrement')
            node.proximalSynPermDecrement = self.__getFloatAttribute(
                xmlReader.attributes(), 'proximalSynPermDecrement')
            node.minPctOverlapDutyCycle = self.__getFloatAttribute(
                xmlReader.attributes(), 'minPctOverlapDutyCycle')
            node.minPctActiveDutyCycle = self.__getFloatAttribute(
                xmlReader.attributes(), 'minPctActiveDutyCycle')
            node.dutyCyclePeriod = self.__getIntegerAttribute(
                xmlReader.attributes(), 'dutyCyclePeriod')
            node.maxBoost = self.__getFloatAttribute(xmlReader.attributes(),
                                                     'maxBoost')
            node.spSeed = self.__getIntegerAttribute(xmlReader.attributes(),
                                                     'spSeed')
            node.enableTemporalLearning = self.__getBooleanAttribute(
                xmlReader.attributes(), 'enableTemporalLearning')
            node.numCellsPerColumn = self.__getIntegerAttribute(
                xmlReader.attributes(), 'numCellsPerColumn')
            node.distalSynInitialPerm = self.__getFloatAttribute(
                xmlReader.attributes(), 'distalSynInitialPerm')
            node.distalSynConnectedPerm = self.__getFloatAttribute(
                xmlReader.attributes(), 'distalSynConnectedPerm')
            node.distalSynPermIncrement = self.__getFloatAttribute(
                xmlReader.attributes(), 'distalSynPermIncrement')
            node.distalSynPermDecrement = self.__getFloatAttribute(
                xmlReader.attributes(), 'distalSynPermDecrement')
            node.minThreshold = self.__getIntegerAttribute(
                xmlReader.attributes(), 'minThreshold')
            node.activationThreshold = self.__getIntegerAttribute(
                xmlReader.attributes(), 'activationThreshold')
            node.maxNumNewSynapses = self.__getIntegerAttribute(
                xmlReader.attributes(), 'maxNumNewSynapses')
            node.tpSeed = self.__getIntegerAttribute(xmlReader.attributes(),
                                                     'tpSeed')
        elif type == 'Sensor':
            dataSourceType = self.__getStringAttribute(xmlReader.attributes(),
                                                       'dataSourceType')
            if dataSourceType == "File":
                node.dataSourceType = DataSourceType.file
                node.fileName = self.__getStringAttribute(
                    xmlReader.attributes(), 'fileName')
            elif dataSourceType == "Database":
                node.dataSourceType = DataSourceType.database
                node.databaseConnectionString = self.__getStringAttribute(
                    xmlReader.attributes(), 'databaseConnectionString')
                node.databaseTable = self.__getStringAttribute(
                    xmlReader.attributes(), 'databaseTable')
            node.predictionsMethod = self.__getStringAttribute(
                xmlReader.attributes(), 'predictionsMethod')
            if node.predictionsMethod == PredictionsMethod.classification:
                node.enableClassificationLearning = self.__getBooleanAttribute(
                    xmlReader.attributes(), 'enableClassificationLearning')
                node.enableClassificationInference = self.__getBooleanAttribute(
                    xmlReader.attributes(), 'enableClassificationInference')

            # If still is not end of element it's because this node has encodings
            token = xmlReader.readNext()
            if not xmlReader.isEndElement():
                while xmlReader.readNextStartElement():
                    encoding = self.__readEncoding(xmlReader)
                    node.encodings.append(encoding)

        token = xmlReader.readNext()

        return node

    def __readEncoding(self, xmlReader):

        # Create a encoding from parameters
        encoding = Encoding()
        encoding.dataSourceFieldName = self.__getStringAttribute(
            xmlReader.attributes(), 'dataSourceFieldName')
        encoding.dataSourceFieldDataType = self.__getStringAttribute(
            xmlReader.attributes(), 'dataSourceFieldDataType')
        encoding.enableInference = self.__getBooleanAttribute(
            xmlReader.attributes(), 'enableInference')
        encoding.encoderModule = self.__getStringAttribute(
            xmlReader.attributes(), 'encoderModule')
        encoding.encoderClass = self.__getStringAttribute(
            xmlReader.attributes(), 'encoderClass')
        encoding.encoderParams = self.__getStringAttribute(
            xmlReader.attributes(), 'encoderParams')
        encoding.encoderFieldName = self.__getStringAttribute(
            xmlReader.attributes(), 'encoderFieldName')
        encoding.encoderFieldDataType = self.__getStringAttribute(
            xmlReader.attributes(), 'encoderFieldDataType')
        token = xmlReader.readNext()

        return encoding

    def __readLink(self, xmlReader):

        # Read link parameters
        outNodeName = self.__getStringAttribute(xmlReader.attributes(),
                                                'outNode')
        inNodeName = self.__getStringAttribute(xmlReader.attributes(),
                                               'inNode')
        token = xmlReader.readNext()

        # Find output node instance
        outNode = None
        for node in self.network.nodes:
            if node.name == outNodeName:
                outNode = node
                break

        # Find input node instance
        inNode = None
        for node in self.network.nodes:
            if node.name == inNodeName:
                inNode = node
                break

        # Create a link from parameters
        link = Link()
        link.outNode = outNode
        link.inNode = inNode

        return link

    def save(self, fileName):
        """
    Saves the content from Project instance to XML file.
    """

        self.fileName = fileName
        file = QtCore.QFile(self.fileName)
        file.open(QtCore.QIODevice.WriteOnly)
        xmlWriter = QtCore.QXmlStreamWriter(file)
        xmlWriter.setAutoFormatting(True)
        xmlWriter.writeStartDocument()
        xmlWriter.writeStartElement('Project')

        xmlWriter.writeStartElement('MetaData')
        xmlWriter.writeAttribute('name', self.name)
        xmlWriter.writeAttribute('author', self.author)
        xmlWriter.writeAttribute('description', self.description)
        xmlWriter.writeEndElement()

        xmlWriter.writeStartElement('Net')
        for node in self.network.nodes:
            self.__writeNode(node, xmlWriter)
        for link in self.network.links:
            self.__writeLink(link, xmlWriter)
        xmlWriter.writeEndElement()

        xmlWriter.writeEndElement()
        xmlWriter.writeEndDocument()
        file.close()

    def __writeNode(self, node, xmlWriter):

        # Write common parameters
        xmlWriter.writeStartElement('Node')
        xmlWriter.writeAttribute('name', node.name)

        # Write specific parameters according to node type
        if node.type == NodeType.region:
            xmlWriter.writeAttribute('type', 'Region')
            xmlWriter.writeAttribute('width', str(node.width))
            xmlWriter.writeAttribute('height', str(node.height))
            xmlWriter.writeAttribute('enableSpatialLearning',
                                     str(node.enableSpatialLearning))
            xmlWriter.writeAttribute('potentialRadius',
                                     str(node.potentialRadius))
            xmlWriter.writeAttribute('potentialPct', str(node.potentialPct))
            xmlWriter.writeAttribute('globalInhibition',
                                     str(node.globalInhibition))
            xmlWriter.writeAttribute('localAreaDensity',
                                     str(node.localAreaDensity))
            xmlWriter.writeAttribute('numActiveColumnsPerInhArea',
                                     str(node.numActiveColumnsPerInhArea))
            xmlWriter.writeAttribute('stimulusThreshold',
                                     str(node.stimulusThreshold))
            xmlWriter.writeAttribute('proximalSynConnectedPerm',
                                     str(node.proximalSynConnectedPerm))
            xmlWriter.writeAttribute('proximalSynPermIncrement',
                                     str(node.proximalSynPermIncrement))
            xmlWriter.writeAttribute('proximalSynPermDecrement',
                                     str(node.proximalSynPermDecrement))
            xmlWriter.writeAttribute('minPctOverlapDutyCycle',
                                     str(node.minPctOverlapDutyCycle))
            xmlWriter.writeAttribute('minPctActiveDutyCycle',
                                     str(node.minPctActiveDutyCycle))
            xmlWriter.writeAttribute('dutyCyclePeriod',
                                     str(node.dutyCyclePeriod))
            xmlWriter.writeAttribute('maxBoost', str(node.maxBoost))
            xmlWriter.writeAttribute('spSeed', str(node.spSeed))
            xmlWriter.writeAttribute('enableTemporalLearning',
                                     str(node.enableTemporalLearning))
            xmlWriter.writeAttribute('numCellsPerColumn',
                                     str(node.numCellsPerColumn))
            xmlWriter.writeAttribute('distalSynInitialPerm',
                                     str(node.distalSynInitialPerm))
            xmlWriter.writeAttribute('distalSynConnectedPerm',
                                     str(node.distalSynConnectedPerm))
            xmlWriter.writeAttribute('distalSynPermIncrement',
                                     str(node.distalSynPermIncrement))
            xmlWriter.writeAttribute('distalSynPermDecrement',
                                     str(node.distalSynPermDecrement))
            xmlWriter.writeAttribute('minThreshold', str(node.minThreshold))
            xmlWriter.writeAttribute('activationThreshold',
                                     str(node.activationThreshold))
            xmlWriter.writeAttribute('maxNumNewSynapses',
                                     str(node.maxNumNewSynapses))
            xmlWriter.writeAttribute('tpSeed', str(node.tpSeed))
        elif node.type == NodeType.sensor:
            xmlWriter.writeAttribute('type', 'Sensor')
            xmlWriter.writeAttribute('width', str(node.width))
            xmlWriter.writeAttribute('height', str(node.height))
            if node.dataSourceType == DataSourceType.file:
                xmlWriter.writeAttribute('dataSourceType', "File")
                xmlWriter.writeAttribute('fileName', node.fileName)
            elif node.dataSourceType == DataSourceType.database:
                xmlWriter.writeAttribute('dataSourceType', "Database")
                xmlWriter.writeAttribute('databaseConnectionString',
                                         node.databaseConnectionString)
                xmlWriter.writeAttribute('databaseTable', node.databaseTable)
            xmlWriter.writeAttribute('predictionsMethod',
                                     node.predictionsMethod)
            if node.predictionsMethod == PredictionsMethod.classification:
                xmlWriter.writeAttribute(
                    'enableClassificationLearning',
                    str(node.enableClassificationLearning))
                xmlWriter.writeAttribute(
                    'enableClassificationInference',
                    str(node.enableClassificationInference))

            # Tranverse all encodings
            for encoding in node.encodings:
                self.__writeEncoding(encoding, xmlWriter)

        xmlWriter.writeEndElement()

    def __writeEncoding(self, encoding, xmlWriter):

        # Write encoding parameters
        xmlWriter.writeStartElement('Encoding')
        xmlWriter.writeAttribute('dataSourceFieldName',
                                 encoding.dataSourceFieldName)
        xmlWriter.writeAttribute('dataSourceFieldDataType',
                                 encoding.dataSourceFieldDataType)
        xmlWriter.writeAttribute('enableInference',
                                 str(encoding.enableInference))
        xmlWriter.writeAttribute('encoderModule', encoding.encoderModule)
        xmlWriter.writeAttribute('encoderClass', encoding.encoderClass)
        xmlWriter.writeAttribute('encoderParams', encoding.encoderParams)
        xmlWriter.writeAttribute('encoderFieldName', encoding.encoderFieldName)
        xmlWriter.writeAttribute('encoderFieldDataType',
                                 encoding.encoderFieldDataType)
        xmlWriter.writeEndElement()

    def __writeLink(self, link, xmlWriter):

        # Write encoding parameters
        xmlWriter.writeStartElement('Link')
        xmlWriter.writeAttribute('outNode', link.outNode.name)
        xmlWriter.writeAttribute('inNode', link.inNode.name)
        xmlWriter.writeEndElement()
Beispiel #11
0
class Project:
    """
    Loads and saves the Elements of the Project file, that contains user entries for Network configuration
    Provides loaded elements as a structure to return.
    """

    def __init__(self):
        """
        Initializes a new instance of this class.
        """

        # Project file
        self.file_name = ''

        # Name of the project.
        self.name = "Untitled"

        # Author of the project.
        self.author = ""

        # Description of the project.
        self.description = ""

        # The network created for the project.
        self.network = Network()

    def new(self):
        """
        Initializes a new instance of this class.
        """

        # Initialize metadata
        self.file_name = ''
        self.name = "Untitled"
        self.author = ""
        self.description = ""

        # Create the top region
        top_region = Region("TopRegion")

        # Create the network and add top_region as its starting node
        self.network = Network()
        self.network.nodes.append(top_region)
        self.network.preparePhases()

    def open(self, file_name):
        """
        Loads the content from XML file to Project instance.
        """

        # Create the network
        self.network = Network()

        try:
            project = eval(open(file_name, 'r').read())
        except:
            QtWidgets.QMessageBox.warning(None, "Warning", "Cannot read the project file (" + file_name + ")!", QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Default, QtWidgets.QMessageBox.NoButton)
            project = {}

        self.file_name = file_name
        self.name = project['name']
        self.author = project['author']
        self.description = project['description']
        for node_dict in project['nodes']:
            node = self.readNode(node_dict)
            self.network.nodes.append(node)
        for link_dict in project['links']:
            link = self.readLink(link_dict)
            self.network.links.append(link)
        self.network.preparePhases()

    def readNode(self, node_dict):

        # Read type of node
        name = node_dict['name']
        type = node_dict['type']

        # Create a node from parameters
        node = None
        if type == 'Region':
            node = Region(name)
        elif type == 'Sensor':
            node = Sensor(name)
        node.width = node_dict['width']
        node.height = node_dict['height']

        # Read specific parameters according to node type
        if type == 'Region':
            node.enable_spatial_learning = node_dict['enable_spatial_learning']
            node.potential_radius = node_dict['potential_radius']
            node.potential_pct = node_dict['potential_pct']
            node.global_inhibition = node_dict['global_inhibition']
            node.local_area_density = node_dict['local_area_density']
            node.num_active_columns_per_inh_area = node_dict['num_active_columns_per_inh_area']
            node.stimulus_threshold = node_dict['stimulus_threshold']
            node.proximal_syn_connected_perm = node_dict['proximal_syn_connected_perm']
            node.proximal_syn_perm_increment = node_dict['proximal_syn_perm_increment']
            node.proximal_syn_perm_decrement = node_dict['proximal_syn_perm_decrement']
            node.min_pct_overlap_duty_cycle = node_dict['min_pct_overlap_duty_cycle']
            node.min_pct_active_duty_cycle = node_dict['min_pct_active_duty_cycle']
            node.duty_cycle_period = node_dict['duty_cycle_period']
            node.max_boost = node_dict['max_boost']
            node.sp_seed = node_dict['sp_seed']
            node.enable_temporal_learning = node_dict['enable_temporal_learning']
            node.cells_per_column = node_dict['cells_per_column']
            node.distal_syn_initial_perm = node_dict['distal_syn_initial_perm']
            node.distal_syn_connected_perm = node_dict['distal_syn_connected_perm']
            node.distal_syn_perm_increment = node_dict['distal_syn_perm_increment']
            node.distal_syn_perm_decrement = node_dict['distal_syn_perm_decrement']
            node.min_threshold = node_dict['min_threshold']
            node.activation_threshold = node_dict['activation_threshold']
            node.max_new_synapses = node_dict['max_new_synapses']
            node.tp_seed = node_dict['tp_seed']
        elif type == 'Sensor':
            data_source_type = node_dict['data_source_type']
            if data_source_type == "File":
                node.data_source_type = DataSourceType.FILE
                node.file_name = node_dict['file_name']
            elif data_source_type == "Database":
                node.data_source_type = DataSourceType.DATABASE
                node.database_connection_string = node_dict['database_connection_string']
                node.database_table = node_dict['database_table']
            node.predictions_method = node_dict['predictions_method']
            if node.predictions_method == PredictionsMethod.CLASSIFICATION:
                node.enable_classification_learning = node_dict['enable_classification_learning']
                node.enable_classification_inference = node_dict['enable_classification_inference']

            # If still is not end of element it's because this node has encodings
            for encoding_dict in node_dict['encodings']:
                encoding = self.readEncoding(encoding_dict)
                node.encodings.append(encoding)

        return node

    def readEncoding(self, encoding_dict):

        # Create a encoding from parameters
        encoding = Encoding()
        encoding.data_source_field_name = encoding_dict['data_source_field_name']
        encoding.data_source_field_data_type = encoding_dict['data_source_field_data_type']
        encoding.enable_inference = encoding_dict['enable_inference']
        encoding.encoder_module = encoding_dict['encoder_module']
        encoding.encoder_class = encoding_dict['encoder_class']
        encoding.encoder_params = encoding_dict['encoder_params']
        encoding.encoder_field_name = encoding_dict['encoder_field_name']
        encoding.encoder_field_data_type = encoding_dict['encoder_field_data_type']

        return encoding

    def readLink(self, link_dict):

        # Read link parameters
        out_node_name = link_dict['out_node']
        in_node_name = link_dict['in_node']

        # Find output node instance
        out_node = None
        for node in self.network.nodes:
            if node.name == out_node_name:
                out_node = node
                break

        # Find input node instance
        in_node = None
        for node in self.network.nodes:
            if node.name == in_node_name:
                in_node = node
                break

        # Create a link from parameters
        link = Link()
        link.out_node = out_node
        link.in_node = in_node

        return link

    def save(self, file_name):
        """
        Saves the content from Project instance to XML file.
        """

        self.file_name = file_name

        project = {}
        project['name'] = self.name
        project['author'] = self.author
        project['description'] = self.description
        project['nodes'] = []
        for node in self.network.nodes:
            node_dict = self.writeNode(node)
            project['nodes'].append(node_dict)
        project['links'] = []
        for link in self.network.links:
            link_dict = self.writeLink(link)
            project['links'].append(link_dict)

        open(file_name, 'w').write(str(project))

    def writeNode(self, node):
        node_dict = {}
        node_dict['name'] = node.name

        # Write specific parameters according to node type
        if node.type == NodeType.REGION:
            node_dict['type'] = 'Region'
            node_dict['width'] = str(node.width)
            node_dict['height'] = str(node.height)
            node_dict['enable_spatial_learning'] = str(node.enable_spatial_learning)
            node_dict['potential_radius'] = str(node.potential_radius)
            node_dict['potential_pct'] = str(node.potential_pct)
            node_dict['global_inhibition'] = str(node.global_inhibition)
            node_dict['local_area_density'] = str(node.local_area_density)
            node_dict['num_active_columns_per_inh_area'] = str(node.num_active_columns_per_inh_area)
            node_dict['stimulus_threshold'] = str(node.stimulus_threshold)
            node_dict['proximal_syn_connected_perm'] = str(node.proximal_syn_connected_perm)
            node_dict['proximal_syn_perm_increment'] = str(node.proximal_syn_perm_increment)
            node_dict['proximal_syn_perm_decrement'] = str(node.proximal_syn_perm_decrement)
            node_dict['min_pct_overlap_duty_cycle'] = str(node.min_pct_overlap_duty_cycle)
            node_dict['min_pct_active_duty_cycle'] = str(node.min_pct_active_duty_cycle)
            node_dict['duty_cycle_period'] = str(node.duty_cycle_period)
            node_dict['max_boost'] = str(node.max_boost)
            node_dict['sp_seed'] = str(node.sp_seed)
            node_dict['enable_temporal_learning'] = str(node.enable_temporal_learning)
            node_dict['cells_per_column'] = str(node.cells_per_column)
            node_dict['distal_syn_initial_perm'] = str(node.distal_syn_initial_perm)
            node_dict['distal_syn_connected_perm'] = str(node.distal_syn_connected_perm)
            node_dict['distal_syn_perm_increment'] = str(node.distal_syn_perm_increment)
            node_dict['distal_syn_perm_decrement'] = str(node.distal_syn_perm_decrement)
            node_dict['min_threshold'] = str(node.min_threshold)
            node_dict['activation_threshold'] = str(node.activation_threshold)
            node_dict['max_new_synapses'] = str(node.max_new_synapses)
            node_dict['tp_seed'] = str(node.tp_seed)
        elif node.type == NodeType.SENSOR:
            node_dict['type'] = 'Sensor'
            node_dict['width'] = str(node.width)
            node_dict['height'] = str(node.height)
            if node.data_source_type == DataSourceType.FILE:
                node_dict['data_source_type'] = "File"
                node_dict['file_name'] = node.file_name
            elif node.data_source_type == DataSourceType.DATABASE:
                node_dict['data_source_type'] = "Database"
                node_dict['database_connection_string'] = node.database_connection_string
                node_dict['database_table'] = node.database_table
            node_dict['predictions_method'] = node.predictions_method
            if node.predictions_method == PredictionsMethod.CLASSIFICATION:
                node_dict['enable_classification_learning'] = str(node.enable_classification_learning)
                node_dict['enable_classification_inference'] = str(node.enable_classification_inference)

            # Tranverse all encodings
            node_dict['encodings'] = []
            for encoding in node.encodings:
                encoding_dict = self.writeEncoding(encoding)
                node_dict['encodings'].append(encoding_dict)

        return node_dict

    def writeEncoding(self, encoding):
        encoding_dict = {}
        encoding_dict['data_source_field_name'] = encoding.data_source_field_name
        encoding_dict['data_source_field_data_type'] = encoding.data_source_field_data_type
        encoding_dict['enable_inference'] = str(encoding.enable_inference)
        encoding_dict['encoder_module'] = encoding.encoder_module
        encoding_dict['encoder_class'] = encoding.encoder_class
        encoding_dict['encoder_params'] = encoding.encoder_params
        encoding_dict['encoder_field_name'] = encoding.encoder_field_name
        encoding_dict['encoder_field_data_type'] = encoding.encoder_field_data_type
        return encoding_dict

    def writeLink(self, link):
        link_dict = {}
        link_dict['out_node'] = link.out_node.name
        link_dict['in_node'] = link.in_node.name
        return link_dict