Passed
Push — master ( 75fbae...59f4f8 )
by Stefan
03:43
created

sciapy.level1c.scia_limb_nc   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 208
Duplicated Lines 85.1 %

Test Coverage

Coverage 89.93%

Importance

Changes 0
Metric Value
eloc 148
dl 177
loc 208
ccs 125
cts 139
cp 0.8993
rs 10
c 0
b 0
f 0
wmc 9

2 Functions

Rating   Name   Duplication   Size   Complexity  
B write_to_netcdf() 96 96 3
B read_from_netcdf() 81 81 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
# -*- coding: utf-8 -*-
2
# vim:fileencoding=utf-8
3
#
4
# Copyright (c) 2014-2017 Stefan Bender
5
#
6
# This file is part of sciapy.
7
# sciapy is free software: you can redistribute it or modify it
8
# under the terms of the GNU General Public License as published by
9
# the Free Software Foundation, version 2.
10
# See accompanying LICENSE file or http://www.gnu.org/licenses/gpl-2.0.html.
11 1
"""SCIAMACHY level 1c limb spectra netcdf interface
12
"""
13
14 1
from __future__ import absolute_import, division, print_function
15
16 1
import numpy as np
17 1
try:
18 1
	from netCDF4 import Dataset as netcdf_file
19 1
	_fmtargs = {"format": "NETCDF4"}
20
except ImportError:
21
	try:
22
		from scipy.io.netcdf import netcdf_file
23
		_fmtargs = {"version": 1}
24
	except ImportError:
25
		from pupynere import netcdf_file
26
		_fmtargs = {"version": 1}
27
28 1
from ._types import _limb_data_dtype, _try_decode
29
30 1 View Code Duplication
def read_from_netcdf(self, filename):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
31
	"""SCIAMACHY level 1c limb scan netcdf import
32
33
	Parameters
34
	----------
35
	filename : str
36
		The netcdf filename to read the data from.
37
38
	Returns
39
	-------
40
	nothing
41
	"""
42 1
	import numpy.lib.recfunctions as rfn
43
44 1
	ncf = netcdf_file(filename, 'r')
45
46 1
	self.textheader_length = ncf.textheader_length
47 1
	self.textheader = _try_decode(ncf.textheader)
48
49 1
	self.orbit_state = ncf.orbit_state
50 1
	(self.orbit, self.state_in_orbit, self.state_id,
51
		self.profiles_per_state, self.profile_in_state) = self.orbit_state
52 1
	self.date = ncf.date
53 1
	self.cent_lat_lon = ncf.cent_lat_lon
54 1
	self.orbit_phase = ncf.orbit_phase
55
56 1
	try:
57 1
		self.nalt = ncf.dimensions['limb'].size
58 1
		self.npix = ncf.dimensions['wavelength'].size
59
	except:
60
		self.nalt = ncf.dimensions['limb']
61
		self.npix = ncf.dimensions['wavelength']
62
63 1
	self.wls = ncf.variables['wavelength'][:].copy()
64
65
	# pre-set the limb_data
66 1
	if self._limb_data_dtype is None:
67 1
		self._limb_data_dtype = _limb_data_dtype[:]
68 1
	self.limb_data = np.zeros((self.nalt), dtype=self._limb_data_dtype)
69
70 1
	self.limb_data["sub_sat_lat"] = ncf.variables['sub_sat_lat'][:].copy()
71 1
	self.limb_data["sub_sat_lon"] = ncf.variables['sub_sat_lon'][:].copy()
72 1
	self.limb_data["tp_lat"] = ncf.variables['TP latitude'][:].copy()
73 1
	self.limb_data["tp_lon"] = ncf.variables['TP longitude'][:].copy()
74 1
	self.limb_data["tp_alt"] = ncf.variables['TP altitude'][:].copy()
75 1
	self.limb_data["tp_sza"] = ncf.variables['TP SZA'][:].copy()
76 1
	self.limb_data["tp_saa"] = ncf.variables['TP SAA'][:].copy()
77 1
	self.limb_data["tp_los"] = ncf.variables['TP LOS Zenith'][:].copy()
78 1
	self.limb_data["toa_sza"] = ncf.variables['TOA SZA'][:].copy()
