worldfile.py 3.39 KB
Newer Older
1
2
3
4
5
6
7
8
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
46
47
48
49
50
51
52
53
54
55
import os.path
from math import fabs
from .raster import Raster
from .const import constants as const
import traceback

__author__ = "Steven B. Hoek"

# Helper class, to be used together with classes derived from Raster
# Reads and writes world files for those format which require it
class WorldFile(object):
    """A helper class ..."""
    datafile = None
    
    def __enter__(self):
        return self
    
    def __exit__(self, exc_type, exc_value, tb):
        try:
            if exc_type is not None:
                traceback.print_exception(exc_type, exc_value, tb)
                return False
            else:
                return True
        finally:
            if self.datafile is not None: self.datafile.close()
    
    def __getpath(self, aRaster):
        name_wo_ext = os.path.splitext(os.path.join(aRaster.folder, aRaster.name))[0] 
        result = os.path.normpath(os.path.join(name_wo_ext + "." + aRaster.getWorldFileExt()))
        return result
    
    def read(self, aRaster):
        try:
            if not isinstance(aRaster, Raster):
                raise ValueError("Not a valid Lmgeo raster!")
            path = self.__getpath(aRaster)
            self.datafile = open(path, 'r')
            line = self.datafile.readline()
            aRaster.dx = float(line.strip())
            line = self.datafile.readline();
            aRaster.roty = float(line.strip())
            line = self.datafile.readline()
            aRaster.rotx = float(line.strip())
            eps = 0.0001;
            if abs(aRaster.rotx)>eps or abs(aRaster.roty)>eps:
                raise NotImplementedError("Cannot handle rotated mapsheets yet!")
            line = self.datafile.readline()
            aRaster.dy = fabs(float(line.strip()))
            sign = lambda x: (1, -1)[x<0]
            if sign(float(line.strip())) == 1.0: aRaster.ycoords_sort = const.ASC;
            line = self.datafile.readline()
            aRaster.xul = float(line.strip()) - 0.5 * aRaster.dx
            line = self.datafile.readline()
            aRaster.yul = float(line.strip()) + 0.5 * aRaster.dy
56
57
            aRaster.xll = aRaster.xul
            aRaster.yll = aRaster.yul - (aRaster.nrows * aRaster.dy)
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
        except Exception as e:
            print(e)
            raise e
    
    def write(self, aRaster):
        try:
            if not isinstance(aRaster, Raster):
                raise ValueError("Not a valid Lmgeo raster!")
            path = self.__getpath(aRaster)

            # Open the file if it exists, otherwise create it
            self.datafile = open(path, 'w')
            
            # Now write all the attributes
            self.datafile.write(str(aRaster.dx) + "\n")
            eps = const.epsilon
            if abs(aRaster.rotx)>eps or abs(aRaster.roty)>eps:
                raise NotImplementedError("Cannot handle rotated mapsheets yet!")
            self.datafile.write(str(aRaster.rotx) + "\n")
            self.datafile.write(str(aRaster.roty) + "\n")
            if aRaster.ycoords_sort == const.ASC:
                self.datafile.write(str(aRaster.dy) + "\n")
            else:
                self.datafile.write(str(-1 * aRaster.dy) + "\n")
            self.datafile.write(str(aRaster.xll + 0.5 * aRaster.dx) + "\n")
            self.datafile.write(str(aRaster.yll + abs(aRaster.nrows) * aRaster.dy - 0.5 * aRaster.dx) + "\n")
            
        except Exception as e:
            print(e)
            raise e