or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

components.mdcore-viewer.mdindex.mdlayers.mdqt-interface.mdtypes.mdutilities.md

utilities.mddocs/

0

# Utilities

1

2

Napari utilities provide essential helper functions and classes for colormaps, progress tracking, system information, notifications, and other supporting functionality that enhances the user experience and developer workflow.

3

4

## Capabilities

5

6

### Colormap Management

7

8

Classes and functions for managing colormaps used in data visualization, supporting both continuous and discrete color mapping schemes.

9

10

```python { .api }

11

class Colormap:

12

"""

13

Colormap class for continuous data visualization.

14

Supports custom color definitions and interpolation.

15

"""

16

17

def __init__(

18

self,

19

colors,

20

*,

21

name: str = None,

22

interpolation: str = 'linear'

23

):

24

"""

25

Create a colormap.

26

27

Parameters:

28

- colors: Color definitions (list of colors or array)

29

- name: Colormap name

30

- interpolation: Interpolation method ('linear', 'zero')

31

"""

32

33

def map(self, values):

34

"""

35

Apply colormap to data values.

36

37

Parameters:

38

- values: Array of values to map

39

40

Returns:

41

Array of RGBA colors

42

"""

43

44

class DirectLabelColormap:

45

"""

46

Colormap for direct label-to-color mapping.

47

Maps integer labels directly to specific colors.

48

"""

49

50

def __init__(self, color_dict: dict):

51

"""

52

Create direct label colormap.

53

54

Parameters:

55

- color_dict: Dictionary mapping labels to colors

56

"""

57

58

class CyclicLabelColormap:

59

"""

60

Colormap that cycles through colors for label data.

61

Automatically assigns colors to labels in sequence.

62

"""

63

64

def __init__(

65

self,

66

colors,

67

*,

68

seed: float = 0.5,

69

shuffle: bool = True

70

):

71

"""

72

Create cyclic label colormap.

73

74

Parameters:

75

- colors: List of colors to cycle through

76

- seed: Random seed for color generation

77

- shuffle: Whether to shuffle color order

78

"""

79

```

80

81

### Progress Indicators

82

83

Functions and context managers for displaying progress information during long-running operations.

84

85

```python { .api }

86

def progress(

87

iterable=None,

88

*,

89

desc: str = None,

90

total: int = None,

91

nest_under=None,

92

**kwargs

93

):

94

"""

95

Create a progress indicator for iterables or manual updates.

96

97

Parameters:

98

- iterable: Iterable to wrap with progress tracking

99

- desc: Description text for progress bar

100

- total: Total number of items (if not using iterable)

101

- nest_under: Parent progress bar for nested progress

102

- kwargs: Additional progress bar parameters

103

104

Returns:

105

Progress context manager or wrapped iterable

106

"""

107

108

def progrange(

109

stop,

110

start: int = 0,

111

step: int = 1,

112

*,

113

desc: str = None,

114

**kwargs

115

):

116

"""

117

Create a progress-wrapped range iterator.

118

119

Parameters:

120

- stop: End value for range

121

- start: Start value for range

122

- step: Step size for range

123

- desc: Progress description

124

- kwargs: Additional progress parameters

125

126

Returns:

127

Progress-wrapped range iterator

128

"""

129

130

def cancelable_progress(

131

iterable=None,

132

*,

133

desc: str = None,

134

total: int = None,

135

**kwargs

136

):

137

"""

138

Create a cancelable progress indicator.

139

Allows users to cancel long-running operations.

140

141

Parameters:

142

- iterable: Iterable to wrap

143

- desc: Progress description

144

- total: Total items count

145

- kwargs: Additional parameters

146

147

Returns:

148

Cancelable progress context manager

149

"""

150

```

151

152

### System Information

153

154

Functions for retrieving and displaying system and environment information useful for debugging and support.

155

156