79 1
	self.limb_data["toa_saa"] = ncf.variables['TOA SAA'][:].copy()
80 1
	self.limb_data["toa_los"] = ncf.variables['TOA LOS Zenith'][:].copy()
81 1
	self.limb_data["sat_sza"] = ncf.variables['SAT SZA'][:].copy()
82 1
	self.limb_data["sat_saa"] = ncf.variables['SAT SAA'][:].copy()
83 1
	self.limb_data["sat_los"] = ncf.variables['SAT LOS Zenith'][:].copy()
84 1
	self.limb_data["sat_alt"] = ncf.variables['SAT altitude'][:].copy()
85 1
	self.limb_data["earth_rad"] = ncf.variables['earthradius'][:].copy()
86
87 1
	tmp_rad_arr = list(ncf.variables['radiance'][:].copy())
88 1
	tmp_err_arr = list(ncf.variables['radiance errors'][:].copy())
89
90
	# save to limb_data recarray
91 1
	rads = np.rec.fromarrays([tmp_rad_arr],
92
				dtype=np.dtype([("rad", 'f4', (self.npix,))]))
93 1
	errs = np.rec.fromarrays([tmp_err_arr],
94
				dtype=np.dtype([("err", 'f4', (self.npix,))]))
95 1
	self.limb_data = rfn.merge_arrays([self.limb_data, rads, errs],
96
			usemask=False, asrecarray=True, flatten=True)
97 1
	self._limb_data_dtype = self.limb_data.dtype
98
99 1
	if hasattr(ncf, "_attributes"):
100
		# scipy.io.netcdf / pupynere
101
		ncattrs = ncf._attributes.keys()
102
	else:
103
		# netcdf4
104 1
		ncattrs = ncf.ncattrs()
105 1
	for _k in ncattrs:
106 1
		if _k.startswith("metadata"):
107 1
			_meta_key = _k.split("::")[1]
108 1
			_att = getattr(ncf, _k)
109 1
			self.metadata[_meta_key] = _try_decode(_att)
110 1
	ncf.close()
111
112 1 View Code Duplication
def write_to_netcdf(self, filename):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
113
	"""SCIAMACHY level 1c limb scan netcdf export
114
115
	Parameters
116
	----------
117
	filename : str
118
		The netcdf filename to write the data to.
119
120
	Returns
121
	-------
122
	nothing
123
	"""
124 1
	ncf = netcdf_file(filename, 'w', **_fmtargs)
125
126 1
	ncf.textheader_length = self.textheader_length
127 1
	ncf.textheader = self.textheader
128
129 1
	ncf.orbit_state = self.orbit_state
130 1
	ncf.date = self.date
131 1
	ncf.cent_lat_lon = self.cent_lat_lon
132 1
	ncf.orbit_phase = self.orbit_phase
133
134 1
	ncf.createDimension('limb', self.nalt)
135 1
	ncf.createDimension('wavelength', self.npix)
136
137 1
	wavs = ncf.createVariable('wavelength', np.dtype('float32').char, ('wavelength',))
138 1
	wavs.units = 'nm'
139 1
	wavs[:] = np.asarray(self.wls)
140
141 1
	sslat = ncf.createVariable('sub_sat_lat', np.dtype('float32').char, ('limb',))
142 1
	sslat.units = 'deg'
143 1
	sslat[:] = np.asarray(self.limb_data["sub_sat_lat"])
144 1
	sslon = ncf.createVariable('sub_sat_lon', np.dtype('float32').char, ('limb',))
145 1
	sslon.units = 'deg'
146 1
	sslon[:] = np.asarray(self.limb_data["sub_sat_lon"])
147 1
	tp_lats = ncf.createVariable('TP latitude', np.dtype('float32').char, ('limb',))
148 1
	tp_lats.units = 'deg'
149 1
	tp_lats[:] = np.asarray(self.limb_data["tp_lat"])
150 1
	tp_lons = ncf.createVariable('TP longitude', np.dtype('float32').char, ('limb',))
151 1
	tp_lons.units = 'deg'
152 1
	tp_lons[:] = np.asarray(self.limb_data["tp_lon"])
