Esempio n. 1
0
  def trainModel(self):
    if not utils.checkFactors(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Factors rasters is not set. Please specify them and try again")
                         )
      return

    matrix = self.__checkMatrix()
    if len(matrix) == 0:
      QMessageBox.warning(self.plugin,
                          self.tr("Incorrect matrix"),
                          self.tr("Please fill the matrix with values")
                         )
      return

    self.settings.setValue("ui/MCE/initialClass", self.spnInitialClass.value())
    self.settings.setValue("ui/MCE/finalClass", self.spnFinalClass.value())

    areaAnalyst = AreaAnalyst(self.inputs["initial"], second=None)

    self.plugin.logMessage(self.tr("Init MCE model"))

    model = MCE(self.inputs["factors"].values(),
                     matrix,
                     self.spnInitialClass.value(),
                     self.spnFinalClass.value(),
                     areaAnalyst
                    )

    self.inputs["model"] = model

    self.plugin.logMessage(self.tr("MCE model trained"))

    weights = model.getWeights()
    for i, w in enumerate(weights):
        item = QTableWidgetItem(unicode(w))
        self.tblWeights.setItem(0, i, item)
    self.tblWeights.resizeRowsToContents()
    self.tblWeights.resizeColumnsToContents()

    # Check consistency of the matrix
    c = model.getConsistency()
    if c < 0.1:
      QMessageBox.warning(self.plugin,
                          self.tr("Consistent matrix"),
                          self.tr("Matrix filled correctly. Consistency value is: %f. The model can be used.") % (c)
                         )
    else:
      QMessageBox.warning(self.plugin,
                          self.tr("Inconsistent matrix"),
                          self.tr("Please adjust matrix before starting simulation. Consistency value is: %f") % (c)
                         )
  def trainModel(self):
    if not utils.checkInputRasters(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Initial or final raster is not set. Please specify input data and try again")
                         )
      return

    if not utils.checkFactors(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Factors rasters is not set. Please specify them and try again")
                         )
      return

    myBins = self.__getBins()

    self.plugin.logMessage(self.tr("Init WoE model"))
    try:
      model = WoeManager(self.inputs["factors"].values(), self.plugin.analyst, bins=myBins)
    except WoeManagerError as err:
      QMessageBox.warning(self.plugin,
                          self.tr("Initialization error"),
                          err.msg
                         )
      return

    self.inputs["model"] = model

    if not model.checkBins():
      QMessageBox.warning(self.plugin,
                          self.tr("Wrong ranges"),
                          self.tr("Ranges are not correctly specified. Please specify them and try again (use space as separator)")
                         )
      return

    model.moveToThread(self.plugin.workThread)
    self.plugin.workThread.started.connect(model.train)
    model.updateProgress.connect(self.plugin.showProgress)
    model.rangeChanged.connect(self.plugin.setProgressRange)
    model.errorReport.connect(self.plugin.logErrorReport)
    model.processFinished.connect(self.__trainFinished)
    model.processFinished.connect(self.plugin.workThread.quit)

    self.plugin.workThread.start()
  def startFitModel(self):
    if not utils.checkInputRasters(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Initial or final raster is not set. Please specify input data and try again")
                         )
      return

    if not utils.checkFactors(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Factors rasters is not set. Please specify them and try again")
                         )
      return

    if not utils.checkChangeMap(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Change map raster is not set. Please create it try again")
                         )
      return

    self.settings.setValue("ui/LR/neighborhood", self.spnNeighbourhood.value())

    self.plugin.logMessage(self.tr("Init LR model"))

    model = LR(ns=self.spnNeighbourhood.value())
    self.inputs["model"] = model
    model.setMaxIter(self.spnMaxIterations.value())

    model.setState(self.inputs["initial"])
    model.setFactors(self.inputs["factors"].values())
    model.setOutput(self.inputs["changeMap"])
    model.setMode(self.inputs["samplingMode"],)
    model.setSamples(self.plugin.spnSamplesCount.value())

    self.plugin.logMessage(self.tr("Set training data"))
    model.moveToThread(self.plugin.workThread)
    self.plugin.workThread.started.connect(model.startTrain)
    self.plugin.setProgressRange("Train LR model", 0)
    model.finished.connect(self.__trainFinished)
    model.errorReport.connect(self.plugin.logErrorReport)
    model.finished.connect(self.plugin.workThread.quit)
    self.plugin.workThread.start()
  def manageGui(self):
    if not utils.checkFactors(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Factors rasters is not set. Please specify them and try again")
                         )
      return

    if not utils.checkChangeMap(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Change map raster is not set. Please create it try again")
                         )
      return

    self.tblReclass.clearContents()
    self.delegate = spinboxdelegate.SpinBoxDelegate(self.tblReclass.model(), minRange=2, maxRange=dataprovider.MAX_CATEGORIES)

    row = 0
    for k, v in self.inputs["factors"].iteritems():
      v.denormalize()   # Denormalize the factor's bands if they are normalized
      for b in xrange(1, v.getBandsCount()+1):
        if v.isCountinues(b):
          self.tblReclass.insertRow(row)
          if v.getBandsCount()>1:
            name = u"%s (band %s)" % (utils.getLayerById(k).name(), unicode(b))
          else:
            name = u"%s" % (utils.getLayerById(k).name(), )
          stat = v.getBandStat(b)
          for n, item_data in enumerate([name, (u"%f" % (stat["min"], )), (u"%f" % (stat["max"])), u"" , u"" ]):
            item = QTableWidgetItem(item_data)
            if n < 3:
              item.setFlags(item.flags() ^ Qt.ItemIsEditable)
            self.tblReclass.setItem(row, n, item)
          row += 1
    rowCount = row

    self.tblReclass.setItemDelegateForColumn(3, self.delegate)
    for row in range(rowCount):
      # Set 2 bins as default value
      self.tblReclass.setItem(row, 3, QTableWidgetItem(u'2'))

    self.tblReclass.resizeRowsToContents()
    self.tblReclass.resizeColumnsToContents()
