grid.py 48.3 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
56
57
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""
Grid data types
"""

from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import int


try:
	## Python 2
	basestring
	PY2 = True
except:
	## Python 3
	PY2 = False
	basestring = str


import numpy as np
import osr, gdal

from .base import BasemapData, WGS84
from .point import MultiPointData
from .line import LineData, MultiLineData
from .polygon import PolygonData, MultiPolygonData


__all__ = ['GridData', 'MeshGridData', 'UnstructuredGridData',
			'GdalRasterData', 'WCSData', 'MeshGridVectorData']


class GridData(BasemapData):
	def __init__(self, lons, lats, values, unit=""):
		self.lons = np.asarray(lons)
		self.lats = np.asarray(lats)
		self.values = np.asarray(values)
		self.unit = unit


class UnstructuredGridData(GridData):
	"""
	Unstructured 2-dimensional data (e.g., point clouds)

	Provides method(s) to interpolate into meshed grid

	:param lons:
		1-D array of longitudes
	:param lats:
		1-D array of latitudes
	:param values:
		1-D array of values
	:param unit:
		str, measurement unit of values
		(default: "")
	"""
	def __init__(self, lons, lats, values, unit=""):
		if lons.ndim != 1 or lats.ndim != 1 or values.ndim != 1:
			raise ValueError("lons, lats, and values should be 1-dimensional")
		super(UnstructuredGridData, self).__init__(lons, lats, values, unit)

	def __len__(self):
		return len(self.lons)

	def lonmin(self):
		"""
		Return minimum longitude
		"""
		return self.lons.min()

	def lonmax(self):
		"""
		Return maximum longitude
		"""
		return self.lons.max()

	def latmin(self):
		"""
		Return minimum latitude
		"""
		return self.lats.min()

	def latmax(self):
		"""
		Return maximum latitude
		"""
		return self.lats.max()

	def get_extent(self):
		"""
		:return:
			(lonmin, lonmax, latmin, latmax) tuple
		"""
		return (self.lonmin(), self.lonmax(), self.latmin(), self.latmax())

	def confine_to_extent(self, extent):
		"""
		Confine grid to given rectangular extent

		:param extent:
			(lonmin, lonmax, latmin, latmax) tuple

		:return:
			instance of :class:`UnstructuredGridData`
		"""
		lonmin, lonmax, latmin, latmax = extent
		idxs = np.where((self.lons >= lonmin) & (self.lons <= lonmax)
						& (self.lats >= latmin) & (self.lats <= latmax))
		lons = self.lons[idxs]
		lats = self.lats[idxs]
		values = self.values[idxs]
		return UnstructuredGridData(lons, lats, values, unit=self.unit)

	def to_multi_point_data(self):
		"""
		Convert to multi-point data

		:return:
			instance of :class:`MultiPointData`
		"""
		lons = self.lons.flatten()
		lats = self.lats.flatten()
		values = self.values.flatten()
		return MultiPointData(lons, lats, list(values))

125
126
	def to_mesh_grid_data(self, num_cells, cell_size=None,
						extent=(None, None, None, None),
127
						interpolation_method='cubic', max_dist=5.):
128
129
130
131
		"""
		Convert to meshed grid data

		:param num_cells:
132
133
134
135
136
137
			int or tuple of ints, number of grid cells in lon and lat
			direction
		:param cell_size:
			float or tuple of floats, cell width in lon and lat direction
			If specified, takes precedence over :param:`num_cells`
			(default: None)
