or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-operations.mdcuda-integration.mdfft.mdindex.mdindexing-selection.mdinput-output.mdjit-kernels.mdlinear-algebra.mdlogic-operations.mdmathematical-functions.mdrandom-generation.mdscipy-extensions.mdstatistics.mdtesting.md

logic-operations.mddocs/

0

# Logic and Comparison Operations

1

2

Comprehensive logical operations, element-wise comparisons, truth value testing, and content validation functions for array processing and conditional operations. CuPy provides complete GPU implementations of logical and comparison operations with NumPy compatibility.

3

4

## Capabilities

5

6

### Element-wise Comparisons

7

8

Element-wise comparison operations returning boolean arrays for conditional processing.

9

10

```python { .api }

11

def equal(x1, x2, out=None, **kwargs):

12

"""Element-wise equality comparison.

13

14

Args:

15

x1: First input array

16

x2: Second input array

17

out: Output array

18

**kwargs: Additional ufunc parameters

19

20

Returns:

21

cupy.ndarray: Boolean array of equality results

22

"""

23

24

def not_equal(x1, x2, out=None, **kwargs):

25

"""Element-wise inequality comparison.

26

27

Args:

28

x1: First input array

29

x2: Second input array

30

out: Output array

31

**kwargs: Additional ufunc parameters

32

33

Returns:

34

cupy.ndarray: Boolean array of inequality results

35

"""

36

37

def less(x1, x2, out=None, **kwargs):

38

"""Element-wise less-than comparison.

39

40

Args:

41

x1: First input array

42

x2: Second input array

43

out: Output array

44

**kwargs: Additional ufunc parameters

45

46

Returns:

47

cupy.ndarray: Boolean array where x1 < x2

48

"""

49

50

def less_equal(x1, x2, out=None, **kwargs):

51

"""Element-wise less-than-or-equal comparison.

52

53

Args:

54

x1: First input array

55

x2: Second input array

56

out: Output array

57

**kwargs: Additional ufunc parameters

58

59

Returns:

60

cupy.ndarray: Boolean array where x1 <= x2

61

"""

62

63

def greater(x1, x2, out=None, **kwargs):

64

"""Element-wise greater-than comparison.

65

66

Args:

67

x1: First input array

68

x2: Second input array

69

out: Output array

70

**kwargs: Additional ufunc parameters

71

72

Returns:

73

cupy.ndarray: Boolean array where x1 > x2

74

"""

75

76

def greater_equal(x1, x2, out=None, **kwargs):

77

"""Element-wise greater-than-or-equal comparison.

78

79

Args:

80

x1: First input array

81

x2: Second input array

82

out: Output array

83

**kwargs: Additional ufunc parameters

84

85

Returns:

86

cupy.ndarray: Boolean array where x1 >= x2

87

"""

88

```

89

90

### Array Comparisons

91

92

Higher-level array comparison functions for testing array equality and similarity.

93

94

```python { .api }

95

def array_equal(a1, a2, equal_nan=False):

96

"""Test if two arrays are element-wise equal.

97

98

Args:

99

a1: First input array

100

a2: Second input array

101

equal_nan: Whether to compare NaN values as equal

102

103

Returns:

104

bool: True if arrays are equal

105

"""

106

107

def array_equiv(a1, a2):

108

"""Test if two arrays are equivalent (broadcastable and equal).

109

110

Args:

111

a1: First input array

112

a2: Second input array

113

114

Returns:

115

bool: True if arrays are equivalent

116

"""

117

118

def allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False):

119

"""Test if two arrays are element-wise equal within tolerance.

120

121

Args:

122

a: First input array

123

b: Second input array

124

rtol: Relative tolerance

125

atol: Absolute tolerance

126

equal_nan: Whether to compare NaN values as equal

127

128

Returns:

129

bool: True if arrays are close

130

"""

131

132

def isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False):

133

"""Element-wise test for closeness within tolerance.

134

135

Args:

136

a: First input array

137

b: Second input array

138

rtol: Relative tolerance

139

atol: Absolute tolerance

140

equal_nan: Whether to compare NaN values as equal

141

142

Returns:

143

cupy.ndarray: Boolean array of closeness results

144

"""

145

```

