1

2# -*- coding: utf-8 -*-

3

4 u'''I{Boolean} operations on I{composite} polygons and I{clip}s.

5

6 Classes L{BooleanFHP} and L{BooleanGH} are I{composites} and

7 provide I{boolean} operations C{intersection}, C{difference},

8 C{reverse-difference}, C{sum} and C{union}.

9

10@note: A I{clip} is defined as a single, usually closed polygon,

11 a I{composite} is a collection of one or more I{clip}s.

12

13@see: U{Forster-Hormann-Popa<https://www.ScienceDirect.com/science/

14 article/pii/S259014861930007X>} and U{Greiner-Hormann

15 <http://www.Inf.USI.CH/hormann/papers/Greiner.1998.ECO.pdf>}.

16'''

17# make sure int/int division yields float quotient, see .basics

18 from __future__ import division as _; del _ # PYCHOK semicolon

19

20 from pygeodesy.basics import isodd, issubclassof, map2, _xscalar

21 from pygeodesy.constants import EPS, EPS2, INT0, _0_0, _0_5, _1_0

22 from pygeodesy.errors import ClipError, _IsnotError, _TypeError, \

23 _ValueError, _xattr, _xkwds_get, _xkwds_pop2

24 from pygeodesy.fmath import favg, hypot, hypot2

25# from pygeodesy.fsums import fsum1 # _MODS

26 from pygeodesy.interns import NN, _BANG_, _clipid_, _COMMASPACE_, \

27 _composite_, _DOT_, _duplicate_, _e_, \

28 _ELLIPSIS_, _few_, _height_, _lat_, _LatLon_, \

29 _lon_, _not_, _points_, _SPACE_, _too_, _X_, \

30 _x_, _B_, _d_, _R_ # PYCHOK used!

31 from pygeodesy.lazily import _ALL_DOCS, _ALL_LAZY, _ALL_MODS as _MODS

32 from pygeodesy.latlonBase import LatLonBase, \

33 LatLon2Tuple, Property_RO, property_RO

34 from pygeodesy.named import _name__, _Named, _NotImplemented, \

35 Fmt, pairs, unstr

36# from pygeodesy.namedTuples import LatLon2Tupe # from .latlonBase

37# from pygeodesy.points import boundsOf # _MODS

38# from pygeodesy.props import Property_RO, property_RO # from .latlonBase

39# from pygeodesy.streprs import Fmt, pairs, unstr # from .named

40 from pygeodesy.units import Height, HeightX

41 from pygeodesy.utily import fabs, _unrollon, _Wrap

42

43# from math import fabs # from .utily

44

45__all__ = _ALL_LAZY.booleans

46__version__ = '24.10.22'

47

48_0_EPS = EPS # near-zero, positive

49_EPS_0 = -EPS # near-zero, negative

50_1_EPS = _1_0 + EPS # near-one, over

51_EPS_1 = _1_0 - EPS # near-one, under

52_10EPS = EPS * 10 # see ._2Abs, ._10eps

53

54_alpha_ = 'alpha'

55_boolean_ = 'boolean'

56_case_ = 'case'

57_corners_ = 'corners'

58_open_ = 'open'

59

60

61 def _Enum(txt, enum): # PYCHOK unused

62 return txt # NN(txt, _TILDE_, enum)

63

64

65 class _L(object): # Intersection labels

66 CROSSING = _Enum(_X_, 1) # C++ enum

67 CROSSING_D = _Enum(_X_ + _d_, 8)

68 CROSSINGs = (CROSSING, CROSSING_D)

69 BOUNCING = _Enum(_B_, 2)

70 BOUNCING_D = _Enum(_B_ + _d_, 9)

71 BOUNCINGs = (BOUNCING, BOUNCING_D) + CROSSINGs

72 LEFT_ON = _Enum('Lo', 3)

73 ON_ON = _Enum('oo', 5)

74 ON_LEFT = _Enum('oL', 6)

75 ON_RIGHT = _Enum('oR', 7)

76 RIGHT_ON = _Enum('Ro', 4)

77 RIGHT_LEFT_ON = (RIGHT_ON, LEFT_ON)

78 # Entry/Exit flags

79 ENTRY = _Enum(_e_, 1)

80 EXIT = _Enum(_x_, 0)

81 Toggle = {ENTRY: EXIT,

82 EXIT: ENTRY,

83 None: None}

84

85_L = _L() # PYCHOK singleton

86

87

88 class _RP(object): # RelativePositions

89 IS_Pm = _Enum('Pm', 2) # C++ enum

90 IS_Pp = _Enum('Pp', 3)

91 LEFT = _Enum('L', 0)

92 RIGHT = _Enum(_R_, 1)

93

94_RP = _RP() # PYCHOK singleton

95

96_RP2L = {(_RP.LEFT, _RP.RIGHT): _L.CROSSING,

97 (_RP.RIGHT, _RP.LEFT): _L.CROSSING,

98 (_RP.LEFT, _RP.LEFT): _L.BOUNCING,

99 (_RP.RIGHT, _RP.RIGHT): _L.BOUNCING,

100 # overlapping cases

101 (_RP.RIGHT, _RP.IS_Pp): _L.LEFT_ON,

102 (_RP.IS_Pp, _RP.RIGHT): _L.LEFT_ON,

103 (_RP.LEFT, _RP.IS_Pp): _L.RIGHT_ON,

104 (_RP.IS_Pp, _RP.LEFT): _L.RIGHT_ON,

105 (_RP.IS_Pm, _RP.IS_Pp): _L.ON_ON,

106 (_RP.IS_Pp, _RP.IS_Pm): _L.ON_ON,

107 (_RP.IS_Pm, _RP.RIGHT): _L.ON_LEFT,

108 (_RP.RIGHT, _RP.IS_Pm): _L.ON_LEFT,

109 (_RP.LEFT, _RP.IS_Pm): _L.ON_RIGHT,

110 (_RP.IS_Pm, _RP.LEFT): _L.ON_RIGHT}

111

112

113 class _LatLonBool(_Named):

114 '''(INTERNAL) Base class for L{LatLonFHP} and L{LatLonGH}.

115 '''

116 _alpha = None # point AND intersection else length

117 _checked = False # checked in phase 3 iff intersection

118 _clipid = INT0 # (polygonal) clip identifier, number

119 _dupof = None # original of a duplicate

120# _e_x_str = NN # shut up PyChecker

121 _height = Height(0) # interpolated height, usually meter

122 _linked = None # link to neighbor iff intersection

123 _next = None # link to the next vertex

124 _prev = None # link to the previous vertex

125

126 def __init__(self, lat_ll, lon=None, height=0, clipid=INT0, wrap=False, **name):

127 '''New C{LatLon[FHP|GH]} from separate C{lat}, C{lon}, C{height} and C{clipid}

128 scalars or from a previous C{LatLon[FHP|GH]}, C{Clip[FHP|GH]4Tuple} or some

129 other C{LatLon} instance.

130

131 @arg lat_ll: Latitude (C{scalar}) or a lat-/longitude (C{LatLon[FHP|GH]},

132 C{Clip[FHP|GH]4Tuple} or some other C{LatLon}).

133 @kwarg lon: Longitude (C{scalar}), required B{C{lat_ll}} is scalar,

134 ignored otherwise.

135 @kwarg height: Height (C{scalar}), conventionally C{meter}.

136 @kwarg clipid: Clip identifier (C{int}).

137 @kwarg wrap: If C{True}, wrap or I{normalize} B{C{lat}} and B{C{lon}} (C{bool}).

138 @kwarg name: Optional C{B{name}=NN} (C{str}).

139 '''

140 h, name = _xkwds_pop2(name, h=height) if name else (height, name)

141

142 if lon is None:

143 y, x = lat_ll.lat, lat_ll.lon

144 h = _xattr(lat_ll, height=h)

145 c = _xattr(lat_ll, clipid=clipid)

146 else:

147 y, x, c = lat_ll, lon, clipid

148 self.y, self.x = _Wrap.latlon(y, x) if wrap else (y, x)

149 # don't duplicate defaults

150 if self._height != h:

151 self._height = h

152 if self._clipid != c:

153 self._clipid = c

154 if name:

155 self.name = name

156

157 def __abs__(self):

158 return max(fabs(self.x), fabs(self.y))

159

160 def __eq__(self, other):

161 return other is self or bool(_other(self, other) and

162 other.x == self.x and

163 other.y == self.y)

164

165 def __ne__(self, other): # required for Python 2

166 return not self.__eq__(other)

167

168 def __repr__(self):

169 '''String C{repr} of this lat-/longitude.

170 '''

171 if self._prev or self._next:

172 t = _ELLIPSIS_(self._prev, self._next)

173 t = _SPACE_(self, Fmt.ANGLE(t))

174 else:

175 t = str(self)

176 return t

177

178 def __str__(self):

179 '''String C{str} of this lat-/longitude.

180 '''

181 t = (_lat_, self.lat), (_lon_, self.lon)

182 if self._height:

183 X = _X_ if self.isintersection else NN

184 t += (_height_ + X, self._height),

185 if self._clipid:

186 t += (_clipid_, self._clipid),

187 if self._alpha is not None:

188 t += (_alpha_, self._alpha),

189# if self._dupof: # recursion risk

190# t += (_dupof_, self._dupof.name),

191 t = pairs(t, prec=8, fmt=Fmt.g, ints=True)

192 t = Fmt.PAREN(_COMMASPACE_.join(t))

193 if self._linked:

194 k = _DOT_ if self._checked else _BANG_

195 t = NN(t, self._e_x_str(k)) # PYCHOK expected

196 return NN(self.name, t)

197

198 def __sub__(self, other):

199 _other(self, other)

200 return self.__class__(self.y - other.y, # classof

201 self.x - other.x)

202

