Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

#!/usr/bin/env python 

# -*- coding: UTF-8 -*- 

# 

# Copyright 2014-2019European Commission (JRC); 

# Licensed under the EUPL (the 'Licence'); 

# You may not use this work except in compliance with the Licence. 

# You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl 

""" 

The algorithmic part of :term:`capturing`. 

 

Prefer accessing the public members from the parent module. 

""" 

 

import logging 

from string import ascii_uppercase 

 

import numpy as np 

 

from . import Coords, _parse 

from ._parse import Cell 

 

 

log = logging.getLogger(__name__) 

 

try: 

from xlrd import colname as xl_colname 

 

# TODO: Try different backends providing `colname` function. 

except ImportError: 

log.warning("One of `xlrd`, `...` libraries is needed, will crash later!") 

 

 

CHECK_CELLTYPE = False 

"""When `True`, most coord-functions accept any 2-tuples.""" 

 

 

class EmptyCaptureException(Exception): 

""" 

Thrown when :term:`targeting` fails. 

""" 

 

 

_special_coord_symbols = {"^", "_", "."} 

 

_primitive_dir_vectors = { 

"L": Coords(0, -1), 

"U": Coords(-1, 0), 

"R": Coords(0, 1), 

"D": Coords(1, 0), 

} 

 

 

def coords2Cell(row, col): 

"""Make *A1* :class:`Cell` from *resolved* coords, with rudimentary error-checking. 

 

Examples:: 

 

>>> coords2Cell(row=0, col=0) 

Cell(row='1', col='A') 

>>> coords2Cell(row=0, col=26) 

Cell(row='1', col='AA') 

 

>>> coords2Cell(row=10, col='.') 

Cell(row='11', col='.') 

 

>>> coords2Cell(row=-3, col=-2) 

Traceback (most recent call last): 

AssertionError: negative row! 

 

 

""" 

if row not in _special_coord_symbols: 

assert row >= 0, "negative row!" 

row = str(row + 1) 

if col not in _special_coord_symbols: 

assert col >= 0, "negative col!" 

col = xl_colname(col) 

return Cell(row=row, col=col) 

 

 

def _row2num(coord): 

""" 

Resolves special coords or converts Excel 1-based rows to zero-based, reporting invalids. 

 

:param str, int coord: excel-row coordinate or one of ``^_.`` 

:return: excel row number, >= 0 

:rtype: int 

 

Examples:: 

 

>>> row = _row2num('1') 

>>> row 

0 

>>> row == _row2num(1) 

True 

 

Negatives (from bottom) are preserved:: 

 

>>> _row2num('-1') 

-1 

 

Fails ugly:: 

 

>>> _row2num('.') 

Traceback (most recent call last): 

ValueError: invalid literal for int() with base 10: '.' 

""" 

rcoord = int(coord) 

if rcoord == 0: 

msg = "Uncooked-coord cannot be zero!" 

raise ValueError(msg.format(coord)) 

if rcoord > 0: 

rcoord -= 1 

 

return rcoord 

 

 

def _col2num(coord): 

""" 

Resolves special coords or converts Excel A1 columns to a zero-based, reporting invalids. 

 

:param str coord: excel-column coordinate or one of ``^_.`` 

:return: excel column number, >= 0 

:rtype: int 

 

Examples:: 

 

>>> col = _col2num('D') 

>>> col 

3 

>>> _col2num('d') == col 

True 

>>> _col2num('AaZ') 

727 

>>> _col2num('10') 

9 

>>> _col2num(9) 

8 

 

Negatives (from left-end) are preserved:: 

 

>>> _col2num('AaZ') 

727 

 

Fails ugly:: 

 

>>> _col2num('%$') 

Traceback (most recent call last): 

ValueError: substring not found 

 

>>> _col2num([]) 

Traceback (most recent call last): 

TypeError: int() argument must be a string, a bytes-like object or 

a number, not 'list' 

 

""" 

try: 

rcoord = int(coord) 

