def method_30(self): filePath = define.appPath + "/Resource/settingData/phxtemplates.xml" fileInfo = QFileInfo(filePath) if fileInfo.exists(): QFile.remove(filePath) doc = QDomDocument() rootElem = doc.createElement("Templates") xmlDeclaration = doc.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"utf-8\"") doc.appendChild(xmlDeclaration) for i in range(self.parametersPanel.gridModel.rowCount()): elem = doc.createElement( "Templates" + self.parametersPanel.gridModel.item(i, 0).text()) valueElem = doc.createElement("title") valueElem.appendChild( doc.createTextNode( self.parametersPanel.gridModel.item(i, 0).text())) elem.appendChild(valueElem) valueElem = doc.createElement("space") valueElem.appendChild( doc.createTextNode( self.parametersPanel.gridModel.item(i, 1).text())) elem.appendChild(valueElem) valueElem = doc.createElement("value") valueElem.appendChild( doc.createTextNode( self.parametersPanel.gridModel.item(i, 2).text())) elem.appendChild(valueElem) rootElem.appendChild(elem) doc.appendChild(rootElem) qFile = QFile(filePath) if qFile.open(QFile.WriteOnly): textStream = QTextStream(qFile) doc.save(textStream, 4) qFile.close() # ###CRC file is created. contents = None with open(filePath, 'rb', 0) as tempFile: contents = tempFile.read() tempFile.flush() tempFile.close() bytes = FasDataBlockFile.CRC_Calculation(contents) string_0 = QString(filePath) path = string_0.left(string_0.length() - 3) + "crc" fileStream = open(path, 'wb') fileStream.write(bytes) fileStream.close()
def __init__(self): super(MainWindow, self).__init__(None) uic.loadUi("./mainwindow.ui", self) doc = QDomDocument() # 添加处理指令即XML说明 instruction = QDomProcessingInstruction() instruction = doc.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"") doc.appendChild(instruction) # 添加根元素 root = doc.createElement(QString("书库")) doc.appendChild(root) # 添加根元素 # 添加第一个图书元素及其子元素 book = doc.createElement(QString("图书")) id = doc.createAttribute(QString("编号")) title = doc.createElement(QString("书名")) author = doc.createElement(QString("作者")) text = QDomText() id.setValue(QString("1")) book.setAttributeNode(id) text = doc.createTextNode(QString("Qt")) title.appendChild(text) text = doc.createTextNode(QString("shiming")) author.appendChild(text) book.appendChild(title) # 图书元素 添加 书名元素 book.appendChild(author) # 图书元素 添加 作者元素 root.appendChild(book) # 根元素 添加 图书元素 # 添加第二个图书元素及其子元素 book = doc.createElement(QString("图书")) id = doc.createAttribute(QString("编号")) title = doc.createElement(QString("书名")) author = doc.createElement(QString("作者")) id.setValue(QString("2")) book.setAttributeNode(id) text = doc.createTextNode(QString("Linux")) title.appendChild(text) text = doc.createTextNode(QString("yafei")) author.appendChild(text) book.appendChild(title) book.appendChild(author) root.appendChild(book) file = QFile("my.xml") if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)): raise Exception("open my.xml Err") out = QTextStream(file) doc.save(out, 4) # 将文档保存到文件,4为子元素缩进字符数 file.close()
def on_pushButton_4_clicked(self): # 我们先清空显示,然后显示“无法添加!”,这样如果添加失败则会显示“无法添加!” self.listWidget.clear() self.listWidget.addItem(QString("无法添加!")) file = QFile("my.xml") if (not file.open(QIODevice.ReadOnly)): raise Exception("open my.xml Err") doc = QDomDocument() status, rrorMsg, errorLine, errorColumn = doc.setContent(file) if not status: file.close() raise Exception(str(rrorMsg)) file.close() root = doc.documentElement() # 获取根元素 book = doc.createElement(QString("图书")) id = doc.createAttribute(QString("编号")) title = doc.createElement(QString("书名")) author = doc.createElement(QString("作者")) text = QDomText() # 我们获得了最后一个孩子结点的编号,然后加1,便是新的编号 num = root.lastChild().toElement().attribute(QString("编号")) count = num.toInt() + 1 id.setValue(QString.number(count)) book.setAttributeNode(id) text = doc.createTextNode(self.lineEdit_2.text()) title.appendChild(text) text = doc.createTextNode(self.lineEdit_3.text()) author.appendChild(text) book.appendChild(title) book.appendChild(author) root.appendChild(book) if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)): raise Exception("file open Err") out = QTextStream(file) doc.save(out, 4) file.close() # 最后更改显示为“添加成功!” self.listWidget.clear() self.listWidget.addItem(QString("添加成功!"))
def test_data_name_attr_true(self): fun = sys._getframe().f_code.co_name print "Run: %s.%s() " % (self.__class__.__name__, fun) doc = QDomDocument() nname = "definition" qdn = doc.createElement(nname) doc.appendChild(qdn) nkids = self.__rnd.randint(1, 10) kds = [] tkds = [] for n in range(nkids): kds.append(doc.createElement("kid%s" % n)) kds[-1].setAttribute("name", "myname%s" % n) kds[-1].setAttribute("type", "mytype%s" % n) kds[-1].setAttribute("units", "myunits%s" % n) qdn.appendChild(kds[-1]) tkds.append(doc.createTextNode("\nText\n %s\n" % n)) kds[-1].appendChild(tkds[-1]) # print doc.toString() allAttr = True cm = ComponentModel(doc, allAttr) self.assertTrue(isinstance(cm, QAbstractItemModel)) self.assertTrue(isinstance(cm.rootIndex, QModelIndex)) cd = cm.rootIndex.internalPointer() self.assertTrue(isinstance(cd, ComponentItem)) self.assertEqual(cm.rootIndex.row(), 0) self.assertEqual(cm.rootIndex.column(), 0) self.assertEqual(cm.headerData(0, Qt.Vertical), None) ri = cm.rootIndex di = cm.index(0, 0, ri) ci = cd.child(0) for n in range(nkids): kd = ci.child(n) ki0 = cm.index(n, 0, di) dt = cm.data(ki0) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(dt.toString(), 'kid%s: myname%s' % (n, n)) ki1 = cm.index(n, 1, di) dt = cm.data(ki1) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual( str(dt.toString()).strip(), 'units="myunits%s" type="mytype%s" name="myname%s"' % (n, n, n)) ki2 = cm.index(n, 2, di) dt = cm.data(ki2) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(str(dt.toString()).strip(), '')
class TestView(object): def __init__(self): try: self.__seed = long(binascii.hexlify(os.urandom(16)), 16) except NotImplementedError: self.__seed = long(time.time() * 256) # self.__seed = 71366247078680776091931824685320965500 self.__rnd = random.Random(self.__seed) print "VIEW SEED", self.__seed self.sindex = None self.eindex = None self.doc = QDomDocument() self.nname = "definition" self.qdn = self.doc.createElement(self.nname) self.doc.appendChild(self.qdn) self.nkids = self.__rnd.randint(1, 10) # print "NKID", self.nkids self.kds = [] self.tkds = [] for n in range(self.nkids): self.kds.append(self.doc.createElement("kid%s" % n)) self.kds[-1].setAttribute("name", "myname%s" % n) self.kds[-1].setAttribute("type", "mytype%s" % n) self.kds[-1].setAttribute("units", "myunits%s" % n) self.qdn.appendChild(self.kds[-1]) self.tkds.append(self.doc.createTextNode("\nText\n %s\n" % n)) self.kds[-1].appendChild(self.tkds[-1]) # print doc.toString() self.allAttr = False self.testModel = ComponentModel(self.doc, self.allAttr) # self.myindex = self.setIndex(0, 0, self.testModel.rootIndex) self.myindex = QModelIndex() def setIndex(self, row, column, parent): self.myindex = self.testModel.index(row, column, parent) # print self.myindex.column() def currentIndex(self): return self.myindex def model(self): return self.testModel def dataChanged(self, sindex, eindex): self.sindex = sindex self.eindex = eindex
def adjust(self): """ Export data to GNU Gama xml, adjust the network and read result :returns: result list of adjusment and blunder from GNU Gama """ # gama-local OK? if self.gama_path is None: logging.error("GNU gama path is None") return (None, None) # fix = 0 free network fix = sum([1 for p, s in self.points if s == 'FIX']) adj = sum([1 for p, s in self.points if s == 'ADJ']) if adj == 0 or len(self.observations) < 2: # no unknowns or observations logging.error("GNU gama no unknowns or not enough observations") return (None, None) doc = QDomDocument() doc.appendChild(doc.createComment('Gama XML created by Ulyxes')) gama_local = doc.createElement('gama-local') gama_local.setAttribute('version', '2.0') doc.appendChild(gama_local) network = doc.createElement('network') network.setAttribute('axes-xy', 'ne') network.setAttribute('angles', 'left-handed') gama_local.appendChild(network) description = doc.createElement('description') if self.dimension == 1: description.appendChild(doc.createTextNode('GNU Gama 1D network')) elif self.dimension == 2: description.appendChild(doc.createTextNode('GNU Gama 2D network')) elif self.dimension == 3: description.appendChild(doc.createTextNode('GNU Gama 3D network')) network.appendChild(description) parameters = doc.createElement('parameters') parameters.setAttribute('sigma-apr', '1') parameters.setAttribute('conf-pr', str(self.probability)) parameters.setAttribute('tol-abs', '1000') parameters.setAttribute('sigma-act', 'aposteriori') # parameters.setAttribute('sigma-act', 'apriori') parameters.setAttribute('update-constrained-coordinates', 'yes') network.appendChild(parameters) points_observations = doc.createElement('points-observations') points_observations.setAttribute('distance-stdev', \ str(self.stdev_dist) + ' ' + \ str(self.stdev_dist1)) points_observations.setAttribute('direction-stdev', str(self.stdev_angle / 3600.0 * 10000.0)) points_observations.setAttribute('angle-stdev', str(math.sqrt(2) * self.stdev_angle / 3600.0 * 10000)) points_observations.setAttribute('zenith-angle-stdev', str(self.stdev_angle / 3600.0 * 10000.0)) network.appendChild(points_observations) for p, s in self.points: if self.dimension == 1: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if 'elev' in p and p['elev'] is not None: tmp.setAttribute('z', str(p['elev'])) if s == 'FIX': tmp.setAttribute('fix', 'z') else: if fix == 0: tmp.setAttribute('adj', 'Z') else: tmp.setAttribute('adj', 'z') points_observations.appendChild(tmp) elif self.dimension == 2: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if 'east' in p and 'north' in p and \ p['east'] is not None and p['north'] is not None: tmp.setAttribute('y', str(p['east'])) tmp.setAttribute('x', str(p['north'])) if s == 'FIX': tmp.setAttribute('fix', 'xy') else: if fix == 0: # free network tmp.setAttribute('adj', 'XY') else: tmp.setAttribute('adj', 'xy') points_observations.appendChild(tmp) elif self.dimension == 3: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if 'east' in p and 'north' in p and \ p['east'] is not None and p['north'] is not None: tmp.setAttribute('y', str(p['east'])) tmp.setAttribute('x', str(p['north'])) if 'elev' in p and p['elev'] is not None: tmp.setAttribute('z', str(p['elev'])) if s == 'FIX': tmp.setAttribute('fix', 'xyz') else: if fix == 0: tmp.setAttribute('adj', 'XYZ') else: tmp.setAttribute('adj', 'xyz') points_observations.appendChild(tmp) for o in self.observations: if 'station' in o: # station record sta = doc.createElement('obs') sta.setAttribute('from', o['station']) # instrument height ih = 0 if 'ih' in o: ih = o['ih'] points_observations.appendChild(sta) else: # observation th = 0 if 'th' in o: th = o['th'] if self.dimension == 2: # horizontal network if 'hz' in o: tmp = doc.createElement('direction') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['hz'].GetAngle('GON'))) sta.appendChild(tmp) if 'distance' in o and 'v' in o: # horizontal distance hd = math.sin(o['v'].GetAngle()) * o['distance'] tmp = doc.createElement('distance') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(hd)) sta.appendChild(tmp) elif self.dimension == 1: # elevations only pass elif self.dimension == 3: # 3d if 'hz' in o: tmp = doc.createElement('direction') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['hz'].GetAngle('GON'))) sta.appendChild(tmp) if 'distance' in o: tmp = doc.createElement('s-distance') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['distance'])) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) if 'v' in o: tmp = doc.createElement('z-angle') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['v'].GetAngle('GON'))) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) else: # unknown dimension logging.error("GNU gama unknown dimension") return (None, None) # generate temp file name f = tempfile.NamedTemporaryFile() tmp_name = f.name f.close() f = open(tmp_name + '.xml', 'w') f.write(doc.toString()) #f.write(doc.toByteArray()) f.close() # run gama-local status = os.system(self.gama_path + ' ' + tmp_name + '.xml --text ' + tmp_name + '.txt --xml ' + tmp_name + 'out.xml ' + '--cov-band 0') if status != 0: logging.error("GNU gama failed") return (None, None) xmlParser = QXmlSimpleReader() xmlFile = QFile(tmp_name + 'out.xml') xmlInputSource = QXmlInputSource(xmlFile) doc = QDomDocument() doc.setContent(xmlInputSource, xmlParser) # get adjusted coordinates adj_nodes = doc.elementsByTagName('adjusted') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted coordinates") return (None, None) res = [] adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'point': p = {} for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': p['id'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Y' or ppp.nodeName() == 'y': p['east'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'X' or ppp.nodeName() == 'x': p['north'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Z' or ppp.nodeName() == 'z': p['elev'] = float(ppp.firstChild().nodeValue()) res.append(p) adj_nodes = doc.elementsByTagName('orientation-shifts') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted orientations") return (None, None) adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'orientation': for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': pid = str(ppp.firstChild().nodeValue()) for p in res: if p['id'] == pid: break else: break elif ppp.nodeName() == 'approx': p['appr_ori'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'adj': p['ori'] = float(ppp.firstChild().nodeValue()) # std-dev # TODO usefull for one unknown point in 3D # TODO band must be 0 adj_nodes = doc.elementsByTagName('cov-mat') if adj_nodes.count() < 1: logging.error("GNU gama no covariance matrix") return (None, None) adj_node = adj_nodes.at(0) ii = 0 for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'flt': w = float(pp.firstChild().nodeValue()) if ii == 0: res[0]['std_east'] = math.sqrt(w) ii += 1 elif ii == 1: res[0]['std_north'] = math.sqrt(w) ii += 1 elif ii == 2: res[0]['std_elev'] = math.sqrt(w) ii += 1 elif ii == 3: res[0]['std_ori'] = math.sqrt(w) ii += 1 adj_nodes = doc.elementsByTagName('observations') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted observations") return (None, None) blunder = {'std-residual': 0} adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() in ['direction', 'slope-distance', 'zenith-angle']: o = {'std-residual': 0} for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'from': o['from'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'to': o['to'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'f': o['f'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'std-residual': o['std-residual'] = float(ppp.firstChild().nodeValue()) if o['std-residual'] > self.krit and \ o['std-residual'] > blunder['std-residual'] and \ o['f'] > 10: # extra observations ratio blunder = dict(o) xmlFile.close() # remove input xml and output xml os.remove(tmp_name + '.xml') os.remove(tmp_name + '.txt') os.remove(tmp_name + 'out.xml') return (res, blunder)
def getObservations (self, offering="", properties=[], features=[], procedures=[], filters=None, resultModel = ""): """ :param offering: Offering name :type offering: str :param properties: Selected properties names :type properties: str list :param features: Selected features of interest names :type features: str list :param procedures: Selected procedures names :type procedures: str list :param filters: Configured filters :type filters: FilterRequest :param resultModel: Selected result model :type resultModel: str :return: xml data """ doc = QDomDocument() doc.appendChild(doc.createProcessingInstruction('xml', 'version="1.0" encoding="UTF-8"')) root = doc.createElement('GetObservation') root.setAttribute('xmlns',"http://www.opengis.net/sos/1.0") root.setAttribute('xmlns:ows',"http://www.opengis.net/ows/1.1") root.setAttribute('xmlns:gml',"http://www.opengis.net/gml") root.setAttribute('xmlns:ogc',"http://www.opengis.net/ogc") root.setAttribute('xmlns:om',"http://www.opengis.net/om/1.0") root.setAttribute('xmlns:xsi',"http://www.w3.org/2001/XMLSchema-instance") root.setAttribute('xsi:schemaLocation',"http://www.opengis.net/sos/1.0 http://schemas.opengis.net/sos/1.0.0/sosGetObservation.xsd") root.setAttribute('service',"SOS") root.setAttribute('version',"1.0.0") root.setAttribute('srsName',self[offering].srsName) doc.appendChild(root) offer = doc.createElement("offering") offer.appendChild(doc.createTextNode(offering)) root.appendChild (offer) if filters.temporalFilter: timeEvent = doc.createElement("eventTime") operator = doc.createElement("ogc:%s" % filters.temporalOperator) prop = doc.createElement("ogc:PropertyName") prop.appendChild (doc.createTextNode ("om:samplingTime")) operand = doc.createElement(filters.temporalOperand) if filters.temporalOperand == "gml:TimeInstant": timePos = doc.createElement("gml:timePosition") timePos.appendChild(doc.createTextNode(str(filters.temporalValue))) operand.appendChild (timePos) elif filters.temporalOperand == "gml:TimePeriod": begin = doc.createElement("gml:beginPosition") begin.appendChild(doc.createTextNode(str(filters.temporalValue).split()[0])) end = doc.createElement("gml:endPosition") end.appendChild(doc.createTextNode(str(filters.temporalValue).split()[-1])) operand.appendChild(begin) operand.appendChild(end) root.appendChild(timeEvent) timeEvent.appendChild(operator) operator.appendChild (prop) operator.appendChild (operand) for proc in procedures: procElement = doc.createElement("procedure") procElement.appendChild (doc.createTextNode(proc)) root.appendChild (procElement) for prop in properties: propElement = doc.createElement("observedProperty") propElement.appendChild(doc.createTextNode(prop)) root.appendChild (propElement) foi = doc.createElement("featureOfInterest") if len (features) else None for foiName in features: foiElement = doc.createElement("ObjectID") foiElement.appendChild(doc.createTextNode(foiName)) foi.appendChild (foiElement) if filters.spatialFilter and not foi: foi = doc.createElement("featureOfInterest") operator = doc.createElement("ogc:%s" % filters.spatialOperator) prop = doc.createElement("ogc:PropertyName") prop.appendChild (doc.createTextNode ("urn:ogc:data:location")) operator.appendChild (prop) try: if filters.spatialOperand == "gml:Point": gmlNode = QgsOgcUtils.geometryToGML(QgsGeometry.fromPoint(filters._spatialValue), doc) elif filters.spatialOperand == "gml:Envelope": gmlNode = QgsOgcUtils.rectangleToGMLEnvelope(QgsGeometry.fromRect(filters._spatialValue).boundingBox(), doc) elif filters.spatialOperand == "gml:Polygon": gmlNode = QgsOgcUtils.geometryToGML(QgsGeometry.fromPolygon(filters._spatialValue), doc) elif filters.spatialOperand == "gml:LineString": gmlNode = QgsOgcUtils.geometryToGML(QgsGeometry.fromPolyline(filters._spatialValue), doc) gmlNode.setAttribute('srsName',self[offering].srsName) operator.appendChild (gmlNode) except: pass foi.appendChild(operator) #Lista de features o filtro espacial if foi: root.appendChild(foi) if filters.scalarFilter: result = doc.createElement("result") operator = doc.createElement("ogc:PropertyIs%s" % filters.scalarOperator) prop = doc.createElement("ogc:PropertyName") prop.appendChild (doc.createTextNode (filters.scalarOperand)) operator.appendChild (prop) if filters.scalarOperator in ["Between"]: try: lower = doc.createElement ("ogc:LowerBoundary") lowValue = doc.createElement ("ogc:Literal") lowValue.appendChild(doc.createTextNode(str(filters.scalarValue).split()[0])) lower.appendChild (lowValue) upper = doc.createElement ("ogc:UpperBoundary") upValue = doc.createElement ("ogc:Literal") upValue.appendChild(doc.createTextNode(str(filters.scalarValue).split()[-1])) upper.appendChild (upValue) operator.appendChild (lower) operator.appendChild (upper) except: pass else: value = doc.createElement ("ogc:Literal") value.appendChild(doc.createTextNode(str(filters.scalarValue))) operator.appendChild (value) root.appendChild(result) result.appendChild(operator) responseFormat = doc.createElement ("responseFormat") responseFormat.appendChild (doc.createTextNode('text/xml;subtype="om/1.0.0"')) root.appendChild (responseFormat) resultModelElement = doc.createElement ("resultModel") resultModelElement.appendChild (doc.createTextNode(resultModel)) root.appendChild (resultModelElement) responseMode = doc.createElement ("responseMode") responseMode.appendChild (doc.createTextNode("inline")) root.appendChild (responseMode) return doc.toString(4)
def adjust(self): """ Export data to GNU Gama xml, adjust the network and read result :returns: result list of adjusment from GNU Gama """ # fix = 0 free network fix = 0 adj = 0 for p, s in self.points: if s == 'FIX': fix += 1 else: adj += 1 if adj == 0 or len(self.observations) == 0: # no unknowns or observations return None doc = QDomDocument() doc.appendChild( doc.createComment( 'Gama XML created by SurveyingCalculation plugin for QGIS')) gama_local = doc.createElement('gama-local') gama_local.setAttribute('version', '2.0') doc.appendChild(gama_local) network = doc.createElement('network') network.setAttribute('axes-xy', 'ne') network.setAttribute('angles', 'left-handed') gama_local.appendChild(network) description = doc.createElement('description') if self.dimension == 1: description.appendChild(doc.createTextNode('GNU Gama 1D network')) elif self.dimension == 2: description.appendChild(doc.createTextNode('GNU Gama 2D network')) elif self.dimension == 3: description.appendChild(doc.createTextNode('GNU Gama 3D network')) network.appendChild(description) parameters = doc.createElement('parameters') parameters.setAttribute('sigma-apr', '1') parameters.setAttribute('conf-pr', str(self.probability)) parameters.setAttribute('tol-abs', '1000') parameters.setAttribute('sigma-act', 'aposteriori') parameters.setAttribute('update-constrained-coordinates', 'yes') network.appendChild(parameters) points_observations = doc.createElement('points-observations') points_observations.setAttribute( 'distance-stdev', str(self.stdev_dist) + ' ' + str(self.stdev_dist1)) points_observations.setAttribute('direction-stdev', str(self.stdev_angle)) points_observations.setAttribute('angle-stdev', str(math.sqrt(self.stdev_angle * 2))) points_observations.setAttribute('zenith-angle-stdev', str(self.stdev_angle)) network.appendChild(points_observations) for p, s in self.points: if self.dimension == 1: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.z is not None: tmp.setAttribute('z', str(p.z)) if s == 'FIX': tmp.setAttribute('fix', 'z') else: if fix == 0: tmp.setAttribute('adj', 'Z') else: tmp.setAttribute('adj', 'z') points_observations.appendChild(tmp) elif self.dimension == 2: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.e is not None and p.n is not None: tmp.setAttribute('y', str(p.e)) tmp.setAttribute('x', str(p.n)) if s == 'FIX': tmp.setAttribute('fix', 'xy') else: if fix == 0: # free network tmp.setAttribute('adj', 'XY') else: tmp.setAttribute('adj', 'xy') points_observations.appendChild(tmp) elif self.dimension == 3: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.e is not None and p.n is not None: tmp.setAttribute('y', str(p.e)) tmp.setAttribute('x', str(p.n)) if p.z is not None: tmp.setAttribute('z', str(p.z)) if s == 'FIX': tmp.setAttribute('fix', 'xyz') else: if fix == 0: tmp.setAttribute('adj', 'XYZ') else: tmp.setAttribute('adj', 'xyz') points_observations.appendChild(tmp) if self.dimension == 1: hd = doc.createElement('height-differences') points_observations.appendChild(hd) for o in self.observations: if o.station == 'station': # station record st_id = o.point_id if o.th is None: ih = 0 else: ih = o.th if self.dimension in [2, 3]: sta = doc.createElement('obs') sta.setAttribute('from', o.point_id) points_observations.appendChild(sta) else: # observation if self.dimension == 2: # horizontal network if o.hz is not None: tmp = doc.createElement('direction') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.hz.get_angle('GON'))) sta.appendChild(tmp) if o.d is not None: # horizontal distance hd = o.horiz_dist() if hd is not None: tmp = doc.createElement('distance') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(hd)) sta.appendChild(tmp) elif self.dimension == 1: # elevations only 1d if o.th is None: th = 0 else: th = o.th if o.d is not None and o.v is not None: tmp = doc.createElement('dh') tmp.setAttribute('from', st_id) tmp.setAttribute('to', o.point_id) # TODO hibaterjedes tmp.setAttribute('stdev', '1') sz = math.sin(o.v.get_angle()) w = self.stdev_dist + self.stdev_dist1 * o.d.d / 1000 ro_cc = 200 * 100 * 100 / math.pi if o.d.mode == 'SD': cz = math.cos(o.v.get_angle()) tmp.setAttribute('val', str(o.d.d * cz + ih - th)) tmp.setAttribute( 'stdev', str( math.sqrt(cz**2 * w**2 + (o.d.d * 1000)**2 * sz**2 * (self.stdev_angle / RO_CC)**2))) else: tz = math.tan(o.v.get_angle()) tmp.setAttribute( 'val', str(o.d.d / math.tan(o.v.get_angle()) + ih - th)) tmp.setAttribute( 'stdev', str( math.sqrt((1 / tz)**2 * w**2 + (o.d.d * 1000)**2 * (o.d.d * 1000)**2 * (1 / sz**2)**2 * (self.stdev_angle / RO_CC)**2))) hd.appendChild(tmp) elif self.dimension == 3: # 3d if o.th is None: th = 0 else: th = o.th if o.hz is not None: tmp = doc.createElement('direction') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.hz.get_angle('GON'))) sta.appendChild(tmp) if o.d is not None: if o.d.mode == 'SD': tmp = doc.createElement('s-distance') tmp.setAttribute('val', str(o.d.d)) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) else: tmp = doc.createElement('distance') tmp.setAttribute('val', str(o.d.d)) tmp.setAttribute('to', o.point_id) sta.appendChild(tmp) if o.v is not None: tmp = doc.createElement('z-angle') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.v.get_angle('GON'))) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) else: # unknown dimension return None # generate temp file name tmpf = QTemporaryFile(QDir.temp().absoluteFilePath('w')) tmpf.open(QIODevice.WriteOnly) tmpf.close() tmp_name = tmpf.fileName() f = QFile(tmp_name + '.xml') if f.open(QIODevice.WriteOnly): f.write(doc.toByteArray()) f.close() # run gama-local if self.gama_prog is None: return None status = QProcess.execute(self.gama_prog, [ tmp_name + '.xml', '--text', tmp_name + '.txt', '--xml', tmp_name + 'out.xml' ]) if status != 0: return None xmlParser = QXmlSimpleReader() xmlFile = QFile(tmp_name + 'out.xml') xmlInputSource = QXmlInputSource(xmlFile) doc.setContent(xmlInputSource, xmlParser) f_txt = QFile(tmp_name + '.txt') f_txt.open(QIODevice.ReadOnly) res = f_txt.readAll().data() f_txt.close() # store coordinates adj_nodes = doc.elementsByTagName('adjusted') if adj_nodes.count() < 1: return res adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'point': for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': p = Point(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Y' or ppp.nodeName() == 'y': p.e = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'X' or ppp.nodeName() == 'x': p.n = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Z' or ppp.nodeName() == 'z': p.z = float(ppp.firstChild().nodeValue()) ScPoint(p).store_coord(self.dimension) # remove input xml and output xml tmpf.remove() f_txt.remove() f.remove() xmlFile.remove() return res
def adjust(self): """ Export data to GNU Gama xml, adjust the network and read result :returns: result list of adjusment from GNU Gama """ # fix = 0 free network fix = 0 adj = 0 for p, s in self.points: if s == 'FIX': fix += 1 else: adj += 1 if adj == 0 or len(self.observations) == 0: # no unknowns or observations return None doc = QDomDocument() doc.appendChild(doc.createComment('Gama XML created by Land Surveying plugin for QGIS')) gama_local = doc.createElement('gama-local') gama_local.setAttribute('version', '2.0') doc.appendChild(gama_local) network = doc.createElement('network') network.setAttribute('axes-xy', 'ne') network.setAttribute('angles', 'left-handed') gama_local.appendChild(network) description = doc.createElement('description') if self.dimension == 1: description.appendChild(doc.createTextNode('GNU Gama 1D network')) elif self.dimension == 2: description.appendChild(doc.createTextNode('GNU Gama 2D network')) elif self.dimension == 3: description.appendChild(doc.createTextNode('GNU Gama 3D network')) network.appendChild(description) parameters = doc.createElement('parameters') parameters.setAttribute('sigma-apr', '1') parameters.setAttribute('conf-pr', str(self.probability)) parameters.setAttribute('tol-abs', '1000') parameters.setAttribute('sigma-act', 'aposteriori') parameters.setAttribute('update-constrained-coordinates', 'yes') network.appendChild(parameters) points_observations = doc.createElement('points-observations') points_observations.setAttribute('distance-stdev', str(self.stdev_dist) + ' ' + str(self.stdev_dist1)) points_observations.setAttribute('direction-stdev', str(self.stdev_angle)) points_observations.setAttribute('angle-stdev', str(math.sqrt(self.stdev_angle * 2))) points_observations.setAttribute('zenith-angle-stdev', str(self.stdev_angle)) network.appendChild(points_observations) for p, s in self.points: if self.dimension == 1: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.z is not None: tmp.setAttribute('z', str(p.z)) if s == 'FIX': tmp.setAttribute('fix', 'z') else: if fix == 0: tmp.setAttribute('adj', 'Z') else: tmp.setAttribute('adj', 'z') points_observations.appendChild(tmp) elif self.dimension == 2: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.e is not None and p.n is not None: tmp.setAttribute('y', str(p.e)) tmp.setAttribute('x', str(p.n)) if s == 'FIX': tmp.setAttribute('fix', 'xy') else: if fix == 0: # free network tmp.setAttribute('adj', 'XY') else: tmp.setAttribute('adj', 'xy') points_observations.appendChild(tmp) elif self.dimension == 3: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.e is not None and p.n is not None: tmp.setAttribute('y', str(p.e)) tmp.setAttribute('x', str(p.n)) if p.z is not None: tmp.setAttribute('z', str(p.z)) if s == 'FIX': tmp.setAttribute('fix', 'xyz') else: if fix == 0: tmp.setAttribute('adj', 'XYZ') else: tmp.setAttribute('adj', 'xyz') points_observations.appendChild(tmp) for o in self.observations: if o.station == 'station': # station record sta = doc.createElement('obs') sta.setAttribute('from', o.point_id) if o.th is None: ih = 0 else: ih = o.th points_observations.appendChild(sta) else: # observation if self.dimension == 2: # horizontal network if o.hz is not None: tmp = doc.createElement('direction') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.hz.get_angle('GON'))) sta.appendChild(tmp) if o.d is not None: # horizontal distance hd = o.horiz_dist() if hd is not None: tmp = doc.createElement('distance') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(hd)) sta.appendChild(tmp) elif self.dimension == 1: # elevations only pass elif self.dimension == 3: # 3d if o.th is None: th = o.th else: th = 0 if o.hz is not None: tmp = doc.createElement('direction') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.hz.get_angle('GON'))) sta.appendChild(tmp) if o.d is not None: if o.d.mode == 'SD': tmp = doc.createElement('s-distance') tmp.setAttribute('val', str(o.d.d)) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) else: tmp = doc.createElement('distance') tmp.setAttribute('val', str(o.d.d)) tmp.setAttribute('to', o.point_id) sta.appendChild(tmp) if o.v is not None: tmp = doc.createElement('z-angle') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.v.get_angle('GON'))) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) else: # unknown dimension return None #print doc.toprettyxml(indent=" ") # generate temp file name tmpf = QTemporaryFile( QDir.temp().absoluteFilePath('w') ) tmpf.open(QIODevice.WriteOnly) tmpf.close() tmp_name = tmpf.fileName() f = QFile(tmp_name + '.xml') if f.open(QIODevice.WriteOnly): f.write(doc.toByteArray()) f.close() # run gama-local if self.gama_prog is None: return None # status = call([str(self.gama_prog), str(tmp_name) + '.xml', '--text', # str(tmp_name) + '.txt', '--xml', str(tmp_name) + 'out.xml']) status = QProcess.execute(self.gama_prog, [ tmp_name+'.xml', '--text', tmp_name+'.txt', '--xml', tmp_name+'out.xml']) if status != 0: return None xmlParser = QXmlSimpleReader() xmlFile = QFile(tmp_name + 'out.xml') xmlInputSource = QXmlInputSource(xmlFile) doc.setContent(xmlInputSource,xmlParser) f_txt = QFile(tmp_name + '.txt') f_txt.open(QIODevice.ReadOnly) res = f_txt.readAll().data() f_txt.close() # store coordinates adj_nodes = doc.elementsByTagName('adjusted') if adj_nodes.count() < 1: return res adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'point': for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': p = Point(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Y' or ppp.nodeName() == 'y': p.e = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'X' or ppp.nodeName() == 'x': p.n = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Z' or ppp.nodeName() == 'z': p.z = float(ppp.firstChild().nodeValue()) ScPoint(p).store_coord(self.dimension) # remove input xml and output xml tmpf.remove() f_txt.remove() f.remove() xmlFile.remove() return res
class XFORMDocument: """ class to generate an Xml file that is needed for data collection using mobile device. The class creates the file and QDOM sections for holding data once the file is called """ def __init__(self, fname): """ Initalize the class so that we have a new file everytime document generation method is called """ self.dt_text = QDate() self.file_handler = FilePaths() self.doc = QDomDocument() self.form = None self.fname = fname self.doc_with_entities = [] self.supports_doc = self.document() def document(self): """ use the globally defined Document name for supporting document :return: """ global DOCUMENT return DOCUMENT def form_name(self): """ Format the name for the new file to be created. We need to ensure it is .xml file. :return: """ if len(self.fname.split(".")) > 1: return self.fname else: return self.fname+"{}".format(DOCEXTENSION) def set_form_name(self, local_name): """ Allow the user to update the name of the file. This method will be called to return a new file with the local_name given :param local_name: string :return: QFile """ self.fname = local_name+"{}".format(DOCEXTENSION) self.form.setFileName(self.fname) self.create_form() return self.fname def create_form(self): """ Create an XML file that will be our XFORM Document for reading and writing We want a new file when everytime we are creating XForm type: file :return: file """ self.form = QFile(os.path.join(FORM_HOME, self.form_name())) if not QFileInfo(self.form).suffix() == DOCEXTENSION: self.form_name() if not self.form.open(QIODevice.ReadWrite | QIODevice.Truncate | QIODevice.Text): return self.form.OpenError def create_node(self, name): """ Create a XML element node :param name: :return: node :rtype: QelementNode """ return self.doc.createElement(name) def create_text_node(self, text): """ Create an XML text node :param text: :return: """ return self.doc.createTextNode(text) def create_node_attribute(self, node, key, value): """ Create an attribute and attach it to the node :param node: Qnode :param key: Qnode name :param value: Qnode value :return: QNode """ return node.setAttribute(key, value) def xform_document(self): """ :return: QDomDocument """ return self.doc def write_to_form(self): """ Write data to xml file from the base calling class to an output file created earlier :return: """ if isinstance(self.form, QFile): self.form.write(self.doc.toByteArray()) self.form.close() self.doc.clear() else: return None def update_form_data(self): """ Update the xml file with changes that the user has made. Particular section of the document will be deleted or added :return: """ pass
def createAndParseSld(qgisLayerItem): document = QDomDocument() header = document.createProcessingInstruction( 'xml', 'version=\'1.0\' encoding=\'UTF-8\'') document.appendChild(header) root = document.createElementNS('http://www.opengis.net/sld', 'StyledLayerDescriptor') root.setAttribute('version', '1.0.0') root.setAttribute('xmlns:ogc', 'http://www.opengis.net/ogc') root.setAttribute('xmlns:sld', 'http://www.opengis.net/sld') root.setAttribute('xmlns:gml', 'http://www.opengis.net/gml') document.appendChild(root) namedLayerNode = document.createElement('sld:NamedLayer') root.appendChild(namedLayerNode) qgisLayerItem.layer.writeSld(namedLayerNode, document, '') ## TODO: if could not be created... nameNode = namedLayerNode.firstChildElement('se:Name') oldNameText = nameNode.firstChild() newname = qgisLayerItem.parentShogunLayer.source['layerNames'] newNameText = document.createTextNode(newname) nameNode.appendChild(newNameText) nameNode.removeChild(oldNameText) userStyleNode = namedLayerNode.firstChildElement('UserStyle') userStyleNameNode = userStyleNode.firstChildElement('se:Name') userStyleNameText = userStyleNameNode.firstChild() userStyleNameNode.removeChild(userStyleNameText) userStyleNameNode.appendChild( document.createTextNode(qgisLayerItem.stylename)) titleNode = document.createElement('sld:Title') title = document.createTextNode('A QGIS-Style for ' + qgisLayerItem.layer.name()) titleNode.appendChild(title) userStyleNode.appendChild(titleNode) defaultNode = document.createElement('sld:IsDefault') defaultNode.appendChild(document.createTextNode('1')) userStyleNode.appendChild(defaultNode) featureTypeStyleNode = userStyleNode.firstChildElement( 'se:FeatureTypeStyle') featureTypeStyleNameNode = document.createElement('sld:Name') featureTypeStyleNameNode.appendChild(document.createTextNode('name')) featureTypeStyleNode.appendChild(featureTypeStyleNameNode) rules = featureTypeStyleNode.elementsByTagName('se:Rule') for x in range(rules.length()): rule = rules.at(x) rule.removeChild(rule.firstChildElement('se:Description')) # Check if custom icons are used in symbology and replace the text: # search if tag 'se:OnlineResource' is in the sld document listOfGraphics = rule.toElement().elementsByTagName('se:OnlineResource') if not listOfGraphics.isEmpty(): for x in range(listOfGraphics.length()): graphicNode = listOfGraphics.at(x) currentIcon = graphicNode.attributes().namedItem( 'xlink:href').nodeValue() iconUrl = qgisLayerItem.ressource.prepareIconForUpload(currentIcon) graphicNode.toElement().setAttribute('xlink:href', iconUrl) graphicNode.toElement().setAttribute( 'xmlns:xlink', 'http://www.w3.org/1999/xlink') sld = document.toString() if qgisLayerItem.layer.labelsEnabled(): labelSld = getLabelingAsSld(qgisLayerItem.layer) sld = sld.replace('</se:Rule>', labelSld + '</se:Rule>') sld = sld.replace('ogc:Filter xmlns:ogc="http://www.opengis.net/ogc"', 'ogc:Filter') # the following fixes weird problems with the sld compability with the # shogun webapp sld = sld.replace('<ogc:And>', '') sld = sld.replace('</ogc:And>', '') sld = sld.replace('<se:Name> ', '<se:Name>') sld = sld.replace(' </se:Name>', '</se:Name>') sld = sld.replace('StyledLayerDescriptor', 'sld:StyledLayerDescriptor') sld = sld.replace('UserStyle', 'sld:UserStyle') sld = sld.replace('se:', 'sld:') sld = sld.replace('SvgParameter', 'CssParameter') sld = sld.replace('\n', '') sld = sld.replace('\t', '') return sld
def test_insertItem(self): fun = sys._getframe().f_code.co_name print "Run: %s.%s() " % (self.__class__.__name__, fun) doc = QDomDocument() nname = "definition" qdn = doc.createElement(nname) doc.appendChild(qdn) nkids = self.__rnd.randint(1, 10) kds = [] tkds = [] for n in range(nkids): kds.append(doc.createElement("kid%s" % n)) kds[-1].setAttribute("name", "myname%s" % n) kds[-1].setAttribute("type", "mytype%s" % n) kds[-1].setAttribute("units", "myunits%s" % n) qdn.appendChild(kds[-1]) tkds.append(doc.createTextNode("\nText\n %s\n" % n)) kds[-1].appendChild(tkds[-1]) # print doc.toString() allAttr = True cm = ComponentModel(doc, allAttr) self.assertTrue(isinstance(cm, QAbstractItemModel)) self.assertTrue(isinstance(cm.rootIndex, QModelIndex)) cd = cm.rootIndex.internalPointer() self.assertTrue(isinstance(cd, ComponentItem)) self.assertEqual(cm.rootIndex.row(), 0) self.assertEqual(cm.rootIndex.column(), 0) ri = cm.rootIndex self.assertEqual(cm.columnCount(ri), 3) # avoids showing #document di = cm.index(0, 0, ri) self.assertEqual(cm.columnCount(di), 3) iv = cm.index(0, 0) self.assertEqual(cm.columnCount(iv), 3) ci = di.internalPointer() self.assertEqual(ci.node, qdn) self.assertEqual(ci.childNumber(), 0) self.assertEqual(ci.node.nodeName(), nname) for k in range(nkids): ks = ci.child(k) self.assertTrue(isinstance(ks, ComponentItem)) self.assertTrue(isinstance(ks.parent, ComponentItem)) self.assertEqual(ks.childNumber(), k) self.assertEqual(ks.node, kds[k]) self.assertEqual(ks.parent.node, qdn) self.assertEqual(ks.node.nodeName(), "kid%s" % k) self.assertEqual(ks.parent, ci) self.assertTrue(isinstance(ks.child(0), ComponentItem)) self.assertTrue(isinstance(ks.child(0).parent, ComponentItem)) self.assertEqual(ks.child(0).childNumber(), 0) self.assertEqual(ks.child(0).node, tkds[k]) self.assertEqual(ks.child(0).parent.node, ks.node) self.assertEqual(ks.child(0).node.nodeName(), "#text") self.assertEqual( ks.child(0).node.toText().data(), '\nText\n %s\n' % k) self.assertEqual(ks.child(0).parent, ks) insd = self.__rnd.randint(0, nkids - 1) inkd = doc.createElement("insertedkid") self.assertTrue(not cm.insertItem(insd, inkd, QModelIndex())) self.assertTrue(cm.insertItem(insd, inkd, di)) for k in range(nkids + 1): ks = ci.child(k) if k == insd: self.assertTrue(isinstance(ks, ComponentItem)) self.assertTrue(isinstance(ks.parent, ComponentItem)) self.assertEqual(ks.childNumber(), k) self.assertEqual(ks.node, inkd) self.assertEqual(ks.parent.node, qdn) self.assertEqual(ks.node.nodeName(), "insertedkid") self.assertEqual(ks.parent, ci) continue kk = k if k < insd else k - 1 self.assertTrue(isinstance(ks, ComponentItem)) self.assertTrue(isinstance(ks.parent, ComponentItem)) self.assertEqual(ks.childNumber(), k) self.assertEqual(ks.node, kds[kk]) self.assertEqual(ks.parent.node, qdn) self.assertEqual(ks.node.nodeName(), "kid%s" % kk) self.assertEqual(ks.parent, ci) self.assertTrue(isinstance(ks.child(0), ComponentItem)) self.assertTrue(isinstance(ks.child(0).parent, ComponentItem)) self.assertEqual(ks.child(0).childNumber(), 0) self.assertEqual(ks.child(0).node, tkds[kk]) self.assertEqual(ks.child(0).parent.node, ks.node) self.assertEqual(ks.child(0).node.nodeName(), "#text") self.assertEqual( ks.child(0).node.toText().data(), '\nText\n %s\n' % kk) self.assertEqual(ks.child(0).parent, ks)
def test_columnCount(self): fun = sys._getframe().f_code.co_name print "Run: %s.%s() " % (self.__class__.__name__, fun) doc = QDomDocument() nname = "definition" qdn = doc.createElement(nname) doc.appendChild(qdn) nkids = self.__rnd.randint(1, 10) kds = [] tkds = [] for n in range(nkids): kds.append(doc.createElement("kid%s" % n)) kds[-1].setAttribute("name", "myname%s" % n) kds[-1].setAttribute("type", "mytype%s" % n) kds[-1].setAttribute("units", "myunits%s" % n) qdn.appendChild(kds[-1]) tkds.append(doc.createTextNode("\nText\n %s\n" % n)) kds[-1].appendChild(tkds[-1]) # print doc.toString() allAttr = True cm = ComponentModel(doc, allAttr) self.assertTrue(isinstance(cm, QAbstractItemModel)) self.assertTrue(isinstance(cm.rootIndex, QModelIndex)) cd = cm.rootIndex.internalPointer() self.assertTrue(isinstance(cd, ComponentItem)) self.assertEqual(cm.rootIndex.row(), 0) self.assertEqual(cm.rootIndex.column(), 0) ri = cm.rootIndex self.assertEqual(cm.columnCount(ri), 3) # avoids showing #document di = cm.index(0, 0, ri) self.assertEqual(cm.columnCount(di), 3) iv = cm.index(0, 0) self.assertEqual(cm.columnCount(iv), 3) for n in range(nkids): allAttr = not allAttr cm.setAttributeView(allAttr) ki = cm.index(n, 0, di) self.assertEqual(cm.columnCount(ki), 3) ki = cm.index(n, 1, di) self.assertEqual(cm.columnCount(ki), 3) ki = cm.index(n, 2, di) self.assertEqual(cm.columnCount(ki), 3) # invalid index ki = cm.index(n, 3, di) self.assertEqual(cm.columnCount(ki), 3) ki = cm.index(n, 0, di) ti = cm.index(0, 0, ki) self.assertEqual(cm.columnCount(ti), 3) ti = cm.index(0, 1, ki) self.assertEqual(cm.columnCount(ti), 3) ti = cm.index(0, 2, ki) self.assertEqual(cm.columnCount(ti), 3) ti = cm.index(0, 3, ki) self.assertEqual(cm.columnCount(ti), 3)
def adjust(self): """ Export data to GNU Gama xml, adjust the network and read result :returns: result list of adjusment and blunder from GNU Gama """ # gama-local OK? if self.gama_path is None: logging.error("GNU gama path is None") return (None, None) # fix = 0 free network fix = sum([1 for p, s in self.points if s == 'FIX']) adj = sum([1 for p, s in self.points if s == 'ADJ']) if adj == 0 or len(self.observations) < 2: # no unknowns or observations logging.error("GNU gama no unknowns or not enough observations") return (None, None) doc = QDomDocument() doc.appendChild(doc.createComment('Gama XML created by Ulyxes')) gama_local = doc.createElement('gama-local') gama_local.setAttribute('version', '2.0') doc.appendChild(gama_local) network = doc.createElement('network') network.setAttribute('axes-xy', 'ne') network.setAttribute('angles', 'left-handed') gama_local.appendChild(network) description = doc.createElement('description') if self.dimension == 1: description.appendChild(doc.createTextNode('GNU Gama 1D network')) elif self.dimension == 2: description.appendChild(doc.createTextNode('GNU Gama 2D network')) elif self.dimension == 3: description.appendChild(doc.createTextNode('GNU Gama 3D network')) network.appendChild(description) parameters = doc.createElement('parameters') parameters.setAttribute('sigma-apr', '1') parameters.setAttribute('conf-pr', str(self.probability)) parameters.setAttribute('tol-abs', '1000') parameters.setAttribute('sigma-act', 'aposteriori') # parameters.setAttribute('sigma-act', 'apriori') parameters.setAttribute('update-constrained-coordinates', 'yes') network.appendChild(parameters) points_observations = doc.createElement('points-observations') points_observations.setAttribute( 'distance-stdev', str(self.stdev_dist) + ' ' + str(self.stdev_dist1)) points_observations.setAttribute( 'direction-stdev', str(self.stdev_angle / 3600.0 * 10000.0)) points_observations.setAttribute( 'angle-stdev', str(math.sqrt(2) * self.stdev_angle / 3600.0 * 10000)) points_observations.setAttribute( 'zenith-angle-stdev', str(self.stdev_angle / 3600.0 * 10000.0)) network.appendChild(points_observations) for p, s in self.points: if self.dimension == 1: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if p['elev'] is not None: tmp.setAttribute('z', str(p['elev'])) if s == 'FIX': tmp.setAttribute('fix', 'z') else: if fix == 0: tmp.setAttribute('adj', 'Z') else: tmp.setAttribute('adj', 'z') points_observations.appendChild(tmp) elif self.dimension == 2: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if p['east'] is not None and p['north'] is not None: tmp.setAttribute('y', str(p['east'])) tmp.setAttribute('x', str(p['north'])) if s == 'FIX': tmp.setAttribute('fix', 'xy') else: if fix == 0: # free network tmp.setAttribute('adj', 'XY') else: tmp.setAttribute('adj', 'xy') points_observations.appendChild(tmp) elif self.dimension == 3: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if p['east'] is not None and p['north'] is not None: tmp.setAttribute('y', str(p['east'])) tmp.setAttribute('x', str(p['north'])) if p['elev'] is not None: tmp.setAttribute('z', str(p['elev'])) if s == 'FIX': tmp.setAttribute('fix', 'xyz') else: if fix == 0: tmp.setAttribute('adj', 'XYZ') else: tmp.setAttribute('adj', 'xyz') points_observations.appendChild(tmp) for o in self.observations: if 'station' in o: # station record sta = doc.createElement('obs') sta.setAttribute('from', o['station']) # instrument height ih = 0 if 'ih' in o: ih = o['ih'] points_observations.appendChild(sta) else: # observation th = 0 if 'th' in o: th = o['th'] if self.dimension == 2: # horizontal network if 'hz' in o: tmp = doc.createElement('direction') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['hz'].GetAngle('GON'))) sta.appendChild(tmp) if 'distance' in o and 'v' in o: # horizontal distance hd = math.sin(o['v'].GetAngle()) * o['distance'] tmp = doc.createElement('distance') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(hd)) sta.appendChild(tmp) elif self.dimension == 1: # elevations only pass elif self.dimension == 3: # 3d if 'hz' in o: tmp = doc.createElement('direction') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['hz'].GetAngle('GON'))) sta.appendChild(tmp) if 'distance' in o: tmp = doc.createElement('s-distance') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['distance'])) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) if 'v' in o: tmp = doc.createElement('z-angle') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['v'].GetAngle('GON'))) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) else: # unknown dimension logging.error("GNU gama unknown dimension") return (None, None) # generate temp file name f = tempfile.NamedTemporaryFile() tmp_name = f.name f.close() f = open(tmp_name + '.xml', 'w') f.write(doc.toByteArray()) f.close() # run gama-local status = os.system(self.gama_path + ' ' + tmp_name + '.xml --text ' + tmp_name + '.txt --xml ' + tmp_name + 'out.xml') if status != 0: logging.error("GNU gama failed") return (None, None) xmlParser = QXmlSimpleReader() xmlFile = QFile(tmp_name + 'out.xml') xmlInputSource = QXmlInputSource(xmlFile) doc.setContent(xmlInputSource, xmlParser) # get adjusted coordinates adj_nodes = doc.elementsByTagName('adjusted') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted coordinates") return (None, None) res = [] adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'point': p = {} for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': p['id'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Y' or ppp.nodeName() == 'y': p['east'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'X' or ppp.nodeName() == 'x': p['north'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Z' or ppp.nodeName() == 'z': p['elev'] = float(ppp.firstChild().nodeValue()) # TODO standard deviation of coords to p res.append(p) adj_nodes = doc.elementsByTagName('observations') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted observations") return (None, None) blunder = {'std-residual': 0} adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() in [ 'direction', 'slope-distance', 'zenith-angle' ]: o = {'std-residual': 0} for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'from': o['from'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'to': o['to'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'f': o['f'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'std-residual': o['std-residual'] = float(ppp.firstChild().nodeValue()) if o['std-residual'] > self.krit and \ o['std-residual'] > blunder['std-residual'] and \ o['f'] > 10: # extra observations ratio blunder = dict(o) xmlFile.close() # remove input xml and output xml os.remove(tmp_name + '.xml') os.remove(tmp_name + '.txt') os.remove(tmp_name + 'out.xml') return (res, blunder)
def WriteProjectInfoXml(self): doc = QDomDocument() rootElem = doc.createElement("ProjectListClass") xmlDeclaration = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"") doc.appendChild(xmlDeclaration) elem = doc.createElement("ProjectCount") elem.appendChild(doc.createTextNode(str(len(self.ProjectsList)))) rootElem.appendChild(elem) for i in range(len(self.ProjectsList)): elem = doc.createElement("ProjectInfo") objNameElem = doc.createElement("Name") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Name)) elem.appendChild(objNameElem) objNameElem = doc.createElement("Path") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Path)) elem.appendChild(objNameElem) objNameElem = doc.createElement("Created") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Created)) elem.appendChild(objNameElem) objNameElem = doc.createElement("ProcedureName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].ProcedureName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("ProjName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].ProjName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("Pt") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Pt)) elem.appendChild(objNameElem) objNameElem = doc.createElement("SubProjName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].SubProjName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("UserName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].UserName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("WorkspaceName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].WorkspaceName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("FullName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].FullName)) elem.appendChild(objNameElem) rootElem.appendChild(elem) doc.appendChild(rootElem) qFile = QFile(self.m_strProjectInfoFullName) if qFile.open(QFile.WriteOnly): textStream = QTextStream(qFile) doc.save(textStream, 4) qFile.close() # ###CRC file is created. with open(self.m_strProjectInfoFullName, 'rb', 0) as tempFile: contents = tempFile.read() tempFile.flush() tempFile.close() bytes = FasDataBlockFile.CRC_Calculation(contents) string_0 = QString(self.m_strProjectInfoFullName) path = string_0.left(string_0.length() - 3) + "crc" fileStream = open(path, 'wb') fileStream.write(bytes) fileStream.close() else: raise UserWarning, "can not open file:" + self.m_strProjectInfoFullName
def getObservations(self, offering="", properties=[], features=[], procedures=[], filters=None, resultModel=""): """ :param offering: Offering name :type offering: str :param properties: Selected properties names :type properties: str list :param features: Selected features of interest names :type features: str list :param procedures: Selected procedures names :type procedures: str list :param filters: Configured filters :type filters: FilterRequest :param resultModel: Selected result model :type resultModel: str :return: xml data """ doc = QDomDocument() doc.appendChild( doc.createProcessingInstruction('xml', 'version="1.0" encoding="UTF-8"')) root = doc.createElement('GetObservation') root.setAttribute('xmlns', "http://www.opengis.net/sos/1.0") root.setAttribute('xmlns:ows', "http://www.opengis.net/ows/1.1") root.setAttribute('xmlns:gml', "http://www.opengis.net/gml") root.setAttribute('xmlns:ogc', "http://www.opengis.net/ogc") root.setAttribute('xmlns:om', "http://www.opengis.net/om/1.0") root.setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance") root.setAttribute( 'xsi:schemaLocation', "http://www.opengis.net/sos/1.0 http://schemas.opengis.net/sos/1.0.0/sosGetObservation.xsd" ) root.setAttribute('service', "SOS") root.setAttribute('version', "2.0.0") root.setAttribute('srsName', self[offering].srsName) doc.appendChild(root) offer = doc.createElement("offering") offer.appendChild(doc.createTextNode(offering)) root.appendChild(offer) if filters.temporalFilter: timeEvent = doc.createElement("eventTime") operator = doc.createElement("ogc:%s" % filters.temporalOperator) prop = doc.createElement("ogc:PropertyName") prop.appendChild(doc.createTextNode("om:samplingTime")) operand = doc.createElement(filters.temporalOperand) if filters.temporalOperand == "gml:TimeInstant": timePos = doc.createElement("gml:timePosition") timePos.appendChild( doc.createTextNode(str(filters.temporalValue))) operand.appendChild(timePos) elif filters.temporalOperand == "gml:TimePeriod": begin = doc.createElement("gml:beginPosition") begin.appendChild( doc.createTextNode(str(filters.temporalValue).split()[0])) end = doc.createElement("gml:endPosition") end.appendChild( doc.createTextNode(str(filters.temporalValue).split()[-1])) operand.appendChild(begin) operand.appendChild(end) root.appendChild(timeEvent) timeEvent.appendChild(operator) operator.appendChild(prop) operator.appendChild(operand) for proc in procedures: procElement = doc.createElement("procedure") procElement.appendChild(doc.createTextNode(proc)) root.appendChild(procElement) for prop in properties: propElement = doc.createElement("observedProperty") propElement.appendChild(doc.createTextNode(prop)) root.appendChild(propElement) foi = doc.createElement("featureOfInterest") if len(features) else None for foiName in features: foiElement = doc.createElement("ObjectID") foiElement.appendChild(doc.createTextNode(foiName)) foi.appendChild(foiElement) if filters.spatialFilter and not foi: foi = doc.createElement("featureOfInterest") operator = doc.createElement("ogc:%s" % filters.spatialOperator) prop = doc.createElement("ogc:PropertyName") prop.appendChild(doc.createTextNode("urn:ogc:data:location")) operator.appendChild(prop) try: if filters.spatialOperand == "gml:Point": gmlNode = QgsOgcUtils.geometryToGML( QgsGeometry.fromPoint(filters._spatialValue), doc) elif filters.spatialOperand == "gml:Envelope": gmlNode = QgsOgcUtils.rectangleToGMLEnvelope( QgsGeometry.fromRect( filters._spatialValue).boundingBox(), doc) elif filters.spatialOperand == "gml:Polygon": gmlNode = QgsOgcUtils.geometryToGML( QgsGeometry.fromPolygon(filters._spatialValue), doc) elif filters.spatialOperand == "gml:LineString": gmlNode = QgsOgcUtils.geometryToGML( QgsGeometry.fromPolyline(filters._spatialValue), doc) gmlNode.setAttribute('srsName', self[offering].srsName) operator.appendChild(gmlNode) except: pass foi.appendChild(operator) #Lista de features o filtro espacial if foi: root.appendChild(foi) if filters.scalarFilter: result = doc.createElement("result") operator = doc.createElement("ogc:PropertyIs%s" % filters.scalarOperator) prop = doc.createElement("ogc:PropertyName") prop.appendChild(doc.createTextNode(filters.scalarOperand)) operator.appendChild(prop) if filters.scalarOperator in ["Between"]: try: lower = doc.createElement("ogc:LowerBoundary") lowValue = doc.createElement("ogc:Literal") lowValue.appendChild( doc.createTextNode( str(filters.scalarValue).split()[0])) lower.appendChild(lowValue) upper = doc.createElement("ogc:UpperBoundary") upValue = doc.createElement("ogc:Literal") upValue.appendChild( doc.createTextNode( str(filters.scalarValue).split()[-1])) upper.appendChild(upValue) operator.appendChild(lower) operator.appendChild(upper) except: pass else: value = doc.createElement("ogc:Literal") value.appendChild(doc.createTextNode(str(filters.scalarValue))) operator.appendChild(value) root.appendChild(result) result.appendChild(operator) responseFormat = doc.createElement("responseFormat") responseFormat.appendChild( doc.createTextNode('text/xml;subtype="om/2.0.0"')) root.appendChild(responseFormat) resultModelElement = doc.createElement("resultModel") resultModelElement.appendChild(doc.createTextNode(resultModel)) root.appendChild(resultModelElement) responseMode = doc.createElement("responseMode") responseMode.appendChild(doc.createTextNode("inline")) root.appendChild(responseMode) return doc.toString(4)