203 def _2A(self, p2, p3):

204 # I{Signed} area of a triangle, I{doubled}.

205 x, y = self.x, self.y

206 return (p2.x - x) * (p3.y - y) - \

207 (p3.x - x) * (p2.y - y)

208

209 def _2Abs(self, p2, p3, eps=_10EPS):

210 # I{Unsigned} area of a triangle, I{doubled}

211 # or 0 if below the given threshold C{eps}.

212 a = fabs(self._2A(p2, p3))

213 return 0 if a < eps else a

214

215 @property_RO

216 def clipid(self):

217 '''Get the I{clipid} (C{int} or C{0}).

218 '''

219 return self._clipid

220

221 def _equi(self, llb, eps):

222 # Is this LLB I{equivalent} to B{C{llb}} within

223 # the given I{non-negative} tolerance B{C{eps}}?

224 return not (fabs(llb.lon - self.x) > eps or

225 fabs(llb.lat - self.y) > eps)

226

227 @property_RO

228 def height(self):

229 '''Get the I{height} (C{Height} or C{int}).

230 '''

231 h = self._height

232 return HeightX(h) if self.isintersection else (

233 Height(h) if h else _LatLonBool._height)

234

235 def isequalTo(self, other, eps=None):

236 '''Is this point equal to an B{C{other}} within a given,

237 I{non-negative} tolerance, ignoring C{height}?

238

239 @arg other: The other point (C{LatLon}).

240 @kwarg eps: Tolerance for equality (C{degrees} or C{None}).

241

242 @return: C{True} if equivalent, C{False} otherwise (C{bool}).

243

244 @raise TypeError: Invalid B{C{other}}.

245 '''

246 try:

247 return self._equi(other, _eps0(eps))

248 except (AttributeError, TypeError, ValueError):

249 raise _IsnotError(_LatLon_, other=other)

250

251 @property_RO

252 def isintersection(self):

253 '''Is this an intersection? May be C{ispoint} too!

254 '''

255 return bool(self._linked)

256

257 @property_RO

258 def ispoint(self):

259 '''Is this an I{original} point? May be C{isintersection} too!

260 '''

261 return self._alpha is None

262

263 @property_RO

264 def lat(self):

265 '''Get the latitude (C{scalar}).

266 '''

267 return self.y

268

269 @property_RO

270 def latlon(self):

271 '''Get the lat- and longitude (L{LatLon2Tuple}).

272 '''

273 return LatLon2Tuple(self.y, self.x)

274

275 def _link(self, other):

276 # Make this and an other point neighbors.

277 # assert _other(self, other)

278 self._linked = other

279 other._linked = self

280

281 @property_RO

282 def lon(self):

283 '''Get the longitude (C{scalar}).

284 '''

285 return self.x

286

287 def _toClas(self, Clas, clipid):

288 # Return this vertex as a C{Clas} instance

289 # (L{Clip[FHP|GH]4Tuple} or L{LatLon[FHP|GH]}).

290 return Clas(self.lat, self.lon, self.height, clipid)

291

292

293 class LatLonFHP(_LatLonBool):

294 '''A point or intersection in a L{BooleanFHP} clip or composite.

295 '''

296 _en_ex = None

297 _label = None

298 _2split = None # or C{._Clip}

299 _2xing = False

300

301 def __init__(self, lat_ll, lon=None, height=0, clipid=INT0, **wrap_name):

302 '''New C{LatLonFHP} from separate C{lat}, C{lon}, C{h}eight and C{clipid}

303 scalars, or from a previous L{LatLonFHP}, L{ClipFHP4Tuple} or some other

304 C{LatLon} instance.

305

306 @arg lat_ll: Latitude (C{scalar}) or a lat-/longitude (L{LatLonFHP},

307 L{ClipFHP4Tuple} or some other C{LatLon}).

308

309 @see: L{Here<_LatLonBool.__init__>} for further details.

310 '''

311 _LatLonBool.__init__(self, lat_ll, lon, height, clipid, **wrap_name)

312

313 def __add__(self, other):

314 _other(self, other)

315 return self.__class__(self.y + other.y, self.x + other.x)

316

317 def __mod__(self, other): # cross product

318 _other(self, other)

319 return self.x * other.y - self.y * other.x

320

321 def __mul__(self, other): # dot product

322 _other(self, other)

323 return self.x * other.x + self.y * other.y

324

325 def __rmul__(self, other): # scalar product

326 _xscalar(other=other)

327 return self.__class__(self.y * other, self.x * other)

328

329# def _edge2(self):

330# # Return the start and end point of the

331# # edge containing I{intersection} C{v}.

332# n = p = self

333# while p.isintersection:

334# p = p._prev

335# if p is self:

336# break

337# while n.isintersection:

338# n = n._next

339# if n is self:

340# break

341# # assert p == self or not p._2Abs(self, n)

342# return p, n

343

344 def _e_x_str(self, t): # PYCHOK no cover

345 if self._label:

346 t = NN(self._label, t)

347 if self._en_ex:

348 t = NN(t, self._en_ex)

349 return t

350

351 @property_RO

352 def _isduplicate(self):

353 # Is this point a I{duplicate} intersection?

354 p = self._dupof

355 return bool(p and self._linked

356 and p is not self

357 and p == self

358# and p._alpha in (None, self._alpha)

359 and self._alpha in (_0_0, p._alpha))

360

361# @property_RO

362# def _isduplicated(self):

363# # Return the number of I{duplicates}?

364# d, v = 0, self

365# while v:

366# if v._dupof is self:

367# d += 1

368# v = v._next

369# if v is self:

370# break

371# return d

372

373 def isenclosedBy(self, *composites_points, **wrap):

374 '''Is this point inside one or more composites or polygons based on

375 the U{winding number<https://www.ScienceDirect.com/science/article/

376 pii/S0925772101000128>}?

377

378 @arg composites_points: Composites and/or iterables of points

379 (L{ClipFHP4Tuple}, L{ClipGH4Tuple}, L{LatLonFHP},

380 L{LatLonGH} or any C{LatLon}).

381 @kwarg wrap: Optional keyword argument C{B{wrap}=False}, if C{True},

382 wrap or I{normalize} and unroll all C{points} (C{bool}).

383

384 @raise ValueError: Some C{points} invalid.

385

386 @see: U{Algorithm 6<https://www.ScienceDirect.com/science/

387 article/pii/S0925772101000128>}.

388 '''

389 class _Pseudo(object):

390 # Pseudo-_CompositeBase._clips tuple

391

392 @property_RO

393 def _clips(self):

394 for cp in _Cps(_CompositeFHP, composites_points,

395 LatLonFHP.isenclosedBy): # PYCHOK yield

396 for c in cp._clips:

397 yield c

398

399 return self._isinside(_Pseudo(), **wrap)

400

401 def _isinside(self, composite, *excludes, **wrap):

402 # Is this point inside a composite, excluding

403 # certain C{_Clip}s? I{winding number}?

404 x, y, i = self.x, self.y, False

405 for c in composite._clips:

406 if c not in excludes:

407 w = 0

408 for p1, p2 in c._edges2(**wrap):

409 # edge [p1,p2] must straddle y

410 if (p1.y < y) is not (p2.y < y): # or ^

411 r = p2.x > x

412 s = p2.y > p1.y

413 if p1.x < x:

414 b = r and (s is (p1._2A(p2, self) > 0))

415 else:

416 b = r or (s is (p1._2A(p2, self) > 0))

417 if b:

418 w += 1 if s else -1

419 if isodd(w):

420 i = not i

421 return i

422

423 @property_RO

424 def _prev_next2(self):

425 # Adjust 2-tuple (._prev, ._next) iff a I{duplicate} intersection

426 p, n = self, self._next

427 if self._isduplicate:

428 p = self._dupof

429 while p._isduplicate:

430 p = p._dupof

431 while n._isduplicate:

432 n = n._next

433 return p._prev, n

434

435 def _RPoracle(self, p1, p2, p3):

436 # Relative Position oracle

437 if p1._linked is self: # or p1._linked2(self):

438 T = _RP.IS_Pm

439 elif p3._linked is self: # or p3._linked2(self):

440 T = _RP.IS_Pp

441 elif p1._2A(p2, p3) > 0: # left turn

442 T = _RP.LEFT if self._2A(p1, p2) > 0 and \

443 self._2A(p2, p3) > 0 else \

444 _RP.RIGHT # PYCHOK indent

445 else: # right turn (or straight)

446 T = _RP.RIGHT if self._2A(p1, p2) < 0 and \

447 self._2A(p2, p3) < 0 else \

448 _RP.LEFT # PYCHOK indent

449 return T

450

451

452 class LatLonGH(_LatLonBool):

453 '''A point or intersection in a L{BooleanGH} clip or composite.

454 '''

455 _entry = None # entry or exit iff intersection

456

457 def __init__(self, lat_ll, lon=None, height=0, clipid=INT0, **wrap_name):

458 '''New C{LatLonGH} from separate C{lat}, C{lon}, C{h}eight and C{clipid}

459 scalars, or from a previous L{LatLonGH}, L{ClipGH4Tuple} or some other

460 C{LatLon} instance.

461

462 @arg lat_ll: Latitude (C{scalar}) or a lat-/longitude (L{LatLonGH},

463 L{ClipGH4Tuple} or some other C{LatLon}).

464

465 @see: L{Here<_LatLonBool.__init__>} for further details.

466 '''

467 _LatLonBool.__init__(self, lat_ll, lon, height, clipid, **wrap_name)

468

469 def _check(self):

470 # Check-mark this vertex and its link.

471 self._checked = True

472 k = self._linked

473 if k and not k._checked:

474 k._checked = True

475

476 def _e_x_str(self, t): # PYCHOK no cover

477 return t if self._entry is None else NN(t,

478 (_e_ if self._entry else _x_))