146

147

### Logical Operations

148

149

Element-wise logical operations for boolean algebra and conditional logic.

150

151

```python { .api }

152

def logical_and(x1, x2, out=None, **kwargs):

153

"""Element-wise logical AND operation.

154

155

Args:

156

x1: First input array

157

x2: Second input array

158

out: Output array

159

**kwargs: Additional ufunc parameters

160

161

Returns:

162

cupy.ndarray: Boolean array of AND results

163

"""

164

165

def logical_or(x1, x2, out=None, **kwargs):

166

"""Element-wise logical OR operation.

167

168

Args:

169

x1: First input array

170

x2: Second input array

171

out: Output array

172

**kwargs: Additional ufunc parameters

173

174

Returns:

175

cupy.ndarray: Boolean array of OR results

176

"""

177

178

def logical_not(x, out=None, **kwargs):

179

"""Element-wise logical NOT operation.

180

181

Args:

182

x: Input array

183

out: Output array

184

**kwargs: Additional ufunc parameters

185

186

Returns:

187

cupy.ndarray: Boolean array of NOT results

188

"""

189

190

def logical_xor(x1, x2, out=None, **kwargs):

191

"""Element-wise logical XOR operation.

192

193

Args:

194

x1: First input array

195

x2: Second input array

196

out: Output array

197

**kwargs: Additional ufunc parameters

198

199

Returns:

200

cupy.ndarray: Boolean array of XOR results

201

"""

202

```

203

204

### Truth Value Testing

205

206

Functions for testing truth values and array conditions across multiple elements.

207

208

```python { .api }

209

def all(a, axis=None, out=None, keepdims=False, where=None):

210

"""Test whether all elements evaluate to True.

211

212

Args:

213

a: Input array

214

axis: Axis along which to perform test

215

out: Output array

216

keepdims: Keep reduced dimensions as 1

217

where: Boolean array for selective testing

218

219

Returns:

220

cupy.ndarray or bool: Result of all-test

221

"""

222

223

def any(a, axis=None, out=None, keepdims=False, where=None):

224

"""Test whether any element evaluates to True.

225

226

Args:

227

a: Input array

228

axis: Axis along which to perform test

229

out: Output array

230

keepdims: Keep reduced dimensions as 1

231

where: Boolean array for selective testing

232

233

Returns:

234

cupy.ndarray or bool: Result of any-test

235

"""

236

237

def alltrue(a, axis=None, out=None, keepdims=False, where=None):

238

"""Test if all elements are True (alias for all)."""

239

240

def sometrue(a, axis=None, out=None, keepdims=False, where=None):

241

"""Test if any element is True (alias for any)."""

242

```

243

244

### Content Validation

245

246

Functions for validating array content and detecting special values.

247

248

```python { .api }

249

def isfinite(x, out=None, **kwargs):

250

"""Test for finite values (not infinity, not NaN).

251

252

Args:

253

x: Input array

254

out: Output array

255

**kwargs: Additional ufunc parameters

256

257

Returns:

258

cupy.ndarray: Boolean array indicating finite values

259

"""

260

261

def isinf(x, out=None, **kwargs):

262

"""Test for infinite values.

263

264

Args:

265

x: Input array

266

out: Output array

267

**kwargs: Additional ufunc parameters

268

269

Returns:

270

cupy.ndarray: Boolean array indicating infinite values

271

"""

272

273

def isnan(x, out=None, **kwargs):

274

"""Test for NaN (Not a Number) values.

275

276

Args:

277

x: Input array

278

out: Output array

279

**kwargs: Additional ufunc parameters

280

281

Returns:

282

cupy.ndarray: Boolean array indicating NaN values

283

"""

284

285

def isneginf(x, out=None):

286

"""Test for negative infinity values.

287

288

Args:

289

x: Input array

290

out: Output array

291

292

Returns:

293

cupy.ndarray: Boolean array indicating negative infinity

294

"""

295

296

def isposinf(x, out=None):

297

"""Test for positive infinity values.

298

299

Args:

300

x: Input array

301

out: Output array

302

303

Returns:

304

cupy.ndarray: Boolean array indicating positive infinity

305

"""

306

307

def isreal(x):

308

"""Test for real values (imaginary part is zero).

309

310

Args:

311

x: Input array

312

313

Returns:

314

cupy.ndarray: Boolean array indicating real values

315

"""

316

317

def iscomplex(x):

318

"""Test for complex values (imaginary part is non-zero).

319

320

Args:

321

x: Input array

322

323

Returns:

324

cupy.ndarray: Boolean array indicating complex values

325

"""

326

```

