or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-creation.mdarray-manipulation.mdcore-arrays.mdindex.mdio-conversion.mdlinear-algebra.mdmath-operations.mdreductions.md

array-creation.mddocs/

0

# Array Creation Functions

1

2

Functions for creating sparse arrays from various inputs, including construction of special matrices, conversion from dense arrays, and generation of arrays with specific patterns.

3

4

## Capabilities

5

6

### Basic Array Construction

7

8

Create sparse arrays with specific shapes and initial values.

9

10

```python { .api }

11

def asarray(obj, /, *, dtype=None, format="coo", copy=False, device=None):

12

"""

13

Convert input to sparse array.

14

15

Parameters:

16

- obj: array-like, input data (numpy array, list, existing sparse array)

17

- dtype: data type for result array

18

- format: str, output sparse format (default: "coo")

19

- copy: bool, whether to copy input data (default: False)

20

- device: str, device constraint (default: None)

21

22

Returns:

23

Sparse array representation of input

24

"""

25

26

def zeros(shape, dtype=float, format="coo", *, device=None, **kwargs):

27

"""

28

Create sparse array filled with zeros.

29

30

Parameters:

31

- shape: tuple, shape of output array

32

- dtype: data type for array elements

33

- format: str, sparse format (default: "coo")

34

- device: str, device constraint (default: None)

35

- **kwargs: additional format-specific arguments

36

37

Returns:

38

Sparse array of zeros with given shape

39

"""

40

41

def ones(shape, dtype=float, format="coo", *, device=None, **kwargs):

42

"""

43

Create sparse array filled with ones.

44

45

Parameters:

46

- shape: tuple, shape of output array

47

- dtype: data type for array elements

48

- format: str, sparse format (default: "coo")

49

- device: str, device constraint (default: None)

50

- **kwargs: additional format-specific arguments

51

52

Returns:

53

Sparse array of ones with given shape

54

"""

55

56

def full(shape, fill_value, dtype=None, format="coo", order="C", *, device=None, **kwargs):

57

"""

58

Create sparse array filled with specified value.

59

60

Parameters:

61

- shape: tuple, shape of output array

62

- fill_value: scalar, value to fill array with

63

- dtype: data type for array elements

64

- format: str, sparse format (default: "coo")

65

- order: str, memory layout order (default: "C")

66

- device: str, device constraint (default: None)

67

- **kwargs: additional format-specific arguments

68

69

Returns:

70

Sparse array filled with fill_value

71

"""

72

73

def empty(shape, dtype=float, format="coo", *, device=None, **kwargs):

74

"""

75

Create uninitialized sparse array.

76

77

Parameters:

78

- shape: tuple, shape of output array

79

- dtype: data type for array elements

80

- format: str, sparse format (default: "coo")

81

- device: str, device constraint (default: None)

82

- **kwargs: additional format-specific arguments

83

84

Returns:

85

Empty sparse array with given shape

86

"""

87

```

88

89

### Template Array Creation

90

91

Create arrays with the same shape and properties as existing arrays.

92

93

