-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathutilities.py
1833 lines (1512 loc) · 62 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
# Princeton University licenses this file to You under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. You may obtain a copy of the License at:
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under the License.
#
#
# ************************************************* Utilities *********************************************************
"""Utilities that must be accessible to all PsyNeuLink modules, but are not PsyNeuLink-specific
That is:
do not require any information about PsyNeuLink objects
are not constrained to be used by PsyNeuLink objects
************************************************* UTILITIES ************************************************************
CONTENTS
--------
*TYPE CHECKING VALUE COMPARISON*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. note::
PsyNeuLink-specific typechecking functions are in the `Component <Component>` module
* `parameter_spec`
* `optional_parameter_spec`
* `all_within_range`
* `is_matrix
* `is_matrix_spec`
* `is_numeric`
* `is_numeric_or_none`
* `is_iterable`
* `iscompatible`
* `is_value_spec`
* `is_unit_interval`
* `is_same_function_spec`
* `is_component`
* `is_comparison_operator`
*ENUM*
~~~~~~
* `Autonumber`
* `Modulation`
* `get_modulationOperation_name`
*KVO*
~~~~~
.. note::
This is for potential future use; not currently used by PsyNeuLink objects
* observe_value_at_keypath
*MATHEMATICAL*
~~~~~~~~~~~~~~
* norm
* sinusoid
* scalar_distance
* powerset
* tensor_power
*OTHER*
~~~~~~~
* `get_args`
* `recursive_update`
* `multi_getattr`
* `np_array_less_that_2d`
* `convert_to_np_array`
* `type_match`
* `get_value_from_array`
* `is_matrix`
* `underscore_to_camelCase`
* `append_type_to_name`
* `ReadOnlyOrderedDict`
* `ContentAddressableList`
* `make_readonly_property`
* `get_class_attributes`
* `insert_list`
* `flatten_list`
* `convert_to_list`
* `get_global_seed`
* `set_global_seed`
"""
import collections
import copy
import inspect
import logging
import numbers
import psyneulink
import re
import time
import warnings
import weakref
import types
import typing
import typecheck as tc
from enum import Enum, EnumMeta, IntEnum
from collections.abc import Mapping
from collections import UserDict, UserList
from itertools import chain, combinations
import numpy as np
from psyneulink.core.globals.keywords import \
comparison_operators, DISTANCE_METRICS, EXPONENTIAL, GAUSSIAN, LINEAR, MATRIX_KEYWORD_VALUES, NAME, SINUSOID, VALUE
__all__ = [
'append_type_to_name', 'AutoNumber', 'ContentAddressableList', 'convert_to_list', 'convert_to_np_array',
'convert_all_elements_to_np_array', 'copy_iterable_with_shared', 'get_class_attributes', 'flatten_list',
'get_all_explicit_arguments', 'get_modulationOperation_name', 'get_value_from_array',
'insert_list', 'is_matrix_spec', 'all_within_range',
'is_comparison_operator', 'iscompatible', 'is_component', 'is_distance_metric', 'is_iterable', 'is_matrix',
'is_modulation_operation', 'is_numeric', 'is_numeric_or_none', 'is_number', 'is_same_function_spec', 'is_unit_interval',
'is_value_spec',
'kwCompatibilityLength', 'kwCompatibilityNumeric', 'kwCompatibilityType',
'make_readonly_property',
'Modulation', 'MODULATION_ADD', 'MODULATION_MULTIPLY','MODULATION_OVERRIDE',
'multi_getattr', 'np_array_less_than_2d', 'object_has_single_value', 'optional_parameter_spec', 'normpdf',
'parse_valid_identifier', 'parse_string_to_psyneulink_object_string', 'parameter_spec', 'powerset',
'random_matrix', 'ReadOnlyOrderedDict', 'safe_equals', 'safe_len',
'scalar_distance', 'sinusoid',
'tensor_power', 'TEST_CONDTION', 'type_match',
'underscore_to_camelCase', 'UtilitiesError', 'unproxy_weakproxy', 'create_union_set', 'merge_dictionaries',
'contains_type'
]
logger = logging.getLogger(__name__)
class UtilitiesError(Exception):
def __init__(self, error_value):
self.error_value = error_value
def __str__(self):
return repr(self.error_value)
MODULATION_OVERRIDE = 'Modulation.OVERRIDE'
MODULATION_MULTIPLY = 'Modulation.MULTIPLY'
MODULATION_ADD = 'Modulation.ADD'
class Modulation(Enum):
MULTIPLY = lambda runtime, default : runtime * default
ADD = lambda runtime, default : runtime + default
OVERRIDE = lambda runtime, default : runtime
DISABLE = 0
def is_modulation_operation(val):
# try:
# val(0,0)
# return True
# except:
# return False
return get_modulationOperation_name(val)
def get_modulationOperation_name(operation):
x = operation(1, 2)
if x == 1:
return MODULATION_OVERRIDE
elif x == 2:
return MODULATION_MULTIPLY
elif x == 3:
return MODULATION_ADD
else:
return False
class AutoNumber(IntEnum):
"""Autonumbers IntEnum type
First item in list of declarations is numbered 0;
Others incremented by 1
Sample:
>>> class NumberedList(AutoNumber):
... FIRST_ITEM = ()
... SECOND_ITEM = ()
>>> NumberedList.FIRST_ITEM.value
0
>>> NumberedList.SECOND_ITEM.value
1
Adapted from AutoNumber example for Enum at https://docs.python.org/3/library/enum.html#enum.IntEnum:
Notes:
* Start of numbering changed to 0 (from 1 in example)
* obj based on int rather than object
"""
def __new__(component_type):
# Original example:
# value = len(component_type.__members__) + 1
# obj = object.__new__(component_type)
value = len(component_type.__members__)
obj = int.__new__(component_type)
obj._value_ = value
return obj
# ******************************** GLOBAL STRUCTURES, CONSTANTS AND METHODS *******************************************
TEST_CONDTION = False
def optional_parameter_spec(param):
"""Test whether param is a legal PsyNeuLink parameter specification or `None`
Calls parameter_spec if param is not `None`
Used with typecheck
Returns
-------
`True` if it is a legal parameter or `None`.
`False` if it is neither.
"""
if not param:
return True
return parameter_spec(param)
def parameter_spec(param, numeric_only=None):
"""Test whether param is a legal PsyNeuLink parameter specification
Used with typecheck
Returns
-------
`True` if it is a legal parameter.
`False` if it is not.
"""
# if isinstance(param, property):
# param = ??
# if is_numeric(param):
from psyneulink.core.components.shellclasses import Projection
from psyneulink.core.components.component import parameter_keywords
from psyneulink.core.globals.keywords import MODULATORY_SPEC_KEYWORDS
from psyneulink.core.components.component import Component
if inspect.isclass(param):
param = param.__name__
elif isinstance(param, Component):
param = param.__class__.__name__
if (isinstance(param, (numbers.Number,
np.ndarray,
list,
tuple,
dict,
types.FunctionType,
Projection))
or param in MODULATORY_SPEC_KEYWORDS
or param in parameter_keywords):
if numeric_only:
if not is_numeric(param):
return False
return True
return False
def all_within_range(x, min, max):
x = np.array(x)
try:
if min is not None and (x<min).all():
return False
if max is not None and (x>max).all():
return False
return True
except (ValueError, TypeError):
for i in x:
if not all_within_range(i, min, max):
return False
return True
def is_numeric_or_none(x):
if x is None:
return True
return is_numeric(x)
def is_numeric(x):
return iscompatible(x, **{kwCompatibilityNumeric:True, kwCompatibilityLength:0})
def is_number(x):
return (
isinstance(x, numbers.Number)
and not isinstance(x, (bool, Enum))
)
def is_matrix_spec(m):
return isinstance(m, str) and m in MATRIX_KEYWORD_VALUES
def is_matrix(m):
from psyneulink.core.components.component import Component
if is_matrix_spec(m):
return True
if isinstance(m, (list, np.ndarray, np.matrix)):
return True
if m is None or isinstance(m, (Component, dict, set)) or (inspect.isclass(m) and issubclass(m, Component)):
return False
try:
m2 = np.matrix(m)
return is_matrix(m2)
except:
pass
if callable(m):
try:
return is_matrix(m())
except:
return False
return False
def is_distance_metric(s):
if s in DISTANCE_METRICS:
return True
else:
return False
def is_iterable(x):
"""
Returns
-------
True - if **x** can be iterated on
False - otherwise
"""
if isinstance(x, np.ndarray) and x.ndim == 0:
return False
else:
return isinstance(x, collections.abc.Iterable)
kwCompatibilityType = "type"
kwCompatibilityLength = "length"
kwCompatibilityNumeric = "numeric"
# IMPLEMENT SUPPORT OF *LIST* OF TYPES IN kwCompatibilityType (see Function.__init__ FOR EXAMPLE)
# IMPLEMENT: IF REFERENCE IS np.ndarray, try converting candidate to array and comparing
def iscompatible(candidate, reference=None, **kargs):
"""Check if candidate matches reference or, if that is omitted, it matches type, length and/or numeric specification
If kargs is omitted, candidate and reference must match in type and length
If reference and kargs are omitted, candidate must be a list of numbers (of any length)
If reference is omitted, candidate must match specs in kargs
kargs is an optional dictionary with the following entries:
kwCompatibilityType ("type"):<type> (default: list): (spec local_variable: match_type)
- if reference is provided, candidate's type must match or be subclass of reference,
irrespective of whether kwCompatibilityType is specified or absent; however, if:
+ kwCompatibilityType is absent, enums are treated as numbers (of which they are a subclass)
+ kwCompatibilityType = enum, then candidate must be an enum if reference is one
- if reference is absent:
if kwCompatibilityType is also absent:
if kwCompatibilityNumeric is `True`, all elements of candidate must be numbers
if kwCompatibilityNumeric is :keyword:`False`, candidate can contain any type
if kwCompatibilityType is specified, candidate's type must match or be subclass of specified type
- for iterables, if kwNumeric is :keyword:`False`, candidate can have multiple types but
if a reference is provided, then the corresponding items must have the same type
kwCompatibilityLength ("length"):<int> (default: 0): (spec local_variable: match_length)
- if kwCompatibilityLength is absent:
if reference is absent, candidate can be of any length
if reference is provided, candidate must match reference length
- if kwCompatibilityLength = 0:
candidate can be any length, irrespective of the reference or its length
- if kwCompatibilityLength > 0:
if reference is provided, candidate must be same length as reference
if reference is omitted, length of candidate must equal value of kwLength
Note: kwCompatibility < 0 is illegal; it will generate a warning and be set to 0
kwCompatibilityNumeric ("number": <bool> (default: `True`) (spec local_variable: number_only)
If kwCompatibilityNumeric is `True`, candidate must be either numeric or a list or tuple of
numeric types
If kwCompatibilityNumberic is :keyword:`False`, candidate can be strings, lists or tuples of strings,
or dicts
Note: if the candidate is a dict, the number of entries (lengths) are compared, but not their contents
:param candidate: (value)
:param reference: (value)
:param args: (dict)
:return:
"""
# If the two are equal, can settle it right here
# IMPLEMENTATION NOTE: remove the duck typing when numpy supports a direct comparison of iterables
try:
with warnings.catch_warnings():
warnings.simplefilter(action='ignore', category=FutureWarning)
if reference is not None and (candidate == reference):
return True
except ValueError:
# raise UtilitiesError("Could not compare {0} and {1}".format(candidate, reference))
# IMPLEMENTATION NOTE: np.array generates the following error:
# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
pass
# If args not provided, assign to default values
# if not specified in args, use these:
# args[kwCompatibilityType] = list
# args[kwCompatibilityLength] = 1
# args[kwCompatibilityNumeric] = True
try:
kargs[kwCompatibilityType]
except KeyError:
kargs[kwCompatibilityType] = list
try:
kargs[kwCompatibilityLength]
except KeyError:
kargs[kwCompatibilityLength] = 1
try:
# number_only = kargs[kwCompatibilityNumeric]
kargs[kwCompatibilityNumeric]
except KeyError:
kargs[kwCompatibilityNumeric] = True
# number_only = True
# If reference is not provided, assign local_variables to arg values (provided or default)
if reference is None:
match_type = kargs[kwCompatibilityType]
match_length = kargs[kwCompatibilityLength]
number_only = kargs[kwCompatibilityNumeric]
# If reference is provided, assign specification local_variables to reference-based values
else:
match_type = type(reference)
# If length specification is non-zero (i.e., use length) and reference is an object for which len is defined:
if (kargs[kwCompatibilityLength] and
(isinstance(reference, (list, tuple, dict)) or
isinstance(reference, np.ndarray) and reference.ndim)
):
match_length = len(reference)
else:
match_length = 0
# If reference is not a number, then don't require the candidate to be one
if not isinstance(reference, numbers.Number):
number_only = False
else:
number_only = kargs[kwCompatibilityNumeric]
if match_length < 0:
# if settings & Settings.VERBOSE:
print("\niscompatible({0}, {1}): length argument must be non-negative; it has been set to 0\n".
format(candidate, kargs, match_length))
match_length = 0
# # FIX??
# # Reference is a matrix or a keyword specification for one
if is_matrix_spec(reference):
return is_matrix(candidate)
# MODIFIED 10/29/17 NEW:
# IMPLEMENTATION NOTE: This allows a number in an ndarray to match a float or int
# If both the candidate and reference are either a number or an ndarray of dim 0, consider it a match
if ((is_number(candidate) or (isinstance(candidate, np.ndarray) and candidate.ndim == 0)) or
(is_number(reference) or (isinstance(reference, np.ndarray) and reference.ndim == 0))):
return True
# MODIFIED 10/29/17 END
# IMPLEMENTATION NOTE:
# modified to allow numeric type mismatches (e.g., int and float;
# should be added as option in future (i.e., to disallow it)
if (isinstance(candidate, match_type) or
(isinstance(candidate, (list, np.ndarray)) and (issubclass(match_type, (list, np.ndarray)))) or
(is_number(candidate) and issubclass(match_type,numbers.Number)) or
# IMPLEMENTATION NOTE: Allow UserDict types to match dict (make this an option in the future)
(isinstance(candidate, UserDict) and match_type is dict) or
# IMPLEMENTATION NOTE: Allow UserList types to match list (make this an option in the future)
(isinstance(candidate, UserList) and match_type is list) or
# IMPLEMENTATION NOTE: This is needed when kwCompatiblityType is not specified
# and so match_type==list as default
(is_number(candidate) and issubclass(match_type,list)) or
(isinstance(candidate, np.ndarray) and issubclass(match_type,list))
):
# Check compatibility of enum's
# IMPLEMENTATION NOTE: THE FIRST VERSION BELOW SOUGHT TO CHECK COMPATIBILTY OF ENUM VALUE; NEEDS WORK
# if (kargs[kwCompatibilityType] is Enum and
# (isinstance(candidate, Enum) or isinstance(match_type, (Enum, IntEnum, EnumMeta)))):
# # If either the candidate enum's label is not in the reference's Enum class
# # or its value is different, then return with fail
# try:
# match_type.__dict__['_member_names_']
# except:
# pass
# if not (candidate.name in match_type.__dict__['_member_names_'] and
# candidate.value is match_type.__dict__['_member_map_'][candidate.name].value):
# return False
# This version simply enforces the constraint that, if either is an enum of some sort, then both must be
if kargs[kwCompatibilityType] is Enum:
return isinstance(candidate, Enum) == isinstance(match_type, (Enum, IntEnum, EnumMeta))
if is_number(candidate):
return True
if number_only:
if isinstance(candidate, np.ndarray) and candidate.ndim ==0 and np.isreal(candidate):
return True
if not isinstance(candidate, (list, tuple, np.ndarray, np.matrix)):
return False
def recursively_check_elements_for_numeric(value):
# Matrices can't be checked recursively, so convert to array
if isinstance(value, np.matrix):
value = value.A
if isinstance(value, (list, np.ndarray)):
for item in value:
if not recursively_check_elements_for_numeric(item):
return False
else:
return True
else:
if not is_number(value):
try:
# True for autograd ArrayBox (and maybe other types?)
# if isinstance(value._value, numbers.Number):
from autograd.numpy.numpy_boxes import ArrayBox
if isinstance(value, ArrayBox):
return True
except:
return False
else:
return True
# Test copy since may need to convert matrix to array (see above)
if not recursively_check_elements_for_numeric(candidate.copy()):
return False
if isinstance(candidate, (list, tuple, dict, np.ndarray)):
if not match_length:
return True
else:
if len(candidate) == match_length:
# No reference, so item by item comparison is not relevant
if reference is None:
return True
# Otherwise, carry out recursive elementwise comparison
if isinstance(candidate, np.matrix):
candidate = np.asarray(candidate)
if isinstance(reference, np.matrix):
reference = np.asarray(reference)
cr = zip(candidate, reference)
if all(iscompatible(c, r, **kargs) for c, r in cr):
return True
# IMPLEMENTATION NOTE: ??No longer needed given recursive call above
# Deal with ints in one and floats in the other
# # elif all((isinstance(c, numbers.Number) and isinstance(r, numbers.Number))
# # for c, r in cr):
# # return True
else:
return False
else:
return True
else:
return False
# MATHEMATICAL ********************************************************************************************************
def normpdf(x, mu=0, sigma=1):
u = float((x - mu) / abs(sigma))
y = np.exp(-u * u / 2) / (np.sqrt(2 * np.pi) * abs(sigma))
return y
def sinusoid(x, amplitude=1, frequency=1, phase=0):
return amplitude * np.sin(2 * np.pi * frequency * x + phase)
def scalar_distance(measure, value, scale=1, offset=0):
if measure == GAUSSIAN:
return normpdf(value, offset, scale)
if measure == LINEAR:
return scale * value + offset
if measure == EXPONENTIAL:
return np.exp(scale * value + offset)
if measure == SINUSOID:
return sinusoid(value, frequency=scale, phase=offset)
def powerset(iterable):
"""powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"""
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
@tc.typecheck
def tensor_power(items, levels:tc.optional(range)=None, flat=False):
"""return tensor product for all members of powerset of items
levels specifies a range of set levels to return; 1=first order terms, 2=2nd order terms, etc.
if None, all terms will be returned
if flat=False, returns list of 1d arrays with tensor product for each member of the powerset
if flat=True, returns 1d array of values
"""
ps = list(powerset(items))
max_levels = max([len(s) for s in ps])
levels = levels or range(1,max_levels)
max_spec = max(list(levels))
min_spec = min(list(levels))
if max_spec > max_levels:
raise UtilitiesError("range ({},{}) specified for {} arg of tensor_power() "
"exceeds max for items specified ({})".
format(min_spec, max_spec + 1, repr('levels'), max_levels + 1))
pp = []
for s in ps:
order = len(s)
if order not in list(levels):
continue
if order==1:
pp.append(np.array(s[0]))
else:
i = 0
tp = np.tensordot(s[i],s[i + 1],axes=0)
i += 2
while i < order:
tp = np.tensordot(tp, s[i], axes=0)
i += 1
if flat is True:
pp.extend(tp.reshape(-1))
else:
pp.append(tp.reshape(-1))
return pp
# OTHER ****************************************************************************************************************
def get_args(frame):
"""Gets dictionary of arguments and their values for a function
Frame should be assigned as follows in the function itself: frame = inspect.currentframe()
"""
args, _, _, values = inspect.getargvalues(frame)
return dict((key, value) for key, value in values.items() if key in args)
def recursive_update(d, u, non_destructive=False):
"""Recursively update entries of dictionary d with dictionary u
From: https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
"""
for k, v in u.items():
if isinstance(v, Mapping):
r = recursive_update(d.get(k, {}), v)
d[k] = r
else:
if non_destructive and k in d and d[k] is not None:
continue
d[k] = u[k]
return d
def multi_getattr(obj, attr, default = None):
"""
Get a named attribute from an object; multi_getattr(x, 'a.b.c.d') is
equivalent to x.a.b.c.d. When a default argument is given, it is
returned when any attribute in the chain doesn't exist; without
it, an exception is raised when a missing attribute is encountered.
"""
attributes = attr.split(".")
for i in attributes:
try:
obj = getattr(obj, i)
except AttributeError:
if default:
return default
else:
raise
return obj
# # Example usage
# obj = [1,2,3]
# attr = "append.__doc__.capitalize.__doc__"
# http://pythoncentral.io/how-to-get-an-attribute-from-an-object-in-python/
# getattr also accepts modules as arguments.
# # http://code.activestate.com/recipes/577346-getattr-with-arbitrary-depth/
# multi_getattr(obj, attr) #Will return the docstring for the
# #capitalize method of the builtin string
# #object
# based off the answer here https://stackoverflow.com/a/15774013/3131666
def get_deepcopy_with_shared(shared_keys=frozenset(), shared_types=()):
"""
Arguments
---------
shared_keys
an Iterable containing strings that should be shallow copied
shared_types
an Iterable containing types that when objects of that type are encountered
will be shallow copied
Returns
-------
a __deepcopy__ function
"""
shared_types = tuple(shared_types)
shared_keys = frozenset(shared_keys)
def __deepcopy__(self, memo):
cls = self.__class__
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
if k in shared_keys or isinstance(v, shared_types):
res_val = v
else:
try:
res_val = copy_iterable_with_shared(v, shared_types, memo)
except TypeError:
res_val = copy.deepcopy(v, memo)
setattr(result, k, res_val)
return result
return __deepcopy__
def copy_iterable_with_shared(obj, shared_types=None, memo=None):
try:
shared_types = tuple(shared_types)
except TypeError:
shared_types = (shared_types, )
dict_types = (dict, collections.UserDict)
list_types = (list, collections.UserList, collections.deque)
tuple_types = (tuple, )
all_types_using_recursion = dict_types + list_types + tuple_types
if isinstance(obj, dict_types):
result = copy.copy(obj)
del_keys = set()
for (k, v) in obj.items():
# key can never be unhashable dict or list
new_k = k if isinstance(k, shared_types) else copy.deepcopy(k, memo)
if new_k is not k:
del_keys.add(k)
if isinstance(v, all_types_using_recursion):
new_v = copy_iterable_with_shared(v, shared_types, memo)
elif isinstance(v, shared_types):
new_v = v
else:
new_v = copy.deepcopy(v, memo)
try:
result[new_k] = new_v
except UtilitiesError:
# handle ReadOnlyOrderedDict
result.__additem__(new_k, new_v)
for k in del_keys:
del result[k]
elif isinstance(obj, list_types + tuple_types):
is_tuple = isinstance(obj, tuple_types)
if is_tuple:
result = list()
# If this is a deque, make sure we copy the maxlen parameter as well
elif isinstance(obj, collections.deque):
# FIXME: Should have a better method for supporting properties like this in general
# We could do something like result = copy(obj); result.clear() but that would be
# wasteful copying I guess.
result = obj.__class__(maxlen=obj.maxlen)
else:
result = obj.__class__()
for item in obj:
if isinstance(item, all_types_using_recursion):
new_item = copy_iterable_with_shared(item, shared_types, memo)
elif isinstance(item, shared_types):
new_item = item
else:
new_item = copy.deepcopy(item, memo)
result.append(new_item)
if is_tuple:
try:
result = obj.__class__(result)
except TypeError:
# handle namedtuple
result = obj.__class__(*result)
else:
raise TypeError
return result
def get_alias_property_getter(name, attr=None):
"""
Arguments
---------
name : str
attr : str : default None
Returns
-------
a property getter method that
if **attr** is None, returns the **name** attribute of an object
if **attr** is not None, returns the **name** attribute of the
**attr** attribute of an object
"""
if attr is not None:
def getter(obj):
return getattr(getattr(obj, attr), name)
else:
def getter(obj):
return getattr(obj, name)
return getter
def get_alias_property_setter(name, attr=None):
"""
Arguments
---------
name : str
attr : str : default None
Returns
-------
a property setter method that
if **attr** is None, sets the **name** attribute of an object
if **attr** is not None, sets the **name** attribute of the
**attr** attribute of an object
"""
if attr is not None:
def setter(obj, value):
setattr(getattr(obj, attr), name, value)
else:
def setter(obj, value):
setattr(obj, name, value)
return setter
#region NUMPY ARRAY METHODS ******************************************************************************************
def np_array_less_than_2d(array):
if not isinstance(array, np.ndarray):
raise UtilitiesError("Argument to np_array_less_than_2d() ({0}) must be an np.ndarray".format(array))
if array.ndim <= 1:
return True
else:
return False
def convert_to_np_array(value, dimension=None):
"""
Converts value to np.ndarray if it is not already. Handles
creation of "ragged" arrays
(https://numpy.org/neps/nep-0034-infer-dtype-is-object.html)
Args:
value
item to convert to np.ndarray
dimension : 1, 2, None
minimum dimension of np.ndarray to convert to
Returns:
value : np.ndarray
"""
def safe_create_np_array(value):
with warnings.catch_warnings():
warnings.filterwarnings('error', category=np.VisibleDeprecationWarning)
# NOTE: this will raise a ValueError in the future.
# See https://numpy.org/neps/nep-0034-infer-dtype-is-object.html
try:
try:
return np.asarray(value)
except np.VisibleDeprecationWarning:
return np.asarray(value, dtype=object)
except ValueError as e:
msg = str(e)
if 'cannot guess the desired dtype from the input' in msg:
return np.asarray(value, dtype=object)
# KDM 6/29/20: this case handles a previously noted case
# by KAM 6/28/18, #877:
# [[0.0], [0.0], np.array([[0.0, 0.0]])]
# but was only handled for dimension=1
elif 'could not broadcast' in msg:
return convert_all_elements_to_np_array(value)
else:
raise
value = safe_create_np_array(value)
if dimension == 1:
value = np.atleast_1d(value)
elif dimension == 2:
# Array is made up of non-uniform elements, so treat as 2d array and pass
if (
value.ndim > 0
and value.dtype == object
and any([safe_len(x) > 1 for x in value])
):
pass
else:
value = np.atleast_2d(value)
elif dimension is not None:
raise UtilitiesError("dimension param ({0}) must be None, 1, or 2".format(dimension))
return value
def object_has_single_value(obj):
"""
Returns
-------
True : if **obj** contains only one value, in any dimension
False : otherwise
**obj** will be cast to a numpy array if it is not already one
"""
if not isinstance(obj, np.ndarray):
obj = np.asarray(obj)
for s in obj.shape:
if s > 1:
return False
return True
def type_match(value, value_type):
if isinstance(value, value_type):
return value
if value_type in {int, np.integer, np.int64, np.int32}:
return int(value)
if value_type in {float, np.float, np.float64, np.float32}:
return float(value)
if value_type is np.ndarray:
return np.array(value)
if value_type is list:
return list(value)
if value_type is None:
return None
if value_type is type(None):
return value
raise UtilitiesError("Type of {} not recognized".format(value_type))
def get_value_from_array(array):
"""Extract numeric value from array, preserving numeric type
:param array:
:return:
"""
def random_matrix(sender, receiver, clip=1, offset=0):
"""Generate a random matrix
Calls np.random.rand to generate a 2d np.array with random values.
Arguments
----------
sender : int
specifies number of rows.
receiver : int
spcifies number of columns.
range : int
specifies upper limit (lower limit = 0).
offset : int
specifies amount added to each entry of the matrix.
Returns
-------
2d np.array
"""
return (clip * np.random.rand(sender, receiver)) + offset
def underscore_to_camelCase(item):
item = item[1:]
item = ''.join(x.capitalize() or '_' for x in item.split('_'))
return item[0].lower() + item[1:]
def append_type_to_name(object, type=None):
name = object.name
# type = type or object.componentType
# type = type or object.__class__.__base__.__base__.__base__.__name__