except ValueError: 

rcoord = 0 

for c in coord: 

rcoord = rcoord * 26 + ascii_uppercase.rindex(c.upper()) + 1 

 

rcoord -= 1 

else: 

if rcoord == 0: 

msg = "Uncooked-coord cannot be zero!" 

raise ValueError(msg.format(coord)) 

elif rcoord > 0: 

rcoord -= 1 

 

return rcoord 

 

 

def _resolve_coord(cname, cfunc, coord, up_coord, dn_coord, base_coords=None): 

""" 

Translates special coords or converts Excel string 1-based rows/cols to zero-based, reporting invalids. 

 

:param str cname: 

the coord-name, one of 'row', 'column' 

:param function cfunc: 

the function to convert coord ``str --> int`` 

:param int, str coord: 

the "A1" coord to translate 

:param int up_coord: 

the resolved *top* or *left* margin zero-based coordinate 

:param int dn_coord: 

the resolved *bottom* or *right* margin zero-based coordinate 

:param int, None base_coords: 

the resolved basis for dependent coord, if any 

 

:return: the resolved coord or `None` if it were not a special coord. 

 

 

Row examples:: 

 

>>> cname = 'row' 

 

>>> r0 = _resolve_coord(cname, _row2num, '1', 1, 10) 

>>> r0 

0 

>>> r0 == _resolve_coord(cname, _row2num, 1, 1, 10) 

True 

>>> _resolve_coord(cname, _row2num, '^', 1, 10) 

1 

>>> _resolve_coord(cname, _row2num, '_', 1, 10) 

10 

>>> _resolve_coord(cname, _row2num, '.', 1, 10, 13) 

13 

>>> _resolve_coord(cname, _row2num, '-3', 0, 10) 

8 

 

But notice when base-cell missing:: 

 

>>> _resolve_coord(cname, _row2num, '.', 0, 10, base_coords=None) 

Traceback (most recent call last): 

ValueError: Cannot resolve `relative-row` without `base-coord`! 

 

Other ROW error-checks:: 

 

>>> _resolve_coord(cname, _row2num, '0', 0, 10) 

Traceback (most recent call last): 

ValueError: invalid row('0') due to: Uncooked-coord cannot be zero! 

 

>>> _resolve_coord(cname, _row2num, 'a', 0, 10) 

Traceback (most recent call last): 

ValueError: invalid row('a') due to: invalid literal for int() with base 10: 'a' 

 

>>> _resolve_coord(cname, _row2num, None, 0, 10) 

Traceback (most recent call last): 

ValueError: invalid row(None) due to: 

int() argument must be a string, 

a bytes-like object or a number, not 'NoneType' 

 

 

Column examples:: 

 

>>> cname = 'column' 

 

>>> _resolve_coord(cname, _col2num, 'A', 1, 10) 

0 

>>> _resolve_coord(cname, _col2num, 'DADA', 1, 10) 

71084 

>>> _resolve_coord(cname, _col2num, '.', 1, 10, 13) 

13 

>>> _resolve_coord(cname, _col2num, '-4', 0, 10) 

7 

 

And COLUMN error-checks:: 

 

>>> _resolve_coord(cname, _col2num, None, 0, 10) 

Traceback (most recent call last): 

ValueError: invalid column(None) due to: int() argument must be a string, 

a bytes-like object or a number, not 'NoneType' 

 

>>> _resolve_coord(cname, _col2num, 0, 0, 10) 

Traceback (most recent call last): 

ValueError: invalid column(0) due to: Uncooked-coord cannot be zero! 

 

""" 

try: 

if coord in _special_coord_symbols: 

special_dict = {"^": up_coord, "_": dn_coord} 

if base_coords is not None: 

special_dict["."] = base_coords 

rcoord = special_dict[coord] 

else: 

rcoord = cfunc(coord) 

 

# Resolve negatives as from the end. 

if rcoord < 0: 

rcoord = dn_coord + rcoord + 1 

 