```python { .api }

157

def sys_info():

158

"""

159

Get comprehensive system information.

160

161

Returns:

162

str: Formatted system information including:

163

- Python and napari versions

164

- Operating system details

165

- Qt backend information

166

- Graphics and display details

167

- Installed packages and dependencies

168

"""

169

170

def citation_text():

171

"""

172

Get citation information for napari.

173

174

Returns:

175

str: Formatted citation text for academic use

176

"""

177

```

178

179

### Notebook Integration

180

181

Utilities for working with napari in Jupyter notebooks and other interactive environments.

182

183

```python { .api }

184

class NotebookScreenshot:

185

"""

186

Class for managing screenshot display in Jupyter notebooks.

187

Handles image formatting and display optimization.

188

"""

189

190

def __init__(self, viewer, *, canvas_only: bool = True):

191

"""

192

Create notebook screenshot handler.

193

194

Parameters:

195

- viewer: Napari viewer instance

196

- canvas_only: Whether to capture only canvas or full window

197

"""

198

199

def _repr_png_(self):

200

"""PNG representation for notebook display."""

201

202

def _repr_jpeg_(self):

203

"""JPEG representation for notebook display."""

204

205

def nbscreenshot(

206

viewer,

207

*,

208

canvas_only: bool = True,

209

**kwargs

210

):

211

"""

212

Take a screenshot optimized for notebook display.

213

214

Parameters:

215

- viewer: Napari viewer instance

216

- canvas_only: Capture canvas only or full window

217

- kwargs: Additional screenshot parameters

218

219

Returns:

220

NotebookScreenshot: Screenshot object for notebook display

221

"""

222

```

223

224

### Memory and Performance

225

226

Utilities for managing memory usage and performance optimization, particularly for large dataset handling.

227

228

```python { .api }

229

def resize_dask_cache(nbytes: str = None):

230

"""

231

Resize the dask cache for improved memory management.

232

233

Parameters:

234

- nbytes: Cache size specification (e.g., '2GB', '512MB')

235

"""

236

```

237

238

### Notifications and Messaging

239

240

System for managing user notifications, warnings, and error messages throughout the napari interface.

241

242

```python { .api }

243

notification_manager

244

"""

245

Global notification manager instance for dispatching and handling notifications.

246

Provides centralized management of info, warning, error, and debug messages.

247

"""

248

```

249

250

### Threading Support

251

252

Constants and utilities related to threading and concurrent processing.

253

254

```python { .api }

255

NUMPY_VERSION_IS_THREADSAFE: bool

256

"""

257

Boolean indicating whether the current NumPy version is thread-safe.

258

Used to determine if threading optimizations can be safely enabled.

259

"""

260

```

261

262

## Usage Examples

263

264

### Colormap Usage

265

266

```python

267

import napari

268

import numpy as np

269

270

# Create custom colormap

271

from napari.utils import Colormap

272

273

# Define custom colors (red to blue)

274

custom_colors = ['red', 'yellow', 'blue']

275

custom_cmap = Colormap(custom_colors, name='custom')

276

277

# Create data and viewer

278

data = np.random.random((100, 100))

279

viewer = napari.Viewer()

280

viewer.add_image(data, colormap=custom_cmap, name='Custom Colors')

281

282

# Use direct label colormap

283

labels = np.zeros((100, 100), dtype=int)

284

labels[25:75, 25:75] = 1

285

labels[10:40, 60:90] = 2

286

287

from napari.utils import DirectLabelColormap

288

label_colors = {0: 'black', 1: 'red', 2: 'blue'}

289

label_cmap = DirectLabelColormap(label_colors)

290

291

viewer.add_labels(labels, colormap=label_cmap, name='Direct Labels')

292

```

293

294

### Progress Tracking

295

296

