def get_plugin_state():
    from qgis.utils import pluginMetadata
    """TODO: Make the paths clickable links to open folder
        def create_path_link(path):
            path = os.path.normpath(path)
            #"<a href={}>Open Project Folder</a>".format("`C:/Progra~1/needed"`)
            return '<a href= file:///"`{0}"`>{0}</a>'.format(path)
        """
    plug_state = 'QGIS Environment :\n'

    plug_state += '    {:20}\t{}\n'.format('QGIS :', Qgis.QGIS_VERSION)
    qgis_prefix = qgis.core.QgsApplication.prefixPath()

    if platform.system() == 'Windows':
        qgis_prefix = os.path.abspath(win32api.GetLongPathName(qgis_prefix))

    plug_state += '    {:20}\t{}\n'.format('Install Path : ', qgis_prefix)

    plug_state += '    {:20}\t{}\n'.format('Plugin Dir :',
                                           os.path.normpath(PLUGIN_DIR))
    plug_state += '    {:20}\t{}\n'.format(
        'Temp Folder :', os.path.normpath(tempfile.gettempdir()))

    plug_state += '    {:20}\t{}\n'.format('Python :', sys.version)
    plug_state += '    {:20}\t{}\n'.format(
        'GDAL :', os.environ.get('GDAL_VERSION', None))

    plug_state += '\nPAT Version :\n'
    plug_state += '    {:20}\t{} {}\n'.format(
        'PAT :', pluginMetadata('pat', 'version'),
        pluginMetadata('pat', 'update_date'))
    plug_state += '    {:20}\t{}\n'.format(
        'pyPrecAg :',
        get_distribution('pyprecag').version)
    plug_state += '    {:20}\t{}\n'.format(
        'Geopandas :',
        get_distribution('geopandas').version)
    plug_state += '    {:20}\t{}\n'.format(
        'Rasterio :',
        get_distribution('rasterio').version)
    plug_state += '    {:20}\t{}\n'.format('Fiona :',
                                           get_distribution('fiona').version)
    plug_state += '    {:20}\t{}\n'.format('Pandas :',
                                           get_distribution('pandas').version)

    plug_state += '\nR Configuration :\n'
    plug_state += '    {:20}\t{}\n'.format(
        'R Active :', read_setting('Processing/Configuration/ACTIVATE_R'))
    plug_state += '    {:20}\t{}\n'.format(
        'R Install Folder :',
        read_setting('Processing/Configuration/R_FOLDER'))
    return plug_state
コード例 #2
0
 def _load_available_trackers(self):
     self.PluginChooser.addItem("", None)
     for pl in plugins.keys():
         if pl:
             tracker = pluginMetadata(pl, 'tracker')
             if "github.com" in tracker:
                 self.PluginChooser.addItem(pl, tracker)
コード例 #3
0
ファイル: explorer.py プロジェクト: menegon/suite-qgis-plugin
 def reportError():
     dlg = ErrorReportDialog()
     dlg.exec_()
     if dlg.message is not None:
         version = "Plugin version: " + pluginMetadata("opengeo", "version")
         email = "Email:" + settings.value("/OpenGeo/Settings/General/SentryEmail", "")
         username = "******" + settings.value("/OpenGeo/Settings/General/SentryUserName", "")
         description = "Description: " + dlg.message            
         self.ravenClient.captureMessage("\n".join([unicode(msg, errors = "ignore"), version, email, username, description]))
     self.resetActivity()
コード例 #4
0
    def _load_additional_info(self):
        plugin = self.PluginChooser.itemText(self.PluginChooser.currentIndex())

        qgis_info = str(QGis.QGIS_VERSION)
        platform_info = "{} {}".format(platform.system(), platform.release())
        plugin_info = "{} {}".format(plugin, pluginMetadata(plugin, "version"))

        txt = "{}, QGIS {} on {}".format(plugin_info, qgis_info, platform_info)

        self.AdditionalInfoLineEdit.setText(txt)
コード例 #5
0
 def reportError():
     dlg = ErrorReportDialog()
     dlg.exec_()
     if dlg.message is not None:
         version = "Plugin version: " + pluginMetadata("opengeo", "version")
         email = "Email:" + settings.value("/OpenGeo/Settings/General/SentryEmail", "")
         username = "******" + settings.value("/OpenGeo/Settings/General/SentryUserName", "")
         description = "Description: " + dlg.message            
         self.ravenClient.captureMessage("\n".join([unicode(msg, errors = "ignore"), version, email, username, description]))
     self.resetActivity()
