def addLayer(self, twoDMFileName):
        from crayfish_viewer_plugin_layer import CrayfishViewerPluginLayer
        layer = CrayfishViewerPluginLayer(twoDMFileName)
        if not layer.isValid():
            layer.showMeshLoadError(twoDMFileName)
            return None

        # Add to layer registry
        QgsMapLayerRegistry.instance().addMapLayer(layer)

        import crayfish
        warn = crayfish.last_load_status()[1]
        if warn == crayfish.Warn_UnsupportedElement:
            # Unsupported element seen
            qgis_message_bar.pushMessage(
                "Crayfish",
                "The mesh contains elements that are unsupported at this time. The following types of elements will be ignored for the time being: E2L, E3L, E6T, E8Q, E9Q",
                level=QgsMessageBar.WARNING)
        elif warn == crayfish.Warn_InvalidElements:
            qgis_message_bar.pushMessage(
                "Crayfish",
                "The mesh contains some invalid elements, they will not be rendered.",
                level=QgsMessageBar.WARNING)

        return layer
    def loadMesh(self, inFileName, fileType):
        # Load mesh as new Crayfish layer for file
        # In file is container of multiple meshes, load them all separately (e.g. netCFD file)
        data_sources_to_add = [inFileName]
        if fileType == '.nc':
            # this one is container of multiple sublayers
            temp_raster = QgsRasterLayer(inFileName)
            if (not temp_raster.isValid()) and (len(temp_raster.subLayers()) >
                                                1):
                data_sources_to_add = temp_raster.subLayers()

        for data_source in data_sources_to_add:
            layerWith2dm = self.getLayerWith2DM(data_source)

            if layerWith2dm:
                # This 2dm has already been added
                qgis_message_bar.pushMessage(
                    "Crayfish",
                    "The mesh file is already loaded in layer " +
                    layerWith2dm.name(),
                    level=QgsMessageBar.INFO)
                return False

            if not self.addLayer(data_source):
                return False  # addLayer() reports errors/warnings

        return True  # success
    def loadDatFile(self, inFileName, parentLayer=None):
        """
            The user is adding a result set:
                Determine its dat file name
                If we have that layer open, add this result to the layer
                Else create a new layer and add to that one
        """

        if not parentLayer:
            parentLayer = self.loadMeshForFile(inFileName)
            if not parentLayer:
                return  # error message has been shown already

        if parentLayer.isDataSetLoaded(inFileName):
            qgis_message_bar.pushMessage(
                "Crayfish",
                "The data file is already loaded in layer " +
                parentLayer.name(),
                level=QgsMessageBar.INFO)
            return

        dsCountBefore = parentLayer.mesh.dataset_count()

        # try to load it as binary file, if not successful, try as ASCII format
        try:
            QApplication.setOverrideCursor(Qt.WaitCursor)
            parentLayer.mesh.load_data(inFileName)
            QApplication.restoreOverrideCursor()
        except ValueError:
            QApplication.restoreOverrideCursor()
            import crayfish
            err = crayfish.last_load_status()[0]
            # reuse from showMeshLoadError
            err_msgs = {
                crayfish.Err_NotEnoughMemory: 'Not enough memory',
                crayfish.Err_FileNotFound:
                'Unable to read the file - missing file or no read access',
                crayfish.Err_UnknownFormat: 'File format not recognized',
                crayfish.Err_IncompatibleMesh: 'Mesh is not compatible'
            }
            msg = "Failed to load the data file"
            if err in err_msgs:
                msg += " (%s)" % err_msgs[err]
            qgis_message_bar.pushMessage("Crayfish",
                                         msg,
                                         level=QgsMessageBar.CRITICAL)
            return

        dsCountAfter = parentLayer.mesh.dataset_count()

        for index in xrange(dsCountBefore, dsCountAfter):
            parentLayer.initCustomValues(parentLayer.mesh.dataset(index))

        # set to most recent data set (first one from the newly added datasets)
        parentLayer.current_ds_index = dsCountBefore
        # update GUI
        self.dock.currentLayerChanged()
        # allow user to go through the time steps with arrow keys
        self.dock.cboTime.setFocus()
    def addCrayfishLayer(self):
        """
            The user wants to view an Crayfish layer
            This layer could be either a .2dm file or a .dat file
            If a .dat file is loaded:
                That result is added to a layer already referencing its .2dm
                Or if no such layer exists, a new layer is created
        """

        # First get the file name of the 'thing' the user wants to view

        # Get the file name
        inFileName = QFileDialog.getOpenFileName(
            self.iface.mainWindow(), 'Open Crayfish Dat File',
            self.lastFolder(),
            "Results Files DAT, SOL, XMDF, GRIB, HEC2D, netCDF, HEC 2D (*.dat *.sol *.xmdf *.sww *.grb *.bin *.grib *.grib1 *.grib2 *.hdf *.nc *.hdf);;2DM Mesh Files (*.2dm)"
        )
        inFileName = unicode(inFileName)
        if len(inFileName) == 0:  # If the length is 0 the user pressed cancel
            return

        # Store the path we just looked in
        head, tail = os.path.split(inFileName)
        self.setLastFolder(head)

        # Determine what type of file it is
        prefix, fileType = os.path.splitext(tail)
        fileType = fileType.lower()
        if (fileType == '.2dm' or fileType == '.sww' or fileType == '.grb'
                or fileType == '.bin' or fileType == '.grib'
                or fileType == '.grib1' or fileType == '.grib2'
                or fileType == '.nc' or fileType == '.hdf'):
            """
                The user has selected a mesh file...
            """
            if not self.loadMesh(inFileName, fileType):
                return

            # update GUI
            self.dock.currentLayerChanged()

        elif fileType == '.dat' or fileType == '.sol' or fileType == '.xmdf':
            """
                The user has selected a results-only file...
            """
            self.loadDatFile(inFileName)

        else:
            # This is an unsupported file type
            qgis_message_bar.pushMessage(
                "Crayfish",
                "The file type you are trying to load is not supported: " +
                fileType,
                level=QgsMessageBar.CRITICAL)
            return
 def showMeshLoadError(self, twoDMFileName):
     e = crayfish.last_load_status()[0]
     if e == crayfish.Err_NotEnoughMemory:
       qgis_message_bar.pushMessage("Crayfish", "Not enough memory to open the mesh file (" + twoDMFileName + ").", level=QgsMessageBar.CRITICAL)
     elif e == crayfish.Err_FileNotFound:
       qgis_message_bar.pushMessage("Crayfish", "Failed to open the mesh file (" + twoDMFileName + ").", level=QgsMessageBar.CRITICAL)
     elif e == crayfish.Err_UnknownFormat:
       qgis_message_bar.pushMessage("Crayfish", "Mesh file format not recognized (" + twoDMFileName + ").", level=QgsMessageBar.CRITICAL)