return rcoord 

except Exception as ex: 

if isinstance(ex, KeyError) and ex.args == (".",): 

msg = "Cannot resolve `relative-{}` without `base-coord`!" 

raise ValueError(msg.format(cname)) 

msg = "invalid {}({!r}) due to: {}" 

raise ValueError(msg.format(cname, coord, ex)) from ex 

 

 

def _resolve_cell(cell, up_coords, dn_coords, base_coords=None): 

""" 

Translates any special coords to absolute ones. 

 

To get the margin_coords, use one of: 

 

* :meth:`ABCSheet.get_margin_coords()` 

* :func:`.io.backend.margin_coords_from_states_matrix()` 

 

:param Cell cell: 

The "A1" cell to translate its coords. 

:param Coords up_coords: 

the top-left resolved coords with full-cells 

:param Coords dn_coords: 

the bottom-right resolved coords with full-cells 

:param Coords base_coords: 

A resolved cell to base dependent coords (``.``). 

:return: the resolved cell-coords 

:rtype: Coords 

 

 

Examples:: 

 

>>> up = Coords(1, 2) 

>>> dn = Coords(10, 6) 

>>> base = Coords(40, 50) 

 

>>> _resolve_cell(Cell(col='B', row='5'), up, dn) 

Coords(row=4, col=1) 

 

>>> _resolve_cell(Cell('^', '^'), up, dn) 

Coords(row=1, col=2) 

 

>>> _resolve_cell(Cell('_', '_'), up, dn) 

Coords(row=10, col=6) 

 

>>> base == _resolve_cell(Cell('.', '.'), up, dn, base) 

True 

 

>>> _resolve_cell(Cell('-1', '-2'), up, dn) 

Coords(row=10, col=5) 

 

>>> _resolve_cell(Cell('A', 'B'), up, dn) 

Traceback (most recent call last): 

ValueError: invalid cell(Cell(row='A', col='B')) due to: 

invalid row('A') due to: invalid literal for int() with base 10: 'A' 

 

But notice when base-cell missing:: 

 

>>> _resolve_cell(Cell('1', '.'), up, dn) 

Traceback (most recent call last): 

ValueError: invalid cell(Cell(row='1', col='.')) due to: 

Cannot resolve `relative-col` without `base-coord`! 

 

""" 

assert not CHECK_CELLTYPE or isinstance(cell, Cell), cell 

assert not CHECK_CELLTYPE or isinstance(up_coords, Coords), up_coords 

assert not CHECK_CELLTYPE or isinstance(dn_coords, Coords), dn_coords 

try: 

if base_coords is None: 

base_row = base_col = None 

else: 

base_row, base_col = base_coords 

row = _resolve_coord( 

"row", _row2num, cell.row, up_coords[0], dn_coords[0], base_row 

) 

col = _resolve_coord( 

"col", _col2num, cell.col, up_coords[1], dn_coords[1], base_col 

) 

 

return Coords(row, col) 

except Exception as ex: 

msg = "invalid cell(%r) due to: %s\n margins(%r)\n base_coords(%r)" 

log.debug(msg, cell, ex, (up_coords, dn_coords), base_coords) 

msg = "invalid cell(%r) due to: %s" 

raise ValueError(msg % (cell, ex)) from ex 

 

 

_mov_vector_slices = { 

# VECTO_SLICE REVERSE COORD_INDEX 

"L": (1, -1, lambda r, c: (r, slice(None, c + 1))), 

"U": (0, -1, lambda r, c: (slice(None, r + 1), c)), 

"R": (1, 1, lambda r, c: (r, slice(c, None))), 

"D": (0, 1, lambda r, c: (slice(r, None), c)), 

} 

 

 

def _extract_states_vector(states_matrix, dn_coords, land, mov): 

"""Extract a slice from the states-matrix by starting from `land` and following `mov`.""" 

coord_indx, is_reverse, slice_func = _mov_vector_slices[mov] 