138
139
140
141
		:param extent:
			(lonmin, lonmax, latmin, latmax) tuple of floats
			(default: (None, None, None, None)
		:param interpolation_method:
142
			str, interpolation method supported by griddata, either
143
144
			"linear", "nearestN" (with N number of neighbors to consider),
			"cubic" or "idwP" (with P power to raise distances to)
145
			(default: "cubic")
146
147
148
149
		:param max_dist:
			float, maximum interpolation distance (in km)
			Only relevant for "nearestN" and "idwP" methods
			(default: 5.)
150
151
152
153

		:return:
			instance of :class:`MeshGridData`
		"""
154
155
		assert num_cells or cell_size

156
157
158
159
160
161
162
163
164
		lonmin, lonmax, latmin, latmax = extent
		if lonmin is None:
			lonmin = self.lonmin()
		if lonmax is None:
			lonmax = self.lonmax()
		if latmin is None:
			latmin = self.latmin()
		if latmax is None:
			latmax = self.latmax()
165
166
167
168
169
170
171
172
173
174
175

		if cell_size:
			if isinstance(cell_size, int):
				cell_size = (cell_size, cell_size)
			num_lons = int(round((lonmax - lonmin) / cell_size[0])) + 1
			num_lats = int(round((latmax - latmin) / cell_size[1])) + 1
		else:
			if isinstance(num_cells, int):
				num_cells = (num_cells, num_cells)
			num_lons, num_lats = num_cells

176
177
178
		lons = np.linspace(lonmin, lonmax, num_lons)
		lats = np.linspace(latmin, latmax, num_lats)
		mesh_lons, mesh_lats = np.meshgrid(lons, lats)
179

180
181
		max_dist *= 1000  ## km --> m

182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
		if (interpolation_method in ('linear', 'cubic') or
			interpolation_method[:7] == 'nearest'):
			from scipy.interpolate import griddata
			from mapping.geotools.coordtrans import lonlat_to_meter
			## Convert geographic to cartesian coordinates
			ref_lat = np.mean([latmin, latmax])
			x, y = lonlat_to_meter(self.lons, self.lats, ref_lat=ref_lat)
			mesh_x, mesh_y = lonlat_to_meter(mesh_lons, mesh_lats, ref_lat=ref_lat)

			if interpolation_method[:7] == 'nearest':
				from scipy.spatial import cKDTree
				tree = cKDTree(zip(x, y))
				num_neighbors = 1
				if len(interpolation_method) > 7:
					num_neighbors = int(interpolation_method[7:])
				d, idxs = tree.query(zip(mesh_x.flatten(), mesh_y.flatten()),
						k=num_neighbors, eps=0, distance_upper_bound=max_dist)
				if num_neighbors == 1:
					## When k == 1, the last dimension of the output is squeezed
					idxs.shape += (1,)
				if max_dist == np.inf:
					mesh_values = self.values[idxs]
				else:
					mesh_values = np.ones_like(idxs) * np.nan
					for i in range(idxs.shape[0]):
						i_idxs = idxs[i]
						## Missing neighbors are indicated with index = len(tree)
						i_idxs = i_idxs[i_idxs < len(self.lons)]
						mesh_values[i,:len(i_idxs)] = self.values[idxs[i,:len(i_idxs)]]
				mesh_values = np.nanmean(mesh_values, axis=-1)
				mesh_values.shape = mesh_lons.shape
			else:
				mesh_values = griddata((x, y), self.values,
							(mesh_x, mesh_y), method=interpolation_method)

		elif interpolation_method[:3] == 'idw':
			from mapping.geotools.geodetic import spherical_distance
			pow = 1
			if len(interpolation_method) > 3:
				pow = int(interpolation_method[3:])
			mesh_values = np.ones_like(mesh_lons) * np.nan
			for i in range(num_lons):
				lon = lons[i]
				for j in range(num_lats):
					lat = lats[j]
					d = spherical_distance(lon, lat, self.lons, self.lats)
					idxs = (d <= max_dist)
					weights = 1. / d[idxs]
					if pow != 1:
						weights **= pow
					if np.sum(weights):
						mesh_values[j, i] = np.average(self.values[idxs], weights=weights)

235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
		return MeshGridData(mesh_lons, mesh_lats, mesh_values)


class MeshGridData(GridData):
	"""
	Meshed grid data, representing a grid with regular longitudinal and
	latitudinal spacing

	:param lons:
		2-D array
	:param lats:
		2-D array
	:param values:
		2-D array
	:param unit:
		str
	"""
	# TODO: add srs parameter and define similar properties as GdalRasterData
	# e.g.: x0, x1, dx instead of lon0, lon1, dlon
	# TODO: correctly implement edge_lons, edge_lats!
	# TODO: add nodata_value (np.nan only works for float arrays!)
	def __init__(self, lons, lats, values, unit=""):
		if lons.ndim != 2 or lats.ndim != 2 or values.ndim != 2:
			raise ValueError("lons, lats, and values should be 2-dimensional")
		## Not sure the following is really necessary
		dlon = np.diff(lons)
		dlat = np.diff(lats)
		if not np.allclose(dlon, dlon[0]) or not np.allclose(dlat, dlat[0]):
			raise ValueError("Grid spacing must be uniform")
		super(MeshGridData, self).__init__(lons, lats, values, unit)

		# TODO: need to make functions for these using source srs
		# (in which grid is rectangular)
		self.center_lons = lons
		self.center_lats = lats
		self._edge_lons, self._edge_lats = None, None

		## For compatibility with GdalRasterData
		self.srs = WGS84

	@property
	def edge_lons(self):
		if self._edge_lons is None:
			lons = np.linspace(self.lon0 - self.dlon/2., self.lon1 + self.dlon/2., self.ncols + 1)
			lats = np.linspace(self.lat0 - self.dlat/2., self.lat1 + self.dlat/2., self.nrows + 1)
			self._edge_lons, self._edge_lats = np.meshgrid(lons, lats)
		return self._edge_lons

	@property
	def edge_lats(self):
		if self._edge_lats is None:
			self._edge_lons
		return self._edge_lats

	@property
	def dlon(self):
		return self.center_lons[0,1] - self.center_lons[0,0]

	@property
	def dlat(self):
		return self.center_lats[1,0] - self.center_lats[0,0]

	@property
	def lon0(self):
		return self.center_lons[0,0]

	@property
	def lon1(self):
		return self.center_lons[0,-1]

	@property
	def lat0(self):
		return self.center_lats[0,0]

	@property
	def lat1(self):
		return self.center_lats[-1,0]

	@property
	def ncols(self):
		return self.center_lons.shape[1]

	@property
	def nrows(self):
		return self.center_lons.shape[0]

	def get_mesh_coordinates(self, cell_registration="corner"):
		"""
		To make MeshGridData compatible with GdalRasterData
		"""
		if cell_registration == "corner":
			return (self.edge_lons, self.edge_lats)
		else:
			return (self.lons, self.lats)

	def to_multi_point_data(self, apply_mask=True):
		"""
		Convert to multi-point data

		:param apply_mask:
			bool, whether or not to leave out masked data
			(default: True)

		:return:
			instance of :class:`MultiPointData`
		"""
		if apply_mask and self.is_masked():
			mask = self.values.mask
			values = self.values[~mask].data
			lons = self.lons[~mask]
			lats = self.lats[~mask]
		else:
			values = self.values.flatten()
			lons = self.lons.flatten()
			lats = self.lats.flatten()
		return MultiPointData(lons, lats, list(values))

	def mask_oceans(self, resolution, mask_lakes=False, grid_spacing=1.25):
		from mpl_toolkits.basemap import maskoceans
		masked_values = maskoceans(self.lons, self.lats, self.values, inlands=mask_lakes, resolution=resolution, grid=grid_spacing)
		return MeshGridData(self.lons, self.lats, masked_values)

	def is_masked(self):
		"""
		:return:
			bool, whether grid is masked or not
		"""
		return hasattr(self.values, 'mask')

	def apply_mask(self, mask):
		"""
		Apply mask to grid

		:param mask:
			numpy bool array with same shape as grid
		"""
		assert mask.shape == self.values.shape
		self.values = np.ma.array(self.values, mask=mask)

	def mask_polygons(self, polygon_data, inside=True):
		"""
		Mask grid according to given polygon(s)

		:param polygon_data:
			instance of :class:`PolygonData` or :class:`MultiPolygonData`
		:param inside:
			bool, whether grid should be masked inside or outside of polygon
			(default: True)

		:return:
			None, mask will be applied in-place
		"""
		ogr_polygon_data = polygon_data.to_ogr_geom()
		if inside:
			mask = np.zeros_like(self.values, dtype=np.bool)
		else:
			mask = np.ones_like(self.values, dtype=np.bool)
		mpt = self.to_multi_point_data()
		ogr_mpt = mpt.to_ogr_geom()
		ogr_intersection = ogr_mpt.Intersection(ogr_polygon_data)
		if ogr_intersection:
			intersection = MultiPointData.from_ogr(ogr_intersection)
			for pt in intersection:
				row = int(round((pt.lat - self.lat0) / self.dlat))
				col = int(round((pt.lon - self.lon0) / self.dlon))
				if inside:
					mask[row, col] = True
				else:
					mask[row, col] = False

		self.apply_mask(mask)

	def set_mask_from_distance_to_data_points(self, data_points, max_dist):
		"""
		Mask grid depending on minimum distance to data points

		:param data_points:
			instance of :class:`MultiPointData` or :class:`UnstructuredGrid`
		:param max_dist:
			float, maximum distance to consider as valid grid cell
			Grid cells with larger minimum distance to data points
			will be masked
			If :param:`data_points` is instance of :class:`MultiPointData`,
			distance is expressed in meters
			If :param:`data_points` is instance of :class:`UnstructuredGrid`,
			distance is expressed in fractional degrees latitude

		:return:
			None, mask will be applied in-place
		"""
		from mapping.geotools.geodetic import spherical_distance
		mask = np.zeros_like(self.values, dtype=np.bool)
		if isinstance(data_points, MultiPointData):
			for r in range(self.nrows):
				for c in range(self.ncols):
					lon, lat = self.lons[r,c], self.lats[r,c]
					distances = spherical_distance(lon, lat, data_points.lons, data_points.lats)
					if np.min(distances) >= max_dist:
						mask[r,c] = True
		elif isinstance(data_points, UnstructuredGridData):
			## max_dist is distance in degrees
			max_lon_dist = max_dist / np.cos(np.radians(max_dist))
			for r in range(self.nrows):
				for c in range(self.ncols):
					lon, lat = self.lons[r,c], self.lats[r,c]
					extent = (lon - max_lon_dist, lon + max_lon_dist,
							lat - max_dist, lat + max_dist)
					close_data_points = data_points.confine_to_extent(extent)
					if len(close_data_points) == 0:
						mask[r,c] = True

		self.apply_mask(mask)

	def reproject(self, target_srs):
		pass

	def interpolate(self, xout, yout, srs=None, checkbounds=False, masked=True,
					order=1):
		"""
		Interpolate grid.
		Note: masked values will be replaced with NaN values

		:param xout:
			array, X coordinates in native SRS or :param:`srs`
		:param yout:
			array, Y coordinates in native SRS or :param:`srs`
		:param srs:
			osr SpatialReference object, SRS of output coordinates
			(default: None)
		:param checkbounds:
			bool, whether or not values of xout and yout are checked
			to see that they are within the range of the grid. If True,
			points falling outside the grid are masked if :param:`masked`
			is True, else they are clipped to the boundary of the grid
			(default: False)
		:param masked:
			bool, whether or not points outside the range of the grid
			are masked
			(default: True)
		:param order:
			int, type of interpolation, 0=nearest neighbor, 1=bilinear,
			3=cubic spline
			(default: 1)

		:return:
			array, interpolated grid values
		"""
		## Check scipy.interpolate.Rbf for additional interpolation methods
		from mpl_toolkits.basemap import interp
		from mapping.geotools.coordtrans import transform_mesh_coordinates

		## xin, yin must be linearly increasing
		values = self.values
		if self.lon0 < self.lon1:
			xin = np.linspace(self.lon0, self.lon1, self.ncols)
		else:
			xin = np.linspace(self.lon1, self.lon0, self.ncols)
			values = values[:,::-1]
		if self.lat0 < self.lat1:
			yin = np.linspace(self.lat0, self.lat1, self.nrows)
		else:
			yin = np.linspace(self.lat1, self.lat0, self.nrows)
			values = values[::-1,:]

		## Transform output coordinates to lon/lat coordinates if necessary
		if srs and srs != self.srs:
			xout, yout = transform_mesh_coordinates(self.srs, WGS84, xout, yout)

		out_data = interp(values, xin, yin, xout, yout, checkbounds=checkbounds,
							masked=masked, order=order)
		if hasattr(out_data, 'mask'):
			out_data = out_data.filled(np.nan)

		return out_data

	def calc_hillshade(self, azimuth, elevation_angle, scale=1.):
		"""
		Compute hillshading

		:param azimuth:
			float, azimuth of light source in degrees
		:param elevation_angle:
			float, elevation angle of light source in degrees
		:param scale:
			float, multiplication factor to apply (default: 1.)
		"""

		"""
		## Source: http://rnovitsky.blogspot.com.es/2010/04/using-hillshade-image-as-intensity.html
		az = np.radians(azimuth)
		elev = np.radians(elevation_angle)
		data = self.values[::-1]

		## Gradient in x and y directions
		dx, dy = np.gradient(data * float(scale))
		slope = 0.5 * np.pi - np.arctan(np.hypot(dx, dy))
		aspect = np.arctan2(dx, dy)
		shade = np.sin(elev) * np.sin(slope) + np.cos(elev) * np.cos(slope) * np.cos(-az - aspect - 0.5*np.pi)
		## Normalize
		shade = (shade - np.nanmin(shade))/(np.nanmax(shade) - np.nanmin(shade))
		shade = shade[::-1]
		"""

		from matplotlib.colors import LightSource
		ls = LightSource(azimuth, elevation_angle)
		# TODO: look into vertical exaggeration with true dx and dy

		if hasattr(self, 'dx'):
			shade = ls.hillshade(self.values, dx=np.sign(self.dx), dy=-np.sign(self.dy))
		else:
			shade = ls.hillshade(self.values, dx=np.sign(self.dlon), dy=-np.sign(self.dlat))

		## Eliminate nan values, they result in black when blended
		# TODO: maybe these values should be masked or made transparent
		shade[np.isnan(shade)] = 0.5

		return shade

	def extract_contour_lines(self, levels):
		"""
		Extract contour lines from grid

		:param levels:
			list or array, contour line values

		:return:
			list with instances of :class:`MultiLineData`
		"""
		import matplotlib._cntr as cntr

		contour_engine = cntr.Cntr(self.lons, self.lats, self.values)
		contour_lines = []
		for level in levels:
			nlist = contour_engine.trace(level, level, 0)
			nseg = len(nlist) // 2
			segs = nlist[:nseg]
			contour_line = MultiLineData([], [])
			for seg in segs:
				cl = LineData(seg[:,0], seg[:,1], value=level)
				contour_line.append(cl)
			contour_lines.append(contour_line)
		return contour_lines

	def extract_contour_intervals(self, levels):
		"""
		Extract contour intervals from grid

		:param levels:
			list or array, contour line values

		:return:
			list with instances of :class:`MultiPolygonData`
		"""
		import numpy.ma as ma
		import matplotlib._contour as _contour

		values = ma.asarray(self.values)
		contour_engine = _contour.QuadContourGenerator(self.lons, self.lats,
												values.filled(), None, False, 0)
		contour_polygons = []
		for lower_level, upper_level in zip(levels[:-1], levels[1:]):
			segs, path_codes = contour_engine.create_filled_contour(lower_level, upper_level)
			contour_mpg = MultiPolygonData([], [])
			for i in range(len(segs)):
				seg = segs[i]
				path_code = path_codes[i]
				seg = np.split(seg, np.where(path_code == 1)[0][1:])
				for s, coords in enumerate(seg):
					if s == 0:
						lons, lats = coords[:,0], coords[:,1]
						interior_lons, interior_lats = [], []
					else:
						if coords.shape[0] > 2:
							interior_lons.append(coords[:,0])
							interior_lats.append(coords[:,1])
610
611
612
				contour_pg = PolygonData(lons, lats, interior_lons=interior_lons,
										interior_lats=interior_lats,
										z=lower_level)
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
				contour_mpg.append(contour_pg)
			contour_polygons.append(contour_mpg)
		return contour_polygons

	@classmethod
	def from_XYZ(cls, xyz_filespec, sep=',', num_header_lines=1, comment_char='#',
				dtype=np.float64):
		"""
		Create meshed grid from potentially unsorted XYZ file

		:param xyz_filespec:
			str, full path to XYZ file
		:param sep:
			char, character separating X, Y, Z values
			(default: ',')
		:param num_header_lines:
			int, number of header lines to skip
			(default: 1)
		:param comment_char:
			char, character indicating comment line
			(default: '#')

		:return:
			instance of :class:`MeshGridData`
		"""
		lons, lats, values = [], [], []
		for l, line in enumerate(open(xyz_filespec)):
			if l >= num_header_lines and line[0] != comment_char:
				lon, lat, val = line.split(';')
				lons.append(float(lon))
				lats.append(float(lat))
				values.append(dtype(val))

		grd_lons = sorted(np.unique(lons))
		grd_lats = sorted(np.unique(lats))
		mesh_lons, mesh_lats = np.meshgrid(grd_lons, grd_lats)
		mesh_values = np.zeros_like(mesh_lons)
		mesh_values[:] = np.nan

		lon0, lat0 = grd_lons[0], grd_lats[0]
		dlon = float(grd_lons[1] - grd_lons[0])
		dlat = float(grd_lats[1] - grd_lats[0])
		for i in range(len(values)):
			lon_idx = round(int((lons[i] - lon0) / dlon))
			lat_idx = round(int((lats[i] - lat0) / dlat))
			#[lon_idx] = np.argwhere(grd_lons == lons[i])
			#[lat_idx] = np.argwhere(grd_lats == lats[i])
			mesh_values[lat_idx, lon_idx] = values[i]

		return cls(mesh_lons, mesh_lats, mesh_values)

	def get_gdal_geotransform(self):
		"""
		Construct GDAL geotransform
		See http://lists.osgeo.org/pipermail/gdal-dev/2011-July/029449.html

		:return:
			6-element array
		"""
		## Note: for rotated grids
		#geotransform[0] = corner lon
		#geotransform[1] = cos(alpha)*(scaling)
		#geotransform[2] = -sin(alpha)*(scaling)
		#geotransform[3] = corner lat
		#geotransform[4] = sin(alpha)*(scaling)
		#geotransform[5] = cos(alpha)*(scaling)
		## where scaling maps pixel space to lat/lon space
		## and alpha denotes rotation to the East in radians

		geotransform = np.zeros(6, dtype='d')
		geotransform[0] = self.lon0 - self.dlon * 0.5	# top-left X
		geotransform[1] = self.dlon					# w-e pixel resolution
		geotransform[2] = 0							# rotation, 0 for north-up
		geotransform[3] = self.lat0 - self.dlat * 0.5	# top-left Y
		geotransform[4] = 0							# rotation, 0 for north-up
		geotransform[5] = self.dlat					# n-s pixel resolution
		return geotransform

	def export_gdal(self, driver_name, out_filespec, proj_info="EPSG:4326",
					nodata_value=np.nan):
		"""
		:param driver_name:
			str, name of driver supported by GDAL
		:param out_filespec:
			str, full path to output file
		:param proj_info:
			int (EPSG code), str (EPSG string or WKT) or osr SpatialReference
			object
			(default: "EPSG:4326" (= WGS84)
		"""
		from mapping.geotools.coordtrans import get_epsg_srs

		driver = gdal.GetDriverByName(driver_name)
		num_bands = 1
		dtype = self.values.dtype.type
		gdal_data_type = {
			np.byte: gdal.GDT_Byte,
			np.int8: gdal.GDT_Byte,
			np.int16: gdal.GDT_Int16,
			np.int32: gdal.GDT_Int32,
			np.float16: gdal.GDT_Float32,
			np.float32: gdal.GDT_Float32,
			np.float64: gdal.GDT_Float64,
			np.uint16: gdal.GDT_UInt16,
			np.uint32: gdal.GDT_UInt16}[dtype]
		ds = driver.Create(out_filespec, self.ncols, self.nrows, num_bands, gdal_data_type)
		ds.SetGeoTransform(self.get_gdal_geotransform())

		if isinstance(proj_info, int):
			wkt = get_epsg_srs(proj_info).ExportToWkt()
		elif isinstance(proj_info, basestring):
			if proj_info[:4].upper() == "EPSG":
				wkt = get_epsg_srs(proj_info).ExportToWkt()
			else:
				wkt = proj_info
		elif isinstance(proj_info, osr.SpatialReference):
			wkt = proj_info.ExportToWkt()
		ds.SetProjection(wkt)

		band = ds.GetRasterBand(1)
		band.WriteArray(self.values)
		band.SetNoDataValue(nodata_value)
		band.ComputeStatistics(False)
		band.SetUnitType(self.unit)
		band.FlushCache()

		return GdalRasterData(out_filespec)


class GdalRasterData(MeshGridData):
	"""
	GDAL raster data (including GeoTiff)
	Unrotated!

	:param filespec:
		str, full path to GDAL raster dataset
	:param band_nr:
		int,  raster band number (one-based). If 0 or None, data
		will be read as truecolor (RGB) image
		(default: 1)
	:param down_sampling:
		float, factor for downsampling, i.e. to divide number of columns and
		rows with
		(default: 1., no downsampling)
	:param nodata_value:
		float, value indicating absence of data
		(default: None)
	:param unit:
		str, measurement unit of gridded values
		(default: "")
	:param bbox:
		list or tuple of floats: (llx, lly, urx, ury) in native coordinates
		(default: [], will use bounding box of dataset)
	:param region:
		list or tuple of floats: (lonmin, lonmax, latmin, latmax)
		that will be used to determine bbox
		(default: [])
	:param value_conversion:
		function to apply to stored grid values.
		Only applies if :param:`band_nr` is not null
		(default: None)
	"""
	def __init__(self, filespec, band_nr=1, down_sampling=1., nodata_value=None,
				unit="", bbox=[], region=[], value_conversion=None):
		self.filespec = filespec
		self.band_nr = band_nr
		self.read_grid_info()
		self.set_down_sampling(max(1, down_sampling))
		self.nodata_value = nodata_value
		if unit is None:
			self.unit = self.read_band_unit_type(self.band_nr)
		else:
			self.unit = unit

		if region:
			bbox = self.get_bbox_from_region(region)
		if not bbox:
			bbox = self.get_native_bbox()
		self.apply_bbox(bbox)

		self.value_conversion = value_conversion or (lambda x:x)

		## Store these when first computed to avoid computing more than once
		self._edge_lons = None
		self._edge_lats = None
		self._center_lons = None
		self._center_lats = None

	# TODO: raster subdatasets
	#subdatasets = dataset.GetSubDatasets()
	#mysubdataset_name = subdatasets[1][0]
	#mydata = gdal.Open(mysubdataset_name, gdal.GA_ReadOnly).ReadAsRaster()

	def get_subdataset_names(self):
		import gdal

		ds = gdal.Open(self.filespec, gdal.GA_ReadOnly)
		sds_names = [sds[0] for sds in ds.GetSubDatasets()]
		ds = None
		return sds_names

	def get_subdatasets(self):
		return [self.get_subdataset(sds_name) for sds_name in self.get_subdataset_names()]

	def get_subdataset(self, subdataset_name):
		return GdalRasterData(subdataset_name)

	## Following methods are based on:
	## http://stackoverflow.com/questions/20488765/plot-gdal-raster-using-matplotlib-basemap

	def read_grid_info(self):
		"""
		Read raster parameters.

		The following properties are set:
		- :prop:`srs`: instance of class osr.SpatialReference
		- :prop:`num_bands`: int, number of raster bands
		- :prop:`_ncols`, :prop:`_nrows`: int, number of raster columns
			and rows in native grid extent
		- :prop:`_dx`, :prop:`_dy`: int, cell size in X and Y direction
			in the native spatial reference system
		- :prop:`_x0`, :prop:`_x1`: float, extent in X direction in
			the native spatial reference system (center of grid cells)
		- :prop:`_y0`, :prop:`_y1`: float, extent in Y direction in
			the native spatial reference system (center of grid cells)
		"""
		ds = gdal.Open(self.filespec, gdal.GA_ReadOnly)
		self.srs = osr.SpatialReference()
		projection = ds.GetProjection()
		if projection:
			self.srs.ImportFromWkt(projection)
		else:
			self.srs = WGS84
			print("Warning: no spatial reference system defined, assuming WGS84!")
		self.num_bands = ds.RasterCount

		gt = ds.GetGeoTransform()
		# TODO: support rotated grids
		if gt[2] or gt[4]:
			print("Warning: rotation of GDAL rasters not supported yet!")
		self._ncols, self._nrows = ds.RasterXSize, ds.RasterYSize
		self._dx, self._dy = gt[1], gt[5]
		## (x0, y0) and (x1, y1) now correspond to cell centers
		self._x0 = gt[0] + self._dx * 0.5
		self._x1 = gt[0] + (self._dx * self._ncols) - self._dx * 0.5
		#if self.dx < 0:
			#xmin, xmax = xmax, xmin
			#self.dx = -self.dx
		self._y0 = gt[3] + self._dy * 0.5
		self._y1 = gt[3] + (self._dy * self._nrows) - self._dy * 0.5
		#if self.dy < 0:
		#ymin, ymax = ymax, ymin
			#self.dy = -self.dy

		ds = None

	def set_down_sampling(self, down_sampling):
		"""
		The following properties are set:
		- :prop:`down_sampling`: float, downsampling factor
		- :prop:`dx`, :prop:`dy`: int, cell size in X and Y direction
			in the native spatial reference system
		"""
		self.down_sampling = float(down_sampling)
		#self.x0 = self._x0 / down_sampling * down_sampling
		#self.x1 = self._x1 / down_sampling * down_sampling
		#self.y0 = self._y0 / down_sampling * down_sampling
		#self.y1 = self._y1 / down_sampling * down_sampling
		self.dx = self._dx * down_sampling
		self.dy = self._dy * down_sampling
		#self.ncols = int(abs((self.x0 - self.x1) / self.dx)) + 1
		#self.nrows = int(abs((self.y0 - self.y1) / self.dy)) + 1

	def get_native_bbox(self):
		return (self._x0, self._y0, self._x1, self._y1)

	def get_bbox(self):
		return (self.x0, self.y0, self.x1, self.y1)

	def adjust_bbox(self, bbox):
		"""
		Make sure bbox has same order as native bbox
		"""
		x0, y0, x1, y1 = bbox
		if np.sign(x0 - x1) != np.sign(self._x0 - self._x1):
			x0, x1 = x1, x0
		if np.sign(y0 - y1) != np.sign(self._y0 - self._y1):
			y0, y1 = y1, y0
		return (x0, y0, x1, y1)

	def align_bbox(self, bbox):
		"""
		Note: bbox must already be adjusted!
		Align x0 to native dx, (x1-x0) to dx
		"""
		x0, y0, x1, y1 = bbox
		if self._x1 > self._x0:
			x0 = max(self._x0, np.floor(x0 / self._dx) * self._dx)
			nx = min(np.ceil((x1 - x0) / self.dx), np.floor((self._x1 - x0) / self.dx))
			x1 = x0 + nx * self.dx
		else:
			x0 = min(self._x0, np.ceil(x0 / self._dx) * self._dx)
			nx = max(np.floor((x0 - x1) / self.dx), np.ceil((x0 - self._x1) / self.dx))
			x1 = x0 - nx * self.dx

		if self._y1 > self._y0:
			y0 = max(self._y0, np.floor(y0 / self._dy) * self._dy)
			ny = min(np.ceil((y1 - y0) / self.dy), np.floor((self._y1 - y0) / self.dy))
			y1 = y0 + ny * self.dy
		else:
			y0 = min(self._y0, np.ceil(y0 / self._dy) * self._dy)
			ny = max(np.floor((y0 - y1) / self.dy), np.ceil((y0 - self._y1) / self.dy))
			y1 = y0 - ny * self.dy

		return (x0, y0, x1, y1)

	def apply_bbox(self, bbox):
		"""
		Apply bounding box

		The following properties are set:
		- :prop:`ncols`, :prop:`nrows`: int, number of raster columns
			and rows in native grid extent
		- :prop:`x0`, :prop:`x1`: float, extent in X direction in
			the native spatial reference system (center of grid cells)
		- :prop:`y0`, :prop:`y1`: float, extent in Y direction in
			the native spatial reference system (center of grid cells)
		"""
		bbox = self.align_bbox(self.adjust_bbox(bbox))
		self.x0, self.y0, self.x1, self.y1 = bbox
		#self.ncols = int(abs((self.x0 - self.x1) / self.dx)) + 1
		#self.nrows = int(abs((self.y0 - self.y1) / self.dy)) + 1

	@property
	def ncols(self):
		return int(round(abs((self.x0 - self.x1) / self.dx))) + 1

	@property
	def nrows(self):
		return int(round(abs((self.y0 - self.y1) / self.dy))) + 1

	def get_bbox_from_region(self, region, margin_fraction=1./20):
		from mapping.geotools.coordtrans import transform_coordinates

		srs = self.srs

		lonmin, lonmax, latmin, latmax = region
		lon_margin = (lonmax - lonmin) * margin_fraction
		lat_margin = (latmax - latmin) * margin_fraction
		coords_in = np.array([(lonmin-lon_margin, latmin-lat_margin),
					(lonmax+lon_margin, latmax+lat_margin)])
		if srs.ExportToWkt() == WGS84.ExportToWkt():
			coords = coords_in
		else:
			coords = transform_coordinates(WGS84, srs, coords_in)

		bbox = (list(np.floor(coords[0] / self._dx) * self._dx) +
				list(np.ceil(coords[1] / self._dy) * self._dy))
		return bbox

	def _get_x_index(self, x):
		"""
		Compute index of x coordinate in native X range

		:param x:
			float, X coordinate

		:return:
			int, index
		"""
		return int(round((x - self._x0) / self._dx))

	def _get_y_index(self, y):
		"""
		Compute index of y coordinate in native Y range

		:param y:
			float, Y coordinate

		:return:
			int, index
		"""
		return int(round((y - self._y0) / self._dy))

	@property
	def xmin(self):
		return min(self.x0, self.x1)

For faster browsing, not all history is shown. View entire blame