def read_cached_dfd_qlr(self): #return file(unicode(self.cached_kf_qlr_filename)).read() f = QFile(self.cached_dfd_qlr_filename) f.open(QIODevice.ReadOnly) return f.readAll()
def read_local_qlr(self): f = QFile(self.local_qlr_filename) f.open(QIODevice.ReadOnly) return f.readAll()
def sendOutputFile(self, handler): formatDict = WFSFormats[self.format] # read the GML outputLayer = QgsVectorLayer( os.path.join(self.tempdir, '%s.gml' % self.filename), 'qgis_server_wfs_features', 'ogr') if outputLayer.isValid(): try: # create save options options = QgsVectorFileWriter.SaveVectorOptions() # driver name options.driverName = formatDict['ogrProvider'] # file encoding options.fileEncoding = 'utf-8' # coordinate transformation if formatDict['forceCRS']: options.ct = QgsCoordinateTransform( outputLayer.crs(), QgsCoordinateReferenceSystem(formatDict['forceCRS']), QgsProject.instance()) # datasource options if formatDict['ogrDatasourceOptions']: options.datasourceOptions = formatDict[ 'ogrDatasourceOptions'] # write file write_result, error_message = QgsVectorFileWriter.writeAsVectorFormat( outputLayer, os.path.join( self.tempdir, '%s.%s' % (self.filename, formatDict['filenameExt'])), options) if write_result != QgsVectorFileWriter.NoError: handler.appendBody(b'') QgsMessageLog.logMessage(error_message, "wfsOutputExtension", Qgis.Critical) return False except Exception as e: handler.appendBody(b'') QgsMessageLog.logMessage(str(e), "wfsOutputExtension", Qgis.Critical) return False if formatDict['zip']: # compress files import zipfile try: import zlib compression = zipfile.ZIP_DEFLATED except: compression = zipfile.ZIP_STORED # create the zip file with zipfile.ZipFile( os.path.join(self.tempdir, '%s.zip' % self.filename), 'w') as zf: # add all files zf.write(os.path.join( self.tempdir, '%s.%s' % (self.filename, formatDict['filenameExt'])), compress_type=compression, arcname='%s.%s' % (self.typename, formatDict['filenameExt'])) for e in formatDict['extToZip']: if os.path.exists( os.path.join(self.tempdir, '%s.%s' % (self.filename, e))): zf.write(os.path.join(self.tempdir, '%s.%s' % (self.filename, e)), compress_type=compression, arcname='%s.%s' % (self.typename, e)) zf.close() f = QFile(os.path.join(self.tempdir, '%s.zip' % self.filename)) if (f.open(QFile.ReadOnly)): ba = f.readAll() handler.appendBody(ba) return True else: # return the file created without zip f = QFile( os.path.join( self.tempdir, '%s.%s' % (self.filename, formatDict['filenameExt']))) if (f.open(QFile.ReadOnly)): ba = f.readAll() handler.appendBody(ba) return True handler.appendBody(b'') QgsMessageLog.logMessage('Error no output file', "wfsOutputExtension", Qgis.Critical) return False
def sendOutputFile(self, handler): format_dict = WFSFormats[self.format] # read the GML gml_path = join(self.tempdir, '{}.gml'.format(self.filename)) output_layer = QgsVectorLayer(gml_path, 'qgis_server_wfs_features', 'ogr') # Temporary file where to write the output temporary = QTemporaryFile( join(QDir.tempPath(), 'request-WFS-XXXXXX.{}'.format(format_dict['filenameExt']))) temporary.open() output_file = temporary.fileName() temporary.close() if output_layer.isValid(): try: # create save options options = QgsVectorFileWriter.SaveVectorOptions() # driver name options.driverName = format_dict['ogrProvider'] # file encoding options.fileEncoding = 'utf-8' # coordinate transformation if format_dict['forceCRS']: options.ct = QgsCoordinateTransform( output_layer.crs(), QgsCoordinateReferenceSystem(format_dict['forceCRS']), QgsProject.instance()) # datasource options if format_dict['ogrDatasourceOptions']: options.datasourceOptions = format_dict[ 'ogrDatasourceOptions'] # write file if Qgis.QGIS_VERSION_INT >= 31003: write_result, error_message = QgsVectorFileWriter.writeAsVectorFormatV2( output_layer, output_file, QgsProject.instance().transformContext(), options) else: write_result, error_message = QgsVectorFileWriter.writeAsVectorFormat( output_layer, output_file, options) if write_result != QgsVectorFileWriter.NoError: handler.appendBody(b'') self.logger.critical(error_message) return False except Exception as e: handler.appendBody(b'') self.logger.critical(str(e)) return False if format_dict['zip']: # compress files import zipfile # noinspection PyBroadException try: import zlib # NOQA compression = zipfile.ZIP_DEFLATED except Exception: compression = zipfile.ZIP_STORED # create the zip file zip_file_path = join(self.tempdir, '%s.zip' % self.filename) with zipfile.ZipFile(zip_file_path, 'w') as zf: # add all files zf.write(join( self.tempdir, '%s.%s' % (self.filename, format_dict['filenameExt'])), compress_type=compression, arcname='%s.%s' % (self.typename, format_dict['filenameExt'])) for e in format_dict['extToZip']: file_path = join(self.tempdir, '%s.%s' % (self.filename, e)) if exists(file_path): zf.write(file_path, compress_type=compression, arcname='%s.%s' % (self.typename, e)) zf.close() f = QFile(zip_file_path) if f.open(QFile.ReadOnly): ba = f.readAll() handler.appendBody(ba) return True else: # return the file created without zip f = QFile(output_file) if f.open(QFile.ReadOnly): ba = f.readAll() handler.appendBody(ba) return True handler.appendBody(b'') self.logger.critical('Error no output file') return False
def send_output_file(self, handler): format_dict = WFSFormats[self.format] # read the GML gml_path = join(self.temp_dir, '{}.gml'.format(self.filename)) output_layer = QgsVectorLayer(gml_path, 'qgis_server_wfs_features', 'ogr') if not output_layer.isValid(): handler.appendBody(b'') self.logger.critical( 'Output layer {} is not valid.'.format(gml_path)) return False # Temporary file where to write the output temporary = QTemporaryFile( join( self.temp_dir, 'to-{}-XXXXXX.{}'.format(self.format, format_dict['filenameExt']))) temporary.open() output_file = temporary.fileName() temporary.remove() # Fix issue #18 try: # create save options options = QgsVectorFileWriter.SaveVectorOptions() # driver name options.driverName = format_dict['ogrProvider'] # file encoding options.fileEncoding = 'utf-8' # coordinate transformation if format_dict['forceCRS']: options.ct = QgsCoordinateTransform( output_layer.crs(), QgsCoordinateReferenceSystem(format_dict['forceCRS']), QgsProject.instance()) # datasource options if format_dict['ogrDatasourceOptions']: options.datasourceOptions = format_dict['ogrDatasourceOptions'] # write file # noinspection PyUnresolvedReferences if Qgis.QGIS_VERSION_INT >= 31003: write_result, error_message = QgsVectorFileWriter.writeAsVectorFormatV2( output_layer, output_file, QgsProject.instance().transformContext(), options) else: write_result, error_message = QgsVectorFileWriter.writeAsVectorFormat( output_layer, output_file, options) if write_result != QgsVectorFileWriter.NoError: handler.appendBody(b'') self.logger.critical(error_message) return False except Exception as e: handler.appendBody(b'') exc_type, _, exc_tb = exc_info() self.logger.critical(str(e)) self.logger.critical(exc_type) self.logger.critical('\n'.join(traceback.format_tb(exc_tb))) return False if format_dict['zip']: # compress files import zipfile try: import zlib # NOQA compression = zipfile.ZIP_DEFLATED except ImportError: compression = zipfile.ZIP_STORED # create the zip file base_filename = splitext(output_file)[0] zip_file_path = join(self.temp_dir, '{}.zip'.format(base_filename)) with zipfile.ZipFile(zip_file_path, 'w') as zf: # Add the main file arc_filename = '{}.{}'.format(self.typename, format_dict['filenameExt']) zf.write(output_file, compress_type=compression, arcname=arc_filename) for extension in format_dict['extToZip']: file_path = join(self.temp_dir, '{}.{}'.format(base_filename, extension)) if exists(file_path): arc_filename = '{}.{}'.format(self.typename, extension) zf.write(file_path, compress_type=compression, arcname=arc_filename) zf.close() f = QFile(zip_file_path) if f.open(QFile.ReadOnly): ba = f.readAll() handler.appendBody(ba) return True else: # return the file created without zip f = QFile(output_file) if f.open(QFile.ReadOnly): ba = f.readAll() handler.appendBody(ba) return True handler.appendBody(b'') self.logger.critical('Error no output file') return False
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', '--angles', '360', '--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