```python { .api }

94

def zeros_like(a, dtype=None, shape=None, format=None, *, device=None, **kwargs):

95

"""

96

Create sparse array of zeros with same shape as input.

97

98

Parameters:

99

- a: sparse array, template for shape and properties

100

- dtype: data type, defaults to same as input array

101

- shape: tuple, override shape (default: None, use input shape)

102

- format: str, output format (default: None, use input format)

103

- device: str, device constraint (default: None)

104

- **kwargs: additional format-specific arguments

105

106

Returns:

107

Sparse array of zeros matching input shape

108

"""

109

110

def ones_like(a, dtype=None, shape=None, format=None, *, device=None, **kwargs):

111

"""

112

Create sparse array of ones with same shape as input.

113

114

Parameters:

115

- a: sparse array, template for shape and properties

116

- dtype: data type, defaults to same as input array

117

- shape: tuple, override shape (default: None, use input shape)

118

- format: str, output format (default: None, use input format)

119

- device: str, device constraint (default: None)

120

- **kwargs: additional format-specific arguments

121

122

Returns:

123

Sparse array of ones matching input shape

124

"""

125

126

def full_like(a, fill_value, dtype=None, shape=None, format=None, *, device=None, **kwargs):

127

"""

128

Create sparse array filled with value, same shape as input.

129

130

Parameters:

131

- a: sparse array, template for shape and properties

132

- fill_value: scalar, value to fill array with

133

- dtype: data type, defaults to same as input array

134

- shape: tuple, override shape (default: None, use input shape)

135

- format: str, output format (default: None, use input format)

136

- device: str, device constraint (default: None)

137

- **kwargs: additional format-specific arguments

138

139

Returns:

140

Sparse array filled with fill_value matching input shape

141

"""

142

143

def empty_like(a, dtype=None, shape=None, format=None, *, device=None, **kwargs):

144

"""

145

Create uninitialized sparse array with same shape as input.

146

147

Parameters:

148

- a: sparse array, template for shape and properties

149

- dtype: data type, defaults to same as input array

150

- shape: tuple, override shape (default: None, use input shape)

151

- format: str, output format (default: None, use input format)

152

- device: str, device constraint (default: None)

153

- **kwargs: additional format-specific arguments

154

155

Returns:

156

Empty sparse array matching input shape

157

"""

158

```

159

160

### Special Matrix Creation

161

162

Create commonly used mathematical matrices in sparse format.

163

164

```python { .api }

165

def eye(N, M=None, k=0, dtype=float, format="coo", *, device=None, **kwargs):

166

"""

167

Create sparse identity matrix.

168

169

Parameters:

170

- N: int, number of rows

171

- M: int, number of columns (defaults to N for square matrix)

172

- k: int, diagonal offset (0=main diagonal, >0=upper, <0=lower)

173

- dtype: data type for matrix elements

174

- format: str, sparse format (default: "coo")

175

- device: str, device constraint (default: None)

176

- **kwargs: additional format-specific arguments

177

178

Returns:

179

Sparse identity matrix with ones on specified diagonal

180

"""

181

```

182

183

### Random Array Generation

184

185

Generate sparse arrays with random values and sparsity patterns.

186

187

```python { .api }

188

def random(shape, density=None, nnz=None, random_state=None, data_rvs=None, format="coo", fill_value=None, idx_dtype=None, **kwargs):

189

"""

190

Generate sparse array with random values.

191

192

Parameters:

193

- shape: tuple, shape of output array

194

- density: float, fraction of elements to be non-zero (default: 0.01 when nnz not specified)

195

- nnz: int, exact number of non-zero elements (mutually exclusive with density)

196

- random_state: int or RandomState, seed for reproducible generation

197

- data_rvs: callable, function to generate random values (default: uniform [0,1))

198

- format: str, output format (default: "coo")

199

- fill_value: scalar, fill value for the array (default: None)

200

- idx_dtype: dtype, data type for indices (default: None)

201

- **kwargs: additional format-specific arguments

202

203

Returns:

204

Sparse array with random non-zero elements at random positions

205

"""

206

```

207

208

### Format Conversion Functions

209

210

Convert arrays to specific sparse formats.

211

212

```python { .api }

213

def as_coo(x, shape=None, fill_value=None, idx_dtype=None):

214

"""

215

Convert input to COO format sparse array.

216

217

Parameters:

218

- x: array-like, input to convert (SparseArray, numpy.ndarray, scipy.sparse, Iterable)

219

- shape: tuple, shape of output array (default: None, infer from input)

220

- fill_value: scalar, fill value (default: None)

221

- idx_dtype: dtype, data type for indices (default: None)

222

223

Returns:

224

COO format sparse array

225

"""

226

227

def asCOO(x):

228

"""

229

Alias for as_coo - convert input to COO format.

230

231

Parameters:

232

- x: array-like, input to convert

233

234

Returns:

235

COO format sparse array

236

"""

237

```