コード例 #6
0
    def _load_available_trackers(self):
        self.PluginChooser.addItem("", None)
        plugins_to_show = sorted(available_plugins, key=lambda s: s.lower())
        for plugin_name in plugins_to_show:
            if plugin_name:
                tracker = pluginMetadata(plugin_name, 'tracker')
                if "error" in tracker:
                    tracker = ""

                self.PluginChooser.addItem(plugin_name, tracker)
コード例 #7
0
    def __init__(self, trace, parent = None):
        super(GeoGigErrorDialog, self).__init__(parent)
        pluginVersion = "Plugin version: " + pluginMetadata("geogig", "version")
        try:
            geogigpyVersion = "Geogig-py version: " + geogigpy.__version__
        except:
            geogigpyVersion = "Geogig-py version: Not available"
        geogigVersion = "GeoGig version: " + _geogigVersion()

        self.trace = "\n".join([pluginVersion, geogigpyVersion, geogigVersion, trace])
        QtGui.QApplication.restoreOverrideCursor()
        self.initGui()
コード例 #8
0
    def __init__(self, trace, parent=None):
        super(GeoGigErrorDialog, self).__init__(parent)
        pluginVersion = "Plugin version: " + pluginMetadata(
            "geogig", "version")
        try:
            geogigpyVersion = "Geogig-py version: " + geogigpy.__version__
        except:
            geogigpyVersion = "Geogig-py version: Not available"
        geogigVersion = "GeoGig version: " + _geogigVersion()

        self.trace = "\n".join(
            [pluginVersion, geogigpyVersion, geogigVersion, trace])
        QtGui.QApplication.restoreOverrideCursor()
        self.initGui()
コード例 #9
0
ファイル: service.py プロジェクト: 3liz/qgis-atlasprint
 def get_capabilities(params: Dict[str, str], response: QgsServerResponse,
                      project: QgsProject) -> None:
     """ Get atlas capabilities based on metadata file
     """
     _ = params, project
     plugin_name = 'atlasprint'
     body = {
         'status': 'success',
         'metadata': {
             'name': plugin_name,
             'version': pluginMetadata(plugin_name, 'version'),
         }
     }
     write_json_response(body, response)
     return
コード例 #10
0
ファイル: service.py プロジェクト: yverdon/geocity
 def get_capabilities(
     params: Dict[str, str], response: QgsServerResponse, project: QgsProject
 ) -> None:
     """ Get atlas capabilities based on metadata file
     """
     _ = params, project
     plugin_name = "atlasprint"
     body = {
         "status": "success",
         "metadata": {
             "name": plugin_name,
             "version": pluginMetadata(plugin_name, "version"),
         },
     }
     write_json_response(body, response)
     return