vect_slice = slice_func(*land) 

states_vect = states_matrix[vect_slice] 

states_vect = states_vect[::is_reverse] 

 

return states_vect, coord_indx, is_reverse 

 

 

def _target_opposite(states_matrix, dn_coords, land, moves, edge_name=""): 

""" 

Follow moves from `land` and stop on the 1st full-cell. 

 

:param np.ndarray states_matrix: 

A 2D-array with `False` wherever cell are blank or empty. 

Use :meth:`ABCSheet.get_states_matrix()` to derrive it. 

:param Coords dn_coords: 

the bottom-right for the top-left of full-cells 

:param Coords land: 

the landing-cell 

:param str moves: MUST not be empty 

:return: the identified target-cell's coordinates 

:rtype: Coords 

 

 

Examples:: 

 

>>> states_matrix = np.array([ 

... [0, 0, 0, 0, 0, 0], 

... [0, 0, 0, 0, 0, 0], 

... [0, 0, 0, 1, 1, 1], 

... [0, 0, 1, 0, 0, 1], 

... [0, 0, 1, 1, 1, 1] 

... ]) 

>>> args = (states_matrix, Coords(4, 5)) 

 

>>> _target_opposite(*(args + (Coords(0, 0), 'DR'))) 

Coords(row=3, col=2) 

 

>>> _target_opposite(*(args + (Coords(0, 0), 'RD'))) 

Coords(row=2, col=3) 

 

It fails if a non-empty target-cell cannot be found, or 

it ends-up beyond bounds:: 

 

>>> _target_opposite(*(args + (Coords(0, 0), 'D'))) 

Traceback (most recent call last): 

pandalone.xleash._capture.EmptyCaptureException: No opposite-target found 

while moving(D) from landing-Coords(row=0, col=0)! 

 

>>> _target_opposite(*(args + (Coords(0, 0), 'UR'))) 

Traceback (most recent call last): 

pandalone.xleash._capture.EmptyCaptureException: No opposite-target found 

while moving(UR) from landing-Coords(row=0, col=0)! 

 

 

But notice that the landing-cell maybe outside of bounds:: 

 

>>> _target_opposite(*(args + (Coords(3, 10), 'L'))) 

Coords(row=3, col=5) 

 

""" 

assert not CHECK_CELLTYPE or isinstance(dn_coords, Coords), dn_coords 

assert not CHECK_CELLTYPE or isinstance(land, Coords), land 

 

up_coords = np.array([0, 0]) 

target = np.array(land) 

 

if land[0] > dn_coords[0] and "U" in moves: 

target[0] = dn_coords[0] 

if land[1] > dn_coords[1] and "L" in moves: 

target[1] = dn_coords[1] 

 

# if states_matrix[target].all(): 

# return Coords(*target) 

 

imoves = iter(moves) 

mov1 = next(imoves) 

mov2 = next(imoves, None) 

dv2 = mov2 and _primitive_dir_vectors[mov2] 

 

# Limit negative coords, since they are valid indices. 

while (up_coords <= target).all(): 

try: 

states_vect, coord_indx, is_reverse = _extract_states_vector( 

states_matrix, dn_coords, target, mov1 

) 

except IndexError: 

break 

else: 

if states_vect.any(): 

indices = states_vect.nonzero()[0] 

target[coord_indx] += is_reverse * indices.min() 

 

return Coords(*target) 

 

if not dv2: 

break 

 

target += dv2 

 

msg = "No opposite-target found while moving({}) from {}landing-{}!" 

raise EmptyCaptureException(msg.format(moves, edge_name, land)) 

 

 

def _target_same_vector(states_matrix, dn_coords, land, mov): 

""" 

:param np.ndarray states_matrix: 

A 2D-array with `False` wherever cell are blank or empty. 

Use :meth:`ABCSheet.get_states_matrix()` to derrive it. 

:param Coords dn_coords: 

the bottom-right for the top-left of full-cells 

:param Coords land: 

The landing-cell, which MUST be full! 

""" 

