forked from insarlab/PyAPS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
672 lines (568 loc) · 23.1 KB
/
utils.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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
############################################################
# Program is part of PyAPS #
# Copyright 2012, by the California Institute of Technology#
# Contact: earthdef@gps.caltech.edu #
# Modified by A. Benoit and R. Jolivet 2019 #
# Ecole Normale Superieure, Paris #
# Contact: insar@geologie.ens.fr #
############################################################
import os
import sys
import time
import numpy as np
import matplotlib.pyplot as plt
import xml.etree.ElementTree as ET
###############Read ISCE / ROIPAC file###############
def get_lat_lon(metafile):
"""Get 2D lat and lon from rsc/xml file
Args:
* metafile (str or dict) : path to metadata file, or dict of metadata
"""
if isinstance(metafile, str):
fext = os.path.splitext(metafile)[1]
if fext == '.rsc':
meta = read_roipac_rsc(metafile)
elif fext == '.xml':
meta = read_isce_xml(metafile)
else:
raise ValueError('unrecognized file extension: {}'.format(fext))
elif isinstance(metafile, dict):
meta = {}
for key, value in metafile.items():
meta[key] = value
length, width = int(meta['FILE_LENGTH']), int(meta['WIDTH'])
# get bbox
if 'Y_FIRST' in meta.keys():
# geo coordinates
lat0 = float(meta['Y_FIRST'])
lon0 = float(meta['X_FIRST'])
lat_step = float(meta['Y_STEP'])
lon_step = float(meta['X_STEP'])
lat1 = lat0 + lat_step * (length - 1)
lon1 = lon0 + lon_step * (width - 1)
else:
# radar coordinates
lats = [float(meta['LAT_REF{}'.format(i)]) for i in [1,2,3,4]]
lons = [float(meta['LON_REF{}'.format(i)]) for i in [1,2,3,4]]
lat0 = np.mean(lats[0:2])
lat1 = np.mean(lats[2:4])
lon0 = np.mean(lons[0:3:2])
lon1 = np.mean(lons[1:4:2])
# bbox --> 2D array
lat, lon = np.mgrid[lat0:lat1:length*1j,
lon0:lon1:width*1j]
return lat, lon
def read_data(fname, dname='inc'):
"""Read 2D data from ISCE / ROIPAC file"""
# get meta file extension
meta_exts = [i for i in ['.xml', '.rsc'] if os.path.isfile(fname+i)]
if len(meta_exts) == 0:
raise FileNotFoundError('No metadata file found for data file: {}'.format(fname))
meta_ext = meta_exts[0]
if meta_ext == '.xml':
data = read_isce_data(fname, dname=dname)
elif meta_ext == '.rsc':
data = read_roipac_data(fname)
return data
def read_metadata(fname, latfile=None, lonfile=None, full=False, verbose=False):
'''Reading metadata for ISCE or ROIPAC style data file
Args:
* fname (str): Path to the ROIPAC or ISCE data file.
Returns:
* lat (np.array) : Array of lat of the 4 corners.
* lon (np.array) : Array of lon of the 4 corners.
* nx (np.int) : Number of range bins.
* ny (np.int) : Number of azimuth lines.
* dpix (np.float): Average pixel spacing.
* meta (dict) : Dictionary of metadata [return if full==True]
'''
# get meta file extension
meta_exts = [i for i in ['.rsc','.xml'] if os.path.isfile(fname+i)]
if len(meta_exts) == 0:
raise FileNotFoundError('No metadata file found for data file: {}'.format(fname))
meta_ext = meta_exts[0]
if verbose:
print("PROGRESS: READING {} FILE".format(fname+meta_ext))
# read metadata
meta = {}
if meta_ext == '.rsc':
meta = read_roipac_rsc(fname+meta_ext)
elif meta_ext == '.xml':
meta = read_isce_xml(fname+meta_ext)
# default latfile
if not latfile:
latfile = os.path.join(os.path.dirname(xmlfile),'lat.rdr')
if not os.path.isfile(latfile):
raise FileNotFoundError("No latitude file found in ISCE style!")
# default lonfile
if not lonfile:
lonfile = os.path.join(os.path.dirname(xmlfile),'lon.rdr')
if not os.path.isfile(lonfile):
raise FileNotFoundError("No longitude file found in ISCE style!")
meta.update(get_isce_lalo_ref(latfile, lonfile))
# prepare output
nx = int(meta['WIDTH'])
ny = int(meta['FILE_LENGTH'])
lat = np.zeros((4,1))
lon = np.zeros((4,1))
lat[0] = float(meta['LAT_REF1'])
lon[0] = float(meta['LON_REF1'])
lat[1] = float(meta['LAT_REF2'])
lon[1] = float(meta['LON_REF2'])
lat[2] = float(meta['LAT_REF3'])
lon[2] = float(meta['LON_REF3'])
lat[3] = float(meta['LAT_REF4'])
lon[3] = float(meta['LON_REF4'])
rgpix = 90.0 #following rd_rsc()
azpix = 90.0 #following rd_rsc()
dpix = np.sqrt(6.25*rgpix*rgpix + azpix*azpix)
if full:
return lon,lat,nx,ny,dpix,meta
else:
return lon,lat,nx,ny,dpix
def read_isce_xml(xmlfile):
"""Read ISCE XML file into dict.
Add from PySAR/pysar/utils/readfile.py by Zhang Yunjun
"""
meta = {}
root = ET.parse(xmlfile).getroot()
if root.tag.startswith('image'):
for child in root.findall('property'):
key = child.get('name')
value = child.find('value').text
meta[key] = value
# Read lat/lon info for geocoded file
# in form: root/component coordinate*/property name/value
for coord_name, prefix in zip(['coordinate1', 'coordinate2'], ['X', 'Y']):
child = root.find("./component[@name='{}']".format(coord_name))
if ET.iselement(child):
v_step = float(child.find("./property[@name='delta']").find('value').text)
v_first = float(child.find("./property[@name='startingvalue']").find('value').text)
if abs(v_step) < 1. and abs(v_step) > 1e-7:
xmlDict['{}_STEP'.format(prefix)] = v_step
xmlDict['{}_FIRST'.format(prefix)] = v_first - v_step / 2.
# convert key name from isce to roipac
isce2roipacKeyDict = {
'width':'WIDTH',
'length':'FILE_LENGTH',
}
for key,value in isce2roipacKeyDict.items():
meta[value] = meta[key]
return meta
def read_isce_data(fname, dname=None):
"""Read ISCE data file"""
# read xml file
xml_file = fname+'.xml'
meta = read_isce_xml(xml_file)
# get data_type
dataTypeDict = {
'byte': 'bool_',
'float': 'float32',
'double': 'float64',
'cfloat': 'complex64',
}
data_type = dataTypeDict[meta['data_type'].lower()]
width = int(meta['width'])
length = int(meta['length'])
num_band = int(meta['number_bands'])
band = 1
if fname.startswith('los') and dname and dname.startswith('az'):
band = 2
# read
data = np.fromfile(fname, dtype=data_type, count=length*width*num_band).reshape(-1, width*num_band)
data = data[:, width*(band-1):width*band]
return data
def get_isce_lalo_ref(lat_file, lon_file):
"""Get LAT/LON_REF1/2/3/4 value from ISCE lat/lon.rdr file
Add from PySAR/pysar/prep_isce.py by Zhang Yunjun
"""
def get_nonzero_row_number(data, buffer=2):
"""Find the first and last row number of rows without zero value
for multiple swaths data
"""
if np.all(data):
r0, r1 = 0 + buffer, -1 - buffer
else:
row_flag = np.sum(data != 0., axis=1) == data.shape[1]
row_idx = np.where(row_flag)[0]
r0, r1 = row_idx[0] + buffer, row_idx[-1] - buffer
return r0, r1
meta = {}
# read LAT/LON_REF1/2/3/4 from lat/lonfile
lat = read_isce_data(lat_file)
r0, r1 = get_nonzero_row_number(lat)
meta['LAT_REF1'] = str(lat[r0, 0])
meta['LAT_REF2'] = str(lat[r0, -1])
meta['LAT_REF3'] = str(lat[r1, 0])
meta['LAT_REF4'] = str(lat[r1, -1])
lon = read_isce_data(lon_file)
r0, r1 = get_nonzero_row_number(lon)
meta['LON_REF1'] = str(lon[r0, 0])
meta['LON_REF2'] = str(lon[r0, -1])
meta['LON_REF3'] = str(lon[r1, 0])
meta['LON_REF4'] = str(lon[r1, -1])
return meta
def read_roipac_rsc(rscfile):
"""Read ROIPAC style RSC file into dict"""
meta = {}
f = open(rscfile,'r')
line = f.readline()
while line:
llist = line.split()
if len(llist)>0 :
meta[llist[0]] = llist[1]
line = f.readline()
f.close()
return meta
def read_roipac_data(fname):
"""Read ROIPAC data file"""
# get length / width
rsc_file = fname+'.rsc'
meta = read_roipac_rsc(rsc_file)
length = int(meta['FILE_LENGTH'])
width = int(meta['WIDTH'])
# get datatype / band
data_type = 'float32'
num_band = 1
band = 1
fext = os.path.splitext(fname)[1]
if fext == '.dem':
data_type = 'int16'
elif fext == '.hgt':
num_band = 2
band = 2
# read
data = np.fromfile(fname, dtype=data_type, count=length*width*num_band).reshape(-1, width*num_band)
data = data[:, width*(band-1):width*band]
return data
###############Read ISCE / ROIPAC file - end###############
###############Reading input RSC file for radar###############
def rd_rsc(inname,full=False,verbose=False):
'''Reading a ROI-PAC style RSC file.
Args:
* inname (str): Path to the RSC file.
Returns:
* lat (np.array) : Array of lat of the 4 corners.
* lon (np.array) : Array of lon of the 4 corners.
* nx (np.int) : Number of range bins.
* ny (np.int) : Number of azimuth lines.
* dpix (np.float): Average pixel spacing.
.. note::
Currently set up to work with SIM_nrlks.hgt from ROI-PAC.'''
if verbose:
print("PROGRESS: READING %s RSC FILE" %inname)
rpacdict = {}
infile = open(inname+'.rsc','r')
line = infile.readline()
rpacdict['LAT_REF1']=0.0
rpacdict['LON_REF1']=0.0
rpacdict['LAT_REF2']=0.0
rpacdict['LON_REF2']=0.0
rpacdict['LAT_REF3']=0.0
rpacdict['LON_REF3']=0.0
rpacdict['LAT_REF4']=0.0
rpacdict['LON_REF4']=0.0
while line:
llist = line.split()
if len(llist)>0 :
rpacdict[llist[0]] = llist[1]
line = infile.readline()
infile.close()
# prepare output
nx = np.int(rpacdict['WIDTH'])
ny = np.int(rpacdict['FILE_LENGTH'])
lat=np.zeros((4,1))
lon=np.zeros((4,1))
lat[0] = np.float(rpacdict['LAT_REF1'])
lon[0] = np.float(rpacdict['LON_REF1'])
lat[1] = np.float(rpacdict['LAT_REF2'])
lon[1] = np.float(rpacdict['LON_REF2'])
lat[2] = np.float(rpacdict['LAT_REF3'])
lon[2] = np.float(rpacdict['LON_REF3'])
lat[3] = np.float(rpacdict['LAT_REF4'])
lon[3] = np.float(rpacdict['LON_REF4'])
#rgpix = np.float(rpacdict['RANGE_PIXEL_SIZE'])
#azpix = np.float(rpacdict['AZIMUTH_PIXEL_SIZE'])
rgpix = 90.0
azpix = 90.0
dpix = np.sqrt(6.25*rgpix*rgpix+azpix*azpix)
if full:
return lon,lat,nx,ny,dpix,rpacdict
else:
return lon,lat,nx,ny,dpix
#######################Finished rd_rsc###########################
###############Reading input RSC file for geo###############
def geo_rsc(inname,full=False,verbose=False):
'''Reading a ROI-PAC style geocoded rsc file.
Args:
* inname (str): Path to the RSC file.
Returns:
* lon (np.array) : Array of min and max lon values.
* lat (np.array) : Array of min and max lat values.
* nx (np.int) : Number of lon bins.
* ny (np.int) : Number of lat bins.
.. note::
Currently set up to work with dem.rsc file from ROI-PAC.'''
if verbose:
print("PROGRESS: READING %s RSC FILE" %inname)
rpacdict = {}
infile = open(inname+'.rsc','r')
line = infile.readline()
while line:
llist = line.split()
if len(llist)>0 :
rpacdict[llist[0]] = llist[1]
line = infile.readline()
infile.close()
nx = np.int(rpacdict['WIDTH'])
ny = np.int(rpacdict['FILE_LENGTH'])
lat=np.zeros((2,1))
lon=np.zeros((2,1))
lat[1] = np.float(rpacdict['Y_FIRST'])
lon[0] = np.float(rpacdict['X_FIRST'])
if(lon[0] < 0):
lon[0] = lon[0] + 360.0
dx = np.float(rpacdict['X_STEP'])
dy = np.float(rpacdict['Y_STEP'])
lat[0] = lat[1] + dy*ny
lon[1] = lon[0] + dx*nx
if full:
return lon,lat,nx,ny,rpacdict
else:
return lon,lat,nx,ny
#######################Finished geo_rsc###########################
##########Conversion from Geo coordinate to Radar coordinates######
def lonlat2rdr(lon, lat, lonlist, latlist, plotflag=False):
'''
Transfer the lat lon coordinates of the weather stations into the index
range and azimuth coordinates of the radar scene.
Args:
* lon : Longitude array of the radar scene size=(ny,nx)
* lat : Latitude array of the radar scene size=(ny,nx)
* lonlist : Longitude list of the weeather stations
* latlist : Latitude list of the weather stations.
Kwargs:
* plotflag : Plot something to check. (default is False)
note:
Mapping function is :
* range = a1*lat+b1*lon+c1
* azimu = a2*lat+b2*lon+c2
* First point is (1,1) i.e. Near Range, First Lane <==> Lat[0,0],Lon[0,0]
* Second point is (nx,1) i.e. Far Range, First Lane <==> Lat[0,-1],Lon[0,-1]
* Third point is (1,ny) i.e. Near Range, Last Lane <==> Lat[-1,0],Lon[-1,0]
* Fourth point is (nx,ny) i.e. Far Range, Last Lane <==> Lat[-1,-1],Lon[-1,-1]
'''
# Size
ny, nx = lon.shape
# Mapping function
A=np.array([ [lat[0,0], lon[0,0], 1.],
[lat[0,-1], lon[0,-1], 1.],
[lat[-1,0], lon[-1,0], 1.],
[lat[-1,-1], lon[-1,-1], 1.]])
b=np.array([[1., 1.],[nx, 1.],[1., ny],[nx,ny]])
mfcn=np.linalg.lstsq(A,b)[0]
#Get grid points xi yi coordinates from this mapping function
A=np.vstack([latlist, lonlist, np.ones(len(lonlist),)]).T
xi=np.dot(A,mfcn[:,0])
yi=np.dot(A,mfcn[:,1])
# Plot y/n
if plotflag:
import matplotlib.patches as ptch
plt.figure()
plt.subplot(211)
plt.scatter(lonlist,latlist,s=8,c=np.cumsum(np.ones(len(lonlist),)))
xline=[lon[0,0],lon[0,-1],lon[-1,-1],lon[-1,0],lon[0,0]]
yline=[lat[0,0],lat[0,-1],lat[-1,-1],lat[-1,0],lat[0,0]]
plt.plot(xline,yline,'-r')
plt.title('Area of interest and {} stations used'.format(len(lonlist)))
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.subplot(212)
plt.scatter(xi,yi,s=8,c=np.cumsum(np.ones(len(lonlist),)))
p = ptch.Rectangle((1,1),lon.shape[1],lon.shape[0],
edgecolor="Red",fill=False)
plt.gca().add_patch(p)
plt.title('Area of interest in Radar Geometry')
plt.xlabel('Range')
plt.ylabel('Azimuth')
plt.show()
# All done
return np.array(xi).astype(float), np.array(yi).astype(float)
def glob2rdr(nx,ny,lat,lon,latl,lonl,plotflag='n'):
'''Transfert these latlon coordinates into radar geometry (xi,yi) with a
simple linear transformation given the first pixel and the pixel
spacing of the simulation.
Args:
* nx (np.int) : Number of range bins.
* ny (np.int) : Number of azimuth lines.
* lat (np.array) : Array of latitudes of the corners
* lon (np.array) : Array of longitudes of the corners
* latl (np.array) : Latitudes of the stations.
* lonl (np.array) : Longitudes of the stations.
Kwargs:
* plotflag (bool) : Plot the stations distribution.
Returns:
* xi (np.array) : Position of stations in range.
* yi (np.array) : Position of stations in azimuth.
.. note::
Mapping function is :
* range = a1*lat+b1*lon+c1
* azimu = a2*lat+b2*lon+c2
* First point is (1,1) i.e. Near Range, First Lane <==> Lat[1],Lon[1]
* Second point is (nx,1) i.e. Far Range, First Lane <==> Lat[2],Lon[2]
* Third point is (1,ny) i.e. Near Range, Last Lane <==> Lat[3],Lon[3]
* Fourth point is (nx,ny) i.e. Far Range, Last Lane <==> Lat[4],Lon[4] '''
# Mapping function
A = np.hstack([lat,lon,np.ones((4,1))])
b = np.array([[1, 1],[nx, 1],[1, ny],[nx,ny]])
mfcn = np.linalg.lstsq(A,b,rcond=None)[0]
#Get grid points xi yi coordinates from this mapping function
nstn = latl.size
A = np.array([latl.reshape(-1,1), lonl.reshape(-1,1), np.ones((nstn,1))]).T
xi = np.dot(A,mfcn[:,0]).reshape(latl.shape)
yi = np.dot(A,mfcn[:,1]).reshape(latl.shape)
if plotflag in ('y','Y'):
plt.figure(1)
plt.subplot(211)
plt.scatter(lonl,latl,s=8,c='k');
xline=[lon[0],lon[1],lon[3],lon[2],lon[0]]
yline=[lat[0],lat[1],lat[3],lat[2],lat[0]]
plt.plot(xline,yline,'-r')
plt.title('Area of interest and %d stations used'%(nstn))
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.subplot(212)
plt.scatter(xi,yi,s=8,c='k')
import matplotlib.patches as ptch
p = ptch.Rectangle((1,1),nx,ny,edgecolor="Red",fill=False)
plt.gca().add_patch(p)
plt.title('Area of interest in Radar Geometry')
plt.xlabel('Range')
plt.ylabel('Azimuth')
plt.show()
return xi,yi
#################Completed transforming geo 2 radar##################
##########Conversion from Geo coordinate to Radar coordinates######
def rdr2glob(wid,lgt,lat,lon,x,y,plotflag='n'): #nx,ny,lat,lon,latl,lonl,plotflag='n'):
'''Transfert these radar geometry (x,y) coordinates in lat/lon coordinates with a
simple linear transformation given the image width/length and the lat/lon coordinates
of the 4 corners
Args:
* wid (np.int) : Width of the image (i.e. number of range bins)
* lgt (np.int) : Length of the image (i.e. number of azimuth lines)
* lat (np.array) : Array of latitudes of the corners
* lon (np.array) : Array of longitudes of the corners
* rang (np.array) : Range of the points to transfert
* azim (np.array) : Azimuth of the points to transfert
Kwargs:
* plotflag (bool) : Plot the stations distribution.
Returns:
* loni (np.array) : Longitude of the points.
* lati (np.array) : Latitude of the points.
.. note::
Mapping function is :
* lat = a1*rang + b1*azim + c1
* lon = a2*rang + b2*azim + c2
* First point is (1,1) i.e. Near Range, First Lane <==> Lat[1],Lon[1]
* Second point is (nx,1) i.e. Far Range, First Lane <==> Lat[2],Lon[2]
* Third point is (1,ny) i.e. Near Range, Last Lane <==> Lat[3],Lon[3]
* Fourth point is (nx,ny) i.e. Far Range, Last Lane <==> Lat[4],Lon[4] '''
A = np.array([[1, 1, 1.],[wid, 1, 1.],[1, lgt, 1.],[wid, lgt, 1.]])
b = np.hstack((lat,lon))
mfcn = np.linalg.lstsq(A,b)[0]
#Get grid points xi yi coordinates from this mapping function
nstn = len(x)
A = np.array([x, y, np.ones((nstn,1))]).T
lati = np.dot(A,mfcn[:,0])
loni = np.dot(A,mfcn[:,1])
if plotflag in ('y','Y'):
plt.figure(1)
plt.subplot(211)
plt.scatter(lon,lat,s=8,c='k');
xline=[lon[0],lon[1],lon[3],lon[2],lon[0]]
yline=[lat[0],lat[1],lat[3],lat[2],lat[0]]
plt.scatter(loni,lati,s=8,c='r')
plt.plot(xline,yline,'-r')
plt.title('Area of interest in geographic coordinates')
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.subplot(212)
plt.scatter(x,y,s=8,c='k')
import matplotlib.patches as ptch
p = ptch.Rectangle((1,1),wid,lgt,edgecolor="Red",fill=False)
plt.gca().add_patch(p)
plt.title('Area of interest in Radar Geometry')
plt.xlabel('Range')
plt.ylabel('Azimuth')
plt.show()
return loni,lati
#################Completed transforming geo 2 radar##################
###########################Simple progress bar######################
class ProgressBar:
""" Creates a text-based progress bar. Call the object with
the simple `print'command to see the progress bar, which looks
something like this:
[=======> 22% ]
You may specify the progress bar's width, min and max values on init.
.. note::
Code originally from http://code.activestate.com/recipes/168639/"""
def __init__(self, minValue = 0, maxValue = 100, totalWidth=80):
self.progBar = "[]" # This holds the progress bar string
self.min = minValue
self.max = maxValue
self.span = maxValue - minValue
self.width = totalWidth
self.reset()
def reset(self):
self.start_time = time.time()
self.amount = 0 # When amount == max, we are 100% done
self.updateAmount(0) # Build progress bar string
def updateAmount(self, newAmount = 0):
""" Update the progress bar with the new amount (with min and max
values set at initialization; if it is over or under, it takes the
min or max value as a default. """
if newAmount < self.min:
newAmount = self.min
if newAmount > self.max:
newAmount = self.max
self.amount = newAmount
# Figure out the new percent done, round to an integer
diffFromMin = np.float(self.amount - self.min)
percentDone = (diffFromMin / np.float(self.span)) * 100.0
percentDone = np.int(np.round(percentDone))
# Figure out how many hash bars the percentage should be
allFull = self.width - 2 - 18
numHashes = (percentDone / 100.0) * allFull
numHashes = np.int(np.round(numHashes))
# Build a progress bar with an arrow of equal signs; special cases for
# empty and full
if numHashes == 0:
self.progBar = '[>%s]' % (' '*(allFull-1))
elif numHashes == allFull:
self.progBar = '[%s]' % ('='*allFull)
else:
self.progBar = '[%s>%s]' % ('='*(numHashes-1),
' '*(allFull-numHashes))
# figure out where to put the percentage, roughly centered
percentPlace = (len(self.progBar) // 2) - len(str(percentDone))
percentString = ' ' + str(percentDone) + '% '
elapsed_time = time.time() - self.start_time
# slice the percentage into the bar
self.progBar = ''.join([self.progBar[0:percentPlace],
percentString,
self.progBar[percentPlace+len(percentString):]])
if percentDone > 0:
self.progBar += ' %6ds / %6ds' % (int(elapsed_time),int(elapsed_time*(100.//percentDone-1)))
def update(self, value, every=1):
""" Updates the amount, and writes to stdout. Prints a
carriage return first, so it will overwrite the current
line in stdout."""
if value % every == 0 or value >= self.max:
self.updateAmount(newAmount=value)
sys.stdout.write('\r' + self.progBar)
sys.stdout.flush()
def close(self):
"""Prints a blank space at the end to ensure proper printing
of future statements."""
print(' ')
################################End of progress bar class####################################