Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#411 property decorator with its setter #500

Open
wants to merge 6 commits into
base: issue-464-logger-instead-of-print
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions nansat/domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
from __future__ import division, absolute_import

import logging
import re
import warnings
from xml.etree.ElementTree import ElementTree
Expand All @@ -28,6 +29,9 @@
from nansat.exceptions import NansatProjectionError
from nansat.warnings import NansatFutureWarning

LOGGER = logging.getLogger("nansat."+__name__)
LOGGER.addHandler(logging.NullHandler())

class Domain(object):
"""Container for geographical reference of a raster

Expand Down Expand Up @@ -225,7 +229,7 @@ def __repr__(self):
"""
corners_temp = '\t (%6.2f, %6.2f) (%6.2f, %6.2f)\n'
wkt, src = self.vrt.get_projection()
out_str = 'Domain:[%d x %d]\n' % self.shape()[::-1]
out_str = 'Domain:[%d x %d]\n' % self.shape[::-1]
out_str += self.OUTPUT_SEPARATOR
corners = self.get_corners()
out_str += 'Projection(%s):\n' % src
Expand Down Expand Up @@ -549,7 +553,7 @@ def get_border(self, n_points=10, fix_lon=True, **kwargs):
vectors with lon/lat values for each point at the border

"""
x_size, y_size = self.shape()[::-1]
x_size, y_size = self.shape[::-1]
x_rc_vec = Domain._get_row_col_vector(x_size, n_points)
y_rc_vec = Domain._get_row_col_vector(y_size, n_points)
col_vec, row_vec = Domain._compound_row_col_vectors(x_size, y_size, x_rc_vec, y_rc_vec)
Expand Down Expand Up @@ -854,6 +858,7 @@ def azimuth_y(self, reductionFactor=1):
a = np.vstack((a, a[-1, :]))
return a

@property
def shape(self):
"""Return Numpy-like shape of Domain object (ySize, xSize)

Expand All @@ -865,6 +870,14 @@ def shape(self):
"""
return self.vrt.dataset.RasterYSize, self.vrt.dataset.RasterXSize

@shape.setter
def shape(self, dims):
y, x = dims.split(',')
self.vrt.dataset.RasterXSize = x
self.vrt.dataset.RasterYSize = y
LOGGER.debug(f"new self.vrt.dataset.RasterYSize:{self.vrt.dataset.RasterYSize}, "
f"new self.vrt.dataset.RasterXSize:{self.vrt.dataset.RasterXSize}")

def reproject_gcps(self, srs_string=''):
"""Reproject all GCPs to a new spatial reference system

Expand Down
2 changes: 1 addition & 1 deletion nansat/mappers/opendap.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def create_vrt(self, filename, gdalDataset, gdalMetadata, date, ds, bands, cache
if bands:
# TODO: select variable names based on standard names instead of band names
# - this means the variable must be looped, like in mapper_netcdf_cf.py
var_names = bands
var_names = bands

# create VRT with correct lon/lat (geotransform)
raster_x, raster_y = self.get_shape()
Expand Down
18 changes: 9 additions & 9 deletions nansat/nansat.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ def has_band(self, band):

def _get_resize_shape(self, factor, width, height, dst_pixel_size):
"""Estimate new shape either from factor or destination width/height or pixel size"""
src_shape = np.array(self.shape(), np.float)
src_shape = np.array(self.shape, np.float)
# estimate factor if either width or height is given and factor is not given
if width is not None:
factor = width / src_shape[1]
Expand Down Expand Up @@ -1377,7 +1377,7 @@ def crop_interactive(self, band=1, maxwidth=1000, **kwargs):

"""
resized = False
if self.shape()[1] > maxwidth:
if self.shape[1] > maxwidth:
factor = self.resize(width=1000)
resized = True
else:
Expand Down Expand Up @@ -1500,15 +1500,15 @@ def crop(self, x_offset, y_offset, x_size, y_size, allow_larger=False):

"""
x_offset, x_size = Nansat._fix_crop_offset_size(x_offset, x_size,
self.shape()[1], allow_larger)
self.shape[1], allow_larger)
y_offset, y_size = Nansat._fix_crop_offset_size(y_offset, y_size,
self.shape()[0], allow_larger)
self.shape[0], allow_larger)

