@@ -210,15 +210,24 @@ def __repr__(self) -> str:
210210
211211
212212 # For NumPy:
213- def __array__ (self ) -> numpy .ndarray :
213+ def __array__ (self , dtype : Optional [ numpy . dtype ] = None , copy : bool = True ) -> numpy .ndarray :
214214 """Convert a ``SparseNdarray`` to a NumPy array.
215215
216+ Args:
217+ dtype:
218+ The desired NumPy type of the output array. If None, the
219+ type of the seed is used.
220+
221+ copy:
222+ Currently ignored. The output is never a reference to the
223+ underlying seed, even if the seed is another NumPy array.
224+
216225 Returns:
217226 Dense array of the same type as :py:attr:`~dtype` and shape as
218227 :py:attr:`~shape`.
219228 """
220229 indices = _spawn_indices (self ._shape )
221- return _extract_dense_array_from_SparseNdarray (self , indices )
230+ return _extract_dense_array_from_SparseNdarray (self , indices , dtype = dtype )
222231
223232 # Assorted dunder methods.
224233 def __add__ (self , other ) -> Union ["SparseNdarray" , numpy .ndarray ]:
@@ -1231,18 +1240,20 @@ def _recursive_extract_dense_array(contents: numpy.ndarray, subset: Tuple[Sequen
12311240 pos += 1
12321241
12331242
1234- def _extract_dense_array_from_SparseNdarray (x : SparseNdarray , subset : Tuple [Sequence [int ], ...]) -> numpy .ndarray :
1243+ def _extract_dense_array_from_SparseNdarray (x : SparseNdarray , subset : Tuple [Sequence [int ], ...], dtype : Optional [ numpy . dtype ] = None ) -> numpy .ndarray :
12351244 idims = [len (y ) for y in subset ]
12361245 subset_summary = _characterize_indices (subset [0 ], x ._shape [0 ])
12371246
12381247 # We reverse the dimensions so that we use F-contiguous storage. This also
12391248 # makes it slightly easier to do the recursion as we can just index by
12401249 # the first dimension to obtain a subarray at each recursive step.
1241- output = numpy .zeros ((* reversed (idims ),), dtype = x ._dtype )
1250+ if dtype is None :
1251+ dtype = x ._dtype
1252+ output = numpy .zeros ((* reversed (idims ),), dtype = dtype )
1253+ if x ._is_masked :
1254+ output = numpy .ma .MaskedArray (output , mask = False )
12421255
12431256 if x ._contents is not None :
1244- if x ._is_masked :
1245- output = numpy .ma .MaskedArray (output , mask = False )
12461257 ndim = len (x ._shape )
12471258 if ndim > 1 :
12481259 _recursive_extract_dense_array (x ._contents , subset , subset_summary = subset_summary , output = output , dim = ndim - 1 )
0 commit comments