コード例 #11
0
def check_python_dependencies(plugin_path, iface):
    """ Check for extra python modules which the plugin requires.

    If they are not installed, a windows batch file will be created on the users desktop.
    Run this as administrator to install relevant packages

    Args:
         iface (): The QGIs gui interface required to add messagebar too.
         plugin_path (): The path to the users plugin directory.

    Returns (bool): Passed Check or Not.
    """

    try:
        # comes from metadata.txt
        from qgis.utils import pluginMetadata
        meta_version = '{} {} '.format(pluginMetadata('pat', 'version'),
                                       pluginMetadata('pat', 'update_date'))

        # # get the list of wheels matching the gdal version
        # if not os.environ.get('GDAL_VERSION', None):
        #     gdal_ver = osgeo.gdal.__version__
        #     LOGGER.warning(
        #         'Environment Variable GDAL_VERSION does not exist. Setting to {}'.format(gdal_ver))
        #     os.environ['GDAL_VERSION'] = gdal_ver

        # the name of the install file.
        title = 'Install_PAT3_Extras'
        if platform.system() == 'Windows':
            user_path = os.path.join(os.path.expanduser('~'))
            shortcutPath = os.path.join(user_path, 'Desktop',
                                        title.replace('_', ' ') + '.lnk')
            osgeo_path = os.path.abspath(
                win32api.GetLongPathName(os.environ['OSGEO4W_ROOT']))

            if os.path.exists(shortcutPath):
                # Copy logs into PAT plugin folder
                pass
        else:
            osgeo_path = os.path.abspath(os.environ['OSGEO4W_ROOT'])

        qgis_prefix_path = os.path.abspath(QgsApplication.prefixPath())

        packCheck = {}
        pip_packs = []
        osgeo_packs = []

        #packCheck['gdal300dll']={'Action': '', 'Version': ''}
        if not os.path.exists(os.path.join(osgeo_path, 'bin', 'gdal300.dll')):
            packCheck['gdal300dll'] = {'Action': 'Install', 'Version': ''}
            osgeo_packs += ['gdal300dll']

        # Check for the listed modules.
        for argCheck in ['fiona', 'geopandas', 'rasterio']:
            packCheck[argCheck] = check_package(argCheck)
            if packCheck[argCheck]['Action'] == 'Install':
                osgeo_packs += [argCheck]

        packCheck['pyprecag'] = check_package('pyprecag')
        cur_pyprecag_ver = check_pip_for_update('pyprecag')
        if cur_pyprecag_ver is not None:
            if parse_version(packCheck['pyprecag']['Version']) < parse_version(
                    cur_pyprecag_ver):
                packCheck['pyprecag']['Action'] = 'Upgrade'

        if packCheck['fiona']['Action'] == 'Install':
            message = ''

            if 'ltr' in os.path.basename(QgsApplication.prefixPath()).lower():
                if Qgis.QGIS_VERSION_INT < 31011:
                    message = 'PAT is no longer supported by QGIS LTR {}\nPlease upgrade to the current QGIS release.'.format(
                        Qgis.QGIS_VERSION)

            elif Qgis.QGIS_VERSION_INT < 31600:
                message = 'PAT is no longer supported by QGIS {}\nPlease upgrade to the current QGIS release.'.format(
                    Qgis.QGIS_VERSION)

            if message != '':
                iface.messageBar().pushMessage(message,
                                               level=Qgis.Critical,
                                               duration=30)
                LOGGER.info(message)
                QMessageBox.critical(None, 'QGIS Upgrade required', message)
                return (message)

        # Install via a tar wheel file prior to publishing via pip to test pyprecag bug fixes
        # otherwise just use a standard pip install.
        local_wheel = glob.glob1(os.path.join(plugin_path, 'install_files'),
                                 "pyprecag*")
        if len(local_wheel) == 1 and 'installed' not in local_wheel[0]:
            packCheck['pyprecag']['Action'] = 'Upgrade'
            pip_packs += [local_wheel[0]]
        elif packCheck['pyprecag']['Action'] in ['Install', 'Upgrade']:
            pip_packs += ['{}'.format('pyprecag')]

        failDependencyCheck = [
            key for key, val in packCheck.items()
            if val['Action'] in ['Install', 'Upgrade']
        ]

        osgeo_packs = [
            '-P ' + p if 'gdal' in p else '-P python3-' + p
            for p in osgeo_packs
        ]

        # create a dictionary to use with the template file.
        d = {
            'dependency_log':
            os.path.join(
                plugin_path, 'install_files',
                'dependency_{}.log'.format(date.today().strftime("%Y-%m-%d"))),
            'QGIS_PATH':
            osgeo_path,
            'QGIS_VERSION':
            Qgis.QGIS_VERSION,
            'osgeo_message':
            'Installing {}'.format(', '.join(osgeo_packs)),
            'osgeo_packs':
            '' if len(osgeo_packs) == 0 else ' '.join(osgeo_packs),
            'pip_func':
            'install',
            'pip_packs':
            '' if len(pip_packs) == 0 else ' '.join(pip_packs),
            'py_version':
            struct.calcsize("P") * 8
        }  # this will return 64 or 32

        # 'osgeo_uninst': ' -x python3-'.join(['fiona', 'geopandas', 'rasterio'])
        temp_file = os.path.join(plugin_path, 'util',
                                 'Install_PAT3_Extras.template')
        install_file = os.path.join(
            plugin_path, 'install_files',
            '{}_4_qgis{}.bat'.format(title,
                                     str(Qgis.QGIS_VERSION_INT)[:-2]))
        uninstall_file = os.path.join(
            plugin_path, 'install_files',
            'Un{}_4_qgis{}.bat'.format(title,
                                       str(Qgis.QGIS_VERSION_INT)[:-2]))
        python_version = struct.calcsize("P") * 8  # this will return 64 or 32

        if not os.path.exists(os.path.dirname(install_file)):
            os.mkdir(os.path.dirname(install_file))

        if len(failDependencyCheck) > 0:

            create_file_from_template(temp_file, d, install_file)

            # Create a shortcut on desktop with admin privileges.
            if platform.system() == 'Windows':
                try:
                    aReg = ConnectRegistry(None, HKEY_CURRENT_USER)
                    aKey = OpenKey(
                        aReg,
                        r"Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
                    )
                    aVal = os.path.normpath(QueryValueEx(aKey, "Desktop")[0])
                    LOGGER.info(
                        'Desktop path from registry is {}'.format(aVal))
                except:
                    pass

                LOGGER.critical(
                    "Failed Dependency Check. Please run the shortcut {} "
                    "or the following bat file as administrator {}".format(
                        shortcutPath, install_file))

                create_link(shortcutPath, install_file,
                            "Install setup for QGIS PAT Plugin", user_path,
                            True)

            message = 'Installation or updates are required for {}.\n\nPlease quit QGIS and run {} ' \
                      'located on your desktop.'.format(', '.join(failDependencyCheck), title)
            iface.messageBar().pushMessage("ERROR Failed Dependency Check",
                                           message,
                                           level=Qgis.Critical,
                                           duration=0)
            QMessageBox.critical(None, 'Failed Dependency Check', message)
            return (message)
        else:

            settings_version = read_setting(PLUGIN_NAME + "/PAT_VERSION")

            if settings_version is None:
                LOGGER.info('Successfully installed and setup PAT {}'.format(
                    meta_version))
            else:
                if parse_version(meta_version) > parse_version(
                        settings_version):
                    LOGGER.info(
                        'Successfully upgraded and setup PAT from {} to {})'.
                        format(settings_version, meta_version))

                elif parse_version(meta_version) < parse_version(
                        settings_version):
                    LOGGER.info(
                        'Successfully downgraded and setup PAT from {} to {})'.
                        format(settings_version, meta_version))

            write_setting(PLUGIN_NAME + '/PAT_VERSION', meta_version)

            if os.path.exists(shortcutPath):
                os.remove(shortcutPath)

            if len(osgeo_packs) == 0:
                osgeo_packs = ['geopandas', 'rasterio']

            if len(pip_packs) == 0:
                pip_packs = ["pyprecag"]

            d.update({
                'osgeo_message':
                'Installing {}'.format(', '.join(osgeo_packs)),
                'osgeo_packs':
                '' if len(osgeo_packs) == 0 else '-P python3-' +
                ' -P python3-'.join(osgeo_packs),
                'pip_packs':
                '' if len(pip_packs) == 0 else ' '.join(pip_packs),
            })

            # Create master un&install files
            create_file_from_template(temp_file, d, install_file)

            d.update({
                'osgeo_message':
                'Uninstalling {}'.format(', '.join(osgeo_packs)),
                'osgeo_packs':
                '-o -x python3-' + ' -x python3-'.join(osgeo_packs),
                'pip_func':
                'uninstall'
            })

            create_file_from_template(temp_file, d, uninstall_file)

    except Exception as err:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        mess = str(traceback.format_exc())

        setup = get_plugin_state()
        LOGGER.info(setup + '\n\n')
        LOGGER.error('\n' + mess)

        message = (
            'An error occurred during setup, please report this error to [email protected] '
            'and attach the following files \n\t {} \n\t{}'.format(
                get_logger_file(), install_file))

        QMessageBox.critical(None, 'Failed setup', message)

        sys.exit(message + '\n\n' + mess)

    return failDependencyCheck