238

239

## Usage Examples

240

241

### Basic Array Creation

242

243

```python

244

import sparse

245

import numpy as np

246

247

# Create arrays with specific values

248

zeros_array = sparse.zeros((100, 100)) # 100x100 zeros

249

ones_array = sparse.ones((50, 50), dtype=int) # 50x50 ones

250

full_array = sparse.full((10, 20), 3.14) # 10x20 filled with pi

251

252

# Create identity matrices

253

identity = sparse.eye(5) # 5x5 identity

254

rectangular_eye = sparse.eye(3, 5, k=1) # 3x5 with ones on super-diagonal

255

256

print(f"Identity matrix shape: {identity.shape}")

257

print(f"Identity nnz: {identity.nnz}") # 5 non-zero elements

258

```

259

260

### Template-Based Creation

261

262

```python

263

# Create template array

264

template = sparse.random((20, 30), density=0.1)

265

266

# Create arrays matching template shape

267

template_zeros = sparse.zeros_like(template)

268

template_ones = sparse.ones_like(template, dtype=int)

269

template_full = sparse.full_like(template, -1.5)

270

271

print(f"All arrays have shape: {template.shape}")

272

print(f"Template zeros nnz: {template_zeros.nnz}") # 0

273

print(f"Template ones nnz: {template_ones.nnz}") # 600 (20*30)

274

```

275

276

### Random Array Generation

277

278

```python

279

# Generate random sparse arrays with different densities

280

sparse_1_percent = sparse.random((1000, 1000), density=0.01, random_state=42)

281

sparse_10_percent = sparse.random((100, 100), density=0.1, dtype=int)

282

283

print(f"1% density array - nnz: {sparse_1_percent.nnz}") # ~10,000

284

print(f"10% density array - nnz: {sparse_10_percent.nnz}") # ~1,000

285

286

# Reproducible random generation

287

rng_array1 = sparse.random((50, 50), density=0.05, random_state=123)

288

rng_array2 = sparse.random((50, 50), density=0.05, random_state=123)

289

print(f"Arrays are identical: {np.array_equal(rng_array1.data, rng_array2.data)}")

290

```

291

292

### Conversion from Dense Arrays

293

294

```python

295

# Convert NumPy arrays to sparse

296

dense_matrix = np.array([[1, 0, 3], [0, 2, 0], [4, 0, 0]])

297

sparse_matrix = sparse.asarray(dense_matrix)

298

299

# Convert with specific data type

300

sparse_int = sparse.asarray(dense_matrix, dtype=np.int32)

301

302

print(f"Original density: {np.count_nonzero(dense_matrix) / dense_matrix.size:.1%}")

303

print(f"Sparse nnz: {sparse_matrix.nnz}")

304

print(f"Sparse density: {sparse_matrix.density:.1%}")

305

```

306

307

### Format-Specific Creation

308

309

```python

310

# Create in specific formats

311

coo_array = sparse.as_coo([[1, 0], [0, 2]]) # Force COO format

312

also_coo = sparse.asCOO([[1, 0], [0, 2]]) # Alternative name

313

314

# Random arrays in different formats

315

random_coo = sparse.random((100, 100), format='coo', density=0.05)

316

random_gcxs = sparse.random((100, 100), format='gcxs', density=0.05)

317

318

print(f"COO format: {type(random_coo).__name__}")

319

print(f"GCXS format: {type(random_gcxs).__name__}")

320

```

321

322

## Performance Considerations

323

324

- **zeros()**: Creates truly sparse arrays with no stored elements

325

- **ones()** and **full()**: May create dense storage for non-zero fill values

326

- **random()**: Density parameter controls memory usage and performance

327

- **eye()**: Highly efficient - stores only diagonal elements

328

- **Template functions**: Inherit sparsity structure from input arrays when possible