479

480 def isenclosedBy(self, *composites_points, **wrap):

481 '''Is this point inside one or more composites or polygons based

482 on the U{even-odd-rule<https://www.ScienceDirect.com/science/

483 article/pii/S0925772101000128>}?

484

485 @arg composites_points: Composites and/or iterables of points

486 (L{ClipFHP4Tuple}, L{ClipGH4Tuple}, L{LatLonFHP},

487 L{LatLonGH} or any C{LatLon}).

488 @kwarg wrap: Optional keyword argument C{B{wrap}=False}, if C{True},

489 wrap or I{normalize} and unroll all C{points} (C{bool}).

490

491 @raise ValueError: Some B{C{points}} invalid.

492 '''

493 class _Pseudo(object):

494 # Pseudo-_CompositeBase._edges3 method

495

496 def _edges3(self, **kwds):

497 for cp in _Cps(_CompositeGH, composites_points,

498 LatLonGH.isenclosedBy): # PYCHOK yield

499 for e in cp._edges3(**kwds):

500 yield e

501

502 return self._isinside(_Pseudo(), **wrap)

503

504 def _isinside(self, composite, *bottom_top, **wrap):

505 # Is this vertex inside the composite? I{even-odd rule}?

506

507 def _x(y, p1, p2):

508 # return C{x} at given C{y} on edge [p1,p2]

509 return (y - p1.y) / (p2.y - p1.y) * (p2.x - p1.x)

510

511 # The I{even-odd} rule counts the number of edges

512 # intersecting a ray emitted from this point to

513 # east-bound infinity. When I{odd} this point lies

514 # inside, if I{even} outside.

515 y, i = self.y, False

516 if not (bottom_top and _outside(y, y, *bottom_top)):

517 x = self.x

518 for p1, p2, _ in composite._edges3(**wrap):

519 if (p1.y < y) is not (p2.y < y): # or ^

520 r = p2.x > x

521 if p1.x < x:

522 b = r and (_x(y, p1, p2) > x)

523 else:

524 b = r or (_x(y, p1, p2) > x)

525 if b:

526 i = not i

527 return i

528

529

530 class _Clip(_Named):

531 '''(INTERNAL) A I{doubly-linked} list representing a I{closed}

532 polygon of L{LatLonFHP} or L{LatLonGH} points, duplicates

533 and intersections with other clips.

534 '''

535 _composite = None

536 _dups = 0

537 _first = None

538 _id = 0

539 _identical = False

540 _noInters = False

541 _last = None

542 _LL = None

543 _len = 0

544 _pushback = False

545

546 def __init__(self, composite, clipid=INT0):

547 '''(INTERNAL) New C{_Clip}.

548 '''

549 # assert isinstance(composite, _CompositeBase)

550 if clipid in composite._clipids:

551 raise ClipError(clipid=clipid, txt=_duplicate_)

552 self._composite = composite

553 self._id = clipid

554 self._LL = composite._LL

555 composite._clips = composite._clips + (self,)

556

557 def __contains__(self, point): # PYCHOK no cover

558 '''Is the B{C{point}} in this clip?

559 '''

560 for v in self:

561 if v is point: # or ==?

562 return True

563 return False

564

565 def __eq__(self, other):

566 '''Is this clip I{equivalent} to an B{C{other}} clip,

567 do both have the same C{len}, the same points, in

568 the same order, possibly rotated?

569 '''

570 return self._equi(_other(self, other), 0)

571

572 def __ge__(self, other):

573 '''See method C{__lt__}.

574 '''

575 return not self.__lt__(other)

576

577 def __gt__(self, other):

578 '''Is this clip C{"above"} an B{C{other}} clip,

579 located or stretched farther North or East?

580 '''

581 return self._bltr4 > _other(self, other)._bltr4

582

583 def __hash__(self): # PYCHOK no over

584 return hash(self._bltr4)

585

586 def __iter__(self):

587 '''Yield the points, duplicates and intersections.

588 '''

589 v = f = self._first

590 while v:

591 yield v

592 v = v._next

593 if v is f:

594 break

595

596 def __le__(self, other):

597 '''See method C{__gt__}.

598 '''

599 return not self.__gt__(other)

600

601 def __len__(self):

602 '''Return the number of points, duplicates and

603 intersections in this clip.

604 '''

605 return self._len

606

607 def __lt__(self, other):

608 '''Is this clip C{"below"} an B{C{other}} clip,

609 located or stretched farther South or West?

610 '''

611 return self._bltr4 < _other(self, other)._bltr4

612

613 def __ne__(self, other): # required for Python 2

614 '''See method C{__eq__}.

615 '''

616 return not self.__eq__(other)

617

618 _all = __iter__

619

620 @property_RO

621 def _all_ON_ON(self):

622 # Check whether all vertices are ON_ON.

623 L_ON_ON = _L.ON_ON

624 return all(v._label is L_ON_ON for v in self)

625

626 def _append(self, y_v, *x_h_clipid):

627 # Append a point given as C{y}, C{x}, C{h}eight and

628 # C{clipid} args or as a C{LatLon[FHP|GH]}.

629 self._last = v = self._LL(y_v, *x_h_clipid) if x_h_clipid else y_v

630 self._len += 1

631 # assert v._clipid == self._id

632

633 v._next = n = self._first

634 if n is None: # set ._first

635 self._first = p = n = v

636 else: # insert before ._first

637 v._prev = p = n._prev

638 p._next = n._prev = v

639 return v

640

641# def _appendedup(self, v, clipid=0):

642# # Like C{._append}, but only append C{v} if not a

643# # duplicate of the one previously append[edup]'ed.

644# y, x, p = v.y, v.x, self._last

645# if p is None or y != p.y or x != p.x or clipid != p._clipid:

646# p = self._append(y, x, v._height, clipid)

647# if v._linked:

648# p._linked = True # to force errors

649# return p

650

651 @Property_RO

652 def _bltr4(self):

653 # Get the bounds as 4-tuple C{(bottom, left, top, right)}.

654 return map2(float, _MODS.points.boundsOf(self, wrap=False))

655

656 def _bltr4eps(self, eps):

657 # Get the ._bltr4 bounds tuple, slightly oversized.

658 if eps > 0: # > EPS

659 yb, xl, yt, xr = self._bltr4

660 yb, yt = _low_high_eps2(yb, yt, eps)

661 xl, xr = _low_high_eps2(xl, xr, eps)

662 t = yb, xl, yt, xr

663 else:

664 t = self._bltr4

665 return t

666

667 def _closed(self, raiser): # PYCHOK unused

668 # End a clip, un-close it and check C{len}.

669 p, f = self._last, self._first

670 if f and f._prev is p and p is not f and \

671 p._next is f and p == f: # PYCHOK no cover

672 # un-close the clip

673 f._prev = p = p._prev

674 p._next = f

675 self._len -= 1

676# elif f and raiser:

677# raise self._OpenClipError(p, f)

678 if len(self) < 3:

679 raise self._Error(_too_(_few_))

680

681 def _dup(self, q):

682 # Duplicate a point (or intersection) as intersection.

683 v = self._insert(q.y, q.x, q)

684 v._alpha = q._alpha or _0_0 # _0_0 replaces None

685 v._dupof = q._dupof or q

686 # assert v._prev is q

687 # assert q._next is v

688 return v

689

690 def _edges2(self, wrap=False, **unused):

691 # Yield each I{original} edge as a 2-tuple

692 # (p1, p2), a pair of C{LatLon[FHP|GH])}s.

693 p1 = p = f = self._first

694 while p:

695 p2 = p = p._next

696 if p.ispoint:

697 if wrap and p is not f:

698 p2 = _unrollon(p1, p)

699 yield p1, p2

700 p1 = p2

701 if p is f:

702 break

703

704 def _equi(self, clip, eps):

705 # Is this clip I{equivalent} to B{C{clip}} within

706 # the given I{non-negative} tolerance B{C{eps}}?

707 r, f = len(self), self._first

708 if f and r == len(clip) and self._bltr4eps(eps) \

709 == clip._bltr4eps(eps):

710 _equi = _LatLonBool._equi

711 for v in clip:

712 if _equi(f, v, eps):

713 s, n = f, v

714 for _ in range(r):

715 s, n = s._next, n._next

716 if not _equi(s, n, eps):

717 break # next v

718 else: # equivalent

719 return True

720 return False

721

722 def _Error(self, txt): # PYCHOK no cover

723 # Build a C{ClipError} instance

724 kwds = dict(len=len(self), txt=txt)

725 if self._dups:

726 kwds.update(dups=self._dups)

727 cp = self._composite

728 if self._id:

729 try:

730 i = cp._clips.index(self)

731 if i != self._id:

732 kwds.update(clip=i)

733 except ValueError:

734 pass

735 kwds[_clipid_] = self._id

736 return ClipError(cp._kind, cp.name, **kwds)

737

738 def _index(self, clips, eps):

739 # see _CompositeBase._equi

740 for i, c in enumerate(clips):

741 if c._equi(self, eps):

742 return i

743 raise ValueError(NN) # like clips.index(self)

744

745 def _insert(self, y, x, start, *end_alpha):

746 # insertVertex between points C{start} and

747 # C{end}, ordered by C{alpha} iff given.

748 v = self._LL(y, x, start._height, start._clipid)

749 n = start._next

750 if end_alpha:

751 end, alpha = end_alpha

752 v._alpha = alpha

753 v._height = favg(v._height, end._height, f=alpha)

754 # assert start is not end

755 while n is not end and n._alpha < alpha:

756 n = n._next

757 v._next = n

758 v._prev = p = n._prev

759 p._next = n._prev = v

760 self._len += 1

761# _Clip._bltr4._update(self)

762# _Clip._ishole._update(self)

763 return v

764