Esempio n. 5
0
  def manageGui(self):
    if not utils.checkInputRasters(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Initial or final raster is not set. Please specify input data and try again")
                         )
      return
    if not utils.checkFactors(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Factors rasters is not set. Please specify them and try again")
                         )
      return

    self.spnInitialClass.setValue(int(self.settings.value("ui/MCE/initialClass", 0)))
    self.spnFinalClass.setValue(int(self.settings.value("ui/MCE/finalClass", 0)))

    gradations = self.inputs["initial"].getBandGradation(1)
    self.spnInitialClass.setRange(min(gradations), max(gradations))
    gradations = self.inputs["final"].getBandGradation(1)
    self.spnFinalClass.setRange(min(gradations), max(gradations))

    self.__prepareTable()
  def trainNetwork(self):
    if not utils.checkInputRasters(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Initial or final raster is not set. Please specify input data and try again")
                         )
      return

    if not utils.checkFactors(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Factors rasters is not set. Please specify them and try again")
                         )
      return

    if not utils.checkChangeMap(self.inputs):
      QMessageBox.warning(self.plugin,
                          self.tr("Missed input data"),
                          self.tr("Change map raster is not set. Please create it try again")
                         )
      return

    if self.leTopology.text() == "":
      QMessageBox.warning(self.plugin,
                          self.tr("Wrong network topology"),
                          self.tr("Network topology is undefined. Please define it and try again")
                         )
      return

    self.settings.setValue("ui/ANN/neighborhood", self.spnNeigbourhood.value())
    self.settings.setValue("ui/ANN/learningRate", self.spnLearnRate.value())
    self.settings.setValue("ui/ANN/maxIterations", self.spnMaxIterations.value())
    self.settings.setValue("ui/ANN/topology", self.leTopology.text())
    self.settings.setValue("ui/ANN/momentum", self.spnMomentum.value())

    self.btnStop.setEnabled(True)
    self.btnTrainNetwork.setEnabled(False)

    self.plugin.logMessage(self.tr("Init ANN model"))

    model = MlpManager(ns=self.spnNeigbourhood.value())
    self.inputs["model"] = model
    model.createMlp(self.inputs["initial"],
                         self.inputs["factors"].values(),
                         self.inputs["changeMap"],
                         [int(n) for n in self.leTopology.text().split(" ")]
                        )

    self.plugin.logMessage(self.tr("Set training data"))
    model.setTrainingData(self.inputs["initial"],
                               self.inputs["factors"].values(),
                               self.inputs["changeMap"],
                               mode=self.inputs["samplingMode"],
                               samples=self.plugin.spnSamplesCount.value()
                              )

    model.setEpochs(self.spnMaxIterations.value())
    model.setValPercent(20)
    model.setLRate(self.spnLearnRate.value())
    model.setMomentum(self.spnMomentum.value())
    model.setContinueTrain()

    self.axes.cla()
    self.axes.grid(True)
    self.dataTrain = []
    self.dataVal = []
    self.plotTrain = self.axes.plot(self.dataTrain,
                                    linewidth=1,
                                    color="green",  marker='o'
                                   )[0]
    self.plotVal = self.axes.plot(self.dataVal,
                                  linewidth=1,
                                  color="red",
                                 )[0]
    leg = self.axes.legend(('Train', 'Validation'), 'upper right', shadow=False)
    for t in leg.get_texts():
        t.set_fontsize('small')
    model.moveToThread(self.plugin.workThread)

    self.plugin.workThread.started.connect(model.startTrain)
    self.btnStop.clicked.connect(model.stopTrain)
    model.updateGraph.connect(self.__updateGraph)
    model.updateDeltaRMS.connect(self.__updateRMS)
    model.updateMinValErr.connect(self.__updateValidationError)
    model.updateKappa.connect(self.__updateKappa)
    model.processInterrupted.connect(self.__trainInterrupted)
    model.rangeChanged.connect(self.plugin.setProgressRange)
    model.updateProgress.connect(self.plugin.showProgress)
    model.errorReport.connect(self.plugin.logErrorReport)
    model.processFinished.connect(self.__trainFinished)
    model.processFinished.connect(self.plugin.workThread.quit)

    self.plugin.logMessage(self.tr("Start trainig ANN model"))
    self.plugin.workThread.start()
