bsqraster.py 6.79 KB
Newer Older
Hoek, Steven's avatar
Hoek, Steven committed
1
2
3
4
5
6
# -*- coding: utf-8 -*-
import os
import stat
import struct
from math import fabs
from array import array
7
from .bandraster import BandRaster
Hoek, Steven's avatar
Hoek, Steven committed
8
9
10
11
12
try:
    import numpy
    HAS_NUMPY = True
except ImportError:
    HAS_NUMPY = False
13
14
    
__author__ = "Steven B. Hoek"
Hoek, Steven's avatar
Hoek, Steven committed
15
16
17
18
19
20
21
22

class BsqRaster(BandRaster):
    "A raster represented by 2 files, with extensions 'bsq' and 'bsq.hdr'"
    
    # TODO: change some function calls so that it's more obvious how to use "with" statements
    # Use of such statements are essential when files are written to disk!
    
    # Data attributes - assign some dummy values for the mean time
23
24
    _const = None
    name = "";
Hoek, Steven's avatar
Hoek, Steven committed
25
    
26
27
28
29
30
31
32
33
    def __init__(self, filepath='', *dataformat):
        # Check input
        if filepath == '':
            print('File path cannot be an empty string (method __init__).')
        if len(dataformat) == 0:
            print("Data type 'float' assumed (method __init__).")
            dataformat = 'f'
            
Hoek, Steven's avatar
Hoek, Steven committed
34
35
        # Initialise super class instance
        BandRaster.__init__(self, filepath, dataformat[0])
36
37
38
39
40
41
42
43
        if self._const == None:
            raise AttributeError("BIL raster not properly initialised!")
        self._const.DATAFILEXT = "bsq"
        self._const.WORLDEXT = "bqw"
        self.byteorder = self._const.INTEL
        self.pixeltype = self._const.UNSIGNEDINT
        if self.name == "":
            self.name = "dummy." + self._const.DATAFILEXT
Hoek, Steven's avatar
Hoek, Steven committed
44
45
        self.currow = -1; 

46
    def open(self, mode, ncols=1, nrows=1, nbands=1, xll=0, yll=0, cellsize=100, nodatavalue=256):
Hoek, Steven's avatar
Hoek, Steven committed
47
48
49
50
51
52
53
54
55
56
57
        result = super(BsqRaster, self).open(mode, ncols, nrows, nbands, xll, yll, cellsize, nodatavalue)
        if (mode[0] == 'w'):
            return result
        else:
            # Open the file
            if os.path.exists(os.path.join(self.folder, self.name)):            
                # Check given format string is valid
                bytesperpix = 2 #default
                try:
                    bytesperpix = struct.calcsize(self.dataformat)
                except:
58
                    raise ValueError("Supplied data format " + str(self.dataformat) + " is invalid")
Hoek, Steven's avatar
Hoek, Steven committed
59
60
61
62
63
64
                # end try
                
                # Check file size matches with size attributes
                fileinfo = os.stat(os.path.join(self.folder, self.name))
                filesize = fileinfo[stat.ST_SIZE]
                if (filesize == 0) and (mode[0] == 'w'):
65
                    print("Empty BSQ file found. I'm going to overwrite it ...")
Hoek, Steven's avatar
Hoek, Steven committed
66
67
68
69
                else:
                    checknum = (((filesize / float(self.nbands)) / float(self.nrows)) / float(bytesperpix)) / self.ncols
                    if checknum != 1:
                        if fabs(checknum - 1) < 0.00003:
70
                            raise ValueError("File size and size calculated from attributes only match approximately")
Hoek, Steven's avatar
Hoek, Steven committed
71
                        else:
72
                            raise ValueError("File size and supplied attributes do not match at all!")
Hoek, Steven's avatar
Hoek, Steven committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
            
                # Open the file for reading in binary mode
                try:
                    self.datafile = open(os.path.join(self.folder, self.name), mode[0] + "b")
                except:
                    msg = "Failed to open BSQ file " + os.path.join(self.folder, self.name)
                    raise IOError(msg)          
                return True;
            else: return False; 
    
    def next(self, parseLine=True):
        super(BsqRaster, self).next()

        # Read the next row if possible, otherwise generate StopIteration
        try:
            self.currow += 1;
            if (self.currow > self.nrows): raise StopIteration
            
            # Get the size in bytes for the given data format
            line = []
            if not parseLine:
                return line
            
            # Idea is to return the i-th line with values from each band. We're dealing with a file
            # that has its i-th line scattered over blocks of data each representing only 1 band
            itemsize = struct.calcsize(self.dataformat)
            rowsize = self.ncols * itemsize 
            blocksize =  self.nrows * rowsize
            bandstartpos = []
            for j in range(self.nbands):
103
                bandstartpos.append(j * blocksize)   
Hoek, Steven's avatar
Hoek, Steven committed
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
            
            if not HAS_NUMPY:
                # The following is for the case without numpy: each line should be
                # a list of length self.ncols, with arrays of length self.nbands 
                for _ in range(0, self.ncols):
                    line.append(array(self.dataformat, self.nbands*[0]))
            else:
                line = numpy.zeros((self.ncols, self.nbands))
            
            # Read the right line from each block - even though this may be slow
            for bandnum in range(0, self.nbands):
                self.datafile.seek(bandstartpos[bandnum] + self.currow * rowsize)
                buffer = self.datafile.read(rowsize)
                dataitems = struct.unpack_from(self.ncols*self.dataformat, buffer)
                if not HAS_NUMPY:
                    for pixnum in range(self.ncols):
                        line[pixnum][bandnum] = dataitems[pixnum]
                    # end for
                else:
                    line[:, bandnum] = dataitems
            # end for
                
            return line            
                   
        except StopIteration:
            raise StopIteration
130
        except Exception as e:
Hoek, Steven's avatar
Hoek, Steven committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
            raise Exception(e)
    
    def writenext(self, sequence_with_data):
        super(BsqRaster, self).writenext(sequence_with_data)
        # TODO: test!
        # Write the next data if possible, otherwise generate StopIteration
        # Assume that the input sequence is a sequence of length self.ncols
        # with 1-dimensional values
        try:            
            # Perform a number of checks
            if not self._is_sequence(sequence_with_data):
                raise ValueError("Input value is not a sequence!")
            if len(sequence_with_data) != self.ncols:
                raise ValueError("Input sequence has not got the expected length")

            # We're writing 1 line for the current band. Assign the data to the right data structure
            itemsize = struct.calcsize(self.dataformat)
            buffer = bytearray(self.ncols * itemsize)
            line = sequence_with_data[0:self.ncols]
            struct.pack_into(self.ncols*self.dataformat, buffer, 0, *line)
            self.datafile.write(buffer)
            self.datafile.flush()
            
            return True
        except StopIteration:
            raise StopIteration
        except ValueError as e:
158
            print(e)
Hoek, Steven's avatar
Hoek, Steven committed
159
160
161
162
163
164
165
166
167
            raise ValueError
        except Exception as e:
            raise IOError(str(e))
    
    def reset(self):
        self.currow = -1
        self.datafile.seek(0)