asciigrid.py 9.29 KB
Newer Older
1
2
3
4
from .const import Const, constants as const
import os.path
import array
from .raster import Raster
Hoek, Steven's avatar
Hoek, Steven committed
5
from .gridenvelope2d import GridEnvelope2D;
6
from builtins import int
Hoek, Steven's avatar
Hoek, Steven committed
7

8
9
10
__author__ = "Steven B. Hoek"

class AsciiGrid(Raster, GridEnvelope2D):
11
    """A raster represented by an ASCII file, with extension 'asc'"""
Hoek, Steven's avatar
Hoek, Steven committed
12
13
    
    # Data attributes - assign some dummy values for the mean time
14
15
    _const = None
    name = ""
Hoek, Steven's avatar
Hoek, Steven committed
16
17
18
19
20
21
22
23
24
25
26
27
    folder = os.getcwd();
    cellsize = 100.0;
    nodatavalue = -9999.0;
    datatype = const.FLOAT;
    dataformat='f'
    
    # Private attributes
    datafile = None;
    currow = 0;
    __mode = 'r';
    __digitspercell = 7;
    
28
29
30
31
32
    def __init__(self, filepath='', *datatype):
        # Check input
        if filepath == '':
            print('File path cannot be an empty string (method __init__).')
            
33
34
35
        # Module wide constants
        self._const = Const()
        self._const.FILEXT = "asc";     
36
        self._const.MAXDIGITSPERCELL = 8 # TODO this is hardcoded - change this
37
38
39
40
41
        self.name = "dummy." + self._const.FILEXT;
        
        # Initialise further
        super(AsciiGrid, self).__init__(filepath)
        
Hoek, Steven's avatar
Hoek, Steven committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
        # Retrieve the name from the filepath and assign - incl. extension
        self.name = os.path.basename(filepath);
        # Also derive the folder
        self.folder = os.path.dirname(filepath);
        # Finally set the datatype
        if len(datatype) > 0:
            if (datatype[0] == const.INTEGER): 
                self.datatype = const.INTEGER;
                self.dataformat = 'i'
            else: 
                self.datatype = const.FLOAT;
                
    def open(self, mode, ncols=1, nrows=1, xll=0.0, yll=0.0, cellsize=100.0, nodatavalue=-9999.0):
        # Initialise
        super(AsciiGrid, self).open(mode); 
57
    
Hoek, Steven's avatar
Hoek, Steven committed
58
        # If file does not exist and mode[0] = 'w', create it!
59
60
        if (mode[0] == 'w') and (not self.file_exists):
            self.datafile = open(os.path.join(self.folder, self.name), 'w');
Hoek, Steven's avatar
Hoek, Steven committed
61
62
63
64
65
66
67
68
            self.__mode = mode;
            GridEnvelope2D.__init__(self, ncols, nrows, xll, yll, cellsize, cellsize);
            self.cellsize = cellsize;
            self.nodatavalue = nodatavalue;
            self.writeheader();
            return True;
        else:    
            # Open the file
69
70
            if self.file_exists:            
                self.datafile = open(os.path.join(self.folder, self.name), mode[0]); 
Hoek, Steven's avatar
Hoek, Steven committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
                if (mode[0] == 'w'):
                    # Assign the data attributes 
                    self.ncols = ncols;
                    self.nrows = nrows;                    
                    self.xll = xll;
                    self.yll = yll;
                    self.cellsize = cellsize;
                    self.nodatavalue = nodatavalue;
                    self.writeheader();
                else: 
                    # File is open - retrieve the data attributes from the header of the file
                    self.readheader();
                    
                    # Also find out how many digits per cell were used - assume it's constant
                    pos = self.datafile.tell();
                    line = self.datafile.readline();
                    self.__digitspercell = ((1 + len(line)) / self.ncols) - 1;
                    self.datafile.seek(pos);  # return to first line with data
                    GridEnvelope2D.__init__(self, self.ncols, self.nrows, self.xll, self.yll, self.cellsize, self.cellsize);
                return True;
            else: return False;
            
    def readheader(self):
        # Assume that the file is open; read header of the file and assign all attributes 
        if (self.datafile != None):
96
            # TODO: make this case-insensitive!
Hoek, Steven's avatar
Hoek, Steven committed
97
98
            if (not self.datafile.closed):            
                hl = self.datafile.readline();
99
                self.ncols = int(hl.replace(const.NCOLS, ''));
Hoek, Steven's avatar
Hoek, Steven committed
100
                hl = self.datafile.readline();
101
                self.nrows = int(hl.replace(const.NROWS, ''));
Hoek, Steven's avatar
Hoek, Steven committed
102
                hl = self.datafile.readline();
103
                self.xll = float(hl.replace(const.XLLCORNER.lower(), ''));        
Hoek, Steven's avatar
Hoek, Steven committed
104
                hl = self.datafile.readline();
105
                self.yll = float(hl.replace(const.YLLCORNER.lower(), ''));        
Hoek, Steven's avatar
Hoek, Steven committed
106
                hl = self.datafile.readline();
107
                self.cellsize = float(hl.replace(const.CELLSIZE, ''));        
Hoek, Steven's avatar
Hoek, Steven committed
108
109
                hl = self.datafile.readline();
                if (self.datatype == const.INTEGER): 
