This repository has been archived by the owner on May 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
pysesa_main.py
626 lines (527 loc) · 26.5 KB
/
pysesa_main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
## PySESA (Python program for Spatially Explicit Spectral Analysis)
## has been developed at the Grand Canyon Monitoring & Research Center,
## U.S. Geological Survey
##
## Author: Daniel Buscombe
##
##This software is in the public domain because it contains materials that originally came from
##the United States Geological Survey, an agency of the United States Department of Interior.
##For more information, see the official USGS copyright policy at
##http://www.usgs.gov/visual-id/credit_usgs.html#copyright
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
## See the GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
PySESA - a Python framework for Spatially Explicit Spectral Analysis
PySESA is an open-source project dedicated to provide a generic Python framework
for spatially explicit statistical analyses of point clouds and other geospatial data,
in the spatial and frequency domains, for use in the geosciences
The program is detailed in:
Buscombe, D. (2016) "spatially explicit spectral analysis of point clouds and geospatial data", Computers and Geosciences 86, 92-108, 10.1016/j.cageo.2015.10.004.
:Author:
Daniel Buscombe
United States Geological Survey
Flagstaff, AZ 86001
:install:
python setup.py install
sudo python setup.py install
:test:
python -c "import pysesa; test()"
:license:
GNU Lesser General Public License, Version 3
(http://www.gnu.org/copyleft/lesser.html)
This software is in the public domain because it contains materials that
originally came from the United States Geological Survey, an agency of the
United States Department of Interior. For more information,
see the official USGS copyright policy at
http://www.usgs.gov/visual-id/credit_usgs.html#copyright
Any use of trade, product, or firm names is for descriptive purposes only
and does not imply endorsement by the U.S. government.
"""
# =========================================================
# ======================== libraries ======================
# =========================================================
from __future__ import division
import numpy as np
from joblib import Parallel, delayed, cpu_count
from time import clock, time
import os #, sys, getopt
# suppress divide and invalid warnings
np.seterr(divide='ignore')
np.seterr(invalid='ignore')
np.seterr(over='ignore')
np.seterr(under='ignore')
#import pysesa
import read, write, spatial, spectral, lengthscale, partition, detrend
#detrend
import filter
import warnings
warnings.filterwarnings("ignore")
# =========================================================
# ===================== subfunctions ======================
# =========================================================
# =========================================================
def ascol( arr ):
'''
reshapes row matrix to be a column matrix (N,1).
'''
if len( arr.shape ) == 1: arr = arr.reshape( ( arr.shape[0], 1 ) )
return arr
##slope, intercept, r_value, p_value, std_err, d, l, wmax, wmean, rms1, rms2, Z, E, sigma, T0_1, T0_2, sw1, sw2, m0, m1, m2, m3, m4, phi
#==================================================
def get_spec(pts, spectype, out, detrend_mode, res, method, nbin, lentype, taper):
'''
call the spectral analysis routine for detrended window of point cloud
Gets called by the parallel processing queue
'''
try:
pts = detrend.detrend(pts, detrend_mode, res, method).getdata()
#pts = pts.astype('float64')
return spatial.spatial(pts).getdata()[:3] +spectral.spectral(pts, nbin, res, spectype, lentype, taper, method).getdata() #spatial.spatial(pts).getcentroid() +
except:
return [np.ones(27)*np.nan]
#==================================================
def get_spat(pts, detrend_mode, res, method):
'''
call the spatial analysis routine for detrended window of point cloud
Gets called by the parallel processing queue
'''
try:
pts = detrend.detrend(pts, detrend_mode, res, method).getdata()
#pts = pts.astype('float32')
return spatial.spatial(pts).getdata()
except:
return [np.ones(10)*np.nan]
## toproc[nr_pts[k],:3], 1, out, detrend_mode, res, method, nbin, lentype, taper
#==================================================
def get_spec_spat(pts, spectype, out, detrend_mode, res, method, nbin, lentype, taper):
'''
call the spectral and spatial analysis routine for detrended window of point cloud
Gets called by the parallel processing queue
'''
try:
pts = detrend.detrend(pts, detrend_mode, res, method).getdata()
pts = pts.astype('float64')
return spatial.spatial(pts).getdata() + spectral.spectral(pts, nbin, res, spectype, lentype, taper, method).getdata()
except:
return [np.ones(34)*np.nan]
# =========================================================
# ==================== begin program ======================
# =========================================================
def process_all(infile, out=1, detrend_mode=4, proctype=1, mxpts=1024, res=0.05, nbin=20, lentype=1, minpts=64, taper=1, prc_overlap=0, nchunks=1, filt=0): # bp=0
'''
Calculate spectral and spatial statistics of a Nx3 point cloud
Syntax
----------
() = process_all(infile, out, detrend, proctype, mxpts, res, nbin, lentype, minpts, taper, prc_overlap, nchunks, filt)
Parameters
-----------
infile : str
ASCII file containing an Nx3 point cloud in 3 columns
Other Parameters
-----------------
out : float, *optional* [default = 0.5]
output grid resolution
detrend : int, *optional* [default = 4]
type of detrending.
1 = remove mean
2 = remove Ordinary least squares plane
3 = remove Robust linear model plane
4 = remove Orthogonal Distance Regression plane
proctype : int, *optional* [default = 1, no spectral smoothing]
proctype type:
1 = spectral only, no spectral smoothing
2 = spatial only
3 = spatial + spectrum, no spectral smoothing
mxpts : float, *optional* [default = 1024]
maximum number of points allowed in a window
res : float, *optional* [default = 0.05]
spatial grid resolution to create a grid
nbin : int, *optional* [default = 20]
number of bins for power spectral binning
lentype : int, *optional* [default = 1, l<0.5]
lengthscale type:
1 = l<0.5
2 = l<1/e
3 = l<0
minpts : float, *optional* [default = 16]
minimum number of points allowed in a window
taper : int, *optional* [default = Hanning]
flag for taper type:
1 = Hanning (Hann)
2 = Hamming
3 = Blackman
4 = Bartlett
prc_overlap : float, *optional" [default = 0]
percentage overlap between windows
nchunks : int, *optional" [default = 1]
split data into nchunks and process each separately
use only if receiving memory errors with very large datasets
filt : int, *optional" [default = 0]
if filt==1, point cloud will be filtered prior to analysis
using a simple thresholded standard deviation approach
Returns [proctype = 1 or proctype = 2]
---------------------------------------
data: list
x = centroid in horizontal coordinate
y = centroid in laterial coordinate
z = centroid in vertical coordinate
slope = slope of regression line through log-log 1D power spectral density
intercept = intercept of regression line through log-log 1D power spectral density
r_value = correlation of regression through log-log 1D power spectral density
p_value = probability that slope of regression through log-log 1D power spectral density is not zero
std_err = standard error of regression through log-log 1D power spectral density
d = fractal dimension
l = integral lengthscale
wmax = peak wavelength
wmean = mean wavelength
rms1 = RMS amplitude from power spectral density
rms2 = RMS amplitude from bin averaged power spectral density
Z = zero-crossings per unit length
E = extreme per unit length
sigma = RMS amplitude
T0_1 = average spatial period (m_0/m_1)
T0_2 = average spatial period (m_0/m_2)^0.5
sw1 = spectral width
sw2 = spectral width (normalised radius of gyration)
m0 = zeroth moment of spectrum
m1 = first moment of spectrum
m2 = second moment of spectrum
m3 = third moment of spectrum
m4 = fourth moment of spectrum
phi = effective slope (degrees)
Returns [proctype = 3]
-------------------------
data: list
x = centroid in horizontal coordinate
y = centroid in laterial coordinate
z = centroid in vertical coordinate
z_mean = centroid in amplitude
z_max = max amplitude
z_min = min amplitude
z_range = range in amplitude
sigma = standard deviation of amplitudes
skewness = skewness of amplitudes
kurtosis = skewness of amplitudes
n = number of 3D coordinates
Returns [proctype = 4 or proctype = 5]
-----------------------------------------
data: list
x = centroid in horizontal coordinate
y = centroid in laterial coordinate
z_mean = centroid in amplitude
z_max = max amplitude
z_min = min amplitude
z_range = range in amplitude
sigma = standard deviation of amplitudes
skewness = skewness of amplitudes
kurtosis = skewness of amplitudes
n = number of 3D coordinates
slope = slope of regression line through log-log 1D power spectral density
intercept = intercept of regression line through log-log 1D power spectral density
r_value = correlation of regression through log-log 1D power spectral density
p_value = probability that slope of regression through log-log 1D power spectral density is not zero
std_err = standard error of regression through log-log 1D power spectral density
d = fractal dimension
l = integral lengthscale
wmax = peak wavelength
wmean = mean wavelength
rms1 = RMS amplitude from power spectral density
rms2 = RMS amplitude from bin averaged power spectral density
Z = zero-crossings per unit length
E = extreme per unit length
sigma = RMS amplitude
T0_1 = average spatial period (m_0/m_1)
T0_2 = average spatial period (m_0/m_2)^0.5
sw1 = spectral width
sw2 = spectral width (normalised radius of gyration)
m0 = zeroth moment of spectrum
m1 = first moment of spectrum
m2 = second moment of spectrum
m3 = third moment of spectrum
m4 = fourth moment of spectrum
phi = effective slope (degrees)
'''
print("""
.. _ __ _ _ ___ ___ ___ __ _
.. | '_ \| | | | / __|/ _ \/ __|/ _` |
.. | |_) | |_| | \__ \ __/\__ \ (_| |
.. | .__/ \__, | |___/\___||___/\__,_|
.. |_| |___/
..
.. +-+-+ +-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
.. |b|y| |D|a|n|i|e|l| |B|u|s|c|o|m|b|e|
.. +-+-+ +-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
.. +-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+
.. |U|.|S|.| |G|e|o|l|o|g|i|c|a|l| |S|u|r|v|e|y|
.. +-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+
""")
if infile:
print('Input file is %s' % (infile))
if prc_overlap:
prc_overlap = np.asarray(prc_overlap,int)
print('Percent overlap is %s' % (str(prc_overlap)))
elif prc_overlap==0:
prc_overlap = np.asarray(prc_overlap,int)
print('Percent overlap is %s' % (str(prc_overlap)))
if out:
out = np.asarray(out,float)
print('Output grid size is %s' % (str(out)))
if detrend_mode:
detrend_mode = np.asarray(detrend_mode,int)
if detrend_mode==1:
print('Detrend type: remove mean')
if detrend_mode==2:
print('Detrend type: Ordinary least squares plane')
if detrend_mode==3:
print('Detrend type: Robust linear model plane')
if detrend_mode==4:
print('Detrend type: Orthogonal Distance Regression plane')
if proctype:
proctype = np.asarray(proctype,int)
if proctype==0:
proctype = 1
if proctype==1:
print('spectral parameters')
# elif proctype==2:
# print('spectral parameters (with smoothing)')
elif proctype==2:
print('spatial parameters')
elif proctype==3:
print('spatial parameters + spectral parameters')
# elif proctype==5:
# print('spatial parameters + spectral parameters (smoothing)')
if res:
res = np.asarray(res,float)
print('Res. is %s' % (str(res)))
if mxpts:
mxpts = np.asarray(mxpts,int)
print('Max points per window is %s' % (str(mxpts)))
if minpts:
minpts = np.asarray(minpts,int)
print('Min points per window is %s' % (str(minpts)))
if nbin:
nbin = np.asarray(nbin,float)
print('Number of bins is %s' % (str(nbin)))
if lentype:
lentype = int(lentype)
if lentype==1:
print("lengthscale type: l<0.5")
elif lentype==2:
print("lengthscale type: l<1/e")
elif lentype==3:
print("lengthscale type: l<0")
if taper:
taper = np.asarray(taper,int)
if taper==1:
print('Hanning taper')
elif taper==2:
print('Hamming taper')
elif taper==3:
print('Blackman taper')
else:
print('Bartlett taper')
if nchunks:
nchunks = np.asarray(nchunks,int)
print('Number of chunks to process separately is %s' % (str(nchunks)))
if filt:
filt = np.asarray(filt,int)
if filt==1:
print('Point cloud will be filtered')
# start timer
if os.name=='posix': # true if linux/mac or cygwin on windows
start1 = time()
else: # windows
start1 = clock()
method = 'nearest'
#internal parameters for filtering
k = 16 #number of neighbours
std_dev = 2 #standard deviation multiplier
n_iter = 1 #number of iterations
#==============================================================================
print("(1) Reading data from file ...")
# check first for laz/las format
if 'las' in infile[-3:]:
toproc_init = read.lasread(infile)
elif 'laz' in infile[-3:]:
toproc_init = read.lasread(infile)
else: # read in ascii 3-column file containing point cloud data
toproc_init = read.txtread(infile)
#==============================================================================
# if requested, filter data
if filt==1:
print("(1b) Filtering data ...")
print("Size of original data: %s" % (str(len(toproc_init))))
# initial pass
_, toproc_init_f = filter.filt_stdev(toproc_init, k = k, std_dev = std_dev)
del toproc_init
#iterate through n_iter to refine filtering
for nn in range(n_iter):
_, toproc_init_f = filter.filt_stdev(toproc_init_f, k = k, std_dev = std_dev)
toproc_init = np.copy(toproc_init_f)
del toproc_init_f
print("Size of filtered data: %s" % (str(len(toproc_init))))
infile = infile.split('.')[-2]+'_filt.xyz'
print("Writing filtered data to file: "+infile)
with open(infile, 'wb') as f:
np.savetxt(f, toproc_init[np.where(toproc_init[:,-1])[0],:], fmt=' '.join(['%8.6f,'] * np.shape(toproc_init)[1])[:-1])
#==============================================================================
toproc2 = np.array_split(toproc_init, nchunks)
del toproc_init
## number of points, undecimated
orig_pts = len(np.vstack(toproc2))
TOWRITE = []
counter = 1
for toproc in toproc2:
print("Working on chunk %s out of %s chunks ... " % (str(counter), str(len(toproc2))))
counter += 1
#==============================================================================
print("(2) Partitioning data into windows ... ")
# get indices to windows
nr_pts = partition.partition(toproc, out, mxpts, minpts, prc_overlap).getdata() #res, bp
#==============================================================================
print("(3) Processing in parallel using %s processors ... " % (str(cpu_count())))
#==============================================================================
if (proctype==1): # or (proctype==2):
print("Number of tasks: %s" % (str(len(nr_pts))))
#spectral, no smooth
try: #parallel processing with all available cores
w = Parallel(n_jobs=cpu_count(), verbose=1)(delayed(get_spec)(toproc[nr_pts[k],:3], 1, out, detrend_mode, res, method, nbin, lentype, taper) for k in range(len(nr_pts)))
except: #fall back to serial
w = Parallel(n_jobs=1, verbose=1)(delayed(get_spec)(toproc[nr_pts[k],:3], 1, out, detrend_mode, res, method, nbin, lentype, taper) for k in range(len(nr_pts)))
try:
x, y, z, slope, intercept, r_value, p_value, std_err, d, l, wmax, wmean, rms1, rms2, Z, E, sigma, T0_1, T0_2, sw1, sw2, m0, m1, m2, m3, m4, phi = zip(*w)
except:
w2 = []
for k in range(len(w)):
if len(w[k])==27:
w2.append(w[k])
x, y, z, slope, intercept, r_value, p_value, std_err, d, l, wmax, wmean, rms1, rms2, Z, E, sigma, T0_1, T0_2, sw1, sw2, m0, m1, m2, m3, m4, phi = zip(*w2)
del w2
del w
# combine into single matrix for writing to file
towrite = np.hstack(( ascol(np.asarray(x)),ascol(np.asarray(y)),ascol(np.asarray(z)),ascol(np.asarray(slope)),ascol(np.asarray(intercept)),ascol(np.asarray(r_value)),ascol(np.asarray(p_value)),ascol(np.asarray(std_err)),ascol(np.asarray(d)),ascol(np.asarray(l)),ascol(np.asarray(wmax)),ascol(np.asarray(wmean)),ascol(np.asarray(rms1)),ascol(np.asarray(rms2)),ascol(np.asarray(Z)),ascol(np.asarray(E)),ascol(np.asarray(sigma)),ascol(np.asarray(T0_1)),ascol(np.asarray(T0_2)),ascol(np.asarray(sw1)),ascol(np.asarray(sw2)),ascol(np.asarray(m0)),ascol(np.asarray(m1)),ascol(np.asarray(m2)),ascol(np.asarray(m3)),ascol(np.asarray(m4)),ascol(np.asarray(phi)) ))
del x, y, z, slope, intercept, r_value, p_value, std_err, d, l, wmax, wmean, rms1, rms2, Z, E, sigma, T0_1, T0_2, sw1, sw2, m0, m1, m2, m3, m4, phi
# remove rows with any NaNs
towrite = towrite[np.where(np.logical_not(np.any(np.isnan(towrite),axis=1)))[0],:]
TOWRITE.append(towrite)
del towrite
# make a header string for the output file
header = 'x, y, z, slope, intercept, r_value, p_value, std_err, d, l, wmax, wmean, rms1, rms2, Z, E, sigma, T0_1, T0_2, sw1, sw2, m0, m1, m2, m3, m4, phi'
#==============================================================================
elif proctype==2: #spatial only
print("Number of tasks: %s" % (str(len(nr_pts))))
try: #parallel processing with all available cores
w = Parallel(n_jobs=cpu_count(), verbose=0)(delayed(get_spat)(toproc[nr_pts[k],:3], detrend_mode, res, method) for k in range(len(nr_pts)))
except: #fall back to serial
w = Parallel(n_jobs=1, verbose=0)(delayed(get_spat)(toproc[nr_pts[k],:3], detrend_mode, res, method) for k in range(len(nr_pts)))
try:
x, y, z_mean, z_max, z_min, z_range, sigma, skewness, kurtosis, n = zip(*w)
except:
w2 = []
for k in range(len(w)):
if len(w[k])==10:
w2.append(w[k])
x, y, z_mean, z_max, z_min, z_range, sigma, skewness, kurtosis, n = zip(*w2)
del w2
del w
# combine into single matrix for writing to file
towrite = np.hstack(( ascol(np.asarray(x)),ascol(np.asarray(y)),ascol(np.asarray(z_mean)),ascol(np.asarray(z_max)),ascol(np.asarray(z_min)),ascol(np.asarray(z_range)),ascol(np.asarray(sigma)),ascol(np.asarray(skewness)),ascol(np.asarray(kurtosis)), ascol(np.asarray(n)) ))
del x, y, z_mean, z_max, z_min, z_range, sigma, skewness, kurtosis, n
# remove rows with any NaNs
towrite = towrite[np.where(np.logical_not(np.any(np.isnan(towrite),axis=1)))[0],:]
TOWRITE.append(towrite)
del towrite
# make a header string for the output file
header = 'x, y, z_mean, z_max, z_min, z_range, sigma, skewness, kurtosis, n'
#==============================================================================
elif (proctype==3): # or (proctype==5): #spectral and spatial
#spatial + spectral, no smooth
print("Number of tasks: %s" % (str(len(nr_pts))))
try: #parallel processing with all available cores
w = Parallel(n_jobs=cpu_count(), verbose=1)(delayed(get_spec_spat)(toproc[nr_pts[k],:3], 1, out, detrend_mode, res, method, nbin, lentype, taper) for k in range(len(nr_pts)))
except: #fall back to serial
w = Parallel(n_jobs=1, verbose=1)(delayed(get_spec_spat)(toproc[nr_pts[k],:3], 1, out, detrend_mode, res, method, nbin, lentype, taper) for k in range(len(nr_pts)))
try:
x, y, z_mean, z_max, z_min, z_range, sigma, skewness, kurtosis, n, slope, intercept, r_value, p_value, std_err, d, l, wmax, wmean, rms1, rms2, Z, E, sigma, T0_1, T0_2, sw1, sw2, m0, m1, m2, m3, m4, phi = zip(*w)
except:
w2 = []
for k in range(len(w)):
if len(w[k])==34:
w2.append(w[k])
x, y, z_mean, z_max, z_min, z_range, sigma, skewness, kurtosis, n, slope, intercept, r_value, p_value, std_err, d, l, wmax, wmean, rms1, rms2, Z, E, sigma, T0_1, T0_2, sw1, sw2, m0, m1, m2, m3, m4, phi = zip(*w2)
del w2
del w
# combine into single matrix for writing to file
towrite = np.hstack(( ascol(np.asarray(x)),ascol(np.asarray(y)), ascol(np.asarray(z_mean)),ascol(np.asarray(z_max)),ascol(np.asarray(z_min)),ascol(np.asarray(z_range)),ascol(np.asarray(sigma)),ascol(np.asarray(skewness)),ascol(np.asarray(kurtosis)), ascol(np.asarray(n)), ascol(np.asarray(slope)),ascol(np.asarray(intercept)),ascol(np.asarray(r_value)),ascol(np.asarray(p_value)),ascol(np.asarray(std_err)),ascol(np.asarray(d)),ascol(np.asarray(l)),ascol(np.asarray(wmax)),ascol(np.asarray(wmean)),ascol(np.asarray(rms1)),ascol(np.asarray(rms2)),ascol(np.asarray(Z)),ascol(np.asarray(E)),ascol(np.asarray(sigma)),ascol(np.asarray(T0_1)),ascol(np.asarray(T0_2)),ascol(np.asarray(sw1)),ascol(np.asarray(sw2)),ascol(np.asarray(m0)),ascol(np.asarray(m1)),ascol(np.asarray(m2)),ascol(np.asarray(m3)),ascol(np.asarray(m4)),ascol(np.asarray(phi)) ))
del x, y, z_mean, z_max, z_min, z_range, skewness, kurtosis, n #,sigma
del slope, intercept, r_value, p_value, std_err, d, l, wmax, wmean, rms1, rms2, Z, E, sigma, T0_1, T0_2, sw1, sw2, m0, m1, m2, m3, m4, phi
# remove rows with any NaNs
towrite = towrite[np.where(np.logical_not(np.any(np.isnan(towrite),axis=1)))[0],:]
TOWRITE.append(towrite)
del towrite
# make a header string for the output file
header = 'x, y, z_mean, z_max, z_min, z_range, sigma, skewness, kurtosis, n, slope, intercept, r_value, p_value, std_err, d, l, wmax, wmean, rms1, rms2, Z, E, sigma, T0_1, T0_2, sw1, sw2, m0, m1, m2, m3, m4, phi'
towrite = np.vstack(TOWRITE)
#==============================================================================
print("(4) Writing data to file ...")
# create a string for the output file
outfile = infile+'_zstat_detrend'+str(detrend_mode)+'_outres'+str(out)+'_proctype'+str(proctype)+'_mxpts'+str(mxpts)+'_minpts'+str(minpts)+'.xyz'
try:
# write the data to the file
write.txtwrite(outfile, towrite, header)
except:
with open(outfile, 'wb') as f:
np.savetxt(f, towrite[np.where(towrite[:,-1])[0],:], header = header, fmt=' '.join(['%8.6f,'] * np.shape(towrite)[1])[:-1])
# stop the clock
if os.name=='posix': # true if linux/mac
elapsed = (time() - start1)
else: # windows
elapsed = (clock() - start1)
print("Done! %s points decimated to %s points. Program ran for %s seconds" % (str(orig_pts), str(len(towrite)), str(elapsed)))
# #spectral, with smooth
# if proctype==2:
# try: #parallel processing with all available cores
# w = Parallel(n_jobs=cpu_count(), verbose=0)(delayed(get_spec)(toproc[nr_pts[k],:3], 2, out, detrend_mode, res, method, nbin, lentype, taper) for k in range(len(nr_pts)))
# except: #fall back to serial
# w = Parallel(n_jobs=1, verbose=0)(delayed(get_spec)(toproc[nr_pts[k],:3], 2, out, detrend_mode, res, method, nbin, lentype, taper) for k in range(len(nr_pts)))
# #spatial + spectral, with smooth
# if proctype==5:
# try: #parallel processing with all available cores
# w = Parallel(n_jobs=cpu_count(), verbose=0)(delayed(get_spec_spat)(toproc[nr_pts[k],:3], 2, out, detrend_mode, res, method, nbin, lentype, taper) for k in range(len(nr_pts)))
# except: #fall back to serial
# w = Parallel(n_jobs=1, verbose=0)(delayed(get_spec_spat)(toproc[nr_pts[k],:3], 2, out, detrend_mode, res, method, nbin, lentype, taper) for k in range(len(nr_pts)))
# x = np.copy(towrite)[:,6:]
# x_normed = (x - x.min(0)) / x.ptp(0)
# towrite2 = np.hstack((towrite[:,:6], x_normed))
# outfile = infile+'_zstat_detrend'+str(detrend_mode)+'_outres'+str(out)+'_proctype'+str(proctype)+'_mxpts'+str(mxpts)+'_minpts'+str(minpts)+'_norm1.xyz'
#
# try:
# # write the data to the file
# write.txtwrite(outfile, towrite2, header)
#
# except:
# with open(outfile, 'wb') as f:
# np.savetxt(f, towrite2[np.where(towrite2[:,-1])[0],:], header = header, fmt=' '.join(['%8.6f,'] * np.shape(towrite2)[1])[:-1])
#
# towrite2 = np.hstack((towrite[:,:6], x_normed*255))
# outfile = infile+'_zstat_detrend'+str(detrend_mode)+'_outres'+str(out)+'_proctype'+str(proctype)+'_mxpts'+str(mxpts)+'_minpts'+str(minpts)+'_norm255.xyz'
#
# try:
# # write the data to the file
# write.txtwrite(outfile, towrite2, header)
#
# except:
# with open(outfile, 'wb') as f:
# np.savetxt(f, towrite2[np.where(towrite2[:,-1])[0],:], header = header, fmt=' '.join(['%8.6f,'] * np.shape(towrite2)[1])[:-1])