765 def _intersection(self, unused, q, *p1_p2_alpha):

766 # insert an intersection or make a point both

767 if p1_p2_alpha: # intersection on edge

768 v = self._insert(q.y, q.x, *p1_p2_alpha)

769 else: # intersection at point

770 v = q

771 # assert not v._linked

772 # assert v._alpha is None

773 return v

774

775 def _intersections(self):

776 # Yield all intersections, some may be points too.

777 for v in self:

778 if v.isintersection:

779 yield v

780

781 @Property_RO

782 def _ishole(self): # PYCHOK no cover

783 # Is this clip a hole inside its composite?

784 v = self._first

785 return v._isinside(self._composite, self) if v else False

786

787 @property_RO

788 def _nodups(self):

789 # Yield all non-duplicates.

790 for v in self:

791 if not v._dupof:

792 yield v

793

794 def _noXings(self, Union):

795 # Are all intersections non-CROSSINGs, -BOUNCINGs?

796 Xings = _L.BOUNCINGs if Union else _L.CROSSINGs

797 return all(v._label not in Xings for v in self._intersections())

798

799 def _OpenClipError(self, s, e): # PYCHOK no cover

800 # Return a C{CloseError} instance

801 t = NN(s, _ELLIPSIS_(_COMMASPACE_, e))

802 return self._Error(_SPACE_(_open_, t))

803

804 def _point2(self, insert):

805 # getNonIntersectionPoint and -Vertex

806 if not (insert and self._noInters):

807 for p in self._points(may_be=False): # not p._isduplicated?

808 return p, None

809 for n in self._intersections():

810 p, _ = n._prev_next2

811 k = p._linked

812 if k:

813 if n._linked not in k._prev_next2:

814 # create a pseudo-point

815 k = _0_5 * (p + n)

816 if insert:

817 k = self._insert(k.y, k.x, n._prev)

818 r = k # to remove later

819 else: # no ._prev, ._next

820 k._clipid = n._clipid

821 r = None

822 return k, r

823 return None, None

824

825 def _points(self, may_be=True):

826 # Yield all points I{in original order}, which may be intersections too.

827 for v in self:

828 if v.ispoint and (may_be or not v.isintersection):

829 yield v

830

831 def _remove2(self, v):

832 # Remove vertex C{v}.

833 # assert not v._isduplicated

834 if len(self) > 1:

835 p = v._prev

836 p._next = n = v._next

837 n._prev = p

838 if self._first is v:

839 self._first = n

840 if self._last is v:

841 self._last = p

842 self._len -= 1

843 else:

844 n = self._last = \

845 p = self._first = None

846 self._len = 0

847 return p, n

848

849 def _update_all(self): # PYCHOK no cover

850 # Zap the I{cached} properties.

851 _Clip._bltr4._update( self)

852 _Clip._ishole._update(self)

853 return self # for _special_identicals

854

855 def _Xings(self):

856 # Yield all I{un-checked} CROSSING intersections.

857 CROSSING = _L.CROSSING

858 for v in self._intersections():

859 if v._label is CROSSING and not v._checked:

860 yield v

861

862

863 class _CompositeBase(_Named):

864 '''(INTERNAL) Base class for L{BooleanFHP} and L{BooleanGH}

865 (C{_CompositeFHP} and C{_CompositeGH}).

866 '''

867 _clips = () # tuple of C{_Clips}

868 _eps = EPS # null edges

869 _kind = _corners_

870 _LL = _LatLonBool # shut up PyChecker

871 _raiser = False

872 _xtend = False

873

874 def __init__(self, lls, kind=NN, eps=EPS, **name):

875 '''(INTERNAL) See L{BooleanFHP} and L{BooleanGH}.

876 '''

877 n = _name__(name, _or_nameof=lls)

878 if n:

879 self.name = n

880 if kind:

881 self._kind = kind

882 if self._eps < eps:

883 self._eps = eps

884

885 c = _Clip(self)

886 lp = None

887 for ll in lls:

888 ll = self._LL(ll)

889 if lp is None:

890 c._id = ll._clipid # keep clipid

891 lp = c._append(ll)

892 elif ll._clipid != lp._clipid: # new clip

893 c._closed(self.raiser)

894 c = _Clip(self, ll._clipid)

895 lp = c._append(ll)

896 elif abs(ll - lp) > eps: # PYCHOK lp

897 lp = c._append(ll)

898 else:

899 c._dups += 1

900 c._closed(self.raiser)

901

902 def __contains__(self, point): # PYCHOK no cover

903 '''Is the B{C{point}} in one of the clips?

904 '''

905 for c in self._clips:

906 if point in c:

907 return True

908 return False

909

910 def __eq__(self, other):

911 '''Is this I{composite} equivalent to an B{C{other}}, i.e.

912 do both contain I{equivalent} clips in the same or in a

913 different order? Two clips are considered I{equivalent}

914 if both have the same points etc. in the same order,

915 possibly rotated.

916 '''

917 return self._equi(_other(self, other), 0)

918

919 def __iter__(self):

920 '''Yield all points, duplicates and intersections.

921 '''

922 for c in self._clips:

923 for v in c:

924 yield v

925

926 def __ne__(self, other): # required for Python 2

927 '''See method C{__eq__}.

928 '''

929 return not self.__eq__(other)

930

931 def __len__(self):

932 '''Return the I{total} number of points.

933 '''

934 return sum(map(len, self._clips)) if self._clips else 0

935

936 def __repr__(self):

937 '''String C{repr} of this composite.

938 '''

939 c = len(self._clips)

940 c = Fmt.SQUARE(c) if c > 1 else NN

941 n = Fmt.SQUARE(len(self))

942 t = Fmt.PAREN(self) # XXX not unstr

943 return NN(self.__class__.__name__, c, n, t)

944

945 def __str__(self):

946 '''String C{str} of this composite.

947 '''

948 return _COMMASPACE_.join(map(str, self))

949

950 @property_RO

951 def _bottom_top_eps2(self):

952 # Get the bottom and top C{y} bounds, oversized.

953 return _min_max_eps2(min(v.y for v in self),

954 max(v.y for v in self))

955

956 def _class(self, corners, kwds, **dflts):

957 # Return a new instance

958 _g = kwds.get

959 kwds = dict((n, _g(n, v)) for n, v in dflts.items())

960 return self.__class__(corners or (), **kwds)

961

962 @property_RO

963 def _clipids(self): # PYCHOK no cover

964 for c in self._clips:

965 yield c._id

966

967 def clipids(self):

968 '''Return a tuple with all C{clipid}s, I{ordered}.

969 '''

970 return tuple(self._clipids)

971

972# def _clipidups(self, other):

973# # Number common C{clipid}s between this and an C{other} composite

974# return len(set(self._clipids).intersection(set(other._clipids)))

975

976 def _edges3(self, **raiser_wrap):

977 # Yield each I{original} edge as a 3-tuple

978 # C{(LatLon[FHP|GH], LatLon[FHP|GH], _Clip)}.

979 for c in self._clips:

980 for p1, p2 in c._edges2(**raiser_wrap):

981 yield p1, p2, c

982

983 def _encloses(self, lat, lon, **wrap):

984 # see function .points.isenclosedBy

985 return self._LL(lat, lon).isenclosedBy(self, **wrap)

986

987 @property

988 def eps(self):

989 '''Get the null edges tolerance (C{degrees}, usually).

990 '''

991 return self._eps

992

993 @eps.setter # PYCHOK setter!

994 def eps(self, eps):

995 '''Set the null edges tolerance (C{degrees}, usually).

996 '''

997 self._eps = eps

998

999 def _10eps(self, **eps_):

1000 # Get eps for _LatLonBool._2Abs

1001 e = _xkwds_get(eps_, eps=self._eps)

1002 if e != EPS:

1003 e *= _10EPS / EPS

1004 else:

1005 e = _10EPS

1006 return e

1007

1008 def _equi(self, other, eps):

1009 # Is this composite I{equivalent} to an B{C{other}} within

1010 # the given, I{non-negative} tolerance B{C{eps}}?

1011 cs, co = self._clips, other._clips

1012 if cs and len(cs) == len(co):

1013 if eps > 0:

1014 _index = _Clip._index

1015 else:

1016 def _index(c, cs, unused):

1017 return cs.index(c)

1018 try:

1019 cs = list(sorted(cs))

1020 for c in sorted(co):

1021 cs.pop(_index(c, cs, eps))

1022 except ValueError: # from ._index

1023 pass

1024 return False if cs else True

1025 else: # both null?

1026 return False if cs or co else True

1027

1028 def _intersections(self):

1029 # Yield all intersections.

1030 for c in self._clips:

1031 for v in c._intersections():

1032 yield v

1033

1034 def isequalTo(self, other, eps=None):

1035 '''Is this boolean/composite equal to an B{C{other}} within

1036 a given, I{non-negative} tolerance?

1037

1038 @arg other: The other boolean/composite (C{Boolean[FHP|GB]}).

1039 @kwarg eps: Tolerance for equality (C{degrees} or C{None}).

1040

1041 @return: C{True} if equivalent, C{False} otherwise (C{bool}).

1042

1043 @raise TypeError: Invalid B{C{other}}.

1044

1045 @see: Method C{__eq__}.

1046 '''

1047 if isinstance(other, _CompositeBase):

1048 return self._equi(other, _eps0(eps))

1049 raise _IsnotError(_boolean_, _composite_, other=other)

1050

1051 def _kwds(self, op, **more):

1052 # Get all keyword arguments as C{dict}.

1053 kwds = dict(raiser=self.raiser, eps=self.eps,

1054 name=self.name or op.__name__)

1055 kwds.update(more)

1056 return kwds

1057

1058 @property_RO

1059 def _left_right_eps2(self):

1060 # Get the left and right C{x} bounds, oversized.