states_vect, coord_indx, is_reverse = _extract_states_vector( 

states_matrix, dn_coords, land, mov 

) 

if states_vect.all(): 

same_len = len(states_vect) - 1 

else: 

indices = np.diff(states_vect.astype(int)).nonzero()[0] 

same_len = indices.min() 

target_coord = land[coord_indx] + is_reverse * same_len 

 

return target_coord, coord_indx 

 

 

def _target_same(states_matrix, dn_coords, land, moves, edge_name=""): 

""" 

Scan term:`exterior` row and column on specified `moves` and stop on the last full-cell. 

 

:param np.ndarray states_matrix: 

A 2D-array with `False` wherever cell are blank or empty. 

Use :meth:`ABCSheet.get_states_matrix()` to derrive it. 

:param Coords dn_coords: 

the bottom-right for the top-left of full-cells 

:param Coords land: 

the landing-cell which MUST be within bounds 

:param moves: which MUST not be empty 

:return: the identified target-cell's coordinates 

:rtype: Coords 

 

 

Examples:: 

 

>>> states_matrix = np.array([ 

... [0, 0, 0, 0, 0, 0], 

... [0, 0, 0, 0, 0, 0], 

... [0, 0, 0, 1, 1, 1], 

... [0, 0, 1, 0, 0, 1], 

... [0, 0, 1, 1, 1, 1] 

... ]) 

>>> args = (states_matrix, Coords(4, 5)) 

 

>>> _target_same(*(args + (Coords(4, 5), 'U'))) 

Coords(row=2, col=5) 

 

>>> _target_same(*(args + (Coords(4, 5), 'L'))) 

Coords(row=4, col=2) 

 

>>> _target_same(*(args + (Coords(4, 5), 'UL', ))) 

Coords(row=2, col=2) 

 

 

It fails if landing is empty or beyond bounds:: 

 

>>> _target_same(*(args + (Coords(2, 2), 'DR'))) 

Traceback (most recent call last): 

pandalone.xleash._capture.EmptyCaptureException: No same-target found 

while moving(DR) from landing-Coords(row=2, col=2)! 

 

>>> _target_same(*(args + (Coords(10, 3), 'U'))) 

Traceback (most recent call last): 

pandalone.xleash._capture.EmptyCaptureException: No same-target found 

while moving(U) from landing-Coords(row=10, col=3)! 

 

""" 

assert not CHECK_CELLTYPE or isinstance(dn_coords, Coords), dn_coords 

assert not CHECK_CELLTYPE or isinstance(land, Coords), land 

 

target = np.asarray(land) 

if (target <= dn_coords).all() and states_matrix[land]: 

for mov in moves: 

coord, indx = _target_same_vector( 

states_matrix, dn_coords, np.asarray(land), mov 

) 

target[indx] = coord 

 

return Coords(*target) 

msg = "No same-target found while moving({}) from {}landing-{}!" 

raise EmptyCaptureException(msg.format(moves, edge_name, land)) 

 

 

def _sort_rect(r1, r2): 

""" 

Sorts rect-vertices in a 2D-array (with vertices in rows). 

 

Example:: 

 

>>> _sort_rect((5, 3), (4, 6)) 

array([[4, 3], 

[5, 6]]) 

""" 

rect = np.array([r1, r2], dtype=int) 

rect.sort(0) 

return rect 

 

 

def _expand_rect(states_matrix, r1, r2, exp_moves): 

