Example #1
0
 def fromCallString(cls, string, project, layerlist):
     args = shlex.split(string)
     execName = os.path.join(project.opalspath, args[0])
     args.remove(args[0])
     # for i in range(len(args)):  # Values with a space in between are supported by opals w/out quotes
     #     curarg = args[i]
     #     nextarg = args[i + 1] if len(args) > i + 1 else "-"
     #     if not curarg.startswith("-") and not nextarg.startswith("-"):
     #         args[i] = curarg + " " + nextarg
     #         args.remove(nextarg)
     #     if len(args) <= i + 1:
     #         break
     args.append("--options")
     # call
     info = subprocess.STARTUPINFO()
     info.dwFlags = subprocess.STARTF_USESHOWWINDOW
     info.wShowWindow = 0  # 0=HIDE
     proc = subprocess.Popen([execName] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE, cwd=project.workdir, startupinfo=info)
     proc.stdin.close()
     stdout, stderr = proc.communicate()
     if proc.returncode != 0:
         raise Exception('Call failed:\n %s' % stdout)
     xml_parsed = parseXML(stderr)
     newModuleBase = cls(execName, project, layerlist)
     newModuleBase.load()
     newModuleBase.getParamUi()
     newModuleBase.params = QpalsParameter.mergeParamLists(newModuleBase.params, xml_parsed['Specific'])
     newModuleBase.globals = QpalsParameter.mergeParamLists(newModuleBase.globals, xml_parsed['Global'])
     newModuleBase.common = QpalsParameter.mergeParamLists(newModuleBase.common, xml_parsed['Common'])
     return newModuleBase
Example #2
0
    def runview(self):
        self.secInst.runSecBtnView.setEnabled(False)
        regionFilter = "Region["
        for p in self.rbPoints:
            regionFilter += "%.3f %.3f " % (p[0], p[1])
        regionFilter += "]"
        if self.secInst.filterStr.text() != "":
            regionFilter = regionFilter + " and " + self.secInst.filterStr.text(
            )
        Module = QpalsModuleBase.QpalsModuleBase(
            execName=os.path.join(self.secInst.project.opalspath,
                                  "opalsView.exe"),
            QpalsProject=self.secInst.project)
        infile = QpalsParameter.QpalsParameter(
            'inFile', self.secInst.txtinfileSimple.text(), None, None, None,
            None, None)
        filter = QpalsParameter.QpalsParameter('filter', regionFilter, None,
                                               None, None, None, None)

        Module.params.append(infile)
        Module.params.append(filter)
        thread, worker = Module.run_async(status=self.update_status,
                                          on_error=self.sec_error,
                                          on_finish=self.runviewfinished)
        self.thread.append(thread)
        self.worker.append(worker)
Example #3
0
def getAttributeInformation(file, project):
    from qpals.qpals import QpalsModuleBase, QpalsParameter
    infoinst = QpalsModuleBase.QpalsModuleBase(execName=os.path.join(project.opalspath, "opalsInfo.exe"),
                                               QpalsProject=project)
    infoinst.params = [QpalsParameter.QpalsParameter('inFile', file,
                                                     None, None, None, None, None)]
    try:
        moduleOut = infoinst.run(show=0)
        outtext = moduleOut['stdout']
        ## begin parsing of log
        header_passed = False
        attrs = []
        entries = []
        for line in outtext.split("\n"):
            if line.startswith("Attribute "):
                header_passed = True
                entries = line.split()
            elif header_passed:
                data = line.split()
                if len(data) == 0:  # end of attribute list
                    break
                attrs.append(data)
        if not header_passed:
            raise NotImplementedError
        return attrs, entries
    except Exception as e:
        raise e
        return None, None