コード例 #12
0
def write_case(
    feedback,
    dem_layer,
    landuse_layer,
    path,
    chid,
    wgs84_origin,
    utm_origin,
    wgs84_fire_origin,
    utm_fire_origin,
    utm_crs,
    verts,
    faces,
    landuses,
    landuse_type,
    mesh_extent,
):
    """
    Get FDS case.
    """

    feedback.pushInfo("Writing the FDS case file...")

    # Calc header
    pv = pluginMetadata("qgis2fds", "version")
    qv = QgsExpressionContextUtils.globalScope().variable("qgis_version")
    now = time.strftime("%a, %d %b %Y, %H:%M:%S", time.localtime())
    filepath = QgsProject.instance().fileName() or "not saved"
    if len(filepath) > 60:
        filepath = "..." + filepath[-57:]

    # Calc MESH XB
    mesh_xb = (
        mesh_extent.xMinimum() - utm_origin.x(),
        mesh_extent.xMaximum() - utm_origin.x(),
        mesh_extent.yMinimum() - utm_origin.y(),
        mesh_extent.yMaximum() - utm_origin.y(),
        min(v[2] for v in verts) - 1.0,
        max(v[2] for v in verts) + 50.0,
    )

    # Calc MESH IJK
    cell_size = 10.0
    mesh_ijk = (
        int((mesh_xb[1] - mesh_xb[0]) / cell_size),
        int((mesh_xb[3] - mesh_xb[2]) / cell_size),
        int((mesh_xb[5] - mesh_xb[4]) / cell_size),
    )

    # Calc ignition point VENT XB
    fx, fy = (
        utm_fire_origin.x() - utm_origin.x(),  # relative to origin
        utm_fire_origin.y() - utm_origin.y(),
    )
    fxb = (
        fx - cell_size / 2,
        fx + cell_size / 2,
        fy - cell_size / 2,
        fy + cell_size / 2,
        mesh_xb[4],
        mesh_xb[4],
    )

    # Prepare and write FDS file
    content = f"""
! Generated by qgis2fds <{pv}> on QGIS <{qv}>
! QGIS file: <{filepath}>
! Selected UTM CRS: <{utm_crs.description()}>
! Terrain extent: <{mesh_extent.toString(precision=1)}>
! DEM layer: <{dem_layer.name()}>
! Landuse layer: <{landuse_layer and landuse_layer.name() or 'None'}>
! Landuse type: <{landuse_layer and ('Landfire FBFM13', 'CIMA Propagator')[landuse_type] or 'None'}>
! Domain Origin: <{utm_origin.x():.1f}, {utm_origin.y():.1f}>
!   {utils.get_lonlat_url(wgs84_origin)}
! Fire Origin: <{utm_fire_origin.x():.1f}, {utm_fire_origin.y():.1f}>
!   {utils.get_lonlat_url(wgs84_fire_origin)}
! Date: <{now}>
 
&HEAD CHID='{chid}' TITLE='Description of {chid}' /
&TIME T_END=1200. /

! MISC LEVEL_SET_MODE parameter
! 1: Wind not affected by the terrain. No fire.
! 2: Wind field established over the terrain, then frozen. No fire.
! 3: Wind field following the terrain, no fire.
! 4: Wind and fire fully-coupled.

&MISC ORIGIN_LAT={wgs84_origin.y():.7f} ORIGIN_LON={wgs84_origin.x():.7f} NORTH_BEARING=0.
      TERRAIN_IMAGE='{chid}_tex.png'
      LEVEL_SET_MODE=1 /

! Domain and its boundary conditions
&MESH IJK={mesh_ijk[0]:d},{mesh_ijk[1]:d},{mesh_ijk[2]:d}
      XB={mesh_xb[0]:.3f},{mesh_xb[1]:.3f},{mesh_xb[2]:.3f},{mesh_xb[3]:.3f},{mesh_xb[4]:.3f},{mesh_xb[5]:.3f} /
&VENT ID='Domain BC XMIN' MB='XMIN' SURF_ID='OPEN' /
&VENT ID='Domain BC XMAX' MB='XMAX' SURF_ID='OPEN' /
&VENT ID='Domain BC YMIN' MB='YMIN' SURF_ID='OPEN' /
&VENT ID='Domain BC YMAX' MB='YMAX' SURF_ID='OPEN' /
&VENT ID='Domain BC ZMAX' MB='ZMAX' SURF_ID='OPEN' /

! Fire origin
&SURF ID='Ignition' VEG_LSET_IGNITE_TIME=0. COLOR='RED' /
&VENT ID='Ignition point' SURF_ID='Ignition', GEOM=T
      XB={fxb[0]:.3f},{fxb[1]:.3f},{fxb[2]:.3f},{fxb[3]:.3f},{fxb[4]:.3f},{fxb[5]:.3f} /
 
! Output quantities
&SLCF AGL_SLICE=1. QUANTITY='LEVEL SET VALUE' /
&SLCF AGL_SLICE=1. QUANTITY='TEMPERATURE' VECTOR=T /
&SLCF PBX={fx:.3f} QUANTITY='TEMPERATURE' /
&SLCF PBX={fy:.3f} QUANTITY='TEMPERATURE' /

! Wind
&WIND SPEED=1., RAMP_SPEED='ws', RAMP_DIRECTION='wd' /
&RAMP ID='ws', T=   0, F=10. /
&RAMP ID='ws', T= 600, F=10. /
&RAMP ID='ws', T=1200, F=20. /
&RAMP ID='wd', T=   0, F=315. /
&RAMP ID='wd', T= 600, F=270. /
&RAMP ID='wd', T=1200, F=360. /
 
! Boundary conditions
! 13 Anderson Fire Behavior Fuel Models
&SURF ID='A01' RGB=255,254,212 VEG_LSET_FUEL_INDEX= 1 /
&SURF ID='A02' RGB=255,253,102 VEG_LSET_FUEL_INDEX= 2 /
&SURF ID='A03' RGB=236,212, 99 VEG_LSET_FUEL_INDEX= 3 /
&SURF ID='A04' RGB=254,193,119 VEG_LSET_FUEL_INDEX= 4 /
&SURF ID='A05' RGB=249,197, 92 VEG_LSET_FUEL_INDEX= 5 /
&SURF ID='A06' RGB=217,196,152 VEG_LSET_FUEL_INDEX= 6 /
&SURF ID='A07' RGB=170,155,127 VEG_LSET_FUEL_INDEX= 7 /
&SURF ID='A08' RGB=229,253,214 VEG_LSET_FUEL_INDEX= 8 /
&SURF ID='A09' RGB=162,191, 90 VEG_LSET_FUEL_INDEX= 9 /
&SURF ID='A10' RGB=114,154, 85 VEG_LSET_FUEL_INDEX=10 /
&SURF ID='A11' RGB=235,212,253 VEG_LSET_FUEL_INDEX=11 /
&SURF ID='A12' RGB=163,177,243 VEG_LSET_FUEL_INDEX=12 /
&SURF ID='A13' RGB=  0,  0,  0 VEG_LSET_FUEL_INDEX=13 /
&SURF ID='Urban' RGB=186,119, 80 /
&SURF ID='Snow-Ice' RGB=234,234,234 /
&SURF ID='Agriculture' RGB=253,242,242 /
&SURF ID='Water' RGB=137,183,221 /
&SURF ID='Barren' RGB=133,153,156 /
&SURF ID='NA' RGB=255,255,255 /

! Terrain
&GEOM ID='Terrain'
      SURF_ID='A01','A02','A03','A04','A05','A06','A07',
              'A08','A09','A10','A11','A12','A13','Urban',
              'Snow-Ice','Agriculture','Water','Barren','NA'
      BINARY_FILE='{chid}_terrain.bingeom'
      IS_TERRAIN=T EXTEND_TERRAIN=F /

&TAIL /
    """
    utils.write_file(feedback=feedback,
                     filepath=f"{path}/{chid}.fds",
                     content=content)

    # Write bingeom file
    filepath = os.path.join(path, chid + "_terrain.bingeom")
    landuse_select = landuse_choices[landuse_type]
    fds_surfs = tuple(
        landuse_select.get(landuses[i], landuses[0])
        for i, _ in enumerate(faces))
    n_surf_id = max(fds_surfs)
    fds_verts = tuple(v for vs in verts for v in vs)
    fds_faces = tuple(f for fs in faces for f in fs)
    utils.write_bingeom(
        geom_type=2,
        n_surf_id=n_surf_id,
        fds_verts=fds_verts,
        fds_faces=fds_faces,
        fds_surfs=fds_surfs,
        fds_volus=list(),
        filepath=filepath,
    )
