0
# Array Operations
1
2
Comprehensive array creation and manipulation operations that provide the foundation for GPU computing with CuPy. These functions mirror NumPy's API while operating efficiently on GPU memory.
3
4
## Capabilities
5
6
### Array Creation Functions
7
8
Create arrays directly on GPU memory with various initialization patterns and data sources.
9
10
```python { .api }
11
def array(obj, dtype=None, copy=True, order='K', subok=False, ndmin=0):
12
"""
13
Create an array on GPU from array-like object.
14
15
Parameters:
16
- obj: array_like, input data
17
- dtype: data type, optional
18
- copy: bool, whether to copy data
19
- order: {'K', 'A', 'C', 'F'}, memory layout
20
- subok: bool, allow subclasses
21
- ndmin: int, minimum dimensions
22
23
Returns:
24
cupy.ndarray: Array on GPU
25
"""
26
27
def asarray(a, dtype=None, order=None):
28
"""Convert input to array, avoiding copy if possible."""
29
30
def asanyarray(a, dtype=None, order=None):
31
"""Convert input to array, preserving subclasses."""
32
33
def ascontiguousarray(a, dtype=None):
34
"""Return contiguous array in C order."""
35
36
def copy(a, order='K', subok=False):
37
"""Return copy of array."""
38
39
def asnumpy(a, stream=None, order='C', out=None):
40
"""Transfer array from GPU to CPU memory."""
41
42
def frombuffer(buffer, dtype=float, count=-1, offset=0):
43
"""Create array from buffer object."""
44
45
def fromfile(file, dtype=float, count=-1, sep=''):
46
"""Create array from data in text or binary file."""
47
48
def fromfunction(function, shape, dtype=float, **kwargs):
49
"""Create array by executing function over grid."""
50
51
def fromiter(iterable, dtype, count=-1):
52
"""Create array from iterable object."""
53
54
def fromstring(string, dtype=float, count=-1, sep=''):
55
"""Create array from string data."""
56
57
def loadtxt(fname, dtype=float, comments='#', delimiter=None, **kwargs):
58
"""Load data from text file."""
59
60
def genfromtxt(fname, dtype=float, comments='#', delimiter=None, **kwargs):
61
"""Load data from text file with missing value handling."""
62
```
63
64
#### Initialization Functions
65
66
```python { .api }
67
def zeros(shape, dtype=float, order='C'):
68
"""Return array filled with zeros."""
69
70
def zeros_like(a, dtype=None, order='K', subok=True, shape=None):
71
"""Return zeros array with same shape and type as input."""
72
73
def ones(shape, dtype=float, order='C'):
74
"""Return array filled with ones."""
75
76
def ones_like(a, dtype=None, order='K', subok=True, shape=None):
77
"""Return ones array with same shape and type as input."""
78
79
def empty(shape, dtype=float, order='C'):
80
"""Return uninitialized array."""
81
82
def empty_like(a, dtype=None, order='K', subok=True, shape=None):
83
"""Return uninitialized array with same shape and type as input."""
84
85
def full(shape, fill_value, dtype=None, order='C'):
86
"""Return array filled with fill_value."""
87
88
def full_like(a, fill_value, dtype=None, order='K', subok=True, shape=None):
89
"""Return filled array with same shape and type as input."""
90
91
def eye(N, M=None, k=0, dtype=float, order='C'):
92
"""Return 2-D array with ones on diagonal."""
93
94
def identity(n, dtype=float):
95
"""Return identity array."""
96
```
97
98
### Range Creation
99
100
Generate sequences and coordinate arrays for numerical computation.
101
102
```python { .api }
103
def arange(start, stop=None, step=1, dtype=None):
104
"""
105
Return evenly spaced values within interval.
106
107
Parameters:
108
- start: number, start of interval
109
- stop: number, end of interval
110
- step: number, spacing between values
111
- dtype: data type
112
113
Returns:
114
cupy.ndarray: Array of evenly spaced values
115
"""
116
117
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
118
"""Return evenly spaced numbers over interval."""
119
120
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None):
121
"""Return evenly spaced numbers on log scale."""
122
123
def meshgrid(*xi, copy=True, sparse=False, indexing='xy'):
124
"""Return coordinate matrices from coordinate vectors."""
125
126
def mgrid():
127
"""nd_grid instance for dense multi-dimensional grids."""
128
129
def ogrid():
130
"""nd_grid instance for open multi-dimensional grids."""
131
```
132
133
### Matrix Creation
134
135
Create specialized matrix structures for linear algebra operations.
136
137
```python { .api }
138
def diag(v, k=0):
139
"""Extract diagonal or construct diagonal array."""
140
141
def diagflat(v, k=0):
142
"""Create 2-D array with flattened input as diagonal."""
143
144
def tri(N, M=None, k=0, dtype=float):
145
"""Array with ones at and below given diagonal."""
146
147
def tril(m, k=0):
148
"""Lower triangle of array."""
149
150
def triu(m, k=0):
151
"""Upper triangle of array."""
152
153
def vander(x, N=None, increasing=False):
154
"""Generate Vandermonde matrix."""
155
```
156
157
### Shape Manipulation
158
159
Modify array shapes and dimensions while preserving data.
160
161
```python { .api }
162
def reshape(a, newshape, order='C'):
163
"""Return array with new shape."""
164
165
def ravel(a, order='C'):
166
"""Return contiguous flattened array."""
167
168
def flatten(a, order='C'):
169
"""Return copy of array collapsed into 1-D."""
170
171
def transpose(a, axes=None):
172
"""Reverse or permute axes of array."""
173
174
def swapaxes(a, axis1, axis2):
175
"""Interchange two axes of array."""
176
177
def moveaxis(a, source, destination):
178
"""Move axes of array to new positions."""
179
180
def rollaxis(a, axis, start=0):
181
"""Roll specified axis backwards."""
182
```
183
184
### Dimension Manipulation
185
186
Add, remove, or modify array dimensions.
187
188
```python { .api }
189
def atleast_1d(*arys):
190
"""Convert inputs to arrays with at least 1 dimension."""
191
192
def atleast_2d(*arys):
193
"""Convert inputs to arrays with at least 2 dimensions."""
194
195
def atleast_3d(*arys):
196
"""Convert inputs to arrays with at least 3 dimensions."""
197
198
def expand_dims(a, axis):
199
"""Expand shape of array by inserting new axes."""
200
201
def squeeze(a, axis=None):
202
"""Remove single-dimensional entries from shape."""
203
204
def broadcast_to(array, shape, subok=False):
205
"""Broadcast array to given shape."""
206
207
def broadcast_arrays(*args, subok=False):
208
"""Broadcast arrays against each other."""
209
```
210
211
### Array Joining
212
213
Combine multiple arrays into single arrays along various axes.
214
215
```python { .api }
216
def concatenate(arrays, axis=0, out=None, dtype=None, casting='same_kind'):
217
"""Join arrays along existing axis."""
218
219
def stack(arrays, axis=0, out=None):
220
"""Join arrays along new axis."""
221
222
def hstack(tup):
223
"""Stack arrays horizontally (column wise)."""
224
225
def vstack(tup):
226
"""Stack arrays vertically (row wise)."""
227
228
def dstack(tup):
229
"""Stack arrays depth wise (along third axis)."""
230
231
def column_stack(tup):
232
"""Stack 1-D arrays as columns into 2-D array."""
233
234
def row_stack(tup):
235
"""Stack arrays vertically (same as vstack)."""
236
```
237
238
### Array Splitting
239
240
Split arrays into multiple sub-arrays along specified axes.
241
242
```python { .api }
243
def split(ary, indices_or_sections, axis=0):
244
"""Split array into multiple sub-arrays."""
245
246
def array_split(ary, indices_or_sections, axis=0):
247
"""Split array into multiple sub-arrays (allows unequal division)."""
248
249
def hsplit(ary, indices_or_sections):
250
"""Split array horizontally (column-wise)."""
251
252
def vsplit(ary, indices_or_sections):
253
"""Split array vertically (row-wise)."""
254
255
def dsplit(ary, indices_or_sections):
256
"""Split array depth-wise (along third axis)."""
257
```
258
259
### Array Tiling and Repetition
260
261
Duplicate array contents in various patterns.
262
263
```python { .api }
264
def tile(A, reps):
265
"""Construct array by repeating A given number of times."""
266
267
def repeat(a, repeats, axis=None):
268
"""Repeat elements of array."""
269
```
270
271
### Array Modification
272
273
Modify existing arrays by adding, removing, or changing elements.
274
275
```python { .api }
276
def append(arr, values, axis=None):
277
"""Append values to end of array."""
278
279
def resize(a, new_shape):
280
"""Return new array with specified shape."""
281
282
def unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None):
283
"""Find unique elements of array."""
284
285
def trim_zeros(filt, trim='fb'):
286
"""Trim leading and/or trailing zeros from 1-D array."""
287
```
288
289
### Array Rearrangement
290
291
Rearrange array elements in various patterns.
292
293
```python { .api }
294
def flip(m, axis=None):
295
"""Reverse order of elements along given axis."""
296
297
def fliplr(m):
298
"""Flip array left to right."""
299
300
def flipud(m):
301
"""Flip array up to down."""
302
303
def roll(a, shift, axis=None):
304
"""Roll array elements along given axis."""
305
306
def rot90(m, k=1, axes=(0, 1)):
307
"""Rotate array by 90 degrees in plane specified by axes."""
308
```
309
310
## Usage Examples
311
312
### Basic Array Creation
313
314
```python
315
import cupy as cp
316
317
# Create arrays from data
318
data = [1, 2, 3, 4, 5]
319
gpu_array = cp.array(data)
320
321
# Create initialized arrays
322
zeros_array = cp.zeros((3, 4))
323
ones_array = cp.ones((2, 3), dtype=cp.float32)
324
random_data = cp.random.random((1000, 1000))
325
326
# Create ranges
327
sequence = cp.arange(0, 10, 0.5)
328
linear_space = cp.linspace(0, 1, 100)
329
```
330
331
### Shape Manipulation
332
333
```python
334
# Reshape operations
335
original = cp.arange(12)
336
reshaped = original.reshape(3, 4)
337
flattened = reshaped.ravel()
338
339
# Transpose and axis operations
340
matrix = cp.random.random((3, 4, 5))
341
transposed = cp.transpose(matrix, (2, 0, 1))
342
swapped = cp.swapaxes(matrix, 0, 2)
343
```
344
345
### Array Joining and Splitting
346
347
```python
348
# Join arrays
349
a = cp.array([1, 2, 3])
350
b = cp.array([4, 5, 6])
351
joined = cp.concatenate([a, b])
352
stacked = cp.stack([a, b])
353
354
# Split arrays
355
data = cp.arange(10)
356
parts = cp.split(data, 5) # Split into 5 equal parts
357
```