-
Notifications
You must be signed in to change notification settings - Fork 4
/
v_utilities.py
executable file
·697 lines (523 loc) · 16.1 KB
/
v_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
# -*- coding: utf-8 -*-
"""
This module contains miscellaneous tools appliable to a variaty of tasks.
It could be divided into 4 main sections:
(1) transforming to and from string other classes
(`nparray_to_string`, `dict_to_string`, `find_numbers`, etc)
(2) useful custom-made classes to manage data
(`WrapperDict`, `DottableWrapper`, `NumpyArrayParamType`)
(3) treating lists of strings (`filter_by_string_must`, `sort_by_number`)
and dicts of strings (`join_strings_dict`)
(4) fixing bugs in my thesis' data due to code mistakes
Some of its most useful tools are...
find_numbers : function
Returns a list of numbers found on a given string
sort_by_number : function
Sorts list of strings by a variable number of recurrent position.
WrapperList : class
A list subclass that applies methods to a list of instances.
WrapperDict : class
A dict subclass that applies methods to a dict of instances.
DottableWrapper : class
Example of a class which allows dot calling instances.
fix_params_dict : function
Fixes the faulty params dict caused by wlen_range np.array on vs.savetxt
@author: Vall
"""
import numpy as np
from re import findall
import warnings
#%%
def nparray_to_string(my_nparray):
"""Transforms np.ndarray to string in a retrievable way.
Parameters
----------
my_nparray : np.ndarray
The np.ndarray to transform (could have ndim>1).
Returns
-------
my_string : str
The np.ndarray transformed to string.
See also
--------
string_to_nparray
"""
this_string = []
for n in my_nparray:
if not isinstance(n, np.ndarray):
this_string.append(str(n))
else:
this_string.append( nparray_to_string(n) )
my_string = "[" + ", ".join(this_string) + "]"
return my_string
#%%
def dict_to_string(my_dict):
"""Transforms dict to string in a retrievable way.
Parameters
----------
my_dict : dict
The dict to transform.
Returns
-------
my_string : str
The dict transformed to string.
See also
--------
string_to_dict
"""
aux = []
for key, value in my_dict.items():
if isinstance(value, str):
value = '"{}"'.format(value)
elif isinstance(value, np.ndarray):
value = "np.array(" + nparray_to_string(value) + ")"
elif isinstance(value, tuple) and len(value) == 2:
condition = isinstance(value[0], str)
if not condition and isinstance(value[1], str):
value = '"{}, {}"'.format(*value)
aux.append(f'{key}={value}' + ', ')
my_string = ''.join(aux)[:-2]
return my_string
#%%
def string_to_nparray(my_nparray_string):
"""Retrieves np.ndarray from string.
Parameters
----------
my_nparray_string : str
The np.ndarray transformed to string.
Returns
-------
my_nparray : np.ndarray
The np.ndarray retrieved (could have ndim>1).
See also
--------
nparray_to_string
"""
return eval(f"np.array({my_nparray_string})")
#%%
def string_to_dict(my_dict_string):
"""Retrieves dict from string.
Parameters
----------
my_dict_string : str
The dict transformed to string.
Returns
-------
my_dict : dict
The dict retrieved.
See also
--------
dict_to_string
"""
return eval(f"dict({my_dict_string})")
#%%
class WrapperList(list):
"""A list subclass that applies methods to a list of instances.
Examples
--------
>> class MyClass:
def __init__(self, value=10):
self.sub_prop = value
self._prop = value
@property
def prop(self):
return self._prop
@prop.setter
def prop(self, value):
self._prop = value
def sub_method(self, item):
return item * self.sub_prop
def method(self, item):
return item * self.prop
>> Z = WrapperList([MyClass(), MyClass(2)])
>> Z.prop
[10, 2]
>> Z._prop
[10, 2]
>> Z.sub_prop
[10, 2]
>> Z.method(2)
[20, 4]
>> Z.prop = 3
>> Z.prop
[3, 3]
>> Z.append(MyClass(1))
>> Z.prop
[3, 3, 1]
>> Z.prop = [10, 2, 1]
>> Z.prop
[10, 2, 1]
Warnings
--------
>> Z.prop = [2, 3]
>> Z.prop
[[2,3], [2,3], [2,3]]
"""
def __init__(self, iterable=[]):
super().__init__(iterable)
def __transf_methods__(self, methods_list):
def function(*args, **kwargs):
results = [m(*args, **kwargs) for m in methods_list]
return results
return function
def __getattr__(self, name):
if name in dir(self):
super().__getattribute__(name)
else:
result = []
for ins in self:
result.append(ins.__getattribute__(name))
if callable(result[0]):
result = self.__transf_methods__(result)
return result
def __setattr__(self, name, value):
if isinstance(value, list) and len(value) == len(self):
for ins, v in zip(self, value):
ins.__setattr__(name, v)
else:
for ins in self:
ins.__setattr__(name, value)
#%%
class WrapperDict(dict):
"""A dict subclass that applies methods to a dict of instances.
Examples
--------
>> class MyClass:
def __init__(self, value=10):
self.sub_prop = value
self._prop = value
@property
def prop(self):
return self._prop
@prop.setter
def prop(self, value):
self._prop = value
def sub_method(self, item):
return item * self.sub_prop
def method(self, item):
return item * self.prop
>> Z = WrapperDict(a=MyClass(), b=MyClass(2))
>> Z.prop
{'a': 10, 'b': 2}
>> Z.update(c=MyClass(1))
>> Z.prop
{'a': 10, 'b': 2, 'c': 1}
>> Z.method(2)
{'a': 20, 'b': 4, 'c': 2}
>> Z.prop = 3
>> Z.prop
{'a': 3, 'b': 3, 'c': 3}
>> Z.prop = {'a': 10, 'b': 2, 'c': 1}
>> Z.prop
{'a': 10, 'b': 2, 'c': 1}
"""
def __init__(self, **elements):
super().__init__(**elements)
def __transf_methods__(self, methods_dic):
def function(*args, **kwargs):
results = {}
for key, method in methods_dic.items():
results.update({key: method(*args, **kwargs)})
return results
return function
def __getattr__(self, name):
if name in dir(self):
super().__getattribute__(name)
else:
result = {n : ins.__getattribute__(name)
for n, ins in self.items()}
if callable(list(result.values())[0]):
result = self.__transf_methods__(result)
return result
def __setattr__(self, name, value):
if isinstance(value, dict):
for ins, v in zip(self.values(), value.values()):
ins.__setattr__(name, v)
else:
for ins in self.values():
ins.__setattr__(name, value)
#%%
class DottableWrapper:
"""Example of a class which allows dot calling instances.
Examples
--------
>> class MyClass:
def __init__(self, value=10):
self.sub_prop = value
self._prop = value
@property
def prop(self):
return self._prop
@prop.setter
def prop(self, value):
self._prop = value
def sub_method(self, item):
return item * self.sub_prop
def method(self, item):
return item * self.prop
>> Z = DottableWrapper(a=MyClass(), b=MyClass(2))
>>
>> # Let's check dot calling
>> Z.a.sub_prop
10
>> Z.a.sub_prop = 1
>> Z.a.sub_prop
1
>>
>> # Let's check dot calling all instances at once
>> Z.all.sub_prop
{'a': 1, 'b': 2}
>> Z.all.sub_prop = 3
>> Z.all.sub_prop
{'a': 3, 'b': 3}
>> Z.all.sub_prop = {'a': 1}
>> Z.all.sub_prop
{'a': 1, 'b': 3}
>>
>> # This also works with methods
>> Z.a.prop
10
>> Z.a.method(2)
20
>> Z.all.prop
{'a': 10, 'b': 2}
>> Z.all.method(2)
{'a': 20, 'b': 4}
>>
>> # This is an updatable class too
>> Z.add(c=MyClass(4))
>> Z.all.sub_prop
{'a': 1, 'b': 3, 'c': 4}
>> Z.c.sub_prop
4
"""
def __init__(self, **instances):
self.all = WrapperDict()
self.add(**instances)
# def __print__(self):
# self.all.__print__()
# def __repr__(self):
# self.all.__repr__()
def add(self, **instances):
instances = dict(instances)
self.__dict__.update(instances)
self.all.update(instances)
#%%
class BilingualManager:
def __init__(self, english=True):
self.english = english
def choose(self, english_string, spanish_string):
if self.english:
return english_string
else:
return spanish_string
#%%
def camel(string):
return string[0].upper() + string[1:].lower()
#%%
def round_to_multiple(numerator, denominator, round_up=False, round_down=False):
if round_up:
result = np.ceil(numerator / denominator) * denominator
elif round_down:
result = np.floor(numerator / denominator) * denominator
else:
result = np.round(numerator / denominator) * denominator
sign = np.sign(numerator)
if sign == -1: result = min(result, -denominator)
else: result = max(result, denominator)
# with warnings.catch_warnings():
# warnings.simplefilter("ignore")
# try:
# decimals = int(abs(np.floor(np.log10( abs(denominator - int(denominator)) ))))
# result = np.round(result, decimals)
# except:
# decimals = 0
# result = int(result)
return result
#%%
def find_numbers(string):
"""Returns a list of numbers found on a given string
Parameters
----------
string: str
The string where you search.
Returns
-------
list
A list of numbers (each an int or float).
Raises
------
"There's no number in this string" : TypeError
If no number is found.
Warnings
--------
Doesn't recognize scientific notation.
"""
numbers = findall(r"[-+]?\d*\.\d+|[-+]?\d+", string)
if not numbers:
raise TypeError("There's no number in this string")
for i, n in enumerate(numbers):
if '.' in n:
numbers[i] = float(n)
else:
numbers[i] = int(n)
return numbers
#%%
def counting_sufix(number):
"""Returns a number's suffix string to use for counting.
Parameters
----------
number: int, float
Any number, though it is designed to work with integers.
Returns
-------
ans: str
A string representing the integer number plus a suffix.
Examples
--------
>> counting_sufix(1)
'1st'
>> counting_sufix(22)
'22nd'
>> counting_sufix(1.56)
'2nd'
"""
number = round(number)
unit = int(str(number)[-1])
if unit == 1:
ans = 'st'
elif unit == 2:
ans = 'nd'
elif unit == 3:
ans = 'rd'
else:
ans = 'th'
return ans
#%%
def filter_by_string_must(string_list, string_must, must=True):
"""Filters list of str by a str required to be always present or absent.
Parameters
----------
string_list : list of str
The list of strings to filter.
string_must : str
The string that must always be present or always absent on each of the
list elements.
must=True : bool
If true, then the string must always be present. If not, the string
must always be absent.
Returns
-------
filtered_string_list: list of str
The filtered list of strings.
"""
if not isinstance(string_must, list):
string_must = [string_must]
filtered_string_list = []
for s in string_list:
do_append = True
for smust in string_must:
if must and smust not in s:
do_append = False
break
elif not must and smust in s:
do_append = False
break
if do_append:
filtered_string_list.append(s)
return filtered_string_list
#%%
def filter_to_only_directories(string_list):
"""Filters list of strings by returning only directories.
Parameters
----------
string_list : list of str
The list of strings to filter.
Returns
-------
filtered_string_list: list of str
The filtered list of strings.
"""
filtered_string_list = []
for s in string_list:
if '.' not in s:
filtered_string_list.append(s)
return filtered_string_list
#%%
def sort_by_number(string_list, number_index=0):
"""Sorts list of strings by a variable number of recurrent position.
Parameters
----------
string_list : list of str
The list of strings to order.
number_index=0 : int, optional
The index of the recurrent number inside the expression (0 would be
the 1st number, 1 the 2nd and so on)
Returns
-------
sorted_string_list: list of str
The ordered list of strings.
"""
numbers = [find_numbers(s)[number_index] for s in string_list]
index = np.argsort(numbers)
sorted_string_list = [string_list[i] for i in index]
return sorted_string_list
#%%
def enumerate_string(str_list, str_sep="and", str_sep_always=False):
"""Returns a one phrase enumeration from a list of strings.
Parameters
----------
str_list : list of str
The list of strings to join into a one phrase enumeration.
str_sep="and" : str, optional
The final separator that isn't a comma. The default is "and".
str_sep_always=False : bool, optional
If true, the string separator is used between all strings and not just
the final two. The default is `False`.
Returns
-------
answer : str
The phrase enumeration as a unique string.
"""
if str_sep_always:
answer = f" {str_sep} ".join(str_list)
else:
answer = ", ".join(str_list[:-1])
answer += f" {str_sep} " + str_list[-1]
return answer
#%%
def join_strings_dict(str_dict, str_joiner="for"):
"""
Returns a list of strings joining key and value from a strings dictionary.
Parameters
----------
str_dict : dict of str
Dictionary of strings. Both key and values must be strings.
str_joiner="for" : str
Joiner for formatting each pair of key-value as 'key str_joiner value'.
Returns
-------
str_list : list of str
List of strings already formatted to join each pair of key-value.
"""
str_list = []
for k, v in str_dict.items():
str_list.append( f"'{k}' for {v}")
return str_list
#%%
def fix_params_dict(faulty_params):
"""Fixes the faulty params dict caused by wlen_range np.array on vs.savetxt
Parameters
----------
faulty_params : str
The faulty params dict wrongly expressed as a string.
Returns
-------
fixed_params : dict
The fixed params dict correctly expressed as a dict.
"""
problem = faulty_params.split("wlen_range=")[1].split(", nfreq")[0]
solved = str(find_numbers(problem))
fixed_params = solved.join(faulty_params.split(problem))
fixed_params = string_to_dict(fixed_params)
return fixed_params