-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicVector.py
More file actions
1856 lines (1477 loc) · 64.3 KB
/
Copy pathDynamicVector.py
File metadata and controls
1856 lines (1477 loc) · 64.3 KB
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
try:
from ._metadata import (
__version__,
__author__,
__credits__,
__maintainer__,
__email__,
__license__,
__status__,
__url__,
__description__,
__copyright__,
)
except ImportError:
try:
from _metadata import (
__version__,
__author__,
__credits__,
__maintainer__,
__email__,
__license__,
__status__,
__url__,
__description__,
__copyright__,
)
except ImportError:
# _metadata.py failed to load,
# fill in with dummy values (script may be standalone)
__version__ = "Failed to load from _metadata.py"
__author__ = "Scott E. Boyce"
__credits__ = "Scott E. Boyce"
__maintainer__ = "Scott E. Boyce"
__email__ = "boyce@engineer.com"
__license__ = "MIT"
__status__ = __version__
__url__ = "https://github.com/ScottBoyce-Python/DynamicVector"
__description__ = "A dynamic vector implementation using NumPy arrays, with dynamic resizing capabilities, fast appending and popping,"
__copyright__ = __version__
# %% --------------------------------------------------------------------------
__all__ = [
"DynamicVector",
]
# Constants that determine when to switch from multiplicative to additive growth
_GROW_USE_ADD = 2**13 # Threshold capacity (8192), where growth switches to additive mode
_GROW_ADD = 2**11 # Capacity to add when additive mode is active (2048)
UNSUPPORTED_ATTRIBUTES = {
"fromfile",
"fromfunction",
"eye",
"r_",
"ogrid",
"mgrid",
"meshgrid",
"identity",
"atleast_1d",
"atleast_2d",
"atleast_3d",
"mat",
}
class DynamicVector:
"""
A dynamic vector implementation using NumPy arrays, with dynamic resizing capabilities.
The dynamic vector includes fast appending and popping, like a list,
while retaining numpy array index support and vector operations.
The dynamic vector support the python list methods and numpy.ndarray 1D array methods.
For access to all the numpy methods, a view of the vector as a numpy.ndarray can be returned.
The storage of the vector automatically grows in capacity by doubling it
until the capacity exceeds a certain threshold (`grow_use_add`),
after which it grows by a fixed amount (`grow_add`).
For example, given a dynamic vector that has an initial capacity of 8
and contains seven values (size=7). If another value is appended (size=8),
then the capacity is increased to 16 (from 2*8) to hold the extra value.
Args:
dtype (np.dtype, optional): numpy.dtype (data type) of the vector elements. Defaults to np.int32.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to 8.
grow_use_add (int, optional): Threshold to switch from multiplicative to additive growth. Defaults to 8192.
grow_add (int, optional): Additive increment in additive growth mode. Defaults to 2048.
Attributes:
size (int): The size of the dynamic vector.
view (np.ndarray): A np.ndarray view of the dynamic vector at its current size.
dtype (np.dtype): The numpy.dtype (data type) of the vector.
capacity (int): The capacity of the underlying vector storage (note, `size <= capacity`).
grow_use_add (int): Threshold that growth switches from multiplicative to additive growth.
grow_add (int): Additive increment in additive growth mode.
Constructors:
from_values(values): Create a DynamicVector from an iterable of values.
from_iter(iterator): Create a DynamicVector from an iterator.
Methods:
append(value):
Append a value to the end of the vector.
extend(values):
Append multiple values to the vector.
insert(index, value):
Insert a value at a specified index.
insert_values(index, values):
Insert multiple values at a specified index.
pop(index=-1):
Remove and return an element at a specified index (default is the last).
remove(value, remove_all=False, from_right=False):
Remove one or more occurrences of a value.
drop(index=-1):
Remove an element at a specified index.
count(value):
Count occurrences of a value.
sort(reverse=False, kind=None):
Sort the vector in ascending or descending order.
reverse():
Reverse the order of elements in the vector.
contains(value):
Check if a value exists in the vector.
copy(min_capacity=8):
Create a copy of the vector.
clear():
Remove all elements from the vector.
abs(where=True):
Compute the absolute value of all elements.
where(value):
Get the indices of elements equal to a value.
index(value, from_right=False):
Get the index of a value in the vector.
resize(size):
Resize the vector to a specified size.
increase_size(increase_by):
Increase the size of the vector by a specified amount.
set_capacity(min_capacity):
Ensure the vector's capacity is at least a given value.
force_capacity(min_capacity):
Set the capacity to the smallest power of two exceeding min_capacity.
is_equal(other):
Check if all elements are equal to those in another vector or value.
is_less(other):
Check if all elements are less than those in another vector or value.
is_greater(other):
Check if all elements are greater than those in another vector or value.
is_less_or_equal(other):
Check if all elements are less than or equal to those in another vector or value.
is_greater_or_equal(other):
Check if all elements are greater than or equal to those in another vector or value.
is_not_equal(other):
Check if all elements are not equal to those in another vector or value.
Example usage:
>>>
>>> from DynamicVector import DynamicVector
>>>
>>> vec = DynamicVector(dtype=np.int32, capacity=4)
>>>
>>> vec.append(10)
>>> vec.append(20)
>>>
>>> vec.extend([30, 40, 50])
>>>
>>> print(vec)
DynamicVector([10, 20, 30, 40, 50])
>>>
>>> print(vec[2]) # vec[2] returns np.int32(20)
30
>>> print(vec[1:4]) # vec[1:4] returns a np.ndarray view of vector
[20 30 40]
>>>
>>> vec.sort() # inplace sort
>>>
>>> print(f"Size: {vec.size}, Capacity: {vec.capacity}")
Size: 5, Capacity: 8
>>>
>>> vec.pop() # Remove the last element
>>>
>>> vec.clear() # Clear the vector (vec.size = 0)
Notes:
- The vector automatically resizes when needed, and it uses multiplicative growth until a specified threshold.
- After reaching the threshold, the growth becomes additive.
- A variable set to the view of the vector does not change size when the DynamicVector changes size.
- Size is always less than or equal to capacity.
"""
_size: int # The current number of elements in the vector.
_cap: int # The current capacity of the underlying np.ndarray.
_data: np.ndarray # The underlying NumPy array that stores the elements.
_dtype: np.dtype # The data type of the array elements.
def __init__(self, dtype=np.int32, capacity=8, *, grow_use_add=None, grow_add=None):
"""
Initialize the DynamicVector.
Parameters:
dtype (np.dtype, optional): numpy.dtype (data type) of the vector elements. Defaults to np.int32.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to 8.
grow_use_add (int, optional): Threshold to switch from multiplicative to additive growth. Defaults to 8192.
grow_add (int, optional): Additive increment in additive growth mode. Defaults to 2048.
"""
if grow_use_add is None:
self._grow_use_add = _GROW_USE_ADD
else:
self._grow_use_add = self._next_power_of_2(grow_use_add)
if grow_add is None:
self._grow_add = _GROW_ADD
else:
self._grow_add = self._next_power_of_2(grow_add)
if dtype is int:
dtype = np.int32
if dtype is float:
dtype = np.float64
self._size = 0
self._cap = 2
self._setup_capacity(capacity) # increase self._cap to meet capacity
self._data = np.zeros(self._cap, dtype=dtype)
self._dtype = self._data.dtype
# self._zero = self._data[0]
@classmethod
def from_values(cls, values, capacity=8, *, grow_use_add=None, grow_add=None):
"""
Create a DynamicVector from an existing vector.
Parameters:
values (sequence): The source array to initialize the vector.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to max(8, len(values)).
grow_use_add (int, optional): Custom threshold to switch from multiplicative to additive growth.
grow_add (int, optional): Custom value for additive growth.
Returns:
DynamicVector: A new dynamic vector initialized with the values from the input vector.
Examples:
DynamicVector.array([1,2,3]) -> DynamicVector([1,2,3])
"""
try:
if len(values) > capacity:
capacity = len(values)
except TypeError:
return cls.from_iter(values, grow_use_add, grow_add)
try:
dtype = values.dtype
except AttributeError:
try:
dtype = np.array(values[0]).dtype
except IndexError:
raise TypeError("Either pass variable with dtype attribute, or len(values) must be greater than zero.")
if isinstance(values, DynamicVector):
if grow_use_add is None:
grow_use_add = values.grow_use_add
if grow_add is None:
grow_add = values.grow_add
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn.extend(values)
return dyn
@classmethod
def from_iter(cls, iterator, capacity=8, *, grow_use_add=None, grow_add=None):
"""
Create a DynamicVector from an iterator.
Parameters:
iterator (iterator): The source iterator to initialize the vector.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to 8.
grow_use_add (int, optional): Custom threshold to switch from multiplicative to additive growth.
grow_add (int, optional): Custom value for additive growth.
Returns:
DynamicVector: A new dynamic vector initialized with the values from the input iterator.
Examples:
DynamicVector.array(iter([1,2,3])) -> DynamicVector([1,2,3])
"""
try:
value = next(iterator)
except TypeError:
iterator = iter(iterator)
value = next(iterator)
try:
dtype = value.dtype
except AttributeError:
dtype = np.array(value).dtype
if isinstance(iterator, DynamicVector):
if grow_use_add is None:
grow_use_add = iterator.grow_use_add
if grow_add is None:
grow_add = iterator.grow_add
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn.append(value)
for value in iterator:
dyn.append(value)
return dyn
@classmethod
def array(cls, object, dtype=None, capacity=8, grow_use_add=None, grow_add=None):
"""
Create a DynamicVector from the given object.
If dtype is given, then it overrides the dtype of the object.
DynamicVector.array(object, dtype=None, capacity=8, *, grow_use_add=None, grow_add=None)
Parameters:
object (array_like): Size and dtype of array used to build the DynamicVector.
dtype (type, optional): The type of the full in the vector. Defaults to `np.array(object).dtype`.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to max(8, len(object)).
Returns:
DynamicVector: A new dynamic vector initialized with the values from the input object.
Examples:
DynamicVector.array([1,2,3]) -> DynamicVector([1,2,3])
DynamicVector.array(3) -> DynamicVector([3])
"""
scalar_input = False
try:
size = len(object)
except TypeError:
try:
size = object.size
except (AttributeError, TypeError):
size = 1
scalar_input = True
if dtype is None:
try:
dtype = object.dtype
except AttributeError:
if scalar_input:
dtype = np.array(object).dtype
else:
dtype = np.array(object[0]).dtype
if capacity < size:
capacity = size
if isinstance(object, DynamicVector):
if grow_use_add is None:
grow_use_add = object.grow_use_add
if grow_add is None:
grow_add = object.grow_add
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn._size = size
dyn._data[:size] = object
return dyn
@classmethod
def zeros(cls, size, dtype=None, capacity=8, grow_use_add=None, grow_add=None):
"""
Create a DynamicVector with size elements set to zero.
If dtype is not given, then it is set to `np.int32`.
DynamicVector.zeros(size, dtype=np.int32, capacity=8, *, grow_use_add=None, grow_add=None)
Parameters:
size (int): The number of zeros in the vector (size of DynamicVector).
dtype (type, optional): The type of the zeros in the vector. Defaults to `np.int32`.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to max(8, size).
Returns:
DynamicVector of zeros with the given size, dtype, and capacity.
Examples:
DynamicVector.zeros(5) -> DynamicVector([0, 0, 0, 0, 0])
"""
if dtype is None:
dtype = np.int32
if capacity < size:
capacity = size
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn._size = size
return dyn
@classmethod
def empty(cls, size, dtype=None, capacity=8, grow_use_add=None, grow_add=None):
"""
Create a DynamicVector with size elements set to zero.
If dtype is not given, then it is set to `np.int32`.
DynamicVector.empty(size, dtype=np.int32, capacity=8, *, grow_use_add=None, grow_add=None)
Parameters:
size (int): The number of empty in the vector (size of DynamicVector).
dtype (type, optional): The type of the empty in the vector. Defaults to `np.int32`.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to max(8, size).
Returns:
DynamicVector of empty with the given size, dtype, and capacity.
Examples:
DynamicVector.empty(5) -> DynamicVector([0, 0, 0, 0, 0])
"""
return cls.zeros(size, dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
@classmethod
def zeros_like(cls, prototype, capacity=8, grow_use_add=None, grow_add=None):
"""
Create a DynamicVector of zeros with the same size and type as prototype.
DynamicVector.zeros_like(prototype, capacity=8, *, grow_use_add=None, grow_add=None)
Parameters:
prototype (array_like): Size and dtype of array used to build the DynamicVector.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to max(8, prototype.size).
Returns:
DynamicVector of zeros of same size and type as prototype.
Examples:
DynamicVector.zeros_like(np.array([1,2,3])) -> DynamicVector([0, 0, 0])
"""
try:
size = len(prototype)
except TypeError:
try:
size = prototype.size
except (AttributeError, TypeError):
raise TypeError("Unable to determine prototype size.")
try:
dtype = prototype.dtype
except AttributeError:
try:
dtype = type(prototype[0])
except IndexError:
raise TypeError("Unable to determine prototype dtype.")
if capacity < size:
capacity = size
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn._size = size
return dyn
@classmethod
def empty_like(cls, prototype, capacity=8, grow_use_add=None, grow_add=None):
"""
Create a DynamicVector of zeros with the same size and type as prototype.
DynamicVector.empty_like(prototype, capacity=8, *, grow_use_add=None, grow_add=None)
Parameters:
prototype (array_like): Size and dtype of array used to build the DynamicVector.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to max(8, prototype.size).
Returns:
DynamicVector of zeros of same size and type as prototype.
Examples:
DynamicVector.empty_like(np.array([1,2,3])) -> DynamicVector([0, 0, 0])
"""
return cls.zeros_like(prototype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
@classmethod
def ones(cls, size, dtype=None, capacity=8, grow_use_add=None, grow_add=None):
"""
Create a DynamicVector with size elements set to one.
If dtype is not given, then it is set to `np.int32`.
DynamicVector.ones(size, dtype=np.int32, capacity=8, *, grow_use_add=None, grow_add=None)
Parameters:
size (int): The number of ones in the vector (size of DynamicVector).
dtype (type, optional): The type of the ones in the vector. Defaults to `np.int32`.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to max(8, size).
Returns:
DynamicVector of zeros with the given size, dtype, and capacity.
Examples:
DynamicVector.zeros(5) -> DynamicVector([0, 0, 0, 0, 0])
"""
if dtype is None:
dtype = np.int32
if capacity < size:
capacity = size
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn._size = size
dyn._data[:size] = 1
return dyn
@classmethod
def ones_like(cls, prototype, capacity=8, grow_use_add=None, grow_add=None):
"""
Create a DynamicVector of ones with the same size and type as prototype.
DynamicVector.ones_like(prototype, capacity=8, *, grow_use_add=None, grow_add=None)
Parameters:
prototype (array_like): Size and dtype of array used to build the DynamicVector.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to max(8, prototype.size).
Returns:
DynamicVector of ones of same size and type as prototype.
Examples:
DynamicVector.ones_like(np.array([1,2,3])) -> DynamicVector([0, 0, 0])
"""
try:
size = len(prototype)
except TypeError:
try:
size = prototype.size
except (AttributeError, TypeError):
raise TypeError("Unable to determine prototype size.")
try:
dtype = prototype.dtype
except AttributeError:
try:
dtype = type(prototype[0])
except IndexError:
raise TypeError("Unable to determine prototype dtype.")
if capacity < size:
capacity = size
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn._size = size
dyn._data[:size] = 1
return dyn
@classmethod
def full(cls, size, fill_value, dtype=None, capacity=8, grow_use_add=None, grow_add=None):
"""
Create a DynamicVector composed of `size` values set to `fill_value`.
If `dtype` is not given, then it is set to `np.array(fill_value).dtype`.
DynamicVector.full(size, fill_value, dtype=np.dtype, capacity=8, *, grow_use_add=None, grow_add=None)
Parameters:
size (int): The number of full in the vector (size of DynamicVector).
fill_value (int): The value to fill the DynamicVector with.
dtype (type, optional): The type of the full in the vector. Defaults to `np.array(fill_value).dtype`.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to max(8, size).
Returns:
DynamicVector with given size, filled with fill_value.
Examples:
DynamicVector.full(5, 3) -> DynamicVector([3, 3, 3, 3, 3])
"""
if dtype is None:
dtype = np.array(fill_value).dtype
if capacity < size:
capacity = size
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn._size = size
dyn._data[:size] = fill_value
return dyn
@classmethod
def arange(
cls, *args, start=None, stop=None, step=None, dtype=None, capacity=None, grow_use_add=None, grow_add=None
):
"""
Create a DynamicVector from evenly spaced values within a given interval
and specified data type (dtype). If dtype is not given, then it is set to `np.int32`.
DynamicVector.arange(start=1, stop, step=1, dtype=np.int32, capacity=8, *, grow_use_add=None, grow_add=None)
`arange` can be called with a varying number of positional arguments:
- `arange(stop)`: Values are generated within the half-open interval [0, stop)
(in other words, the interval including start but excluding stop).
- `arange(start, stop)`: Values are generated within the half-open interval [start, stop).
- `arange(start, stop, step)`: Values are generated within the half-open interval [start, stop),
with spacing between values given by step.
- `arange(start, stop, step, dtype)`: Values are generated within the half-open interval [start, stop),
with spacing between values given by step and has data type, dtype.
`arange` can also use keyword argument `start`, `stop`, `step` and `dtype`.
However, if a positional argument of the same name is used, as described above,
then only the keywords that are not one of the position arguments names can be used.
Such as:
- `arange(stop)`: Cannot use the keyword `stop`.
- `arange(start, stop)`: Cannot use the keywords `start`, `stop`.
- `arange(start, stop, step)`: Cannot use the keywords `start`, `stop`, `step`,.
- `arange(start, stop, step, dtype)`: Cannot use the keywords `start`, `stop`, `step`, `dtype`.
For integer arguments the function is roughly equivalent to the Python built-in range,
but returns an DynamicVector rather than a range instance.
When using a non-integer step, such as 0.1, it is often better to use `DynamicVector.linspace`.
Parameters:
start (int or float, optional): The starting value of the sequence, defaults to 0.
stop (int or float): The end value of the sequence.
step (int or float, optional): The increment (step size). Defaults to 1.
dtype (type, optional): The type of the output values. Defaults to `np.int32`.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to 8.
Returns:
DynamicVector of evenly spaced dtype values from given start, stop, and step.
Examples:
DynamicVector.arange(5) -> DynamicVector([0, 1, 2, 3, 4])
DynamicVector.arange(2, 5) -> DynamicVector([2, 3, 4])
DynamicVector.arange(2, 10, step=2) -> DynamicVector([2, 4, 6, 8])
DynamicVector.arange(0, 5, step=0.5) -> DynamicVector([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5])
"""
if len(args) > 5:
raise TypeError(f"arange() takes from 0 to 5 positional arguments but {len(args)} were given")
args[::-1]
if len(args) == 1:
if stop is None:
stop = args.pop()
if start is None:
start = 0
elif start is None:
start = args.pop()
elif len(args) > 1:
if start is None:
start = args.pop()
if stop is None and len(args) > 0:
stop = args.pop()
if stop is None:
raise TypeError("DynamicVector.arange() must specify `stop`.")
if step is None and len(args) > 0:
step = args.pop()
elif step is None:
step = 1
if dtype is None and len(args) > 0:
dtype = args.pop()
elif dtype is None:
dtype = np.int32
if capacity is None and len(args) > 0:
capacity = args.pop()
elif capacity is None:
capacity = 8
if len(args) > 0:
raise TypeError(
"DynamicVector.arange() incorrect arguments passed.\n"
"`start`, `stop`, `step`, `dtype`, `capacity` can be a positional argument or keyword argument, but not both.\n"
)
tmp = np.arange(start, stop, step, dtype)
dim = tmp.size
capacity = max(dim, capacity)
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn._size = dim
dyn._data[:dim] = tmp
return dyn
@classmethod
def linspace(
cls,
start,
stop,
num=50,
endpoint=True,
retstep=False,
dtype=None,
capacity=8,
*,
grow_use_add=None,
grow_add=None,
):
"""
Create a DynamicVector evenly spaced numbers over a specified interval.
and specified data type (dtype). If dtype is not given, the data type is inferred from start and stop.
DynamicVector.arange(start, stop, num=50, endpoint=True, retstep=False, dtype=inferred, capacity=8, *, grow_use_add=None, grow_add=None)
Parameters:
start (int or float): The starting value of the sequence.
stop (int or float): The end value of the sequence, unless endpoint is set to False.
num (int, optional): Number of samples to generate. Default is 50. Must be non-negative.
retstep (bool, optional): If True, stop is the last sample. Otherwise, it is not included. Default is True.
dtype (type, optional): The type of the output array. If dtype is not given, the data type is inferred from start and stop.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to 8.
Returns:
DynamicVector of num equally spaced samples in the closed interval [start, stop]
or the half-open interval [start, stop) (depending on whether endpoint is True or False).
May also return size of spacing between samples, if retstep is True.
"""
tmp = np.linspace(start, stop, num, endpoint, retstep, dtype)
if retstep:
tmp, step = tmp
dim = tmp.size
if capacity < dim:
capacity = dim
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn._size = dim
dyn._data[:dim] = tmp
if retstep:
return dyn, step
else:
return dyn
@classmethod
def geomspace(
cls,
start,
stop,
num=50,
endpoint=True,
dtype=None,
capacity=8,
*,
grow_use_add=None,
grow_add=None,
):
"""
Create a DynamicVector numbers spaced evenly on a log scale (a geometric progression).
If dtype is not given, the data type is inferred from start and stop.
DynamicVector.arange(start, stop, num=50, endpoint=True, dtype=inferred, capacity=8, *, grow_use_add=None, grow_add=None)
Parameters:
start (int or float): The starting value of the sequence.
stop (int or float): The end value of the sequence, unless endpoint is set to False.
num (int, optional): Number of samples to generate. Default is 50. Must be non-negative.
dtype (type, optional): The type of the output array. If dtype is not given, the data type is inferred from start and stop.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to 8.
Returns:
DynamicVector of num samples, equally spaced on a log scale.
"""
tmp = np.geomspace(start, stop, num, endpoint, dtype)
dim = tmp.size
if capacity < dim:
capacity = dim
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn._size = dim
dyn._data[:dim] = tmp
return dyn
@classmethod
def logspace(
cls,
start,
stop,
num=50,
endpoint=True,
base=10.0,
dtype=None,
capacity=8,
*,
grow_use_add=None,
grow_add=None,
):
"""
Create a DynamicVector numbers spaced evenly on a log scale.
If dtype is not given, the data type is inferred from start and stop.
DynamicVector.arange(start, stop, num=50, endpoint=True, base=10.0, dtype=inferred, capacity=8, *, grow_use_add=None, grow_add=None)
Parameters:
start (int or float): The starting value of the sequence.
stop (int or float): The end value of the sequence, unless endpoint is set to False.
num (int, optional): Number of samples to generate. Default is 50. Must be non-negative.
base (float, optional): The base of the log space. The step size between the elements in
ln(samples) / ln(base) (or log_base(samples)) is uniform. Default is 10.0.
dtype (type, optional): The type of the output array. If dtype is not given, the data type is inferred from start and stop.
capacity (int, optional): Initial minimum capacity of the underlying storage vector. Defaults to 8.
Returns:
DynamicVector of num samples, equally spaced on a log scale.
"""
tmp = np.logspace(start, stop, num, endpoint, base, dtype)
dim = tmp.size
if capacity < dim:
capacity = dim
dyn = cls(dtype, capacity, grow_use_add=grow_use_add, grow_add=grow_add)
dyn._size = dim
dyn._data[:dim] = tmp
return dyn
@property
def size(self) -> int:
"""Returns the current size of the vector."""
return self._size
@property
def capacity(self) -> int:
"""Returns the current capacity of the vector."""
return self._cap
@property
def view(self) -> np.ndarray:
"""Returns a numpy array view of the vector at its current size.
This view can use all the numpy built in methods.
Any changes to the values in the DynamicVector are reflected in the view,
and vice-versa.
The view does NOT change if the DynamicVector size changes.
If the size does change, then you must remake the view.
It is recommended to not set view to another variable,
but instead use `self.view` it as needed."""
return self._data[: self._size]
# @view.setter
# def view(self, value):
# self._data[: self._size] = value
@property
def dtype(self) -> np.dtype:
"""Returns the numpy.dtype (data type) of the vector."""
return self._dtype
@property
def grow_use_add(self) -> int:
"""Returns the threshold capacity where growth switches to additive."""
return self._grow_use_add
@property
def grow_add(self) -> int:
"""Returns the capacity increment used in additive growth mode."""
return self._grow_add
def append(self, value):
"""
Append a value to the end of the vector, increasing the vector's size by one.
Parameters:
value: The value to be appended.
Notes:
1) Appending an item has a minimal performance penalty if size < capacity.
If size == capacity, then the vector is reallocated to increase capacity.
"""
if self._size >= self._cap:
self._grow_data(self._size + 1)
self._data[self._size] = value
self._size += 1
def extend(self, values):
"""
Extend the vector by appending multiple values.
The size of the vector increases to reflect the addition of the values.
Parameters:
values (iterable): The values to append to the vector.
Notes:
1) Extending an item has a minimal performance penalty if size + len(values) < capacity.
If size + len(values) >= capacity, then the vector is reallocated to increase capacity.
"""
try:
new_size = self._size + len(values)
except TypeError: # iterator so need to manually add values
for value in values:
self.append(value)
return
if new_size > self._cap:
self._grow_data(new_size)
self._data[self._size : new_size] = values
self._size = new_size
def insert(self, index, value):
"""Insert an item at a given position.
The first argument is the index of the element before which to insert, so a.insert(0, x)
inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Index may be a single value or list-like array that represent all the index locations to place value"""
if isinstance(index, (int, np.integer, np.unsignedinteger)):
if index == self._size:
self.append(value)
return
index = [self._format_int_index(index)]
elif isinstance(index, slice):
index = self._slice_to_range(index)
else:
index = sorted(index, reverse=True) # assume its listlike input
if self._size + len(index) > self._cap:
self._grow_data(self._size + len(index))
for p in index:
self._size += 1
self._data[p + 1 : self._size] = self._data[p : self._size - 1]
self._data[p] = value
def insert_values(self, index, values):
"""Insert a set of values at a given position.
The first argument is the index of the element before which to insert, so a.insert(0, x)
inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
values may be any listlike array that supports len()."""
if len(values) == 1:
self.insert(index, values[0])
return
if index == self._size:
self.extend(values)
return
index = self._format_int_index(index)
new_size = self._size + len(values)
if new_size > self._cap:
self._grow_data(new_size)
self._data[index + len(values) : new_size] = self._data[index : self._size]
self._data[index : index + len(values)] = values
self._size = new_size
def remove(self, value, remove_all=False, from_right=False) -> bool:
"""
Remove the first or all occurrences of a value from the vector.
Parameters:
value: The value to be removed.
remove_all (bool): If True, remove all occurrences of value. Default is False.
from_right (bool): If True, remove the rightmost occurrence. Default is False.
Returns:
bool: True if at least one occurrence was removed, False otherwise.
"""
if self._size < 1:
return False
index = self.where(value)
if len(index) < 1:
return False # no values found
if remove_all: