File size: 42,071 Bytes
9c6594c |
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF 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.
# Avoid name clash with `pa.struct` function
import struct as _struct
cdef class Tensor(_Weakrefable):
"""
A n-dimensional array a.k.a Tensor.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
<pyarrow.Tensor>
type: int32
shape: (2, 3)
strides: (12, 4)
"""
def __init__(self):
raise TypeError("Do not call Tensor's constructor directly, use one "
"of the `pyarrow.Tensor.from_*` functions instead.")
cdef void init(self, const shared_ptr[CTensor]& sp_tensor):
self.sp_tensor = sp_tensor
self.tp = sp_tensor.get()
self.type = pyarrow_wrap_data_type(self.tp.type())
self._ssize_t_shape = self._make_shape_or_strides_buffer(self.shape)
self._ssize_t_strides = self._make_shape_or_strides_buffer(self.strides)
def _make_shape_or_strides_buffer(self, values):
"""
Make a bytes object holding an array of `values` cast to `Py_ssize_t`.
"""
return _struct.pack(f"{len(values)}n", *values)
def __repr__(self):
return """<pyarrow.Tensor>
type: {0.type}
shape: {0.shape}
strides: {0.strides}""".format(self)
@staticmethod
def from_numpy(obj, dim_names=None):
"""
Create a Tensor from a numpy array.
Parameters
----------
obj : numpy.ndarray
The source numpy array
dim_names : list, optional
Names of each dimension of the Tensor.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
<pyarrow.Tensor>
type: int32
shape: (2, 3)
strides: (12, 4)
"""
cdef:
vector[c_string] c_dim_names
shared_ptr[CTensor] ctensor
if dim_names is not None:
for x in dim_names:
c_dim_names.push_back(tobytes(x))
check_status(NdarrayToTensor(c_default_memory_pool(), obj,
c_dim_names, &ctensor))
return pyarrow_wrap_tensor(ctensor)
def to_numpy(self):
"""
Convert arrow::Tensor to numpy.ndarray with zero copy
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> tensor = pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
>>> tensor.to_numpy()
array([[ 2, 2, 4],
[ 4, 5, 100]], dtype=int32)
"""
if np is None:
raise ImportError(
"Cannot return a numpy.ndarray if NumPy is not present")
cdef PyObject* out
check_status(TensorToNdarray(self.sp_tensor, self, &out))
return PyObject_to_object(out)
def equals(self, Tensor other):
"""
Return true if the tensors contains exactly equal data.
Parameters
----------
other : Tensor
The other tensor to compare for equality.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> tensor = pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
>>> y = np.array([[2, 2, 4], [4, 5, 10]], np.int32)
>>> tensor2 = pa.Tensor.from_numpy(y, dim_names=["a","b"])
>>> tensor.equals(tensor)
True
>>> tensor.equals(tensor2)
False
"""
return self.tp.Equals(deref(other.tp))
def __eq__(self, other):
if isinstance(other, Tensor):
return self.equals(other)
else:
return NotImplemented
def dim_name(self, i):
"""
Returns the name of the i-th tensor dimension.
Parameters
----------
i : int
The physical index of the tensor dimension.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> tensor = pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
>>> tensor.dim_name(0)
'dim1'
>>> tensor.dim_name(1)
'dim2'
"""
return frombytes(self.tp.dim_name(i))
@property
def dim_names(self):
"""
Names of this tensor dimensions.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> tensor = pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
>>> tensor.dim_names
['dim1', 'dim2']
"""
return [frombytes(x) for x in tuple(self.tp.dim_names())]
@property
def is_mutable(self):
"""
Is this tensor mutable or immutable.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> tensor = pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
>>> tensor.is_mutable
True
"""
return self.tp.is_mutable()
@property
def is_contiguous(self):
"""
Is this tensor contiguous in memory.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> tensor = pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
>>> tensor.is_contiguous
True
"""
return self.tp.is_contiguous()
@property
def ndim(self):
"""
The dimension (n) of this tensor.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> tensor = pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
>>> tensor.ndim
2
"""
return self.tp.ndim()
@property
def size(self):
"""
The size of this tensor.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> tensor = pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
>>> tensor.size
6
"""
return self.tp.size()
@property
def shape(self):
"""
The shape of this tensor.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> tensor = pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
>>> tensor.shape
(2, 3)
"""
# Cython knows how to convert a vector[T] to a Python list
return tuple(self.tp.shape())
@property
def strides(self):
"""
Strides of this tensor.
Examples
--------
>>> import pyarrow as pa
>>> import numpy as np
>>> x = np.array([[2, 2, 4], [4, 5, 100]], np.int32)
>>> tensor = pa.Tensor.from_numpy(x, dim_names=["dim1","dim2"])
>>> tensor.strides
(12, 4)
"""
return tuple(self.tp.strides())
def __getbuffer__(self, cp.Py_buffer* buffer, int flags):
buffer.buf = <char *> self.tp.data().get().data()
pep3118_format = self.type.pep3118_format
if pep3118_format is None:
raise NotImplementedError("type %s not supported for buffer "
"protocol" % (self.type,))
buffer.format = pep3118_format
buffer.itemsize = self.type.bit_width // 8
buffer.internal = NULL
buffer.len = self.tp.size() * buffer.itemsize
buffer.ndim = self.tp.ndim()
buffer.obj = self
if self.tp.is_mutable():
buffer.readonly = 0
else:
buffer.readonly = 1
buffer.shape = <Py_ssize_t *> cp.PyBytes_AsString(self._ssize_t_shape)
buffer.strides = <Py_ssize_t *> cp.PyBytes_AsString(self._ssize_t_strides)
buffer.suboffsets = NULL
ctypedef CSparseCOOIndex* _CSparseCOOIndexPtr
cdef class SparseCOOTensor(_Weakrefable):
"""
A sparse COO tensor.
"""
def __init__(self):
raise TypeError("Do not call SparseCOOTensor's constructor directly, "
"use one of the `pyarrow.SparseCOOTensor.from_*` "
"functions instead.")
cdef void init(self, const shared_ptr[CSparseCOOTensor]& sp_sparse_tensor):
self.sp_sparse_tensor = sp_sparse_tensor
self.stp = sp_sparse_tensor.get()
self.type = pyarrow_wrap_data_type(self.stp.type())
def __repr__(self):
return """<pyarrow.SparseCOOTensor>
type: {0.type}
shape: {0.shape}""".format(self)
@classmethod
def from_dense_numpy(cls, obj, dim_names=None):
"""
Convert numpy.ndarray to arrow::SparseCOOTensor
Parameters
----------
obj : numpy.ndarray
Data used to populate the rows.
dim_names : list[str], optional
Names of the dimensions.
Returns
-------
pyarrow.SparseCOOTensor
"""
return cls.from_tensor(Tensor.from_numpy(obj, dim_names=dim_names))
@staticmethod
def from_numpy(data, coords, shape, dim_names=None):
"""
Create arrow::SparseCOOTensor from numpy.ndarrays
Parameters
----------
data : numpy.ndarray
Data used to populate the rows.
coords : numpy.ndarray
Coordinates of the data.
shape : tuple
Shape of the tensor.
dim_names : list, optional
Names of the dimensions.
"""
cdef shared_ptr[CSparseCOOTensor] csparse_tensor
cdef vector[int64_t] c_shape
cdef vector[c_string] c_dim_names
for x in shape:
c_shape.push_back(x)
if dim_names is not None:
for x in dim_names:
c_dim_names.push_back(tobytes(x))
# Enforce precondition for SparseCOOTensor indices
coords = np.require(coords, dtype='i8', requirements='C')
if coords.ndim != 2:
raise ValueError("Expected 2-dimensional array for "
"SparseCOOTensor indices")
check_status(NdarraysToSparseCOOTensor(c_default_memory_pool(),
data, coords, c_shape,
c_dim_names, &csparse_tensor))
return pyarrow_wrap_sparse_coo_tensor(csparse_tensor)
@staticmethod
def from_scipy(obj, dim_names=None):
"""
Convert scipy.sparse.coo_matrix to arrow::SparseCOOTensor
Parameters
----------
obj : scipy.sparse.csr_matrix
The scipy matrix that should be converted.
dim_names : list, optional
Names of the dimensions.
"""
import scipy.sparse
if not isinstance(obj, scipy.sparse.coo_matrix):
raise TypeError(
"Expected scipy.sparse.coo_matrix, got {}".format(type(obj)))
cdef shared_ptr[CSparseCOOTensor] csparse_tensor
cdef vector[int64_t] c_shape
cdef vector[c_string] c_dim_names
for x in obj.shape:
c_shape.push_back(x)
if dim_names is not None:
for x in dim_names:
c_dim_names.push_back(tobytes(x))
row = obj.row
col = obj.col
# When SciPy's coo_matrix has canonical format, its indices matrix is
# sorted in column-major order. As Arrow's SparseCOOIndex is sorted
# in row-major order if it is canonical, we must sort indices matrix
# into row-major order to keep its canonicalness, here.
if obj.has_canonical_format:
order = np.lexsort((col, row)) # sort in row-major order
row = row[order]
col = col[order]
coords = np.vstack([row, col]).T
coords = np.require(coords, dtype='i8', requirements='C')
check_status(NdarraysToSparseCOOTensor(c_default_memory_pool(),
obj.data, coords, c_shape,
c_dim_names, &csparse_tensor))
return pyarrow_wrap_sparse_coo_tensor(csparse_tensor)
@staticmethod
def from_pydata_sparse(obj, dim_names=None):
"""
Convert pydata/sparse.COO to arrow::SparseCOOTensor.
Parameters
----------
obj : pydata.sparse.COO
The sparse multidimensional array that should be converted.
dim_names : list, optional
Names of the dimensions.
"""
import sparse
if not isinstance(obj, sparse.COO):
raise TypeError(
"Expected sparse.COO, got {}".format(type(obj)))
cdef shared_ptr[CSparseCOOTensor] csparse_tensor
cdef vector[int64_t] c_shape
cdef vector[c_string] c_dim_names
for x in obj.shape:
c_shape.push_back(x)
if dim_names is not None:
for x in dim_names:
c_dim_names.push_back(tobytes(x))
coords = np.require(obj.coords.T, dtype='i8', requirements='C')
check_status(NdarraysToSparseCOOTensor(c_default_memory_pool(),
obj.data, coords, c_shape,
c_dim_names, &csparse_tensor))
return pyarrow_wrap_sparse_coo_tensor(csparse_tensor)
@staticmethod
def from_tensor(obj):
"""
Convert arrow::Tensor to arrow::SparseCOOTensor.
Parameters
----------
obj : Tensor
The tensor that should be converted.
"""
cdef shared_ptr[CSparseCOOTensor] csparse_tensor
cdef shared_ptr[CTensor] ctensor = pyarrow_unwrap_tensor(obj)
with nogil:
check_status(TensorToSparseCOOTensor(ctensor, &csparse_tensor))
return pyarrow_wrap_sparse_coo_tensor(csparse_tensor)
def to_numpy(self):
"""
Convert arrow::SparseCOOTensor to numpy.ndarrays with zero copy.
"""
if np is None:
raise ImportError(
"Cannot return a numpy.ndarray if NumPy is not present")
cdef PyObject* out_data
cdef PyObject* out_coords
check_status(SparseCOOTensorToNdarray(self.sp_sparse_tensor, self,
&out_data, &out_coords))
return PyObject_to_object(out_data), PyObject_to_object(out_coords)
def to_scipy(self):
"""
Convert arrow::SparseCOOTensor to scipy.sparse.coo_matrix.
"""
from scipy.sparse import coo_matrix
cdef PyObject* out_data
cdef PyObject* out_coords
check_status(SparseCOOTensorToNdarray(self.sp_sparse_tensor, self,
&out_data, &out_coords))
data = PyObject_to_object(out_data)
coords = PyObject_to_object(out_coords)
row, col = coords[:, 0], coords[:, 1]
result = coo_matrix((data[:, 0], (row, col)), shape=self.shape)
# As the description in from_scipy above, we sorted indices matrix
# in row-major order if SciPy's coo_matrix has canonical format.
# So, we must call sum_duplicates() to make the result coo_matrix
# has canonical format.
if self.has_canonical_format:
result.sum_duplicates()
return result
def to_pydata_sparse(self):
"""
Convert arrow::SparseCOOTensor to pydata/sparse.COO.
"""
from sparse import COO
cdef PyObject* out_data
cdef PyObject* out_coords
check_status(SparseCOOTensorToNdarray(self.sp_sparse_tensor, self,
&out_data, &out_coords))
data = PyObject_to_object(out_data)
coords = PyObject_to_object(out_coords)
result = COO(data=data[:, 0], coords=coords.T, shape=self.shape)
return result
def to_tensor(self):
"""
Convert arrow::SparseCOOTensor to arrow::Tensor.
"""
cdef shared_ptr[CTensor] ctensor
with nogil:
ctensor = GetResultValue(self.stp.ToTensor())
return pyarrow_wrap_tensor(ctensor)
def equals(self, SparseCOOTensor other):
"""
Return true if sparse tensors contains exactly equal data.
Parameters
----------
other : SparseCOOTensor
The other tensor to compare for equality.
"""
return self.stp.Equals(deref(other.stp))
def __eq__(self, other):
if isinstance(other, SparseCOOTensor):
return self.equals(other)
else:
return NotImplemented
@property
def is_mutable(self):
return self.stp.is_mutable()
@property
def ndim(self):
return self.stp.ndim()
@property
def shape(self):
# Cython knows how to convert a vector[T] to a Python list
return tuple(self.stp.shape())
@property
def size(self):
return self.stp.size()
def dim_name(self, i):
"""
Returns the name of the i-th tensor dimension.
Parameters
----------
i : int
The physical index of the tensor dimension.
Returns
-------
str
"""
return frombytes(self.stp.dim_name(i))
@property
def dim_names(self):
names_tuple = tuple(self.stp.dim_names())
return tuple(frombytes(x) for x in names_tuple)
@property
def non_zero_length(self):
return self.stp.non_zero_length()
@property
def has_canonical_format(self):
cdef:
_CSparseCOOIndexPtr csi
csi = <_CSparseCOOIndexPtr>(self.stp.sparse_index().get())
if csi != nullptr:
return csi.is_canonical()
return True
cdef class SparseCSRMatrix(_Weakrefable):
"""
A sparse CSR matrix.
"""
def __init__(self):
raise TypeError("Do not call SparseCSRMatrix's constructor directly, "
"use one of the `pyarrow.SparseCSRMatrix.from_*` "
"functions instead.")
cdef void init(self, const shared_ptr[CSparseCSRMatrix]& sp_sparse_tensor):
self.sp_sparse_tensor = sp_sparse_tensor
self.stp = sp_sparse_tensor.get()
self.type = pyarrow_wrap_data_type(self.stp.type())
def __repr__(self):
return """<pyarrow.SparseCSRMatrix>
type: {0.type}
shape: {0.shape}""".format(self)
@classmethod
def from_dense_numpy(cls, obj, dim_names=None):
"""
Convert numpy.ndarray to arrow::SparseCSRMatrix
Parameters
----------
obj : numpy.ndarray
The dense numpy array that should be converted.
dim_names : list, optional
The names of the dimensions.
Returns
-------
pyarrow.SparseCSRMatrix
"""
return cls.from_tensor(Tensor.from_numpy(obj, dim_names=dim_names))
@staticmethod
def from_numpy(data, indptr, indices, shape, dim_names=None):
"""
Create arrow::SparseCSRMatrix from numpy.ndarrays.
Parameters
----------
data : numpy.ndarray
Data used to populate the sparse matrix.
indptr : numpy.ndarray
Range of the rows,
The i-th row spans from `indptr[i]` to `indptr[i+1]` in the data.
indices : numpy.ndarray
Column indices of the corresponding non-zero values.
shape : tuple
Shape of the matrix.
dim_names : list, optional
Names of the dimensions.
"""
cdef shared_ptr[CSparseCSRMatrix] csparse_tensor
cdef vector[int64_t] c_shape
cdef vector[c_string] c_dim_names
for x in shape:
c_shape.push_back(x)
if dim_names is not None:
for x in dim_names:
c_dim_names.push_back(tobytes(x))
# Enforce precondition for SparseCSRMatrix indices
indptr = np.require(indptr, dtype='i8')
indices = np.require(indices, dtype='i8')
if indptr.ndim != 1:
raise ValueError("Expected 1-dimensional array for "
"SparseCSRMatrix indptr")
if indices.ndim != 1:
raise ValueError("Expected 1-dimensional array for "
"SparseCSRMatrix indices")
check_status(NdarraysToSparseCSRMatrix(c_default_memory_pool(),
data, indptr, indices, c_shape,
c_dim_names, &csparse_tensor))
return pyarrow_wrap_sparse_csr_matrix(csparse_tensor)
@staticmethod
def from_scipy(obj, dim_names=None):
"""
Convert scipy.sparse.csr_matrix to arrow::SparseCSRMatrix.
Parameters
----------
obj : scipy.sparse.csr_matrix
The scipy matrix that should be converted.
dim_names : list, optional
Names of the dimensions.
"""
import scipy.sparse
if not isinstance(obj, scipy.sparse.csr_matrix):
raise TypeError(
"Expected scipy.sparse.csr_matrix, got {}".format(type(obj)))
cdef shared_ptr[CSparseCSRMatrix] csparse_tensor
cdef vector[int64_t] c_shape
cdef vector[c_string] c_dim_names
for x in obj.shape:
c_shape.push_back(x)
if dim_names is not None:
for x in dim_names:
c_dim_names.push_back(tobytes(x))
# Enforce precondition for CSparseCSRMatrix indices
indptr = np.require(obj.indptr, dtype='i8')
indices = np.require(obj.indices, dtype='i8')
check_status(NdarraysToSparseCSRMatrix(c_default_memory_pool(),
obj.data, indptr, indices,
c_shape, c_dim_names,
&csparse_tensor))
return pyarrow_wrap_sparse_csr_matrix(csparse_tensor)
@staticmethod
def from_tensor(obj):
"""
Convert arrow::Tensor to arrow::SparseCSRMatrix.
Parameters
----------
obj : Tensor
The dense tensor that should be converted.
"""
cdef shared_ptr[CSparseCSRMatrix] csparse_tensor
cdef shared_ptr[CTensor] ctensor = pyarrow_unwrap_tensor(obj)
with nogil:
check_status(TensorToSparseCSRMatrix(ctensor, &csparse_tensor))
return pyarrow_wrap_sparse_csr_matrix(csparse_tensor)
def to_numpy(self):
"""
Convert arrow::SparseCSRMatrix to numpy.ndarrays with zero copy.
"""
if np is None:
raise ImportError(
"Cannot return a numpy.ndarray if NumPy is not present")
cdef PyObject* out_data
cdef PyObject* out_indptr
cdef PyObject* out_indices
check_status(SparseCSRMatrixToNdarray(self.sp_sparse_tensor, self,
&out_data, &out_indptr,
&out_indices))
return (PyObject_to_object(out_data), PyObject_to_object(out_indptr),
PyObject_to_object(out_indices))
def to_scipy(self):
"""
Convert arrow::SparseCSRMatrix to scipy.sparse.csr_matrix.
"""
from scipy.sparse import csr_matrix
cdef PyObject* out_data
cdef PyObject* out_indptr
cdef PyObject* out_indices
check_status(SparseCSRMatrixToNdarray(self.sp_sparse_tensor, self,
&out_data, &out_indptr,
&out_indices))
data = PyObject_to_object(out_data)
indptr = PyObject_to_object(out_indptr)
indices = PyObject_to_object(out_indices)
result = csr_matrix((data[:, 0], indices, indptr), shape=self.shape)
return result
def to_tensor(self):
"""
Convert arrow::SparseCSRMatrix to arrow::Tensor.
"""
cdef shared_ptr[CTensor] ctensor
with nogil:
ctensor = GetResultValue(self.stp.ToTensor())
return pyarrow_wrap_tensor(ctensor)
def equals(self, SparseCSRMatrix other):
"""
Return true if sparse tensors contains exactly equal data.
Parameters
----------
other : SparseCSRMatrix
The other tensor to compare for equality.
"""
return self.stp.Equals(deref(other.stp))
def __eq__(self, other):
if isinstance(other, SparseCSRMatrix):
return self.equals(other)
else:
return NotImplemented
@property
def is_mutable(self):
return self.stp.is_mutable()
@property
def ndim(self):
return self.stp.ndim()
@property
def shape(self):
# Cython knows how to convert a vector[T] to a Python list
return tuple(self.stp.shape())
@property
def size(self):
return self.stp.size()
def dim_name(self, i):
"""
Returns the name of the i-th tensor dimension.
Parameters
----------
i : int
The physical index of the tensor dimension.
Returns
-------
str
"""
return frombytes(self.stp.dim_name(i))
@property
def dim_names(self):
names_tuple = tuple(self.stp.dim_names())
return tuple(frombytes(x) for x in names_tuple)
@property
def non_zero_length(self):
return self.stp.non_zero_length()
cdef class SparseCSCMatrix(_Weakrefable):
"""
A sparse CSC matrix.
"""
def __init__(self):
raise TypeError("Do not call SparseCSCMatrix's constructor directly, "
"use one of the `pyarrow.SparseCSCMatrix.from_*` "
"functions instead.")
cdef void init(self, const shared_ptr[CSparseCSCMatrix]& sp_sparse_tensor):
self.sp_sparse_tensor = sp_sparse_tensor
self.stp = sp_sparse_tensor.get()
self.type = pyarrow_wrap_data_type(self.stp.type())
def __repr__(self):
return """<pyarrow.SparseCSCMatrix>
type: {0.type}
shape: {0.shape}""".format(self)
@classmethod
def from_dense_numpy(cls, obj, dim_names=None):
"""
Convert numpy.ndarray to arrow::SparseCSCMatrix
Parameters
----------
obj : numpy.ndarray
Data used to populate the rows.
dim_names : list[str], optional
Names of the dimensions.
Returns
-------
pyarrow.SparseCSCMatrix
"""
return cls.from_tensor(Tensor.from_numpy(obj, dim_names=dim_names))
@staticmethod
def from_numpy(data, indptr, indices, shape, dim_names=None):
"""
Create arrow::SparseCSCMatrix from numpy.ndarrays
Parameters
----------
data : numpy.ndarray
Data used to populate the sparse matrix.
indptr : numpy.ndarray
Range of the rows,
The i-th row spans from `indptr[i]` to `indptr[i+1]` in the data.
indices : numpy.ndarray
Column indices of the corresponding non-zero values.
shape : tuple
Shape of the matrix.
dim_names : list, optional
Names of the dimensions.
"""
cdef shared_ptr[CSparseCSCMatrix] csparse_tensor
cdef vector[int64_t] c_shape
cdef vector[c_string] c_dim_names
for x in shape:
c_shape.push_back(x)
if dim_names is not None:
for x in dim_names:
c_dim_names.push_back(tobytes(x))
# Enforce precondition for SparseCSCMatrix indices
indptr = np.require(indptr, dtype='i8')
indices = np.require(indices, dtype='i8')
if indptr.ndim != 1:
raise ValueError("Expected 1-dimensional array for "
"SparseCSCMatrix indptr")
if indices.ndim != 1:
raise ValueError("Expected 1-dimensional array for "
"SparseCSCMatrix indices")
check_status(NdarraysToSparseCSCMatrix(c_default_memory_pool(),
data, indptr, indices, c_shape,
c_dim_names, &csparse_tensor))
return pyarrow_wrap_sparse_csc_matrix(csparse_tensor)
@staticmethod
def from_scipy(obj, dim_names=None):
"""
Convert scipy.sparse.csc_matrix to arrow::SparseCSCMatrix
Parameters
----------
obj : scipy.sparse.csc_matrix
The scipy matrix that should be converted.
dim_names : list, optional
Names of the dimensions.
"""
import scipy.sparse
if not isinstance(obj, scipy.sparse.csc_matrix):
raise TypeError(
"Expected scipy.sparse.csc_matrix, got {}".format(type(obj)))
cdef shared_ptr[CSparseCSCMatrix] csparse_tensor
cdef vector[int64_t] c_shape
cdef vector[c_string] c_dim_names
for x in obj.shape:
c_shape.push_back(x)
if dim_names is not None:
for x in dim_names:
c_dim_names.push_back(tobytes(x))
# Enforce precondition for CSparseCSCMatrix indices
indptr = np.require(obj.indptr, dtype='i8')
indices = np.require(obj.indices, dtype='i8')
check_status(NdarraysToSparseCSCMatrix(c_default_memory_pool(),
obj.data, indptr, indices,
c_shape, c_dim_names,
&csparse_tensor))
return pyarrow_wrap_sparse_csc_matrix(csparse_tensor)
@staticmethod
def from_tensor(obj):
"""
Convert arrow::Tensor to arrow::SparseCSCMatrix
Parameters
----------
obj : Tensor
The dense tensor that should be converted.
"""
cdef shared_ptr[CSparseCSCMatrix] csparse_tensor
cdef shared_ptr[CTensor] ctensor = pyarrow_unwrap_tensor(obj)
with nogil:
check_status(TensorToSparseCSCMatrix(ctensor, &csparse_tensor))
return pyarrow_wrap_sparse_csc_matrix(csparse_tensor)
def to_numpy(self):
"""
Convert arrow::SparseCSCMatrix to numpy.ndarrays with zero copy
"""
if np is None:
raise ImportError(
"Cannot return a numpy.ndarray if NumPy is not present")
cdef PyObject* out_data
cdef PyObject* out_indptr
cdef PyObject* out_indices
check_status(SparseCSCMatrixToNdarray(self.sp_sparse_tensor, self,
&out_data, &out_indptr,
&out_indices))
return (PyObject_to_object(out_data), PyObject_to_object(out_indptr),
PyObject_to_object(out_indices))
def to_scipy(self):
"""
Convert arrow::SparseCSCMatrix to scipy.sparse.csc_matrix
"""
from scipy.sparse import csc_matrix
cdef PyObject* out_data
cdef PyObject* out_indptr
cdef PyObject* out_indices
check_status(SparseCSCMatrixToNdarray(self.sp_sparse_tensor, self,
&out_data, &out_indptr,
&out_indices))
data = PyObject_to_object(out_data)
indptr = PyObject_to_object(out_indptr)
indices = PyObject_to_object(out_indices)
result = csc_matrix((data[:, 0], indices, indptr), shape=self.shape)
return result
def to_tensor(self):
"""
Convert arrow::SparseCSCMatrix to arrow::Tensor
"""
cdef shared_ptr[CTensor] ctensor
with nogil:
ctensor = GetResultValue(self.stp.ToTensor())
return pyarrow_wrap_tensor(ctensor)
def equals(self, SparseCSCMatrix other):
"""
Return true if sparse tensors contains exactly equal data
Parameters
----------
other : SparseCSCMatrix
The other tensor to compare for equality.
"""
return self.stp.Equals(deref(other.stp))
def __eq__(self, other):
if isinstance(other, SparseCSCMatrix):
return self.equals(other)
else:
return NotImplemented
@property
def is_mutable(self):
return self.stp.is_mutable()
@property
def ndim(self):
return self.stp.ndim()
@property
def shape(self):
# Cython knows how to convert a vector[T] to a Python list
return tuple(self.stp.shape())
@property
def size(self):
return self.stp.size()
def dim_name(self, i):
"""
Returns the name of the i-th tensor dimension.
Parameters
----------
i : int
The physical index of the tensor dimension.
Returns
-------
str
"""
return frombytes(self.stp.dim_name(i))
@property
def dim_names(self):
names_tuple = tuple(self.stp.dim_names())
return tuple(frombytes(x) for x in names_tuple)
@property
def non_zero_length(self):
return self.stp.non_zero_length()
cdef class SparseCSFTensor(_Weakrefable):
"""
A sparse CSF tensor.
CSF is a generalization of compressed sparse row (CSR) index.
CSF index recursively compresses each dimension of a tensor into a set
of prefix trees. Each path from a root to leaf forms one tensor
non-zero index. CSF is implemented with two arrays of buffers and one
arrays of integers.
"""
def __init__(self):
raise TypeError("Do not call SparseCSFTensor's constructor directly, "
"use one of the `pyarrow.SparseCSFTensor.from_*` "
"functions instead.")
cdef void init(self, const shared_ptr[CSparseCSFTensor]& sp_sparse_tensor):
self.sp_sparse_tensor = sp_sparse_tensor
self.stp = sp_sparse_tensor.get()
self.type = pyarrow_wrap_data_type(self.stp.type())
def __repr__(self):
return """<pyarrow.SparseCSFTensor>
type: {0.type}
shape: {0.shape}""".format(self)
@classmethod
def from_dense_numpy(cls, obj, dim_names=None):
"""
Convert numpy.ndarray to arrow::SparseCSFTensor
Parameters
----------
obj : numpy.ndarray
Data used to populate the rows.
dim_names : list[str], optional
Names of the dimensions.
Returns
-------
pyarrow.SparseCSFTensor
"""
return cls.from_tensor(Tensor.from_numpy(obj, dim_names=dim_names))
@staticmethod
def from_numpy(data, indptr, indices, shape, axis_order=None,
dim_names=None):
"""
Create arrow::SparseCSFTensor from numpy.ndarrays
Parameters
----------
data : numpy.ndarray
Data used to populate the sparse tensor.
indptr : numpy.ndarray
The sparsity structure.
Each two consecutive dimensions in a tensor correspond to
a buffer in indices.
A pair of consecutive values at `indptr[dim][i]`
`indptr[dim][i + 1]` signify a range of nodes in
`indices[dim + 1]` who are children of `indices[dim][i]` node.
indices : numpy.ndarray
Stores values of nodes.
Each tensor dimension corresponds to a buffer in indptr.
shape : tuple
Shape of the matrix.
axis_order : list, optional
the sequence in which dimensions were traversed to
produce the prefix tree.
dim_names : list, optional
Names of the dimensions.
"""
cdef shared_ptr[CSparseCSFTensor] csparse_tensor
cdef vector[int64_t] c_axis_order
cdef vector[int64_t] c_shape
cdef vector[c_string] c_dim_names
for x in shape:
c_shape.push_back(x)
if not axis_order:
axis_order = np.argsort(shape)
for x in axis_order:
c_axis_order.push_back(x)
if dim_names is not None:
for x in dim_names:
c_dim_names.push_back(tobytes(x))
# Enforce preconditions for SparseCSFTensor indices
if not (isinstance(indptr, (list, tuple)) and
isinstance(indices, (list, tuple))):
raise TypeError("Expected list or tuple, got {}, {}"
.format(type(indptr), type(indices)))
if len(indptr) != len(shape) - 1:
raise ValueError("Expected list of {ndim} np.arrays for "
"SparseCSFTensor.indptr".format(ndim=len(shape)))
if len(indices) != len(shape):
raise ValueError("Expected list of {ndim} np.arrays for "
"SparseCSFTensor.indices".format(ndim=len(shape)))
if any([x.ndim != 1 for x in indptr]):
raise ValueError("Expected a list of 1-dimensional arrays for "
"SparseCSFTensor.indptr")
if any([x.ndim != 1 for x in indices]):
raise ValueError("Expected a list of 1-dimensional arrays for "
"SparseCSFTensor.indices")
indptr = [np.require(arr, dtype='i8') for arr in indptr]
indices = [np.require(arr, dtype='i8') for arr in indices]
check_status(NdarraysToSparseCSFTensor(c_default_memory_pool(), data,
indptr, indices, c_shape,
c_axis_order, c_dim_names,
&csparse_tensor))
return pyarrow_wrap_sparse_csf_tensor(csparse_tensor)
@staticmethod
def from_tensor(obj):
"""
Convert arrow::Tensor to arrow::SparseCSFTensor
Parameters
----------
obj : Tensor
The dense tensor that should be converted.
"""
cdef shared_ptr[CSparseCSFTensor] csparse_tensor
cdef shared_ptr[CTensor] ctensor = pyarrow_unwrap_tensor(obj)
with nogil:
check_status(TensorToSparseCSFTensor(ctensor, &csparse_tensor))
return pyarrow_wrap_sparse_csf_tensor(csparse_tensor)
def to_numpy(self):
"""
Convert arrow::SparseCSFTensor to numpy.ndarrays with zero copy
"""
if np is None:
raise ImportError(
"Cannot return a numpy.ndarray if NumPy is not present")
cdef PyObject* out_data
cdef PyObject* out_indptr
cdef PyObject* out_indices
check_status(SparseCSFTensorToNdarray(self.sp_sparse_tensor, self,
&out_data, &out_indptr,
&out_indices))
return (PyObject_to_object(out_data), PyObject_to_object(out_indptr),
PyObject_to_object(out_indices))
def to_tensor(self):
"""
Convert arrow::SparseCSFTensor to arrow::Tensor
"""
cdef shared_ptr[CTensor] ctensor
with nogil:
ctensor = GetResultValue(self.stp.ToTensor())
return pyarrow_wrap_tensor(ctensor)
def equals(self, SparseCSFTensor other):
"""
Return true if sparse tensors contains exactly equal data
Parameters
----------
other : SparseCSFTensor
The other tensor to compare for equality.
"""
return self.stp.Equals(deref(other.stp))
def __eq__(self, other):
if isinstance(other, SparseCSFTensor):
return self.equals(other)
else:
return NotImplemented
@property
def is_mutable(self):
return self.stp.is_mutable()
@property
def ndim(self):
return self.stp.ndim()
@property
def shape(self):
# Cython knows how to convert a vector[T] to a Python list
return tuple(self.stp.shape())
@property
def size(self):
return self.stp.size()
def dim_name(self, i):
"""
Returns the name of the i-th tensor dimension.
Parameters
----------
i : int
The physical index of the tensor dimension.
Returns
-------
str
"""
return frombytes(self.stp.dim_name(i))
@property
def dim_names(self):
names_tuple = tuple(self.stp.dim_names())
return tuple(frombytes(x) for x in names_tuple)
@property
def non_zero_length(self):
return self.stp.non_zero_length()
|