[GRASS-SVN] r59127 - in grass/trunk/lib/python/pygrass: . gis messages modules modules/grid modules/interface raster shell tests vector
svn_grass at osgeo.org
svn_grass at osgeo.org
Sun Feb 23 12:45:30 PST 2014
Author: zarch
Date: 2014-02-23 12:45:30 -0800 (Sun, 23 Feb 2014)
New Revision: 59127
Modified:
grass/trunk/lib/python/pygrass/__init__.py
grass/trunk/lib/python/pygrass/errors.py
grass/trunk/lib/python/pygrass/functions.py
grass/trunk/lib/python/pygrass/gis/__init__.py
grass/trunk/lib/python/pygrass/gis/region.py
grass/trunk/lib/python/pygrass/messages/__init__.py
grass/trunk/lib/python/pygrass/modules/__init__.py
grass/trunk/lib/python/pygrass/modules/grid/__init__.py
grass/trunk/lib/python/pygrass/modules/grid/grid.py
grass/trunk/lib/python/pygrass/modules/grid/patch.py
grass/trunk/lib/python/pygrass/modules/grid/split.py
grass/trunk/lib/python/pygrass/modules/interface/__init__.py
grass/trunk/lib/python/pygrass/modules/interface/flag.py
grass/trunk/lib/python/pygrass/modules/interface/module.py
grass/trunk/lib/python/pygrass/modules/interface/parameter.py
grass/trunk/lib/python/pygrass/modules/interface/read.py
grass/trunk/lib/python/pygrass/modules/interface/typedict.py
grass/trunk/lib/python/pygrass/modules/shortcuts.py
grass/trunk/lib/python/pygrass/raster/__init__.py
grass/trunk/lib/python/pygrass/raster/abstract.py
grass/trunk/lib/python/pygrass/raster/buffer.py
grass/trunk/lib/python/pygrass/raster/category.py
grass/trunk/lib/python/pygrass/raster/history.py
grass/trunk/lib/python/pygrass/raster/rowio.py
grass/trunk/lib/python/pygrass/raster/segment.py
grass/trunk/lib/python/pygrass/shell/__init__.py
grass/trunk/lib/python/pygrass/tests/benchmark.py
grass/trunk/lib/python/pygrass/tests/set_mapset.py
grass/trunk/lib/python/pygrass/vector/__init__.py
grass/trunk/lib/python/pygrass/vector/abstract.py
grass/trunk/lib/python/pygrass/vector/basic.py
grass/trunk/lib/python/pygrass/vector/find.py
grass/trunk/lib/python/pygrass/vector/geometry.py
grass/trunk/lib/python/pygrass/vector/table.py
grass/trunk/lib/python/pygrass/vector/vector_type.py
Log:
Add support for python2 code and python3
Modified: grass/trunk/lib/python/pygrass/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/__init__.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/__init__.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -9,11 +9,11 @@
import os as _os
import sys as _sys
-import errors
-import gis
-import functions
-import raster
-import vector
-import modules
-import shell
-import messages
+from . import errors
+from . import gis
+from . import functions
+from . import raster
+from . import vector
+from . import modules
+from . import shell
+from . import messages
Modified: grass/trunk/lib/python/pygrass/errors.py
===================================================================
--- grass/trunk/lib/python/pygrass/errors.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/errors.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,10 +4,10 @@
@author: pietro
"""
+from functools import wraps
+from grass.pygrass.messages import get_msgr
-from grass.script import warning
-
class AbstractError(Exception):
def __init__(self, value):
self.value = value
@@ -37,10 +37,11 @@
def must_be_open(method):
+
+ @wraps(method)
def wrapper(self, *args, **kargs):
if self.is_open():
return method(self, *args, **kargs)
else:
- warning(_("The map is close!"))
- wrapper.__doc__ = method.__doc__
+ get_msgr().warning(_("The map is close!"))
return wrapper
Modified: grass/trunk/lib/python/pygrass/functions.py
===================================================================
--- grass/trunk/lib/python/pygrass/functions.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/functions.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -160,13 +160,13 @@
"""
if name[0].isdigit():
return False
- for char in ' @#^?°,;%&/':
+ for char in u' @#^?°,;%&/':
if name.find(char) != -1:
return False
return True
-def coor2pixel((east, north), region):
+def coor2pixel(coord, region):
"""Convert coordinates into a pixel row and col ::
>>> reg = Region()
@@ -175,11 +175,12 @@
>>> coor2pixel((reg.east, reg.south), reg) == (reg.rows, reg.cols)
True
"""
+ (east, north) = coord
return (libraster.Rast_northing_to_row(north, region.c_region),
libraster.Rast_easting_to_col(east, region.c_region))
-def pixel2coor((col, row), region):
+def pixel2coor(pixel, region):
"""Convert row and col of a pixel into a coordinates ::
>>> reg = Region()
@@ -188,6 +189,7 @@
>>> pixel2coor((reg.cols, reg.rows), reg) == (reg.south, reg.east)
True
"""
+ (col, row) = pixel
return (libraster.Rast_row_to_northing(row, region.c_region),
libraster.Rast_col_to_easting(col, region.c_region))
Modified: grass/trunk/lib/python/pygrass/gis/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/gis/__init__.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/gis/__init__.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -1,6 +1,8 @@
# -*- coding: utf-8 -*-
#!/usr/bin/env python2.7
-from __future__ import print_function
+
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
from os import listdir
from os.path import join, exists, isdir
import shutil
@@ -23,7 +25,7 @@
import grass.lib.gis as libgis
from grass.pygrass.functions import getenv
from grass.pygrass.errors import GrassError
-import region
+from . import region
#write dec to check if user have permissions or not
Modified: grass/trunk/lib/python/pygrass/gis/region.py
===================================================================
--- grass/trunk/lib/python/pygrass/gis/region.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/gis/region.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,6 +4,8 @@
@author: Pietro Zambelli
"""
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
import ctypes
import grass.lib.gis as libgis
import grass.script as grass
Modified: grass/trunk/lib/python/pygrass/messages/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/messages/__init__.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/messages/__init__.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -317,7 +317,7 @@
time.sleep(1)
-def get_msgr(_instance=[None, ], raise_on_error=False):
+def get_msgr(_instance=[None, ], *args, **kwargs):
"""!Return a Messenger instance.
@return the Messenger instance.
@@ -332,7 +332,7 @@
False
"""
if not _instance[0]:
- _instance[0] = Messenger(raise_on_error)
+ _instance[0] = Messenger(*args, **kwargs)
return _instance[0]
Modified: grass/trunk/lib/python/pygrass/modules/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/__init__.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/__init__.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -5,10 +5,10 @@
@author: pietro
"""
-import interface
-from interface import Module, ParallelModuleQueue
+from . import interface
+from .interface import Module, ParallelModuleQueue
-import grid
-from grid.grid import GridModule
+from . import grid
+from .grid.grid import GridModule
-import shortcuts
+from . import shortcuts
Modified: grass/trunk/lib/python/pygrass/modules/grid/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/grid/__init__.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/grid/__init__.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,7 +4,8 @@
@author: pietro
"""
-import split
-import patch
-import grid
-from grid import GridModule
\ No newline at end of file
+from . import split
+from . import patch
+from . import grid
+from .grid import GridModule
+
Modified: grass/trunk/lib/python/pygrass/modules/grid/grid.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/grid/grid.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/grid/grid.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,6 +4,8 @@
@author: pietro
"""
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
import os
import multiprocessing as mltp
import subprocess as sub
@@ -434,7 +436,7 @@
else:
# set the computational region
lcmd = ['g.region', ]
- lcmd.extend(["%s=%s" % (k, v) for k, v in bbox.iteritems()])
+ lcmd.extend(["%s=%s" % (k, v) for k, v in bbox.items()])
sub.Popen(lcmd, env=env).wait()
if groups:
copy_groups(groups, gisrc_src, gisrc_dst)
Modified: grass/trunk/lib/python/pygrass/modules/grid/patch.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/grid/patch.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/grid/patch.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,6 +4,8 @@
@author: pietro
"""
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
from grass.pygrass.gis.region import Region
from grass.pygrass.raster import RasterRow
from grass.pygrass.functions import coor2pixel
@@ -29,7 +31,7 @@
buff = rasts[0][0]
rbuff = rasts[0][0]
r_start, r_end, c_start, c_end = sei[0]
- for row in xrange(r_start, r_end):
+ for row in range(r_start, r_end):
for col, ras in enumerate(rasts):
r_start, r_end, c_start, c_end = sei[col]
buff = ras.get_row(row, buff)
Modified: grass/trunk/lib/python/pygrass/modules/grid/split.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/grid/split.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/grid/split.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,6 +4,8 @@
@author: pietro
"""
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
from grass.pygrass.gis.region import Region
from grass.pygrass.vector.basic import Bbox
@@ -46,9 +48,9 @@
nrows = (reg.rows + height - 1) // height
box_list = []
#print reg
- for row in xrange(nrows):
+ for row in range(nrows):
row_list = []
- for col in xrange(ncols):
+ for col in range(ncols):
#print 'c', c, 'r', r
row_list.append(get_bbox(reg, row, col, width, height, overlap))
box_list.append(row_list)
@@ -81,9 +83,9 @@
nrows = (reg.rows + height - 1) // height
box_list = []
#print reg
- for row in xrange(nrows):
+ for row in range(nrows):
row_list = []
- for col in xrange(ncols):
+ for col in range(ncols):
#print 'c', c, 'r', r
row_list.append(get_bbox(reg, row, col, width, height, -overlap))
box_list.append(row_list)
Modified: grass/trunk/lib/python/pygrass/modules/interface/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/interface/__init__.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/interface/__init__.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,10 +4,10 @@
@author: pietro
"""
-import flag
-import parameter
-import module
-import typedict
-import read
+from . import flag
+from . import parameter
+from . import module
+from . import typedict
+from . import read
-from module import Module, ParallelModuleQueue
+from .module import Module, ParallelModuleQueue
Modified: grass/trunk/lib/python/pygrass/modules/interface/flag.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/interface/flag.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/interface/flag.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,7 +4,9 @@
@author: pietro
"""
-import read
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
+from . import read
class Flag(object):
Modified: grass/trunk/lib/python/pygrass/modules/interface/module.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/interface/module.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/interface/module.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -47,18 +47,23 @@
@endcode
"""
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
+import sys
-from __future__ import print_function
-from itertools import izip_longest
+if sys.version_info.major == 2:
+ from itertools import izip_longest as zip_longest
+else:
+ from itertools import zip_longest
from xml.etree.ElementTree import fromstring
import time
from grass.script.core import Popen, PIPE
from grass.pygrass.errors import GrassError, ParameterError
-from parameter import Parameter
-from flag import Flag
-from typedict import TypeDict
-from read import GETFROMTAG, DOC
+from .parameter import Parameter
+from .flag import Flag
+from .typedict import TypeDict
+from .read import GETFROMTAG, DOC
class ParallelModuleQueue(object):
@@ -362,7 +367,7 @@
(k in self.outputs and self.outputs[k].value is None)):
msg = "Required parameter <%s> not set."
raise ParameterError(msg % key)
- self.run()
+ return self.run()
def get_bash(self):
@@ -373,15 +378,18 @@
name = '_'.join(self.name.split('.')[1:])
params = ', '.join([par.get_python() for par in self.params_list
if par.get_python() != ''])
+ flags = ''.join([flg.get_python()
+ for flg in self.flags.values()
+ if not flg.special and flg.get_python() != ''])
special = ', '.join([flg.get_python()
for flg in self.flags.values()
if flg.special and flg.get_python() != ''])
# pre name par flg special
- if self.flags and special:
+ if flags and special:
return "%s.%s(%s, flags=%r, %s)" % (prefix, name, params,
- self.flags, special)
- elif self.flags:
- return "%s.%s(%s, flags=%r)" % (prefix, name, params, self.flags)
+ flags, special)
+ elif flags:
+ return "%s.%s(%s, flags=%r)" % (prefix, name, params, flags)
elif special:
return "%s.%s(%s, %s)" % (prefix, name, params, special)
else:
@@ -406,7 +414,7 @@
# transform each parameter in string
[str(param) for param in line if param is not None])
# make a list of parameters with only 3 param per line
- for line in izip_longest(*[iter(self.params_list)] * 3)]),)
+ for line in zip_longest(*[iter(self.params_list)] * 3)]),)
params = '\n'.join([par.__doc__ for par in self.params_list])
flags = self.flags.__doc__
return '\n'.join([head, params, DOC['flag_head'], flags, DOC['foot']])
@@ -472,6 +480,7 @@
self.outputs['stdout'].value = stdout if stdout else ''
self.outputs['stderr'].value = stderr if stderr else ''
self.time = time.time() - start
+ return self
###############################################################################
Modified: grass/trunk/lib/python/pygrass/modules/interface/parameter.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/interface/parameter.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/interface/parameter.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,12 +4,12 @@
@author: pietro
"""
-
-from __future__ import print_function
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
import re
-from read import GETTYPE, element2dict, DOC
+from .read import GETTYPE, element2dict, DOC
class Parameter(object):
@@ -116,7 +116,8 @@
raise ValueError(values_error % (self.name, self.values))
else:
self._value = value
- elif self.type is str and isinstance(value, unicode):
+ # was: elif self.type is str and isinstance(value, unicode):
+ elif self.type is str and isinstance(value, str):
if hasattr(self, 'values'):
if value in self.values:
self._value = value
Modified: grass/trunk/lib/python/pygrass/modules/interface/read.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/interface/read.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/interface/read.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,7 +4,8 @@
@author: pietro
"""
-from __future__ import print_function
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
def read_keydesc(par):
Modified: grass/trunk/lib/python/pygrass/modules/interface/typedict.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/interface/typedict.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/interface/typedict.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,6 +4,8 @@
@author: pietro
"""
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
from copy import deepcopy
try:
from collections import OrderedDict
@@ -48,7 +50,7 @@
def __deepcopy__(self, memo):
obj = TypeDict(self._type)
- for k, v in self.iteritems():
+ for k, v in self.items():
obj[k] = deepcopy(v)
return obj
Modified: grass/trunk/lib/python/pygrass/modules/shortcuts.py
===================================================================
--- grass/trunk/lib/python/pygrass/modules/shortcuts.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/modules/shortcuts.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,12 +4,13 @@
@author: pietro
"""
-from __future__ import print_function
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
import fnmatch
from grass.script.core import get_commands
-from interface import Module
+from .interface import Module
_CMDS = list(get_commands()[0])
_CMDS.sort()
Modified: grass/trunk/lib/python/pygrass/raster/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/__init__.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/raster/__init__.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,6 +4,9 @@
@author: pietro
"""
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
+import os
import ctypes
import numpy as np
@@ -27,11 +30,11 @@
#
# import raster classes
#
-from abstract import RasterAbstractBase, Info
-from raster_type import TYPE as RTYPE, RTYPE_STR
-from buffer import Buffer
-from segment import Segment
-from rowio import RowIO
+from .abstract import RasterAbstractBase, Info
+from .raster_type import TYPE as RTYPE, RTYPE_STR
+from .buffer import Buffer
+from .segment import Segment
+from .rowio import RowIO
class RasterRow(RasterAbstractBase):
@@ -169,14 +172,20 @@
# check if exist and instantiate all the private attributes
if self.exist():
- self.info = Info(self.name, self.mapset)
+ self.info.read()
+ self.cats.mtype = self.mtype
+ self.cats.read()
+ self.hist.read()
if self.mode == 'r':
# the map exist, read mode
self._fd = libraster.Rast_open_old(self.name, self.mapset)
self._gtype = libraster.Rast_get_map_type(self._fd)
self.mtype = RTYPE_STR[self._gtype]
- self.cats.read(self)
- self.hist.read(self.name)
+# try:
+# self.cats.read(self)
+# self.hist.read(self.name)
+# except:
+# import ipdb; ipdb.set_trace()
elif self.overwrite:
if self._gtype is None:
raise OpenError(_("Raster type not defined"))
@@ -269,7 +278,7 @@
if isinstance(key, slice):
#Get the start, stop, and step from the slice
return [self.put_row(ii, row)
- for ii in xrange(*key.indices(len(self)))]
+ for ii in range(*key.indices(len(self)))]
elif isinstance(key, tuple):
x, y = key
return self.put(x, y, row)
@@ -287,7 +296,7 @@
"""Transform an existing map to segment file.
"""
row_buffer = Buffer((self._cols), self.mtype)
- for row in xrange(self._rows):
+ for row in range(self._rows):
libraster.Rast_get_row(
self._fd, row_buffer.p, row, self._gtype)
self.segment.put_row(row, row_buffer)
@@ -297,7 +306,7 @@
"""Transform the segment file to a map.
"""
row_buffer = Buffer((self._cols), self.mtype)
- for row in xrange(self._rows):
+ for row in range(self._rows):
row_buffer = self.segment.get_row(row, row_buffer)
libraster.Rast_put_row(self._fd, row_buffer.p, self._gtype)
@@ -387,7 +396,10 @@
self.overwrite = overwrite if overwrite is not None else self.overwrite
if self.exist():
- self.info = Info(self.name, self.mapset)
+ self.info.read()
+ self.cats.mtype = self.mtype
+ self.cats.read()
+ self.hist.read()
if ((self.mode == "w" or self.mode == "rw") and
self.overwrite is False):
str_err = _("Raster map <{0}> already exists. Use overwrite.")
@@ -579,52 +591,26 @@
@return 0 on success
@return non-zero code on failure
"""
- self.null = None
+ with RasterRow(self.name, self.mapset, mode='r') as rst:
+ buff = rst[0]
+ for i in range(len(rst)):
+ self[i] = rst.get_row(i, buff)
- size, kind = self._get_flags(self.dtype.itemsize, self.dtype.kind)
- kind = 'f' if kind == 'd' else kind
- ret = grasscore.run_command('r.out.bin', flags=kind,
- input=self._name, output=self.filename,
- bytes=size, null=self.null,
- quiet=True)
- return ret
def _write(self):
"""
r.in.bin input=/home/pietro/docdat/phd/thesis/gis/north_carolina/user1/.tmp/eraclito/14325.0 output=new title='' bytes=1,anull='' --verbose --overwrite north=228500.0 south=215000.0 east=645000.0 west=630000.0 rows=1350 cols=1500
"""
- self.tofile(self.filename)
- size, kind = self._get_flags(self.dtype.itemsize, self.dtype.kind)
- #print size, kind
- if kind == 'i':
- kind = None
- size = 4
- size = None if kind == 'f' else size
+ if not self.exist() or self.mode != 'r':
+ self.flush()
+ buff = Buffer(self[0].shape, mtype=self.mtype)
+ with RasterRow(self.name, self.mapset, mode='w',
+ mtype=self.mtype) as rst:
+ for i in range(len(rst)):
+ buff[:] = self[i][:]
+ rst.put_row(buff[:])
- # To be set in the future
- self.title = None
- self.null = None
-
- #import pdb; pdb.set_trace()
- if self.mode in ('w+', 'r+'):
- if not self._name:
- import os
- self._name = "doctest_%i" % os.getpid()
- ret = grasscore.run_command('r.in.bin', flags=kind,
- input=self.filename, output=self._name,
- title=self.title, bytes=size,
- anull=self.null,
- overwrite=self.overwrite,
- verbose=True,
- north=self.reg.north,
- south=self.reg.south,
- east=self.reg.east,
- west=self.reg.west,
- rows=self.reg.rows,
- cols=self.reg.cols)
- return ret
-
def open(self, mtype='', null=None, overwrite=None):
"""Open the map, if the map already exist: determine the map type
and copy the map to the segment files;
@@ -641,6 +627,10 @@
self.null = null
# rows and cols already set in __new__
if self.exist():
+ self.info.read()
+ self.cats.mtype = self.mtype
+ self.cats.read()
+ self.hist.read()
self._read()
else:
if mtype:
@@ -652,8 +642,7 @@
def close(self):
self._write()
- np.memmap._close(self)
- grasscore.try_remove(self.filename)
+ os.remove(self.filename)
self._fd = None
def get_value(self, point, region=None):
@@ -676,7 +665,7 @@
row_buf = Buffer((region.cols, ), mtype,
buffer=(np.random.random(region.cols,) * factor).data)
random_map.open('w', mtype, overwrite)
- for _ in xrange(region.rows):
+ for _ in range(region.rows):
random_map.put_row(row_buf)
random_map.close()
return random_map
@@ -686,7 +675,7 @@
region = Region()
random_map = RasterRow(mapname)
random_map.open('w', mtype, overwrite)
- for _ in xrange(region.rows):
+ for _ in range(region.rows):
row_buf = Buffer((region.cols, ), mtype,
buffer=(np.random.random(region.cols,) * factor).data)
random_map.put_row(row_buf)
Modified: grass/trunk/lib/python/pygrass/raster/abstract.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/abstract.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/raster/abstract.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,6 +4,8 @@
@author: pietro
"""
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
import ctypes
#
@@ -25,9 +27,9 @@
#
# import raster classes
#
-from raster_type import TYPE as RTYPE
-from category import Category
-from history import History
+from .raster_type import TYPE as RTYPE
+from .category import Category
+from .history import History
## Define global variables to not exceed the 80 columns
@@ -62,14 +64,19 @@
self.name = name
self.mapset = mapset
self.c_region = ctypes.pointer(libgis.Cell_head())
- libraster.Rast_get_cellhd(name, mapset,
- self.c_region)
- self._get_range()
+ self.c_range = ctypes.pointer(libraster.Range())
def _get_range(self):
- self.c_range = ctypes.pointer(libraster.Range())
libraster.Rast_read_range(self.name, self.mapset, self.c_range)
+ def _get_raster_region(self):
+ if self.name and self.mapset:
+ libraster.Rast_get_cellhd(self.name, self.mapset, self.c_region)
+
+ def read(self):
+ self._get_range()
+ self._get_raster_region()
+
@property
def north(self):
return self.c_region.contents.north
@@ -196,10 +203,9 @@
# when you open the file, using Rast_window_cols()
self._cols = None
#self.region = Region()
- self.cats = Category()
- self.hist = History()
- if self.exist():
- self.info = Info(self.name, self.mapset)
+ self.hist = History(self.name, self.mapset)
+ self.cats = Category(self.name, self.mapset)
+ self.info = Info(self.name, self.mapset)
self.mode = mode
self.mtype = mtype
self.overwrite = overwrite
@@ -288,7 +294,7 @@
if isinstance(key, slice):
#import pdb; pdb.set_trace()
#Get the start, stop, and step from the slice
- return (self.get_row(ii) for ii in xrange(*key.indices(len(self))))
+ return (self.get_row(ii) for ii in range(*key.indices(len(self))))
elif isinstance(key, tuple):
x, y = key
return self.get(x, y)
@@ -304,7 +310,7 @@
def __iter__(self):
"""Return a constructor of the class"""
- return (self.__getitem__(irow) for irow in xrange(self._rows))
+ return (self.__getitem__(irow) for irow in range(self._rows))
def _repr_png_(self):
return raw_figure(functions.r_export(self))
Modified: grass/trunk/lib/python/pygrass/raster/buffer.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/buffer.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/raster/buffer.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,7 +4,7 @@
@author: pietro
"""
-from raster_type import TYPE as RTYPE
+from .raster_type import TYPE as RTYPE
import ctypes
import numpy as np
Modified: grass/trunk/lib/python/pygrass/raster/category.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/category.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/raster/category.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -11,7 +11,7 @@
from grass.pygrass.errors import GrassError
-from raster_type import TYPE as RTYPE
+from .raster_type import TYPE as RTYPE
class Category(list):
@@ -65,9 +65,11 @@
>>> libraster.Rast_get_ith_c_cat(ctypes.byref(cats.cats), 0,
... min_cat, max_cat)
"""
- def __init__(self, mtype=None, *args, **kargs):
- self._cats = libraster.Categories()
- libraster.Rast_init_cats("", ctypes.byref(self._cats))
+ def __init__(self, name, mapset='', mtype=None, *args, **kargs):
+ self.name = name
+ self.mapset = mapset
+ self.c_cats = libraster.Categories()
+ libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
self._mtype = mtype
self._gtype = None if mtype is None else RTYPE[mtype]['grass type']
super(Category, self).__init__(*args, **kargs)
@@ -85,11 +87,11 @@
mtype = property(fget=_get_mtype, fset=_set_mtype)
def _get_title(self):
- return libraster.Rast_get_cats_title(ctypes.byref(self._cats))
+ return libraster.Rast_get_cats_title(ctypes.byref(self.c_cats))
def _set_title(self, newtitle):
return libraster.Rast_set_cats_title(newtitle,
- ctypes.byref(self._cats))
+ ctypes.byref(self.c_cats))
title = property(fget=_get_title, fset=_set_title)
@@ -156,7 +158,7 @@
"""
min_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
max_cat = ctypes.pointer(RTYPE[self.mtype]['grass def']())
- lab = libraster.Rast_get_ith_cat(ctypes.byref(self._cats),
+ lab = libraster.Rast_get_ith_cat(ctypes.byref(self.c_cats),
index,
ctypes.cast(min_cat, ctypes.c_void_p),
ctypes.cast(max_cat, ctypes.c_void_p),
@@ -186,7 +188,7 @@
err = libraster.Rast_set_cat(ctypes.cast(min_cat, ctypes.c_void_p),
ctypes.cast(max_cat, ctypes.c_void_p),
label,
- ctypes.byref(self._cats), self._gtype)
+ ctypes.byref(self.c_cats), self._gtype)
# Manage C function Errors
if err == 1:
return None
@@ -196,7 +198,7 @@
raise GrassError(_("Error executing: Rast_set_cat"))
def __del__(self):
- libraster.Rast_free_cats(ctypes.byref(self._cats))
+ libraster.Rast_free_cats(ctypes.byref(self.c_cats))
def get_cat(self, index):
return self.__getitem__(index)
@@ -210,19 +212,19 @@
raise TypeError("Index outside range.")
def reset(self):
- for i in xrange(len(self) - 1, -1, -1):
+ for i in range(len(self) - 1, -1, -1):
del(self[i])
- libraster.Rast_init_cats("", ctypes.byref(self._cats))
+ libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
def _read_cats(self):
"""Copy from the C struct to the list"""
- for i in xrange(self._cats.ncats):
+ for i in range(self.c_cats.ncats):
self.append(self._get_c_cat(i))
def _write_cats(self):
"""Copy from the list data to the C struct"""
# reset only the C struct
- libraster.Rast_init_cats("", ctypes.byref(self._cats))
+ libraster.Rast_init_cats("", ctypes.byref(self.c_cats))
# write to the c struct
for cat in self.__iter__():
label, min_cat, max_cat = cat
@@ -230,7 +232,7 @@
max_cat = min_cat
self._set_c_cat(label, min_cat, max_cat)
- def read(self, rast, mapset=None, mtype=None):
+ def read(self):
"""Read categories from a raster map
The category file for raster map name in mapset is read into the
@@ -242,25 +244,15 @@
struct Categories * pcats
)
"""
- if type(rast) == str:
- mapname = rast
- if mapset is None or mtype is None:
- raise TypeError(_('Mapset and maptype must be specify'))
- else:
- mapname = rast.name
- mapset = rast.mapset
- mtype = rast.mtype
-
- self.mtype = mtype
self.reset()
- err = libraster.Rast_read_cats(mapname, mapset,
- ctypes.byref(self._cats))
+ err = libraster.Rast_read_cats(self.name, self.mapset,
+ ctypes.byref(self.c_cats))
if err == -1:
raise GrassError("Can not read the categories.")
# copy from C struct to list
self._read_cats()
- def write(self, map):
+ def write(self):
"""Writes the category file for the raster map name in the current
mapset from the cats structure.
@@ -268,18 +260,14 @@
struct Categories * cats
)
"""
- if type(map) == str:
- mapname = map
- else:
- mapname = map.name
# copy from list to C struct
self._write_cats()
# write to the map
- libraster.Rast_write_cats(mapname, ctypes.byref(self._cats))
+ libraster.Rast_write_cats(self.name, ctypes.byref(self.c_cats))
def copy(self, category):
"""Copy from another Category class"""
- libraster.Rast_copy_cats(ctypes.byref(self._cats), # to
+ libraster.Rast_copy_cats(ctypes.byref(self.c_cats), # to
ctypes.byref(category._cats)) # from
self._read_cats()
@@ -342,7 +330,7 @@
f.write('\n'.join(cats))
def sort(self):
- libraster.Rast_sort_cats(ctypes.byref(self._cats))
+ libraster.Rast_sort_cats(ctypes.byref(self.c_cats))
def labels(self):
- return map(itemgetter(0), self)
+ return list(map(itemgetter(0), self))
Modified: grass/trunk/lib/python/pygrass/raster/history.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/history.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/raster/history.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -36,13 +36,28 @@
..
"""
- def __init__(self, name=''):
+ def __init__(self, name, mapset='', mtype='',
+ creator='', src1='', src2='', keyword='',
+ date='', title=''):
self.c_hist = ctypes.pointer(libraster.History())
# 'Tue Nov 7 01:11:23 2006'
self.date_fmt = '%a %b %d %H:%M:%S %Y'
- if name:
- self.read(name)
+ self.name = name
+ self.mapset = mapset
+ self.mtype = mtype
+ self.creator = creator
+ self.src1 = src1
+ self.src2 = src2
+ self.keyword = keyword
+ self.date = date
+ self.title = title
+ def __repr__(self):
+ attrs = ['name', 'mapset', 'mtype', 'creator', 'src1', 'src2',
+ 'keyword', 'date', 'title']
+ return "History(%s)" % ', '.join(["%s=%r" % (attr, getattr(self, attr))
+ for attr in attrs])
+
def __del__(self):
"""Rast_free_history"""
pass
@@ -104,13 +119,15 @@
def _get_date(self):
date_str = libraster.Rast_get_history(self.c_hist,
libraster.HIST_MAPID)
- return datetime.datetime.strptime(date_str, self.date_fmt)
+ if date_str:
+ return datetime.datetime.strptime(date_str, self.date_fmt)
def _set_date(self, datetimeobj):
- date_str = datetimeobj.strftime(self.date_fmt)
- return libraster.Rast_set_history(self.c_hist,
- libraster.HIST_MAPID,
- ctypes.c_char_p(date_str))
+ if datetimeobj:
+ date_str = datetimeobj.strftime(self.date_fmt)
+ return libraster.Rast_set_history(self.c_hist,
+ libraster.HIST_MAPID,
+ ctypes.c_char_p(date_str))
date = property(fget=_get_date, fset=_set_date)
@@ -203,7 +220,7 @@
libraster.Rast_history_line(self.c_hist,
ctypes.c_int(line))
- def read(self, name):
+ def read(self):
"""Rast_read_history. ::
>>> import grass.lib.gis as libgis
@@ -221,17 +238,15 @@
..
"""
- libraster.Rast_read_history(ctypes.c_char_p(name),
- ctypes.c_char_p(''),
- self.c_hist)
+ libraster.Rast_read_history(self.name, self.mapset, self.c_hist)
- def write(self, name):
+ def write(self):
"""Rast_write_history"""
- libraster.Rast_write_history(ctypes.c_char_p(name),
+ libraster.Rast_write_history(self.name,
self.c_hist)
- def short(self, name, maptype,):
+ def short(self):
"""Rast_short_history"""
- libraster.Rast_short_history(ctypes.c_char_p(name),
- ctypes.c_char_p(maptype),
+ libraster.Rast_short_history(self.name,
+ 'raster',
self.c_hist)
Modified: grass/trunk/lib/python/pygrass/raster/rowio.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/rowio.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/raster/rowio.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -10,7 +10,7 @@
import grass.lib.raster as librast
from grass.pygrass.errors import GrassError
-from raster_type import TYPE as RTYPE
+from .raster_type import TYPE as RTYPE
CMPFUNC = ctypes.CFUNCTYPE(ctypes.c_int,
Modified: grass/trunk/lib/python/pygrass/raster/segment.py
===================================================================
--- grass/trunk/lib/python/pygrass/raster/segment.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/raster/segment.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -8,7 +8,7 @@
import grass.lib.gis as libgis
import grass.lib.raster as libraster
import grass.lib.segment as libseg
-from raster_type import TYPE as RTYPE
+from .raster_type import TYPE as RTYPE
class Segment(object):
Modified: grass/trunk/lib/python/pygrass/shell/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/shell/__init__.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/shell/__init__.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -5,6 +5,6 @@
@author: pietro
"""
-import conversion
-import show
+from . import conversion
+from . import show
Modified: grass/trunk/lib/python/pygrass/tests/benchmark.py
===================================================================
--- grass/trunk/lib/python/pygrass/tests/benchmark.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/tests/benchmark.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -4,6 +4,9 @@
@author: soeren
"""
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
+
import optparse
#import numpy as np
import time
@@ -28,8 +31,8 @@
test_c = pygrass.RasterNumpy(name="test_c", mtype="CELL", mode="w+", overwrite=True)
test_c.open()
- for row in xrange(test_a.rows):
- for col in xrange(test_a.cols):
+ for row in range(test_a.rows):
+ for col in range(test_a.cols):
test_c[row, col] = test_a[row, col] > 50
test_a.close()
@@ -45,8 +48,8 @@
test_c = pygrass.RasterNumpy(name="test_c", mtype="DCELL", mode="w+", overwrite=True)
test_c.open()
- for row in xrange(test_a.rows):
- for col in xrange(test_a.cols):
+ for row in range(test_a.rows):
+ for col in range(test_a.cols):
test_c[row, col] = test_a[row, col] + test_b[row, col]
test_a.close()
@@ -60,7 +63,7 @@
test_c = pygrass.RasterNumpy(name="test_c", mtype="CELL", mode="w+", overwrite=True)
test_c.open()
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_c[row] = test_a[row] > 50
test_a.close()
@@ -76,7 +79,7 @@
test_c = pygrass.RasterNumpy(name="test_c", mtype="DCELL", mode="w+", overwrite=True)
test_c.open()
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_c[row] = test_a[row] + test_b[row]
test_a.close()
@@ -120,9 +123,9 @@
buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_a.get_row(row, buff_a)
- for col in xrange(test_a.cols):
+ for col in range(test_a.cols):
test_c.put(row, col, buff_a[col] > 50)
test_a.close()
@@ -141,10 +144,10 @@
buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_a.get_row(row, buff_a)
test_b.get_row(row,buff_b)
- for col in xrange(test_a.cols):
+ for col in range(test_a.cols):
test_c.put(row, col, buff_a[col] + buff_b[col])
test_a.close()
@@ -160,7 +163,7 @@
buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_a.get_row(row, buff_a)
test_c.put_row(row, buff_a > 50)
@@ -180,7 +183,7 @@
buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_a.get_row(row, buff_a)
test_b.get_row(row,buff_b)
test_c.put_row(row, buff_a + buff_b)
@@ -203,11 +206,11 @@
buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
buff_c = pygrass.Buffer(test_b.cols, test_b.mtype)
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_a.get_row(row, buff_a)
test_b.get_row(row,buff_b)
- for col in xrange(test_a.cols):
+ for col in range(test_a.cols):
buff_c[col] = buff_a[col] + buff_b[col]
test_c.put_row(buff_c)
@@ -226,10 +229,10 @@
buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
buff_c = pygrass.Buffer(test_a.cols, test_a.mtype)
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_a.get_row(row, buff_a)
- for col in xrange(test_a.cols):
+ for col in range(test_a.cols):
buff_c[col] = buff_a[col] > 50
test_c.put_row(buff_c)
@@ -250,7 +253,7 @@
buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_a.get_row(row, buff_a)
test_b.get_row(row,buff_b)
test_c.put_row(buff_a + buff_b)
@@ -268,7 +271,7 @@
buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_a.get_row(row, buff_a)
test_c.put_row(buff_a > 50)
@@ -288,7 +291,7 @@
buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
buff_b = pygrass.Buffer(test_b.cols, test_b.mtype)
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_a.get_row(row, buff_a)
test_b.get_row(row,buff_b)
test_c.put_row(buff_a + buff_b)
@@ -306,7 +309,7 @@
buff_a = pygrass.Buffer(test_a.cols, test_a.mtype)
- for row in xrange(test_a.rows):
+ for row in range(test_a.rows):
test_a.get_row(row, buff_a)
test_c.put_row(buff_a > 50)
@@ -322,7 +325,7 @@
def mytimer(func, runs=1):
times = []
t = 0.0
- for _ in xrange(runs):
+ for _ in range(runs):
start = time.time()
func()
end = time.time()
@@ -363,15 +366,15 @@
result['rows'] = region.rows
result['cells'] = region.rows * region.cols
result['results'] = copy.deepcopy(testdict)
- for execmode, operation in result['results'].iteritems():
+ for execmode, operation in result['results'].items():
print(execmode)
- for oper, operdict in operation.iteritems():
+ for oper, operdict in operation.items():
operdict['time'], operdict['times'] = mytimer(operdict['func'],runs)
if profile:
filename = '{}_{}_{}'.format(execmode, oper, profile)
cProfile.runctx(operdict['func'].__name__ + '()',
globals(), locals(), filename = filename)
- print(' {0}: {1: 40.6f}s'.format(oper, operdict['time']))
+ print((' {0}: {1: 40.6f}s'.format(oper, operdict['time'])))
del(operdict['func'])
regions.append(result)
@@ -380,7 +383,7 @@
return regions
def get_testlist(loc):
- testlist = [test for test in loc.keys() if 'test' in test[:5]]
+ testlist = [test for test in list(loc.keys()) if 'test' in test[:5]]
testlist.sort()
return testlist
@@ -389,7 +392,7 @@
for testfunc in testlist:
#import pdb; pdb.set_trace()
dummy, execmode, operation = testfunc.split('__')
- if execmode in testdict.keys():
+ if execmode in list(testdict.keys()):
testdict[execmode][operation] = collections.OrderedDict()
testdict[execmode][operation]['func'] = loc[testfunc]
else:
@@ -399,14 +402,14 @@
return testdict
def print_test(testdict):
- for execmode, operation in testdict.iteritems():
- print execmode
- for oper, operdict in operation.iteritems():
- print ' ', oper
- for key, value in operdict.iteritems():
- print ' ', key
+ for execmode, operation in testdict.items():
+ print(execmode)
+ for oper, operdict in operation.items():
+ print(' ', oper)
+ for key, value in operdict.items():
+ print(' ', key)
-TXT = u"""
+TXT = """
{% for region in regions %}
{{ '#'*60 }}
### Benchmark cols = {{ region.cols }} rows = {{ region.rows}} cells = {{ region.cells }}
@@ -506,7 +509,7 @@
pickle.dump(results, output)
output.close()
#import pdb; pdb.set_trace()
- print get_txt(results)
+ print(get_txt(results))
#add options
Modified: grass/trunk/lib/python/pygrass/tests/set_mapset.py
===================================================================
--- grass/trunk/lib/python/pygrass/tests/set_mapset.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/tests/set_mapset.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -5,6 +5,9 @@
@author: pietro
"""
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
+
import os
import subprocess
import optparse
@@ -31,8 +34,8 @@
parser.add_option("-P", "--password", dest="passwd", default=None,
help="PostgreSQL password for user [default=%default]")
parser.add_option("-D", "--database", dest="db", default='pygrassdb_doctest',
- help="PostgreSQL database name [default=%default]")
-
+ help="PostgreSQL database name [default=%default]")
+
(opts, args) = parser.parse_args()
#
# Create DB
@@ -41,19 +44,19 @@
createdb = ['createdb', '--encoding=UTF-8', '--owner=%s' % opts.user,
'--host=localhost', '--username=%s' % opts.user, opts.db]
if opts.passwd:
- print opts.passwd
+ print(opts.passwd)
createdb.append("--password=%s" % opts.passwd)
else:
createdb.append("--no-password")
subprocess.Popen(createdb)
-
+
#
# set postgreSQL
#
print("\n\nSet Postgres connection...\n")
grasscore.run_command('db.connect', driver='pg',
database='host=localhost,dbname=%s' % opts.db)
-
+
grasscore.run_command('db.login', user=opts.user)
print("\n\nCopy the map from PERMANENT to user1...\n")
grasscore.run_command('g.copy',
@@ -61,8 +64,8 @@
overwrite=True)
print("\n\nBuild topology...\n")
grasscore.run_command('v.build', map='boundary_municp_pg', overwrite=True)
-
-
+
+
#
# set sqlite
#
@@ -76,6 +79,6 @@
overwrite=True)
print("\n\nBuild topology...\n")
grasscore.run_command('v.build', map='boundary_municp_sqlite', overwrite=True)
-
+
if __name__ == "__main__":
main()
\ No newline at end of file
Modified: grass/trunk/lib/python/pygrass/vector/__init__.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/__init__.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/vector/__init__.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -5,7 +5,7 @@
@author: pietro
"""
import grass.lib.vector as libvect
-from vector_type import VTYPE
+from .vector_type import VTYPE
from os.path import join, exists
#
@@ -14,11 +14,11 @@
from grass.pygrass.errors import GrassError, must_be_open
from grass.pygrass.gis import Location
-from geometry import GEOOBJ as _GEOOBJ
-from geometry import read_line, read_next_line
-from geometry import Area as _Area
-from abstract import Info
-from basic import Bbox, Cats, Ilist
+from .geometry import GEOOBJ as _GEOOBJ
+from .geometry import read_line, read_next_line
+from .geometry import Area as _Area
+from .abstract import Info
+from .basic import Bbox, Cats, Ilist
_NUMOF = {"areas": libvect.Vect_get_num_areas,
@@ -276,7 +276,7 @@
#import pdb; pdb.set_trace()
#Get the start, stop, and step from the slice
return [self.read(indx + 1)
- for indx in xrange(*key.indices(len(self)))]
+ for indx in range(*key.indices(len(self)))]
elif isinstance(key, int):
return self.read(key)
else:
@@ -389,7 +389,7 @@
"""
if vtype in _GEOOBJ.keys():
if _GEOOBJ[vtype] is not None:
- ids = (indx for indx in xrange(1, self.number_of(vtype) + 1))
+ ids = (indx for indx in range(1, self.number_of(vtype) + 1))
if idonly:
return ids
return (_GEOOBJ[vtype](v_id=indx, c_mapinfo=self.c_mapinfo,
@@ -422,7 +422,7 @@
libvect.Vect_rewind(self.c_mapinfo)
@must_be_open
- def cat(self, cat_id, vtype, layer=None, generator=False):
+ def cat(self, cat_id, vtype, layer=None, generator=False, geo=None):
"""Return the geometry features with category == cat_id.
Parameters
@@ -436,18 +436,22 @@
generator : bool, optional
If True return a generator otherwise it return a list of features.
"""
- if vtype not in _GEOOBJ:
+ if geo is None and vtype not in _GEOOBJ:
keys = "', '".join(sorted(_GEOOBJ.keys()))
raise ValueError("vtype not supported, use one of: '%s'" % keys)
- Obj = _GEOOBJ[vtype]
+ Obj = _GEOOBJ[vtype] if geo is None else geo
ilist = Ilist()
libvect.Vect_cidx_find_all(self.c_mapinfo,
layer if layer else self.layer,
Obj.gtype, cat_id, ilist.c_ilist)
if generator:
- return (Obj(v_id=v_id, c_mapinfo=self.c_mapinfo) for v_id in ilist)
+ return (read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
+ table=self.table, writable=self.writable)
+ for v_id in ilist)
else:
- return [Obj(v_id=v_id, c_mapinfo=self.c_mapinfo) for v_id in ilist]
+ return [read_line(feature_id=v_id, c_mapinfo=self.c_mapinfo,
+ table=self.table, writable=self.writable)
+ for v_id in ilist]
@must_be_open
def read(self, feature_id):
@@ -549,4 +553,4 @@
occupied by spatial index is released"""
if release:
libvect.Vect_set_release_support(self.c_mapinfo)
- super(VectorTopo, self).close()
+ super(VectorTopo, self).close(build=build)
Modified: grass/trunk/lib/python/pygrass/vector/abstract.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/abstract.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/vector/abstract.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -7,12 +7,12 @@
import ctypes
import datetime
import grass.lib.vector as libvect
-from vector_type import MAPTYPE
+from .vector_type import MAPTYPE
from grass.pygrass import functions
from grass.pygrass.errors import GrassError, OpenError, must_be_open
-from table import DBlinks, Link
-from find import PointFinder, BboxFinder, PolygonFinder
+from .table import DBlinks, Link
+from .find import PointFinder, BboxFinder, PolygonFinder
def is_open(c_mapinfo):
@@ -78,8 +78,8 @@
"""
def __init__(self, name, mapset='', layer=None, mode='r'):
- self._name = None
- self._mapset = None
+ self._name = ''
+ self._mapset = ''
# Set map name and mapset
self.name = name
self.mapset = mapset
@@ -121,8 +121,6 @@
"""Private method to change the Vector name"""
if mapset:
self._mapset = mapset
- else:
- self._mapset = ''
mapset = property(fget=_get_mapset, fset=_set_mapset)
Modified: grass/trunk/lib/python/pygrass/vector/basic.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/basic.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/vector/basic.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -186,7 +186,7 @@
self.c_boxlist.contents.box[indx] = bbox
def __iter__(self):
- return (self.__getitem__(box_id) for box_id in xrange(self.__len__()))
+ return (self.__getitem__(box_id) for box_id in range(self.__len__()))
def __str__(self):
return self.__repr__()
@@ -297,7 +297,7 @@
#import pdb; pdb.set_trace()
#Get the start, stop, and step from the slice
return [self.c_ilist.contents.value[indx]
- for indx in xrange(*key.indices(len(self)))]
+ for indx in range(*key.indices(len(self)))]
elif isinstance(key, int):
if key < 0: # Handle negative indices
key += self.c_ilist.contents.n_values
@@ -316,7 +316,7 @@
return self.c_ilist.contents.n_values
def __iter__(self):
- return (self.c_ilist.contents.value[i] for i in xrange(self.__len__()))
+ return (self.c_ilist.contents.value[i] for i in range(self.__len__()))
def __repr__(self):
return "Ilist(%r)" % [i for i in self.__iter__()]
@@ -395,12 +395,12 @@
@property
def layer(self):
field = self.c_cats.contents.field
- return [field[i] for i in xrange(self.n_cats)]
+ return [field[i] for i in range(self.n_cats)]
@property
def cat(self):
cat = self.c_cats.contents.cat
- return [cat[i] for i in xrange(self.n_cats)]
+ return [cat[i] for i in range(self.n_cats)]
@property
def n_cats(self):
@@ -490,13 +490,13 @@
def min(self):
"""Return the minimum value"""
min_values = self.c_cat_list.contents.min
- return [min_values[i] for i in xrange(self.n_ranges)]
+ return [min_values[i] for i in range(self.n_ranges)]
@property
def max(self):
"""Return the maximum value"""
max_values = self.c_cat_list.contents.max
- return [max_values[i] for i in xrange(self.n_ranges)]
+ return [max_values[i] for i in range(self.n_ranges)]
def __init__(self, c_cat_list=None):
self.c_cat_list = c_cat_list if c_cat_list \
Modified: grass/trunk/lib/python/pygrass/vector/find.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/find.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/vector/find.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -8,8 +8,8 @@
from grass.pygrass.errors import must_be_open
-from basic import Ilist, BoxList
-from geometry import read_line, Isle, Area, Point
+from .basic import Ilist, BoxList
+from .geometry import read_line, Isle, Area, Point
class AbstractFinder(object):
@@ -27,7 +27,7 @@
def is_open(self):
"""Check if the vector map is open or not"""
- import abstract
+ from . import abstract
return abstract.is_open(self.c_mapinfo)
Modified: grass/trunk/lib/python/pygrass/vector/geometry.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/geometry.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/vector/geometry.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -15,8 +15,8 @@
from grass.pygrass.errors import GrassError
-from basic import Ilist, Bbox, Cats
-import sql
+from .basic import Ilist, Bbox, Cats
+from . import sql
WKT = {'POINT\((.*)\)': 'point', # 'POINT\(\s*([+-]*\d+\.*\d*)+\s*\)'
@@ -159,9 +159,12 @@
"""
#SELECT {cols} FROM {tname} WHERE {condition};
- cur = self.table.execute(sql.SELECT_WHERE.format(cols=key,
+ try:
+ cur = self.table.execute(sql.SELECT_WHERE.format(cols=key,
tname=self.table.name,
condition=self.cond))
+ except:
+ import ipdb; ipdb.set_trace()
results = cur.fetchone()
if results is not None:
return results[0] if len(results) == 1 else results
@@ -316,7 +319,7 @@
False
>>> pnt
Point(0.000000, 0.000000, 0.000000)
- >>> print pnt
+ >>> print(pnt)
POINT(0.000000, 0.000000, 0.000000)
..
@@ -547,7 +550,7 @@
return [Point(self.c_points.contents.x[indx],
self.c_points.contents.y[indx],
None if self.is2D else self.c_points.contents.z[indx])
- for indx in xrange(*key.indices(len(self)))]
+ for indx in range(*key.indices(len(self)))]
elif isinstance(key, int):
if key < 0: # Handle negative indices
key += self.c_points.contents.n_points
@@ -1017,7 +1020,7 @@
return Area(boundary=Line(c_points=p_bound.contents),
centroid=self[0],
isles=[Line(c_points=pp_isle[i].contents)
- for i in xrange(n_isles.contents.value)])
+ for i in range(n_isles.contents.value)])
def reset(self):
"""Reset line, using `Vect_reset_line` C function. ::
@@ -1053,7 +1056,7 @@
super(Boundary, self).__init__(**kargs)
self.c_left = ctypes.pointer(ctypes.c_int())
self.c_right = ctypes.pointer(ctypes.c_int())
- self.get_left_right()
+ #self.get_left_right()
@property
def left_id(self):
@@ -1395,7 +1398,7 @@
return Area(boundary=Line(c_points=p_bound.contents),
centroid=self.centroid,
isles=[Line(c_points=pp_isle[i].contents)
- for i in xrange(n_isles.contents.value)])
+ for i in range(n_isles.contents.value)])
def boundaries(self, ilist=False):
"""Creates list of boundaries for given area.
Modified: grass/trunk/lib/python/pygrass/vector/table.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/table.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/vector/table.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -7,7 +7,14 @@
"""
+from __future__ import (nested_scopes, generators, division, absolute_import,
+ with_statement, print_function, unicode_literals)
+
import os
+import sys
+
+long = int if sys.version_info.major == 3 else long
+
import ctypes
import numpy as np
from sqlite3 import OperationalError
@@ -24,7 +31,7 @@
from grass.script.db import db_table_in_vector
from grass.script.core import warning
-import sql
+from . import sql
DRIVERS = ('sqlite', 'pg')
@@ -724,12 +731,12 @@
..
"""
- print "layer: ", self.layer
- print "name: ", self.name
- print "table: ", self.table_name
- print "key: ", self.key
- print "database: ", self.database
- print "driver: ", self.driver
+ print("layer: ", self.layer)
+ print("name: ", self.name)
+ print("table: ", self.table_name)
+ print("key: ", self.key)
+ print("database: ", self.database)
+ print("driver: ", self.driver)
class DBlinks(object):
@@ -756,7 +763,7 @@
def __iter__(self):
return (self.by_index(i)
- for i in xrange(self.num_dblinks()))
+ for i in range(self.num_dblinks()))
def __getitem__(self, item):
"""
@@ -904,7 +911,7 @@
def __iter__(self):
cur = self.execute()
- return (cur.fetchone() for _ in xrange(self.__len__()))
+ return (cur.fetchone() for _ in range(self.__len__()))
def __len__(self):
"""Return the number of rows"""
@@ -965,6 +972,7 @@
return cur.executemany(sqlc, values)
return cur.execute(sqlc)
except:
+ #import ipdb; ipdb.set_trace()
raise ValueError("The SQL is not correct:\n%r" % sqlc)
def exist(self, cursor=None):
@@ -1004,6 +1012,6 @@
coldef=coldef))
self.conn.commit()
else:
- print "The table: %s already exist." % self.name
+ print("The table: %s already exist." % self.name)
cur.close()
self.columns.update_odict()
Modified: grass/trunk/lib/python/pygrass/vector/vector_type.py
===================================================================
--- grass/trunk/lib/python/pygrass/vector/vector_type.py 2014-02-23 16:05:59 UTC (rev 59126)
+++ grass/trunk/lib/python/pygrass/vector/vector_type.py 2014-02-23 20:45:30 UTC (rev 59127)
@@ -6,7 +6,7 @@
"""
import grass.lib.vector as libvect
-import geometry as geo
+from . import geometry as geo
MAPTYPE = {libvect.GV_FORMAT_NATIVE: "native",
libvect.GV_FORMAT_OGR: "OGR",
More information about the grass-commit
mailing list