110
                    self.nodatavalue = int(hl.replace(const.NODATA_VALUE, ''));
Hoek, Steven's avatar
Hoek, Steven committed
111
                else: 
112
                    self.nodatavalue = float(hl.replace(const.NODATA_VALUE, ''));
Hoek, Steven's avatar
Hoek, Steven committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
            else: 
                msg = "File " + self.name + " not found in folder " + self.folder;
                raise IOError(msg);                
    
    def next(self, parseLine=True):
        # Read the next row if possible, otherwise generate StopIteration
        # Assume that the header lines have been read and are correct wrt. ncols and nrows
        result = None;
        try:
            if (self.datafile != None):
                if (not self.datafile.closed):
                    self.currow += 1;
                    if (self.currow > self.nrows): 
                        raise StopIteration("Attempt to move beyond last row.");
                    
                    # Allocate a new array with ncols of the right type
                    if (self.datatype == const.INTEGER):
                        result = array.array('l', self.ncols * [self.nodatavalue]);
                    else:
                        result = array.array('f', self.ncols * [self.nodatavalue]);

                    # Now fill the array - first translate whitespace into space
                    rawline = self.datafile.readline();
                    if parseLine:
                        i = 0;                    
                        for x in rawline.split(): 
                            if (i < self.ncols):
                                if (self.datatype == const.INTEGER):
                                    result[i] = int(x);
                                else:
                                    result[i] = float(x);
                            i = i + 1;
                    return result;
                else: raise StopIteration("Attempt to read raster data from a closed file.");
            else: raise StopIteration("Attempt to read raster data from an unassigned file.")
148
149
        except Exception as e:
            print("Error: " + str(e));
Hoek, Steven's avatar
Hoek, Steven committed
150
151
152
            raise StopIteration;
           
    @staticmethod
153
154
    def getFileExt(self):
        return Raster.getDataFileExt()
Hoek, Steven's avatar
Hoek, Steven committed
155
156
157
158
159
160
        
    def writeheader(self):
        # Assume that the file is open; write header of the file with all attributes 
        if (self.datafile != None):
            if (not self.datafile.closed):
                try:
161
162
163
164
165
166
167
168
169
                    maxdigits = self._const.MAXDIGITSPERCELL + 1
                    self.datafile.write(const.NCOLS + "         " + str(self.ncols).rjust(maxdigits) + "\n");
                    self.datafile.write(const.NROWS + "         " + str(self.nrows).rjust(maxdigits) + "\n");
                    self.datafile.write(const.XLLCORNER.lower() + "     " + str(self.xll).rjust(maxdigits) + "\n");
                    self.datafile.write(const.YLLCORNER.lower() + "     " + str(self.yll).rjust(maxdigits) + "\n");
                    self.datafile.write(const.CELLSIZE + "      " + str(self.cellsize).rjust(maxdigits) + "\n");
                    self.datafile.write(const.NODATA_VALUE + "  " + str(self.nodatavalue).rjust(maxdigits) + "\n");
                except Exception as e:
                    print(e);
Hoek, Steven's avatar
Hoek, Steven committed
170
171
172
173
174
175
176
177
                    msg = "Header lines could not be written to file " + self.name + " in folder " + self.folder;
                    raise IOError(msg);
        
    def writenext(self, sequence_with_data):
        # Write the next line if possible, otherwise generate StopIteration
        # We assume that exactly 1 row is included.
        try:          
            if (self.datatype == const.INTEGER):
178
                # TODO deal with numpy arrays if necessary
Hoek, Steven's avatar
Hoek, Steven committed
179
                for k in range(0, self.ncols):
180
                    s = str(sequence_with_data[k]).rjust(self._const.MAXDIGITSPERCELL + 1);
Hoek, Steven's avatar
Hoek, Steven committed
181
182
                    self.datafile.write(s);  
            else:
183
                totalwidth = self._const.MAXDIGITSPERCELL - 1
184
                fmtstr = "{:" + str(totalwidth) + ".3f}" # TODO format is hardcoded - change this!
Hoek, Steven's avatar
Hoek, Steven committed
185
                for k in range(0, self.ncols):
186
                    s = fmtstr.format(sequence_with_data[k]).rjust(self._const.MAXDIGITSPERCELL + 1);
Hoek, Steven's avatar
Hoek, Steven committed
187
188
                    self.datafile.write(s);                 
            return self.datafile.write("\n");
189
190
        except Exception as e:
            print(e);            
Hoek, Steven's avatar
Hoek, Steven committed
191
192
193
194
195
196
197
198
199
200
            raise StopIteration
    
    def flush(self):
        self.datafile.flush();
                
    def reset(self):
        self.datafile.seek(0);
        if (self.__mode[0] == 'r'):
            self.readheader();
        super(AsciiGrid, self).reset() 
201
202
203
204
205
206
207
      
    def get_value(self, i, k):    
        # Return the wanted value
        for _ in range(0, i): self.next(False)
        line = self.next()
        self.reset()
        return line[int(k)]
208
209
210
211
212
213
    
    def get_type(self):
        if self.dataformat == 'i':
            return int
        else:
            return float
Hoek, Steven's avatar
Hoek, Steven committed
214