Example #4
0
    def runSection(self):
        outParamFileH = tempfile.NamedTemporaryFile(delete=False)
        outParamFile = outParamFileH.name
        outParamFileH.close()
        self.runSecBtn.setEnabled(False)
        self.runSecBtn.setText("Calculating sections...")
        outParamFileParam = QpalsParameter.QpalsParameter(
            'outParamFile', outParamFile, None, None, None, None, None)
        self.secInst.params.append(outParamFileParam)
        self.secInst.run()
        self.secInst.params.remove(outParamFileParam)
        dom = minidom.parse(outParamFile)
        parameters = dom.getElementsByTagName("Parameter")
        outGeoms = []
        for param in parameters:
            if param.attributes["Name"].value == "outGeometry":
                for val in param.getElementsByTagName("Val"):
                    outGeoms.append(val.firstChild.nodeValue
                                    )  # contains WKT for one section
        dom.unlink()

        self.secLayer = self.iface.addVectorLayer(
            "Polygon?crs=" + self.visLayer.crs().toWkt(), "Sections", "memory")
        pr = self.secLayer.dataProvider()
        featcnt = 1
        for outGeom in outGeoms:
            obj = ogr.CreateGeometryFromWkt(outGeom)
            geometrycnt = obj.GetGeometryCount()
            centersec = obj.GetGeometryRef(0)
            box = obj.GetGeometryRef(1)
            origin = obj.GetGeometryRef(2)
            pointcloud = obj.GetGeometryRef(3)

            feat = QgsFeature(featcnt)
            points = []
            ring = box.GetGeometryRef(0)
            for i in range(ring.GetPointCount()):
                pt = ring.GetPoint(i)
                points.append(QgsPoint(pt[0], pt[1]))
            feat.setGeometry(QgsGeometry.fromPolygon([points]))
            pr.addFeatures([feat])
            self.sections[featcnt] = {
                'wkt': pointcloud.ExportToWkt(),
                'name': origin.GetY()
            }
            if geometrycnt > 4:
                attrcloud = obj.GetGeometryRef(4)
                self.sections[featcnt]['attr_wkt'] = attrcloud.ExportToWkt()

            featcnt += 1

        self.secLayer.updateExtents()
        self.secLayer.setCustomProperty("qpals-odmpath", "section")
        self.secLayer.setLayerTransparency(50)
        QgsMapLayerRegistry.instance().addMapLayer(self.secLayer)
        self.iface.mapCanvas().refresh()

        self.runSecBtn.setText("Calculate sections")
        self.runSecBtn.setEnabled(True)
Example #5
0
    def runLM(self):
        params = {}
        layer = self.cmbLineLayer.currentLayer()
        if self.selectedChkBox.checkState() == 2:
            infile = tempfile.NamedTemporaryFile(delete=False)
            params["approxFile"] = infile.name + ".shp"
            infile.close()
            QgsVectorFileWriter.writeAsVectorFormat(layer,
                                                    params["approxFile"],
                                                    "utf-8", layer.crs(),
                                                    "ESRI Shapefile",
                                                    1)  # 1 for selected only
            try:
                os.remove(infile.name + ".prj")
            except:
                pass
        else:
            params["approxFile"] = layer.source()

        outfile = tempfile.NamedTemporaryFile(delete=False)
        params["outFile"] = outfile.name + ".shp"
        outfile.close()

        params["inFile"] = self.cmbOdmPath.text()

        Module = QpalsModuleBase.QpalsModuleBase(execName=os.path.join(
            self.project.opalspath, "opalsLineModeler.exe"),
                                                 QpalsProject=self.project)

        paramlist = []
        for param in params.keys():
            paramlist.append(
                QpalsParameter.QpalsParameter(param, params[param], None, None,
                                              None, None, None))
        Module.params = paramlist
        #print "running module. writing outfile to %s" % params["outFile"]
        moduleOut = Module.run(show=0)
        #print moduleOut
        self.iface.addVectorLayer(params["outFile"],
                                  os.path.basename("Modelled Lines"), "ogr")