Beispiel #6
0
 def showMeshLoadError(self, twoDMFileName):
     e = crayfish.last_load_status()[0]
     if e == crayfish.Err_NotEnoughMemory:
         qgis_message_bar.pushMessage(
             "Crayfish",
             "Not enough memory to open the mesh file (" + twoDMFileName +
             ").",
             level=QgsMessageBar.CRITICAL)
     elif e == crayfish.Err_FileNotFound:
         qgis_message_bar.pushMessage("Crayfish",
                                      "Failed to open the mesh file (" +
                                      twoDMFileName + ").",
                                      level=QgsMessageBar.CRITICAL)
     elif e == crayfish.Err_UnknownFormat:
         qgis_message_bar.pushMessage("Crayfish",
                                      "Mesh file format not recognized (" +
                                      twoDMFileName + ").",
                                      level=QgsMessageBar.CRITICAL)
    def readXml(self, node):
        element = node.toElement()
        prj = QgsProject.instance()

        # load mesh
        twoDmFile = prj.readPath( element.attribute('meshfile') )
        self.loadMesh(twoDmFile)

        if not self.isValid():
            self.showMeshLoadError(twoDmFile)
            return False

        # load bed settings
        bedElem = element.firstChildElement("bed")
        if not bedElem.isNull():
          ds = self.mesh.dataset(0)
          self.readDataSetXml(ds, bedElem)

        # load data files
        datNodes = element.elementsByTagName("dat")
        for i in xrange(datNodes.length()):
            datElem = datNodes.item(i).toElement()
            datFilePath = prj.readPath( datElem.attribute('path') )
            try:
                if not self.isDataSetLoaded(datFilePath):
                    self.mesh.load_data(datFilePath)
            except ValueError:
                qgis_message_bar.pushMessage("Crayfish", "Unable to load dataset " + datFilePath, level=QgsMessageBar.WARNING)
                continue
            dsName = datElem.attribute("name")
            if len(dsName) != 0:
                # dat files can contain multiple datasets - name identifies which one
                ds = self.mesh.dataset_from_name(dsName)
            else:
                # project file before names started to be used - assuming just one dataset per file
                ds = self.mesh.dataset(self.mesh.dataset_count()-1)
            self.readDataSetXml(ds, datElem)

            dsUserName = datElem.attribute("user-name")
            if len(dsUserName) != 0:
                ds_index = list(self.mesh.datasets()).index(ds)
                self.ds_user_names[ds_index] = dsUserName


        # load settings
        currentDataSetIndex = qstring2int(element.attribute("current-dataset"))
        if currentDataSetIndex is not None:
            self.current_ds_index = currentDataSetIndex

        currentOutputTime = qstring2float(element.attribute("current-output-time"))
        if currentOutputTime is not None:
            self.current_output_time = currentOutputTime

        lockCurrent = qstring2bool(element.attribute("lock-current"))
        if lockCurrent is not None:
            self.lockCurrent = lockCurrent

        contour_ds_index = qstring2int(element.attribute("display-contour"))
        if contour_ds_index is not None:
            self.contour_ds_index = contour_ds_index

        vector_ds_index = qstring2int(element.attribute("display-vector"))
        if vector_ds_index is not None:
            self.vector_ds_index = vector_ds_index

        # mesh rendering
        meshElem = element.firstChildElement("render-mesh")
        if not meshElem.isNull():
            meshRendering = qstring2bool(meshElem.attribute("enabled"))
            if meshRendering is not None:
                self.config["mesh"] = meshRendering
            meshColor = qstring2rgb(meshElem.attribute("color"))
            if meshColor is not None:
                self.config["m_color"] = meshColor

        return True