327

328

### Set Operations and Membership Testing

329

330

Functions for testing membership and performing set-like operations.

331

332

```python { .api }

333

def in1d(ar1, ar2, assume_unique=False, invert=False):

334

"""Test membership of elements in 1D arrays.

335

336

Args:

337

ar1: Input array

338

ar2: Values to test for membership

339

assume_unique: Assume input arrays contain unique elements

340

invert: Return complement of membership

341

342

Returns:

343

cupy.ndarray: Boolean array indicating membership

344

"""

345

346

def isin(element, test_elements, assume_unique=False, invert=False):

347

"""Test element membership in array.

348

349

Args:

350

element: Element or array to test

351

test_elements: Array of test values

352

assume_unique: Assume test_elements contains unique values

353

invert: Return complement of membership

354

355

Returns:

356

cupy.ndarray: Boolean array indicating membership

357

"""

358

359

def intersect1d(ar1, ar2, assume_unique=False, return_indices=False):

360

"""Find intersection of two 1D arrays.

361

362

Args:

363

ar1: First input array

364

ar2: Second input array

365

assume_unique: Assume input arrays are unique

366

return_indices: Return indices of intersection

367

368

Returns:

369

cupy.ndarray or tuple: Intersection values and optionally indices

370

"""

371

372

def setdiff1d(ar1, ar2, assume_unique=False):

373

"""Find set difference between two 1D arrays.

374

375

Args:

376

ar1: First input array

377

ar2: Second input array

378

assume_unique: Assume input arrays are unique

379

380

Returns:

381

cupy.ndarray: Values in ar1 but not in ar2

382

"""

383

384

def union1d(ar1, ar2):

385

"""Find union of two 1D arrays.

386

387

Args:

388

ar1: First input array

389

ar2: Second input array

390

391

Returns:

392

cupy.ndarray: Unique union values

393

"""

394

395

def setxor1d(ar1, ar2, assume_unique=False):

396

"""Find symmetric difference of two 1D arrays.

397

398

Args:

399

ar1: First input array

400

ar2: Second input array

401

assume_unique: Assume input arrays are unique

402

403

Returns:

404

cupy.ndarray: Values in either array but not both

405

"""

406

```

407

408

### Type Testing

409

410

Functions for testing array properties and data types.

411

412

```python { .api }

413

def isscalar(element):

414

"""Test if input is scalar type.

415

416

Args:

417

element: Input to test

418

419

Returns:

420

bool: True if input is scalar

421

"""

422

423

def isrealobj(x):

424

"""Test if input object has real data type.

425

426

Args:

427

x: Input object

428

429

Returns:

430

bool: True if object is real-valued

431

"""

432

433

def iscomplexobj(x):

434

"""Test if input object has complex data type.

435

436

Args:

437

x: Input object

438

439

Returns:

440

bool: True if object is complex-valued

441

"""

442

443

def isfortran(a):

444

"""Test if array is Fortran-contiguous.

445

446

Args:

447

a: Input array

448

449

Returns:

450

bool: True if array is Fortran-contiguous

451

"""

452

453

def issubdtype(arg1, arg2):

454

"""Test if data type is subtype of another.

455

456

Args:

457

arg1: First data type

458

arg2: Second data type

459

460

Returns:

461

bool: True if arg1 is subtype of arg2

462

"""

463

464

def issubclass_(arg1, arg2):

465

"""Test if class is subclass of another.

466

467

Args:

468

arg1: First class

469

arg2: Second class

470

471

Returns:

472

bool: True if arg1 is subclass of arg2

473

"""

474

475

def issubsctype(arg1, arg2):

476

"""Test if scalar type is subtype of another.

477

478

Args:

479

arg1: First scalar type

480

arg2: Second scalar type

481

482

Returns:

483

bool: True if arg1 is subtype of arg2

484

"""

485

```

