Skip to content

Commit

Permalink
Merge pull request #1 from lpoaura/develop
Browse files Browse the repository at this point in the history
v0.0.1
  • Loading branch information
lpofredc authored May 18, 2020
2 parents 1c29de8 + 69d7fb0 commit 07e9310
Show file tree
Hide file tree
Showing 19 changed files with 712 additions and 179 deletions.
118 changes: 118 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@

# Created by https://www.gitignore.io/api/code,python
# Edit at https://www.gitignore.io/?templates=code,python

### Code ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# Mr Developer
.mr.developer.cfg
.project
.pydevproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# End of https://www.gitignore.io/api/code,python

8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# v0.0.1

Pemière pre-release avec un premier lot de fonctions:
* Extraction de données à partir d'une couche de zonages
* Création d'un tableau de synthèse par taxons à partir d'une couche de zonages
* Création d'un graphique de synthèse d'état des connaissances par groupes taxonomiques à partir d'une couche de zonages


16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Scripts de processing framework de la LPO AuRA

Ce plugin ajoute à QGIS des scripts d'exploitation des données naturalistes de
la [LPO Auvergne-Rhône-Alpes](https://auvergne-rhone-alpes.lpo.fr/) à QGIS.

## Licence

## Equipe

* @eguilley (LPO Auvergne-Rhône-Alpes)
* @lpofredc (@lpofredc - LPO Auvergne-Rhône-Alpes)
* @jgirardclaudon (@lpojgc LPO Auvergne-Rhône-Alpes)

![logoLPO AuRA](https://raw.githubusercontent.com/lpoaura/biodivsport-widget/master/images/LPO_AuRA_l250px.png)


26 changes: 0 additions & 26 deletions README.txt

This file was deleted.

1 change: 1 addition & 0 deletions VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v0.0.1
Binary file removed __pycache__/__init__.cpython-36.pyc
Binary file not shown.
Binary file removed __pycache__/extract_data.cpython-36.pyc
Binary file not shown.
Binary file removed __pycache__/scripts_lpo.cpython-36.pyc
Binary file not shown.
Binary file removed __pycache__/scripts_lpo_algorithm.cpython-36.pyc
Binary file not shown.
Binary file removed __pycache__/scripts_lpo_provider.cpython-36.pyc
Binary file not shown.
Binary file removed __pycache__/summary_table.cpython-36.pyc
Binary file not shown.
145 changes: 145 additions & 0 deletions common_functions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# -*- coding: utf-8 -*-

"""
/***************************************************************************
ScriptsLPO : common_functions.py
-------------------
Date : 2020-04-16
Copyright : (C) 2020 by Elsa Guilley (LPO AuRA)
Email : lpo-aura@lpo.fr
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""

__author__ = 'Elsa Guilley (LPO AuRA)'
__date__ = '2020-04-16'
__copyright__ = '(C) 2020 by Elsa Guilley (LPO AuRA)'

# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

from qgis.utils import iface
from qgis.gui import QgsMessageBar

from qgis.PyQt.QtCore import QVariant
from qgis.core import (QgsWkbTypes,
QgsField,
QgsProcessingException,
Qgis)
import processing


def simplify_name(string):
"""
Simplify a layer name written by the user.
"""
translation_table = str.maketrans(
'àâäéèêëîïôöùûüŷÿç~- ',
'aaaeeeeiioouuuyyc___',
"2&'([{|}])`^\/@+-=*°$£%§#.?!;:<>"
)
return string.lower().translate(translation_table)

# def check_layer_geometry(layer):
# """
# Check if the input vector layer is a polygon layer.
# """
# if QgsWkbTypes.displayString(layer.wkbType()) not in ['Polygon', 'MultiPolygon']:
# iface.messageBar().pushMessage("Erreur", "La zone d'étude fournie n'est pas valide ! Veuillez sélectionner une couche vecteur de type POLYGONE.", level=Qgis.Critical, duration=10)
# raise QgsProcessingException("La zone d'étude fournie n'est pas valide ! Veuillez sélectionner une couche vecteur de type POLYGONE.")
# return None

def check_layer_is_valid(feedback, layer):
"""
Check if the input vector layer is valid.
"""
if not layer.isValid():
raise QgsProcessingException(""""La couche PostGIS chargée n'est pas valide !
Checkez les logs de PostGIS pour visualiser les messages d'erreur.""")
else:
#iface.messageBar().pushMessage("Info", "La couche PostGIS demandée est valide, la requête SQL a été exécutée avec succès !", level=Qgis.Info, duration=10)
feedback.pushInfo("La couche PostGIS demandée est valide, la requête SQL a été exécutée avec succès !")
return None

def construct_sql_array_polygons(layer):
"""
Construct the sql array containing the input vector layer's features geometry.
"""
# Initialization of the sql array containing the study area's features geometry
array_polygons = "array["
# Retrieve the CRS of the layer
crs = layer.sourceCrs().authid().split(':')[1]
# For each entity in the study area...
for feature in layer.getFeatures():
# Retrieve the geometry
area = feature.geometry() # QgsGeometry object
# Retrieve the geometry type (single or multiple)
geomSingleType = QgsWkbTypes.isSingleType(area.wkbType())
# Increment the sql array
if geomSingleType:
array_polygons += "ST_transform(ST_PolygonFromText('{}', {}), 2154), ".format(area.asWkt(), crs)
else:
array_polygons += "ST_transform(ST_MPolyFromText('{}', {}), 2154), ".format(area.asWkt(), crs)
# Remove the last "," in the sql array which is useless, and end the array
array_polygons = array_polygons[:len(array_polygons)-2] + "]"
return array_polygons

def load_layer(context, layer):
"""
Load a layer in the current project.
"""
root = context.project().layerTreeRoot()
plugin_lpo_group = root.findGroup('Résultats plugin LPO')
if not plugin_lpo_group:
plugin_lpo_group = root.insertGroup(0, 'Résultats plugin LPO')
context.project().addMapLayer(layer, False)
plugin_lpo_group.addLayer(layer)
### Variant
# context.temporaryLayerStore().addMapLayer(layer)
# context.addLayerToLoadOnCompletion(
# layer.id(),
# QgsProcessingContext.LayerDetails("Données d'observations", context.project(), self.OUTPUT)
# )

def execute_sql_queries(context, feedback, connection, queries):
"""
Execute several sql queries.
"""
for query in queries:
processing.run(
'qgis:postgisexecutesql',
{
'DATABASE': connection,
'SQL': query
},
is_child_algorithm=True,
context=context,
feedback=feedback
)
feedback.pushInfo('Requête SQL exécutée avec succès !')
return None

def format_layer_export(layer):
"""
Create new valid fields for the sink.
"""
old_fields = layer.fields()
new_fields = layer.fields()
new_fields.clear()
invalid_formats = ["_text", "jsonb"]
for field in old_fields:
if field.typeName() in invalid_formats:
new_fields.append(QgsField(field.name(), QVariant.String, "str"))
else:
new_fields.append(field)
# for i,field in enumerate(new_fields):
# feedback.pushInfo('Elt : {}- {} {}'.format(i, field.name(), field.typeName()))
return new_fields
Loading

0 comments on commit 07e9310

Please sign in to comment.