""" 

Applies the :term:`expansion-moves` based on the `states_matrix`. 

 

:param state: 

:param Coords r1: 

any vertice of the rect to expand 

:param Coords r2: 

any vertice of the rect to expand 

:param np.ndarray states_matrix: 

A 2D-array with `False` wherever cell are blank or empty. 

Use :meth:`ABCSheet.get_states_matrix()` to derrive it. 

:param exp_moves: 

Just the parsed string, and not `None`. 

:return: a sorted rect top-left/bottom-right 

 

 

Examples:: 

 

>>> states_matrix = np.array([ 

... #0 1 2 3 4 5 

... [0, 0, 0, 0, 0, 0], #0 

... [0, 0, 1, 1, 1, 0], #1 

... [0, 1, 0, 0, 1, 0], #2 

... [0, 1, 1, 1, 1, 0], #3 

... [0, 0, 0, 0, 0, 1], #4 

... ], dtype=bool) 

 

>>> r1, r2 = (Coords(2, 1), Coords(2, 1)) 

>>> _expand_rect(states_matrix, r1, r2, 'U') 

(Coords(row=2, col=1), Coords(row=2, col=1)) 

 

>>> r1, r2 = (Coords(3, 1), Coords(2, 1)) 

>>> _expand_rect(states_matrix, r1, r2, 'R') 

(Coords(row=2, col=1), Coords(row=3, col=4)) 

 

>>> r1, r2 = (Coords(2, 1), Coords(6, 1)) 

>>> _expand_rect(states_matrix, r1, r2, 'r') 

(Coords(row=2, col=1), Coords(row=6, col=5)) 

 

>>> r1, r2 = (Coords(2, 3), Coords(2, 3)) 

>>> _expand_rect(states_matrix, r1, r2, 'LURD') 

(Coords(row=1, col=1), Coords(row=3, col=4)) 

 

""" 

assert not CHECK_CELLTYPE or isinstance(r1, Coords), r1 

assert not CHECK_CELLTYPE or isinstance(r2, Coords), r2 

 

exp_moves = _parse.parse_expansion_moves(exp_moves) 

 

nd_offsets = np.array([0, 1, 0, 1]) 

coord_offsets = { 

"L": np.array([0, 0, -1, 0]), 

"R": np.array([0, 0, 0, 1]), 

"U": np.array([-1, 0, 0, 0]), 

"D": np.array([0, 1, 0, 0]), 

} 

coord_indices = { 

"L": [0, 1, 2, 2], 

"R": [0, 1, 3, 3], 

"U": [0, 0, 2, 3], 

"D": [1, 1, 2, 3], 

} 

 

# Sort rect's vertices top-left/bottom-right. 

# 

rect = _sort_rect(r1, r2) 

# ``[r1, r2, c1, c2]`` to use slices, below 

rect = rect.T.flatten() 

for dirs_repeated in exp_moves: 

for dirs in dirs_repeated: 

orig_rect = rect 

for d in dirs: 

exp_rect = rect + coord_offsets[d] 

exp_vect_i = exp_rect[coord_indices[d]] + nd_offsets 

exp_vect_v = states_matrix[ 

slice(*exp_vect_i[:2]), slice(*exp_vect_i[2:]) 

] 

if exp_vect_v.any(): 

rect = exp_rect 

if (rect == orig_rect).all(): 

break 

 

return Coords(*rect[[0, 2]]), Coords(*rect[[1, 3]]) 

 

 

def resolve_capture_rect( 

states_matrix, 

up_dn_margins, 

st_edge, 

nd_edge=None, 

exp_moves=None, 

base_coords=None, 

): 

