"""
/***************************************************************************
Name : IBAMA expressions
Description : Set of expressions for QGIS ( 2.8 or above )
Date : April, 2015.
copyright : (C) 2015 by Luiz Motta
email : motta.luiz@gmail.com
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
from qgis import core as QgsCore
import qgis.utils as QgsUtils
from PyQt4 import QtCore
# //////// Inline Functions \\\\\\\\
def dms_format(dd, orients):
def decdeg2dms(dd):
minutes, seconds = divmod( abs( dd ) * 3600, 60 )
degrees, minutes = divmod( minutes, 60 )
return { 'orient': dd >= 0.0, 'degrees': degrees, 'minutes': minutes, 'seconds': seconds }
def formatDMS(dms):
( d, m, s, o ) = ( "%02.0f" % dms['degrees'], "%02.0f" % dms['minutes'], " %05.2f" % dms['seconds'], orients[ dms['orient'] ] )
return "%s%s %s%s %s%s %s" % ( d, chr(176), m, chr(39), s, chr(34), o )
#
return formatDMS( decdeg2dms( dd ) )
def getGeomTrasformed(feature, idEpsg, isGeographicCRS):
if not type(idEpsg) is int:
raise Exception("Enter with ID EPSG with integer type")
return -1
crDest = QgsCore.QgsCoordinateReferenceSystem( idEpsg, QgsCore.QgsCoordinateReferenceSystem. EpsgCrsId)
if not crDest.geographicFlag() == isGeographicCRS:
v_is = 'not' if isGeographicCRS else ''
msg = "ID EPSG is %s Geographic" % v_is
raise Exception(msg)
return -1
ct = QgsCore.QgsCoordinateTransform( QgsUtils.iface.activeLayer().crs(), crDest )
geom = QgsCore.QgsGeometry( feature.geometry() )
geom.transform( ct )
return geom
# \\\\\\\\ Inline Functions ////////
@qgsfunction(args=1, group='Ibama')
def getNameFile(values, feature, parent):
"""
Return
Only name of file whithout extension
Syntax
getNameFile(path_file)
Argument
path_file -> name file with path
Example
getNameFile('/home/user/readme.txt')-> readme
* Change the '/' for your system (this example is for Linux)
"""
try:
info = QtCore.QFileInfo( values[0] )
name = info.baseName()
except:
raise Exception("Enter with name of file.")
return ''
#
return name
@qgsfunction(args=1, group="Ibama", usesgeometry=True)
def dms_x(values, feature, parent):
"""
Return
Coordinate X of geometry D M S Q(W or E)
Point: Coordinate own
Line: Coordinate of center
Polygon: Coordinate of centroid
Syntax
dms_x(ID EPSG)
"""
idEpsg = values[0]
geom = getGeomTrasformed(feature, idEpsg, True)
if geom == -1:
return ''
if geom is None:
return 'No Geometry'
point = geom.centroid().asPoint()
orients = {True: 'E', False: 'W'}
return dms_format( point.x(), orients )
@qgsfunction(args=1, group="Ibama", usesgeometry=True)
def dms_y(values, feature, parent):
"""
Return
Coordinate Y of geometry D M S Q(N or S)
Point: Coordinate own
Line: Coordinate of center
Polygon: Coordinate of centroid
Syntax
dms_y(ID EPSG)
"""
idEpsg = values[0]
geom = getGeomTrasformed( feature, idEpsg, True )
if geom == -1:
return ''
if geom is None:
return 'No Geometry'
point = geom.centroid().asPoint()
orients = {True: 'N', False: 'S'}
return dms_format( point.y(), orients )
@qgsfunction(1, "Ibama")
def existFile(values, feature, parent):
"""
Return
True if exist and False otherwise
Syntax
existFile(v_file)
Argument
v_file-> file with path
Example
existFile( '/home/not_exist.txt')-> False
* Change the '/' for your system (this example is for Linux)
"""
try:
info = QtCore.QFileInfo( values[0] )
exist = info.isFile()
except:
raise Exception("Enter with file with path")
return None
#
return exist
@qgsfunction(1, "Ibama")
def getDateLandsat(values, feature, parent):
"""
Return
QDate from file name of Landsat
Syntax
getDateLandsat(name_landsat)
Argument
name_landsat -> name file of Landsat
Example
getDateLandsat('LC81390452014295LGN00')-> QDate(2014, 10, 22)
"""
try:
julianYear = QtCore.QDate( int( values[0][9:13] ), 1, 1 ).toJulianDay() - 1
julianDays = julianYear + int( values[0][13:16] )
v_date = QtCore.QDate.fromJulianDay ( julianDays )
except:
raise Exception("Enter with landsat 8 name (ex. 'LC81390452014295LGN00').")
return QtCore.QDate()
#
return v_date
@qgsfunction(args=1, group='Ibama')
def getDateRapideye(values, feature, parent):
"""
Return
QDate from file name of Rapideye
Syntax
getDateRapideye(name_rapideye)
Argument
name_rapideye -> name file of Rapideye
Example
getDateRapideye('2227625_2012-12-26T142009_RE1_3A-NAC_14473192_171826')-> QDate(2012, 12, 26)
"""
try:
v_date = QtCore.QDate.fromString( values[0].split('_')[1][:10], "yyyy-MM-dd" )
except:
raise Exception("Enter with Rapideye name (ex. '2227625_2012-12-26T142009_RE1_3A-NAC_14473192_171826'). Value error = %s" % values[0])
return QtCore.QDate()
#
return v_date
@qgsfunction(args=1, group="Ibama")
def getDateSentinel(values, feature, parent):
"""
Return
QDate from file name of Sentinel
Syntax
getDateRapideye(name_sentinel)
Argument
name_sentinel -> name file of Sentinel
Example
getDateSentinel('s1a-ew-grd-hh-20141031t223708-20141031t223811-003079-003869-001')-> QDate(2014, 10, 31)
"""
try:
v_date = QtCore.QDate.fromString( values[0].split('-')[5][:8], "yyyyMMdd" )
except:
raise Exception("Enter with Sentinel name (ex. 's1a-ew-grd-hh-20141031t223708-20141031t223811-003079-003869-001'). Value error = %s" % values[0])
return QtCore.QDate()
#
return v_date
@qgsfunction(args=0, group="Ibama", usesgeometry=True)
def num_geoms(values, feature, parent):
"""
Return
Number of geoms
Syntax
num_geoms()
"""
geom = feature.geometry()
if geom is None or not geom.isGeosValid():
return -1
if not geom.isMultipart():
return 1
wkbType = geom.wkbType()
if wkbType == QGis.WKBMultiPoint:
return len( geom.asMultiPoint() )
if wkbType == QGis.WKBMultiLineString:
return len( geom.asMultiPolyline() )
if wkbType == QGis.WKBMultiPolygon:
return len( geom.asMultiPolygon() )
return -1
@qgsfunction(args=1, group="Ibama", usesgeometry=True)
def json_leaflet_catalog(values, feature, parent):
"""
Return
Leafleft Javascript code
Syntax
json_leaflet_catalog('satellite')
Argument
satellite -> name of satellite
Example
json_leaflet_catalog('landsat')-> { 'name': ..., 'url':.., 'southWest':..., 'northEast':...}
"""
satellite = values[0]
crsLayer = QgsUtils.iface.activeLayer().crs()
geom = feature.geometry()
cr4326 = QgsCore.QgsCoordinateReferenceSystem( 4326, QgsCore.QgsCoordinateReferenceSystem.EpsgCrsId )
ct = QgsCore.QgsCoordinateTransform( crsLayer, cr4326 )
bb = ct.transform( geom.boundingBox() )
image = feature.attribute( 'image' )
url = "../../tms/%s/%s.tms/{z}/{x}/{y}.png" % ( satellite, image.replace( ".tif", "" ) )
southWest = "L.latLng( %f, %f )" % ( bb.yMinimum(), bb.xMinimum() )
northEast = "L.latLng( %f, %f )" % ( bb.yMaximum(), bb.xMaximum() )
return "{ 'name': '%s', 'url': '%s', 'southWest': %s, 'northEast': %s }" % ( image, url, southWest, northEast)
@qgsfunction(args=1, group="Ibama", usesgeometry=True)
def area_epsg(values, feature, parent):
"""
Return
Area using the ID EPSG
Syntax
area_epsg(idEPSG)
Argument
ID EPS
Example
area_epsg(5641)-> area
"""
idEpsg = values[0]
geom = getGeomTrasformed( feature, idEpsg, False )
if geom == -1:
return -1
return geom.area()
@qgsfunction(args=1, group="Ibama")
def is_selected(values, feature, parent):
# Source: http://gis.stackexchange.com/questions/157718/label-only-selected-feature-using-qgis/157769#157769
layer = QgsUtils.iface.activeLayer()
return feature.id() in layer.selectedFeaturesIds()