1061 return _min_max_eps2(min(v.x for v in self),

1062 max(v.x for v in self))

1063

1064 def _points(self, may_be=True): # PYCHOK no cover

1065 # Yield all I{original} points, which may be intersections too.

1066 for c in self._clips:

1067 for v in c._points(may_be=may_be):

1068 yield v

1069

1070 @property

1071 def raiser(self):

1072 '''Get the option to throw L{ClipError} exceptions (C{bool}).

1073 '''

1074 return self._raiser

1075

1076 @raiser.setter # PYCHOK setter!

1077 def raiser(self, throw):

1078 '''Set the option to throw L{ClipError} exceptions (C{bool}).

1079 '''

1080 self._raiser = bool(throw)

1081

1082 def _results(self, _presults, Clas, closed=False, inull=False, **eps):

1083 # Yield the dedup'd results, as L{ClipFHP4Tuple}s

1084 C = self._LL if Clas is None else Clas

1085 e = self._10eps(**eps)

1086 for clipid, ns in enumerate(_presults):

1087 f = p = v = None

1088 for n in ns:

1089 if f is None:

1090 yield n._toClas(C, clipid)

1091 f = p = n

1092 elif v is None:

1093 v = n # got f, p, v

1094 elif inull or p._2Abs(v, n, eps=e):

1095 yield v._toClas(C, clipid)

1096 p, v = v, n

1097 else: # null, colinear, ... skipped

1098 v = n

1099 if v and (inull or p._2Abs(v, f, eps=e)):

1100 yield v._toClas(C, clipid)

1101 p = v

1102 if f and p != f and closed: # close clip

1103 yield f._toClas(C, clipid)

1104

1105 def _sum(self, other, op):

1106 # Combine this and an C{other} composite

1107 LL = self._LL

1108 sp = self.copy(name=self.name or op.__name__)

1109 sp._clips, sid = (), INT0 # new clips

1110 for cp in (self, other):

1111 for c in cp._clips:

1112 _ap = _Clip(sp, sid)._append

1113 for v in c._nodups:

1114 _ap(LL(v.y, v.x, v.height, sid))

1115 sid += 1

1116 return sp

1117

1118 def _sum1(self, _a_p, *args, **kwds): # in .karney, .points

1119 # Sum the area or perimeter of all clips

1120 return _MODS.fsums.fsum1((_a_p(c, *args, **kwds) for c in self._clips))

1121

1122 def _sum2(self, LL, _a_p, *args, **kwds): # in .sphericalNvector, -Trigonometry

1123 # Sum the area or perimeter of all clips

1124

1125 def _lls(clip): # convert clip to LLs

1126 _LL = LL

1127 for v in clip:

1128 yield _LL(v.lat, v.lon) # datum=Sphere

1129

1130 return _MODS.fsums.fsum1((_a_p(_lls(c), *args, **kwds) for c in self._clips))

1131

1132 def toLatLon(self, LatLon=None, closed=False, **LatLon_kwds):

1133 '''Yield all (non-duplicate) points and intersections

1134 as an instance of B{C{LatLon}}.

1135

1136 @kwarg LatLon: Class to use (C{LatLon}) or if C{None},

1137 L{LatLonFHP} or L{LatLonGH}.

1138 @kwarg closed: If C{True}, close each clip (C{bool}).

1139 @kwarg LatLon_kwds: Optional, additional B{C{LatLon}}

1140 keyword arguments, ignore if

1141 C{B{LatLon} is None}.

1142

1143 @raise TypeError: Invalid B{C{LatLon}}.

1144

1145 @note: For intersections, C{height} is an instance

1146 of L{HeightX}, otherwise of L{Height}.

1147 '''

1148 if LatLon is None:

1149 LL, kwds = self._LL, {}

1150 elif issubclassof(LatLon, _LatLonBool, LatLonBase):

1151 LL, kwds = LatLon, LatLon_kwds

1152 else:

1153 raise _TypeError(LatLon=LatLon)

1154

1155 for c in self._clips:

1156 lf, cid = None, c._id

1157 for v in c._nodups:

1158 ll = LL(v.y, v.x, **kwds)

1159 ll._height = v.height

1160 if ll._clipid != cid:

1161 ll._clipid = cid

1162 yield ll

1163 if lf is None:

1164 lf = ll

1165 if closed and lf:

1166 yield lf

1167

1168

1169 class _CompositeFHP(_CompositeBase):

1170 '''(INTERNAL) A list of clips representing a I{composite}

1171 of L{LatLonFHP} points, duplicates and intersections

1172 with an other I{composite}.

1173 '''

1174 _LL = LatLonFHP

1175 _Union = False

1176

1177 def __init__(self, lls, raiser=False, **name_kind_eps):

1178 # New L{_CompositeFHP}.

1179 if raiser:

1180 self._raiser = True

1181 _CompositeBase.__init__(self, lls, **name_kind_eps)

1182

1183 def _classify(self):

1184 # 2) Classify intersection chains.

1185 L = _L

1186 for v in self._intersections():

1187 n, b = v, v._label

1188 if b in L.RIGHT_LEFT_ON: # next chain

1189 while True:

1190 n._label = None # _xkwds_pop(n.__dict__, _label=None)

1191 n = n._next

1192 if n is v or n._label is not L.ON_ON: # n._label and ...

1193 break

1194 a = L.LEFT_ON if n._label is L.ON_LEFT else L.RIGHT_ON

1195 v._label = n._label = L.BOUNCING_D if a is b else L.CROSSING_D

1196

1197 # 3) Copy labels

1198 for v in self._intersections():

1199 v._linked._label = v._label

1200

1201 def _clip(self, corners, Union=False, Clas=None,

1202 **closed_inull_raiser_eps):

1203 # Clip this composite with another one, C{corners},

1204 # using the Foster-Hormann-Popa's algorithm.

1205 P = self

1206 Q = self._class(corners, closed_inull_raiser_eps,

1207 eps=P._eps, raiser=False)

1208 if Union:

1209 P._Union = Q._Union = True

1210

1211 bt = Q._bottom_top_eps2

1212 lr = Q._left_right_eps2

1213 # compute and insert intersections

1214 for p1, p2, Pc in P._edges3(**closed_inull_raiser_eps):

1215 if not (_outside(p1.x, p2.x, *lr) or

1216 _outside(p1.y, p2.y, *bt)):

1217 e = _EdgeFHP(p1, p2)

1218 if e._dp2 > EPS2: # non-null edge

1219 for q1, q2, Qc in Q._edges3(**closed_inull_raiser_eps):

1220 for T, p, q in e._intersect3(q1, q2):

1221 p = Pc._intersection(T, *p)

1222 q = Qc._intersection(T, *q)

1223 # assert not p._linked

1224 # assert not q._linked

1225 p._link(q)

1226

1227 # label and classify intersections

1228 P._labelize()

1229 P._classify()

1230

1231 # check for special cases

1232 P._special_cases(Q)

1233 Q._special_cases(P)

1234 # handle identicals

1235 P._special_identicals(Q)

1236

1237 # set Entry/Exit flags

1238 P._set_entry_exits(Q)

1239 Q._set_entry_exits(P)

1240

1241 # handle splits and crossings

1242 P._splits_xings(Q)

1243

1244 # yield the results

1245 return P._results(P._presults(Q), Clas, **closed_inull_raiser_eps)

1246

1247 @property_RO

1248 def _identicals(self):

1249 # Yield all clips marked C{._identical}.

1250 for c in self._clips:

1251 if c._identical:

1252 yield c

1253

1254 def _labelize(self):

1255 # 1) Intersections classification

1256 for p in self._intersections():

1257 q = p._linked

1258 # determine local configuration at this intersection

1259 # and positions of Q- and Q+ relative to (P-, I, P+)

1260 p1, p3 = p._prev_next2

1261 q1, q3 = q._prev_next2

1262 t = (q1._RPoracle(p1, p, p3),

1263 q3._RPoracle(p1, p, p3))

1264 # check intersecting and overlapping cases

1265 p._label = _RP2L.get(t, None)

1266

1267 def _presults(self, other):

1268 # Yield the result clips, each as a generator

1269 # of the L{_LatLonFHP}s in that clip

1270 for cp in (self, other):

1271 for c in cp._clips:

1272 if c._pushback:

1273 yield c._all()

1274 for c in self._clips:

1275 for X in c._Xings():

1276 yield self._resultX(X)

1277

1278 def _resultX(self, X):

1279 # Yield the results from CROSSING C{X}.

1280 L, U, v = _L, self._Union, X

1281 while v:

1282 v._checked = True

1283 r = v # in P or Q

1284 s = L.Toggle[v._en_ex]

1285 e = (s is L.EXIT) ^ U

1286 while True:

1287 v = v._next if e else v._prev

1288 yield v

1289 v._checked = True

1290 if v._en_ex is s or v is X:

1291 break

1292 if v is r: # full circle

1293 raise ClipError(full_circle=v, clipid=v._clipid)

1294 if v is not X:

1295 v = v._linked

1296 if v is X:

1297 break

1298

1299 def _set_entry_exits(self, other): # MCCABE 14

1300 # 4) Set entry/exit flags

1301 L, U = _L, self._Union

1302 for c in self._clips:

1303 n, k = c._point2(True)

1304 if n:

1305 f = n

1306 s = L.EXIT if n._isinside(other) else L.ENTRY

1307 t = L.EXIT # first_chain_vertex = True

1308 while True:

1309 if n.isintersection:

1310 b = n._label

1311 if b is L.CROSSING:

1312 n._en_ex = s

1313 s = L.Toggle[s]

1314 elif b is L.BOUNCING and ((s is L.EXIT) ^ U):

1315 n._2split = c # see ._splits_xings

1316 elif b is L.CROSSING_D:

1317 n._en_ex = s

