-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.py
1689 lines (1459 loc) · 41.1 KB
/
utilities.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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
from numpy import log, exp
from collections import namedtuple
import os
import shutil
import re
import gzip
import argparse
import itertools
lrg_fig = (12, 8)
#############################################
## Error utilities
#############################################
class UtilitiesException(Exception):
pass
class ParameterException(Exception):
pass
class UserException(Exception):
pass
def approx(num1, num2, m=4, precision=None):
"""
Returns true if num1 and num2 are within a sliver of a floating point
m gives the multplier on the floating point precision
>>> np.exp(np.log(.1)) == .1
False
>>> approx(np.exp(np.log(.1)), .1)
True
"""
if precision:
return abs(num1-num2) <= 10**precision
else:
return abs(num1-num2) <= m * np.spacing(1)
def all_approx(l1, l2, m=4):
"""
Returns true if every element of l1 and l2 are approximately equivalent
>>> l1 = [.1, .2, .3]
>>> l2 = [np.exp(np.log(l)) for l in l1]
>>> all_approx(l1, l2)
True
>>> l1[0]==l2[0]
False
>>> l2 = l2+[.4]
>>> all_approx(l1, l2)
False
>>> all_approx(l2, l1)
False
>>> l1 = l1+[.4]
>>> all_approx(l1, l2)
True
"""
same = (len(l1) == len(l2))
i = 0
while same and i < len(l1):
same = approx(l1[i], l2[i], m)
i += 1
return same
#############################################
## Vector utilities
#############################################
def scale_features(f, mn=None, mx=None, cap_values=1, verbose=False):
if mn is None:
mn = min(f)
if mx is None:
mx = max(f)
if mx - mn == 0:
if verbose:
print("Feature is a constant", mx)
return f
f = (f - mn) / (mx - mn)
if cap_values:
f = np.clip(f, 0, cap_values)
return f
def scale_val(val, rng, cap_values=None):
val = (val - rng[0]) / (rng[1] - rng[0])
if cap_values:
val = np.clip(val, 0, cap_values)
return val
def decay_trace(f, trace=0, replacing_traces=True):
num_steps = len(f)
max_value = max(f)
decayed = np.array([0]*num_steps, dtype=float)
decayed[0] = f[0]
for t in range(1, num_steps):
decayed[t] = f[t] + trace * decayed[t-1]
if replacing_traces:
decayed[t] = min(decayed[t], max_value)
return decayed
def calculate_return(r, gamma=1, horizon=None):
"""
Returns a sequence of len(r) using gamma to calculate
the return value.
Should use horizon rather than discounting, will assume r[0:horizon] is the
relevant bit
>>> calculate_return([1, 0, 0], .5)
array([ 1., 0., 0.])
>>> calculate_return([0, 0, 1], .5)
array([ 0.25, 0.5 , 1. ])
>>> calculate_return([0, 1, 0, 0, 0, 1],.5)
array([ 0.53125, 1.0625 , 0.125 , 0.25 , 0.5 , 1. ])
>>> a = calculate_return([0, 0, 1, 1, 0, 0, -1, -1], .1)
>>> a[:5]
array([ 0.0109989, 0.109989 , 1.09989 , 0.9989 , -0.011 ])
>>> a[5:]
array([-0.11, -1.1 , -1. ])
>>> calculate_return([0, 1, 0, 1, 0, 1], horizon=3)
array([1, 2, 1, 2, 1, 1])
>>> calculate_return([0, 1, 0, 1, 0, 1], horizon=6)
array([3, 3, 2, 2, 1, 1])
>>> calculate_return([0, 1, 0, 1, 0, 1], horizon=10)
array([3, 3, 2, 2, 1, 1])
"""
l = len(r)
if l == 0:
return []
if gamma is None or gamma >= 1:
r = list(r)
ret = [sum(r[i:min(i+horizon, l)]) for i in range(l)]
return np.array(ret)
ret = np.array([0.0]*l)
ret[l-1] = r[l-1]
for i in range(l-2, -1, -1):
ret[i] = r[i] + gamma * ret[i+1]
return ret
def get_bin_index(signal, bins):
"""
Returns the index of the bin that feature belongs in.
bin_bounds contains the upper bound on each bin's value, sorted.
"""
# could do this binary search-like at least
index = 0
for v in bin_bounds:
if signal > v:
return index
index += 1
return index - 1
def log_sum_exp(v):
"""
Calculate the log of the sum of exponentials of the vector elements.
Use the shifting trick to minimize numerical precision errors.
Argument is a list-like thing
similar to np.logaddexp(x1, x2) but takes a 1d list.
>>> log_sum_exp([log(0.5), log(0.5)])
0.0
>>> approx(exp(log_sum_exp([log(0.001), log(0.009), log(0.3)])), .31)
True
"""
m = max(v)
x = m * np.ones(np.size(v))
return m + np.log(sum(np.exp(v - x)))
#############################################
## Math utilities
#############################################
def mscb(t):
"""
Find the index of the most significant change bit,
the bit that will change when t is incremented
>>> mscb(0)
0
>>> mscb(1)
1
>>> mscb(7)
3
>>> mscb(8)
0
"""
return int(np.log2(t ^ (t + 1)))
def argmax(values):
"""
Return the index of the largest value, randomly breaking ties.
>>> argmax([0, 1])
1
>>> argmax([1, 0])
0
>>> a = argmax([0, 1, 1])
>>> a in (1, 2)
True
>>> counter = {0: 0, 1: 0}
>>> for _ in range(20): counter[argmax([1, 1])] += 1
>>> counter[0] > 0
True
>>> counter[1] > 0
True
"""
values = np.array(values)
mx = np.max(values)
val = np.where(values==mx)[0]
return np.random.choice(val)
def calc_alpha_init(alpha, decay):
"""
Calculate the numerator such that at t=0, a/(decay+t)=alpha
"""
if not decay or decay <= 0:
return alpha
else:
return float(alpha * decay)
def running_mean(data, n):
"""
Take a vector a values and a integer window size
Return the vector of values that are the mean over n steps.
Note that (right now at least) the returned vector will be n-1 elements smaller.
>>> running_mean([1, 2, 2, 4, 1, 1], 2)
array([ 1.5, 2. , 3. , 2.5, 1. ])
>>> running_mean([1, 1, 1, 1, 2, 2, 1, 1, 2, 2, 2, 2], 4)
array([ 1. , 1.25, 1.5 , 1.5 , 1.5 , 1.5 , 1.5 , 1.75, 2. ])
"""
return np.convolve(data, np.ones((n, ))/n)[(n-1):-(n-1)]
#############################################
## Format utilities
##
## converts variables into strings that are valid for file names
## uses _ to separate variables and - for equality
## can handle _ in variable name, I think
## varName-value
## listName-item1-item2-item3
## var1-value_var2-value_list-item1-item2
##
##
#############################################
def clean_string(value):
"""
Remove non-standard characters from the string.
"""
return re.sub(r'[^a-zA-Z0-9_.]', '', str(value))
def join_items(values, sort=False):
"""
Converts a list of items into a string with special characters removed
Underscores are left
>>> join_items(['a','b','c'])
'a-b-c'
>>> join_items(['a[0]','a[1]'])
'a0-a1'
>>> join_items(['true_value',8])
'true_value-8'
>>> join_items(['true_values',.1,.2])
'true_values-0.1-0.2'
>>> join_items(['elbow_joint','wrist_joint','shoulder_joint'], True)
'elbow_joint-shoulder_joint-wrist_joint'
>>> join_items('fred')
'fred'
>>> join_items(.9)
'0.9'
>>> join_items(None)
'None'
>>> join_items('')
''
>>> join_items(['a_return', 'a', 'b', 'a_trace'], sort=True)
'a-a_return-a_trace-b'
"""
if isinstance(values, str):
return clean_string(values)
try:
val = []
for v in values:
val.append(clean_string(v))
if sort:
val.sort()
return "-".join(val)
except TypeError:
return str(values)
def split_items(item_string):
"""
Splits a string of - separated items into its component parts.
>>> split_items('true_values-0.1-0.2')
['true_values', 0.1, 0.2]
>>> split_items('a-b-c')
['a', 'b', 'c']
>>> split_items('true_value-8')
['true_value', 8]
>>> split_items('elbow_joint-shoulder_joint-wrist_joint')
['elbow_joint', 'shoulder_joint', 'wrist_joint']
>>> split_items('fred')
['fred']
>>> split_items('None')
[None]
>>> split_items('alpha-0.1_gamma-0.9')
['alpha', '0.1_gamma', 0.9]
"""
parts = item_string.split('-')
items = []
# now clean up the types
for v in parts:
if v.isnumeric():
items.append(int(v))
elif v == 'None':
items.append(None)
else:
try:
items.append(float(v))
except:
items.append(v)
return items
def get_best_file_match(required_features, base_dir):
"""
Looks for files in the given directory that have filenames that
match required_features (using feature1_feature2.txt naming convention)
If no files exist, return the standard filename
Otherwise return the file that includes all the required features with the
fewest extra features
"""
best_match = join_items(remove_modifiers(required_features), sort=True)
required = set(split_items(best_match))
best_match = best_match+".txt"
fe = file_exists(os.path.join(base_dir, best_match), check_zip=True)
if fe:
return os.path.split(fe)[1]
options = get_all_text_files(base_dir, keep_extension=True)
if not options:
return best_match
extra_features = len(required_features) * 10
for o in options:
opt = split_ext(o)[0]
match = match_items(required, opt)
if match > 0 and match < extra_features:
extra_features = match
best_match = o
return best_match
def split_ext(filepath):
"""
Take off extension, and check for another if extension is gz
>>> split_ext('tmp.txt')
('tmp', '.txt')
>>> split_ext('tmp.txt.gz')
('tmp', '.txt.gz')
"""
(fn, ext) = os.path.splitext(filepath)
if ext=='.gz':
(fn, ext) = os.path.splitext(fn)
ext += '.gz'
return (fn, ext)
def match_items(required, potential):
if isinstance(required, str):
required = set(split_items(required))
if isinstance(potential, str):
potential = set(split_items(potential))
return match_sets(required, potential)
def match_sets(required, potential):
"""
Compare the features in required to potential,
return the number of extra features in potential
-1 means missing features
"""
if required.issubset(potential):
return len(potential) - len(required)
else:
return -1
def shorten_keys(params):
"""
Creates a shorter version of the keys in params
"""
param_names = {}
for n in params:
parts = n.split('_')
firsts = [p[0] for p in parts]
param_names[n] = ''.join(firsts)
return param_names
def join_params(**params):
"""
Creates a string from the key-value pairs with _ separating them,
sorted by key
>>> join_params(alpha=.5, gamma=.9)
'alpha-0.5_gamma-0.9'
>>> join_params(features=['a','b','c'],depth=15)
'depth-15_features-a-b-c'
>>> join_params(alpha=.1, trace_rate=None, l=['a','b'])
'alpha-0.1_l-a-b_trace_rate-None'
"""
param_list = get_sorted_keys(params)
values = []
for k in param_list:
values.append(k+'-'+join_items(params[k]))
return "_".join(values)
def params_to_args(**params):
"""
Turns a dictionary of parameters into a command-line list of arguments
>>> params = {'horizon':2, 'trace_rate': .9, 'input_features':['a', 'b'], 'manager': 'env'}
>>> params_to_args(**params)
['--horizon', '2', '--input_features', 'a', 'b', '--manager', 'env', '--trace_rate', '0.9']
>>> params_to_args(alpha=.1, **params)
['--alpha', '0.1', '--horizon', '2', '--input_features', 'a', 'b', '--manager', 'env', '--trace_rate', '0.9']
>>> params_to_args(alpha=.1, weight_reset=True)
['--alpha', '0.1', '--weight_reset']
>>> params_to_args(alpha=.1, weight_reset=False)
['--alpha', '0.1']
"""
args = []
keys = get_sorted_keys(params)
for k in keys:
if params[k] == False:
continue
args.append('--'+k)
if params[k] == True:
continue
if isinstance(params[k], str):
args.append(params[k])
continue
try:
args.extend([str(v) for v in params[k]])
except:
args.append(str(params[k]))
return args
def params_to_arg_string(**params):
"""
Turns a dictionary of parameters into a command-line argument
>>> params = {'horizon':2, 'trace_rate': .9, 'input_features':['a', 'b'], 'manager':'env'}
>>> params_to_arg_string(**params)
'--horizon 2 --input_features a b --manager env --trace_rate 0.9'
"""
args = params_to_args(**params)
return ' '.join(args)
def get_all_dirs(dirpath, base_dir=None):
"""
Return an list of the directories in dirpath, starting with the directory in base_dir
If base_dir is provided but dirpath does not contain it, return None
>>> get_all_dirs('/tmp/asdf/fred')
['tmp', 'asdf', 'fred']
>>> get_all_dirs('/tmp/asdf/fred/') #doesn't care about final slash
['tmp', 'asdf', 'fred']
>>> get_all_dirs('tmp/asdf/fred') # doesn't care about starting slash
['tmp', 'asdf', 'fred']
>>> get_all_dirs('/tmp/asdf/fred/raw.txt') #does include file
['tmp', 'asdf', 'fred', 'raw.txt']
>>> get_all_dirs('./tmp/asdf//fred') # ignores extraneous details
['tmp', 'asdf', 'fred']
>>> get_all_dirs('/tmp/asdf/fred', base_dir='tmp')
['asdf', 'fred']
>>> get_all_dirs('/tmp/asdf/fred', base_dir='/tmp/')
['asdf', 'fred']
>>> get_all_dirs('tmp/asdf/fred', base_dir='/tmp/') # base_dir must match
>>> get_all_dirs('tmp/asdf/fred/', base_dir='../tmp')
>>> get_all_dirs('../tmp/asdf/fred/', base_dir='../tmp')
['asdf', 'fred']
"""
if not base_dir:
post = os.path.normpath(dirpath)
elif base_dir in dirpath:
(pre, post) = dirpath.split(os.path.normpath(base_dir))
post = os.path.normpath(post)
else:
return
dirs = []
(head, tail) = os.path.split(post)
while tail:
dirs.append(tail)
(head, tail) = os.path.split(head)
dirs.reverse()
return dirs
def get_dir_params(dirpath, params):
"""
Split off the tail directory and add the parameters in that string to param
dictionary passed. Return the head directory
>>> params = {}
>>> get_dir_params('/tmp/alpha-1.0_alpha_decay--1', params)
'/tmp'
>>> len(params)
2
>>> params['alpha_decay']
-1
>>> params['alpha']
1.0
"""
(head, tail) = os.path.split(dirpath)
params.update(split_params(tail))
return head
def join_number(string, num, width=None):
"""
Join a number to the end of a string in the standard way
If width is provided will backfill
>>> join_number('fred', 10)
'fred-10'
>>> join_number('fred', 10, 3)
'fred-010'
"""
num = str(num)
if width:
num = num.rjust(width, '0')
return string + '-' + str(num)
def split_number(string):
"""
Splits off a number from the end of the string and returns the tuple
>>> split_number('raw-data.txt-500')
('raw-data.txt', 500)
>>> split_number('square-box-square-2.5')
('square-box-square', 2.5)
>>> split_number('fred')
('fred', None)
>>> split_number('fred-jones')
('fred-jones', None)
>>> split_number(0)
('', 0)
>>> split_number('0')
('', 0)
>>> print(split_number([0]))
None
"""
try:
parts = string.split('-')
except AttributeError:
try:
string * string
return ('', string)
except TypeError:
return None
end = parts[-1]
if '.' in end:
try:
num = float(end)
except:
num = None
else:
try:
num = int(end)
except:
num = None
if num is not None:
parts.pop(-1)
return ('-'.join(parts), num)
def split_params(param_string):
"""
Splits a parameter string into its key-value pairs
>>> d = split_params('alpha-0.5_gamma-0.9')
>>> d['alpha']
0.5
>>> d['gamma']
0.9
>>> d = split_params('depth-15_features-a-b-c')
>>> d['depth']
15
>>> d['features']
['a', 'b', 'c']
>>> d = split_params('alpha-0.1_l-a-b_trace_rate-None')
>>> d['alpha']
0.1
>>> d['l']
['a', 'b']
>>> d['trace_rate']
>>> print(d['trace_rate'])
None
>>> split_params('a-b-c')
{'a': ['b', 'c']}
>>> split_params('a_b_c')
{}
"""
#TODO: check for negatives i.e. alpha--1
parts = param_string.split('_')
params = {}
for i in range(len(parts)):
param = split_items(parts[i])
if len(param) < 2:
try:
parts[i+1] = parts[i] + "_" + parts[i+1]
except:
pass
continue
elif len(param) == 2:
params[param[0]] = param[1]
elif len(param) == 3 and len(param[1]) == 0:
params[param[0]] = -param[2]
else:
params[param[0]] = param[1:]
return params
def add_modifiers(headers, modifiers, keep_unmodified=True, sort=False):
if isinstance(headers, str):
headers = [headers]
if isinstance(modifiers, str):
modifiers = [modifiers]
mod = []
for h in headers:
if keep_unmodified:
mod.append(h)
for m in modifiers:
if m not in h:
mod.append(h+"_"+m)
return mod
def split_modifiers(mod_string, mod_set=None):
"""
Removes modifiers from the given string and returns the
original name plus a list of the modifiers present (checked against mod_set if provided)
>>> split_modifiers('joint_active_scaled_return', ['trace', 'scaled', 'return'])
('joint_active', ['scaled', 'return'])
>>> split_modifiers('joint_active_scaled')
('joint', ['active', 'scaled'])
>>> split_modifiers('joint_active_scaled', {'scaled':'fred','trace':'active'})
('joint_active', ['scaled'])
>>> split_modifiers('joint_scaled_trace')
('joint', ['scaled', 'trace'])
>>> split_modifiers('joint_trace_scaled')
('joint', ['trace', 'scaled'])
>>> split_modifiers('joint_scaled_active_trace', ['trace', 'scaled'])
('joint_active', ['scaled', 'trace'])
>>> split_modifiers('trace_rate_scaled', ['trace', 'scaled'])
('trace_rate', ['scaled'])
"""
parts = mod_string.split('_')
if mod_set is None:
return (parts[0], parts[1:])
name = [parts[0]]
mods = []
for p in parts[1:]:
if p in mod_set:
mods.append(p)
else:
name.append(p)
return ('_'.join(name), mods)
def remove_modifiers(*values, sort=False, mod_set=None):
"""
Removes _scaled, etc, from the feature list to create a unique set
of the features as in the environment directory
>>> features = ['obs2_scaled_decayed','obs1_scaled','obs2_scaled','obs1_return']
>>> remove_modifiers(*features, sort=False)
['obs2', 'obs1']
>>> remove_modifiers(*features, sort=True)
['obs1', 'obs2']
>>> remove_modifiers('trace_rate','trace_key_scaled', 'trace_rate_scaled')
['trace']
>>> remove_modifiers('trace_rate','trace_key_scaled', 'trace_rate_trace', mod_set=['scaled', 'trace'])
['trace_rate', 'trace_key']
"""
features = []
for f in values:
(name, mods) = split_modifiers(f, mod_set=mod_set)
if name not in features:
features.append(name)
if sort:
features.sort()
return features
def get_indices(data_list):
return {d: i for i, d in enumerate(data_list)}
def get_sorted_keys(data):
keys = list(data.keys())
keys.sort()
return keys
#############################################
## File utilities
##
## File format - values are space-separated
## Lines at the beginning starting with '#' are ignored
## The first non-comment line is assumed to be the column headers
## The data is converted to floats and stored in a header-indexed dictionary
## of numpy arrays
def is_zip(filepath):
"""
Return true if filepath ends in 'gz' extension
"""
return os.path.splitext(filepath)[1] == '.gz'
def make_dirs(dirpath, debug=False):
"""
Recursively creates every directory in dirpath if it does not exists.
Returns True/False on success/failure
>>> newdir = '/tmp/asdf/fdsa/fred'
>>> os.path.exists(newdir)
False
>>> os.path.exists('/tmp/asdf/fdsa')
False
>>> make_dirs(newdir)
'/tmp/asdf/fdsa/fred'
>>> os.path.exists(newdir)
True
>>> os.path.exists('/tmp/asdf/fdsa')
True
>>> shutil.rmtree('/tmp/asdf')
>>> make_dirs('/Users/fred', debug=False)
False
"""
if not os.path.exists(dirpath):
try:
os.mkdir(dirpath)
except OSError as e:
if debug:
print(e)
(head, tail) = os.path.split(dirpath)
if '/' not in head or os.path.exists(head):
return False
else:
if(make_dirs(head)):
return make_dirs(dirpath)
return dirpath
def get_array_headers(array_name, length):
"""
Standardize array naming!
>>> get_array_headers('tile_index', 3)
['tile_index-0', 'tile_index-1', 'tile_index-2']
>>> get_array_headers('a', 1)
['a-0']
>>> get_array_headers('a', 10)[0]
'a-00'
>>> get_array_headers('a', 1000)[1]
'a-0001'
"""
width = len(str(length))
return [join_items([array_name, str(i).zfill(width)]) for i in range(length)]
def set_attributes(obj, include_all=True, validate_params=False, valid_params=None, **params):
"""
Set attributes of the obj according to arguments in params
include_all will add all the arguments in params to the object
if not will only add those that are in valid_params
if validate_params, will check that the params in valid_params are not None
# TODO: add validate_params (which will only set it if the object
has that attribute) and valid_params (which will add/change only those
attributes in the list
>>> required_params = ['a','b','c']
>>> ignore_list = ['c']
>>> ns = argparse.Namespace()
>>> set_attributes(ns, a=1, b=None)
>>> ns.a
1
>>> print(ns.b)
None
>>> set_attributes(ns, include_all=False, a=2, b=2)
>>> ns.a
1
>>> set_attributes(ns, include_all=True, a=3, b=3, c=3, valid_params=['a','b'])
>>> ns.a
3
>>> ns.c
3
>>> set_attributes(ns, include_all=False, a=4, b=4, c=4, valid_params=['a','b'])
>>> ns.a
4
>>> ns.c
3
>>> set_attributes(ns, validate_params=True, a=5, b=5, c='foo')
>>> ns.a
5
>>> ns.c
'foo'
>>> set_attributes(ns, validate_params=True, a=6, b=None)
Traceback (most recent call last):
...
ParameterException: Required parameter b set to None
>>> set_attributes(ns, validate_params=True, a=7, b=0, c=None, valid_params=['a','b'])
>>> ns.b
0
>>> set_attributes(ns, validate_params=True, a=8, b=8, c=None, valid_params=['a','b'])
>>> ns.b
8
>>> print(ns.c)
None
>>> set_attributes(ns, a=9, b=9, valid_params=['a','b','c'])
>>> ns.a
9
>>> print(ns.c)
None
>>> set_attributes(ns, a=10, b=10, valid_params=['a','b','c', 'd'])
Traceback (most recent call last):
...
ParameterException: Required parameter d missing
>>> set_attributes(ns, validate_params=True, valid_params=['a','b','c'])
Traceback (most recent call last):
...
ParameterException: Required parameter c set to None
>>> set_attributes(ns, validate_params=True, c=11, valid_params=['a','b','c'])
>>> ns.a
9
>>> ns.c
11
"""
# make sure all required values are here
if valid_params:
for k in valid_params:
if k not in params:
if not hasattr(obj, k):
raise ParameterException("Required parameter {0} missing".format(k))
else:
params[k] = getattr(obj, k)
for k, v in params.items():
check_value = False
# see if we're supposed to add this parameter
if not include_all:
if not valid_params or (valid_params and k not in valid_params):
continue
# see if we are supposed to validate the value, and if it's excluded
if validate_params and (not valid_params or k in valid_params):
check_value = True
if check_value and v is None:
raise ParameterException("Required parameter {0} set to None".format(k))
else:
setattr(obj, k, v)
return
def validate_params(params, required_params, validate_values=False):
"""
Make sure the iterable params contains all elements of required_params
If validate_values is True, make sure params[k] are set.
If required_params is a dictionary, make sure params[k] are set to the values given
>>> validate_params(['a','b','c'], ['a','b'])
True
>>> validate_params(['a','b','c'], ['a','b','d'])
False
>>> validate_params({'a':0,'b':1,'c':2}, ['a','b'])
True
>>> validate_params({'a':0,'b':1,'c':2}, ['a','b','d'])
False
>>> validate_params({'a':0,'b':1,'c':2}, ['a','b'], validate_values=True)
True
>>> validate_params({'a':0,'b':1,'c':2}, ['a','b','d'], validate_values=True)
False
>>> validate_params({'a':None,'b':1,'c':2}, ['a','b','d'], validate_values=True)
False
>>> validate_params({'a':0,'b':1,'c':2}, {'a':0,'b':2}, validate_values=False)
True
>>> validate_params({'a':0,'b':1,'c':2}, {'a':0,'b':2}, validate_values=True)
False
>>> validate_params({'a':0,'b':1,'c':2}, {'a':0,'b':1}, validate_values=True)
True
>>> validate_params({'a':None,'b':1,'c':2}, {'a':0,'b':1}, validate_values=True)
False
>>> validate_params({'a':None,'b':1,'c':2}, {'a':None,'b':1}, validate_values=True)
True
>>> validate_params({'a':0,'b':1,'c':2}, {'a':0,'b':1, 'd':2}, validate_values=True)
False
>>> validate_params({'a':None,'b':1,'c':2}, {'a':[0, None],'b':1, 'c':2}, validate_values=True)
True
"""
# every key (or element) in required_params must be present in the given params
for k in required_params:
if k not in params:
return False
elif validate_values:
try:
# see if we got a dictionary of parameters
p_val = params.get(k)
except AttributeError:
# if it's not a dictionary, it doesn't have values, obviously
return False
# now we need to check if the given parameter value is valid
try:
req_vals = required_params.get(k)
# check if there's a list of requirements
try:
if p_val not in req_vals:
return False
except TypeError:
# check if it matches the required value
if p_val != req_vals:
return False
except AttributeError:
# if the requirements are not specified, just make sure it's set to something
if p_val is None:
return False
# and if we pass all the checks for all the required_params, it's valid
return True
def read_strings(filepointer):
"""
Get the next non-commented line of strings from a file,
separated by whitespace
>>> f = open('results/testing/pos/Large/raw-data.txt', 'r')
>>> read_strings(f)
['a', 'b', 'c', 'd', 'e', 'f', 'step']
>>> for _ in range(100): t = read_strings(f)
>>> print(t)
None
>>> f.closed
False
>>> f.close()
>>> read_strings(f)