コード例 #13
0
ファイル: fds.py プロジェクト: oriolrios/qgis2fds
def write_case(
    feedback,
    dem_layer,
    landuse_layer,
    path,
    chid,
    wgs84_origin,
    utm_origin,
    wgs84_fire_origin,
    utm_fire_origin,
    utm_crs,
    verts,
    faces,
    landuses,
    landuse_type,
    mesh_extent,
):
    """
    Get FDS case.
    """

    feedback.pushInfo("Writing the FDS case file...")

    # Calc header
    pv = pluginMetadata("qgis2fds", "version")
    qv = QgsExpressionContextUtils.globalScope().variable("qgis_version")
    now = time.strftime("%a, %d %b %Y, %H:%M:%S", time.localtime())
    filepath = QgsProject.instance().fileName() or "not saved"
    if len(filepath) > 60:
        filepath = "..." + filepath[-57:]

    # Calc MESH XB
    mesh_xb = (
        mesh_extent.xMinimum() - utm_origin.x(),
        mesh_extent.xMaximum() - utm_origin.x(),
        mesh_extent.yMinimum() - utm_origin.y(),
        mesh_extent.yMaximum() - utm_origin.y(),
        min(v[2] for v in verts) - 1.0,
        max(v[2] for v in verts) + 50.0,
    )
    # Calc center of VENT patch
    fire_x, fire_y = (
        utm_fire_origin.x() - utm_origin.x(),  # relative to origin
        utm_fire_origin.y() - utm_origin.y(),
    )

    # Prepare and write FDS file
    content = "\n".join((
        f"! Generated by qgis2fds <{pv}> on QGIS <{qv}>",
        f"! QGIS file: <{filepath}>",
        f"! Selected UTM CRS: <{utm_crs.description()}>",
        f"! Terrain extent: <{mesh_extent.toString(precision=1)}>",
        f"! DEM layer: <{dem_layer.name()}>",
        f"! Landuse layer: <{landuse_layer and landuse_layer.name() or 'None'}>",
        f"! Landuse type: <{landuse_layer and ('Landfire FBFM13', 'CIMA Propagator')[landuse_type] or 'None'}>",
        f"! Domain Origin: <{utm_origin.x():.1f}, {utm_origin.y():.1f}>",
        f"!   {utils.get_lonlat_url(wgs84_origin)}",
        f"! Fire Origin: <{utm_fire_origin.x():.1f}, {utm_fire_origin.y():.1f}>",
        f"!   {utils.get_lonlat_url(wgs84_fire_origin)}",
        f"! Date: <{now}>",
        f" ",
        f"&HEAD CHID='{chid}' TITLE='Description of {chid}' /",
        f"&TIME T_END=1. /",
        f" ",
        f"&MISC ORIGIN_LAT={wgs84_origin.y():.7f}, ORIGIN_LON={wgs84_origin.x():.7f}, NORTH_BEARING=0.",
        f"      TERRAIN_IMAGE='{chid}_tex.png', LEVEL_SET_MODE=1 /",
        f" ",
        f"! Domain and its boundary conditions",
        f"&MESH IJK=50,50,50, XB={mesh_xb[0]:.3f},{mesh_xb[1]:.3f},{mesh_xb[2]:.3f},{mesh_xb[3]:.3f},{mesh_xb[4]:.3f},{mesh_xb[5]:.3f} /",
        f"&VENT MB='XMIN', SURF_ID='OPEN' /",
        f"&VENT MB='XMAX', SURF_ID='OPEN' /",
        f"&VENT MB='YMIN', SURF_ID='OPEN' /",
        f"&VENT MB='YMAX', SURF_ID='OPEN' /",
        f"&VENT MB='ZMAX', SURF_ID='OPEN' /",
        f" ",
        f"! Fire origin",
        f"&SURF ID='Ignition', VEG_LSET_IGNITE_TIME=0., COLOR='RED' /",
        f"&VENT XB={fire_x-5:.3f},{fire_x+5:.3f},{fire_y-5:.3f},{fire_y+5:.3f},{mesh_xb[4]:.3f},{mesh_xb[4]:.3f}, SURF_ID='Ignition', GEOM=T /",
        f" ",
        f"! Output quantities",
        f"&SLCF AGL_SLICE=1., QUANTITY='LEVEL SET VALUE' /",
        f" ",
        f"! Wind",
        f"&WIND SPEED=1., RAMP_SPEED='ws', RAMP_DIRECTION='wd' /",
        f"&RAMP ID='ws', T=   0, F= 0. /",
        f"&RAMP ID='ws', T= 600, F=10. /",
        f"&RAMP ID='ws', T=1200, F=20. /",
        f"&RAMP ID='wd', T=   0, F=330. /",
        f"&RAMP ID='wd', T= 600, F=300. /",
        f"&RAMP ID='wd', T=1200, F=270. /",
        f" ",
        f"! Boundary conditions",
        f"! 13 Anderson Fire Behavior Fuel Models",
        f"&SURF ID='A01', VEG_LSET_FUEL_INDEX= 1 /",
        f"&SURF ID='A02', VEG_LSET_FUEL_INDEX= 2 /",
        f"&SURF ID='A03', VEG_LSET_FUEL_INDEX= 3 /",
        f"&SURF ID='A04', VEG_LSET_FUEL_INDEX= 4 /",
        f"&SURF ID='A05', VEG_LSET_FUEL_INDEX= 5 /",
        f"&SURF ID='A06', VEG_LSET_FUEL_INDEX= 6 /",
        f"&SURF ID='A07', VEG_LSET_FUEL_INDEX= 7 /",
        f"&SURF ID='A08', VEG_LSET_FUEL_INDEX= 8 /",
        f"&SURF ID='A09', VEG_LSET_FUEL_INDEX= 9 /",
        f"&SURF ID='A10', VEG_LSET_FUEL_INDEX=10 /",
        f"&SURF ID='A11', VEG_LSET_FUEL_INDEX=11 /",
        f"&SURF ID='A12', VEG_LSET_FUEL_INDEX=12 /",
        f"&SURF ID='A13', VEG_LSET_FUEL_INDEX=13 /",
        f"&SURF ID='Urban' RGB=186,119, 80 /",
        f"&SURF ID='Snow-Ice' RGB=234,234,234 /",
        f"&SURF ID='Agriculture' RGB=253,242,242 /",
        f"&SURF ID='Water' RGB=137,183,221 /",
        f"&SURF ID='Barren' RGB=133,153,156 /",
        f"&SURF ID='NA' RGB=255,255,255 /",
        f" ",
        f"! Terrain",
        f"&GEOM ID='Terrain'",
        f"      READ_BINARY=T IS_TERRAIN=T EXTEND_TERRAIN=F",
        f"      SURF_ID='A01','A02','A03','A04','A05','A06','A07',",
        f"              'A08','A09','A10','A11','A12','A13','Urban',",
        f"              'Snow-Ice','Agriculture','Water','Barren','NA' /",
        f" ",
        f"&TAIL /\n",
    ))

    utils.write_file(feedback=feedback,
                     filepath=f"{path}/{chid}.fds",
                     content=content)

    # Write bingeom file
    landuse_select = landuse_choices[landuse_type]
    fds_surfs = tuple(
        landuse_select.get(landuses[i], landuses[0])
        for i, _ in enumerate(faces))
    n_surf_id = max(fds_surfs)
    fds_verts = tuple(v for vs in verts for v in vs)
    fds_faces = tuple(f for fs in faces for f in fs)
    utils.write_bingeom(
        geom_type=2,
        n_surf_id=n_surf_id,
        fds_verts=fds_verts,
        fds_faces=fds_faces,
        fds_surfs=fds_surfs,
        fds_volus=list(),
        filepath=f"{path}/{chid}_Terrain.bingeom",
    )
