Completed
Push — master ( 25dceb...54142a )
by Stefan
11:22
created

sciapy.level1c.scia_limb_nc.write_to_netcdf()   B

Complexity

Conditions 3

Size

Total Lines 96
Code Lines 78

Duplication

Lines 96
Ratio 100 %

Code Coverage

Tests 71
CRAP Score 3.0005

Importance

Changes 0
Metric Value
cc 3
eloc 78
nop 2
dl 96
loc 96
ccs 71
cts 74
cp 0.9595
crap 3.0005
rs 7.72
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
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 1
	ncf = netcdf_file(filename, 'r')
44
45 1
	self.textheader_length = ncf.textheader_length
46 1
	self.textheader = ncf.textheader
47
48 1
	self.orbit_state = ncf.orbit_state
49 1
	(self.orbit, self.state_in_orbit, self.state_id,
50
		self.profiles_per_state, self.profile_in_state) = self.orbit_state
51 1
	self.date = ncf.date
52 1
	self.cent_lat_lon = ncf.cent_lat_lon
53 1
	self.orbit_phase = ncf.orbit_phase
54
55 1
	try:
56 1
		self.nalt = ncf.dimensions['limb'].size
57 1
		self.npix = ncf.dimensions['wavelength'].size
58
	except:
59
		self.nalt = ncf.dimensions['limb']
60
		self.npix = ncf.dimensions['wavelength']
61
62 1
	self.wls = ncf.variables['wavelength'][:].copy()
63
64
	# pre-set the limb_data
65 1
	if self._limb_data_dtype is None:
66 1
		self._limb_data_dtype = _limb_data_dtype[:]
67 1
	self.limb_data = np.zeros((self.nalt), dtype=self._limb_data_dtype)
68
69 1
	self.limb_data["sub_sat_lat"] = ncf.variables['sub_sat_lat'][:].copy()
70 1
	self.limb_data["sub_sat_lon"] = ncf.variables['sub_sat_lon'][:].copy()
71 1
	self.limb_data["tp_lat"] = ncf.variables['TP latitude'][:].copy()
72 1
	self.limb_data["tp_lon"] = ncf.variables['TP longitude'][:].copy()
73 1
	self.limb_data["tp_alt"] = ncf.variables['TP altitude'][:].copy()
74 1
	self.limb_data["tp_sza"] = ncf.variables['TP SZA'][:].copy()
75 1
	self.limb_data["tp_saa"] = ncf.variables['TP SAA'][:].copy()
76 1
	self.limb_data["tp_los"] = ncf.variables['TP LOS Zenith'][:].copy()
77 1
	self.limb_data["toa_sza"] = ncf.variables['TOA SZA'][:].copy()
78 1
	self.limb_data["toa_saa"] = ncf.variables['TOA SAA'][:].copy()
79 1
	self.limb_data["toa_los"] = ncf.variables['TOA LOS Zenith'][:].copy()
80 1
	self.limb_data["sat_sza"] = ncf.variables['SAT SZA'][:].copy()
81 1
	self.limb_data["sat_saa"] = ncf.variables['SAT SAA'][:].copy()
82 1
	self.limb_data["sat_los"] = ncf.variables['SAT LOS Zenith'][:].copy()
83 1
	self.limb_data["sat_alt"] = ncf.variables['SAT altitude'][:].copy()
84 1
	self.limb_data["earth_rad"] = ncf.variables['earthradius'][:].copy()
85
86 1
	tmp_rad_arr = list(ncf.variables['radiance'][:].copy())
87 1
	tmp_err_arr = list(ncf.variables['radiance errors'][:].copy())
88
89
	# save to limb_data recarray
90 1
	rads = np.rec.fromarrays([tmp_rad_arr],
91
				dtype=np.dtype([("rad", 'f4', (self.npix,))]))
92 1
	errs = np.rec.fromarrays([tmp_err_arr],
93
				dtype=np.dtype([("err", 'f4', (self.npix,))]))
94 1
	self.limb_data = rfn.merge_arrays([self.limb_data, rads, errs],
95
			usemask=False, asrecarray=True, flatten=True)
96 1
	self._limb_data_dtype = self.limb_data.dtype
97
98 1
	if hasattr(ncf, "_attributes"):
99
		# scipy.io.netcdf / pupynere
100
		ncattrs = ncf._attributes.keys()
101
	else:
102
		# netcdf4
103 1
		ncattrs = ncf.ncattrs()
104 1
	for _k in ncattrs:
105 1
		if _k.startswith("metadata"):
106 1
			_meta_key = _k.split("::")[1]
107 1
			self.metadata[_meta_key] = getattr(ncf, _k)
108 1
	ncf.close()
109
110 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...
111
	"""SCIAMACHY level 1c limb scan netcdf export
112
113
	Parameters
114
	----------
115
	filename : str
116
		The netcdf filename to write the data to.
117
118
	Returns
119
	-------
120
	nothing
121
	"""
122 1
	ncf = netcdf_file(filename, 'w', **_fmtargs)
123
124 1
	ncf.textheader_length = self.textheader_length
125 1
	ncf.textheader = self.textheader
126
127 1
	ncf.orbit_state = self.orbit_state
128 1
	ncf.date = self.date
129 1
	ncf.cent_lat_lon = self.cent_lat_lon
130 1
	ncf.orbit_phase = self.orbit_phase
131
132 1
	ncf.createDimension('limb', self.nalt)