153 1
	tp_alts = ncf.createVariable('TP altitude', np.dtype('float32').char, ('limb',))
154 1
	tp_alts.units = 'km'
155 1
	tp_alts[:] = np.asarray(self.limb_data["tp_alt"])
156 1
	tp_szas = ncf.createVariable('TP SZA', np.dtype('float32').char, ('limb',))
157 1
	tp_szas.units = 'deg'
158 1
	tp_szas[:] = np.asarray(self.limb_data["tp_sza"])
159 1
	tp_saas = ncf.createVariable('TP SAA', np.dtype('float32').char, ('limb',))
160 1
	tp_saas.units = 'deg'
161 1
	tp_saas[:] = np.asarray(self.limb_data["tp_saa"])
162 1
	tp_los_zeniths = ncf.createVariable('TP LOS Zenith', np.dtype('float32').char, ('limb',))
163 1
	tp_los_zeniths.units = 'deg'
164 1
	tp_los_zeniths[:] = np.asarray(self.limb_data["tp_los"])
165 1
	toa_szas = ncf.createVariable('TOA SZA', np.dtype('float32').char, ('limb',))
166 1
	toa_szas.units = 'deg'
167 1
	toa_szas[:] = np.asarray(self.limb_data["toa_sza"])
168 1
	toa_saas = ncf.createVariable('TOA SAA', np.dtype('float32').char, ('limb',))
169 1
	toa_saas.units = 'deg'
170 1
	toa_saas[:] = np.asarray(self.limb_data["toa_saa"])
171 1
	toa_los_zeniths = ncf.createVariable('TOA LOS Zenith', np.dtype('float32').char, ('limb',))
172 1
	toa_los_zeniths.units = 'deg'
173 1
	toa_los_zeniths[:] = np.asarray(self.limb_data["toa_los"])
174 1
	sat_szas = ncf.createVariable('SAT SZA', np.dtype('float32').char, ('limb',))
175 1
	sat_szas.units = 'deg'
176 1
	sat_szas[:] = np.asarray(self.limb_data["sat_sza"])
177 1
	sat_saas = ncf.createVariable('SAT SAA', np.dtype('float32').char, ('limb',))
178 1
	sat_saas.units = 'deg'
179 1
	sat_saas[:] = np.asarray(self.limb_data["sat_saa"])
180 1
	sat_los_zeniths = ncf.createVariable('SAT LOS Zenith', np.dtype('float32').char, ('limb',))
181 1
	sat_los_zeniths.units = 'deg'
182 1
	sat_los_zeniths[:] = np.asarray(self.limb_data["sat_los"])
183 1
	sat_alts = ncf.createVariable('SAT altitude', np.dtype('float32').char, ('limb',))
184 1
	sat_alts.units = 'km'
185 1
	sat_alts[:] = np.asarray(self.limb_data["sat_alt"])
186 1
	eradii_alts = ncf.createVariable('earthradius', np.dtype('float32').char, ('limb',))
187 1
	eradii_alts.units = 'km'
188 1
	eradii_alts[:] = np.asarray(self.limb_data["earth_rad"])
189
190 1
	try:
191 1
		rads = ncf.createVariable('radiance', np.dtype('float32').char,
192
				('limb', 'wavelength'), zlib=True, complevel=1)
193 1
		errs = ncf.createVariable('radiance errors', np.dtype('float32').char,
194
				('limb', 'wavelength'), zlib=True, complevel=1)
195
	except TypeError:
196
		rads = ncf.createVariable('radiance', np.dtype('float32').char,
197
				('limb', 'wavelength'))
198
		errs = ncf.createVariable('radiance errors', np.dtype('float32').char,
199
				('limb', 'wavelength'))
200 1
	rads.units = 'ph / s / cm^2 / nm'
201 1
	errs.units = 'ph / s / cm^2 / nm'
202 1
	rads[:] = np.asarray(self.limb_data["rad"]).reshape(self.nalt, self.npix)
203 1
	errs[:] = np.asarray(self.limb_data["err"]).reshape(self.nalt, self.npix)
204
205 1
	for _k, _v in self.metadata.items():
206 1
		setattr(ncf, "metadata::" + _k, _v)
207
	ncf.close()
208