コード例 #14
0
 def reportError():
     version = "Plugin version: " + pluginMetadata("opengeo", "version")
     message = unicode(msg, errors="ignore") + "\n" + version
     self.ravenClient.captureMessage(message)
     self.resetActivity()
コード例 #15
0
 def reportError():
     version = "Plugin version: " + pluginMetadata("opengeo", "version")
     message = unicode(msg, errors = "ignore") + "\n" + version
     self.ravenClient.captureMessage(message)
     self.resetActivity()
コード例 #16
0
ファイル: __init__.py プロジェクト: filmfer/PAT_QGIS_Plugin
def classFactory(iface):
    """Load pat_toolbar class from file pat_toolbar.

    :param iface: A QGIS interface instance.
    :type iface: QgsInterface
    """

    if platform.system() != 'Windows':
        message = 'PAT is only available for Windows'

        iface.messageBar().pushMessage("ERROR",
                                       message,
                                       level=Qgis.Critical,
                                       duration=0)

        QMessageBox.critical(None, 'Error', message)
        sys.exit(message)

    if not os.path.exists(TEMPDIR):
        os.mkdir(TEMPDIR)

    from .util.settings import read_setting, write_setting
    if read_setting(PLUGIN_NAME + "/DISP_TEMP_LAYERS") is None:
        write_setting(PLUGIN_NAME + "/DISP_TEMP_LAYERS", False)

    if read_setting(PLUGIN_NAME + "/DEBUG") is None:
        write_setting(PLUGIN_NAME + "/DEBUG", False)

    try:
        from pyprecag import config
        config.set_debug_mode(read_setting(PLUGIN_NAME + "/DEBUG", bool))
    except ImportError:
        # pyprecag is not yet installed
        pass

    # the custom logging import requires qgis_config so leave it here
    from .util.custom_logging import setup_logger

    # Call the logger pyprecag so it picks up the module debugging as well.
    setup_logger(LOGGER_NAME)
    LOGGER = logging.getLogger(LOGGER_NAME)
    LOGGER.addHandler(logging.NullHandler())  # logging.StreamHandler()

    from .util.check_dependencies import (check_pat_symbols,
                                          check_R_dependency,
                                          check_gdal_dependency,
                                          check_python_dependencies)

    meta_version = pluginMetadata('pat', 'version')
    plugin_state = '\nPAT Plugin:\n'
    plugin_state += '    {:25}\t{}\n'.format('QGIS Version:',
                                             Qgis.QGIS_VERSION)
    plugin_state += '    {:25}\t{}\n'.format('Python Version:', sys.version)
    plugin_state += '    {:25}\t{} {}'.format(
        'PAT:', pluginMetadata('pat', 'version'),
        pluginMetadata('pat', 'update_date'))
    LOGGER.info(plugin_state)

    # if not check_gdal:
    #     LOGGER.critical('QGIS Version {} and GDAL {} is are not currently supported.'.format(Qgis.QGIS_VERSION, gdal_ver))
    #
    #     message = ('QGIS Version {} and GDAL {}  are not currently supported. '
    #                'Downgrade QGIS to an earlier version. If required email [email protected] '
    #                'for assistance.'.format(Qgis.QGIS_VERSION, gdal_ver))
    #
    #     iface.messageBar().pushMessage("ERROR Failed Dependency Check", message,
    #                                    level= Qgis.Critical, duration=0)
    #     QMessageBox.critical(None, 'Failed Dependency Check', message)
    #     sys.exit(message)

    gdal_ver = check_gdal_dependency()
    check_pat_symbols()
    # check_R_dependency()
    result = check_python_dependencies(PLUGIN_DIR, iface)
    if len(result) > 0:
        iface.messageBar().pushMessage("ERROR Failed Dependency Check",
                                       result,
                                       level=Qgis.Critical,
                                       duration=0)
    from .pat_toolbar import pat_toolbar

    return pat_toolbar(iface)