486

487

### Bitwise Operations

488

489

Element-wise bitwise operations for integer arrays and boolean logic.

490

491

```python { .api }

492

def bitwise_and(x1, x2, out=None, **kwargs):

493

"""Element-wise bitwise AND operation.

494

495

Args:

496

x1: First input array

497

x2: Second input array

498

out: Output array

499

**kwargs: Additional ufunc parameters

500

501

Returns:

502

cupy.ndarray: Bitwise AND result

503

"""

504

505

def bitwise_or(x1, x2, out=None, **kwargs):

506

"""Element-wise bitwise OR operation.

507

508

Args:

509

x1: First input array

510

x2: Second input array

511

out: Output array

512

**kwargs: Additional ufunc parameters

513

514

Returns:

515

cupy.ndarray: Bitwise OR result

516

"""

517

518

def bitwise_xor(x1, x2, out=None, **kwargs):

519

"""Element-wise bitwise XOR operation.

520

521

Args:

522

x1: First input array

523

x2: Second input array

524

out: Output array

525

**kwargs: Additional ufunc parameters

526

527

Returns:

528

cupy.ndarray: Bitwise XOR result

529

"""

530

531

def bitwise_not(x, out=None, **kwargs):

532

"""Element-wise bitwise NOT operation.

533

534

Args:

535

x: Input array

536

out: Output array

537

**kwargs: Additional ufunc parameters

538

539

Returns:

540

cupy.ndarray: Bitwise NOT result

541

"""

542

543

def invert(x, out=None, **kwargs):

544

"""Bitwise inversion (alias for bitwise_not)."""

545

546

def left_shift(x1, x2, out=None, **kwargs):

547

"""Element-wise left bit shift.

548

549

Args:

550

x1: Input array

551

x2: Number of positions to shift

552

out: Output array

553

**kwargs: Additional ufunc parameters

554

555

Returns:

556

cupy.ndarray: Left-shifted values

557

"""

558

559

def right_shift(x1, x2, out=None, **kwargs):

560

"""Element-wise right bit shift.

561

562

Args:

563

x1: Input array

564

x2: Number of positions to shift

565

out: Output array

566

**kwargs: Additional ufunc parameters

567

568

Returns:

569

cupy.ndarray: Right-shifted values

570

"""

571

```

572

573

### Bit Packing and Manipulation

574

575

Functions for packing and manipulating bits within arrays.

576

577

```python { .api }

578

def packbits(a, axis=None, bitorder='big'):

579

"""Pack binary values into bytes.

580

581

Args:

582

a: Input array of binary values

583

axis: Axis along which to pack

584

bitorder: Bit order ('big' or 'little')

585

586

Returns:

587

cupy.ndarray: Packed byte array

588

"""

589

590

def unpackbits(a, axis=None, count=None, bitorder='big'):

591

"""Unpack bytes into binary values.

592

593

Args:

594

a: Input byte array

595

axis: Axis along which to unpack

596

count: Number of bits to unpack

597

bitorder: Bit order ('big' or 'little')

598

599

Returns:

600

cupy.ndarray: Unpacked binary array

601

"""

602

603

def binary_repr(num, width=None):

604

"""Return binary representation of number as string.

605

606

Args:

607

num: Input number

608

width: Minimum width of representation

609

610

Returns:

611

str: Binary representation

612

"""

613

```

614

615

## Usage Examples

616

617

### Basic Comparisons and Logic

618

619