Esempio n. 7
0
    def trainNetwork(self):
        if not utils.checkInputRasters(self.inputs):
            QMessageBox.warning(
                self.plugin, self.tr("Missed input data"),
                self.
                tr("Initial or final raster is not set. Please specify input data and try again"
                   ))
            return

        if not utils.checkFactors(self.inputs):
            QMessageBox.warning(
                self.plugin, self.tr("Missed input data"),
                self.
                tr("Factors rasters is not set. Please specify them and try again"
                   ))
            return

        if not utils.checkChangeMap(self.inputs):
            QMessageBox.warning(
                self.plugin, self.tr("Missed input data"),
                self.
                tr("Change map raster is not set. Please create it try again"))
            return

        if self.leTopology.text() == "":
            QMessageBox.warning(
                self.plugin, self.tr("Wrong network topology"),
                self.
                tr("Network topology is undefined. Please define it and try again"
                   ))
            return

        self.settings.setValue("ui/ANN/neighborhood",
                               self.spnNeigbourhood.value())
        self.settings.setValue("ui/ANN/learningRate",
                               self.spnLearnRate.value())
        self.settings.setValue("ui/ANN/maxIterations",
                               self.spnMaxIterations.value())
        self.settings.setValue("ui/ANN/topology", self.leTopology.text())
        self.settings.setValue("ui/ANN/momentum", self.spnMomentum.value())

        self.btnStop.setEnabled(True)
        self.btnTrainNetwork.setEnabled(False)

        self.plugin.logMessage(self.tr("Init ANN model"))

        model = MlpManager(ns=self.spnNeigbourhood.value())
        self.inputs["model"] = model
        model.createMlp(self.inputs["initial"],
                        self.inputs["factors"].values(),
                        self.inputs["changeMap"],
                        [int(n) for n in self.leTopology.text().split(" ")])

        self.plugin.logMessage(self.tr("Set training data"))
        model.setTrainingData(self.inputs["initial"],
                              self.inputs["factors"].values(),
                              self.inputs["changeMap"],
                              mode=self.inputs["samplingMode"],
                              samples=self.plugin.spnSamplesCount.value())

        model.setEpochs(self.spnMaxIterations.value())
        model.setValPercent(20)
        model.setLRate(self.spnLearnRate.value())
        model.setMomentum(self.spnMomentum.value())
        model.setContinueTrain()

        self.axes.cla()
        self.axes.grid(True)
        self.dataTrain = []
        self.dataVal = []
        self.plotTrain = self.axes.plot(self.dataTrain,
                                        linewidth=1,
                                        color="green",
                                        marker='o')[0]
        self.plotVal = self.axes.plot(
            self.dataVal,
            linewidth=1,
            color="red",
        )[0]
        leg = self.axes.legend(('Train', 'Validation'),
                               'upper right',
                               shadow=False)
        for t in leg.get_texts():
            t.set_fontsize('small')
        model.moveToThread(self.plugin.workThread)

        self.plugin.workThread.started.connect(model.startTrain)
        self.btnStop.clicked.connect(model.stopTrain)
        model.updateGraph.connect(self.__updateGraph)
        model.updateDeltaRMS.connect(self.__updateRMS)
        model.updateMinValErr.connect(self.__updateValidationError)
        model.updateKappa.connect(self.__updateKappa)
        model.processInterrupted.connect(self.__trainInterrupted)
        model.rangeChanged.connect(self.plugin.setProgressRange)
        model.updateProgress.connect(self.plugin.showProgress)
        model.errorReport.connect(self.plugin.logErrorReport)
        model.processFinished.connect(self.__trainFinished)
        model.processFinished.connect(self.plugin.workThread.quit)

        self.plugin.logMessage(self.tr("Start trainig ANN model"))
        self.plugin.workThread.start()