-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathvector.py
More file actions
1789 lines (1638 loc) · 59 KB
/
Copy pathvector.py
File metadata and controls
1789 lines (1638 loc) · 59 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 itertools
import numpy as np
from suitesparse_graphblas.utils import claim_buffer, unclaim_buffer
import graphblas as gb
from ... import binary, monoid
from ...dtypes import _INDEX, INT64, UINT64, lookup_dtype
from ...exceptions import _error_code_lookup, check_status, check_status_carg
from .. import NULL, ffi, lib
from ..base import call
from ..operator import get_typed_op
from ..scalar import Scalar, _as_scalar
from ..utils import (
_CArray,
_MatrixArray,
ints_to_numpy_buffer,
normalize_chunks,
values_to_numpy_buffer,
wrapdoc,
)
from ._utils import _resolve_serialized_dtype
from .config import BaseConfig
from .descriptor import get_descriptor
from .matrix import _concat_mn, njit
from .prefix_scan import prefix_scan
ffi_new = ffi.new
def head(vector, n=10, dtype=None, *, sort=False):
"""Like ``vector.to_coo()``, but only returns the first n elements.
If sort is True, then the results will be sorted by index, otherwise the order of the
result is not guaranteed. Formats full and bitmap should always return in sorted order.
"""
if vector._nvals <= n:
return vector.to_coo(dtype, sort=sort)
if sort:
vector.wait()
if dtype is None:
dtype = vector.dtype
else:
dtype = lookup_dtype(dtype)
indices, vals = zip(*itertools.islice(vector.ss.iteritems(), n), strict=True)
return np.array(indices, np.uint64), np.array(vals, dtype.np_type)
class VectorConfig(BaseConfig):
"""Get and set configuration options for this Vector.
See SuiteSparse:GraphBLAS documentation for more details.
Config parameters
-----------------
bitmap_switch : double
Threshold that determines when to switch to bitmap format
sparsity_control : Set[str] from {"sparse", "bitmap", "full", "auto"}
Allowed sparsity formats. May be set with a single string or a set of strings.
sparsity_status : str, {"sparse", "bitmap", "full"}
Current sparsity format
"""
_get_function = "GxB_Vector_Option_get"
_set_function = "GxB_Vector_Option_set"
_options = {
"bitmap_switch": (lib.GxB_BITMAP_SWITCH, "double"),
"sparsity_control": (lib.GxB_SPARSITY_CONTROL, "int"),
# read-only
"sparsity_status": (lib.GxB_SPARSITY_STATUS, "int"),
# "format": (lib.GxB_FORMAT, "GxB_Format_Value"), # Not useful to show
}
_bitwise = {
"sparsity_control": {
# "hypersparse": lib.GxB_HYPERSPARSE, # For matrices, not vectors
"sparse": lib.GxB_SPARSE,
"bitmap": lib.GxB_BITMAP,
"full": lib.GxB_FULL,
"auto": lib.GxB_AUTO_SPARSITY,
},
}
_enumerations = {
"format": {
"by_row": lib.GxB_BY_ROW,
"by_col": lib.GxB_BY_COL,
# "no_format": lib.GxB_NO_FORMAT, # Used by iterators; not valid here
},
"sparsity_status": {
"hypersparse": lib.GxB_HYPERSPARSE,
"sparse": lib.GxB_SPARSE,
"bitmap": lib.GxB_BITMAP,
"full": lib.GxB_FULL,
},
}
_defaults = {
"sparsity_control": "auto",
}
_read_only = {"sparsity_status", "format"}
class ss:
__slots__ = "_parent", "config"
def __init__(self, parent):
self._parent = parent
self.config = VectorConfig(parent)
@property
def nbytes(self):
size = ffi_new("size_t*")
check_status(lib.GxB_Vector_memoryUsage(size, self._parent._carg), self._parent)
return size[0]
@property
def is_iso(self):
is_iso = ffi_new("bool*")
check_status(lib.GxB_Vector_iso(is_iso, self._parent._carg), self._parent)
return is_iso[0]
@property
def iso_value(self):
if self.is_iso:
# This may not be thread-safe if the parent is being modified in another thread
return Scalar.from_value(next(self.itervalues()), dtype=self._parent.dtype, name="")
raise ValueError("Vector is not iso-valued")
@property
def format(self):
parent = self._parent
sparsity_ptr = ffi_new("int32_t*")
check_status(
lib.GxB_Vector_Option_get_INT32(parent._carg, lib.GxB_SPARSITY_STATUS, sparsity_ptr),
parent,
)
sparsity_status = sparsity_ptr[0]
if sparsity_status == lib.GxB_SPARSE:
format = "sparse"
elif sparsity_status == lib.GxB_BITMAP:
format = "bitmap"
elif sparsity_status == lib.GxB_FULL:
format = "full"
else: # pragma: no cover (sanity)
raise NotImplementedError(f"Unknown sparsity status: {sparsity_status}")
return format
def build_diag(self, matrix, k=0, **opts):
"""GxB_Vector_diag.
Extract a diagonal from a Matrix or TransposedMatrix into a Vector.
Existing entries in the Vector are discarded.
Parameters
----------
matrix : Matrix or TransposedMatrix
Extract a diagonal from this matrix.
k : int, default 0
Diagonal in question. Use ``k>0`` for diagonals above the main diagonal,
and ``k<0`` for diagonals below the main diagonal.
See Also
--------
Matrix.diag
Vector.diag
"""
from ..matrix import Matrix, TransposedMatrix
matrix = self._parent._expect_type(
matrix,
(Matrix, TransposedMatrix),
within="ss.build_diag",
argname="matrix",
)
if type(matrix) is TransposedMatrix:
# Transpose descriptor doesn't do anything, so use the parent
k = -k
matrix = matrix._matrix
call(
"GxB_Vector_diag",
[self._parent, matrix, _as_scalar(k, INT64, is_cscalar=True), get_descriptor(**opts)],
)
def split(self, chunks, *, name=None, **opts):
"""GxB_Matrix_split.
Split a Vector into a 1D array of sub-vectors according to ``chunks``.
This performs the opposite operation as ``concat``.
``chunks`` is short for "chunksizes" and indicates the chunk sizes.
``chunks`` may be a single integer, or a tuple or list. Example chunks:
- ``chunks=10``
- Split vector into chunks of size 10 (the last chunk may be smaller).
- ``chunks=[5, 10]``
- Split vector into two chunks of size 5 and 10.
See Also
--------
Vector.ss.concat
graphblas.ss.concat
"""
from ..vector import Vector
tile_nrows, _ = normalize_chunks([chunks, None], (self._parent._size, 1))
m = len(tile_nrows)
tiles = ffi_new("GrB_Matrix[]", m)
parent = self._parent._as_matrix()
call(
"GxB_Matrix_split",
[
_MatrixArray(tiles, parent, name="tiles"),
_as_scalar(m, _INDEX, is_cscalar=True),
_as_scalar(1, _INDEX, is_cscalar=True),
_CArray(tile_nrows),
_CArray([1]),
parent,
get_descriptor(**opts),
],
)
rv = []
dtype = self._parent.dtype
if name is None:
name = self._parent.name
for i, size in enumerate(tile_nrows):
# Copy to a new handle so we can free `tiles`
new_vector = ffi_new("GrB_Vector*")
new_vector[0] = ffi.cast("GrB_Vector", tiles[i])
tile = Vector._from_obj(new_vector, dtype, size, name=f"{name}_{i}")
rv.append(tile)
return rv
def _concat(self, tiles, m, opts):
ctiles = ffi_new("GrB_Matrix[]", m)
for i, tile in enumerate(tiles):
ctiles[i] = tile.gb_obj[0]
call(
"GxB_Matrix_concat",
[
self._parent._as_matrix(),
_MatrixArray(ctiles, name="tiles"),
_as_scalar(m, _INDEX, is_cscalar=True),
_as_scalar(1, _INDEX, is_cscalar=True),
get_descriptor(**opts),
],
)
def concat(self, tiles, **opts):
"""GxB_Matrix_concat.
Concatenate a 1D list of Vector objects into the current Vector.
Any existing values in the current Vector will be discarded.
To concatenate into a new Vector, use ``graphblas.ss.concat``.
This performs the opposite operation as ``split``.
See Also
--------
Vector.ss.split
graphblas.ss.concat
"""
tiles, m, _n, _is_matrix = _concat_mn(tiles, is_matrix=False)
self._concat(tiles, m, opts)
def build_scalar(self, indices, value):
"""GxB_Vector_build_Scalar.
Like ``build``, but uses a scalar for all the values.
See Also
--------
Vector.build
Vector.from_coo
"""
indices = ints_to_numpy_buffer(indices, np.uint64, name="indices")
scalar = _as_scalar(value, self._parent.dtype, is_cscalar=False) # pragma: is_grbscalar
call(
"GxB_Vector_build_Scalar",
[
self._parent,
_CArray(indices),
scalar,
_as_scalar(indices.size, _INDEX, is_cscalar=True),
],
)
def _begin_iter(self, seek):
it_ptr = ffi_new("GxB_Iterator*")
info = lib.GxB_Iterator_new(it_ptr)
it = it_ptr[0]
success = lib.GrB_SUCCESS
info = lib.GxB_Vector_Iterator_attach(it, self._parent._carg, NULL)
if info != success: # pragma: no cover (safety)
lib.GxB_Iterator_free(it_ptr)
raise _error_code_lookup[info]("Vector iterator failed to attach")
if seek < 0:
seek = max(0, seek + lib.GxB_Vector_Iterator_getpmax(it))
info = lib.GxB_Vector_Iterator_seek(it, seek)
if info != success:
lib.GxB_Iterator_free(it_ptr)
raise _error_code_lookup[info]("Vector iterator failed to seek")
return it_ptr
def iterkeys(self, seek=0):
"""Iterate over all the indices of a Vector.
Parameters
----------
seek : int, default 0
Index of entry to seek to. May be negative to seek backwards from the end.
Vector objects in bitmap format seek as if it's full format (i.e., it
ignores the bitmap mask).
The Vector should not be modified during iteration; doing so will
result in undefined behavior.
"""
try:
it_ptr = self._begin_iter(seek)
except StopIteration:
return
it = it_ptr[0]
info = success = lib.GrB_SUCCESS
key_func = lib.GxB_Vector_Iterator_getIndex
next_func = lib.GxB_Vector_Iterator_next
try:
while info == success:
yield key_func(it)
info = next_func(it)
except GeneratorExit:
pass
else:
if info != lib.GxB_EXHAUSTED: # pragma: no cover (safety)
raise _error_code_lookup[info]("Vector iterator failed")
finally:
lib.GxB_Iterator_free(it_ptr)
def itervalues(self, seek=0):
"""Iterate over all the values of a Vector.
Parameters
----------
seek : int, default 0
Index of entry to seek to. May be negative to seek backwards from the end.
Vector objects in bitmap format seek as if it's full format (i.e., it
ignores the bitmap mask).
The Vector should not be modified during iteration; doing so will
result in undefined behavior.
"""
try:
it_ptr = self._begin_iter(seek)
except StopIteration:
return
it = it_ptr[0]
info = success = lib.GrB_SUCCESS
val_func = getattr(lib, f"GxB_Iterator_get_{self._parent.dtype.name}")
next_func = lib.GxB_Vector_Iterator_next
try:
while info == success:
yield val_func(it)
info = next_func(it)
except GeneratorExit:
pass
else:
if info != lib.GxB_EXHAUSTED: # pragma: no cover (safety)
raise _error_code_lookup[info]("Vector iterator failed")
finally:
lib.GxB_Iterator_free(it_ptr)
def iteritems(self, seek=0):
"""Iterate over all the indices and values of a Vector.
Parameters
----------
seek : int, default 0
Index of entry to seek to. May be negative to seek backwards from the end.
Vector objects in bitmap format seek as if it's full format (i.e., it
ignores the bitmap mask).
The Vector should not be modified during iteration; doing so will
result in undefined behavior.
"""
try:
it_ptr = self._begin_iter(seek)
except StopIteration:
return
it = it_ptr[0]
info = success = lib.GrB_SUCCESS
key_func = lib.GxB_Vector_Iterator_getIndex
val_func = getattr(lib, f"GxB_Iterator_get_{self._parent.dtype.name}")
next_func = lib.GxB_Vector_Iterator_next
try:
while info == success:
yield (key_func(it), val_func(it))
info = next_func(it)
except GeneratorExit:
pass
else:
if info != lib.GxB_EXHAUSTED: # pragma: no cover (safety)
raise _error_code_lookup[info]("Vector iterator failed")
finally:
lib.GxB_Iterator_free(it_ptr)
def export(self, format=None, *, sort=False, give_ownership=False, raw=False, **opts):
"""GxB_Vextor_export_xxx.
Parameters
----------
format : str or None, default None
If ``format`` is not specified, this method exports in the currently stored format.
To control the export format, set ``format`` to one of:
- "sparse"
- "bitmap"
- "full"
sort : bool, default False
Whether to sort indices if the format is "sparse"
give_ownership : bool, default False
Perform a zero-copy data transfer to Python if possible. This gives ownership of
the underlying memory buffers to NumPy.
** If True, this nullifies the current object, which should no longer be used! **
raw : bool, default False
If True, always return array the same size as returned by SuiteSparse.
If False, arrays may be trimmed to be the expected size.
It may make sense to choose ``raw=True`` if one wants to use the data to perform
a zero-copy import back to SuiteSparse.
Returns
-------
dict; keys depend on ``format`` and ``raw`` arguments (see below).
See Also
--------
Vector.to_coo
Vector.ss.import_any
Return values
- Note: for ``raw=True``, arrays may be larger than specified.
- "sparse" format
- indices : ndarray(dtype=uint64, size=nvals)
- values : ndarray(size=nvals)
- sorted_index : bool
- True if the values in "indices" are sorted
- size : int
- nvals : int, only present if raw == True
- "bitmap" format
- bitmap : ndarray(dtype=bool, size=size)
- values : ndarray(size=size)
- Elements where bitmap is False are undefined
- nvals : int
- The number of True elements in the bitmap
- size : int, only present if raw == True
- "full" format
- values : ndarray(size=size)
- size : int, only present if raw == True or is_iso == True
Examples
--------
Simple usage:
>>> pieces = v.ss.export()
>>> v2 = Vector.ss.import_any(**pieces)
"""
return self._export(
format=format,
sort=sort,
give_ownership=give_ownership,
raw=raw,
method="export",
opts=opts,
)
def unpack(self, format=None, *, sort=False, raw=False, **opts):
"""GxB_Vector_unpack_xxx.
``unpack`` is like ``export``, except that the Vector remains valid but empty.
``pack_*`` methods are the opposite of ``unpack``.
See ``Vector.ss.export`` documentation for more details.
"""
return self._export(
format=format, sort=sort, give_ownership=True, raw=raw, method="unpack", opts=opts
)
def _export(self, format=None, *, sort=False, give_ownership=False, raw=False, method, opts):
if give_ownership:
parent = self._parent
else:
parent = self._parent.dup(name=f"v_{method}")
dtype = parent.dtype.np_type
index_dtype = np.dtype(np.uint64)
if format is None:
format = self.format
else:
format = format.lower()
size = parent._size
if method == "export":
vhandle = ffi_new("GrB_Vector*", parent._carg)
type_ = ffi_new("GrB_Type*")
size_ = ffi_new("GrB_Index*")
args = (type_, size_)
else:
vhandle = parent._carg
args = ()
vx = ffi_new("void**")
vx_size = ffi_new("GrB_Index*")
if sort:
jumbled = NULL
else:
jumbled = ffi_new("bool*")
is_iso = ffi_new("bool*")
desc = get_descriptor(**opts)
desc_obj = NULL if desc is None else desc._carg
if format == "sparse":
vi = ffi_new("GrB_Index**")
vi_size = ffi_new("GrB_Index*")
nvals = ffi_new("GrB_Index*")
check_status(
getattr(lib, f"GxB_Vector_{method}_CSC")(
vhandle,
*args,
vi,
vx,
vi_size,
vx_size,
is_iso,
nvals,
jumbled,
desc_obj,
),
parent,
)
is_iso = is_iso[0]
nvals = nvals[0]
indices = claim_buffer(ffi, vi[0], vi_size[0] // index_dtype.itemsize, index_dtype)
values = claim_buffer(ffi, vx[0], vx_size[0] // dtype.itemsize, dtype)
if not raw:
if indices.size > nvals:
indices = indices[:nvals]
if is_iso:
if values.size > 1: # pragma: no cover (suitesparse)
values = values[:1]
elif values.size > nvals:
values = values[:nvals]
rv = {
"size": size,
"indices": indices,
"sorted_index": True if sort else not jumbled[0],
}
if raw:
rv["nvals"] = nvals
elif format == "bitmap":
vb = ffi_new("int8_t**")
vb_size = ffi_new("GrB_Index*")
nvals = ffi_new("GrB_Index*")
check_status(
getattr(lib, f"GxB_Vector_{method}_Bitmap")(
vhandle,
*args,
vb,
vx,
vb_size,
vx_size,
is_iso,
nvals,
desc_obj,
),
parent,
)
is_iso = is_iso[0]
bool_dtype = np.dtype(np.bool_)
bitmap = claim_buffer(ffi, vb[0], vb_size[0] // bool_dtype.itemsize, bool_dtype)
values = claim_buffer(ffi, vx[0], vx_size[0] // dtype.itemsize, dtype)
if not raw:
if bitmap.size > size: # pragma: no branch (suitesparse)
bitmap = bitmap[:size]
if is_iso:
if values.size > 1: # pragma: no cover (suitesparse)
values = values[:1]
elif values.size > size: # pragma: no cover (suitesparse)
values = values[:size]
rv = {
"bitmap": bitmap,
"nvals": nvals[0],
}
if raw:
rv["size"] = size
elif format == "full":
check_status(
getattr(lib, f"GxB_Vector_{method}_Full")(
vhandle,
*args,
vx,
vx_size,
is_iso,
desc_obj,
),
parent,
)
is_iso = is_iso[0]
values = claim_buffer(ffi, vx[0], vx_size[0] // dtype.itemsize, dtype)
if not raw:
if is_iso:
if values.size > 1:
values = values[:1]
elif values.size > size: # pragma: no branch (suitesparse)
values = values[:size]
rv = {}
if raw or is_iso:
rv["size"] = size
else:
raise ValueError(f"Invalid format: {format}")
rv["is_iso"] = is_iso
rv.update(
format=format,
values=values,
)
if method == "export":
parent.gb_obj[0] = NULL
if parent.dtype._is_udt:
rv["dtype"] = parent.dtype
return rv
@classmethod
def import_any(
cls,
*,
# All
values,
size=None,
is_iso=False,
take_ownership=False,
secure_import=False,
format=None,
dtype=None,
name=None,
# Sparse
indices=None,
sorted_index=False,
# Bitmap
bitmap=None,
# Bitmap/Sparse
nvals=None, # optional
**opts,
):
"""GxB_Vector_import_xxx.
Dispatch to appropriate import method inferred from inputs.
See the other import functions and ``Vector.ss.export`` for details.
Returns
-------
Vector
See Also
--------
Vector.from_coo
Vector.ss.export
Vector.ss.import_sparse
Vector.ss.import_bitmap
Vector.ss.import_full
Examples
--------
Simple usage:
>>> pieces = v.ss.export()
>>> v2 = Vector.ss.import_any(**pieces)
"""
return cls._import_any(
values=values,
size=size,
is_iso=is_iso,
take_ownership=take_ownership,
secure_import=secure_import,
format=format,
dtype=dtype,
name=name,
# Sparse
indices=indices,
sorted_index=sorted_index,
# Bitmap
bitmap=bitmap,
# Bitmap/Sparse
nvals=nvals,
method="import",
opts=opts,
)
def pack_any(
self,
*,
# All
values,
is_iso=False,
take_ownership=False,
secure_import=False,
format=None,
# Sparse
indices=None,
sorted_index=False,
# Bitmap
bitmap=None,
# Bitmap/Sparse
nvals=None, # optional
# Unused for pack, ignored
size=None,
dtype=None,
name=None,
**opts,
):
"""GxB_Vector_pack_xxx.
``pack_any`` is like ``import_any`` except it "packs" data into an
existing Vector. This is the opposite of ``unpack()``
See ``Vector.ss.import_any`` documentation for more details.
"""
return self._import_any(
values=values,
is_iso=is_iso,
take_ownership=take_ownership,
secure_import=secure_import,
format=format,
# Sparse
indices=indices,
sorted_index=sorted_index,
# Bitmap
bitmap=bitmap,
# Bitmap/Sparse
nvals=nvals,
method="pack",
vector=self._parent,
opts=opts,
)
@classmethod
def _import_any(
cls,
*,
# All
values,
size=None,
is_iso=False,
take_ownership=False,
secure_import=False,
format=None,
dtype=None,
name=None,
# Sparse
indices=None,
sorted_index=False,
# Bitmap
bitmap=None,
# Bitmap/Sparse
nvals=None, # optional
method,
vector=None,
opts,
):
if format is None:
if indices is not None:
if bitmap is not None:
raise TypeError("Cannot provide both `indptr` and `bitmap`")
format = "sparse"
elif bitmap is not None:
format = "bitmap"
else:
format = "full"
else:
format = format.lower()
if method == "pack":
obj = vector.ss
else:
obj = cls
if format == "sparse":
return getattr(obj, f"{method}_sparse")(
size=size,
indices=indices,
values=values,
nvals=nvals,
is_iso=is_iso,
sorted_index=sorted_index,
take_ownership=take_ownership,
secure_import=secure_import,
dtype=dtype,
name=name,
**opts,
)
if format == "bitmap":
return getattr(obj, f"{method}_bitmap")(
nvals=nvals,
bitmap=bitmap,
values=values,
size=size,
is_iso=is_iso,
take_ownership=take_ownership,
secure_import=secure_import,
dtype=dtype,
name=name,
**opts,
)
if format == "full":
return getattr(obj, f"{method}_full")(
values=values,
size=size,
is_iso=is_iso,
take_ownership=take_ownership,
secure_import=secure_import,
dtype=dtype,
name=name,
**opts,
)
raise ValueError(f"Invalid format: {format}")
@classmethod
def import_sparse(
cls,
*,
size,
indices,
values,
nvals=None,
is_iso=False,
sorted_index=False,
take_ownership=False,
secure_import=False,
dtype=None,
format=None,
name=None,
**opts,
):
"""GxB_Vector_import_CSC.
Create a new Vector from sparse input.
Parameters
----------
size : int
indices : array-like
values : array-like
nvals : int, optional
The number of elements in "values" to use.
If not specified, will be set to ``len(values)``.
is_iso : bool, default False
Is the Vector iso-valued (meaning all the same value)?
If true, then ``values`` should be a length 1 array.
sorted_index : bool, default False
Indicate whether the values in "col_indices" are sorted.
take_ownership : bool, default False
If True, perform a zero-copy data transfer from input numpy arrays
to GraphBLAS if possible. To give ownership of the underlying
memory buffers to GraphBLAS, the arrays must:
- be C contiguous
- have the correct dtype (uint64 for indices)
- own its own data
- be writeable
If all of these conditions are not met, then the data will be
copied and the original array will be unmodified. If zero copy
to GraphBLAS is successful, then the array will be modified to be
read-only and will no longer own the data.
dtype : dtype, optional
dtype of the new Vector.
If not specified, this will be inferred from ``values``.
format : str, optional
Must be "sparse" or None. This is included to be compatible with
the dict returned from exporting.
name : str, optional
Name of the new Vector.
Returns
-------
Vector
"""
return cls._import_sparse(
size=size,
indices=indices,
values=values,
nvals=nvals,
is_iso=is_iso,
sorted_index=sorted_index,
take_ownership=take_ownership,
secure_import=secure_import,
dtype=dtype,
format=format,
name=name,
method="import",
opts=opts,
)
def pack_sparse(
self,
*,
indices,
values,
nvals=None,
is_iso=False,
sorted_index=False,
take_ownership=False,
secure_import=False,
format=None,
# Unused for pack, ignored
size=None,
dtype=None,
name=None,
**opts,
):
"""GxB_Vector_pack_CSC.
``pack_sparse`` is like ``import_sparse`` except it "packs" data into an
existing Vector. This is the opposite of ``unpack("sparse")``
See ``Vector.ss.import_sparse`` documentation for more details.
"""
return self._import_sparse(
indices=indices,
values=values,
nvals=nvals,
is_iso=is_iso,
sorted_index=sorted_index,
take_ownership=take_ownership,
secure_import=secure_import,
format=format,
method="pack",
vector=self._parent,
opts=opts,
)
@classmethod
def _import_sparse(
cls,
*,
size=None,
indices,
values,
nvals=None,
is_iso=False,
sorted_index=False,
take_ownership=False,
secure_import=False,
dtype=None,
format=None,
name=None,
method,
vector=None,
opts,
):
if format is not None and format.lower() != "sparse":
raise ValueError(f"Invalid format: {format!r}. Must be None or 'sparse'.")
copy = not take_ownership
indices = ints_to_numpy_buffer(indices, np.uint64, copy=copy, ownable=True, name="indices")
if method == "pack":
dtype = vector.dtype
values, dtype = values_to_numpy_buffer(
values, dtype, copy=copy, ownable=True, subarray_after=1
)
if indices is values:
values = np.copy(values)
vi = ffi_new("GrB_Index**", ffi.from_buffer("GrB_Index*", indices))
vx = ffi_new("void**", ffi.from_buffer("void*", values))
if nvals is None:
if is_iso:
nvals = indices.size
elif dtype.np_type.subdtype is not None:
nvals = values.shape[0]
else:
nvals = values.size
if method == "import":
vhandle = ffi_new("GrB_Vector*")
args = (dtype._carg, size)
else:
vhandle = vector._carg
args = ()
desc = get_descriptor(secure_import=secure_import, **opts)
status = getattr(lib, f"GxB_Vector_{method}_CSC")(
vhandle,
*args,
vi,
vx,
indices.nbytes,
values.nbytes,
is_iso,
nvals,
not sorted_index,
NULL if desc is None else desc._carg,
)
if method == "import":
check_status_carg(