extent = (int(x_offset), int(y_offset), int(x_size), int(y_size))
self.logger.debug('x_offset: %d, y_offset: %d, x_size: %d, y_size: %d' % extent)

# test if crop is larger or equal to image size
if x_offset == y_offset == 0 and (y_size, x_size) == self.shape():
if x_offset == y_offset == 0 and (y_size, x_size) == self.shape:
self.logger.error(('WARNING! Cropping region is larger or equal to image!'))
return extent

Expand Down Expand Up @@ -1540,8 +1540,8 @@ def extend(self, left=0, right=0, top=0, bottom=0):

"""
x_offset, y_offset = -left, -top
x_size = self.shape()[1] + left + right
y_size = self.shape()[0] + top + bottom
x_size = self.shape[1] + left + right
y_size = self.shape[0] + top + bottom
self.crop(x_offset, y_offset, x_size, y_size, allow_larger=True)

def _get_pix_lin_vectors(self, points, lonlat, cornersonly, smooth_radius):
Expand Down Expand Up @@ -1569,8 +1569,8 @@ def _get_pix_lin_vectors(self, points, lonlat, cornersonly, smooth_radius):
linVector = np.floor(linVector)
gpi = ((pixVector >= (0 + smooth_radius)) *
(linVector >= (0 + smooth_radius)) *
(pixVector < (self.shape()[1] - smooth_radius)) *
(linVector < (self.shape()[0] - smooth_radius)))
(pixVector < (self.shape[1] - smooth_radius)) *
(linVector < (self.shape[0] - smooth_radius)))

return pixVector[gpi], linVector[gpi]

Expand Down
4 changes: 2 additions & 2 deletions nansat/tests/mappers/test_mapper_opendap.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ def test_test_mapper(self):
with self.assertRaises(WrongMapperError):
self.od.test_mapper(filename='http://not-in-base-urls.net/path/to/the/file.nc')

""" Not sure how to test get_dataset..
""" Not sure how to test get_dataset..

According toe the followingm, mocking C modules seems not to be possible.. Can that be the
reason the below doesn't work?

Expand Down
8 changes: 4 additions & 4 deletions nansat/tests/test_domain.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,20 +111,20 @@ def test_init_lonlat(self):
self.assertTrue(nansat_warning_raised)

self.assertEqual(type(d), Domain)
self.assertEqual(d.shape(), lat.shape)
self.assertEqual(d.shape, lat.shape)

def test_init_from_lonlat(self):
lat, lon = np.mgrid[-10:10:0.5, -20:20:2]
d = Domain.from_lonlat(lon=lon, lat=lat)
self.assertEqual(type(d), Domain)
self.assertEqual(d.shape(), lat.shape)
self.assertEqual(d.shape, lat.shape)
self.assertEqual(len(d.vrt.dataset.GetGCPs()), 100)

def test_init_from_lonlat_no_gcps(self):
lat, lon = np.mgrid[-10:10:0.5, -20:20:2]
d = Domain.from_lonlat(lon=lon, lat=lat, add_gcps=False)
self.assertEqual(type(d), Domain)
self.assertEqual(d.shape(), lat.shape)
self.assertEqual(d.shape, lat.shape)
self.assertEqual(len(d.vrt.dataset.GetGCPs()), 0)

@patch.object(Domain, 'get_corners',
Expand Down Expand Up @@ -495,7 +495,7 @@ def test_azimuth_y(self, mock_get_geolocation_grids):

def test_shape(self):
d = Domain(4326, "-te 25 70 35 72 -ts 500 500")
self.assertEqual(d.shape(), (500, 500))
self.assertEqual(d.shape, (500, 500))

def test_reproject_gcps(self):
ds = gdal.Open(self.test_file)
Expand Down
12 changes: 6 additions & 6 deletions nansat/tests/test_exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,11 @@ def test_time_coverage_metadata_of_exported_equals_original(self):
def test_export_netcdf(self):
""" Test export and following import of data with bands containing np.nan values """
n = Nansat(self.test_file_gcps, mapper=self.default_mapper)
arrNoNaN = np.random.randn(n.shape()[0], n.shape()[1])
arrNoNaN = np.random.randn(n.shape[0], n.shape[1])
n.add_band(arrNoNaN, {'name': 'testBandNoNaN'})
arrWithNaN = arrNoNaN.copy()
arrWithNaN[int(n.shape()[0] / 2.) - 10:int(n.shape()[0] / 2 + 10),
int(n.shape()[1] / 2.) - 10:int(n.shape()[1] / 2 + 10)] = np.nan
arrWithNaN[int(n.shape[0] / 2.) - 10:int(n.shape[0] / 2 + 10),
int(n.shape[1] / 2.) - 10:int(n.shape[1] / 2 + 10)] = np.nan
n.add_band(arrWithNaN, {'name': 'testBandWithNaN'})
n.export(self.tmp_filename)
exported = Nansat(self.tmp_filename, mapper=self.default_mapper)
Expand Down Expand Up @@ -187,7 +187,7 @@ def test_reproject_and_export_band(self):
def test_export_selected_bands(self):
n = Nansat(self.test_file_gcps, mapper=self.default_mapper)
resfile = 'tmp.nc'
new_band = np.random.randn(n.shape()[0], n.shape()[1])
new_band = np.random.randn(n.shape[0], n.shape[1])
n.add_band(new_band, {'name': 'newBand'})
# Test with band numbers
n.export(resfile, bands=[4, 2])
Expand Down Expand Up @@ -259,7 +259,7 @@ def test_export2thredds_arctic_long_lat(self):
def test_dont_export2thredds_gcps(self):
n = Nansat(self.test_file_gcps, log_level=40, mapper=self.default_mapper)
n2 = Nansat.from_domain(n)
n.add_band(np.ones(n2.shape(), np.float32))
n.add_band(np.ones(n2.shape, np.float32))
tmpfilename = os.path.join(self.tmp_data_path,
'nansat_export2thredds.nc')
with self.assertRaises(ValueError) as e:
Expand All @@ -275,7 +275,7 @@ def test_export2thredds_longlat_dict(self):
d = Domain("+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs",
"-te 27 70 31 72 -ts 200 200")
n = Nansat.from_domain(d)
n.add_band(np.ones(d.shape(), np.float32),
n.add_band(np.ones(d.shape, np.float32),
parameters={'name': 'L_469'})
n.set_metadata('time_coverage_start', '2016-01-19')

Expand Down
48 changes: 24 additions & 24 deletions nansat/tests/test_nansat.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ def test_reproject_domain(self):
tmpfilename = os.path.join(self.tmp_data_path, 'nansat_reproject_domain.png')
n.write_figure(tmpfilename, 2, clim='hist')

self.assertEqual(n.shape(), (500, 500))
self.assertEqual(n.shape, (500, 500))
self.assertEqual(type(n[1]), np.ndarray)
self.assertTrue(n.has_band('swathmask'))

Expand All @@ -301,7 +301,7 @@ def test_reproject_domain_if_dst_domain_is_given(self):
tmpfilename = os.path.join(self.tmp_data_path, 'nansat_reproject_domain.png')
n.write_figure(tmpfilename, 2, clim='hist')

self.assertEqual(n.shape(), (500, 500))
self.assertEqual(n.shape, (500, 500))
self.assertEqual(type(n[1]), np.ndarray)
self.assertTrue(n.has_band('swathmask'))

Expand All @@ -312,7 +312,7 @@ def test_reproject_domain_if_resample_alg_is_given(self):
tmpfilename = os.path.join(self.tmp_data_path, 'nansat_reproject_domain.png')
n.write_figure(tmpfilename, 2, clim='hist')

self.assertEqual(n.shape(), (500, 500))
self.assertEqual(n.shape, (500, 500))
self.assertEqual(type(n[1]), np.ndarray)
self.assertTrue(n.has_band('swathmask'))

Expand All @@ -325,7 +325,7 @@ def test_reproject_domain_if_source_and_destination_domain_span_entire_lons(self
tmpfilename = os.path.join(self.tmp_data_path, 'nansat_reproject_domain_span_entire_lons.png')
n.write_figure(tmpfilename, 2, clim='hist')

self.assertEqual(n.shape(), (500, 500))
self.assertEqual(n.shape, (500, 500))
self.assertEqual(type(n[1]), np.ndarray)
self.assertTrue(n.has_band('swathmask'))

Expand All @@ -337,7 +337,7 @@ def test_reproject_domain_if_tps_is_given(self):
'nansat_reproject_domain.png')
n.write_figure(tmpfilename, 2, clim='hist')

self.assertEqual(n.shape(), (500, 500))
self.assertEqual(n.shape, (500, 500))
self.assertEqual(type(n[1]), np.ndarray)
self.assertTrue(n.has_band('swathmask'))

Expand All @@ -348,7 +348,7 @@ def test_reproject_domain_if_tps_is_given(self):
'nansat_reproject_domain.png')
n.write_figure(tmpfilename, 2, clim='hist')

self.assertEqual(n.shape(), (500, 500))
self.assertEqual(n.shape, (500, 500))
self.assertEqual(type(n[1]), np.ndarray)
self.assertTrue(n.has_band('swathmask'))

Expand All @@ -367,7 +367,7 @@ def test_add_band_and_reproject(self):
""" Should add band and swath mask and return np.nan in areas out of swath """
n = Nansat(self.test_file_gcps, log_level=40, mapper=self.default_mapper)
d = Domain(4326, "-te 27 70 30 72 -ts 500 500")
n.add_band(np.ones(n.shape(), np.uint8))
n.add_band(np.ones(n.shape, np.uint8))
n.reproject(d)
b4 = n[4] # added, reprojected band
b5 = n[5] # swathmask
Expand Down Expand Up @@ -398,7 +398,7 @@ def test_reproject_stere(self):
'nansat_reproject_stere.png')
n1.write_figure(tmpfilename, 2, clim='hist')

self.assertEqual(n1.shape(), n2.shape())
self.assertEqual(n1.shape, n2.shape)
self.assertEqual(type(n1[1]), np.ndarray)

def test_reproject_gcps(self):
Expand All @@ -409,7 +409,7 @@ def test_reproject_gcps(self):
'nansat_reproject_gcps.png')
n1.write_figure(tmpfilename, 2, clim='hist')

self.assertEqual(n1.shape(), n2.shape())
self.assertEqual(n1.shape, n2.shape)
self.assertEqual(type(n1[1]), np.ndarray)

def test_reproject_gcps_on_repro_gcps(self):
Expand All @@ -421,7 +421,7 @@ def test_reproject_gcps_on_repro_gcps(self):
'nansat_reproject_gcps_on_repro_gcps.png')
n1.write_figure(tmpfilename, 2, clim='hist')

self.assertEqual(n1.shape(), n2.shape())
self.assertEqual(n1.shape, n2.shape)
self.assertEqual(type(n1[1]), np.ndarray)

def test_reproject_gcps_resize(self):
Expand All @@ -433,16 +433,16 @@ def test_reproject_gcps_resize(self):
'nansat_reproject_gcps_resize.png')
n1.write_figure(tmpfilename, 2, clim='hist')

self.assertEqual(n1.shape()[0], n2.shape()[0] * 2)
self.assertEqual(n1.shape()[1], n2.shape()[1] * 2)
self.assertEqual(n1.shape[0], n2.shape[0] * 2)
self.assertEqual(n1.shape[1], n2.shape[1] * 2)
self.assertEqual(type(n1[1]), np.ndarray)

def test_undo(self):
n1 = Nansat(self.test_file_stere, log_level=40, mapper=self.default_mapper)
shape1 = n1.shape()
shape1 = n1.shape
n1.resize(10)
n1.undo()
shape2 = n1.shape()
shape2 = n1.shape

self.assertEqual(shape1, shape2)

Expand Down Expand Up @@ -645,14 +645,14 @@ def test_crop(self):
n1 = Nansat(self.test_file_gcps, log_level=40, mapper=self.default_mapper)
ext = n1.crop(10, 20, 50, 60)

self.assertEqual(n1.shape(), (60, 50))
self.assertEqual(n1.shape, (60, 50))
self.assertEqual(ext, (10, 20, 50, 60))
self.assertEqual(type(n1[1]), np.ndarray)

n1 = Nansat(self.test_file_gcps, log_level=40, mapper=self.default_mapper)
ext = n1.crop(0, 0, 200, 200)

self.assertEqual(n1.shape(), (200, 200))
self.assertEqual(n1.shape, (200, 200))
self.assertEqual(ext, (0, 0, 200, 200))
self.assertEqual(type(n1[1]), np.ndarray)

Expand All @@ -673,23 +673,23 @@ def test_crop_complex(self):
n1 = Nansat(self.test_file_complex, log_level=40, mapper=self.default_mapper)
ext = n1.crop(10, 20, 50, 60)

self.assertEqual(n1.shape(), (60, 50))
self.assertEqual(n1.shape, (60, 50))
self.assertEqual(ext, (10, 20, 50, 60))
self.assertEqual(type(n1[1]), np.ndarray)

def test_crop_no_gcps_arctic(self):
n1 = Nansat(self.test_file_arctic, log_level=40, mapper=self.default_mapper)
ext = n1.crop(10, 20, 50, 60)

self.assertEqual(n1.shape(), (60, 50))
self.assertEqual(n1.shape, (60, 50))
self.assertEqual(ext, (10, 20, 50, 60))
self.assertEqual(type(n1[1]), np.ndarray)

def test_crop_lonlat(self):
n1 = Nansat(self.test_file_gcps, log_level=40, mapper=self.default_mapper)
ext = n1.crop_lonlat([28, 29], [70.5, 71])

self.assertEqual(n1.shape(), (111, 110))
self.assertEqual(n1.shape, (111, 110))
self.assertEqual(ext, (31, 89, 110, 111))
self.assertEqual(type(n1[1]), np.ndarray)

Expand All @@ -705,8 +705,8 @@ def test_watermask(self):
if mod44path is not None and os.path.exists(mod44path + '/MOD44W.vrt'):
wm = n1.watermask()[1]
self.assertEqual(type(wm), np.ndarray)
self.assertEqual(wm.shape[0], n1.shape()[0])
self.assertEqual(wm.shape[1], n1.shape()[1])
self.assertEqual(wm.shape[0], n1.shape[0])
self.assertEqual(wm.shape[1], n1.shape[1])

def test_watermask_fail_if_mod44path_is_wrong(self):
""" Nansat.watermask should raise an IOError"""
Expand Down Expand Up @@ -774,14 +774,14 @@ def test_crop_interactive(self, mock_digitize_points):
mock_digitize_points.return_value=[np.array([[10, 20], [10, 30]])]
n = Nansat(self.test_file_arctic, log_level=40, mapper=self.default_mapper)
n.crop_interactive()
self.assertEqual(n.shape(), (20, 10))
self.assertEqual(n.shape, (20, 10))

def test_extend(self):
n = Nansat(self.test_file_arctic, log_level=40, mapper=self.default_mapper)
nshape1 = n.shape()
nshape1 = n.shape
n.extend(left=10, right=20, top=30, bottom=40)
be = n[1]
self.assertEqual(n.shape(), (nshape1[0]+70, nshape1[1]+30))
self.assertEqual(n.shape, (nshape1[0]+70, nshape1[1]+30))
self.assertIsInstance(be, np.ndarray)

def test_open_no_mapper(self):
Expand Down