inmemoryraster.py 2.36 KB
Newer Older
1
2
from .gridenvelope2d import GridEnvelope2D;
from .raster import Raster
3
import numpy as np
4
from .const import constants as const
5

6
__author__ = "Steven B. Hoek"
7

8
class InMemoryRaster(Raster, GridEnvelope2D):
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    "A raster developed in the first place for testing purposes"
    # Data attributes
    data = None
    __datatype = None
    __open = False
    dataformat = 'f'

    def __init__(self, filepath, data=None, *datatype):
        Raster.__init__(self, filepath)
        if data != None:
            self.data = data
        if len(datatype) > 0:
            if (datatype[0] == const.INTEGER): 
                self.__datatype = const.INTEGER;
                self.dataformat = 'i'
            else: 
                self.__datatype = const.FLOAT; 
                self.dataformat = 'f'
    
    def open(self, mode, ncols=1, nrows=1, xll=0.0, yll=0.0, cellsize=1.0, nodatavalue=-9999.0):
        super(InMemoryRaster, self).open(mode);
        self.__open = True
        if self.__datatype == const.INTEGER:
            dtype = np.int 
        else:
            dtype = np.float   
        if mode[0] == 'w':
            self.data = np.zeros((nrows*ncols), dtype=dtype)
        else:
            if self.data == None: raise Exception("Memory was not initialised!")
            self.data = np.array(self.data, dtype=dtype)
        self.data = self.data.flatten()
        self.data.shape = (nrows, ncols)
        self.xll = xll
        self.yll = yll
        self.dx = cellsize
        self.dy = cellsize
46
        self.cellsize = cellsize
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
        self.nodatavalue = nodatavalue
        GridEnvelope2D.__init__(self, ncols, nrows, self.xll, self.yll, self.dx, self.dy)
        return True;
    
    def next(self, parseLine=True):
        if not self.__open: raise Exception("Not yet fully initialised!") 
        self.currow += 1;
        if (self.currow > self.nrows): raise StopIteration;
        if parseLine:
            return self.data[self.currow - 1, :]
        else:
            return None
    
    def writenext(self, sequence_with_data):
        if not self.__open: raise Exception("Not yet fully initialised!")
        self.currow += 1;
        if (self.currow > self.nrows): raise StopIteration;
        if len(sequence_with_data) != self.ncols:
            raise Exception("Attempt to assign line of wrong length!")
        self.data[self.currow - 1, :] = sequence_with_data
        return True