├── .git_archival.txt
├── .gitattributes
├── .github
└── workflows
│ └── python-publish.yml
├── .gitignore
├── IMProToo
├── __init__.py
├── core.py
└── tools.py
├── LICENSE
├── README.md
├── examples
├── batch_convert_rawData.py
└── batch_makeQuicklooks.py
├── pyproject.toml
└── setup.py
/.git_archival.txt:
--------------------------------------------------------------------------------
1 | ref-names: HEAD -> master, tag: 0.107
2 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | .git_archival.txt export-subst
2 |
--------------------------------------------------------------------------------
/.github/workflows/python-publish.yml:
--------------------------------------------------------------------------------
1 | # This workflow will upload a Python Package using Twine when a release is created
2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries
3 |
4 | # This workflow uses actions that are not certified by GitHub.
5 | # They are provided by a third-party and are governed by
6 | # separate terms of service, privacy policy, and support
7 | # documentation.
8 |
9 | name: Upload Python Package
10 |
11 | on:
12 | release:
13 | types: [published]
14 |
15 | permissions:
16 | contents: read
17 |
18 | jobs:
19 | deploy:
20 |
21 | runs-on: ubuntu-latest
22 |
23 | steps:
24 | - uses: actions/checkout@v3
25 | - name: Set up Python
26 | uses: actions/setup-python@v3
27 | with:
28 | python-version: '3.x'
29 | - name: Install dependencies
30 | run: |
31 | python -m pip install --upgrade pip
32 | pip install build
33 | - name: Build package
34 | run: python -m build
35 | - name: Publish package
36 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
37 | with:
38 | user: __token__
39 | password: ${{ secrets.PYPI_API_TOKEN }}
40 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *~
2 | *.pyc
3 | *.backup
4 | *.png
5 | *.nc
6 | *.kate-swp
7 | .nfs*
8 | *FRIEDHOF.py
9 | IMProToo.egg-info
10 | build
11 | dist
12 | .DS_Store
13 | .eggs
--------------------------------------------------------------------------------
/IMProToo/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | """
3 | IMProToo
4 | Improved MRR Processing Tool
5 | """
6 | from __future__ import division
7 |
8 |
9 | from .core import *
10 | from .core import __version__
11 | from .tools import *
12 |
--------------------------------------------------------------------------------
/IMProToo/core.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | '''
3 | IMProToo
4 | Improved MRR Processing Tool
5 |
6 | Python toolkit to read, write and process MRR Data. Raw Data, Average and
7 | Instantaneous Data are supported.
8 |
9 | Copyright (C) 2011-2021 Maximilian Maahn, U Leipzig
10 | maximilian.maahn_AT_uni-leipzig.de
11 | https://github.com/maahn/IMProToo
12 |
13 |
14 | This program is free software: you can redistribute it and/or modify
15 | it under the terms of the GNU General Public License as published by
16 | the Free Software Foundation, either version 3 of the License, or
17 | any later version.
18 |
19 | This program is distributed in the hope that it will be useful,
20 | but WITHOUT ANY WARRANTY; without even the implied warranty of
21 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 | GNU General Public License for more details.
23 |
24 | You should have received a copy of the GNU General Public License
25 | along with this program. If not, see .
26 |
27 | '''
28 |
29 | from __future__ import division
30 | from __future__ import print_function
31 |
32 | import numpy as np
33 | import gzip
34 | import re
35 | import datetime
36 | import calendar
37 | import time
38 | import glob
39 | from copy import deepcopy
40 | import warnings
41 | import sys
42 | import os
43 | import codecs
44 |
45 | from .tools import unix2date, date2unix, limitMaInidces, quantile
46 | from .tools import oneD2twoD, _get_netCDF_module
47 |
48 | try:
49 | from importlib.metadata import version, PackageNotFoundError
50 | py3 = True
51 | except ImportError:
52 | from pkg_resources import get_distribution, DistributionNotFound
53 | py3 = False
54 |
55 | if py3:
56 | try:
57 | __version__ = version("IMProToo")
58 | except PackageNotFoundError:
59 | # package is not installed
60 | pass
61 | else:
62 | try:
63 | __version__ = get_distribution("IMProToo").version
64 | except DistributionNotFound:
65 | # package is not installed
66 | pass
67 |
68 |
69 | class MrrZe:
70 | '''
71 | class to calculate the 'real' MRR Ze from MRR raw data. The spectra are
72 | noise corrected and dealiased. see batch_convert_rawData.py for
73 | exemplary use
74 | '''
75 | warnings.filterwarnings('always', '.*', UserWarning,)
76 |
77 | def __init__(self, rawData):
78 |
79 | if rawData.mrrRawCC == 0:
80 | print('WARNING: MRR calibration constant set to 0!')
81 |
82 | self.co = dict()
83 |
84 | # verbosity
85 | self.co["debug"] = 0
86 |
87 | # ######MRR Settings#######
88 |
89 | # mrr frequency, MRR after 2011 (or upgraded) use 24.23e9
90 | self.co["mrrFrequency"] = 24.15e9 # in Hz,
91 | # wavelength in m
92 | self.co["lamb"] = 299792458. / self.co["mrrFrequency"]
93 | # mrr calibration constant
94 | self.co["mrrCalibConst"] = rawData.mrrRawCC
95 |
96 | # do not change these values, unless you have a non standard MRR!
97 | # nyquist range minimum
98 | self.co["nyqVmin"] = 0
99 | # nyquist range maximum
100 | self.co["nyqVmax"] = 11.9301147
101 | # nyquist delta
102 | self.co["nyqVdelta"] = 0.1893669
103 | # list with nyquist velocities
104 | self.co["nyqVel"] = np.arange(
105 | self.co["nyqVmin"],
106 | self.co["nyqVmax"]+0.0001,
107 | self.co["nyqVdelta"]
108 | )
109 | # spectral resolution
110 | self.co["widthSpectrum"] = 64
111 | # min height to be processed
112 | self.co["minH"] = 1 # start counting at 0
113 | # max height to be processed
114 | self.co["maxH"] = 31 # start counting at 0
115 | # no of processed heights
116 | self.co["noH"] = self.co["maxH"]+1 - self.co["minH"]
117 | # shape of spectrum for one time step
118 | self.co["specShape"] = (self.co["noH"], self.co["widthSpectrum"],)
119 | # input data MRR averaging time
120 | self.co["averagingTime"] = 10
121 | # |K**2| dielectric constant
122 | self.co["K2"] = 0.92
123 |
124 | # ######options for finding peaks#######
125 |
126 | # minimum width of a peak. if set to 4 instead of 3, more clutter is
127 | # removed, but sensitivity becomes worse.
128 | self.co["findPeak_minPeakWidth"] = 3
129 | # minimum standard deviation of of spectrum for peak
130 | # self.co["findPeak_minStdPerS"]/np.sqrt(self.co["averagingTime"])
131 | self.co["findPeak_minStdPerS"] = 0.6
132 | # minimum difference of Doppler velocity from self.co["nyqVmax"]/2 for
133 | # peak
134 | self.co["findPeak_minWdiff"] = 0.2
135 |
136 | # ######options for getting peaks#######
137 |
138 | # method for finding peaks in the spectrum, either based on Hildebrand
139 | # and Sekhon, 1974 [hilde] or on the method of descending average
140 | # [descAve]. [hilde] is recommended
141 | self.co["getPeak_method"] = "hilde" # ["hilde","descAve"]
142 | # sometimes the first method fails and almost the whole spectrum is
143 | # found as a peak, so apply a second check based on the remaining
144 | # method from [hilde,descAve]
145 | self.co["getPeak_makeDoubleCheck"] = True
146 | # apply double check to peaks wider than xx*noOfSpec
147 | # wider real peaks can actually happen! These are usually bimodal
148 | # peaks, descending average method fails for them, thus the spectrum
149 | self.co["getPeak_makeDoubleCheck_minPeakWidth"] = 0.9
150 | # hilde method uses an extra buffer to avoid to large peaks. loop stops
151 | # first at spectrum >= self.co["getPeak_hildeExtraLimit"]*hilde_limit,
152 | # only one more bin is added if above self.co[
153 | # "getPeak_hildeExtraLimit"]. More bins above self.co[
154 | # "getPeak_hildeExtraLimit"] are ignored
155 | self.co["getPeak_hildeExtraLimit"] = 1.2 # times hildebrand limit
156 | # options for descAve method
157 | # window to calculate the average, if too large, it might go into the
158 | # next peak! if too small, it might not catch bimodal distributions
159 | self.co["getPeak_descAveCheckWidth"] = 10
160 | # descAve stops not before mean is smaller than self.co[
161 | # "getPeak_descAveMinMeanWeight"] of the mean of the self.co[
162 | # "getPeak_descAveCheckWidth"] smallest bins. make very big to turn off
163 | self.co["getPeak_descAveMinMeanWeight"] = 4
164 |
165 | # ####options for confirming peaks ##########
166 | # check whether time/height neighbors of a peak contain a peak as well
167 | self.co["confirmPeak_5x5boxCoherenceTest"] = True
168 | # maximum of other peaks must be within X Doppler-bins of the maximum
169 | # of the tested peak
170 | self.co["confirmPeak_5x5boxCoherenceTest_maxBinDistane"] = 10
171 |
172 | # ######general options#######
173 |
174 | # process only peaks in self.co["spectrumBorderMin"][height]:
175 | # self.co["spectrumBorderMax"][height]
176 | self.co["spectrumBorderMin"] = [5, 4, 3, 2, 2, 2, 2, 2, 2, 2,
177 | 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
178 | 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 5]
179 | self.co["spectrumBorderMax"] = [60, 61, 62, 63, 63, 63, 63, 63, 63,
180 | 63, 63, 63, 63, 63, 63, 63, 63, 63,
181 | 63, 63, 63, 63, 63, 63, 63, 63, 63,
182 | 63, 62, 61, 63]
183 | # interpolate spectrum in between
184 | self.co["interpolateSpectrum"] = True
185 | # extend also peaks to interpolated part
186 | self.co["fillInterpolatedPeakGaps"] = True
187 | # mask everything in these heights, since they are disturbed
188 | self.co["completelyMaskedHeights"] = [0, 1, 30]
189 | # first height with trustful peaks. Setting important for dealiasing
190 | # to avoid folding from completelyMaskedHeights into the first used#
191 | # height.
192 | self.co["firstUsedHeight"] = 2
193 |
194 | # ######dealiasing options#######
195 |
196 | # dealiase spectrum yes/no
197 | self.co["dealiaseSpectrum"] = True
198 | # save also non dealiased eta, Ze, W, Znoise specWidth,
199 | # peakVelLeftBorder, peakVelRightBorder
200 | self.co["dealiaseSpectrum_saveAlsoNonDealiased"] = True
201 | # make sure there is only one peak per height after dealiasing!
202 | self.co["dealiaseSpectrum_maxOnePeakPerHeight"] = True
203 | # dealiasing is based on comparison with reference velocity calculated
204 | # from reflectivity. v = A*Ze**B
205 | # Atlas et al. 1973
206 | self.co['dealiaseSpectrum_Ze-vRelationSnowA'] = 0.817
207 | # Atlas et al. 1973
208 | self.co['dealiaseSpectrum_Ze-vRelationSnowB'] = 0.063
209 | # Atlas et al. 1973
210 | self.co['dealiaseSpectrum_Ze-vRelationRainA'] = 2.6
211 | # Atlas et al. 1973
212 | self.co['dealiaseSpectrum_Ze-vRelationRainB'] = 0.107
213 | # trusted peak needs minimal Ze
214 | self.co['dealiaseSpectrum_trustedPeakminZeQuantile'] = 0.1
215 | # if you have interference, you don't want to start you dealiasing
216 | # procedure there
217 | self.co["dealiaseSpectrum_heightsWithInterference"] = []
218 | # test coherence of dealiasesd velocity spectrum in time dimension.
219 | # try to refold short jumps.
220 | self.co["dealiaseSpectrum_makeCoherenceTest"] = True
221 | # if the height averaged velocity between to timesteps is larger than
222 | # this, it is tried to refold the spectrum
223 | self.co["dealiaseSpectrum_makeCoherenceTest_velocityThreshold"] = 8
224 | # if there are after coherence test still velocity jumps, mask
225 | # +/- timesteps
226 | self.co["dealiaseSpectrum_makeCoherenceTest_maskRadius"] = 10
227 |
228 | # ######netCDF options#######
229 |
230 | self.co["ncCreator"] = "IMProToo user"
231 | self.co["ncDescription"] = "MRR data processed with IMProToo"
232 | self.co["ncLocation"] = ""
233 | self.co["ncInstitution"] = ""
234 |
235 | # ######end of settings#######
236 |
237 | # special option to top processing in the middel and return results
238 | self.debugStopper = 0
239 |
240 | self.missingNumber = -9999.
241 |
242 | self.header = rawData.header
243 | self.time = rawData.mrrRawTime
244 | self.timezone = rawData.timezone
245 | self.H = rawData.mrrRawHeight[:, self.co["minH"]:self.co["maxH"]+1]
246 | self.TF = rawData.mrrRawTF[:, self.co["minH"]:self.co["maxH"]+1]
247 | self.rawSpectrum = rawData.mrrRawSpectrum[
248 | :, self.co["minH"]:self.co["maxH"]+1
249 | ]
250 | self.noSpecPerTimestep = rawData.mrrRawNoSpec
251 |
252 | self.no_h = np.shape(self.H)[1]
253 | self.no_t = np.shape(self.time)[0]
254 | self.no_v = self.co["widthSpectrum"]
255 |
256 | self._shape2D = np.shape(self.H)
257 | self._shape3D = np.shape(self.rawSpectrum)
258 |
259 | self.qual = dict()
260 |
261 | return
262 |
263 | def averageSpectra(self, averagingTime):
264 | """
265 | average spectra and other data. If averaging time is e.g. 60, the
266 | data with the timestamp 14:00 contains all measurements from 13:59:00
267 | to 13:59:59 (like MRR standard software)
268 | """
269 |
270 | rawSpectra = self.rawSpectrum
271 | rawTimestamps = self.time
272 | heights = self.H
273 | TFs = self.TF
274 | noSpec = self.noSpecPerTimestep
275 |
276 | # find first entry
277 | startSeconds = unix2date(rawTimestamps[0]).second
278 | start = rawTimestamps[0] + averagingTime - startSeconds
279 | # find last minute
280 | endSeconds = unix2date(rawTimestamps[-1]).second
281 | end = rawTimestamps[-1] + 60 - endSeconds
282 | # make new time vector and
283 | rawTimestampsAve = np.ma.arange(
284 | start, end+averagingTime, averagingTime, dtype="int")
285 |
286 | # create new arrays
287 | newSpectraShape = list(rawSpectra.shape)
288 | newSpectraShape[0] = rawTimestampsAve.shape[0]
289 | rawSpectraAve = np.ma.zeros(newSpectraShape) * np.nan
290 |
291 | newTFsShape = list(TFs.shape)
292 | newTFsShape[0] = rawTimestampsAve.shape[0]
293 | TFsAve = np.ma.zeros(newTFsShape) * np.nan
294 |
295 | newHeightsShape = list(heights.shape)
296 | newHeightsShape[0] = rawTimestampsAve.shape[0]
297 | heightsAve = np.ma.zeros(newHeightsShape) * np.nan
298 |
299 | newNoSpecShape = (rawTimestampsAve.shape[0],)
300 | noSpecAve = np.ma.zeros(newNoSpecShape, dtype=int)
301 |
302 | # ugly loop trough new, averaged time vector!
303 | for t, timestamp in enumerate(rawTimestampsAve):
304 | # boolean array containing the wanted entries
305 | booleanTimes = (rawTimestamps < timestamp) * \
306 | (rawTimestamps >= timestamp-averagingTime)
307 | aveLength = np.sum(booleanTimes)
308 | # proceed only if entries were found
309 | if aveLength != 0:
310 | # and if TF and heights are NOT changing and if heights are
311 | # not zero!!
312 | if (
313 | np.all(TFs[booleanTimes] == TFs[booleanTimes][0]) and
314 | np.all(heights[booleanTimes] == heights[booleanTimes][0])
315 | and np.logical_not(np.all(heights[booleanTimes] == 0))
316 | ):
317 | # averaging:
318 | rawSpectraAve[t] = np.ma.average(
319 | rawSpectra[booleanTimes], axis=0)
320 | heightsAve[t] = np.ma.average(
321 | heights[booleanTimes], axis=0)
322 | TFsAve[t] = np.ma.average(TFs[booleanTimes], axis=0)
323 | noSpecAve[t] = np.ma.sum(noSpec[booleanTimes])
324 | else:
325 | print("Skipping data due to changed MRR configuration!")
326 | else:
327 | rawSpectraAve[t] = np.nan
328 | heightsAve[t] = np.nan
329 | TFsAve[t] = np.nan
330 | noSpecAve[t] = 0
331 | print("No Data at " + str(unix2date(timestamp)))
332 |
333 | self.rawSpectrum = rawSpectraAve
334 | self.time = rawTimestampsAve
335 | self.H = heightsAve
336 | self.TF = TFsAve
337 | self.noSpecPerTimestep = noSpecAve.filled(0)
338 |
339 | self.no_t = np.shape(self.time)[0]
340 | self._shape2D = np.shape(self.H)
341 | self._shape3D = np.shape(self.rawSpectrum)
342 |
343 | self.co["averagingTime"] = averagingTime
344 | return
345 |
346 | def getSub(self, start, stop):
347 | """
348 | cut out some spectra (for debugging)
349 |
350 | start,stop (int): border indices
351 | """
352 | if stop == -1:
353 | stop = self._shape2D[0]
354 |
355 | self.rawSpectrum = self.rawSpectrum[start:stop]
356 | self.time = self.time[start:stop]
357 | self.H = self.H[start:stop]
358 | self.TF = self.TF[start:stop]
359 | self.noSpecPerTimestep = self.noSpecPerTimestep[start:stop]
360 |
361 | if len(self.noSpecPerTimestep) == 0:
362 | raise ValueError('getSub: No data lef!')
363 |
364 | self.no_t = np.shape(self.time)[0]
365 | self._shape2D = np.shape(self.H)
366 | self._shape3D = np.shape(self.rawSpectrum)
367 |
368 | return
369 |
370 | def rawToSnow(self):
371 | '''
372 | core function for calculating Ze and other moments. Settings have
373 | to be set before
374 | '''
375 |
376 | if self.co["mrrCalibConst"] == 0:
377 | raise IOError('ERROR: MRR calibration constant set to 0!')
378 |
379 | self.untouchedRawSpectrum = deepcopy(self.rawSpectrum)
380 |
381 | self.specVel = self.co["nyqVel"]
382 | self.specVel3D = np.zeros(self._shape3D)
383 | self.specVel3D[:] = self.specVel
384 |
385 | self.specIndex = np.arange(self.no_v)
386 |
387 | self._specBorderMask = np.ones(self.co["specShape"], dtype=bool)
388 | for h in range(self.co["noH"]):
389 | self._specBorderMask[h, self.co["spectrumBorderMin"]
390 | [h]:self.co["spectrumBorderMax"][h]] = False
391 | self._specBorderMask3D = np.ones(self._shape3D, dtype=bool)
392 | self._specBorderMask3D[:] = self._specBorderMask
393 |
394 | # but we have to apply the TF before we start anything:
395 | TF3D = np.zeros(self._shape3D)
396 | TF3D.T[:] = self.TF.T
397 | self.rawSpectrum = np.ma.masked_array(
398 | self.rawSpectrum.data / TF3D, self.rawSpectrum.mask)
399 |
400 | # 1)missing spectra
401 | missingMask = np.any(np.isnan(self.rawSpectrum.data), axis=-1)
402 | self.qual["incompleteSpectrum"] = missingMask
403 | # 2) Wdiff
404 | WdiffMask, self.wdiffs = self._testMeanW(self.rawSpectrum)
405 |
406 | # 3) std
407 | stdMask, self.stds = self._testStd(self.rawSpectrum)
408 |
409 | # join the results
410 | noiseMask = missingMask+(stdMask*WdiffMask)
411 | self.qual["spectrumVarianceTooLowForPeak"] = stdMask * \
412 | WdiffMask # 2) no signal detected by variance test
413 |
414 | # make 3D noise Mask
415 | noiseMaskLarge = np.zeros(self._shape3D, dtype=bool).T
416 | noiseMaskLarge[:] = noiseMask.T
417 | noiseMaskLarge = noiseMaskLarge.T
418 |
419 | # we don't need the mask right now since missingMask contains all
420 | # mask entries
421 | self.rawSpectrum = self.rawSpectrum.data
422 |
423 | if self.debugStopper == 1:
424 | self.rawSpectrum = np.ma.masked_array(
425 | self.rawSpectrum, noiseMaskLarge)
426 | return
427 | # find the peak
428 | peakMask = np.ones(self._shape3D, dtype=bool)
429 | self.qual["usedSecondPeakAlgorithmDueToWidePeak"] = np.zeros(
430 | self._shape2D, dtype=bool)
431 | self.qual["peakTooThinn"] = np.zeros(self._shape2D, dtype=bool)
432 | for h in range(0, self.co["noH"]):
433 | # check whether there is anything to do
434 | if np.any(np.logical_not(noiseMaskLarge[:, h])):
435 | # get the peak
436 | specMins = self.co["spectrumBorderMin"][h]
437 | specMaxs = self.co["spectrumBorderMax"][h]
438 | res = self._getPeak(
439 | self.rawSpectrum[:, h, specMins:specMaxs][
440 | ~noiseMask[:, h]],
441 | self.noSpecPerTimestep[~noiseMask[:, h]],
442 | h
443 | )
444 | (
445 | peakMask[:, h, specMins:specMaxs][~noiseMask[:, h]],
446 | self.qual["peakTooThinn"][:, h][~noiseMask[:, h]],
447 | self.qual["usedSecondPeakAlgorithmDueToWidePeak"][:, h][
448 | ~noiseMask[:, h]]
449 | ) = res
450 | # apply results
451 | self.rawSpectrum = np.ma.masked_array(self.rawSpectrum, peakMask)
452 |
453 | # what is the noise, but _without_ the borders, we want in noise 3D
454 | # also
455 | noise = np.ma.masked_array(self.rawSpectrum.data, (np.logical_not(
456 | self.rawSpectrum.mask)+self._specBorderMask3D))
457 | self.specNoise = np.ma.average(noise, axis=-1).filled(0)
458 |
459 | if self.debugStopper == 2:
460 | return
461 |
462 | if self.co["confirmPeak_5x5boxCoherenceTest"]:
463 | coherCheckNoiseMask = self._cleanUpNoiseMask(self.rawSpectrum)
464 | coherCheckNoiseMask3D = np.zeros(self._shape3D, dtype=bool)
465 | coherCheckNoiseMask3D.T[:] = coherCheckNoiseMask.T
466 | else:
467 | coherCheckNoiseMask = np.zeros(self._shape2D, dtype=bool)
468 | coherCheckNoiseMask3D = np.zeros(self._shape3D, dtype=bool)
469 | self.qual["peakRemovedByCoherenceTest"] = coherCheckNoiseMask * \
470 | (~np.all(self.rawSpectrum.mask, axis=-1))
471 |
472 | self.rawSpectrum.mask = self.rawSpectrum.mask + coherCheckNoiseMask3D
473 | if self.debugStopper == 3:
474 | return
475 |
476 | # since we have removed more noisy spectra we have to calculate the
477 | # noise again
478 | noise = np.ma.masked_array(self.rawSpectrum.data, (np.logical_not(
479 | self.rawSpectrum.mask)+self._specBorderMask3D))
480 | self.specNoise = np.ma.average(noise, axis=-1).filled(0)
481 | self.specNoise_std = np.ma.std(noise, axis=-1).filled(0)
482 | self.specNoise3D = np.zeros_like(noise).filled(0)
483 | self.specNoise3D.T[:] = self.specNoise.T
484 |
485 | # remove the noise
486 | self.rawSpectrum = np.ma.masked_array(
487 | self.rawSpectrum.data - self.specNoise3D, self.rawSpectrum.mask)
488 |
489 | if self.co["interpolateSpectrum"]:
490 | # interpolate spectrum
491 | intSpectrum = deepcopy(self.rawSpectrum.data)
492 | ix = np.arange(len(self.rawSpectrum.ravel()))
493 | intSpectrum[self._specBorderMask3D] = np.interp(
494 | ix[self._specBorderMask3D.ravel()],
495 | ix[~self._specBorderMask3D.ravel()],
496 | self.rawSpectrum[~self._specBorderMask3D]
497 | )
498 |
499 | self.rawSpectrum = np.ma.masked_array(
500 | intSpectrum, self.rawSpectrum.mask)
501 | self.qual["interpolatedSpectrum"] = np.ones(
502 | self._shape2D, dtype=bool)
503 | if self.debugStopper == 5:
504 | return
505 | else:
506 | self.qual["interpolatedSpectrum"] = np.zeros(
507 | self._shape2D, dtype=bool)
508 |
509 | if self.co["fillInterpolatedPeakGaps"]:
510 | (
511 | self.rawSpectrum.mask,
512 | self.qual["filledInterpolatedPeakGaps"]
513 | ) = self._fillInterpolatedPeakGaps(self.rawSpectrum.mask)
514 | else:
515 | self.qual["filledInterpolatedPeakGaps"] = np.zeros(
516 | self._shape2D, dtype=bool)
517 |
518 | # calculate the (not dealiased) SNR
519 | self.SNR = (10*np.ma.log10(np.ma.sum(self.rawSpectrum, axis=-1) /
520 | (self.specNoise*self.co["widthSpectrum"]))).filled(-9999)
521 |
522 | if self.co["dealiaseSpectrum"] == True:
523 |
524 | if self.co["dealiaseSpectrum_saveAlsoNonDealiased"] == True:
525 | self.eta_noDA, self.Ze_noDA, self.W_noDA, self.etaNoiseAve_noDA_TBD, self.etaNoiseStd_noDA_TBD, self.specWidth_noDA, self.skewness_noDA, self.kurtosis_noDA, self.peakVelLeftBorder_noDA, self.peakVelRightBorder_noDA, self.leftSlope_noDA, self.rightSlope_noDA = self._calcEtaZeW(
526 | self.rawSpectrum, self.H, self.specVel3D, self.specNoise, self.specNoise_std)
527 | self.qual_noDA = deepcopy(self.qual)
528 |
529 | # can be deleted, is identical to self.etaNoise, because noise is not dealiased.
530 | del self.etaNoiseAve_noDA_TBD, self.etaNoiseStd_noDA_TBD
531 |
532 | self.rawSpectrum = self._dealiaseSpectrum(self.rawSpectrum)
533 | # since we don't want that spectrum from teh disturbed 1st range gate are folded into the secod on, peaks in the second one might be incomplete. try to make an entry in the quality mask.
534 | self.qual["peakMightBeIncomplete"] = np.zeros(
535 | self._shape2D, dtype=bool)
536 | self.qual["peakMightBeIncomplete"][:, self.co["firstUsedHeight"]][self.rawSpectrum.mask[:, self.co["firstUsedHeight"],
537 | self.co["widthSpectrum"]+self.co["spectrumBorderMin"][self.co["firstUsedHeight"]]] == False] = True
538 |
539 | # no dealiasing
540 | else:
541 | pass
542 | self.eta, self.Ze, self.W, self.etaNoiseAve, self.etaNoiseStd, self.specWidth, self.skewness, self.kurtosis, self.peakVelLeftBorder, self.peakVelRightBorder, self.leftSlope, self.rightSlope = self._calcEtaZeW(
543 | self.rawSpectrum, self.H, self.specVel3D, self.specNoise, self.specNoise_std)
544 | # make bin mask out of quality information
545 | self.qualityBin, self.qualityDesc = self.getQualityBinArray(self.qual)
546 | return
547 |
548 | def _testMeanW(self, rawSpectrum):
549 | '''
550 | checks whether spectrum mean velocity is unequal to mean velocity (6m s^-1)
551 | '''
552 |
553 | mask = deepcopy(rawSpectrum.mask) + self._specBorderMask3D
554 | spec = np.ma.masked_array(rawSpectrum.data, mask)
555 | velocity = np.ma.masked_array(self.specVel3D, self._specBorderMask3D)
556 |
557 | Wdiff = np.absolute(np.ma.average(
558 | velocity, axis=-1)-(np.ma.sum(velocity*spec, axis=-1)/np.sum(spec, axis=-1)))
559 |
560 | noiseMask = Wdiff.filled(0) < self.co["findPeak_minWdiff"]
561 |
562 | return noiseMask, Wdiff.filled(0)
563 |
564 | def _testStd(self, rawSpectrum):
565 | '''
566 | checks whether spectrum passes variance limit
567 | '''
568 |
569 | mask = deepcopy(rawSpectrum.mask) + self._specBorderMask3D
570 | spec = np.ma.masked_array(rawSpectrum.data, mask)
571 |
572 | std = (np.ma.std(spec, axis=-1)/np.ma.mean(spec, axis=-1))
573 |
574 | # the 5.7 is because we have typically 5.7 spectra per second and this
575 | # quantitiy was defined with self.co["averagingTime"] instead of
576 | # self.noSpecPerTimestep before
577 | maxStd = self.co["findPeak_minStdPerS"] / \
578 | np.sqrt(self.noSpecPerTimestep/5.7)
579 |
580 | return std.filled(0) < maxStd[:, np.newaxis], std.filled(0)
581 |
582 | def _findAddtionalPeaks(self, rawSpectrum):
583 | '''
584 | This functio tries to find addtional peaks in the spectrum
585 |
586 | disabled since it gives too many false positives...
587 |
588 | '''
589 | qual = np.zeros(self._shape2D, dtype=bool)
590 |
591 | # invert mask
592 | rawSpectrum = np.ma.masked_array(rawSpectrum.data, ~rawSpectrum.mask)
593 | self.co["findAddtionalPeaksThreshold"] = 15
594 | for tt in range(self.no_t):
595 | for hh in range(self.no_h):
596 | if hh in self.co["completelyMaskedHeights"]:
597 | continue
598 | greaterZero = 0
599 | for ii in range(self.co["spectrumBorderMin"][hh], self.co["spectrumBorderMax"][hh]):
600 | if greaterZero >= self.co["findAddtionalPeaksThreshold"]:
601 | qual[tt, hh] = True
602 | if rawSpectrum.mask[tt, hh, ii] == True or rawSpectrum.data[tt, hh, ii] <= 0:
603 | greaterZero = 0
604 | continue
605 | else:
606 | greaterZero += 1
607 |
608 | return qual
609 |
610 | def _cleanUpNoiseMask(self, spectrum):
611 | """
612 | 11 of 5x5 points in height/time space must have a signal to be valid!
613 |
614 | @parameter spectrum (numpy masked float): spectrum + noiseMask to be applied to teh data
615 | @return - newMask (numpy boolean):numpy boolean noiseMask
616 | """
617 |
618 | noiseMask = np.all(spectrum.mask, axis=-1)
619 | newMask = deepcopy(noiseMask)
620 | # make it bigger to cover edges for 5x5 test, 2 pixel border
621 | maxs = np.ma.masked_all((self.no_t+4, self.no_h+1))
622 | maxs[2:-2, 2:-2] = np.ma.masked_array(
623 | np.ma.argmax(spectrum, axis=-1), noiseMask)[:, 2:30]
624 |
625 | highLimit = 11
626 | lowLimit = 9
627 | lowestLimit = 8
628 |
629 | hOffset = self.co["minH"] # since we don't start at zero height
630 |
631 | # loop through all points...
632 | for t in np.arange(self.no_t):
633 | # is it real signal? only if at least 11 of 25 neigbours have signal as well!
634 | # for h in np.arange(4,28):
635 | for h in np.arange(2, 30):
636 | if noiseMask[t, h] == False:
637 | tSM = t+2 # for subMaxs t needs to be 2 larger due to 2 pixel border! for h not neccesary, 2 pixel border at botztom already there
638 | subMaxs = maxs[tSM-2:tSM+3, h-2:h+3]
639 | thisMaxsDiff = 32-maxs[tSM, h]
640 | subMaxsNormed = limitMaInidces(subMaxs + thisMaxsDiff, 64)
641 | diffs = np.abs(subMaxsNormed - 32)
642 |
643 | if t in [0, self.no_t-1] or h in [2, 29]:
644 | limit = lowestLimit
645 | elif t in [1, self.no_t-2] or h in [3, 28]:
646 | limit = lowLimit
647 | else:
648 | limit = highLimit
649 |
650 | if np.ma.sum(diffs <= self.co["confirmPeak_5x5boxCoherenceTest_maxBinDistane"]) < limit:
651 | newMask[t, h] = True
652 |
653 | # kick out heights #0,1,30
654 | newMask[:, self.co["completelyMaskedHeights"]] = True
655 |
656 | self.qual["spectrumNotProcessed"] = np.zeros(self._shape2D, dtype=bool)
657 | self.qual["spectrumNotProcessed"][:,
658 | self.co["completelyMaskedHeights"]] = True
659 |
660 | return newMask
661 |
662 | def _getPeak(self, spectrum, noSpecs, h):
663 | """
664 | get the peak of the spectrum, first getPeakHildebrand is used, if the spectrum is wider than 10 and makeDoubleCheck = True, also getPeakDescendingAve is used and the smaller one is taken!
665 |
666 | @parameter spectrum (numpy float64): (averaged, dealiased) raw data from MRR Raw data
667 | @parameter noSpecs (numpy float64):number of single spectras which belong to each average spectrum, usually 58* No of averaged spectra
668 | @paramter h, (int): height, for easier debugging
669 | @return - spectrum (numpy float64): masked(!) spectrum
670 | @return - qualiy (dict with array bool)
671 | """
672 | t = time.time()
673 | quality = dict()
674 |
675 | specLength = np.shape(spectrum)[-1]
676 | # get maxima of reduced spectra
677 | iMax = np.argmax(spectrum, axis=-1)
678 | iMaxFlat = np.ravel(iMax)
679 | # arrays don't work, so make them flat
680 | spectrumFlat = np.reshape(spectrum, (-1, specLength))
681 |
682 | if self.co["getPeak_method"] == "hilde":
683 | # get peak using Hildebrands method
684 | firstPeakMask = self._getPeakHildebrand(
685 | spectrumFlat, iMaxFlat, noSpecs, h)
686 | elif self.co["getPeak_method"] == "descAve":
687 | # get peak using Hildebrands method
688 | firstPeakMask = self._getPeakDescendingAve(spectrumFlat, iMaxFlat)
689 | else:
690 | raise ValueError("Unknown doubleCheckPreference: " +
691 | self.co["getPeak_method"])
692 |
693 | peakMask = deepcopy(firstPeakMask)
694 | # look for wide peak and make a second check
695 | if self.co["getPeak_makeDoubleCheck"]:
696 | doubleCheck = np.sum(np.logical_not(
697 | firstPeakMask), axis=-1) > specLength * self.co["getPeak_makeDoubleCheck_minPeakWidth"]
698 | quality["veryWidePeakeUsedSecondPeakAlgorithm"] = doubleCheck
699 | if np.any(doubleCheck == True):
700 | #secondPeakMVeryWidePeakeUask = getPeakDescendingAve(spectrumFlat,iMaxFlat)
701 | secondPeakMask = np.zeros(np.shape(spectrumFlat), dtype=bool)
702 | if self.co["getPeak_method"] == "hilde":
703 | # get peak using desc Average method
704 | secondPeakMask[doubleCheck] = self._getPeakDescendingAve(
705 | spectrumFlat[doubleCheck], iMaxFlat[doubleCheck])
706 | elif self.co["getPeak_method"] == "descAve":
707 | # get peak using Hildebrands method
708 | secondPeakMask[doubleCheck] = self._getPeakHildebrand(
709 | spectrumFlat[doubleCheck], iMaxFlat[doubleCheck], noSpecs[doubleCheck], h)
710 | peakMask[doubleCheck] = firstPeakMask[doubleCheck] + \
711 | secondPeakMask[doubleCheck]
712 | else:
713 | quality["veryWidePeakeUsedSecondPeakAlgorithm"] = np.zeros(
714 | specLength, dtype=bool)
715 | # only peaks which are at least 3 bins wide, remove the others
716 | tooThinn = np.sum(np.logical_not(peakMask), axis=-
717 | 1) < self.co["findPeak_minPeakWidth"]
718 | peakMask[tooThinn] = True
719 | quality["peakTooThinn"] = tooThinn * (np.sum(~peakMask, axis=-1) != 0)
720 |
721 | if self.co["debug"] > 0:
722 | print("runtime", time.time()-t, "s")
723 | # spectrum
724 | return np.reshape(peakMask, np.shape(spectrum)), quality["peakTooThinn"], quality["veryWidePeakeUsedSecondPeakAlgorithm"]
725 |
726 | # get the border indices belonging to the hildebrand limit
727 |
728 | def _getPeakHildebrand(self, dataFlat, iMax, noSpecs, h):
729 | """
730 | get the peak of the spectrum using Hildebrand algorithm. Note that this routine works
731 | 'the other way around' than e.g. pamtra's or pyart's Hildebrand routine. I.e. we start
732 | with the full spectrum and remove the largest bins instead of starting with the
733 | smallest values and adding larger ones. This is more robust for the MRR. also
734 | getPeak_hildeExtraLimit works better for MRR than teh traditional threshold definition from HS74.
735 |
736 | @parameter dataFlat (numpy float64): flat spectrum from MRR Raw data
737 | @parameter iMax (numpy float64): vector containing indices of the maxima
738 | @parameter Nspec (numpy float64): number of spectra of each averaged spectrum
739 |
740 | @return - iPeakMin, iMax (int float64): edges of each spectrum
741 | """
742 |
743 | # first get the limit reflectivity
744 | limits = self._noiseHildebrand(dataFlat, noSpecs, h)
745 | maskHildebrand = np.ones(np.shape(dataFlat), dtype=bool)
746 | iPeakMax = deepcopy(iMax)
747 | iPeakMin = deepcopy(iMax)
748 |
749 | # not only uses extra limit, but also starts at the peak!, thus specturm is refolded around peak!
750 |
751 | # then get the edges of the peak as index of the spectrum
752 | for k in np.arange(iMax.shape[0]):
753 | # unmask the peak
754 | maskHildebrand[k, iMax[k]] = False
755 |
756 | spectrum = np.roll(dataFlat[k], -iMax[k])
757 | mask = np.roll(maskHildebrand[k], -iMax[k])
758 | # to the right
759 | for i in np.arange(1, dataFlat.shape[-1], 1):
760 | # unmask if above limit (=peak)
761 | if spectrum[i] > limits[k]*self.co["getPeak_hildeExtraLimit"]:
762 | mask[i] = False
763 | # else stop
764 | else:
765 | # unmask on last bin if between limits[k]*self.co["getPeak_hildeExtraLimit"] and limits[k], but stop in any case!
766 | if spectrum[i] > limits[k]:
767 | mask[i] = False
768 | break
769 | # to the left
770 | for i in np.arange(dataFlat.shape[-1]-1, 0-1, -1):
771 | if spectrum[i] > limits[k]*self.co["getPeak_hildeExtraLimit"]:
772 | mask[i] = False
773 | else:
774 | if spectrum[i] > limits[k]:
775 | mask[i] = False
776 | break
777 |
778 | dataFlat[k] = np.roll(spectrum, iMax[k])
779 | maskHildebrand[k] = np.roll(mask, iMax[k])
780 |
781 | return maskHildebrand
782 |
783 | def _noiseHildebrand(self, dataFlat, noSpecs, h, flat=True):
784 | """
785 | #calculate the minimum reflectivity of the peak (or maximum of the noise) according to Hildebrand and Sekhon
786 |
787 | @parameter dataFlat (numpy masked array float64): flat spectrum from MRR Raw data
788 | @parameter Nspec (numpy float64): number of spectra of each averaged spectrum
789 |
790 | @return - limits (int float64): limit reflectivity of each spectrum
791 | """
792 |
793 | specLength = np.shape(dataFlat)[-1]
794 | if flat == False:
795 | dataShape = np.shape(dataFlat)[0]
796 | dataFlat = np.reshape(dataFlat, (-1, specLength))
797 |
798 | # sort the data
799 | dataFlat = np.ma.sort(dataFlat, axis=-1)
800 |
801 | # calculate all variances and means (that is cheaper than a loop!)
802 | # start with whole spectrum, then discard maximum, than second but next maximum etc.
803 | Dvar = np.zeros(dataFlat.shape)
804 | Dmean = np.zeros(dataFlat.shape)
805 | limits = np.zeros(np.shape(dataFlat[..., 0]))
806 | for i in np.arange(specLength-1, 1, -1):
807 | Dvar[..., i] = np.ma.var(dataFlat[..., 0:i], axis=-1)
808 | Dmean[..., i] = np.ma.mean(dataFlat[..., 0:i], axis=-1)
809 | # calculate the Hildebrand coefficient
810 | Dvar[Dvar == 0] = 0.0001
811 | Coefficient = ((Dmean**2) / Dvar)
812 | # check where hildebrands assumption is true
813 | for j in np.arange(np.shape(dataFlat)[0]):
814 | for i in np.arange(specLength-1, -1, -1):
815 | if Coefficient[j, i] >= noSpecs[j]:
816 | limits[j] = dataFlat[j, i-1]
817 | break
818 |
819 | if flat == False:
820 | limits = np.reshape(limits, (dataShape, self.co["noH"]))
821 |
822 | return limits
823 |
824 | def _getPeakDescendingAve(self, dataFlat, iMax):
825 | """
826 | get the peak of the spectrum
827 | function iterates through the _not_ size-sorted spectrum from the maximum to the left and to the right and stops as soon as the average stops decreasing.
828 |
829 | @parameter dataFlat (numpy float64): flat spectrum from MRR Raw data
830 | @parameter iMax (numpy float64): vector containing indices of the maxima
831 |
832 | @return - iPeakMin, iMax (int float64): edges of each spectrum
833 | """
834 |
835 | maskDescAve = np.ones(np.shape(dataFlat), dtype=bool)
836 |
837 | # iterate through spectras:
838 | for k in np.arange(iMax.shape[0]):
839 | # the rolling allow recognition also if 0 m s^-1 is crossed
840 | rolledSpectrum = np.roll(dataFlat[k], -iMax[k])
841 | rolledMask = np.roll(maskDescAve[k], -iMax[k])
842 | meanRightOld = np.ma.mean(
843 | rolledSpectrum[1:self.co["getPeak_descAveCheckWidth"]+1])
844 | meanLeftOld = np.ma.mean(
845 | rolledSpectrum[-1:-(self.co["getPeak_descAveCheckWidth"]+1):-1])
846 | minMeanToBreak = self.co["getPeak_descAveMinMeanWeight"] * np.mean(
847 | np.sort(dataFlat[k])[0:self.co["getPeak_descAveCheckWidth"]])
848 | # unmask peak
849 | rolledMask[0] = False
850 | # to the right:
851 | for i in np.arange(1, dataFlat.shape[-1], 1):
852 | meanRight = np.ma.mean(
853 | rolledSpectrum[i:i+self.co["getPeak_descAveCheckWidth"]])
854 | # is the average still decraesing?
855 | if meanRight <= meanRightOld or meanRight > minMeanToBreak:
856 | rolledMask[i] = False
857 | meanRightOld = meanRight
858 | else:
859 | break
860 | # to the left
861 | for i in np.arange(dataFlat.shape[-1]-1, 0-1, -1):
862 | meanLeft = np.ma.mean(
863 | rolledSpectrum[i:i-self.co["getPeak_descAveCheckWidth"]:-1])
864 | # is the average still decraesing?
865 | if meanLeft <= meanLeftOld or meanLeft > minMeanToBreak:
866 | rolledMask[i] = False
867 | meanLeftOld = meanLeft
868 | else:
869 | break
870 | dataFlat[k] = np.roll(rolledSpectrum, iMax[k])
871 | maskDescAve[k] = np.roll(rolledMask, iMax[k])
872 |
873 | return maskDescAve
874 |
875 | def _fillInterpolatedPeakGaps(self, specMask):
876 | '''
877 | Interpolate gaps of specMask around 0 m s^-1 between spectrumBorderMin and spectrumBorderMax in noH heights
878 | returns updated specMask and quality information
879 | '''
880 | quality = np.zeros(self._shape2D, dtype=bool)
881 | for h in range(1, self.co["noH"]):
882 | # the ones with peaks at both sides around 0 m s^-1!
883 | peaksAroundZero = (specMask[:, h-1, self.co["spectrumBorderMax"][h-1]-1] == False) * (
884 | specMask[:, h, self.co["spectrumBorderMin"][h]] == False)
885 | specMask[:, h, 0:self.co["spectrumBorderMin"]
886 | [h]][peaksAroundZero] = False
887 | specMask[:, h-1, self.co["spectrumBorderMax"]
888 | [h-1]:][peaksAroundZero] = False
889 |
890 | # the ones with peak at only one side,
891 | peaksAroundZeroHalfToLeft = (specMask[:, h-1, self.co["spectrumBorderMax"][h-1]-1] == True) * (
892 | specMask[:, h, self.co["spectrumBorderMin"][h]] == False)
893 | peaksAroundZeroHalfToLeftBMin = (peaksAroundZeroHalfToLeft * (
894 | self.rawSpectrum.data[:, h, 0:self.co["spectrumBorderMin"][h]] > self.specNoise3D[:, h, 0:self.co["spectrumBorderMin"][h]]).T).T
895 | peaksAroundZeroHalfToLeftBMax = (peaksAroundZeroHalfToLeft * (
896 | self.rawSpectrum.data[:, h-1, self.co["spectrumBorderMax"][h-1]:] > self.specNoise3D[:, h, self.co["spectrumBorderMax"][h-1]:]).T).T
897 | specMask[:, h, 0:self.co["spectrumBorderMin"]
898 | [h]][peaksAroundZeroHalfToLeftBMin] = False
899 | specMask[:, h-1, self.co["spectrumBorderMax"]
900 | [h-1]:][peaksAroundZeroHalfToLeftBMax] = False
901 |
902 | peaksAroundZeroHalfToRight = (specMask[:, h-1, self.co["spectrumBorderMax"][h-1]-1] == False) * (
903 | specMask[:, h, self.co["spectrumBorderMin"][h]] == True)
904 | peaksAroundZeroHalfToRightBMin = (peaksAroundZeroHalfToRight * (
905 | self.rawSpectrum.data[:, h, 0:self.co["spectrumBorderMin"][h]] > self.specNoise3D[:, h-1, 0:self.co["spectrumBorderMin"][h]]).T).T
906 | peaksAroundZeroHalfToRightBMax = (peaksAroundZeroHalfToRight * (
907 | self.rawSpectrum.data[:, h-1, self.co["spectrumBorderMax"][h-1]:] > self.specNoise3D[:, h-1, self.co["spectrumBorderMax"][h-1]:]).T).T
908 | specMask[:, h, 0:self.co["spectrumBorderMin"]
909 | [h]][peaksAroundZeroHalfToRightBMin] = False
910 | specMask[:, h-1, self.co["spectrumBorderMax"][h-1] :][peaksAroundZeroHalfToRightBMax] = False
911 |
912 | quality[:, h] = quality[:, h-1] = peaksAroundZero + \
913 | peaksAroundZeroHalfToLeft + peaksAroundZeroHalfToRight
914 |
915 | return specMask, quality
916 |
917 | def _dealiaseSpectrum(self, rawSpectrum):
918 | '''
919 | dealiase Spectrum
920 |
921 | input rawSpectrum
922 | output extendSpectrum with 192 bins
923 | '''
924 | self.qual["severeProblemsDuringDA"] = np.zeros(
925 | self._shape2D, dtype=bool)
926 |
927 | # first locate peaks in raveld specturm
928 | self._allPeaks, self._allPeaksIndices, self._allPeaksMaxIndices, self._allPeaksVelMe, self._allPeaksHeight, self._allPeaksRefV, self._allPeaksZe = self._locatePeaks(
929 | rawSpectrum)
930 |
931 | # find one peaks and its veloci/heigth you trust
932 | self._trustedPeakNo, self._trustedPeakHeight, self._trustedPeakVel, self._trustedPeakHeightStart, self._trustedPeakHeightStop = self._getTrustedPeak(
933 | self._allPeaksZe, self._allPeaksVelMe, self._allPeaksRefV, self._allPeaksMaxIndices, self._allPeaksHeight)
934 |
935 | # now extend spectrum!
936 | extendedRawSpectrum = deepcopy(rawSpectrum.data)
937 | extendedRawSpectrum = np.concatenate((np.roll(
938 | extendedRawSpectrum, 1, axis=1), extendedRawSpectrum, np.roll(extendedRawSpectrum, -1, axis=1)), axis=2)
939 |
940 | # do not apply fo first range gates
941 | extendedRawSpectrum[:, 0, :self.co["widthSpectrum"]] = 0
942 | # and not to the last one
943 | extendedRawSpectrum[:, self.co["noH"] -
944 | 1, 2*self.co["widthSpectrum"]:] = 0
945 | extendedRawSpectrum = np.ma.masked_array(extendedRawSpectrum, True)
946 |
947 | # if wanted, save old values
948 | if self.co["dealiaseSpectrum_saveAlsoNonDealiased"] == True:
949 | self.specVel_noDA = deepcopy(self.specVel)
950 | self.specVel3D_noDA = deepcopy(self.specVel3D)
951 | self.specIndex_noDA = deepcopy(self.specIndex)
952 | self.no_v_noDA = deepcopy(self.no_v)
953 |
954 | # save new velocities
955 | self.specVel = np.array(list(self.co["nyqVel"] - self.co["widthSpectrum"]*self.co["nyqVdelta"])+list(
956 | self.co["nyqVel"])+list(self.co["nyqVel"] + self.co["widthSpectrum"]*self.co["nyqVdelta"]))
957 | self.specVel3D = np.zeros(np.shape(extendedRawSpectrum))
958 | self.specVel3D[:] = self.specVel
959 | self.specIndex = np.arange(3*self.no_v)
960 | self.no_v = self.no_v * 3
961 |
962 | # extend spectrum to 192 bins and unmask best fitting peaks
963 | extendedRawSpectrum = self._findHeightsForPeaks(extendedRawSpectrum, self._trustedPeakNo, self._trustedPeakVel, self._trustedPeakHeight,
964 | self._trustedPeakHeightStart, self._trustedPeakHeightStop, self._allPeaks, self._allPeaksIndices, self._allPeaksVelMe, self._allPeaksHeight)
965 |
966 | if self.co["dealiaseSpectrum_makeCoherenceTest"]:
967 | # simple method to detect falsely folded peaks, works only for 1-2 outliers
968 | extendedRawSpectrum = self._deAlCoherence(extendedRawSpectrum)
969 |
970 | self.qual["spectrumIsDealiased"] = np.all(
971 | extendedRawSpectrum.mask[:, :, self.co["widthSpectrum"]:2*self.co["widthSpectrum"]] != rawSpectrum.mask[:, :], axis=-1)
972 |
973 | # still we don't want peaks at height 0,1,31
974 | extendedRawSpectrum.mask[:, self.co["completelyMaskedHeights"]] = True
975 |
976 | return extendedRawSpectrum
977 |
978 | def _locatePeaks(self, rawSpectrum):
979 | '''
980 | ravel rawSpectrum and try to find one peak per height
981 |
982 | returns time dictonaries with:
983 | allPeaks - time dictonary with lists of the spectral reflectivities for each peak
984 | allPeaksIndices - related indices
985 | allPeaksMaxIndices - time dictonary maximum of each peak
986 | allPeaksVelMe - first guess peak velocity based on the last bin
987 | allPeaksHeight - first guess peak height based on the last bin
988 | allPeaksRefV - expected velocity of each peak based on Ze according to theory
989 | allPeaksZe - time dictonary with lists of first guess Ze for each peak
990 |
991 | '''
992 | allPeaks = dict()
993 | allPeaksIndices = dict()
994 | allPeaksMaxIndices = dict()
995 | allPeaksVelMe = dict()
996 | allPeaksHeight = dict()
997 | allPeaksRefV = dict()
998 | allPeaksZe = dict()
999 | # get velocities of spectrum. we start negative, because first guess height is always defualt height of most right bin of peak
1000 | velMe = np.array(list(
1001 | self.co["nyqVel"] - self.co["widthSpectrum"]*self.co["nyqVdelta"])+list(self.co["nyqVel"]))
1002 |
1003 | for t in np.arange(self.no_t):
1004 | completeSpectrum = self.rawSpectrum[t].ravel()
1005 |
1006 | # skip if there are no peaks in the timestep
1007 | if np.all(completeSpectrum.mask) == True:
1008 | if self.co["debug"] > 4:
1009 | '_locatePeaks: nothing to do at', t
1010 | continue
1011 |
1012 | deltaH = self.H[t, 15] - self.H[t, 14]
1013 |
1014 | peaks = list()
1015 | peaksIndices = list()
1016 | peaksMaxIndices = list()
1017 | peaksVelMe = list()
1018 | peaksHeight = list()
1019 | peaksVref = list()
1020 | peaksZe = list()
1021 |
1022 | peakTmp = list()
1023 | peakTmpInd = list()
1024 | peaksStartIndices = list()
1025 | peaksEndIndices = list()
1026 | truncatingPeak = False
1027 |
1028 | # go through all bins
1029 | for ii, spec in enumerate(completeSpectrum):
1030 | # found peak!
1031 | withinPeak = (completeSpectrum.mask[ii] == False) and (
1032 | truncatingPeak == False)
1033 | if withinPeak:
1034 | peakTmp.append(spec)
1035 | peakTmpInd.append(ii)
1036 | # if the peak length is now larger than the raw spectrum width, then this peak has
1037 | # wrapped around the entire width. Flag will cause the peak to be split in two, because
1038 | # the next step within the loop through completeSpectrum will have withinPeak False.
1039 | if len(peakTmp) >= self.co["widthSpectrum"]:
1040 | truncatingPeak = True
1041 | warnings.warn('Truncated peak early. Masked area has wrapped around spectrum width at ' +
1042 | 'timestemp ' + str(t) + ', bin number ' + str(ii))
1043 | # 3found no peak, but teh last one has to be processed
1044 | elif len(peakTmp) >= self.co["findPeak_minPeakWidth"]:
1045 | # get the height of the LAST entry of the peak, uses int division // !
1046 | peakTmpHeight = peakTmpInd[-1]//self.co["widthSpectrum"]
1047 |
1048 | # reconstruct the non folded indices shifted by 64! since peakTmpInd[-1] is reference
1049 | orgIndex = np.arange(peakTmpInd[-1] % self.co["widthSpectrum"]-len(
1050 | peakTmpInd), peakTmpInd[-1] % self.co["widthSpectrum"])+1+self.co["widthSpectrum"]
1051 |
1052 | # calculate a first guess Ze
1053 | etaSumTmp = np.sum(
1054 | peakTmp * np.array((self.co["mrrCalibConst"] * (peakTmpHeight**2 * deltaH)) / (1e20), dtype=float))
1055 | # in rare cases, Ze is below Zero, maybey since the wrong peak is examined?
1056 | if etaSumTmp <= 0:
1057 | warnings.warn('negative (linear) Ze occured during dealiasing, peak removed at timestep '+str(
1058 | t)+', bin number ' + str(ii)+', most likely at height ' + str(peakTmpHeight))
1059 | self.qual["severeProblemsDuringDA"][t,
1060 | peakTmpHeight] = True
1061 | peakTmp = list()
1062 | peakTmpInd = list()
1063 | continue
1064 | ZeTmp = 1e18*(self.co["lamb"]**4 *
1065 | etaSumTmp/(np.pi**5*self.co["K2"]))
1066 |
1067 | # guess doppler velocity
1068 | peakTmpSnowVel = self.co['dealiaseSpectrum_Ze-vRelationSnowA'] * \
1069 | ZeTmp**self.co['dealiaseSpectrum_Ze-vRelationSnowB']
1070 | peakTmpRainVel = self.co['dealiaseSpectrum_Ze-vRelationRainA'] * \
1071 | ZeTmp**self.co['dealiaseSpectrum_Ze-vRelationRainB']
1072 | peakTmpRefVel = (peakTmpSnowVel + peakTmpRainVel)/2.
1073 |
1074 | # save other features
1075 | peaksVref.append(peakTmpRefVel)
1076 | peaks.append(peakTmp)
1077 | peaksIndices.append(peakTmpInd)
1078 | peaksStartIndices.append(peakTmpInd[0])
1079 | peaksEndIndices.append(peakTmpInd[-1])
1080 |
1081 | peaksMaxIndices.append(np.argmax(peakTmp)+ii-len(peakTmp))
1082 | peaksHeight.append(peakTmpHeight)
1083 | peaksVelMe.append(
1084 | np.sum((velMe[orgIndex[0]:orgIndex[-1]+1]*peakTmp))/np.sum(peakTmp))
1085 | peaksZe.append(ZeTmp)
1086 |
1087 | peakTmp = list()
1088 | peakTmpInd = list()
1089 | truncatingPeak = False
1090 | # small peaks can show up again due to dealiasing, get rid of them:
1091 | elif len(peakTmp) > 0 and len(peakTmp) < self.co["findPeak_minPeakWidth"]:
1092 | peakTmp = list()
1093 | peakTmpInd = list()
1094 | truncatingPeak = False
1095 | # no peak
1096 | else:
1097 | continue
1098 |
1099 | # we want only ONE peak per range gate!
1100 | if self.co["dealiaseSpectrum_maxOnePeakPerHeight"]:
1101 | # get list with peaks, whcih are too much
1102 | peaksTbd = self._maxOnePeakPerHeight(
1103 | t, peaksStartIndices, peaksEndIndices, peaksZe)
1104 | # remove them
1105 | for peakTbd in np.sort(peaksTbd)[::-1]:
1106 | peaks.pop(peakTbd)
1107 | peaksIndices.pop(peakTbd)
1108 | peaksMaxIndices.pop(peakTbd)
1109 | peaksVelMe.pop(peakTbd)
1110 | peaksHeight.pop(peakTbd)
1111 | peaksVref.pop(peakTbd)
1112 | peaksZe.pop(peakTbd)
1113 |
1114 | # if anything was found, save it
1115 | if len(peaks) > 0:
1116 | allPeaks[t] = peaks
1117 | allPeaksIndices[t] = peaksIndices
1118 | allPeaksMaxIndices[t] = peaksMaxIndices
1119 | allPeaksVelMe[t] = peaksVelMe
1120 | allPeaksHeight[t] = peaksHeight
1121 | allPeaksRefV[t] = peaksVref
1122 | allPeaksZe[t] = peaksZe
1123 | # end for t
1124 |
1125 | return allPeaks, allPeaksIndices, allPeaksMaxIndices, allPeaksVelMe, allPeaksHeight, allPeaksRefV, allPeaksZe
1126 |
1127 | def _maxOnePeakPerHeight(self, t, peaksStartIndices, peaksEndIndices, peaksZe):
1128 | '''
1129 | some height will contain more than one peak, try to find them
1130 | returns a list with peaks to be delteted
1131 | '''
1132 |
1133 | peaksStartIndices = np.array(peaksStartIndices)
1134 | peaksEndIndices = np.array(peaksEndIndices)
1135 | peaksZeCopy = np.array(peaksZe)
1136 |
1137 | peaksTbd = list()
1138 |
1139 | for pp, peakStart in enumerate(peaksStartIndices):
1140 | deletePeaks = False
1141 | if peakStart == -9999:
1142 | continue # peak has been deleted
1143 | followingPeaks = (peaksStartIndices >= peakStart) * \
1144 | (peaksStartIndices < peakStart+(1.5*self.co["widthSpectrum"]))
1145 | if (np.sum(followingPeaks) >= 3):
1146 | # if you have three peaks so close together it is cristal clear:
1147 | deletePeaks = True
1148 | elif (np.sum(followingPeaks) == 2):
1149 | # if you have only two they must be close together
1150 | secondPeak = np.where(followingPeaks)[0][1]
1151 | deletePeaks = (
1152 | peaksEndIndices[secondPeak] - peakStart < self.co["widthSpectrum"]/2.)
1153 | if deletePeaks == True:
1154 |
1155 | # don't consider more than 3! the rest is hopefully caught by next loop!
1156 | Indices = np.where(followingPeaks)[0][0:3]
1157 | smallestZe = Indices[np.argmin(peaksZeCopy[Indices])]
1158 | peaksTbd.append(smallestZe)
1159 |
1160 | # these are needed for the loop, so they are only masked, not deleted
1161 | peaksStartIndices[peaksTbd[-1]] = -9999
1162 | peaksEndIndices[peaksTbd[-1]] = -9999
1163 | peaksZeCopy[peaksTbd[-1]] = 9999
1164 |
1165 | return peaksTbd
1166 |
1167 | def _getTrustedPeak(self, allPeaksZe, allPeaksVelMe, allPeaksRefV, allPeaksMaxIndices, allPeaksHeight):
1168 | '''
1169 | find heigth and position of most trustfull peak
1170 |
1171 | allPeaksZe - time dictonary with lists of first guess Ze for each peak
1172 | allPeaksVelMe - first guess peak velocity based on the last bin
1173 | allPeaksRefV - expected velocity of each peak based on Ze according to theory
1174 | allPeaksMaxIndices - time dictonary maximum of each peak
1175 | allPeaksHeight - first guess peak height based on the last bin
1176 |
1177 | returns 1D time arrays
1178 | trustedPeakNo - no of trusted peaks (starting at bottom)
1179 | trustedPeakHeight - estimated height
1180 | trustedPeakVel - -estimated velocity
1181 | trustedPeakHeightStart, trustedPeakHeightStop - start and stop indices from 0:192 range
1182 | '''
1183 | trustedPeakHeight = np.zeros(self.no_t, dtype=int)
1184 | trustedPeakVel = np.zeros(self.no_t)
1185 | trustedPeakNo = np.ones(self.no_t, dtype=int)*-9999
1186 | trustedPeakHeightStart = np.zeros(self.no_t, dtype=int)
1187 | trustedPeakHeightStop = np.zeros(self.no_t, dtype=int)
1188 | for t in np.arange(self.no_t):
1189 | # now process the found peaks
1190 | if t in list(self._allPeaks.keys()):
1191 |
1192 | # the trusted peak needs a certain minimal reflectivity to avoid confusion by interference etc, get the minimum threshold
1193 | averageZe = np.sum(allPeaksZe[t])/float(len(allPeaksZe[t]))
1194 | minZe = quantile(
1195 | self._allPeaksZe[t], self.co['dealiaseSpectrum_trustedPeakminZeQuantile'])
1196 |
1197 | peaksVelMe = np.array(allPeaksVelMe[t])
1198 | peaksVels = np.array([peaksVelMe+self.co["nyqVdelta"]*self.co["widthSpectrum"],
1199 | peaksVelMe, peaksVelMe-self.co["nyqVdelta"]*self.co["widthSpectrum"]])
1200 | refVels = np.array(
1201 | [allPeaksRefV[t], allPeaksRefV[t], allPeaksRefV[t]])
1202 | # this difference between real velocity (thee different ones are tried: dealaisisnmg up, static or down) and expected Ze based velocityhas to be minimum to find trusted peak
1203 | diffs = np.abs(peaksVels - refVels)
1204 |
1205 | # mask small peaks, peaks which are in the firt processed range gate and peaks which are in self.co["dealiaseSpectrum_heightsWithInterference"] (e.g. disturbed by interference)
1206 | diffs = np.ma.masked_array(diffs, [allPeaksZe[t] <= minZe]*3)
1207 | tripplePeaksMaxIndices = np.array(3*[allPeaksMaxIndices[t]])
1208 | # the first used height is a bit special, often peaks are incomplete,try to catch them to avoid trust them
1209 | diffs = np.ma.masked_array(diffs, (tripplePeaksMaxIndices >= self.co["firstUsedHeight"]*self.co["widthSpectrum"])*(
1210 | tripplePeaksMaxIndices < self.co["firstUsedHeight"]*(self.co["widthSpectrum"]*1.5)))
1211 | # now mask all other peaks which are found unlikely
1212 | for hh in self.co["dealiaseSpectrum_heightsWithInterference"]+self.co["completelyMaskedHeights"]:
1213 | diffs = np.ma.masked_array(diffs, (tripplePeaksMaxIndices >= hh*self.co["widthSpectrum"])*(
1214 | tripplePeaksMaxIndices < (hh+1)*self.co["widthSpectrum"]))
1215 |
1216 | # if we managed to mask all peaks, we have no choice but taking all
1217 | if np.all(diffs.mask == True):
1218 | diffs.mask[:] = False
1219 | if self.co["debug"] > 4:
1220 | print("managed to mask all peaks at " + str(t) +
1221 | " while trying to find most trustfull one during dealiasing.")
1222 |
1223 | # the minimum velocity difference tells wehther dealiasing goes up, down or is not applied
1224 | UpOrDn = np.ma.argmin(np.ma.min(diffs, axis=1))
1225 | # get paramters for trusted peaks
1226 | trustedPeakNo[t] = np.ma.argmin(diffs[UpOrDn])
1227 | # -1 to ensure that updraft is negative now!!
1228 | trustedPeakHeight[t] = allPeaksHeight[t][trustedPeakNo[t]] + UpOrDn-1
1229 | trustedPeakSpecShift = trustedPeakHeight[t] * \
1230 | self.co["widthSpectrum"] - self.co["widthSpectrum"]
1231 | trustedPeakVel[t] = peaksVels[UpOrDn][trustedPeakNo[t]]
1232 | # transform back to height related spectrum
1233 | # in dimension of 0:192 #spectrum is extended to the left
1234 | trustedPeakHeightIndices = (np.array(
1235 | self._allPeaksIndices[t][trustedPeakNo[t]])-trustedPeakSpecShift)[[0, -1]]
1236 | trustedPeakHeightStart[t] = trustedPeakHeightIndices[0]
1237 | trustedPeakHeightStop[t] = trustedPeakHeightIndices[-1]
1238 |
1239 | return trustedPeakNo, trustedPeakHeight, trustedPeakVel, trustedPeakHeightStart, trustedPeakHeightStop
1240 |
1241 | def _findHeightsForPeaks(self, extendedRawSpectrum, trustedPeakNo, trustedPeakVel, trustedPeakHeight, trustedPeakHeightStart, trustedPeakHeightStop, allPeaks, allPeaksIndices, allPeaksVelMe, allPeaksHeight):
1242 | '''
1243 | try to find the height of each peak by starting at the trusted peak
1244 | extendedRawSpectrum - extended to 192 bins, returned with new, dealiased mask
1245 | trustedPeakNo - trusted peak number of all peaks in time step
1246 | trustedPeakVel - most liekely velocity
1247 | trustedPeakHeight - most likely height
1248 | trustedPeakHeightStart, trustedPeakHeightStop - start/stop of peaks
1249 | allPeaks - time dictonary with lists of the spectral reflectivities for each peak
1250 | allPeaksIndices - related indices
1251 | allPeaksVelMe - first guess peak velocity based on the last bin
1252 | allPeaksHeight - first guess peak height based on the last bin
1253 | '''
1254 | for t in np.arange(self.no_t):
1255 | if t in list(self._allPeaks.keys()):
1256 | extendedRawSpectrum[t, trustedPeakHeight[t],
1257 | trustedPeakHeightStart[t]:trustedPeakHeightStop[t]+1].mask = False
1258 |
1259 | peaksVelMe = np.array(allPeaksVelMe[t])
1260 | # get all three possible velocities
1261 | peaksVels = np.array([peaksVelMe+self.co["nyqVdelta"]*self.co["widthSpectrum"],
1262 | peaksVelMe, peaksVelMe-self.co["nyqVdelta"]*self.co["widthSpectrum"]])
1263 |
1264 | formerPeakVel = trustedPeakVel[t]
1265 | # loop through all peaks, starting at the trusted one
1266 | for jj in list(range(trustedPeakNo[t]-1, -1, -1))+list(range(trustedPeakNo[t]+1, len(allPeaks[t]))):
1267 | # To combine ascending and descending loop in one:
1268 | if jj == trustedPeakNo[t]+1:
1269 | formerPeakVel = trustedPeakVel[t]
1270 | # go up, stay or down? for which option fifference to former (trusted) peaks is smallest.
1271 | UpOrDn = np.argmin(
1272 | np.abs(peaksVels[:, jj] - formerPeakVel))
1273 | # change height, indices and velocity accordingly
1274 | thisPeakHeight = allPeaksHeight[t][jj] + UpOrDn-1
1275 | if thisPeakHeight not in list(range(self.co["noH"])):
1276 | warnings.warn('Dealiasing failed! peak boundaries excced max/min height. time step '+str(
1277 | t)+', peak number ' + str(jj)+', tried to put at height ' + str(thisPeakHeight))
1278 | self.qual["severeProblemsDuringDA"][t] = True
1279 | continue
1280 | thisPeakSpecShift = thisPeakHeight * \
1281 | self.co["widthSpectrum"] - self.co["widthSpectrum"]
1282 | thisPeakVel = peaksVels[UpOrDn][jj]
1283 | thisPeakHeightIndices = np.array(
1284 | allPeaksIndices[t][jj])-thisPeakSpecShift
1285 | if np.any(thisPeakHeightIndices < 0) or np.any(thisPeakHeightIndices >= 3*self.co["widthSpectrum"]):
1286 | warnings.warn('Dealiasing failed! peak boundaries fall out of spectrum. time step '+str(
1287 | t)+', peak number ' + str(jj)+', most likely at height ' + str(thisPeakHeight))
1288 | self.qual["severeProblemsDuringDA"][t] = True
1289 |
1290 | # check whether there is already a peak in the found height!
1291 | if np.all(extendedRawSpectrum[t, thisPeakHeight].mask == True):
1292 | if thisPeakHeight >= self.co["noH"] or thisPeakHeight < 0:
1293 | warnings.warn('Dealiasing reached max/min height... time step '+str(
1294 | t)+', peak number ' + str(jj)+', most likely at height ' + str(thisPeakHeight))
1295 | self.qual["severeProblemsDuringDA"][t] = True
1296 | continue
1297 | # only if there is no peak yet!!
1298 | extendedRawSpectrum[t, thisPeakHeight, thisPeakHeightIndices[0] :thisPeakHeightIndices[-1]+1].mask = False
1299 | formerPeakVel = thisPeakVel
1300 | # if there is already a peak in the height, repeat the process, but take the second likely height/velocity
1301 | else:
1302 | if self.co["debug"] > 4:
1303 | print('DA: there is already a peak in found height, take second choice',
1304 | t, jj, thisPeakHeight, trustedPeakNo[t], trustedPeakHeight)
1305 | # otherwise take second choice!
1306 | formerPeakVelList = np.array([formerPeakVel]*3)
1307 | formerPeakVelList[UpOrDn] = 1e10 # make extremely big
1308 | UpOrDn2 = np.ma.argmin(
1309 | np.abs(peaksVels[:, jj] - formerPeakVelList))
1310 | thisPeakHeight = allPeaksHeight[t][jj] + UpOrDn2-1
1311 | if thisPeakHeight not in list(range(self.co["noH"])):
1312 | warnings.warn('Dealiasing step 2 failed! peak boundaries excced max/min height. time step '+str(
1313 | t)+', peak number ' + str(jj)+', tried to put at height ' + str(thisPeakHeight))
1314 | self.qual["severeProblemsDuringDA"][t] = True
1315 | continue
1316 | thisPeakSpecShift = thisPeakHeight * \
1317 | self.co["widthSpectrum"] - self.co["widthSpectrum"]
1318 | thisPeakVel = peaksVels[UpOrDn2][jj]
1319 | thisPeakHeightIndices = np.array(
1320 | allPeaksIndices[t][jj])-thisPeakSpecShift
1321 | if np.any(thisPeakHeightIndices < 0) or np.any(thisPeakHeightIndices >= 3*self.co["widthSpectrum"]):
1322 | warnings.warn('Dealiasing step 2 failed! peak boundaries fall out of spectrum. time step '+str(
1323 | t)+', peak number ' + str(jj)+', most likely at height ' + str(thisPeakHeight))
1324 | self.qual["severeProblemsDuringDA"][t] = True
1325 | if thisPeakHeight >= self.co["noH"] or thisPeakHeight < 0:
1326 | warnings.warn('Dealiasing reached max/min height... time step '+str(
1327 | t)+', peak number ' + str(jj)+', most likely at height ' + str(thisPeakHeight))
1328 | self.qual["severeProblemsDuringDA"][t] = True
1329 | continue
1330 | # check again whether there is already a peak in the spectrum
1331 | if np.all(extendedRawSpectrum[t, thisPeakHeight].mask == True):
1332 | # next try
1333 | extendedRawSpectrum[t, thisPeakHeight, thisPeakHeightIndices[0] :thisPeakHeightIndices[-1]+1].mask = False
1334 | formerPeakVel = thisPeakVel
1335 | # if yes, give up
1336 | else:
1337 | warnings.warn('Could not find height of peak! time step '+str(
1338 | t)+', peak number ' + str(jj)+', most likely at height ' + str(thisPeakHeight))
1339 | self.qual["severeProblemsDuringDA"][t] = True
1340 |
1341 | return extendedRawSpectrum
1342 |
1343 | def _deAlCoherence(self, newSpectrum):
1344 | '''
1345 | make sure no weired foldings happend by looking for big jumps in the height-averaged velocity
1346 | if two jumps very closely together (<=3 peaks inbetween) are found, teh peaks inbetween are corrected
1347 | can make it worse if dealiasing produces zig-zag patterns.
1348 |
1349 | '''
1350 | self.qual["DAdirectionCorrectedByCoherenceTest"] = np.zeros(
1351 | self._shape2D, dtype=bool)
1352 | meanVelocity = np.ma.average(np.ma.sum(
1353 | newSpectrum*self.specVel, axis=-1)/np.ma.sum(newSpectrum, axis=-1), axis=-1)
1354 |
1355 | velDiffs = np.diff(meanVelocity)
1356 |
1357 | # find velocity jumps
1358 | velDiffsBig = np.where(
1359 | velDiffs > self.co["dealiaseSpectrum_makeCoherenceTest_velocityThreshold"])[0]
1360 | velDiffsSmall = np.where(
1361 | velDiffs < -self.co["dealiaseSpectrum_makeCoherenceTest_velocityThreshold"])[0]
1362 |
1363 | # check whether there is an opposite one close by and collect time steps to be refolded
1364 | foldUp = list()
1365 | for ll in velDiffsBig:
1366 | if ll+1 in velDiffsSmall:
1367 | foldUp.append(ll+1)
1368 | continue
1369 | if ll+2 in velDiffsSmall:
1370 | foldUp.append(ll+1)
1371 | foldUp.append(ll+2)
1372 | continue
1373 | if ll+3 in velDiffsSmall:
1374 | foldUp.append(ll+1)
1375 | foldUp.append(ll+2)
1376 | foldUp.append(ll+3)
1377 |
1378 | updatedSpectrumMask = deepcopy(newSpectrum.mask)
1379 |
1380 | for tt in foldUp:
1381 | updatedSpectrumMask[tt] = np.roll(updatedSpectrumMask[tt].ravel(
1382 | ), 2 * self.co["widthSpectrum"]).reshape((self.co["noH"], 3*self.co["widthSpectrum"]))
1383 | # avoid that something is folded into the highest range gate
1384 | updatedSpectrumMask[tt, 0, :2*self.co["widthSpectrum"]] = True
1385 | self.qual["DAdirectionCorrectedByCoherenceTest"][tt, :] = True
1386 | if self.co["debug"] > 4:
1387 | print('coherenceTest corrected dealiasing upwards:', foldUp)
1388 |
1389 | newSpectrum = np.ma.masked_array(newSpectrum.data, updatedSpectrumMask)
1390 |
1391 | # now the same for the other folding direction
1392 | meanVelocity = np.ma.average(np.ma.sum(
1393 | newSpectrum*self.specVel, axis=-1)/np.ma.sum(newSpectrum, axis=-1), axis=-1)
1394 |
1395 | velDiffs = np.diff(meanVelocity)
1396 |
1397 | # find very big differences
1398 | velDiffsBig = np.where(
1399 | velDiffs > self.co["dealiaseSpectrum_makeCoherenceTest_velocityThreshold"])[0]
1400 | velDiffsSmall = np.where(
1401 | velDiffs < -self.co["dealiaseSpectrum_makeCoherenceTest_velocityThreshold"])[0]
1402 |
1403 | foldDn = list()
1404 | # check whether there is an opposite one close by and collect time steps to be refolded
1405 | for ll in velDiffsSmall:
1406 | if ll+1 in velDiffsBig:
1407 | foldDn.append(ll+1)
1408 | continue
1409 | if ll+2 in velDiffsBig:
1410 | foldDn.append(ll+1)
1411 | foldDn.append(ll+2)
1412 | continue
1413 | if ll+3 in velDiffsBig:
1414 | foldDn.append(ll+1)
1415 | foldDn.append(ll+2)
1416 | foldDn.append(ll+2)
1417 |
1418 | updatedSpectrumMask = deepcopy(newSpectrum.mask)
1419 | # change all peaks accordingly
1420 | for tt in foldDn:
1421 | # roll the mask!
1422 | updatedSpectrumMask[tt] = np.roll(updatedSpectrumMask[tt].ravel(
1423 | ), -2*self.co["widthSpectrum"]).reshape((self.co["noH"], 3*self.co["widthSpectrum"]))
1424 | # avoid that something is folded into the lowest range gate
1425 | updatedSpectrumMask[tt, -1, -2*self.co["widthSpectrum"]:] = True
1426 | self.qual["DAdirectionCorrectedByCoherenceTest"][tt, :] = True
1427 | if self.co["debug"] > 4:
1428 | print('coherenceTest corrected dealiasing Donwards:', foldDn)
1429 |
1430 | newSpectrum = np.ma.masked_array(newSpectrum.data, updatedSpectrumMask)
1431 |
1432 | # this method is very incompelte, so save still odd looking peaks in the quality mask:
1433 | # first, collect all height which should be treated, we don't want to find jumps of the interpolated area!:
1434 | includedHeights = list(set(range(self.co["maxH"])).difference(set(
1435 | self.co["completelyMaskedHeights"]+self.co["dealiaseSpectrum_heightsWithInterference"])))
1436 | # now get the mean velocity of the profile
1437 | meanVelocity = np.ma.average(np.ma.sum(
1438 | newSpectrum[:, includedHeights]*self.specVel, axis=-1)/np.ma.sum(newSpectrum[:, includedHeights], axis=-1), axis=-1)
1439 | velDiffs = np.abs(np.diff(meanVelocity))
1440 | # find all steps exceeding a min velocity threshold
1441 | crazyVelDiffs = np.where(
1442 | velDiffs > self.co["dealiaseSpectrum_makeCoherenceTest_velocityThreshold"])[0]
1443 |
1444 | self.qual["DAbigVelocityJumpDespiteCoherenceTest"] = np.zeros(
1445 | self._shape2D, dtype=bool)
1446 | # surrounding data has to be masked as well, take +- self.co["dealiaseSpectrum_makeCoherenceTest_maskRadius"] (default 20min) around suspicous data
1447 | for crazyVelDiff in crazyVelDiffs:
1448 | self.qual["DAbigVelocityJumpDespiteCoherenceTest"][crazyVelDiff-self.co["dealiaseSpectrum_makeCoherenceTest_maskRadius"] :crazyVelDiff+self.co["dealiaseSpectrum_makeCoherenceTest_maskRadius"]+1, :] = True
1449 |
1450 | return newSpectrum
1451 |
1452 | def _calcEtaZeW(self, rawSpectra, heights, velocities, noise, noise_std):
1453 | '''
1454 | calculate the spectral moements and other spectral variables
1455 | '''
1456 |
1457 | deltaH = oneD2twoD(
1458 | heights[..., 15]-heights[..., 14], heights.shape[-1], 1)
1459 |
1460 | # transponieren um multiplizieren zu ermoeglichen!
1461 | eta = (rawSpectra.data.T * np.array(
1462 | (self.co["mrrCalibConst"] * (heights**2 / deltaH)) / (1e20), dtype=float).T).T
1463 | eta = np.ma.masked_array(eta, rawSpectra.mask)
1464 | etaNoiseAve = noise * \
1465 | (self.co["mrrCalibConst"] * (heights**2 / deltaH)) / 1e20
1466 | etaNoiseStd = noise_std * \
1467 | (self.co["mrrCalibConst"] * (heights**2 / deltaH)) / 1e20
1468 |
1469 | # calculate Ze
1470 | Ze = 1e18*(self.co["lamb"]**4*np.ma.sum(eta,
1471 | axis=-1)/(np.pi**5*self.co["K2"]))
1472 | Ze = (10*np.ma.log10(Ze)).filled(-9999)
1473 | #Znoise = 1e18*(self.co["lamb"]**4*(etaNoise*self.co["widthSpectrum"])/(np.pi**5*self.co["K2"]))
1474 | #Znoise = 10*np.ma.log10(Znoise).filled(-9999)
1475 |
1476 | # no slicing neccesary due to mask! definign average value "my"
1477 | my = np.ma.sum(velocities*rawSpectra, axis=-1) / \
1478 | np.ma.sum(rawSpectra, axis=-1)
1479 |
1480 | # normed weights
1481 | P = (rawSpectra.T/np.ma.sum(rawSpectra, axis=-1).T).T
1482 | x = velocities
1483 |
1484 | # http://mathworld.wolfram.com/CentralMoment.html
1485 | # T is neccessary due to different dimensions
1486 | mom2 = np.ma.sum(P*(x.T-my.T).T**2, axis=-1)
1487 | mom3 = np.ma.sum(P*(x.T-my.T).T**3, axis=-1)
1488 | mom4 = np.ma.sum(P*(x.T-my.T).T**4, axis=-1)
1489 |
1490 | # average fall velocity is my
1491 | W = my.filled(-9999)
1492 | # spec width is weighted std
1493 | specWidth = np.sqrt(mom2).filled(-9999)
1494 | # http://mathworld.wolfram.com S^-1kewness.html
1495 | skewness = (mom3/mom2**(3./2.)).filled(-9999)
1496 | # http://mathworld.wolfram.com/Kurtosis.html
1497 | kurtosis = (mom4/mom2**(2.)).filled(-9999)
1498 |
1499 | # get velocity at borders and max of peak
1500 | peakVelLeftBorder = self.specVel[np.argmin(rawSpectra.mask, axis=-1)]
1501 | peakVelRightBorder = self.specVel[len(
1502 | self.specVel) - np.argmin(rawSpectra.mask[..., ::-1], axis=-1) - 1]
1503 | peakVelMax = self.specVel[np.argmax(rawSpectra.filled(-9999), axis=-1)]
1504 |
1505 | # get the according indices
1506 | peakArgLeftBorder = np.argmin(rawSpectra.mask, axis=-1)
1507 | peakArgRightBorder = len(
1508 | self.specVel) - np.argmin(rawSpectra.mask[..., ::-1], axis=-1) - 1
1509 |
1510 | # to find the entries we have to flatten everything
1511 | etaSpectraFlat = eta.reshape((eta.shape[0]*eta.shape[1], eta.shape[2]))
1512 |
1513 | # no get the according values
1514 | peakEtaLeftBorder = 10*np.log10(etaSpectraFlat[list(range(
1515 | etaSpectraFlat.shape[0])), peakArgLeftBorder.ravel()].reshape(self._shape2D))
1516 | peakEtaRightBorder = 10*np.log10(etaSpectraFlat[list(range(
1517 | etaSpectraFlat.shape[0])), peakArgRightBorder.ravel()].reshape(self._shape2D))
1518 |
1519 | peakEtaMax = 10*np.log10(np.max(eta.filled(-9999), axis=-1))
1520 |
1521 | leftSlope = (peakEtaMax - peakEtaLeftBorder) / \
1522 | (peakVelMax - peakVelLeftBorder)
1523 | rightSlope = (peakEtaMax - peakEtaRightBorder) / \
1524 | (peakVelMax - peakVelRightBorder)
1525 |
1526 | peakVelLeftBorder[Ze == -9999] = -9999
1527 | peakVelRightBorder[Ze == -9999] = -9999
1528 | leftSlope[Ze == -9999] = -9999
1529 | rightSlope[Ze == -9999] = -9999
1530 | leftSlope[np.isnan(leftSlope)] = -9999
1531 | rightSlope[np.isnan(rightSlope)] = -9999
1532 |
1533 | return eta, Ze, W, etaNoiseAve, etaNoiseStd, specWidth, skewness, kurtosis, peakVelLeftBorder, peakVelRightBorder, leftSlope, rightSlope
1534 |
1535 | def getQualityBinArray(self, qual):
1536 | '''
1537 | convert the bool quality masks to one binary array
1538 | '''
1539 |
1540 | binQual = np.zeros(self._shape2D, dtype=int)
1541 | qualFac = dict()
1542 | description = ''
1543 | description += 'A) usually, the following erros can be ignored (no. is position of bit): '
1544 | qualFac["interpolatedSpectrum"] = 0b1
1545 | description += '1) spectrum interpolated around 0 and 12 m s^-1 '
1546 |
1547 | qualFac["filledInterpolatedPeakGaps"] = 0b10
1548 | description += '2) peak streches over interpolated part '
1549 |
1550 | qualFac["spectrumIsDealiased"] = 0b100
1551 | description += '3) peak is dealiased '
1552 |
1553 | qualFac["usedSecondPeakAlgorithmDueToWidePeak"] = 0b1000
1554 | description += '4) first Algorithm to determine peak failed, used backup '
1555 |
1556 | qualFac["DAdirectionCorrectedByCoherenceTest"] = 0b10000
1557 | description += '5) dealiasing went wrong, but is corrected '
1558 |
1559 | description += 'B) reasons why a spectrum does NOT contain a peak: '
1560 | qualFac["incompleteSpectrum"] = 0b10000000
1561 | description += '8) spectrum was incompletely recorded '
1562 |
1563 | qualFac["spectrumVarianceTooLowForPeak"] = 0b100000000
1564 | description += '9) the variance test indicated no peak '
1565 |
1566 | qualFac["spectrumNotProcessed"] = 0b1000000000
1567 | description += '10) spectrum is not processed due to according setting '
1568 |
1569 | qualFac["peakTooThinn"] = 0b10000000000
1570 | description += '11) peak removed since not wide enough '
1571 |
1572 | qualFac["peakRemovedByCoherenceTest"] = 0b100000000000
1573 | description += '12) peak removed, because too few neighbours show signal, too '
1574 |
1575 | description += "C) thinks went seriously wrong, don't use data with these codes"
1576 | qualFac["peakMightBeIncomplete"] = 0b1000000000000000
1577 | description += '16) peak is at the very border to bad data '
1578 |
1579 | qualFac["DAbigVelocityJumpDespiteCoherenceTest"] = 0b10000000000000000
1580 | description += '17) in this area there are still strong velocity jumps, indicates failed dealiasing '
1581 |
1582 | qualFac["severeProblemsDuringDA"] = 0b100000000000000000
1583 | description += '18) during dealiasing, a warning was triggered, applied to whole columm '
1584 |
1585 | for key in list(qual.keys()):
1586 | binQual[:] = binQual[:] + (qual[key] * qualFac[key])
1587 |
1588 | return binQual, description
1589 |
1590 | def writeNetCDF(self, fname, varsToSave="all", ncForm="NETCDF3_CLASSIC"):
1591 | '''
1592 | write the results to a netcdf file
1593 |
1594 | Input:
1595 |
1596 | fname: str filename with path
1597 | varsToSave list of variables of the profile to be saved. "all" saves all implmented ones
1598 | ncForm: str netcdf file format, possible values are NETCDF3_CLASSIC, NETCDF3_64BIT, NETCDF4_CLASSIC, and NETCDF4 for the python-netcdf4 package, NETCDF3 takes the "old" Scientific.IO.NetCDF module, which is a bit more convinient to install or as fall back option python-netcdf3
1599 | '''
1600 |
1601 | nc, pyNc = _get_netCDF_module(ncForm=ncForm)
1602 |
1603 | # option dealiaseSpectrum_saveAlsoNonDealiased makes only sence, if spectrum is really dealiased:
1604 | saveAlsoNonDealiased = self.co["dealiaseSpectrum_saveAlsoNonDealiased"] and self.co["dealiaseSpectrum"]
1605 |
1606 | if pyNc:
1607 | cdfFile = nc.Dataset(fname, "w", format=ncForm)
1608 | else:
1609 | cdfFile = nc.NetCDFFile(fname, "w")
1610 |
1611 | # write meta data
1612 | cdfFile.title = 'Micro rain radar data processed with IMProToo'
1613 | cdfFile.comment = 'IMProToo has been developed for improved snow measurements. Note that this data has been processed regardless of precipitation type.'
1614 | cdfFile.institution = self.co["ncInstitution"]
1615 | cdfFile.contact_person = self.co["ncCreator"]
1616 | cdfFile.source = 'MRR-2'
1617 | cdfFile.location = self.co["ncLocation"]
1618 | cdfFile.history = 'Created with IMProToo v' + __version__
1619 | cdfFile.author = 'Max Maahn'
1620 | cdfFile.processing_date = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
1621 | cdfFile.reference = 'Maahn, M. and Kollias, P., 2012: Improved Micro Rain Radar snow measurements using Doppler spectra post-processing, Atmos. Meas. Tech., 5, 2661-2673, doi:10.5194/amt-5-2661-2012. '
1622 |
1623 | cdfFile.properties = str(self.co)
1624 | cdfFile.mrrHeader = str(self.header)
1625 |
1626 | # make frequsnions
1627 | cdfFile.createDimension('time', int(self.no_t))
1628 | cdfFile.createDimension('range', int(self.no_h))
1629 | cdfFile.createDimension('velocity', int(self.no_v))
1630 | if saveAlsoNonDealiased:
1631 | cdfFile.createDimension('velocity_noDA', int(self.no_v_noDA))
1632 |
1633 | ncShape2D = ("time", "range",)
1634 | ncShape3D = ("time", "range", "velocity",)
1635 | ncShape3D_noDA = ("time", "range", "velocity_noDA",)
1636 |
1637 | fillVDict = dict()
1638 | # little cheat to avoid hundreds of if, else...
1639 | if pyNc:
1640 | fillVDict["fill_value"] = self.missingNumber
1641 |
1642 | nc_time = cdfFile.createVariable('time', 'i', ('time',), **fillVDict)
1643 | nc_time.description = "measurement time. Following Meteks convention, the dataset at e.g. 11:55 contains all recorded raw between 11:54:00 and 11:54:59 (if delta t = 60s)!"
1644 | nc_time.timezone = self.timezone
1645 | nc_time.units = 'seconds since 1970-01-01 00:00:00'
1646 | nc_time[:] = np.array(self.time.filled(self.missingNumber), dtype="i4")
1647 | # commented because of Ubuntu bug: https://bugs.launchpad.net/ubuntu/+source/python-scientific/+bug/1005571
1648 | #if not pyNc: nc_time._FillValue =int(self.missingNumber)
1649 |
1650 | nc_range = cdfFile.createVariable(
1651 | 'range', 'i', ('range',), **fillVDict) # = missingNumber)
1652 | nc_range.description = "range bins"
1653 | nc_range.units = '#'
1654 | nc_range[:] = np.arange(self.co["minH"], self.co["maxH"]+1, dtype="i4")
1655 | #if not pyNc: nc_range._FillValue =int(self.missingNumber)
1656 |
1657 | nc_velocity = cdfFile.createVariable(
1658 | 'velocity', 'f', ('velocity',), **fillVDict)
1659 | nc_velocity.description = "Doppler velocity bins. If dealiasing is applied, the spectra are triplicated"
1660 | nc_velocity.units = 'm s^-1'
1661 | nc_velocity[:] = np.array(self.specVel, dtype="f4")
1662 | #if not pyNc: nc_velocity._FillValue =float(self.missingNumber)
1663 |
1664 | if saveAlsoNonDealiased:
1665 | nc_velocity_noDA = cdfFile.createVariable(
1666 | 'velocity_noDA', 'f', ('velocity_noDA',), **fillVDict)
1667 | nc_velocity_noDA.description = "Original, non dealiased, Doppler velocity bins."
1668 | nc_velocity_noDA.units = 'm s^-1'
1669 | nc_velocity_noDA[:] = np.array(self.specVel_noDA, dtype="f4")
1670 | #if not pyNc: nc_velocity_noDA._FillValue =float(self.missingNumber)
1671 |
1672 | nc_height = cdfFile.createVariable(
1673 | 'height', 'f', ncShape2D, **fillVDict) # = missingNumber)
1674 | nc_height.description = "height above instrument"
1675 | nc_height.units = 'm'
1676 | nc_height[:] = np.array(self.H.filled(self.missingNumber), dtype="f4")
1677 | #if not pyNc: nc_height._FillValue =float(self.missingNumber)
1678 |
1679 | if (varsToSave == 'all' and saveAlsoNonDealiased) or "eta_noDA" in varsToSave:
1680 | nc_eta_noDA = cdfFile.createVariable(
1681 | 'eta_noDA', 'f', ncShape3D_noDA, **fillVDict)
1682 | nc_eta_noDA.description = "spectral reflectivities NOT dealiased"
1683 | nc_eta_noDA.units = "mm^6 m^-3"
1684 | nc_eta_noDA[:] = np.array(self.eta_noDA.data, dtype="f4")
1685 | #if not pyNc: nc_eta_noDA._FillValue =float(self.missingNumber)
1686 |
1687 | nc_etaMask_noDA = cdfFile.createVariable(
1688 | 'etaMask_noDA', 'i', ncShape3D_noDA, **fillVDict)
1689 | nc_etaMask_noDA.description = "noise mask of eta NOT dealiased, 0: signal, 1:noise"
1690 | nc_etaMask_noDA.units = "bool"
1691 | nc_etaMask_noDA[:] = np.array(
1692 | np.array(self.eta_noDA.mask, dtype=int), dtype="i4")
1693 | #if not pyNc: nc_etaMask_noDA._FillValue =int(self.missingNumber)
1694 |
1695 | if varsToSave == 'all' or "eta" in varsToSave:
1696 | nc_eta = cdfFile.createVariable('eta', 'f', ncShape3D, **fillVDict)
1697 | nc_eta.description = "spectral reflectivities. if dealiasing is applied, the spectra are triplicated, thus up to three peaks can occur from -12 to +24 m s^-1. However, only one peak is not masked in etaMask"
1698 | nc_eta.units = "mm^6 m^-3"
1699 | nc_eta[:] = np.array(self.eta.data, dtype="f4")
1700 | #if not pyNc: nc_eta._FillValue =float(self.missingNumber)
1701 |
1702 | nc_etaMask = cdfFile.createVariable(
1703 | 'etaMask', 'i', ncShape3D, **fillVDict)
1704 | nc_etaMask.description = "noise mask of eta, 0: signal, 1:noise"
1705 | nc_etaMask.units = "bool"
1706 | nc_etaMask[:] = np.array(
1707 | np.array(self.eta.mask, dtype=int), dtype="i4")
1708 | #if not pyNc: nc_etaMask._FillValue =int(self.missingNumber)
1709 |
1710 | if varsToSave == 'all' or "quality" in varsToSave:
1711 | qualArray, qualDescription = self.getQualityBinArray(self.qual)
1712 |
1713 | nc_qual = cdfFile.createVariable(
1714 | 'quality', 'i', ncShape2D, **fillVDict)
1715 | nc_qual.description = qualDescription
1716 | nc_qual.units = "bin"
1717 | nc_qual[:] = np.array(qualArray, dtype="i4")
1718 | #if not pyNc: nc_qual._FillValue =int(self.missingNumber)
1719 |
1720 | if varsToSave == 'all' or "TF" in varsToSave:
1721 | nc_TF = cdfFile.createVariable('TF', 'f', ncShape2D, **fillVDict)
1722 | nc_TF.description = "Transfer Function (see Metek's documentation)"
1723 | nc_TF.units = "-"
1724 | nc_TF[:] = np.array(self.TF.filled(self.missingNumber), dtype="f4")
1725 | #if not pyNc: nc_TF._FillValue =float(self.missingNumber)
1726 |
1727 | if (varsToSave == 'all' and saveAlsoNonDealiased) or "Ze_noDA" in varsToSave:
1728 | nc_ze_noDA = cdfFile.createVariable(
1729 | 'Ze_noDA', 'f', ncShape2D, **fillVDict)
1730 | nc_ze_noDA.description = "reflectivity of the most significant peak, not dealiased"
1731 | nc_ze_noDA.units = "dBz"
1732 | nc_ze_noDA[:] = np.array(self.Ze_noDA, dtype="f4")
1733 | #if not pyNc: nc_ze_noDA._FillValue =float(self.missingNumber)
1734 |
1735 | if varsToSave == 'all' or "Ze" in varsToSave:
1736 | nc_ze = cdfFile.createVariable('Ze', 'f', ncShape2D, **fillVDict)
1737 | nc_ze.description = "reflectivity of the most significant peak"
1738 | nc_ze.units = "dBz"
1739 | nc_ze[:] = np.array(self.Ze, dtype="f4")
1740 | #if not pyNc: nc_ze._FillValue =float(self.missingNumber)
1741 |
1742 | if (varsToSave == 'all' and saveAlsoNonDealiased) or "specWidth_noDA" in varsToSave:
1743 | nc_specWidth_noDA = cdfFile.createVariable(
1744 | 'spectralWidth_noDA', 'f', ncShape2D, **fillVDict)
1745 | nc_specWidth_noDA.description = "spectral width of the most significant peak, not dealiased"
1746 | nc_specWidth_noDA.units = "m s^-1"
1747 | nc_specWidth_noDA[:] = np.array(self.specWidth_noDA, dtype="f4")
1748 | #if not pyNc: nc_specWidth_noDA._FillValue =float(self.missingNumber)
1749 |
1750 | if varsToSave == 'all' or "specWidth" in varsToSave:
1751 | nc_specWidth = cdfFile.createVariable(
1752 | 'spectralWidth', 'f', ncShape2D, **fillVDict)
1753 | nc_specWidth.description = "spectral width of the most significant peak"
1754 | nc_specWidth.units = "m s^-1"
1755 | nc_specWidth[:] = np.array(self.specWidth, dtype="f4")
1756 | #if not pyNc: nc_specWidth._FillValue =float(self.missingNumber)
1757 |
1758 | if (varsToSave == 'all' and saveAlsoNonDealiased) or "skewness_noDA" in varsToSave:
1759 | nc_skewness_noDA = cdfFile.createVariable(
1760 | 'skewness_noDA', 'f', ncShape2D, **fillVDict)
1761 | nc_skewness_noDA.description = "Skewness of the most significant peak, not dealiased"
1762 | nc_skewness_noDA.units = "-"
1763 | nc_skewness_noDA[:] = np.array(self.skewness_noDA, dtype="f4")
1764 | #if not pyNc: nc_skewness_noDA._FillValue =float(self.missingNumber)
1765 |
1766 | if varsToSave == 'all' or "skewness" in varsToSave:
1767 | nc_skewness = cdfFile.createVariable(
1768 | 'skewness', 'f', ncShape2D, **fillVDict)
1769 | nc_skewness.description = "Skewness of the most significant peak"
1770 | nc_skewness.units = "-"
1771 | nc_skewness[:] = np.array(self.skewness, dtype="f4")
1772 | #if not pyNc: nc_skewness._FillValue =float(self.missingNumber)
1773 |
1774 | if (varsToSave == 'all' and saveAlsoNonDealiased) or "kurtosis_noDA" in varsToSave:
1775 | nc_kurtosis_noDA = cdfFile.createVariable(
1776 | 'kurtosis_noDA', 'f', ncShape2D, **fillVDict)
1777 | nc_kurtosis_noDA.description = "kurtosis of the most significant peak, not dealiased"
1778 | nc_kurtosis_noDA.units = "-"
1779 | nc_kurtosis_noDA[:] = np.array(self.kurtosis_noDA, dtype="f4")
1780 | #if not pyNc: nc_kurtosis_noDA._FillValue =float(self.missingNumber)
1781 |
1782 | if varsToSave == 'all' or "kurtosis" in varsToSave:
1783 | nc_kurtosis = cdfFile.createVariable(
1784 | 'kurtosis', 'f', ncShape2D, **fillVDict)
1785 | nc_kurtosis.description = "kurtosis of the most significant peak"
1786 | nc_kurtosis.units = "-"
1787 | nc_kurtosis[:] = np.array(self.kurtosis, dtype="f4")
1788 | #if not pyNc: nc_kurtosis._FillValue =float(self.missingNumber)
1789 |
1790 | if (varsToSave == 'all' and saveAlsoNonDealiased) or "peakVelLeftBorder_noDA" in varsToSave:
1791 | nc_peakVelLeftBorder_noDA = cdfFile.createVariable(
1792 | 'peakVelLeftBorder_noDA', 'f', ncShape2D, **fillVDict)
1793 | nc_peakVelLeftBorder_noDA.description = "Doppler velocity of the left border of the peak, not dealiased"
1794 | nc_peakVelLeftBorder_noDA.units = "m s^-1"
1795 | nc_peakVelLeftBorder_noDA[:] = np.array(
1796 | self.peakVelLeftBorder_noDA, dtype="f4")
1797 | #if not pyNc: nc_peakVelLeftBorder_noDA._FillValue =float(self.missingNumber)
1798 |
1799 | if varsToSave == 'all' or "peakVelLeftBorder" in varsToSave:
1800 | nc_peakVelLeftBorder = cdfFile.createVariable(
1801 | 'peakVelLeftBorder', 'f', ncShape2D, **fillVDict)
1802 | nc_peakVelLeftBorder.description = "Doppler velocity of the left border of the peak"
1803 | nc_peakVelLeftBorder.units = "m s^-1"
1804 | nc_peakVelLeftBorder[:] = np.array(
1805 | self.peakVelLeftBorder, dtype="f4")
1806 | #if not pyNc: nc_peakVelLeftBorder._FillValue =float(self.missingNumber)
1807 |
1808 | if (varsToSave == 'all' and saveAlsoNonDealiased) or "peakVelRightBorder_noDA" in varsToSave:
1809 | nc_peakVelRightBorder_noDA = cdfFile.createVariable(
1810 | 'peakVelRightBorder_noDA', 'f', ncShape2D, **fillVDict)
1811 | nc_peakVelRightBorder_noDA.description = "Doppler velocity of the right border of the peak, not dealiased"
1812 | nc_peakVelRightBorder_noDA.units = "m s^-1"
1813 | nc_peakVelRightBorder_noDA[:] = np.array(
1814 | self.peakVelRightBorder_noDA, dtype="f4")
1815 | #if not pyNc: nc_peakVelRightBorder_noDA._FillValue =float(self.missingNumber)
1816 |
1817 | if varsToSave == 'all' or "peakVelRightBorder" in varsToSave:
1818 | nc_peakVelRightBorder = cdfFile.createVariable(
1819 | 'peakVelRightBorder', 'f', ncShape2D, **fillVDict)
1820 | nc_peakVelRightBorder.description = "Doppler velocity of the right border of the peak"
1821 | nc_peakVelRightBorder.units = "m s^-1"
1822 | nc_peakVelRightBorder[:] = np.array(
1823 | self.peakVelRightBorder, dtype="f4")
1824 | #if not pyNc: nc_peakVelRightBorder._FillValue =float(self.missingNumber)
1825 |
1826 | if (varsToSave == 'all' and saveAlsoNonDealiased) or "leftSlope_noDA" in varsToSave:
1827 | nc_leftSlope_noDA = cdfFile.createVariable(
1828 | 'leftSlope_noDA', 'f', ncShape2D, **fillVDict)
1829 | nc_leftSlope_noDA.description = "Slope at the left side of the peak, not dealiased"
1830 | nc_leftSlope_noDA.units = "dB/(m s^-1)"
1831 | nc_leftSlope_noDA[:] = np.array(self.leftSlope_noDA, dtype="f4")
1832 | #if not pyNc: nc_leftSlope_noDA._FillValue =float(self.missingNumber)
1833 |
1834 | if varsToSave == 'all' or "leftSlope" in varsToSave:
1835 | nc_leftSlope = cdfFile.createVariable(
1836 | 'leftSlope', 'f', ncShape2D, **fillVDict)
1837 | nc_leftSlope.description = "Slope at the left side of the peak"
1838 | nc_leftSlope.units = "dB/(m s^-1)"
1839 | nc_leftSlope[:] = np.array(self.leftSlope, dtype="f4")
1840 | #if not pyNc: nc_leftSlope._FillValue =float(self.missingNumber)
1841 |
1842 | if (varsToSave == 'all' and saveAlsoNonDealiased) or "rightSlope_noDA" in varsToSave:
1843 | nc_rightSlope_noDA = cdfFile.createVariable(
1844 | 'rightSlope_noDA', 'f', ncShape2D, **fillVDict)
1845 | nc_rightSlope_noDA.description = "Slope at the right side of the peak, not dealiased"
1846 | nc_rightSlope_noDA.units = "dB/(m s^-1)"
1847 | nc_rightSlope_noDA[:] = np.array(self.rightSlope_noDA, dtype="f4")
1848 | #if not pyNc: nc_rightSlope_noDA._FillValue =float(self.missingNumber)
1849 |
1850 | if varsToSave == 'all' or "rightSlope" in varsToSave:
1851 | nc_rightSlope = cdfFile.createVariable(
1852 | 'rightSlope', 'f', ncShape2D, **fillVDict)
1853 | nc_rightSlope.description = "Slope at the right side of the peak"
1854 | nc_rightSlope.units = "dB/(m s^-1)"
1855 | nc_rightSlope[:] = np.array(self.rightSlope, dtype="f4")
1856 | #if not pyNc: nc_rightSlope._FillValue =float(self.missingNumber)
1857 |
1858 | if (varsToSave == 'all' and saveAlsoNonDealiased) or "W_noDA" in varsToSave:
1859 | nc_w_noDA = cdfFile.createVariable(
1860 | 'W_noDA', 'f', ncShape2D, **fillVDict)
1861 | nc_w_noDA.description = "Mean Doppler Velocity of the most significant peak, not dealiased"
1862 | nc_w_noDA.units = "m s^-1"
1863 | nc_w_noDA[:] = np.array(self.W_noDA, dtype="f4")
1864 | #if not pyNc: nc_w_noDA._FillValue =float(self.missingNumber)
1865 |
1866 | if varsToSave == 'all' or "W" in varsToSave:
1867 | nc_w = cdfFile.createVariable('W', 'f', ncShape2D, **fillVDict)
1868 | nc_w.description = "Mean Doppler Velocity of the most significant peak"
1869 | nc_w.units = "m s^-1"
1870 | nc_w[:] = np.array(self.W, dtype="f4")
1871 | #if not pyNc: nc_w._FillValue =float(self.missingNumber)
1872 |
1873 | if varsToSave == 'all' or "etaNoiseAve" in varsToSave:
1874 | nc_noiseAve = cdfFile.createVariable(
1875 | 'etaNoiseAve', 'f', ncShape2D, **fillVDict)
1876 | nc_noiseAve.description = "mean noise of one Doppler Spectrum in the same units as eta, never dealiased"
1877 | nc_noiseAve.units = "mm^6 m^-3"
1878 | nc_noiseAve[:] = np.array(self.etaNoiseAve, dtype="f4")
1879 | #if not pyNc: nc_noiseAve._FillValue =float(self.missingNumber)
1880 |
1881 | if varsToSave == 'all' or "etaNoiseStd" in varsToSave:
1882 | nc_noiseStd = cdfFile.createVariable(
1883 | 'etaNoiseStd', 'f', ncShape2D, **fillVDict)
1884 | nc_noiseStd.description = "std of noise of one Doppler Spectrum in the same units as eta, never dealiased"
1885 | nc_noiseStd.units = "mm^6 m^-3"
1886 | nc_noiseStd[:] = np.array(self.etaNoiseStd, dtype="f4")
1887 | #if not pyNc: nc_noiseStd._FillValue =float(self.missingNumber)
1888 |
1889 | if varsToSave == 'all' or "SNR" in varsToSave:
1890 | nc_SNR = cdfFile.createVariable('SNR', 'f', ncShape2D, **fillVDict)
1891 | nc_SNR.description = "signal to noise ratio of the most significant peak, never dealiased!"
1892 | nc_SNR.units = "dB"
1893 | nc_SNR[:] = np.array(self.SNR, dtype="f4")
1894 | #if not pyNc: nc_SNR._FillValue =float(self.missingNumber)
1895 |
1896 | cdfFile.close()
1897 | return
1898 |
1899 |
1900 | class mrrProcessedData:
1901 | '''
1902 | Class to read MRR average or instantaneous data
1903 | includes function to save data to netcdf
1904 |
1905 | '''
1906 | missingNumber = -9999
1907 |
1908 | def __init__(self, fname, debugLimit=0, maskData=True, verbosity=2, ncForm="NETCDF3_CLASSIC"):
1909 | """
1910 | reads MRR Average or Instantaneous data. The data is not converted, no magic! The input files can be .gz compressed. Invalid or missing data is marked as nan
1911 |
1912 | @parameter fname (str or list): list of files or Filename, wildcards allowed, or
1913 | a single netCDF filename if reading from a file previously
1914 | created by mrrProcessedData.writeNetCDF()
1915 | @parameter debugLimit (int): stop after debugLimit timestamps
1916 | @parameter maskData (bool): mask nan's in arrays
1917 | @parameter verbosity (int): 0: silent exept warnings/errors, 2:verbose
1918 | @parameter ncForm (string): set netCDF format
1919 |
1920 | No return, but provides MRR dataset variables
1921 | """
1922 |
1923 | # If this is a single filename input, and it is a netCDF
1924 | # (extension is nc or cdf), then read it directly and return.
1925 | if type(fname) is str:
1926 | if os.path.splitext(fname)[1] in ('.nc', '.cdf'):
1927 |
1928 | nc, pyNc = _get_netCDF_module(ncForm=ncForm)
1929 |
1930 | if pyNc:
1931 | cdfFile = nc.Dataset(fname, "r", format=ncForm)
1932 | else:
1933 | cdfFile = nc.NetCDFFile(fname, "r")
1934 |
1935 | self.header = cdfFile.getncattr('mrrHeader')
1936 | self.mrrTimestamps = cdfFile.variables['time'][:]
1937 | self.mrrH = cdfFile.variables['MRR_H'][:]
1938 | self.mrrTF = cdfFile.variables['MRR_TF'][:]
1939 | self.mrrF = cdfFile.variables['MRR_F'][:]
1940 | self.mrrD = cdfFile.variables['MRR_D'][:]
1941 | self.mrrN = cdfFile.variables['MRR_N'][:]
1942 | self.mrrK = cdfFile.variables['MRR_K'][:]
1943 | self.mrrCapitalZ = cdfFile.variables['MRR_Capital_Z'][:]
1944 | self.mrrSmallz = cdfFile.variables['MRR_Small_z'][:]
1945 | self.mrrPIA = cdfFile.variables['MRR_PIA'][:]
1946 | self.mrrRR = cdfFile.variables['MRR_RR'][:]
1947 | self.mrrLWC = cdfFile.variables['MRR_LWC'][:]
1948 | self.mrrW = cdfFile.variables['MRR_W'][:]
1949 |
1950 | cdfFile.close()
1951 |
1952 | self.shape2D = np.shape(self.mrrH)
1953 | self.shape3D = np.shape(self.mrrF)
1954 |
1955 | return
1956 |
1957 | # some helper functions!
1958 | def splitMrrAveData(string, debugTime, floatInt):
1959 | '''
1960 | splits one line of mrr data into list
1961 | @parameter string (str) string of MRR data
1962 | @parameter debugTime (int) time for debug output
1963 | @parameter floatInt (type) convert float or integer
1964 |
1965 | @retrun array with mrr data
1966 | '''
1967 | listOfData = list()
1968 | listOfData_append = listOfData.append
1969 |
1970 | i_start = 3
1971 | i_offset = 7
1972 | try:
1973 | for k in np.arange(i_start, i_offset*31, i_offset):
1974 | listOfData_append(mrrDataEsc(
1975 | string[k:k+i_offset], floatInt))
1976 | except:
1977 | # try to fix MRR bug
1978 | print("repairing data at " + str(unix2date(debugTime)))
1979 | string = string.replace("10000.0", "10000.")
1980 | string = string.replace("1000.00", "1000.0")
1981 | string = string.replace("100.000", "100.00")
1982 | string = string.replace("10.0000", "10.000")
1983 | string = string.replace("1.00000", "1.0000")
1984 | listOfData = list()
1985 | listOfData_append = listOfData.append
1986 | for k in np.arange(i_start, i_offset*31, i_offset):
1987 | try:
1988 | listOfData_append(mrrDataEsc(
1989 | string[k:k+i_offset], floatInt))
1990 | except:
1991 | print("######### Warning, Corrupt data at " + str(unix2date(debugTime)
1992 | ) + ", position "+str(k)+": " + string+" #########")
1993 | listOfData_append(np.nan)
1994 | return np.array(listOfData)
1995 |
1996 | def mrrDataEsc(string, floatInt):
1997 | """
1998 | set invalid data to nan!
1999 |
2000 | @parameter string (str): string from mrr data
2001 | @parameter floatInt (function): int or float function
2002 |
2003 | @return - float or int number
2004 | """
2005 |
2006 | if (string == " "*7) or (len(string) != 7):
2007 | return np.nan
2008 | else:
2009 | return floatInt(string)
2010 |
2011 | if type(fname) == list:
2012 | files = fname
2013 | else:
2014 | files = glob.glob(fname)
2015 | files.sort()
2016 |
2017 | foundAtLeastOneFile = False
2018 |
2019 | # go through all files
2020 | for f, file in enumerate(files):
2021 | if verbosity > 1:
2022 | print("%s of %s:" % (f+1, len(files)), file)
2023 |
2024 | # open file, gzip or ascii
2025 | try:
2026 | if file[-3:] == ".gz":
2027 | try:
2028 | allData = gzip.open(file, 'rt')
2029 | except:
2030 | print("could not open:", file)
2031 | raise IOError("could not open:" + file)
2032 | else:
2033 | try:
2034 | # without errors='ignore', post-processing script crashes
2035 | # when loading MRR raw file with some missing/corrupt data
2036 | # using codecs.open(... encoding='UTF-8' ...) as this seems to be
2037 | # the only method that works in python 2 and 3.
2038 | allData = codecs.open(file, 'r', encoding='UTF-8', errors='ignore')
2039 | except:
2040 | print("could not open:", file)
2041 | raise IOError("could not open:" + file)
2042 |
2043 | if len(allData.read(10)) == 0:
2044 | print(file, "empty!")
2045 | allData.close()
2046 | raise IOError("File empty")
2047 | else:
2048 | allData.seek(0)
2049 | i = 0
2050 | except IOError:
2051 | print("skipping...", file)
2052 | continue
2053 |
2054 | foundAtLeastOneFile = True
2055 |
2056 | # go through file and make a dictionary with timestamp as key and all corresponding lines of data as values
2057 | dataMRR = {}
2058 | prevDate = 0
2059 | tmpList = list()
2060 | for line in allData:
2061 | if line[0:3] == "MRR":
2062 | if i != 0:
2063 | dataMRR[prevDate] = tmpList
2064 | tmpList = []
2065 | asciiDate = line[4:20]
2066 | # We must have UTC!
2067 | if (re.search("UTC", line) == None):
2068 | sys.exit("Warning, line must start with UTC!")
2069 | date = datetime.datetime(year=2000+int(asciiDate[0:2]), month=int(asciiDate[2:4]), day=int(
2070 | asciiDate[4:6]), hour=int(asciiDate[6:8]), minute=int(asciiDate[8:10]), second=int(asciiDate[10:12]))
2071 | date = int(date2unix(date))
2072 | tmpList.append(line)
2073 | prevDate = date
2074 | else:
2075 | tmpList.append(line)
2076 | i += 1
2077 |
2078 | dataMRR[prevDate] = tmpList
2079 | allData.close()
2080 |
2081 | try:
2082 | del dataMRR[0]
2083 | print("Warning: some lines without timestamp")
2084 | except:
2085 | pass
2086 |
2087 | if debugLimit == 0:
2088 | debugLimit = len(list(dataMRR.keys()))
2089 |
2090 | # create arrays for data
2091 | aveTimestamps = np.array(np.sort(list(dataMRR.keys()))[
2092 | 0:debugLimit], dtype=int)
2093 | aveH = np.ones((debugLimit, 31), dtype=float)*np.nan
2094 | aveTF = np.ones((debugLimit, 31), dtype=float)*np.nan
2095 | aveF = np.ones((debugLimit, 31, 64), dtype=float)*np.nan
2096 | aveN = np.ones((debugLimit, 31, 64), dtype=float)*np.nan
2097 | aveD = np.ones((debugLimit, 31, 64), dtype=float)*np.nan
2098 | aveK = np.ones((debugLimit, 31), dtype=float)*np.nan
2099 | aveCapitalZ = np.ones((debugLimit, 31), dtype=float)*np.nan
2100 | aveSmallz = np.ones((debugLimit, 31), dtype=float)*np.nan
2101 | avePIA = np.ones((debugLimit, 31), dtype=float)*np.nan
2102 | aveRR = np.ones((debugLimit, 31), dtype=float)*np.nan
2103 | aveLWC = np.ones((debugLimit, 31), dtype=float)*np.nan
2104 | aveW = np.ones((debugLimit, 31), dtype=float)*np.nan
2105 |
2106 | # go through timestamps and fill up arrays
2107 | for t, timestamp in enumerate(aveTimestamps[0:debugLimit]):
2108 | # print unix2date(timestamp)
2109 | dataSet = dataMRR[timestamp]
2110 | for dataLine in dataSet:
2111 | if dataLine[0:3] == "MRR":
2112 | # just one is stored, thus no array
2113 | self.header = dataLine[21:-2]
2114 | continue # print timestamp
2115 | elif dataLine[0:3] == "H ":
2116 | aveH[t, :] = splitMrrAveData(
2117 | dataLine, timestamp, float)
2118 | continue
2119 | elif dataLine[0:3] == "TF ":
2120 | aveTF[t, :] = splitMrrAveData(
2121 | dataLine, timestamp, float)
2122 | continue # print "TF"
2123 | elif dataLine[0:1] == "F":
2124 | try:
2125 | specBin = int(dataLine[1:3])
2126 | except:
2127 | print("######### Warning, Corrupt data header at " +
2128 | str(unix2date(timestamp)) + ", " + dataLine+" #########")
2129 | continue
2130 | aveF[t, :, specBin] = splitMrrAveData(
2131 | dataLine, timestamp, float)
2132 | continue
2133 | elif dataLine[0:1] == "D":
2134 | try:
2135 | specBin = int(dataLine[1:3])
2136 | except:
2137 | print("######### Warning, Corrupt data header at " +
2138 | str(unix2date(timestamp)) + ", " + dataLine+" #########")
2139 | continue
2140 | aveD[t, :, specBin] = splitMrrAveData(
2141 | dataLine, timestamp, float)
2142 | continue
2143 | elif dataLine[0:1] == "N":
2144 | try:
2145 | specBin = int(dataLine[1:3])
2146 | except:
2147 | print("######### Warning, Corrupt data header at " +
2148 | str(unix2date(timestamp)) + ", " + dataLine+" #########")
2149 | continue
2150 | aveN[t, :, specBin] = splitMrrAveData(
2151 | dataLine, timestamp, float)
2152 | continue
2153 | elif dataLine[0:3] == "K ":
2154 | aveK[t, :] = splitMrrAveData(
2155 | dataLine, timestamp, float)
2156 | continue
2157 | elif dataLine[0:3] == "PIA":
2158 | avePIA[t, :] = splitMrrAveData(
2159 | dataLine, timestamp, float)
2160 | continue
2161 | elif dataLine[0:3] == "Z ":
2162 | aveCapitalZ[t, :] = splitMrrAveData(
2163 | dataLine, timestamp, float)
2164 | continue
2165 | elif dataLine[0:3] == "z ":
2166 | aveSmallz[t, :] = splitMrrAveData(
2167 | dataLine, timestamp, float)
2168 | continue
2169 | elif dataLine[0:3] == "RR ":
2170 | aveRR[t, :] = splitMrrAveData(
2171 | dataLine, timestamp, float)
2172 | continue
2173 | elif dataLine[0:3] == "LWC":
2174 | aveLWC[t, :] = splitMrrAveData(
2175 | dataLine, timestamp, float)
2176 | continue
2177 | elif dataLine[0:3] == "W ":
2178 | aveW[t, :] = splitMrrAveData(
2179 | dataLine, timestamp, float)
2180 | continue
2181 | elif len(dataLine) == 2:
2182 | continue
2183 | else:
2184 | print("? Line not recognized:", str(
2185 | unix2date(timestamp)), dataLine, len(dataLine))
2186 |
2187 | # join arrays of different files
2188 | try:
2189 | self.mrrTimestamps = np.concatenate(
2190 | (self.mrrTimestamps, aveTimestamps), axis=0)
2191 | self.mrrH = np.concatenate((self.mrrH, aveH), axis=0)
2192 | self.mrrTF = np.concatenate((self.mrrTF, aveTF), axis=0)
2193 | self.mrrF = np.concatenate((self.mrrF, aveF), axis=0)
2194 | self.mrrN = np.concatenate((self.mrrN, aveN), axis=0)
2195 | self.mrrD = np.concatenate((self.mrrD, aveD), axis=0)
2196 | self.mrrK = np.concatenate((self.mrrK, aveK), axis=0)
2197 | self.mrrPIA = np.concatenate((self.mrrPIA, avePIA), axis=0)
2198 | self.mrrCapitalZ = np.concatenate(
2199 | (self.mrrCapitalZ, aveCapitalZ), axis=0)
2200 | self.mrrSmallz = np.concatenate(
2201 | (self.mrrSmallz, aveSmallz), axis=0)
2202 | self.mrrRR = np.concatenate((self.mrrRR, aveRR), axis=0)
2203 | self.mrrLWC = np.concatenate((self.mrrLWC, aveLWC), axis=0)
2204 | self.mrrW = np.concatenate((self.mrrW, aveW), axis=0)
2205 | except AttributeError:
2206 | self.mrrTimestamps = aveTimestamps
2207 | self.mrrH = aveH
2208 | self.mrrTF = aveTF
2209 | self.mrrF = aveF
2210 | self.mrrN = aveN
2211 | self.mrrD = aveD
2212 | self.mrrK = aveK
2213 | self.mrrPIA = avePIA
2214 | self.mrrCapitalZ = aveCapitalZ
2215 | self.mrrSmallz = aveSmallz
2216 | self.mrrRR = aveRR
2217 | self.mrrLWC = aveLWC
2218 | self.mrrW = aveW
2219 | if foundAtLeastOneFile == False:
2220 | print("NO DATA")
2221 | raise UnboundLocalError
2222 | try:
2223 | self.header
2224 | except:
2225 | print("did not find any MRR data in file!")
2226 | raise IOError("did not find any MRR data in file!")
2227 | del aveTimestamps, aveH, aveTF, aveF, aveN, aveD, aveK, avePIA, aveCapitalZ, aveSmallz, aveRR, aveLWC, aveW
2228 |
2229 | if maskData:
2230 | self.mrrTimestamps = np.ma.masked_array(
2231 | self.mrrTimestamps, np.isnan(self.mrrTimestamps))
2232 | self.mrrH = np.ma.masked_array(self.mrrH, np.isnan(self.mrrH))
2233 | self.mrrTF = np.ma.masked_array(self.mrrTF, np.isnan(self.mrrTF))
2234 | self.mrrF = np.ma.masked_array(self.mrrF, np.isnan(self.mrrF))
2235 | self.mrrN = np.ma.masked_array(self.mrrN, np.isnan(self.mrrN))
2236 | self.mrrD = np.ma.masked_array(self.mrrD, np.isnan(self.mrrD))
2237 | self.mrrK = np.ma.masked_array(self.mrrK, np.isnan(self.mrrK))
2238 | self.mrrPIA = np.ma.masked_array(
2239 | self.mrrPIA, np.isnan(self.mrrPIA))
2240 | self.mrrCapitalZ = np.ma.masked_array(
2241 | self.mrrCapitalZ, np.isnan(self.mrrCapitalZ))
2242 | self.mrrSmallz = np.ma.masked_array(
2243 | self.mrrSmallz, np.isnan(self.mrrSmallz))
2244 | self.mrrRR = np.ma.masked_array(self.mrrRR, np.isnan(self.mrrRR))
2245 | self.mrrLWC = np.ma.masked_array(
2246 | self.mrrLWC, np.isnan(self.mrrLWC))
2247 | self.mrrW = np.ma.masked_array(self.mrrW, np.isnan(self.mrrW))
2248 |
2249 | self.shape2D = np.shape(self.mrrH)
2250 | self.shape3D = np.shape(self.mrrF)
2251 |
2252 | if verbosity > 0:
2253 | print("done reading")
2254 | # end def __init__
2255 |
2256 | def writeNetCDF(self, fileOut, author="IMProToo", location="", institution="", ncForm="NETCDF3_CLASSIC"):
2257 | '''
2258 | writes MRR Average or Instantaneous Data into Netcdf file
2259 |
2260 | @parameter fileOut (str): netCDF file name
2261 | @parameter author (str): Author for netCDF meta data (default:IMProToo)
2262 | @parameter location (str): Location of instrument for NetCDF Metadata (default: "")
2263 | @parameter institution (str): Institution to whom the instrument belongs (default: "")
2264 | @parameter ncForm (str): netCDF Format, possible values are NETCDF3_CLASSIC, NETCDF3_64BIT, NETCDF4_CLASSIC, and NETCDF4 for the python-netcdf4 package, NETCDF3 takes the "old" Scientific.IO.NetCDF module, which is a bit more convinient to install or as fall back option python-netcdf3
2265 |
2266 | '''
2267 |
2268 | nc, pyNc = _get_netCDF_module(ncForm=ncForm)
2269 |
2270 | if pyNc:
2271 | cdfFile = nc.Dataset(fileOut, "w", format=ncForm)
2272 | else:
2273 | cdfFile = nc.NetCDFFile(fileOut, "w")
2274 |
2275 | fillVDict = dict()
2276 | # little cheat to avoid hundreds of if, else...
2277 | if pyNc:
2278 | fillVDict["fill_value"] = self.missingNumber
2279 |
2280 | print("writing %s ..." % (fileOut))
2281 | # Attributes
2282 | cdfFile.history = 'Created with IMProToo v' + __version__
2283 | cdfFile.author = 'Max Maahn'
2284 | cdfFile.processing_date = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
2285 | cdfFile.reference = 'Maahn, M. and Kollias, P., 2012: Improved Micro Rain Radar snow measurements using Doppler spectra post-processing, Atmos. Meas. Tech., 5, 2661-2673, doi:10.5194/amt-5-2661-2012. '
2286 | cdfFile.title = 'Micro rain radar averaged data (Metek standard output) converted to netcdf'
2287 | cdfFile.comment = 'This data is only valid in case of liquid precipitation. Note that this data has been processed regardless of precipitation type and additional external information about precipitation type is needed for correct interpretation of the measurements.'
2288 | cdfFile.institution = institution
2289 | cdfFile.contact_person = author
2290 | cdfFile.source = 'MRR-2'
2291 | cdfFile.location = location
2292 | cdfFile.mrrHeader = self.header
2293 |
2294 | # Dimensions
2295 | cdfFile.createDimension('MRR rangegate', 31)
2296 | cdfFile.createDimension('time', None) # allows Multifile read
2297 | cdfFile.createDimension('MRR spectralclass', 64)
2298 |
2299 | nc_times = cdfFile.createVariable('time', 'i', ('time',), **fillVDict)
2300 | nc_ranges = cdfFile.createVariable(
2301 | 'MRR rangegate', 'f', ('time', 'MRR rangegate',), **fillVDict)
2302 | nc_classes = cdfFile.createVariable(
2303 | 'MRR spectralclass', 'i', ('MRR spectralclass',))
2304 |
2305 | nc_times.units = 'seconds since 1970-01-01 00:00:00'
2306 | nc_ranges.units = 'm'
2307 | nc_classes.units = 'none'
2308 |
2309 | # Create Variables
2310 | nc_h = cdfFile.createVariable(
2311 | 'MRR_H', 'f', ('time', 'MRR rangegate',), **fillVDict)
2312 | nc_h.units = 'm'
2313 |
2314 | nc_tf = cdfFile.createVariable(
2315 | 'MRR_TF', 'f', ('time', 'MRR rangegate',), **fillVDict)
2316 | nc_tf.units = 'none'
2317 |
2318 | nc_f = cdfFile.createVariable(
2319 | 'MRR_F', 'f', ('time', 'MRR rangegate', 'MRR spectralclass',), **fillVDict)
2320 | nc_f.units = 'dB'
2321 |
2322 | nc_d = cdfFile.createVariable(
2323 | 'MRR_D', 'f', ('time', 'MRR rangegate', 'MRR spectralclass',), **fillVDict)
2324 | nc_d.units = 'mm'
2325 |
2326 | nc_n = cdfFile.createVariable(
2327 | 'MRR_N', 'f', ('time', 'MRR rangegate', 'MRR spectralclass',), **fillVDict)
2328 | nc_n.units = 'm^-3 mm^-1'
2329 |
2330 | nc_k = cdfFile.createVariable(
2331 | 'MRR_K', 'f', ('time', 'MRR rangegate',), **fillVDict)
2332 | nc_k.units = 'dB'
2333 |
2334 | nc_capitalZ = cdfFile.createVariable(
2335 | 'MRR_Capital_Z', 'f', ('time', 'MRR rangegate',), **fillVDict)
2336 | nc_capitalZ.units = 'dBz'
2337 |
2338 | nc_smallz = cdfFile.createVariable(
2339 | 'MRR_Small_z', 'f', ('time', 'MRR rangegate',), **fillVDict)
2340 | nc_smallz.units = 'dBz'
2341 |
2342 | nc_pia = cdfFile.createVariable(
2343 | 'MRR_PIA', 'f', ('time', 'MRR rangegate',), **fillVDict)
2344 | nc_pia.units = 'dB'
2345 |
2346 | nc_rr = cdfFile.createVariable(
2347 | 'MRR_RR', 'f', ('time', 'MRR rangegate',), **fillVDict)
2348 | nc_rr.units = 'mm/h'
2349 |
2350 | nc_lwc = cdfFile.createVariable(
2351 | 'MRR_LWC', 'f', ('time', 'MRR rangegate',), **fillVDict)
2352 | nc_lwc.units = 'g/m^3'
2353 |
2354 | nc_w = cdfFile.createVariable(
2355 | 'MRR_W', 'f', ('time', 'MRR rangegate',), **fillVDict)
2356 | nc_w.units = 'm s^-1'
2357 |
2358 | # fill dimensions
2359 | nc_classes[:] = np.arange(0, 64, 1, dtype="i4")
2360 | nc_times[:] = np.array(self.mrrTimestamps, dtype="i4")
2361 | nc_ranges[:] = np.array(self.mrrH, dtype="f4")
2362 |
2363 | # fill data
2364 | nc_h[:] = np.array(self.mrrH, dtype="f4")
2365 | nc_tf[:] = np.array(self.mrrTF, dtype="f4")
2366 | nc_f[:] = np.array(self.mrrF, dtype="f4")
2367 | nc_d[:] = np.array(self.mrrD, dtype="f4")
2368 | nc_n[:] = np.array(self.mrrN, dtype="f4")
2369 | nc_k[:] = np.array(self.mrrK, dtype="f4")
2370 | nc_capitalZ[:] = np.array(self.mrrCapitalZ, dtype="f4")
2371 | nc_smallz[:] = np.array(self.mrrSmallz, dtype="f4")
2372 | nc_pia[:] = np.array(self.mrrPIA, dtype="f4")
2373 | nc_rr[:] = np.array(self.mrrRR, dtype="f4")
2374 | nc_lwc[:] = np.array(self.mrrLWC, dtype="f4")
2375 | nc_w[:] = np.array(self.mrrW, dtype="f4")
2376 |
2377 | # commented because of Ubuntu bug: https://bugs.launchpad.net/ubuntu/+source/python-scientific/+bug/1005571
2378 | # if not pyNc:
2379 | ##import pdb;pdb.set_trace()
2380 | #nc_ranges._FillValue =float(self.missingNumber)
2381 | #nc_tf._FillValue =float(self.missingNumber)
2382 | #nc_f._FillValue =float(self.missingNumber)
2383 | #nc_d._FillValue =float(self.missingNumber)
2384 | #nc_n._FillValue =float(self.missingNumber)
2385 | #nc_k._FillValue =float(self.missingNumber)
2386 | #nc_capitalZ._FillValue =float(self.missingNumber)
2387 | #nc_smallz._FillValue =float(self.missingNumber)
2388 | #nc_pia._FillValue =float(self.missingNumber)
2389 | #nc_rr._FillValue =float(self.missingNumber)
2390 | #nc_lwc._FillValue =float(self.missingNumber)
2391 | #nc_w._FillValue =float(self.missingNumber)
2392 |
2393 | cdfFile.close()
2394 | print("done")
2395 | # end def writeNetCDF
2396 | # end class MrrData
2397 |
2398 |
2399 | class mrrRawData:
2400 | '''
2401 | Class to read MRR raw data
2402 | includes function to save data to netcdf
2403 | '''
2404 |
2405 | missingNumber = -9999
2406 |
2407 | def __init__(self, fname, debugStart=0, debugLimit=0, maskData=True, ncForm="NETCDF3_CLASSIC"):
2408 | """
2409 | reads MRR raw data. The data is not converted, no magic! The input files can be .gz compressed.
2410 | A single netCDF file can be input, that was previously created from mrrRawData.writeNetCDF()
2411 | Invalid or Missing data is marked as nan and masked
2412 |
2413 | Since MRR raw data can contains all teh data transfered on the serial bus, a lot warnings can be raised. Usually these can be ignored.
2414 |
2415 | @parameter fname (str or list): list of files or Filename, wildcards allowed!
2416 | a single netCDF filename if reading from a file previously
2417 | created by mrrProcessedData.writeNetCDF()
2418 | @parameter debugstart (int): start after debugstart timestamps
2419 | @parameter debugLimit (int): stop after debugLimit timestamps
2420 | @parameter ncForm (string): set netCDF format
2421 |
2422 | provides:
2423 | mrrRawTime (numpy int64): timestamps in seconds since 01-01-1970 (time)
2424 | mrrRawHeight (numpy float64): height levels (time*height)
2425 | mrrRawTF (numpy float64): Transfer function (time*height)
2426 | mrrRawSpectrum (numpy float64): spectral reflectivities of MRR raw data (time*height*velocity)
2427 | """
2428 |
2429 | # only provided in newer Firmware, has to be guessed for older ones
2430 | self.defaultSpecPer10Sec = 58
2431 | self.timezone = None
2432 |
2433 | # If this is a single filename input, and it is a netCDF
2434 | # (extension is nc or cdf), then read it directly and return.
2435 | if type(fname) is str:
2436 | if os.path.splitext(fname)[1] in ('.nc', '.cdf'):
2437 |
2438 | nc, pyNc = _get_netCDF_module(ncForm=ncForm)
2439 |
2440 | if pyNc:
2441 | cdfFile = nc.Dataset(fname, "r", format=ncForm)
2442 | else:
2443 | cdfFile = nc.NetCDFFile(fname, "r")
2444 |
2445 | self.header = cdfFile.getncattr('mrrHeader')
2446 | self.mrrRawCC = cdfFile.getncattr('mrrCalibrationConstant')
2447 | self.mrrRawHeight = cdfFile.variables['MRR rangegate'][:]
2448 | self.mrrRawTime = cdfFile.variables['MRR time'][:]
2449 | self.mrrRawTF = cdfFile.variables['MRR_TF'][:]
2450 | self.mrrRawSpectrum = cdfFile.variables['MRR_Spectra'][:]
2451 | self.mrrRawNoSpec = cdfFile.variables['MRR_NoSpectra'][:]
2452 |
2453 | try:
2454 | self.timezone = str(cdfFile.variables['MRR time'].timezone)
2455 | except AttributeError:
2456 | # this can occur when loading a file created with an older
2457 | # version of IMProToo, before the timezone update.
2458 | warnings.warn("timezone attribute missing, assuming UTC")
2459 | self.timezone = "UTC"
2460 |
2461 | cdfFile.close()
2462 |
2463 | self.shape2D = np.shape(self.mrrRawHeight)
2464 | self.shape3D = np.shape(self.mrrRawSpectrum)
2465 |
2466 | return
2467 |
2468 | # some helper functions
2469 | def rawEsc(string, floatInt):
2470 | """
2471 | set invalid data to nan!
2472 |
2473 | @parameter string (str): string from mrr data
2474 | @parameter floatInt (function): int or float function
2475 |
2476 | @return - float or int number
2477 | """
2478 |
2479 | if (string == " "*9) or (len(string) != 9):
2480 | return np.nan
2481 | else:
2482 | return floatInt(string)
2483 |
2484 | def splitMrrRawData(string, debugTime, floatInt, startI):
2485 | '''
2486 | splits one line of mrr raw data into list
2487 | @parameter string (str) string of MRR data
2488 | @parameter debugTime (int) time for debug output
2489 | @parameter floatInt (type) convert float or integer
2490 | @parameter startI (int) first data index, old file format 6, new 3
2491 | @retrun array with mrr data
2492 | '''
2493 |
2494 | instData = list()
2495 | instData_append = instData.append
2496 |
2497 | for k in np.arange(startI, 9*32, 9):
2498 | try:
2499 | instData_append(rawEsc(string[k:k+9], floatInt))
2500 | except:
2501 | print("######### Warning, Corrupt data at " + str(unix2date(debugTime)) +
2502 | ", " + str(timestamp) + ", position "+str(k)+": " + string+" #########")
2503 | instData_append(np.nan)
2504 | return np.array(instData)
2505 |
2506 | if type(fname) == list:
2507 | files = fname
2508 | else:
2509 | files = glob.glob(fname)
2510 | files.sort()
2511 |
2512 | foundAtLeastOneFile = False
2513 |
2514 | # go thorugh all files
2515 | for f, file in enumerate(files):
2516 | print("%s of %s:" % (f+1, len(files)), file)
2517 | # open file gz or ascii
2518 | try:
2519 | if file[-3:] == ".gz":
2520 | try:
2521 | allData = gzip.open(file, 'rt')
2522 | except:
2523 | print("could not open:", file)
2524 | raise IOError("could not open:" + file)
2525 | else:
2526 | try:
2527 | # without errors='ignore', post-processing script crashes
2528 | # when loading MRR raw file with some missing/corrupt data
2529 | # using codecs.open(... encoding='UTF-8' ...) as this seems to be
2530 | # the only method that works in python 2 and 3.
2531 | allData = codecs.open(file, 'r', encoding='UTF-8', errors='ignore')
2532 | except:
2533 | print("could not open:", file)
2534 | raise IOError("could not open:" + file)
2535 |
2536 | if len(allData.read(10)) == 0:
2537 | print(file, "empty!")
2538 | allData.close()
2539 | raise IOError("File empty")
2540 | else:
2541 | allData.seek(0)
2542 | i = 0
2543 | except IOError:
2544 | print("skipping...")
2545 | continue
2546 |
2547 | foundAtLeastOneFile = True
2548 |
2549 | # go through file and make a dictionary with timestamp as key and all corresponding lines of data as values
2550 | dataMRR = {}
2551 | prevDate = 0
2552 | tmpList = list()
2553 |
2554 | # preset, is changed in 8 lines if required
2555 | fileFormat = "new"
2556 |
2557 | for line in allData:
2558 | if line[0:2] == "T:" or line[0:3] == "MRR":
2559 | if i != 0:
2560 | dataMRR[prevDate] = tmpList
2561 | tmpList = []
2562 | if line[0:2] == "T:":
2563 | asciiDate = line[2:14] # old mrr raw data
2564 | fileFormat = "old" # if there
2565 | elif line[0:4] == "MRR ":
2566 | asciiDate = line[4:16] # new mrr raw spectra
2567 | else:
2568 | raise IOError("must be either new or old file format!")
2569 | # Script wants UTC!
2570 | date = datetime.datetime(year=2000+int(asciiDate[0:2]), month=int(asciiDate[2:4]), day=int(
2571 | asciiDate[4:6]), hour=int(asciiDate[6:8]), minute=int(asciiDate[8:10]), second=int(asciiDate[10:12]))
2572 | date = int(date2unix(date))
2573 | tmpList.append(line)
2574 | prevDate = date
2575 | else:
2576 | tmpList.append(line)
2577 | i += 1
2578 | # end for line
2579 | dataMRR[prevDate] = tmpList
2580 | allData.close()
2581 |
2582 | try:
2583 | del dataMRR[0]
2584 | warnings.warn("Warning: some lines without timestamp")
2585 | except:
2586 | pass
2587 |
2588 | if fileFormat == "new":
2589 | startIndex = 3
2590 | elif fileFormat == "old":
2591 | startIndex = 6
2592 | else:
2593 | raise IOError("must be either new or old file format!")
2594 |
2595 | if debugLimit == 0:
2596 | debugLimit = len(list(dataMRR.keys()))
2597 |
2598 | specLength = debugLimit - debugStart
2599 |
2600 | # create arrays for data
2601 | rawSpectra = np.ones((specLength, 32, 64), dtype=int)*np.nan
2602 | rawTimestamps = np.array(np.sort(list(dataMRR.keys()))[
2603 | debugStart:debugLimit], dtype=int)
2604 | rawHeights = np.ones((specLength, 32), dtype=int)*np.nan
2605 | rawTFs = np.ones((specLength, 32), dtype=float)*np.nan
2606 | rawNoSpec = np.zeros(specLength, dtype=int)
2607 |
2608 | # default value - if the whole file is processed without ever setting mrrRawCC, this
2609 | # means the file is not usable for Ze calculations, but there is no workaround there.
2610 | self.mrrRawCC = 0
2611 |
2612 | # go through timestamps and fill up arrays
2613 | for t, timestamp in enumerate(rawTimestamps):
2614 | dataSet = dataMRR[timestamp]
2615 | for dataLine in dataSet:
2616 | if dataLine[0:2] == "T:" or dataLine[0:3] == "MRR":
2617 | # store the first or second header line as an example, but parse every one
2618 | # to check for the CC and number of spectra variables. The first header line
2619 | # of MRR data might be messed up after starting the MRR, so the second one
2620 | # is used if available.
2621 | if t in [0, 1]:
2622 | self.header = dataLine
2623 | headerLineCC, headerLineNumSpectra, timezone = self.parseHeaderLine(
2624 | dataLine, fileFormat)
2625 | if headerLineCC is not None:
2626 | self.mrrRawCC = headerLineCC
2627 | if headerLineNumSpectra is not None:
2628 | rawNoSpec[t] = headerLineNumSpectra
2629 | else:
2630 | # if fileFormat is "old", then the default value must always be taken;
2631 | # otherwise, use the value from the headerLine, if present, otherwise
2632 | # print a warning, since that means the headerLine had a problem.
2633 | if fileFormat == "new":
2634 | warnings.warn(
2635 | 'Warning, could not read number of Spectra, taking default instead: '+self.defaultSpecPer10Sec)
2636 | rawNoSpec[t] = self.defaultSpecPer10Sec
2637 | if self.timezone is None:
2638 | self.timezone = timezone
2639 | else:
2640 | assert self.timezone == timezone
2641 |
2642 | continue # print timestamp
2643 | elif dataLine[0:3] == "M:h" or dataLine[0] == "H":
2644 | rawHeights[t, :] = splitMrrRawData(
2645 | dataLine, timestamp, int, startIndex)
2646 | continue # print "H"
2647 | elif dataLine[0:4] == "M:TF" or dataLine[0:2] == "TF":
2648 | rawTFs[t, :] = splitMrrRawData(
2649 | dataLine, timestamp, float, startIndex)
2650 | continue # print "TF"
2651 | elif dataLine[0:3] == "M:f" or dataLine[0] == "F":
2652 | try:
2653 | if fileFormat == "old":
2654 | specBin = int(dataLine[3:5])
2655 | else:
2656 | specBin = int(dataLine[1:3])
2657 | except:
2658 | warnings.warn("######### Warning, Corrupt data header at " + str(
2659 | unix2date(timestamp)) + ", " + str(timestamp) + ", " + dataLine+" #########")
2660 | continue
2661 | rawSpectra[t, :, specBin] = splitMrrRawData(
2662 | dataLine, timestamp, int, startIndex)
2663 | continue
2664 | elif (dataLine[0:2] == "C:") or (dataLine[0:2] == "R:"):
2665 | continue
2666 | else:
2667 | warnings.warn("? Line not recognized:" + dataLine)
2668 |
2669 | # end for t,timestamp
2670 |
2671 | # discard spectra which are only partly valid!
2672 |
2673 | rawSpectra[np.any(np.isnan(rawSpectra), axis=2)] = np.nan
2674 | rawSpectra[np.any(np.isnan(rawTFs), axis=1)] = np.nan
2675 | rawSpectra[np.any(np.isnan(rawHeights), axis=1)] = np.nan
2676 | rawTFs[np.any(np.isnan(rawTFs), axis=1)] = np.nan
2677 | rawHeights[np.any(np.isnan(rawHeights), axis=1)] = np.nan
2678 |
2679 | # join arrays of different days
2680 | try:
2681 | self.mrrRawHeight = np.concatenate(
2682 | (self.mrrRawHeight, rawHeights), axis=0)
2683 | self.mrrRawTime = np.concatenate(
2684 | (self.mrrRawTime, rawTimestamps), axis=0)
2685 | self.mrrRawTF = np.concatenate((self.mrrRawTF, rawTFs), axis=0)
2686 | self.mrrRawSpectrum = np.concatenate(
2687 | (self.mrrRawSpectrum, rawSpectra), axis=0)
2688 | self.mrrRawNoSpec = np.concatenate(
2689 | (self.mrrRawNoSpec, rawNoSpec), axis=0)
2690 | except AttributeError:
2691 | self.mrrRawHeight = rawHeights
2692 | self.mrrRawTime = rawTimestamps
2693 | self.mrrRawTF = rawTFs
2694 | self.mrrRawSpectrum = rawSpectra
2695 | self.mrrRawNoSpec = rawNoSpec
2696 | # end try
2697 | # end for f,file
2698 |
2699 | if foundAtLeastOneFile == False:
2700 | raise UnboundLocalError("No files found: " + fname)
2701 | try:
2702 | self.header
2703 | except:
2704 | print("did not find any MRR data in file!")
2705 | raise IOError("did not find any MRR data in file!")
2706 | del rawHeights, rawTimestamps, rawTFs, rawSpectra
2707 |
2708 | if maskData:
2709 | self.mrrRawHeight = np.ma.masked_array(
2710 | self.mrrRawHeight, np.isnan(self.mrrRawHeight))
2711 | self.mrrRawTime = np.ma.masked_array(
2712 | self.mrrRawTime, np.isnan(self.mrrRawTime))
2713 | self.mrrRawTF = np.ma.masked_array(
2714 | self.mrrRawTF, np.isnan(self.mrrRawTF))
2715 | self.mrrRawSpectrum = np.ma.masked_array(
2716 | self.mrrRawSpectrum, np.isnan(self.mrrRawSpectrum))
2717 |
2718 | self.shape2D = np.shape(self.mrrRawHeight)
2719 | self.shape3D = np.shape(self.mrrRawSpectrum)
2720 |
2721 | # end def __init__
2722 |
2723 | @staticmethod
2724 | def parseHeaderLine(headerLine, fileFormat):
2725 | '''
2726 | Parses the raw data header line.
2727 | Tries to parse according to the fileFormat ("old", or "new")
2728 | Prints a warning if unsuccessful.
2729 | '''
2730 |
2731 | tokens = headerLine.split()
2732 |
2733 | CC = None
2734 | numSpectra = None
2735 |
2736 | try:
2737 | idx = tokens.index('CC')
2738 | except:
2739 | warnings.warn('Warning, could not find Keyword CC in :'+headerLine)
2740 | else:
2741 | try:
2742 | CC = int(tokens[idx+1])
2743 | except:
2744 | warnings.warn('Warning, could not read CC in: ' + headerLine)
2745 |
2746 | if fileFormat == "new":
2747 | if not tokens[2].startswith("UTC"):
2748 | raise IOError("ERROR, timestring must start with UTC!")
2749 | timezone = tokens[2]
2750 | if tokens[-1] != "RAW":
2751 | raise IOError("Was expecting MRR RAW DATA, found: "+tokens[-1])
2752 | try:
2753 | idx = tokens.index('MDQ')
2754 | except:
2755 | warnings.warn(
2756 | 'Warning, could not find Keyword MDQ in :'+headerLine)
2757 | else:
2758 | try:
2759 | numSpectra = int(tokens[idx+2])
2760 | except:
2761 | warnings.warn(
2762 | 'Warning, could not read number of Spectra: in ' + headerLine)
2763 |
2764 | elif fileFormat == "old":
2765 | if tokens[1] != "UTC":
2766 | raise IOError("ERROR, time must be UTC!")
2767 | timezone = tokens[1]
2768 |
2769 | else:
2770 | raise IOError("must be either new or old file format!")
2771 |
2772 | return CC, numSpectra, timezone
2773 |
2774 | def writeNetCDF(self, fileOut, author="IMProToo", description="MRR Raw Data", ncForm='NETCDF3_CLASSIC'):
2775 | '''
2776 | writes MRR raw Data into Netcdf file
2777 |
2778 | @parameter fileOut (str): netCDF file name
2779 | @parameter author (str): Author for netCDF meta data (default:IMProToo)
2780 | @parameter description (str): Description for NetCDF Metadata (default: empty)
2781 | @parameter netcdfFormat (str): netcdf format, possible values are NETCDF3_CLASSIC, NETCDF3_64BIT, NETCDF4_CLASSIC, and NETCDF4 for the python-netcdf4 package, NETCDF3 takes the "old" Scientific.IO.NetCDF module, which is a bit more convinient to install or as fall back option python-netcdf3
2782 | '''
2783 |
2784 | nc, pyNc = _get_netCDF_module(ncForm=ncForm)
2785 |
2786 | if pyNc:
2787 | cdfFile = nc.Dataset(fileOut, "w", format=ncForm)
2788 | else:
2789 | cdfFile = nc.NetCDFFile(fileOut, "w")
2790 |
2791 | print("writing %s ..." % (fileOut))
2792 | # Attributes
2793 | cdfFile.history = 'Created ' + str(time.ctime(time.time()))
2794 | cdfFile.source = 'Created by '+author + ' with IMProToo v' + __version__
2795 | cdfFile.mrrHeader = self.header
2796 | cdfFile.description = description
2797 | cdfFile.mrrCalibrationConstant = self.mrrRawCC
2798 |
2799 | fillVDict = dict()
2800 | # little cheat to avoid hundreds of if, else...
2801 | if pyNc:
2802 | fillVDict["fill_value"] = self.missingNumber
2803 |
2804 | # Dimensions
2805 | cdfFile.createDimension('MRR rangegate', 32)
2806 | cdfFile.createDimension('time', None) # allows Multifile read
2807 | cdfFile.createDimension('MRR spectralclass', 64)
2808 |
2809 | nc_times = cdfFile.createVariable(
2810 | 'MRR time', 'i', ('time',), **fillVDict)
2811 | nc_ranges = cdfFile.createVariable(
2812 | 'MRR rangegate', 'f', ('time', 'MRR rangegate',))
2813 | nc_classes = cdfFile.createVariable(
2814 | 'MRR spectralclass', 'i', ('MRR spectralclass',), **fillVDict)
2815 |
2816 | nc_times.units = 'seconds since 1970-01-01 00:00:00'
2817 | nc_times.timezone = self.timezone
2818 | nc_ranges.units = 'm'
2819 | nc_classes.units = 'none'
2820 |
2821 | # Create Variables
2822 | nc_tf = cdfFile.createVariable(
2823 | 'MRR_TF', 'f', ('time', 'MRR rangegate',), **fillVDict)
2824 | nc_tf.units = 'none'
2825 |
2826 | nc_spectra = cdfFile.createVariable(
2827 | 'MRR_Spectra', 'f', ('time', 'MRR rangegate', 'MRR spectralclass',), **fillVDict)
2828 | nc_spectra.units = 'none'
2829 |
2830 | nc_noSpec = cdfFile.createVariable(
2831 | 'MRR_NoSpectra', 'i', ('time',), **fillVDict)
2832 | nc_noSpec.units = 'none'
2833 |
2834 | # fill dimensions
2835 | nc_classes[:] = np.array(np.arange(0, 64, 1), dtype="i4")
2836 | nc_times[:] = np.array(self.mrrRawTime, dtype="i4")
2837 | nc_ranges[:] = np.array(self.mrrRawHeight, dtype="f4")
2838 |
2839 | # fill data
2840 | nc_tf[:] = np.array(self.mrrRawTF, dtype="f4")
2841 | nc_spectra[:] = np.array(self.mrrRawSpectrum, dtype="f4")
2842 | nc_noSpec[:] = np.array(self.mrrRawNoSpec, dtype="i4")
2843 |
2844 | # commented because of Ubuntu bug: https://bugs.launchpad.net/ubuntu/+source/python-scientific/+bug/1005571
2845 | # if not pyNc:
2846 | #nc_noSpec._FillValue =int(self.missingNumber)
2847 | #nc_spectra._FillValue =float(self.missingNumber)
2848 | #nc_tf._FillValue =float(self.missingNumber)
2849 | #nc_ranges._FillValue =float(self.missingNumber)
2850 |
2851 | cdfFile.close()
2852 | print("done")
2853 | # end def write2NetCDF
2854 | # end class MrrData
2855 |
--------------------------------------------------------------------------------
/IMProToo/tools.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | '''
3 | IMProToo
4 | Improved MRR Processing Tool
5 |
6 | Python toolkit to read write and process MRR Data. Raw Data, Average and
7 | Instantaneous Data are supported.
8 |
9 | This file includes some helper functions
10 |
11 | Copyright (C) 2011-2021 Maximilian Maahn, U Leipzig
12 | maximilian.maahn_AT_uni-leipzig.de
13 | https://github.com/maahn/IMProToo
14 |
15 | This program is free software: you can redistribute it and/or modify
16 | it under the terms of the GNU General Public License as published by
17 | the Free Software Foundation, either version 3 of the License, or
18 | any later version.
19 |
20 | This program is distributed in the hope that it will be useful,
21 | but WITHOUT ANY WARRANTY; without even the implied warranty of
22 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 | GNU General Public License for more details.
24 |
25 | You should have received a copy of the GNU General Public License
26 | along with this program. If not, see .
27 |
28 |
29 |
30 | IMProTooTools: various helper functions
31 |
32 |
33 | '''
34 | from __future__ import division
35 | from __future__ import print_function
36 |
37 | import numpy as np
38 | import time
39 | import datetime
40 | import calendar
41 | import warnings
42 |
43 | #warnings.filterwarnings('always', '.*', UserWarning,)
44 |
45 |
46 | def getManualQualityArray(inputFile, timeVector):
47 | '''
48 | returns quality array for timevector using inputFile. See readQualityFile for details about inputFile.
49 | '''
50 | startTimes, endTimes, comments = readQualityFile(inputFile)
51 | quality = np.zeros(timeVector.shape, dtype=bool)
52 | for startTime, endTime in zip(startTimes, endTimes):
53 | startTime = date2unix(startTime)
54 | endTime = date2unix(endTime)
55 | quality = quality + ((timeVector >= startTime)
56 | * (timeVector < endTime))
57 | return quality
58 |
59 |
60 | def readQualityFile(inputFile):
61 | '''
62 | reads manual quality control files, format is like ancient 'Hatpro" format:
63 |
64 | file format is:
65 | date, no of entries for this day, starttime (00.00 - 23:59), endtime (00:01 - 24:00), comment
66 | 120105 3 11.00 17.00 snow on dish
67 | 19.00 20.00 snow on dish
68 | 22.00 24.00 interference
69 | 120106 1 00.00 21.00 snow on dish
70 | #this is a comment
71 | 120107 1 00.00 24.00 maintenance
72 |
73 | '''
74 | startTimes = list()
75 | endTimes = list()
76 | comments = list()
77 |
78 | belongsToOldDate = 1
79 | ll = -1
80 |
81 | f = open(inputFile, "r")
82 | for line in f.readlines():
83 | ll += 1
84 | fields = line.split()
85 | try:
86 | # check for comments
87 | if fields[0][0:1] == '#':
88 | print('comment', ' '.join(fields))
89 | continue
90 | # does the line hav its own timestamp?
91 | if belongsToOldDate == 1:
92 | startDate = fields[0]
93 | belongsToOldDate = int(fields[1])
94 | startTime = fields[2]
95 | endTime = fields[3]
96 | comment = ' '.join(fields[4:])
97 | else:
98 | startTime = fields[0]
99 | endTime = fields[1]
100 | comment = ' '.join(fields[2:])
101 | belongsToOldDate -= 1
102 | # yes, 24.00 is a weired timestamp, correct this to 00.00 next day
103 | if endTime == '24.00':
104 | #import pdb;pdb.set_trace()
105 | endDate = datetime.datetime.strftime((datetime.datetime.strptime(
106 | startDate, '%y%m%d')+datetime.timedelta(1)), '%y%m%d')
107 | endTime = '00.00'
108 | else:
109 | endDate = startDate
110 | comment = ' '.join(fields[4:])
111 | startTimes.append(datetime.datetime.strptime(
112 | startDate+' '+startTime, '%y%m%d %H.%M'))
113 | endTimes.append(datetime.datetime.strptime(
114 | endDate+' '+endTime, '%y%m%d %H.%M'))
115 | comments.append(comment)
116 | except:
117 | belongsToOldDate = 1
118 | warnings.warn('Could not read line no. '+str(ll) + str(fields))
119 |
120 | f.close()
121 |
122 | return startTimes, endTimes, comments
123 |
124 |
125 | def date2unix(date):
126 | '''
127 | converts datetime object to seconds since 01-01-1970
128 | '''
129 | return calendar.timegm(date.timetuple())
130 |
131 |
132 | def unix2date(unix):
133 | '''
134 | converts seconds since 01-01-1970 to datetime object
135 | '''
136 |
137 | return datetime.datetime.utcfromtimestamp(unix)
138 |
139 |
140 | def quantile(x, q, qtype=7, issorted=False):
141 | """
142 | Args:
143 | x - input data
144 | q - quantile
145 | qtype - algorithm
146 | issorted- True if x already sorted.
147 |
148 | Compute quantiles from input array x given q.For median,
149 | specify q=0.5.
150 |
151 | References:
152 | http://reference.wolfram.com/mathematica/ref/Quantile.html
153 | http://wiki.r-project.org/rwiki/doku.php?id=rdoc:stats:quantile
154 |
155 | Author:
156 | Ernesto P.Adorio Ph.D.
157 | UP Extension Program in Pampanga, Clark Field.
158 | """
159 | if not issorted:
160 | y = sorted(x)
161 | else:
162 | y = x
163 | if not (1 <= qtype <= 9):
164 | return None # error!
165 |
166 | # Parameters for the Hyndman and Fan algorithm
167 | abcd = [(0, 0, 1, 0), # inverse empirical distrib.function., R type 1
168 | (0.5, 0, 1, 0), # similar to type 1, averaged, R type 2
169 | (0.5, 0, 0, 0), # nearest order statistic,(SAS) R type 3
170 |
171 | (0, 0, 0, 1), # California linear interpolation, R type 4
172 | (0.5, 0, 0, 1), # hydrologists method, R type 5
173 | # mean-based estimate(Weibull method), (SPSS,Minitab), type 6
174 | (0, 1, 0, 1),
175 | (1, -1, 0, 1), # mode-based method,(S, S-Plus), R type 7
176 | (1.0/3, 1.0/3, 0, 1), # median-unbiased , R type 8
177 | (3/8.0, 0.25, 0, 1) # normal-unbiased, R type 9.
178 | ]
179 |
180 | a, b, c, d = abcd[qtype-1]
181 | n = len(x)
182 | g, j = np.modf(a + (n+b) * q - 1)
183 | if j < 0:
184 | return y[0]
185 | elif j >= n:
186 | return y[n-1] # oct. 8, 2010 y[n]???!! uncaught off by 1 error!!!
187 |
188 | j = int(np.floor(j))
189 | if g == 0:
190 | return y[j]
191 | else:
192 | return y[j] + (y[j+1] - y[j]) * (c + d * g)
193 |
194 |
195 | def oneD2twoD(vector, shape2, axis):
196 | '''
197 | helper function to convert 1D to 2D data
198 | '''
199 | if axis == 0:
200 | matrix = np.zeros((shape2, len(vector)))
201 | for h in np.arange(shape2):
202 | matrix[h] = vector
203 | elif axis == 1:
204 | matrix = np.zeros((len(vector), shape2))
205 | for h in np.arange(shape2):
206 | matrix[:, h] = vector
207 | else:
208 | raise ValueError("wrong axis")
209 | return matrix
210 |
211 |
212 | def limitMaInidces(iArray, max):
213 | '''
214 | helper function to limit indices to certain interval
215 | lower limit 0
216 | max in python style -> actuallay max-1
217 |
218 | '''
219 | reArray = np.ma.masked_all_like(iArray.ravel())
220 | shape = iArray.shape
221 | for n, i in enumerate(iArray.ravel()):
222 | if i >= max:
223 | reArray[n] = i - max
224 | elif i < 0:
225 | reArray[n] = i + max
226 | else:
227 | reArray[n] = i
228 | return reArray.reshape(shape)
229 |
230 |
231 | def _get_netCDF_module(ncForm="NETCDF3"):
232 | '''
233 | helper function to determine which netCDF module is loaded, to enable
234 | consistency between the various writeNetCDF methods.
235 |
236 | Returns both 'nc' (the netCDF module) and 'pyNC', a bool variable which
237 | controls how some attribute data is set, and how to create the netCDF file
238 | (since the function is different in the various netCDF modules.)
239 | '''
240 |
241 | # most syntax is identical, but there is one nasty difference regarding the fillValue...
242 | if ncForm in ["NETCDF3_CLASSIC", "NETCDF3_64BIT", "NETCDF4_CLASSIC", "NETCDF4"]:
243 | import netCDF4 as nc
244 | pyNc = True
245 | elif ncForm in ["NETCDF3"]:
246 | try:
247 | import Scientific.IO.NetCDF as nc
248 | pyNc = False
249 | except:
250 | # fallback for netcdf3 with the same syntax as netcdf4!
251 | import netCDF3 as nc
252 | pyNc = True
253 | else:
254 | raise ValueError("Unknown nc form "+ncForm)
255 |
256 | return nc, pyNc
257 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # IMProToo - Improved Mrr Processing Tool
2 |
3 |
4 |
5 | IMProToo is an improved processing method for Micro Rain radar. It is especially suited for snow observations and provides besides other things effective reflectivity, Doppler velocity and spectral width. The method features a noise removal based on recognition of the most significant peak and a dynamic dealiasing routine which allows observations even if the Nyquist velocity range is exceeded. The software requires MRR "raw data", it does not work with Metek's standard products MRR "Averaged Data" or "Processed Data".
6 |
7 | Please note that this software was developed for observations at low SNR ratios such as snow, drizzle or light rain. Heavy rain, especially in combination with strong turbulence, might give wrong results.
8 |
9 | The software can be used under the GPL license
10 |
11 | ## What's new?
12 |
13 | ### 0.107
14 | * PyPI release, fixed installation from github archive through setuptools_scm_git_archive
15 |
16 | ### 0.106
17 | * Fixed Python 2.7 file reading and timezone bug (thanks to A. Merrelli)
18 |
19 | ### 0.105
20 | * Fixed Python 3 file reading bug (thanks to M. Bartolini)
21 |
22 | ### 0.104
23 | * Python 3 compatibility (2.7 still working)
24 | * Meta data bug fix
25 |
26 | ### 0.103
27 | * Non-UTC time stamps permitted
28 | * Fixed bug caused by numpy update
29 |
30 | ### 0.102
31 | * Various bug fixes, see https://github.com/maahn/IMProToo/issues/6 and https://github.com/maahn/IMProToo/issues/5
32 |
33 | ### 0.101
34 | * An installation routine is provided (See below). To avoid conflicts, please remove earlier versions manually before installing a newer version.
35 |
36 | ## How does it work
37 |
38 | The routine is described in
39 | Maahn, M. and Kollias, P.: Improved Micro Rain Radar snow measurements using Doppler spectra post-processing, Atmos. Meas. Tech. Discuss., 5, 4771-4808, doi:10.5194/amtd-5-4771-2012, 2012. http://www.atmos-meas-tech-discuss.net/5/4771/2012/amtd-5-4771-2012.html
40 |
41 | Please quote the article if you use the routine for your publication.
42 |
43 | ## How to install
44 |
45 | The software is developed for python 2.7 or 3.6+ and should run on any recent Linux system (and most likely also Mac OS X). Windows is currently not supported, but probably only minor changes are necessary.
46 |
47 | The following python packages are required:
48 | * numpy
49 | * scipy
50 | * matplotlib (for plotting only)
51 | * netcdf4-python http://code.google.com/p/netcdf4-python/ OR python-netcdf (for saving the results only)
52 |
53 | ## Installation
54 |
55 | IMProToo is available on PyPI, so it can be installed with
56 | ```
57 | pip install IMProToo
58 | ```
59 | in the terminal.
60 |
61 | ## How to use
62 |
63 | To use the toolkit, start python and import it:
64 | ```
65 | import IMProToo
66 | ```
67 |
68 | read the raw data file (can be gzip-compressed)
69 | ```
70 | rawData = IMProToo.mrrRawData("mrrRawFile.mrr.gz")
71 | ```
72 |
73 | create the IMProToo object and load rawData
74 | ```
75 | processedSpec = IMProToo.MrrZe(rawData)
76 | ```
77 |
78 | if needed, average rawData to 60s
79 | ```
80 | processedSpec.averageSpectra(60)
81 | ```
82 |
83 | all settings (e.g. creator attribute of netCDF file, dealiasing) are available in the 'processedSpec.co' dictionary and must be set before calculating Ze etc. See the source code for a description of the settings.
84 | ```
85 | processedSpec.co["ncCreator"] = "M.Maahn, IGM University of Cologne"
86 | processedSpec.co["ncDescription"] = "MRR data from Cologne"
87 | processedSpec.co["dealiaseSpectrum"] = True
88 | ```
89 |
90 | calculate Ze and other moments
91 | ```
92 | processedSpec.rawToSnow()
93 | ```
94 |
95 | write all variables to a netCDF file.
96 | ```
97 | processedSpec.writeNetCDF("IMProToo_netCDF_file.nc",ncForm="NETCDF3_CLASSIC")
98 | ```
99 |
100 |
101 | ## Questions
102 | In case of any questions, please don't hesitate to contact Maximilian Maahn: maximilian [dot] maahn [at] uni [dash] leipzig [dot] de
103 |
--------------------------------------------------------------------------------
/examples/batch_convert_rawData.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | '''
4 | Copyright (C) 2011-2021 Maximilian Maahn, U Leipzig
5 | maximilian.maahn_AT_uni-leipzig.de
6 |
7 | example script for converting mrrRaw data to netcdf using IMProToos
8 | '''
9 | from __future__ import print_function
10 |
11 | import sys
12 | import numpy as np
13 | import glob
14 | import os
15 | import datetime
16 | import IMProToo
17 | import gzip
18 |
19 |
20 | version = IMProToo.__version__
21 |
22 |
23 | if len(sys.argv) < 4:
24 | sys.exit('use: python batch_convert_rawData.py pathIn pathOut site')
25 |
26 | pathIn = sys.argv[1]
27 | pathOut = sys.argv[2]
28 | site = sys.argv[3]
29 |
30 | skipExisting = True
31 |
32 | print(pathIn)
33 |
34 | try:
35 | os.mkdir(pathOut)
36 | except OSError:
37 | pass
38 |
39 | # go through all gz compressed files in pathIn/year/month/
40 | for nfile in np.sort(glob.glob(pathIn+"/*raw*")):
41 | # get the timestamp
42 | timestamp = None
43 | if nfile.split('.')[-1] == 'gz':
44 | f = gzip.open(nfile, 'rt')
45 | else:
46 | f = open(nfile, 'r')
47 | # Sometimes the first MRR timestamps are from the day before, so we cannot take the first date we found. get list of line breaks
48 | line_offset = []
49 | offset = 0
50 | for line in f:
51 | line_offset.append(offset)
52 | offset += len(line)
53 | f.seek(0)
54 |
55 | # Now, to skip 20% of the file
56 | f.seek(line_offset[len(line_offset)//5])
57 |
58 | # now find the date
59 | try:
60 | while True:
61 | string = str(f.readline())
62 | if not string:
63 | break
64 | if string[:2] == "T:":
65 | timestamp = datetime.datetime.strptime(
66 | string[2:14], "%y%m%d%H%M%S").strftime("%Y%m%d")
67 | break
68 | elif string[:4] == "MRR ":
69 | timestamp = datetime.datetime.strptime(
70 | string[4:16], "%y%m%d%H%M%S").strftime("%Y%m%d")
71 | break
72 |
73 | finally:
74 | f.close()
75 |
76 | if timestamp is None:
77 | print("did not find MRR timesamp in %s, Skipping" % nfile)
78 | continue
79 |
80 | fileOut = pathOut+"/mrr_improtoo_"+version+"_"+site+"_"+timestamp+".nc"
81 |
82 | if skipExisting and (os.path.isfile(fileOut) or os.path.isfile(fileOut+".gz")):
83 | print("NetCDF file aready exists, skipping: ", timestamp, nfile, fileOut)
84 | continue
85 |
86 | print(timestamp, nfile, fileOut)
87 |
88 | # load raw data from file
89 | print("reading...", nfile)
90 | try:
91 | rawData = IMProToo.mrrRawData(nfile)
92 | except:
93 | print("could not read data")
94 | continue
95 |
96 | try:
97 | # convert rawData object
98 | processedSpec = IMProToo.MrrZe(rawData)
99 | # average rawData to 60s
100 | processedSpec.averageSpectra(60)
101 | # the MRR at 'lyr' was affected by interference for some days, dealiasing routine needs to know about that:
102 | if site == "lyr" and timestamp in ['20100620', '20100621', '20100622', '20100623', '20100624', '20100625', '20100626', '20100627', '20100628', '20100629', '20100630', '20100701', '20100702', '20100703', '20100704', '20100705', '20100706', '20100707']:
103 | processedSpec.co['dealiaseSpectrum_heightsWithInterference'] = processedSpec.co[
104 | 'dealiaseSpectrum_heightsWithInterference'] + [25, 26, 27, 28, 29, 30]
105 | # creator attribute of netCDF file
106 | processedSpec.co["ncCreator"] = "M.Maahn, IGM University of Cologne"
107 |
108 | # calculate Ze and other moments
109 | processedSpec.rawToSnow()
110 |
111 | # write all variables to a netCDF file.
112 | print("writing...", fileOut)
113 | processedSpec.writeNetCDF(fileOut, ncForm="NETCDF3_CLASSIC")
114 | except Exception as error:
115 | print(str(error))
116 | print("could not process data")
117 | continue
118 |
--------------------------------------------------------------------------------
/examples/batch_makeQuicklooks.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | '''
3 | Copyright (C) 2011-2021 Maximilian Maahn, U Leipzig
4 | maximilian.maahn_AT_uni-leipzig.de
5 |
6 | make quicklooks from IMProToo NetCDF files.
7 |
8 |
9 | use: python batch_makeQuicklooks.py pathIn pathOut site
10 |
11 | requires:
12 |
13 | numpy, matplotlib, netcdf4-python or python-netcdf
14 |
15 | '''
16 |
17 |
18 | from __future__ import print_function
19 | from copy import deepcopy
20 | import matplotlib.font_manager as font_manager
21 | from matplotlib import rc, ticker
22 | from IMProToo.tools import *
23 | import IMProToo
24 | import string
25 | import random
26 | import matplotlib.pyplot as plt
27 | import matplotlib.mlab as mlab
28 |
29 |
30 | import sys
31 | import numpy as np
32 | import glob
33 | import calendar
34 | import datetime
35 | import os
36 | import matplotlib
37 | matplotlib.use('Agg')
38 |
39 | try:
40 | import netCDF4 as nc
41 | pyNc = True
42 | except:
43 | import Scientific.IO.NetCDF as nc
44 | pyNc = False
45 |
46 | tmpDir = "/tmp/"
47 | skipExisting = True
48 |
49 |
50 | def unix2timestamp(unix):
51 | return datetime.datetime.utcfromtimestamp(unix).strftime("%Y%m%d")
52 |
53 |
54 | def timestamp2unix(timestamp):
55 | return calendar.timegm(datetime.datetime(year=int(timestamp[0:4]), month=int(timestamp[4:6]), day=int(timestamp[6:8]), hour=0, minute=0, second=0).timetuple())
56 |
57 |
58 | def quicklook(site, ncFile, imgFile, imgTitle):
59 | """
60 | Makes Quicklooks of MRR data
61 |
62 |
63 | @parameter site (str): code for the site where the data was recorded (usually 3 letter)
64 | @parameter ncFile (str): netcdf file name incl. path, usually "path/mrr_site_yyyymmdd.nc"
65 | @parameter imgFile (str): image file name, incl. path, extensions determines file format (e.g. png, eps, pdf ...)
66 | @parameter imgTitle (str): plot title
67 | """
68 | print("##### " + imgTitle + "######")
69 | tmpFile = False
70 | if ncFile.split(".")[-1] == "gz":
71 | tmpFile = True
72 | gzFile = deepcopy(ncFile)
73 | ncFile = tmpDir+"/maxLibs_netcdf_" + \
74 | ''.join(random.choice(string.ascii_uppercase + string.digits)
75 | for x in range(5))+".tmp.nc"
76 | print('uncompressing', gzFile, "->", ncFile)
77 | os.system("zcat "+gzFile+">"+ncFile)
78 | else:
79 | print('opening', ncFile)
80 |
81 | if pyNc:
82 | ncData = nc.Dataset(ncFile, 'r')
83 | else:
84 | ncData = nc.NetCDFFile(ncFile, 'r')
85 |
86 | timestampsNew = ncData.variables["time"][:]
87 | HNew = ncData.variables["height"][:]
88 | ZeNew = ncData.variables["Ze"][:]
89 | noiseAveNew = ncData.variables["etaNoiseAve"][:]
90 | noiseStdNew = ncData.variables["etaNoiseStd"][:]
91 | spectralWidthNew = ncData.variables["spectralWidth"][:]
92 | WNew = ncData.variables["W"][:]
93 | qualityNew = ncData.variables["quality"][:]
94 |
95 | ncData.close()
96 | if (tmpFile):
97 | os.system("rm -f "+ncFile)
98 |
99 | date = unix2timestamp(timestampsNew[0])
100 | starttime = timestamp2unix(date)
101 | endtime = starttime+60*60*24
102 |
103 | HNew[np.isnan(HNew)] = -9999
104 | ylim = [np.min(HNew[HNew != -9999]), np.max(HNew)]
105 | xlim = [starttime, endtime]
106 | timestampsNew = oneD2twoD(timestampsNew, ZeNew.shape[1], 1)
107 |
108 | fig = plt.figure(figsize=(10, 13))
109 |
110 | sp1 = fig.add_subplot(511)
111 | sp1.set_title(imgTitle)
112 | levels = np.arange(-15, 40, 0.1)
113 | plotCF = sp1.contourf(timestampsNew, HNew, ZeNew, levels, extend="both")
114 | cbZe = plt.colorbar(plotCF)
115 | cbZe.set_label('MRR Ze [dBz]')
116 | sp1.set_ylim(ylim)
117 | sp1.set_xlim(xlim)
118 |
119 | sp1.axhline(HNew[-1, 2])
120 | sp1.axhline(HNew[-1, 29])
121 |
122 | sp2 = fig.add_subplot(512)
123 | levels = np.arange(-10, 18, 0.1)
124 | plotCF = sp2.contourf(timestampsNew, HNew, WNew, levels, extend="both")
125 | cbZe = plt.colorbar(plotCF)
126 | cbZe.set_label('MRR W [m/s]')
127 | sp2.set_ylim(ylim)
128 | sp2.set_xlim(xlim)
129 |
130 | sp2.axhline(HNew[-1, 2])
131 | sp2.axhline(HNew[-1, 29])
132 |
133 | sp3 = fig.add_subplot(513)
134 | levels = np.arange(0, 1.5, 0.1)
135 | plotCF = sp3.contourf(timestampsNew, HNew,
136 | spectralWidthNew, levels, extend="both")
137 | cbZe = plt.colorbar(plotCF)
138 | cbZe.set_label('spectralWidth [m/s]')
139 | sp3.set_ylim(ylim)
140 | sp3.set_xlim(xlim)
141 |
142 | sp3.axhline(HNew[-1, 2])
143 | sp3.axhline(HNew[-1, 29])
144 |
145 | sp4 = fig.add_subplot(514)
146 | levels = np.arange(1e-10, 1e-8, 2e-10)
147 | plotCF = sp4.contourf(timestampsNew, HNew,
148 | noiseAveNew, levels, extend="both")
149 | cbZe = plt.colorbar(plotCF)
150 | cbZe.set_label('mean spectral noise [1/m]')
151 | sp4.set_ylim(ylim)
152 | sp4.set_xlim(xlim)
153 | sp4.axhline(HNew[-1, 2])
154 | sp4.axhline(HNew[-1, 29])
155 | #import pdb;pdb.set_trace()
156 |
157 | sp5 = fig.add_subplot(515)
158 | levels = np.arange(20)
159 | for i in levels:
160 | levels[i] = 2**i
161 | plotCF = sp5.contourf(timestampsNew, HNew, qualityNew,
162 | levels, norm=matplotlib.colors.LogNorm())
163 | cbZe = plt.colorbar(plotCF)
164 | cbZe.set_label('quality array')
165 | sp5.set_ylim(ylim)
166 | sp5.set_xlim(xlim)
167 | sp5.axhline(HNew[-1, 2])
168 | sp5.axhline(HNew[-1, 29])
169 |
170 | # sp1.set_xlim(np.min(timestampsNew),np.max(timestampsNew))
171 | sp1.set_xticks(np.arange(sp1.get_xlim()[0], sp1.get_xlim()[1], 7200))
172 | sp1.set_xticklabels([])
173 |
174 | # sp2.set_xlim(np.min(timestampsNew),np.max(timestampsNew))
175 | sp2.set_xticks(np.arange(sp1.get_xlim()[0], sp1.get_xlim()[1], 7200))
176 | sp2.set_xticklabels([])
177 |
178 | # sp3.set_xlim(np.min(timestampsNew),np.max(timestampsNew))
179 | sp3.set_xticks(np.arange(sp1.get_xlim()[0], sp1.get_xlim()[1], 7200))
180 | sp3.set_xticklabels([])
181 |
182 | # sp4.set_xlim(np.min(timestampsNew),np.max(timestampsNew))
183 | sp4.set_xticks(np.arange(sp1.get_xlim()[0], sp1.get_xlim()[1], 7200))
184 | sp4.set_xticklabels([])
185 |
186 | # pdb.set_trace()
187 | # sp5.set_xlim(np.min(timestampsNew)-60,np.max(timestampsNew))
188 | sp5.set_xticks(np.arange(sp5.get_xlim()[0], sp5.get_xlim()[1]+7200, 7200))
189 | niceDates = list()
190 | for timestamp in np.arange(sp5.get_xlim()[0], sp5.get_xlim()[1]+7200, 7200):
191 | niceDates.append(
192 | str(datetime.datetime.utcfromtimestamp(timestamp).strftime("%H:%M")))
193 | sp5.set_xticklabels(niceDates)
194 |
195 | plt.subplots_adjust(hspace=0.02, left=0.085, right=0.78)
196 |
197 | plt.savefig(imgFile)
198 | print(imgFile)
199 |
200 | plt.close()
201 | return
202 |
203 |
204 | if len(sys.argv) < 4:
205 | print('use: batch_makeQuicklooks.py pathIn pathOut site')
206 | sys.exit()
207 |
208 | pathIn = sys.argv[1]
209 | pathOut = sys.argv[2]
210 | site = sys.argv[3]
211 |
212 |
213 | try:
214 | os.mkdir(pathOut)
215 | except OSError:
216 | pass
217 |
218 |
219 | for ncFile in np.sort(glob.glob(pathIn+"/*nc")):
220 | #import pdb;pdb.set_trace()
221 | date = ncFile.split("_")[-1].split(".")[0]
222 | print(date, ncFile)
223 | imgFile = pathOut + "/mrr_improtoo_" + \
224 | IMProToo.__version__+'_'+site+"_"+date+".png"
225 | imgTitle = site + " " + date + " IMProToo " + IMProToo.__version__
226 |
227 | if skipExisting and os.path.isfile(imgFile):
228 | print("Quicklook aready exists, skipping: ", date, ncFile, imgFile)
229 | continue
230 |
231 | quicklook(site, ncFile, imgFile, imgTitle)
232 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | # pyproject.toml
2 | [build-system]
3 | requires = ["setuptools>=42", "wheel", "setuptools_scm>=5.0.2"]
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | '''
3 | pyOptimalEstimation
4 |
5 | Copyright (C) 2014-15 Maximilian Maahn, IGMK (mmaahn_(AT)_meteo.uni-koeln.de)
6 | http://gop.meteo.uni-koeln.de/software
7 |
8 | This program is free software: you can redistribute it and/or modify
9 | it under the terms of the GNU General Public License as published by
10 | the Free Software Foundation, either version 3 of the License, or
11 | any later version.
12 |
13 | This program is distributed in the hope that it will be useful,
14 | but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | GNU General Public License for more details.
17 |
18 | You should have received a copy of the GNU General Public License
19 | along with this program. If not, see .
20 |
21 | '''
22 |
23 | from setuptools import setup
24 | import io
25 | # read the contents of your README file
26 | from os import path
27 | this_directory = path.abspath(path.dirname(__file__))
28 | with io.open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
29 | long_description = f.read()
30 |
31 |
32 | if __name__ == "__main__":
33 | setup(
34 | name='IMProToo',
35 | use_scm_version=True,
36 | packages=['IMProToo', ],
37 | license='GNU General Public License 3',
38 | author="Maximilian Maahn",
39 | long_description=long_description,
40 | long_description_content_type='text/markdown',
41 | classifiers=[
42 | "Development Status :: 4 - Beta",
43 | "Topic :: Utilities",
44 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
45 | "Operating System :: OS Independent",
46 | "Programming Language :: Python",
47 | 'Intended Audience :: Science/Research',
48 | 'Topic :: Scientific/Engineering',
49 | ],
50 | install_requires=['numpy', 'matplotlib', 'netCDF4', 'scipy'],
51 | setup_requires=['setuptools_scm','setuptools_scm_git_archive'],
52 | )
53 |
--------------------------------------------------------------------------------