```python

620

import cupy as cp

621

622

# Create test arrays

623

a = cp.array([1, 2, 3, 4, 5])

624

b = cp.array([3, 2, 1, 4, 6])

625

626

# Element-wise comparisons

627

equal_mask = cp.equal(a, b) # [False, True, False, True, False]

628

less_mask = cp.less(a, b) # [True, False, False, False, True]

629

greater_mask = cp.greater(a, b) # [False, False, True, False, False]

630

631

print(f"Equal: {equal_mask}")

632

print(f"Less: {less_mask}")

633

print(f"Greater: {greater_mask}")

634

635

# Logical operations

636

and_result = cp.logical_and(a > 2, b > 2) # [True, False, False, True, True]

637

or_result = cp.logical_or(a > 4, b > 4) # [False, False, False, True, True]

638

not_result = cp.logical_not(a > 3) # [True, True, True, False, False]

639

640

print(f"AND (a>2 & b>2): {and_result}")

641

print(f"OR (a>4 | b>4): {or_result}")

642

print(f"NOT (a>3): {not_result}")

643

644

# Truth value testing

645

all_positive = cp.all(a > 0) # True

646

any_greater_than_4 = cp.any(a > 4) # True

647

all_equal = cp.all(cp.equal(a, b)) # False

648

649

print(f"All positive: {all_positive}")

650

print(f"Any > 4: {any_greater_than_4}")

651

print(f"All equal: {all_equal}")

652

```

653

654

### Array Validation and Special Values

655

656

```python

657

import cupy as cp

658

659

# Create array with special values

660

data = cp.array([1.0, 2.0, cp.inf, cp.nan, -cp.inf, 0.0])

661

662

# Test for special values

663

finite_mask = cp.isfinite(data) # [True, True, False, False, False, True]

664

inf_mask = cp.isinf(data) # [False, False, True, False, True, False]

665

nan_mask = cp.isnan(data) # [False, False, False, True, False, False]

666

posinf_mask = cp.isposinf(data) # [False, False, True, False, False, False]

667

neginf_mask = cp.isneginf(data) # [False, False, False, False, True, False]

668

669

print(f"Original data: {data}")

670

print(f"Finite values: {finite_mask}")

671

print(f"Infinite values: {inf_mask}")

672

print(f"NaN values: {nan_mask}")

673

674

# Clean data by removing non-finite values

675

clean_data = data[cp.isfinite(data)]

676

print(f"Clean data: {clean_data}")

677

678

# Complex number testing

679

complex_array = cp.array([1+2j, 3+0j, 4-1j, 5])

680

real_mask = cp.isreal(complex_array) # [False, True, False, True]

681

complex_mask = cp.iscomplex(complex_array) # [True, False, True, False]

682

683

print(f"Complex array: {complex_array}")

684

print(f"Real elements: {real_mask}")

685

print(f"Complex elements: {complex_mask}")

686

```

687

688

### Set Operations and Membership

689

690

```python

691

import cupy as cp

692

693

# Set operations example

694

set1 = cp.array([1, 2, 3, 4, 5])

695

set2 = cp.array([3, 4, 5, 6, 7])

696

test_values = cp.array([1, 3, 6, 9])

697

698

# Membership testing

699

in_set1 = cp.isin(test_values, set1) # [True, True, False, False]

700

in_set2 = cp.isin(test_values, set2) # [False, True, True, False]

701

not_in_set1 = cp.isin(test_values, set1, invert=True) # [False, False, True, True]

702

703

print(f"Test values: {test_values}")

704

print(f"In set1: {in_set1}")

705

print(f"In set2: {in_set2}")

706

print(f"Not in set1: {not_in_set1}")

707

708

# Set operations

709

intersection = cp.intersect1d(set1, set2) # [3, 4, 5]

710

union = cp.union1d(set1, set2) # [1, 2, 3, 4, 5, 6, 7]

711

difference = cp.setdiff1d(set1, set2) # [1, 2]

712

symmetric_diff = cp.setxor1d(set1, set2) # [1, 2, 6, 7]

713

714

print(f"Set1: {set1}")

715

print(f"Set2: {set2}")

716

print(f"Intersection: {intersection}")

717

print(f"Union: {union}")

718

print(f"Difference (set1 - set2): {difference}")

719

print(f"Symmetric difference: {symmetric_diff}")

720

```

721

722

### Conditional Array Processing

723

724