1318 if (s is t) ^ U:

1319 n._label = L.CROSSING

1320 t = L.Toggle[t]

1321 if t is L.EXIT: # first_chain_vertex == True

1322 s = L.Toggle[s]

1323 elif b is L.BOUNCING_D:

1324 n._en_ex = s

1325 if (s is t) ^ U:

1326 n._2xing = True # see ._splits_xings

1327 s = L.Toggle[s]

1328 t = L.Toggle[t]

1329 n = n._next # _, n = n._prev_next2

1330 if n is f:

1331 break # PYCHOK attr?

1332 if k:

1333 c._remove2(k)

1334

1335 def _special_cases(self, other):

1336 # 3.5) Check special cases

1337 U = self._Union

1338 for c in self._clips:

1339 if c._noXings(U):

1340 c._noInters = True

1341 if c._all_ON_ON:

1342 c._identical = True

1343 else:

1344 p, _ = c._point2(False)

1345 if p and (p._isinside(other) ^ U):

1346 c._pushback = True

1347

1348 def _special_identicals(self, other):

1349 # 3.5) Handle identicals

1350 _u = _Clip._update_all

1351 cds = dict((c._id, _u(c)) for c in other._identicals)

1352 # assert len(cds) == len(other._identicals)

1353 if cds: # PYCHOK no cover

1354 for c in self._identicals:

1355 c._update_all()

1356 for v in c._intersections():

1357 d = cds.get(v._linked._clipid, None)

1358 if d and d._ishole is c._ishole:

1359 c._pushback = True

1360 break # next c

1361

1362 @property_RO

1363 def _2splits(self):

1364 # Yield all intersections marked C{._2split}

1365 for p in self._intersections():

1366 if p._2split:

1367 # assert isinstance(p._2split, _Clip)

1368 yield p

1369

1370 def _splits_xings(self, other): # MCCABE 15

1371 # 5) Handle split pairs and 6) crossing candidates

1372

1373 def _2A_dup2(p, P): # PYCHOK unused

1374 p1, p2 = p._prev_next2

1375 ap = p1._2A(p, p2)

1376 Pc = p._2split

1377 # assert Pc in P._clips

1378 # assert p in Pc

1379 return ap, Pc._dup(p)

1380

1381 def _links2(ps, qs): # PYCHOK P unused?

1382 # Yield each link as a 2-tuple(p, q)

1383 id_qs = set(map(id, qs))

1384 if id_qs:

1385 for p in ps:

1386 q = p._linked

1387 if q and id(q) in id_qs:

1388 yield p, q

1389

1390 L = _L

1391 E = L.ENTRY if self._Union else L.EXIT

1392 X = L.Toggle[E]

1393 for p, q in _links2(self._2splits, other._2splits):

1394 ap, pp = _2A_dup2(p, self)

1395 aq, qq = _2A_dup2(q, other)

1396 if (ap * aq) > 0: # PYCHOK no cover

1397 p._link(qq) # overwrites ...

1398 q._link(pp) # ... p-q link

1399 else:

1400 pp._link(qq)

1401 p._en_ex = q._en_ex = E

1402 pp._en_ex = qq._en_ex = X

1403 p._label = pp._label = \

1404 q._label = qq._label = L.CROSSING

1405

1406 for p, q in _links2(self._2xings, other._2xings):

1407 p._label = q._label = L.CROSSING

1408

1409 @property_RO

1410 def _2xings(self):

1411 # Yield all intersections marked C{._2xing}

1412 for p in self._intersections():

1413 if p._2xing:

1414 yield p

1415

1416

1417 class _CompositeGH(_CompositeBase):

1418 '''(INTERNAL) A list of clips representing a I{composite}

1419 of L{LatLonGH} points, duplicates and intersections

1420 with an other I{composite}.

1421 '''

1422 _LL = LatLonGH

1423 _xtend = False

1424

1425 def __init__(self, lls, raiser=False, xtend=False, **name_kind_eps):

1426 # New L{_CompositeGH}.

1427 if xtend:

1428 self._xtend = True

1429 elif raiser:

1430 self._raiser = True

1431 _CompositeBase.__init__(self, lls, **name_kind_eps)

1432

1433 def _clip(self, corners, s_entry, c_entry, Clas=None,

1434 **closed_inull_raiser_xtend_eps):

1435 # Clip this polygon with another one, C{corners}.

1436

1437 # Core of Greiner/Hormann's algorithm, enhanced U{Correia's

1438 # <https://GitHub.com/helderco/univ-polyclip>} implementation***

1439 # and extended to optionally handle so-called "degenerate cases"

1440 S = self

1441 C = self._class(corners, closed_inull_raiser_xtend_eps,

1442 raiser=False, xtend=False)

1443 bt = C._bottom_top_eps2

1444 lr = C._left_right_eps2

1445

1446 # 1. find intersections

1447 for s1, s2, Sc in S._edges3(**closed_inull_raiser_xtend_eps):

1448 if not (_outside(s1.x, s2.x, *lr) or

1449 _outside(s1.y, s2.y, *bt)):

1450 e = _EdgeGH(s1, s2, **closed_inull_raiser_xtend_eps)

1451 if e._hypot2 > EPS2: # non-null edge

1452 for c1, c2, Cc in C._edges3(**closed_inull_raiser_xtend_eps):

1453 for y, x, sa, ca in e._intersect4(c1, c2):

1454 s = Sc._insert(y, x, s1, s2, sa)

1455 c = Cc._insert(y, x, c1, c2, ca)

1456 s._link(c)

1457

1458 # 2. identify entry/exit intersections

1459 if S._first:

1460 s_entry ^= S._first._isinside(C, *bt)

1461 for v in S._intersections():

1462 v._entry = s_entry = not s_entry

1463

1464 if C._first:

1465 c_entry ^= C._first._isinside(S)

1466 for v in C._intersections():

1467 v._entry = c_entry = not c_entry

1468

1469 # 3. yield the result(s)

1470 return S._results(S._presults(), Clas, **closed_inull_raiser_xtend_eps)

1471

1472 @property_RO

1473 def _first(self):

1474 # Get the very first vertex of the first clip

1475 for v in self:

1476 return v

1477 return None # PYCHOK no cover

1478

1479 def _kwds(self, op, **more):

1480 # Get the kwds C{dict}.

1481 return _CompositeBase._kwds(self, op, xtend=self.xtend, **more)

1482

1483 def _presults(self):

1484 # Yield the unchecked intersection(s).

1485 for c in self._clips:

1486 for v in c._intersections():

1487 if not v._checked:

1488 yield self._resultU(v)

1489

1490 def _resultU(self, v):

1491 # Yield the result from an un-checked intersection.

1492 while v and not v._checked:

1493 v._check()

1494 yield v

1495 r = v

1496 e = v._entry

1497 while True:

1498 v = v._next if e else v._prev

1499 yield v

1500 if v._linked:

1501 break

1502 if v is r:

1503 raise ClipError(full_circle=v, clipid=v._clipid)

1504 v = v._linked # switch

1505

1506 @property

1507 def xtend(self):

1508 '''Get the option to handle I{degenerate cases} (C{bool}).

1509 '''

1510 return self._xtend

1511

1512 @xtend.setter # PYCHOK setter!

1513 def xtend(self, xtend):

1514 '''Set the option to handle I{degenerate cases} (C{bool}).

1515 '''

1516 self._xtend = bool(xtend)

1517

1518

1519 class _EdgeFHP(object):

1520 # An edge between two L{LatLonFHP} points.

1521

1522 X_INTERSECT = _Enum('Xi', 1) # C++ enum

1523 X_OVERLAP = _Enum('Xo', 5)

1524 P_INTERSECT = _Enum('Pi', 3)

1525 P_OVERLAP = _Enum('Po', 7)

1526 Ps = (P_INTERSECT, P_OVERLAP, X_OVERLAP)

1527 Q_INTERSECT = _Enum('Qi', 2)

1528 Q_OVERLAP = _Enum('Qo', 6)

1529 Qs = (Q_INTERSECT, Q_OVERLAP, X_OVERLAP)

1530 V_INTERSECT = _Enum('Vi', 4)

1531 V_OVERLAP = _Enum('Vo', 8)

1532 Vs = (V_INTERSECT, V_OVERLAP)

1533

1534 def __init__(self, p1, p2, **unused):

1535 # New edge between points C{p1} and C{p2}, each a L{LatLonFHP}.

1536 self._p1_p2 = p1, p2

1537 self._dp = dp = p2 - p1

1538 self._dp2 = dp * dp # dot product, hypot2

1539

1540 self._lr, \

1541 self._bt = _left_right_bottom_top_eps2(p1, p2)

1542

1543 def _intersect3(self, q1, q2):

1544 # Yield intersection(s) Type or C{None}

1545 if not (_outside(q1.x, q2.x, *self._lr) or

1546 _outside(q1.y, q2.y, *self._bt)):

1547 dq = q2 - q1

1548 dq2 = dq * dq # dot product, hypot2

1549 if dq2 > EPS2: # like ._clip

1550 T, _E = None, _EdgeFHP # self.__class__

1551 p1, p2 = self._p1_p2

1552 ap1 = p1._2A(q1, q2)

1553 ap2_1 = p2._2A(q1, q2) - ap1

1554 if fabs(ap2_1) > _0_EPS: # non-parallel edges

1555 aq1 = q1._2A(p1, p2)

1556 aq2_1 = q2._2A(p1, p2) - aq1

1557 if fabs(aq2_1) > _0_EPS:

1558 # compute and classify alpha and beta

1559 a, a_0, a_0_1, _ = _alpha4(-ap1 / ap2_1)

1560 b, b_0, b_0_1, _ = _alpha4(-aq1 / aq2_1)

1561 # distinguish intersection types