Example #6
0
def parseXML(xml):
    xml = xml.decode('utf-8').encode('ascii', errors='ignore')
    try:
        dom = minidom.parseString(xml)
    except:
        raise Exception(
            'Error: xml string (%s characters) could not be parsed \n %s' %
            (len(xml), str(xml)))
    outd = dict()
    for type in ['Specific', 'Global', 'Common']:
        elements = []
        specOptsNode = dom.getElementsByTagName(type)[0]
        specOpts = specOptsNode.getElementsByTagName('Parameter')
        for opt in specOpts:
            values = opt.getElementsByTagName('Val')
            choices = opt.getElementsByTagName('Choice')
            choiceList = []
            valString = ""
            if values:
                if len(values) > 1:
                    try:
                        for val in values:
                            valString += val.firstChild.nodeValue + ";"
                        valString = valString[:-1]
                    except:
                        valString = ""
                else:
                    if values[0].firstChild:
                        valString = values[0].firstChild.nodeValue
            if choices:
                for choice in choices:
                    choiceList.append(getTagContent(choice))
            elements.append(
                QpalsParameter.QpalsParameter(
                    opt.attributes['Name'].value, valString, choiceList,
                    opt.attributes['Type'].value, opt.attributes['Opt'].value,
                    opt.attributes['Desc'].value,
                    opt.attributes['LongDesc'].value))
        outd[type] = elements
    return outd
Example #7
0
    def run_next(self):
        self.count += 1
        outShapeFileH = tempfile.NamedTemporaryFile(suffix=".shp", delete=True)
        outShapeFile = outShapeFileH.name
        outShapeFileH.close()

        self.write_axis_shape(outShapeFile)

        self.currattr = self.attrs_left.pop()
        self.secInst.progress.setValue(0)
        self.secInst.progress.setFormat(
            "Running opalsSection for attribute %s (%s/%s)..." %
            (self.currattr, self.count, self.total))
        Module = QpalsModuleBase.QpalsModuleBase(
            execName=os.path.join(self.secInst.project.opalspath,
                                  "opalsSection.exe"),
            QpalsProject=self.secInst.project)
        infile = QpalsParameter.QpalsParameter(
            'inFile', self.secInst.txtinfileSimple.text(), None, None, None,
            None, None)
        axisfile = QpalsParameter.QpalsParameter('axisFile', outShapeFile,
                                                 None, None, None, None, None)
        attribute = QpalsParameter.QpalsParameter('attribute', self.currattr,
                                                  None, None, None, None, None)
        if self.filter.text():
            attribute = QpalsParameter.QpalsParameter('filter',
                                                      self.filter.text(), None,
                                                      None, None, None, None)
        thickness = QpalsParameter.QpalsParameter(
            'patchSize', '%s;%s' % (self.seclength, self.width * 4), None,
            None, None, None, None)

        outParamFileH = tempfile.NamedTemporaryFile(suffix='.xml', delete=True)
        self.outParamFile = outParamFileH.name
        outParamFileH.close()
        outParamFileParam = QpalsParameter.QpalsParameter(
            'outParamFile', self.outParamFile, None, None, None, None, None)
        Module.params.append(infile)
        Module.params.append(axisfile)
        Module.params.append(thickness)
        Module.params.append(attribute)
        Module.params.append(outParamFileParam)
        thread, worker = Module.run_async(status=self.update_status,
                                          on_finish=self.parse_output,
                                          on_error=self.sec_error)
        self.thread.append(thread)
        self.worker.append(worker)
Example #8
0
 def call(self,
          module,
          params,
          outext="",
          returnstdout=False,
          nooutfile=False):
     Module = QpalsModuleBase.QpalsModuleBase(execName=os.path.join(
         self.project.opalspath, module + ".exe"),
                                              QpalsProject=self.project)
     if "outFile" not in params and not nooutfile:
         file = tempfile.NamedTemporaryFile(delete=False)
         params["outFile"] = file.name + outext
         file.close()
     paramlist = []
     for param in params.keys():
         paramlist.append(
             QpalsParameter.QpalsParameter(param, params[param], None, None,
                                           None, None, None))
     Module.params = paramlist
     moduleOut = Module.run(show=0)
     if returnstdout:
         return moduleOut
     return params["outFile"]