```python

725

import cupy as cp

726

727

# Create sample data

728

temperature = cp.array([15.2, 22.1, 28.7, 31.4, 19.8, 25.3, 33.1, 18.9])

729

humidity = cp.array([65, 70, 45, 40, 80, 55, 35, 75])

730

pressure = cp.array([1013, 1018, 1020, 1015, 1010, 1022, 1025, 1012])

731

732

# Define comfort conditions

733

temp_comfort = cp.logical_and(temperature >= 20, temperature <= 30)

734

humidity_comfort = cp.logical_and(humidity >= 40, humidity <= 70)

735

pressure_comfort = cp.logical_and(pressure >= 1010, pressure <= 1025)

736

737

# Overall comfort condition

738

comfortable = cp.logical_and(cp.logical_and(temp_comfort, humidity_comfort),

739

pressure_comfort)

740

741

print(f"Temperature comfortable: {temp_comfort}")

742

print(f"Humidity comfortable: {humidity_comfort}")

743

print(f"Pressure comfortable: {pressure_comfort}")

744

print(f"Overall comfortable: {comfortable}")

745

746

# Count and extract comfortable conditions

747

comfort_count = cp.sum(comfortable)

748

comfort_indices = cp.where(comfortable)[0]

749

750

print(f"Number of comfortable readings: {comfort_count}")

751

print(f"Comfortable indices: {comfort_indices}")

752

753

# Statistical analysis of comfortable vs uncomfortable

754

if comfort_count > 0:

755

avg_temp_comfort = cp.mean(temperature[comfortable])

756

avg_temp_uncomfort = cp.mean(temperature[~comfortable])

757

758

print(f"Average temperature when comfortable: {avg_temp_comfort:.1f}°C")

759

print(f"Average temperature when uncomfortable: {avg_temp_uncomfort:.1f}°C")

760

```

761

762

### Advanced Logical Operations

763

764

```python

765

import cupy as cp

766

767

# Multi-dimensional logical operations

768

data = cp.random.randn(100, 50)

769

threshold = 2.0

770

771

# Find outliers (values beyond threshold standard deviations)

772

mean_vals = cp.mean(data, axis=0)

773

std_vals = cp.std(data, axis=0)

774

z_scores = cp.abs((data - mean_vals) / std_vals)

775

outliers = z_scores > threshold

776

777

# Count outliers per column

778

outlier_counts = cp.sum(outliers, axis=0)

779

columns_with_outliers = cp.any(outliers, axis=0)

780

781

print(f"Data shape: {data.shape}")

782

print(f"Columns with outliers: {cp.sum(columns_with_outliers)}")

783

print(f"Total outliers: {cp.sum(outliers)}")

784

print(f"Max outliers in single column: {cp.max(outlier_counts)}")

785

786

# Complex condition with multiple criteria

787

condition1 = data > 1.0 # Positive values above 1

788

condition2 = z_scores < 1.5 # Not too extreme

789

condition3 = cp.any(data > 0, axis=1, keepdims=True) # Row has positive values

790

791

# Combine conditions

792

complex_mask = cp.logical_and(cp.logical_and(condition1, condition2), condition3)

793

794

# Apply mask and compute statistics

795

filtered_data = cp.where(complex_mask, data, cp.nan)

796

valid_count = cp.sum(~cp.isnan(filtered_data), axis=0)

797

798

print(f"Valid values per column (min/max): {cp.min(valid_count)}/{cp.max(valid_count)}")

799

800

# Boolean indexing for advanced selection

801

high_variance_cols = std_vals > cp.median(std_vals)

802

stable_data = data[:, high_variance_cols]

803

stable_outliers = outliers[:, high_variance_cols]

804

805

print(f"High variance columns: {cp.sum(high_variance_cols)}")

806

print(f"Outliers in high variance data: {cp.sum(stable_outliers)}")

807

```

808

809

### Bitwise Operations

810

811