""" 

Performs :term:`targeting`, :term:`capturing` and :term:`expansions` based on the :term:`states-matrix`. 

 

To get the margin_coords, use one of: 

 

* :meth:`ABCSheet.get_margin_coords()` 

* :func:`.io.backend.margin_coords_from_states_matrix()` 

 

Its results can be fed into :func:`read_capture_values()`. 

 

:param np.ndarray states_matrix: 

A 2D-array with `False` wherever cell are blank or empty. 

Use :meth:`ABCSheet.get_states_matrix()` to derrive it. 

:param (Coords, Coords) up_dn_margins: 

the top-left/bottom-right coords with full-cells 

:param Edge st_edge: "uncooked" as matched by regex 

:param Edge nd_edge: "uncooked" as matched by regex 

:param list or none exp_moves: 

Just the parsed string, and not `None`. 

:param Coords base_coords: 

The base for a :term:`dependent` :term:`1st` edge. 

 

:return: a ``(Coords, Coords)`` with the 1st and 2nd :term:`capture-cell` 

ordered from top-left --> bottom-right. 

:rtype: tuple 

 

:raises EmptyCaptureException: 

When :term:`targeting` failed, and no :term:`target` cell identified. 

 

Examples:: 

>>> from pandalone.xleash import Edge, margin_coords_from_states_matrix 

 

>>> states_matrix = np.array([ 

... [0, 0, 0, 0, 0, 0], 

... [0, 0, 0, 0, 0, 0], 

... [0, 0, 0, 1, 1, 1], 

... [0, 0, 1, 0, 0, 1], 

... [0, 0, 1, 1, 1, 1] 

... ], dtype=bool) 

>>> up, dn = margin_coords_from_states_matrix(states_matrix) 

 

>>> st_edge = Edge(Cell('1', 'A'), 'DR') 

>>> nd_edge = Edge(Cell('.', '.'), 'DR') 

>>> resolve_capture_rect(states_matrix, (up, dn), st_edge, nd_edge) 

(Coords(row=3, col=2), Coords(row=4, col=2)) 

 

Using dependenent coordinates for the 2nd edge:: 

 

>>> st_edge = Edge(Cell('_', '_'), None) 

>>> nd_edge = Edge(Cell('.', '.'), 'UL') 

>>> rect = resolve_capture_rect(states_matrix, (up, dn), st_edge, nd_edge) 

>>> rect 

(Coords(row=2, col=2), Coords(row=4, col=5)) 

 

Using sheet's margins:: 

 

>>> st_edge = Edge(Cell('^', '_'), None) 

>>> nd_edge = Edge(Cell('_', '^'), None) 

>>> rect == resolve_capture_rect(states_matrix, (up, dn), st_edge, nd_edge) 

True 

 

Walking backwards:: 

 

>>> st_edge = Edge(Cell('^', '_'), 'L') # Landing is full, so 'L' ignored. 

>>> nd_edge = Edge(Cell('_', '_'), 'L', '+') # '+' or would also stop. 

>>> rect == resolve_capture_rect(states_matrix, (up, dn), st_edge, nd_edge) 

True 

 

""" 

up_margin, dn_margin = up_dn_margins 

assert not CHECK_CELLTYPE or isinstance(up_margin, Coords), up_margin 

assert not CHECK_CELLTYPE or isinstance(dn_margin, Coords), dn_margin 

 

st = _resolve_cell(st_edge.land, up_margin, dn_margin, base_coords) 

try: 

st_state = states_matrix[st] 

except IndexError: 

st_state = False 

 

if st_edge.mov is not None: 

if st_state: 

if st_edge.mod == "+": 

st = _target_same(states_matrix, dn_margin, st, st_edge.mov, "1st-") 

else: 

st = _target_opposite(states_matrix, dn_margin, st, st_edge.mov, "1st-") 

 

if nd_edge is None: 

nd = None 

else: 

nd = _resolve_cell(nd_edge.land, up_margin, dn_margin, st) 

 

if nd_edge.mov is not None: 

try: 

nd_state = states_matrix[nd] 

except IndexError: 

nd_state = False 

 

mov = nd_edge.mov 

if nd_state: 

if ( 

nd_edge.mod == "+" 

or nd_edge.land == Cell(".", ".") 

and nd_edge.mod != "?" 

): 

nd = _target_same(states_matrix, dn_margin, nd, mov, "2nd-") 

else: 

nd = _target_opposite(states_matrix, dn_margin, nd, mov, "2nd-") 

 

if exp_moves: 

st, nd = _expand_rect(states_matrix, st, nd or st, exp_moves) 

else: 

if nd is not None: 

rect = _sort_rect(st, nd) 

st, nd = tuple(Coords(*c) for c in rect) 

 

return st, nd