1562 T = _E.X_INTERSECT if a_0_1 and b_0_1 else (

1563 _E.P_INTERSECT if a_0_1 and b_0 else (

1564 _E.Q_INTERSECT if a_0 and b_0_1 else (

1565 _E.V_INTERSECT if a_0 and b_0 else None)))

1566

1567 elif fabs(ap1) < _0_EPS: # parallel or colinear edges

1568 dp = self._dp

1569 d1 = q1 - p1

1570 # compute and classify alpha and beta

1571 a, a_0, a_0_1, _a_0_1 = _alpha4((d1 * dp) / self._dp2)

1572 b, b_0, b_0_1, _b_0_1 = _alpha4((d1 * dq) / (-dq2))

1573 # distinguish overlap type

1574 T = _E.X_OVERLAP if a_0_1 and b_0_1 else (

1575 _E.P_OVERLAP if a_0_1 and _b_0_1 else (

1576 _E.Q_OVERLAP if _a_0_1 and b_0_1 else (

1577 _E.V_OVERLAP if a_0 and b_0 else None)))

1578

1579 if T:

1580 if T is _E.X_INTERSECT:

1581 v = p1 + a * self._dp

1582 yield T, (v, p1, p2, a), (v, q1, q2, b)

1583 elif T in _E.Vs:

1584 yield T, (p1,), (q1,)

1585 else:

1586 if T in _E.Qs:

1587 yield T, (p1,), (p1, q1, q2, b)

1588 if T in _E.Ps:

1589 yield T, (q1, p1, p2, a), (q1,)

1590

1591

1592 class _EdgeGH(object):

1593 # An edge between two L{LatLonGH} points.

1594

1595 _raiser = False

1596 _xtend = False

1597

1598 def __init__(self, s1, s2, raiser=False, xtend=False, **unused):

1599 # New edge between points C{s1} and C{s2}, each a L{LatLonGH}.

1600 self._s1, self._s2 = s1, s2

1601 self._x_sx_y_sy = (s1.x, s2.x - s1.x,

1602 s1.y, s2.y - s1.y)

1603 self._lr, \

1604 self._bt = _left_right_bottom_top_eps2(s1, s2)

1605

1606 if xtend:

1607 self._xtend = True

1608 elif raiser:

1609 self._raiser = True

1610

1611 def _alpha2(self, x, y, dx, dy):

1612 # Return C{(alpha)}, see .points.nearestOn5

1613 a = (y * dy + x * dx) / self._hypot2

1614 d = (y * dx - x * dy) / self._hypot0

1615 return a, fabs(d)

1616

1617 def _Error(self, n, *args, **kwds): # PYCHOK no cover

1618 t = _DOT_(unstr(_EdgeGH, self._s1, self._s2),

1619 unstr(_EdgeGH._intersect4, *args, **kwds))

1620 return ClipError(_case_, n, txt=t)

1621

1622 @Property_RO

1623 def _hypot0(self):

1624 _, sx, _, sy = self._x_sx_y_sy

1625 return hypot(sx, sy) * _0_EPS

1626

1627 @Property_RO

1628 def _hypot2(self):

1629 _, sx, _, sy = self._x_sx_y_sy

1630 return hypot2(sx, sy)

1631

1632 def _intersect4(self, c1, c2, parallel=True): # MCCABE 14

1633 # Yield the intersection(s) of this and another edge.

1634

1635 # @return: None, 1 or 2 intersections, each a 4-Tuple

1636 # (y, x, s_alpha, c_alpha) with intersection

1637 # coordinates x and y and both alphas.

1638

1639 # @raise ClipError: Intersection unhandled.

1640

1641 # @see: U{Intersection point of two line segments

1642 # <http://PaulBourke.net/geometry/pointlineplane/>}.

1643 c1_x, c1_y = c1.x, c1.y

1644 if not (_outside(c1_x, c2.x, *self._lr) or

1645 _outside(c1_y, c2.y, *self._bt)):

1646 x, sx, \

1647 y, sy = self._x_sx_y_sy

1648

1649 cx = c2.x - c1_x

1650 cy = c2.y - c1_y

1651 d = cy * sx - cx * sy

1652

1653 if fabs(d) > _0_EPS: # non-parallel edges

1654 dx = x - c1_x

1655 dy = y - c1_y

1656 ca = (sx * dy - sy * dx) / d

1657 if _0_EPS < ca < _EPS_1 or (self._xtend and

1658 _EPS_0 < ca < _1_EPS):

1659 sa = (cx * dy - cy * dx) / d

1660 if _0_EPS < sa < _EPS_1 or (self._xtend and

1661 _EPS_0 < sa < _1_EPS):

1662 yield (y + sa * sy), (x + sa * sx), sa, ca

1663

1664 # unhandled, "degenerate" cases 1, 2 or 3

1665 elif self._raiser and not (sa < _EPS_0 or sa > _1_EPS): # PYCHOK no cover

1666 raise self._Error(1, c1, c2, sa=sa) # intersection at s1 or s2

1667

1668 elif self._raiser and not (ca < _EPS_0 or ca > _1_EPS): # PYCHOK no cover

1669 # intersection at c1 or c2 or at c1 or c2 and s1 or s2

1670 sa = (cx * dy - cy * dx) / d

1671 e = 2 if sa < _EPS_0 or sa > _1_EPS else 3

1672 raise self._Error(e, c1, c2, ca=ca)

1673

1674 elif parallel and (sx or sy) and (cx or cy): # PYCHOK no cover

1675 # non-null, parallel or colinear edges

1676 sa1, d1 = self._alpha2(c1_x - x, c1_y - y, sx, sy)

1677 sa2, d2 = self._alpha2(c2.x - x, c2.y - y, sx, sy)

1678 if max(d1, d2) < _0_EPS:

1679 if self._xtend and not _outside(sa1, sa2, _EPS_0, _1_EPS):

1680 if sa1 > sa2: # anti-parallel

1681 sa1, sa2 = sa2, sa1

1682 ca1, ca2 = _1_0, _0_0

1683 else: # parallel

1684 ca1, ca2 = _0_0, _1_0

1685 ca = fabs((sx / cx) if cx else (sy / cy))

1686 # = hypot(sx, sy) / hypot(cx, cy)

1687 if sa1 < 0: # s1 is between c1 and c2

1688 ca *= ca1 + sa1

1689 yield y, x, ca1, _alpha1(ca)

1690 else: # c1 is between s1 and s2

1691 yield (y + sa1 * sy), (x + sa1 * sx), sa1, ca1

1692 if sa2 > 1: # s2 is between c1 and c2

1693 ca *= sa2 - _1_0

1694 yield (y + sy), (x + sx), ca2, _alpha1(ca2 - ca)

1695 else: # c2 is between s1 and s2

1696 yield (y + sa2 * sy), (x + sa2 * sx), sa2, ca2

1697 elif self._raiser and not _outside(sa1, sa2, _0_0, _1_EPS):

1698 raise self._Error(4, c1, c2, d1=d1, d2=d2)

1699

1700

1701 class _BooleanBase(object):

1702 # Shared C{Boolean[FHP|GH]} methods.

1703

1704 def __add__(self, other):

1705 '''Sum: C{this + other} clips.

1706 '''

1707 return self._sum(_other(self, other), self.__add__) # PYCHOK OK

1708

1709 def __and__(self, other):

1710 '''Intersection: C{this & other}.

1711 '''

1712 return self._boolean(other, False, False, self.__and__) # PYCHOK OK

1713

1714 def __iadd__(self, other):

1715 '''In-place sum: C{this += other} clips.

1716 '''

1717 return self._inplace(self.__add__(other))

1718

1719 def __iand__(self, other):

1720 '''In-place intersection: C{this &= other}.

1721 '''

1722 return self._inplace(self.__and__(other))

1723

1724 def __ior__(self, other):

1725 '''In-place union: C{this |= other}.

1726 '''

1727 return self._inplace(self.__or__(other))

1728

1729 def __or__(self, other):

1730 '''Union: C{this | other}.

1731 '''

1732 return self._boolean(other, True, True, self.__or__) # PYCHOK OK

1733

1734 def __radd__(self, other):

1735 '''Reverse sum: C{other + this} clips.

1736 '''

1737 return _other(self, other)._sum(self, self.__radd__)

1738

1739 def __rand__(self, other):

1740 '''Reverse intersection: C{other & this}

1741 '''

1742 return _other(self, other).__and__(self)

1743

1744 def __ror__(self, other):

1745 '''Reverse union: C{other | this}

1746 '''

1747 return _other(self, other).__or__(self)

1748

1749 def _boolean4(self, other, op):

1750 # Set up a new C{Boolean[FHP|GH]}.

1751 C = self.__class__

1752 kwds = C._kwds(self, op)

1753 a = C(self, **kwds)

1754 b = _other(self, other)

1755 return a, b, C, kwds

1756

1757 def _inplace(self, r):

1758 # Replace this with a L{Boolean*} result.

1759 self._clips, r._clips = r._clips, None

1760# if self._raiser != r._raiser:

1761# self._raiser = r._raiser

1762# if self._xtend != r._xtend:

1763# self._xtend = r._xtend

1764# if self._eps != r._eps:

1765# self._eps = r._eps

1766 return self

1767

1768

1769 class BooleanFHP(_CompositeFHP, _BooleanBase):

1770 '''I{Composite} class providing I{boolean} operations between two

1771 I{composites} using U{Forster-Hormann-Popa<https://www.ScienceDirect.com/

1772 science/article/pii/S259014861930007X>}'s C++ implementation, transcoded

1773 to pure Python.

1774

1775 The supported operations between (composite) polygon A and B are:

1776

1777 - C = A & B or A &= B, intersection of A and B

1778

1779 - C = A + B or A += B, sum of A and B clips

1780

1781 - C = A | B or A |= B, union of A and B

1782

1783 - A == B or A != B, equivalent A and B clips

1784

1785 - A.isequalTo(B, eps), equivalent within tolerance

1786

1787 @see: Methods C{__eq__} and C{isequalTo}, function L{clipFHP4}

1788 and class L{BooleanGH}.

1789 '''