```python

812

import cupy as cp

813

814

# Bitwise operations on integers

815

a = cp.array([5, 3, 8, 1], dtype=cp.uint8) # Binary: [101, 011, 1000, 001]

816

b = cp.array([3, 5, 2, 7], dtype=cp.uint8) # Binary: [011, 101, 010, 111]

817

818

# Bitwise operations

819

and_result = cp.bitwise_and(a, b) # [1, 1, 0, 1]

820

or_result = cp.bitwise_or(a, b) # [7, 7, 10, 7]

821

xor_result = cp.bitwise_xor(a, b) # [6, 6, 10, 6]

822

not_a = cp.bitwise_not(a) # [250, 252, 247, 254] (8-bit complement)

823

824

print(f"a: {a} (binary: {[bin(x) for x in cp.asnumpy(a)]})")

825

print(f"b: {b} (binary: {[bin(x) for x in cp.asnumpy(b)]})")

826

print(f"a & b: {and_result}")

827

print(f"a | b: {or_result}")

828

print(f"a ^ b: {xor_result}")

829

print(f"~a: {not_a}")

830

831

# Bit shifting

832

left_shift = cp.left_shift(a, 2) # Multiply by 4

833

right_shift = cp.right_shift(a, 1) # Divide by 2

834

835

print(f"a << 2: {left_shift}")

836

print(f"a >> 1: {right_shift}")

837

838

# Bit packing/unpacking

839

binary_data = cp.array([0, 1, 1, 0, 1, 0, 0, 1], dtype=cp.uint8)

840

packed = cp.packbits(binary_data)

841

unpacked = cp.unpackbits(packed)

842

843

print(f"Binary data: {binary_data}")

844

print(f"Packed: {packed} (binary: {bin(cp.asnumpy(packed)[0])})")

845

print(f"Unpacked: {unpacked}")

846

847

# Using bitwise operations for flags

848

FLAG_READ = 1 # 001

849

FLAG_WRITE = 2 # 010

850

FLAG_EXECUTE = 4 # 100

851

852

permissions = cp.array([1, 3, 5, 7, 0, 6]) # Various permission combinations

853

854

# Test for specific permissions

855

can_read = cp.bitwise_and(permissions, FLAG_READ) != 0

856

can_write = cp.bitwise_and(permissions, FLAG_WRITE) != 0

857

can_execute = cp.bitwise_and(permissions, FLAG_EXECUTE) != 0

858

859

print(f"Permissions: {permissions}")

860

print(f"Can read: {can_read}")

861

print(f"Can write: {can_write}")

862

print(f"Can execute: {can_execute}")

863

864

# Set/unset permissions

865

new_permissions = cp.bitwise_or(permissions, FLAG_WRITE) # Add write

866

removed_execute = cp.bitwise_and(permissions, ~FLAG_EXECUTE) # Remove execute

867

868

print(f"With write permission: {new_permissions}")

869

print(f"Without execute permission: {removed_execute}")

870

```

871

872

### Performance Comparison and Validation

873

874

```python

875

import cupy as cp

876

import time

877

878

# Performance comparison of logical operations

879

n = 10_000_000

880

a = cp.random.rand(n) > 0.5 # Random boolean array

881

b = cp.random.rand(n) > 0.3 # Random boolean array

882

883

# Time logical operations

884

operations = [

885

('logical_and', lambda: cp.logical_and(a, b)),

886

('logical_or', lambda: cp.logical_or(a, b)),

887

('logical_not', lambda: cp.logical_not(a)),

888

('bitwise_and', lambda: cp.bitwise_and(a, b)),

889

('element_and', lambda: a & b),

890

('element_or', lambda: a | b),

891

]

892

893

print(f"Performance comparison on {n:,} elements:")

894

for name, operation in operations:

895

start_time = time.perf_counter()

896

result = operation()

897

cp.cuda.Stream.null.synchronize() # Ensure GPU completion

898

end_time = time.perf_counter()

899

900

print(f"{name:12}: {(end_time - start_time)*1000:.2f} ms")

901

902

# Validation of array equality methods

903

arr1 = cp.array([1.0, 2.0, 3.0, cp.nan])

904

arr2 = cp.array([1.0, 2.0, 3.0, cp.nan])

905

arr3 = cp.array([1.0, 2.0, 3.1, cp.nan])

906

907

print(f"\nArray equality validation:")

908

print(f"arr1 == arr2 (element-wise): {cp.equal(arr1, arr2)}")

909

print(f"array_equal(arr1, arr2): {cp.array_equal(arr1, arr2)}")

910

print(f"array_equal(arr1, arr2, equal_nan=True): {cp.array_equal(arr1, arr2, equal_nan=True)}")

911

print(f"allclose(arr1, arr3, atol=0.1): {cp.allclose(arr1, arr3, atol=0.1)}")

912

print(f"allclose(arr1, arr3, atol=0.05): {cp.allclose(arr1, arr3, atol=0.05)}")

913

```