```python

297

import napari

298

import numpy as np

299

import time

300

301

# Progress with iterable

302

data_list = []

303

for i in napari.utils.progrange(10, desc="Generating data"):

304

# Simulate work

305

time.sleep(0.1)

306

data_list.append(np.random.random((50, 50)))

307

308

# Manual progress updates

309

with napari.utils.progress(total=100, desc="Processing") as pbar:

310

for i in range(100):

311

# Simulate work

312

time.sleep(0.01)

313

pbar.update(1)

314

315

# Cancelable progress

316

def long_computation():

317

results = []

318

for i in napari.utils.cancelable_progress(

319

range(1000),

320

desc="Long computation"

321

):

322

# Simulate expensive operation

323

time.sleep(0.01)

324

results.append(i * 2)

325

326

# Check if cancelled

327

if i > 100: # User can cancel via GUI

328

break

329

return results

330

331

# results = long_computation()

332

```

333

334

### System Information

335

336

```python

337

import napari

338

339

# Get system information

340

info = napari.utils.sys_info()

341

print(info)

342

343

# Get citation information

344

citation = napari.utils.citation_text()

345

print(citation)

346

```

347

348

### Notebook Integration

349

350

```python

351

# In Jupyter notebook

352

import napari

353

import numpy as np

354

355

# Create viewer and data

356

data = np.random.random((100, 100))

357

viewer = napari.Viewer()

358

viewer.add_image(data, name='Sample')

359

360

# Take screenshot for notebook display

361

screenshot = napari.utils.nbscreenshot(viewer, canvas_only=True)

362

363

# Display in notebook (automatically calls _repr_png_)

364

screenshot

365

```

366

367

### Notifications Usage

368

369

```python

370

import napari

371

372

# Access the global notification manager

373

manager = napari.notification_manager

374

375

# The notification manager handles system-wide messages

376

# and is used internally by napari for error reporting

377

# and user feedback

378

```

379

380

### Memory Management

381

382

```python

383

import napari

384

import numpy as np

385

386

# Configure dask cache for large datasets

387

napari.utils.resize_dask_cache('2GB')

388

389

# Create large dataset

390

large_data = np.random.random((1000, 1000, 100))

391

392

# Create viewer

393

viewer = napari.Viewer()

394

viewer.add_image(large_data, name='Large Dataset')

395

396

# Check if NumPy threading is safe

397

if napari.utils.NUMPY_VERSION_IS_THREADSAFE:

398

print("NumPy threading optimizations available")

399

else:

400

print("Using single-threaded NumPy operations")

401

```

402

403

### Integrated Workflow Example

404

405

```python

406

import napari

407

import numpy as np

408

import time

409

410

# Setup memory management

411

napari.utils.resize_dask_cache('1GB')

412

413

# Create viewer

414

viewer = napari.Viewer(title='Analysis Pipeline')

415

416

# Generate data with progress tracking

417

datasets = []

418

for i in napari.utils.progrange(5, desc="Loading datasets"):

419

# Simulate loading data

420

time.sleep(0.2)

421

data = np.random.random((100, 100)) + i * 0.1

422

datasets.append(data)

423

424

# Process data with cancelable progress

425

processed_data = []

426

with napari.utils.cancelable_progress(

427

datasets,

428

desc="Processing datasets"

429

) as pdata:

430

for i, data in enumerate(pdata):

431

# Add to viewer

432

viewer.add_image(data, name=f'Dataset {i}')

433

434

# Simulate processing

435

time.sleep(0.1)

436

processed = data * 2

437

processed_data.append(processed)

438

439

# Create custom colormap for final result

440

from napari.utils import Colormap

441

result_cmap = Colormap(['black', 'red', 'yellow', 'white'], name='heat')

442

443

# Add final processed result

444

final_result = np.mean(processed_data, axis=0)

445

viewer.add_image(final_result, colormap=result_cmap, name='Final Result')

446

447

# Take screenshot for documentation

448

screenshot = napari.utils.nbscreenshot(viewer)

449

450

# Print system info for debugging

451

print("System Information:")

452

print(napari.utils.sys_info())

453

454

napari.run()

455

```