1790 _kind = _boolean_

1791

1792 def __init__(self, lls, raiser=False, eps=EPS, **name):

1793 '''New L{BooleanFHP} operand for I{boolean} operation.

1794

1795 @arg lls: The polygon points and clips (iterable of L{LatLonFHP}s,

1796 L{ClipFHP4Tuple}s or other C{LatLon}s).

1797 @kwarg raiser: If C{True}, throw L{ClipError} exceptions (C{bool}).

1798 @kwarg esp: Tolerance for eliminating null edges (C{degrees}, same

1799 units as the B{C{lls}} coordinates).

1800 @kwarg name: Optional C{B{name}=NN} (C{str}).

1801 '''

1802 _CompositeFHP.__init__(self, lls, raiser=raiser, eps=eps, **name)

1803

1804 def __isub__(self, other):

1805 '''Not implemented.'''

1806 return _NotImplemented(self, other)

1807

1808 def __rsub__(self, other):

1809 '''Not implemented.'''

1810 return _NotImplemented(self, other)

1811

1812 def __sub__(self, other):

1813 '''Not implemented.'''

1814 return _NotImplemented(self, other)

1815

1816 def _boolean(self, other, Union, unused, op):

1817 # One C{BooleanFHP} operation.

1818 p, q, C, kwds = self._boolean4(other, op)

1819 r = p._clip(q, Union=Union, **kwds)

1820 return C(r, **kwds)

1821

1822

1823 class BooleanGH(_CompositeGH, _BooleanBase):

1824 '''I{Composite} class providing I{boolean} operations between two

1825 I{composites} using the U{Greiner-Hormann<http://www.Inf.USI.CH/

1826 hormann/papers/Greiner.1998.ECO.pdf>} algorithm and U{Correia

1827 <https://GitHub.com/helderco/univ-polyclip>}'s implementation,

1828 modified and extended.

1829

1830 The supported operations between (composite) polygon A and B are:

1831

1832 - C = A - B or A -= B, difference A less B

1833

1834 - C = B - A or B -= A, difference B less B

1835

1836 - C = A & B or A &= B, intersection of A and B

1837

1838 - C = A + B or A += B, sum of A and B clips

1839

1840 - C = A | B or A |= B, union of A and B

1841

1842 - A == B or A != B, equivalent A and B clips

1843

1844 - A.isequalTo(B, eps), equivalent within tolerance

1845

1846 @note: To handle I{degenerate cases} like C{point-edge} and

1847 C{point-point} intersections, use class L{BooleanFHP}.

1848

1849 @see: Methods C{__eq__} and C{isequalTo}, function L{clipGH4}

1850 and class L{BooleanFHP}.

1851 '''

1852 _kind = _boolean_

1853

1854 def __init__(self, lls, raiser=True, xtend=False, eps=EPS, **name):

1855 '''New L{BooleanFHP} operand for I{boolean} operation.

1856

1857 @arg lls: The polygon points and clips (iterable of L{LatLonGH}s,

1858 L{ClipGH4Tuple}s or other C{LatLon}s).

1859 @kwarg raiser: If C{True}, throw L{ClipError} exceptions (C{bool}).

1860 @kwarg xtend: If C{True}, extend edges of I{degenerate cases}, an

1861 attempt to handle the latter (C{bool}).

1862 @kwarg esp: Tolerance for eliminating null edges (C{degrees}, same

1863 units as the B{C{lls}} coordinates).

1864 @kwarg name: Optional C{B{name}=NN} (C{str}).

1865 '''

1866 _CompositeGH.__init__(self, lls, raiser=raiser, xtend=xtend, eps=eps, **name)

1867

1868 def _boolean(self, other, s_entry, c_entry, op):

1869 # One C{BooleanGH} operation.

1870 s, c, C, kwds = self._boolean4(other, op)

1871 r = s._clip(c, s_entry, c_entry, **kwds)

1872 return C(r, **kwds)

1873

1874 def __isub__(self, other):

1875 '''In-place difference: C{this -= other}.

1876 '''

1877 return self._inplace(self.__sub__(other))

1878

1879 def __rsub__(self, other):

1880 ''' Reverse difference: C{other - this}

1881 '''

1882 return _other(self, other).__sub__(self)

1883

1884 def __sub__(self, other):

1885 '''Difference: C{this - other}.

1886 '''

1887 return self._boolean(other, True, False, self.__sub__)

1888

1889

1890 def _alpha1(alpha):

1891 # Return C{alpha} in C{[0..1]} range

1892 if _EPS_0 < alpha < _1_EPS:

1893 return max(_0_0, min(alpha, _1_0))

1894 t = _not_(Fmt.SQUARE(_ELLIPSIS_(0, 1)))

1895 raise ClipError(_alpha_, alpha, txt=t)

1896

1897

1898 def _alpha4(a):

1899 # Return 4-tuple (alpha, -EPS < alpha < EPS,

1900 # 0 < alpha < 1,

1901 # not 0 < alpha < 1)

1902 a_EPS = bool(_EPS_0 < a < _0_EPS)

1903 a_0_1 = bool(_0_EPS < a < _EPS_1)

1904 return a, a_EPS, a_0_1, (not a_0_1)

1905

1906

1907 def _Cps(Cp, composites_points, where):

1908 # Yield composites and points as a C{Cp} composite.

1909 try:

1910 kwds = dict(kind=_points_, name__=where)

1911 for cp in composites_points:

1912 yield cp if isBoolean(cp) else Cp(cp, **kwds)

1913 except (AttributeError, ClipError, TypeError, ValueError) as x:

1914 raise _ValueError(points=cp, cause=x)

1915

1916

1917 def _eps0(eps):

1918 # Adjust C{eps} or C{0}.

1919 return eps if eps and eps > EPS else 0

1920

1921

1922 def isBoolean(obj):

1923 '''Check for C{Boolean} composites.

1924

1925 @arg obj: The object (any C{type}).

1926

1927 @return: C{True} if B{C{obj}} is L{BooleanFHP}, L{BooleanGH}

1928 or some other composite, C{False} otherwise.

1929 '''

1930 return isinstance(obj, _CompositeBase)

1931

1932

1933 def _left_right_bottom_top_eps2(p1, p2):

1934 '''(INTERNAL) Return 2-tuple C{((left, right), (bottom, top))}, both oversized.

1935 '''

1936 return (_min_max_eps2(p1.x, p2.x),

1937 _min_max_eps2(p1.y, p2.y))

1938

1939

1940 def _low_high_eps2(lo, hi, eps):

1941 '''(INTERNAL) Return 2-tuple C{(lo, hi)}, oversized.

1942 '''

1943 # assert eps > 0

1944 lo -= fabs(eps * lo)

1945 hi += fabs(eps * hi)

1946 if lo < hi:

1947 pass

1948 elif lo > hi:

1949 lo, hi = hi, lo

1950 else:

1951 lo -= eps

1952 hi += eps

1953 return lo, hi

1954

1955

1956 def _min_max_eps2(*xs):

1957 '''(INTERNAL) Return 2-tuple C{(min, max)}, oversized.

1958 '''

1959 return _low_high_eps2(min(xs), max(xs), EPS)

1960

1961

1962 def _other(this, other):

1963 '''(INTERNAL) Check for compatible C{type}s.

1964 '''

1965 C = this.__class__

1966 if isinstance(other, C):

1967 return other

1968 raise _IsnotError(C, other=other)

1969

1970

1971 def _outside(x1, x2, lo, hi):

1972 '''(INTERNAL) Are C{x1} and C{x2} outside C{(lo, hi)}?

1973 '''

1974 # assert lo <= hi

1975 return (x1 < lo or x2 > hi) if x1 > x2 else \

1976 (x2 < lo or x1 > hi)

1977

1978

1979__all__ += _ALL_DOCS(_BooleanBase, _Clip,

1980 _CompositeBase, _CompositeFHP, _CompositeGH,

1981 _LatLonBool)

1982

1983# **) MIT License

1984#

1985# Copyright (C) 2018-2024 -- mrJean1 at Gmail -- All Rights Reserved.

1986#

1987# Permission is hereby granted, free of charge, to any person obtaining a

1988# copy of this software and associated documentation files (the "Software"),

1989# to deal in the Software without restriction, including without limitation

1990# the rights to use, copy, modify, merge, publish, distribute, sublicense,

1991# and/or sell copies of the Software, and to permit persons to whom the

1992# Software is furnished to do so, subject to the following conditions:

1993#

1994# The above copyright notice and this permission notice shall be included

1995# in all copies or substantial portions of the Software.

1996#

1997# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS

1998# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,

1999# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL

2000# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR

2001# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,

2002# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR

2003# OTHER DEALINGS IN THE SOFTWARE.

2004

2005# ***) GNU GPL 3

2006#

2007# Copyright (C) 2011-2012 Helder Correia <Helder.MC@Gmail.com>

2008#

2009# This program is free software: you can redistribute it and/or

2010# modify it under the terms of the GNU General Public License as

2011# published by the Free Software Foundation, either version 3 of

2012# the License, or any later version.

2013#

2014# This program is distributed in the hope that it will be useful,

2015# but WITHOUT ANY WARRANTY; without even the implied warranty of

2016# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

2017# GNU General Public License for more details.

2018#

2019# You should have received a copy of the GNU General Public License

2020# along with this program. If not, see <http://www.GNU.org/licenses/>.

2021#

2022# You should have received the README file along with this program.

2023# If not, see <https://GitHub.com/helderco/univ-polyclip>.