133 1
	ncf.createDimension('wavelength', self.npix)
134
135 1
	wavs = ncf.createVariable('wavelength', np.dtype('float32').char, ('wavelength',))
136 1
	wavs.units = 'nm'
137 1
	wavs[:] = np.asarray(self.wls)
138
139 1
	sslat = ncf.createVariable('sub_sat_lat', np.dtype('float32').char, ('limb',))
140 1
	sslat.units = 'deg'
141 1
	sslat[:] = np.asarray(self.limb_data["sub_sat_lat"])
142 1
	sslon = ncf.createVariable('sub_sat_lon', np.dtype('float32').char, ('limb',))
143 1
	sslon.units = 'deg'
144 1
	sslon[:] = np.asarray(self.limb_data["sub_sat_lon"])
145 1
	tp_lats = ncf.createVariable('TP latitude', np.dtype('float32').char, ('limb',))
146 1
	tp_lats.units = 'deg'
147 1
	tp_lats[:] = np.asarray(self.limb_data["tp_lat"])
148 1
	tp_lons = ncf.createVariable('TP longitude', np.dtype('float32').char, ('limb',))
149 1
	tp_lons.units = 'deg'
150 1
	tp_lons[:] = np.asarray(self.limb_data["tp_lon"])
151 1
	tp_alts = ncf.createVariable('TP altitude', np.dtype('float32').char, ('limb',))
152 1
	tp_alts.units = 'km'
153 1
	tp_alts[:] = np.asarray(self.limb_data["tp_alt"])
154 1
	tp_szas = ncf.createVariable('TP SZA', np.dtype('float32').char, ('limb',))
155 1
	tp_szas.units = 'deg'
156 1
	tp_szas[:] = np.asarray(self.limb_data["tp_sza"])
157 1
	tp_saas = ncf.createVariable('TP SAA', np.dtype('float32').char, ('limb',))
158 1
	tp_saas.units = 'deg'
159 1
	tp_saas[:] = np.asarray(self.limb_data["tp_saa"])
160 1
	tp_los_zeniths = ncf.createVariable('TP LOS Zenith', np.dtype('float32').char, ('limb',))
161 1
	tp_los_zeniths.units = 'deg'
162 1
	tp_los_zeniths[:] = np.asarray(self.limb_data["tp_los"])
163 1
	toa_szas = ncf.createVariable('TOA SZA', np.dtype('float32').char, ('limb',))
164 1
	toa_szas.units = 'deg'
165 1
	toa_szas[:] = np.asarray(self.limb_data["toa_sza"])
166 1
	toa_saas = ncf.createVariable('TOA SAA', np.dtype('float32').char, ('limb',))
167 1
	toa_saas.units = 'deg'
168 1
	toa_saas[:] = np.asarray(self.limb_data["toa_saa"])
169 1
	toa_los_zeniths = ncf.createVariable('TOA LOS Zenith', np.dtype('float32').char, ('limb',))
170 1
	toa_los_zeniths.units = 'deg'
171 1
	toa_los_zeniths[:] = np.asarray(self.limb_data["toa_los"])
172 1
	sat_szas = ncf.createVariable('SAT SZA', np.dtype('float32').char, ('limb',))
173 1
	sat_szas.units = 'deg'
174 1
	sat_szas[:] = np.asarray(self.limb_data["sat_sza"])
175 1
	sat_saas = ncf.createVariable('SAT SAA', np.dtype('float32').char, ('limb',))
176 1
	sat_saas.units = 'deg'
177 1
	sat_saas[:] = np.asarray(self.limb_data["sat_saa"])
178 1
	sat_los_zeniths = ncf.createVariable('SAT LOS Zenith', np.dtype('float32').char, ('limb',))
179 1
	sat_los_zeniths.units = 'deg'
180 1
	sat_los_zeniths[:] = np.asarray(self.limb_data["sat_los"])
181 1
	sat_alts = ncf.createVariable('SAT altitude', np.dtype('float32').char, ('limb',))
182 1
	sat_alts.units = 'km'
183 1
	sat_alts[:] = np.asarray(self.limb_data["sat_alt"])
184 1
	eradii_alts = ncf.createVariable('earthradius', np.dtype('float32').char, ('limb',))
185 1
	eradii_alts.units = 'km'
186 1
	eradii_alts[:] = np.asarray(self.limb_data["earth_rad"])
187
188 1
	try:
189 1
		rads = ncf.createVariable('radiance', np.dtype('float32').char,
190
				('limb', 'wavelength'), zlib=True, complevel=1)
191 1
		errs = ncf.createVariable('radiance errors', np.dtype('float32').char,
192
				('limb', 'wavelength'), zlib=True, complevel=1)
193
	except TypeError:
194
		rads = ncf.createVariable('radiance', np.dtype('float32').char,
195
				('limb', 'wavelength'))
196
		errs = ncf.createVariable('radiance errors', np.dtype('float32').char,
197
				('limb', 'wavelength'))
198 1
	rads.units = 'ph / s / cm^2 / nm'
199 1
	errs.units = 'ph / s / cm^2 / nm'
200 1
	rads[:] = np.asarray(self.limb_data["rad"]).reshape(self.nalt, self.npix)
201 1
	errs[:] = np.asarray(self.limb_data["err"]).reshape(self.nalt, self.npix)
202
203 1
	for _k, _v in self.metadata.items():
204 1
		setattr(ncf, "metadata::" + _k, _v)
205
	ncf.close()
206