Beispiel #8
0
    def readXml(self, node):
        element = node.toElement()
        prj = QgsProject.instance()

        # load mesh
        twoDmFile = prj.readPath(element.attribute('meshfile'))
        self.loadMesh(twoDmFile)

        if not self.isValid():
            self.showMeshLoadError(twoDmFile)
            return False

        # load bed settings
        bedElem = element.firstChildElement("bed")
        if not bedElem.isNull():
            ds = self.mesh.dataset(0)
            self.readDataSetXml(ds, bedElem)

        # load data files
        datNodes = element.elementsByTagName("dat")
        for i in xrange(datNodes.length()):
            datElem = datNodes.item(i).toElement()
            datFilePath = prj.readPath(datElem.attribute('path'))
            try:
                if not self.isDataSetLoaded(datFilePath):
                    self.mesh.load_data(datFilePath)
            except ValueError:
                qgis_message_bar.pushMessage("Crayfish",
                                             "Unable to load dataset " +
                                             datFilePath,
                                             level=QgsMessageBar.WARNING)
                continue
            dsName = datElem.attribute("name")
            if len(dsName) != 0:
                # dat files can contain multiple datasets - name identifies which one
                ds = self.mesh.dataset_from_name(dsName)
            else:
                # project file before names started to be used - assuming just one dataset per file
                ds = self.mesh.dataset(self.mesh.dataset_count() - 1)
            self.readDataSetXml(ds, datElem)

            dsUserName = datElem.attribute("user-name")
            if len(dsUserName) != 0:
                ds_index = list(self.mesh.datasets()).index(ds)
                self.ds_user_names[ds_index] = dsUserName

        # load settings
        currentDataSetIndex = qstring2int(element.attribute("current-dataset"))
        if currentDataSetIndex is not None:
            self.current_ds_index = currentDataSetIndex

        currentOutputTime = qstring2float(
            element.attribute("current-output-time"))
        if currentOutputTime is not None:
            self.current_output_time = currentOutputTime

        lockCurrent = qstring2bool(element.attribute("lock-current"))
        if lockCurrent is not None:
            self.lockCurrent = lockCurrent

        contour_ds_index = qstring2int(element.attribute("display-contour"))
        if contour_ds_index is not None:
            self.contour_ds_index = contour_ds_index

        vector_ds_index = qstring2int(element.attribute("display-vector"))
        if vector_ds_index is not None:
            self.vector_ds_index = vector_ds_index

        # mesh rendering
        meshElem = element.firstChildElement("render-mesh")
        if not meshElem.isNull():
            meshRendering = qstring2bool(meshElem.attribute("enabled"))
            if meshRendering is not None:
                self.config["mesh"] = meshRendering
            meshColor = qstring2rgb(meshElem.attribute("color"))
            if meshColor is not None:
                self.config["m_color"] = meshColor

        return True