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

# This file is part of afw. 

# 

# Developed for the LSST Data Management System. 

# This product includes software developed by the LSST Project 

# (https://www.lsst.org). 

# See the COPYRIGHT file at the top-level directory of this distribution 

# for details of code ownership. 

# 

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

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 3 of the License, or 

# (at your option) any later version. 

# 

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

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

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

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

# along with this program. If not, see <https://www.gnu.org/licenses/>. 

 

""" 

Tests for table.SourceTable 

 

Run with: 

python test_sourceTable.py 

or 

pytest test_sourceTable.py 

""" 

import os 

import unittest 

import tempfile 

import pickle 

import math 

 

import numpy as np 

 

import lsst.utils.tests 

import lsst.pex.exceptions 

import lsst.geom 

import lsst.afw.table 

import lsst.afw.geom 

import lsst.afw.image 

import lsst.afw.detection 

 

testPath = os.path.abspath(os.path.dirname(__file__)) 

 

 

def makeArray(size, dtype): 

return np.array(np.random.randn(*size), dtype=dtype) 

 

 

def makeCov(size, dtype): 

m = np.array(np.random.randn(size, size), dtype=dtype) 

return np.dot(m, m.transpose()) 

 

 

def makeWcs(): 

crval = lsst.geom.SpherePoint(1.606631*lsst.geom.degrees, 

5.090329*lsst.geom.degrees) 

crpix = lsst.geom.Point2D(2036.0, 2000.0) 

cdMatrix = np.array([5.399452e-5, -1.30770e-5, 1.30770e-5, 5.399452e-5]) 

cdMatrix.shape = (2, 2) 

return lsst.afw.geom.makeSkyWcs(crpix=crpix, crval=crval, cdMatrix=cdMatrix) 

 

 

class SourceTableTestCase(lsst.utils.tests.TestCase): 

 

def fillRecord(self, record): 

record.set(self.instFluxKey, np.random.randn()) 

record.set(self.instFluxErrKey, np.random.randn()) 

record.set(self.centroidKey.getX(), np.random.randn()) 

record.set(self.centroidKey.getY(), np.random.randn()) 

record.set(self.xErrKey, np.random.randn()) 

record.set(self.yErrKey, np.random.randn()) 

record.set(self.shapeKey.getIxx(), np.random.randn()) 

record.set(self.shapeKey.getIyy(), np.random.randn()) 

record.set(self.shapeKey.getIxy(), np.random.randn()) 

record.set(self.xxErrKey, np.random.randn()) 

record.set(self.yyErrKey, np.random.randn()) 

record.set(self.xyErrKey, np.random.randn()) 

record.set(self.fluxFlagKey, np.random.randn() > 0) 

record.set(self.centroidFlagKey, np.random.randn() > 0) 

record.set(self.shapeFlagKey, np.random.randn() > 0) 

 

def setUp(self): 

np.random.seed(1) 

self.schema = lsst.afw.table.SourceTable.makeMinimalSchema() 

self.instFluxKey = self.schema.addField("a_instFlux", type="D") 

self.instFluxErrKey = self.schema.addField("a_instFluxErr", type="D") 

self.fluxFlagKey = self.schema.addField("a_flag", type="Flag") 

 

# the meas field is added using a functor key, but the error is added 

# as scalars, as we lack a ResultKey functor as exists in meas_base 

self.centroidKey = lsst.afw.table.Point2DKey.addFields( 

self.schema, "b", "", "pixel") 

self.xErrKey = self.schema.addField("b_xErr", type="F") 

self.yErrKey = self.schema.addField("b_yErr", type="F") 

self.centroidFlagKey = self.schema.addField("b_flag", type="Flag") 

 

self.shapeKey = lsst.afw.table.QuadrupoleKey.addFields( 

self.schema, "c", "", lsst.afw.table.CoordinateType.PIXEL) 

self.xxErrKey = self.schema.addField("c_xxErr", type="F") 

self.xyErrKey = self.schema.addField("c_xyErr", type="F") 

self.yyErrKey = self.schema.addField("c_yyErr", type="F") 

self.shapeFlagKey = self.schema.addField("c_flag", type="Flag") 

 

self.table = lsst.afw.table.SourceTable.make(self.schema) 

self.catalog = lsst.afw.table.SourceCatalog(self.table) 

self.record = self.catalog.addNew() 

self.fillRecord(self.record) 

self.record.setId(50) 

self.fillRecord(self.catalog.addNew()) 

self.fillRecord(self.catalog.addNew()) 

 

def tearDown(self): 

del self.schema 

del self.record 

del self.table 

del self.catalog 

 

def checkCanonical(self): 

self.assertEqual(self.record.get(self.instFluxKey), 

self.record.getPsfInstFlux()) 

self.assertEqual(self.record.get(self.fluxFlagKey), 

self.record.getPsfFluxFlag()) 

self.assertEqual(self.table.getSchema().getAliasMap().get("slot_Centroid"), "b") 

self.assertEqual(self.centroidKey.get(self.record), 

self.record.getCentroid()) 

self.assertFloatsAlmostEqual( 

math.fabs(self.record.get(self.xErrKey)), 

math.sqrt(self.record.getCentroidErr()[0, 0]), rtol=1e-6) 

self.assertFloatsAlmostEqual( 

math.fabs(self.record.get(self.yErrKey)), 

math.sqrt(self.record.getCentroidErr()[1, 1]), rtol=1e-6) 

self.assertEqual(self.table.getSchema().getAliasMap().get("slot_Shape"), "c") 

self.assertEqual(self.shapeKey.get(self.record), 

self.record.getShape()) 

self.assertFloatsAlmostEqual( 

math.fabs(self.record.get(self.xxErrKey)), 

math.sqrt(self.record.getShapeErr()[0, 0]), rtol=1e-6) 

self.assertFloatsAlmostEqual( 

math.fabs(self.record.get(self.yyErrKey)), 

math.sqrt(self.record.getShapeErr()[1, 1]), rtol=1e-6) 

self.assertFloatsAlmostEqual( 

math.fabs(self.record.get(self.xyErrKey)), 

math.sqrt(self.record.getShapeErr()[2, 2]), rtol=1e-6) 

 

def testPersisted(self): 

self.table.definePsfFlux("a") 

self.table.defineCentroid("b") 

self.table.defineShape("c") 

with lsst.utils.tests.getTempFilePath(".fits") as filename: 

self.catalog.writeFits(filename) 

catalog = lsst.afw.table.SourceCatalog.readFits(filename) 

table = catalog.getTable() 

record = catalog[0] 

# I'm using the keys from the non-persisted table. They should work at least in the 

# current implementation 

self.assertEqual(record.get(self.instFluxKey), record.getPsfInstFlux()) 

self.assertEqual(record.get(self.fluxFlagKey), record.getPsfFluxFlag()) 

self.assertEqual(table.getSchema().getAliasMap().get("slot_Centroid"), "b") 

centroid = self.centroidKey.get(self.record) 

self.assertEqual(centroid, record.getCentroid()) 

self.assertFloatsAlmostEqual( 

math.fabs(self.record.get(self.xErrKey)), 

math.sqrt(self.record.getCentroidErr()[0, 0]), rtol=1e-6) 

self.assertFloatsAlmostEqual( 

math.fabs(self.record.get(self.yErrKey)), 

math.sqrt(self.record.getCentroidErr()[1, 1]), rtol=1e-6) 

shape = self.shapeKey.get(self.record) 

self.assertEqual(table.getSchema().getAliasMap().get("slot_Shape"), "c") 

self.assertEqual(shape, record.getShape()) 

self.assertFloatsAlmostEqual( 

math.fabs(self.record.get(self.xxErrKey)), 

math.sqrt(self.record.getShapeErr()[0, 0]), rtol=1e-6) 

self.assertFloatsAlmostEqual( 

math.fabs(self.record.get(self.yyErrKey)), 

math.sqrt(self.record.getShapeErr()[1, 1]), rtol=1e-6) 

self.assertFloatsAlmostEqual( 

math.fabs(self.record.get(self.xyErrKey)), 

math.sqrt(self.record.getShapeErr()[2, 2]), rtol=1e-6) 

 

def testCanonical2(self): 

self.table.definePsfFlux("a") 

self.table.defineCentroid("b") 

self.table.defineShape("c") 

self.checkCanonical() 

 

def testPickle(self): 

p = pickle.dumps(self.catalog) 

new = pickle.loads(p) 

 

self.assertEqual(self.catalog.schema.getNames(), new.schema.getNames()) 

self.assertEqual(len(self.catalog), len(new)) 

for r1, r2 in zip(self.catalog, new): 

# Columns that are easy to test 

for field in ("a_instFlux", "a_instFluxErr", "id"): 

k1 = self.catalog.schema.find(field).getKey() 

k2 = new.schema.find(field).getKey() 

self.assertEqual(r1[k1], r2[k2]) 

 

def testCoordUpdate(self): 

self.table.defineCentroid("b") 

wcs = makeWcs() 

self.record.updateCoord(wcs) 

coord1 = self.record.getCoord() 

coord2 = wcs.pixelToSky(self.record.get(self.centroidKey)) 

self.assertEqual(coord1, coord2) 

 

def testSorting(self): 

self.assertFalse(self.catalog.isSorted()) 

self.catalog.sort() 

self.assertTrue(self.catalog.isSorted()) 

r = self.catalog.find(2) 

self.assertEqual(r["id"], 2) 

r = self.catalog.find(500) 

self.assertIsNone(r) 

 

def testConversion(self): 

catalog1 = self.catalog.cast(lsst.afw.table.SourceCatalog) 

catalog2 = self.catalog.cast(lsst.afw.table.SimpleCatalog) 

catalog3 = self.catalog.cast(lsst.afw.table.SourceCatalog, deep=True) 

catalog4 = self.catalog.cast(lsst.afw.table.SimpleCatalog, deep=True) 

self.assertEqual(self.catalog.table, catalog1.table) 

self.assertEqual(self.catalog.table, catalog2.table) 

self.assertNotEqual(self.catalog.table, catalog3.table) 

self.assertNotEqual(self.catalog.table, catalog3.table) 

for r, r1, r2, r3, r4 in zip(self.catalog, catalog1, catalog2, catalog3, catalog4): 

self.assertEqual(r, r1) 

self.assertEqual(r, r2) 

self.assertNotEqual(r, r3) 

self.assertNotEqual(r, r4) 

self.assertEqual(r.getId(), r3.getId()) 

self.assertEqual(r.getId(), r4.getId()) 

 

def testColumnView(self): 

cols1 = self.catalog.getColumnView() 

cols2 = self.catalog.columns 

self.assertIs(cols1, cols2) 

self.assertIsInstance(cols1, lsst.afw.table.SourceColumnView) 

self.table.definePsfFlux("a") 

self.table.defineCentroid("b") 

self.table.defineShape("c") 

self.assertFloatsEqual(cols2["a_instFlux"], cols2.getPsfInstFlux()) 

self.assertFloatsEqual(cols2["a_instFluxErr"], cols2.getPsfInstFluxErr()) 

self.assertFloatsEqual(cols2["b_x"], cols2.getX()) 

self.assertFloatsEqual(cols2["b_y"], cols2.getY()) 

self.assertFloatsEqual(cols2["c_xx"], cols2.getIxx()) 

self.assertFloatsEqual(cols2["c_yy"], cols2.getIyy()) 

self.assertFloatsEqual(cols2["c_xy"], cols2.getIxy()) 

 

# Trying to access slots which have been removed should raise. 

self.catalog.table.schema.getAliasMap().erase("slot_Centroid") 

self.catalog.table.schema.getAliasMap().erase("slot_Shape") 

for quantity in ["X", "Y", "Ixx", "Iyy", "Ixy"]: 

with self.assertRaises(lsst.pex.exceptions.LogicError): 

getattr(self.catalog, f"get{quantity}")() 

 

def testForwarding(self): 

"""Verify that Catalog forwards unknown methods to its table and/or columns.""" 

self.table.definePsfFlux("a") 

self.table.defineCentroid("b") 

self.table.defineShape("c") 

self.assertFloatsEqual(self.catalog.columns["a_instFlux"], 

self.catalog["a_instFlux"]) 

self.assertFloatsEqual(self.catalog.columns[self.instFluxKey], 

self.catalog.get(self.instFluxKey)) 

self.assertFloatsEqual(self.catalog.columns.get(self.instFluxKey), 

self.catalog.getPsfInstFlux()) 

self.assertEqual(self.instFluxKey, self.catalog.getPsfFluxSlot().getMeasKey()) 

with self.assertRaises(AttributeError): 

self.catalog.foo() 

 

def testBitsColumn(self): 

 

allBits = self.catalog.getBits() 

someBits = self.catalog.getBits(["a_flag", "c_flag"]) 

self.assertEqual(allBits.getMask("a_flag"), 0x1) 

self.assertEqual(allBits.getMask("b_flag"), 0x2) 

self.assertEqual(allBits.getMask("c_flag"), 0x4) 

self.assertEqual(someBits.getMask(self.fluxFlagKey), 0x1) 

self.assertEqual(someBits.getMask(self.shapeFlagKey), 0x2) 

np.testing.assert_array_equal( 

(allBits.array & 0x1 != 0), self.catalog.columns["a_flag"]) 

np.testing.assert_array_equal( 

(allBits.array & 0x2 != 0), self.catalog.columns["b_flag"]) 

np.testing.assert_array_equal( 

(allBits.array & 0x4 != 0), self.catalog.columns["c_flag"]) 

np.testing.assert_array_equal( 

(someBits.array & 0x1 != 0), self.catalog.columns["a_flag"]) 

np.testing.assert_array_equal( 

(someBits.array & 0x2 != 0), self.catalog.columns["c_flag"]) 

 

def testCast(self): 

baseCat = self.catalog.cast(lsst.afw.table.BaseCatalog) 

baseCat.cast(lsst.afw.table.SourceCatalog) 

 

def testFootprints(self): 

'''Test round-tripping Footprints (inc. HeavyFootprints) to FITS 

''' 

src1 = self.catalog.addNew() 

src2 = self.catalog.addNew() 

src3 = self.catalog.addNew() 

self.fillRecord(src1) 

self.fillRecord(src2) 

self.fillRecord(src3) 

src2.setParent(src1.getId()) 

 

W, H = 100, 100 

mim = lsst.afw.image.MaskedImageF(W, H) 

im = mim.getImage() 

msk = mim.getMask() 

var = mim.getVariance() 

x, y = np.meshgrid(np.arange(W, dtype=int), np.arange(H, dtype=int)) 

im.array[:] = y*1E6 + x*1E3 

msk.array[:] = (y << 8) | x 

var.array[:] = y*1E2 + x 

spanSet = lsst.afw.geom.SpanSet.fromShape(20).shiftedBy(50, 50) 

circ = lsst.afw.detection.Footprint(spanSet) 

heavy = lsst.afw.detection.makeHeavyFootprint(circ, mim) 

src2.setFootprint(heavy) 

 

for i, src in enumerate(self.catalog): 

if src != src2: 

spanSet = lsst.afw.geom.SpanSet.fromShape(1 + i*2).shiftedBy(50, 50) 

src.setFootprint(lsst.afw.detection.Footprint(spanSet)) 

 

# insert this HeavyFootprint into an otherwise blank image (for comparing the results) 

mim2 = lsst.afw.image.MaskedImageF(W, H) 

heavy.insert(mim2) 

 

with lsst.utils.tests.getTempFilePath(".fits") as fn: 

self.catalog.writeFits(fn) 

 

cat2 = lsst.afw.table.SourceCatalog.readFits(fn) 

r2 = cat2[-2] 

h2 = r2.getFootprint() 

self.assertTrue(h2.isHeavy()) 

mim3 = lsst.afw.image.MaskedImageF(W, H) 

h2.insert(mim3) 

 

self.assertFalse(cat2[-1].getFootprint().isHeavy()) 

self.assertFalse(cat2[-3].getFootprint().isHeavy()) 

self.assertFalse(cat2[0].getFootprint().isHeavy()) 

self.assertFalse(cat2[1].getFootprint().isHeavy()) 

self.assertFalse(cat2[2].getFootprint().isHeavy()) 

 

if False: 

# Write out before-n-after FITS images 

for MI in [mim, mim2, mim3]: 

f, fn2 = tempfile.mkstemp(prefix='testHeavyFootprint-', suffix='.fits') 

os.close(f) 

MI.writeFits(fn2) 

print('wrote', fn2) 

 

self.assertFloatsEqual(mim2.getImage().getArray(), mim3.getImage().getArray()) 

self.assertFloatsEqual(mim2.getMask().getArray(), mim3.getMask().getArray()) 

self.assertFloatsEqual(mim2.getVariance().getArray(), mim3.getVariance().getArray()) 

 

im3 = mim3.getImage() 

ma3 = mim3.getMask() 

va3 = mim3.getVariance() 

for y in range(H): 

for x in range(W): 

if circ.contains(lsst.geom.Point2I(x, y)): 

self.assertEqual(im[x, y, lsst.afw.image.PARENT], im3[x, y, lsst.afw.image.PARENT]) 

self.assertEqual(msk[x, y, lsst.afw.image.PARENT], ma3[x, y, lsst.afw.image.PARENT]) 

self.assertEqual(var[x, y, lsst.afw.image.PARENT], va3[x, y, lsst.afw.image.PARENT]) 

else: 

self.assertEqual(im3[x, y, lsst.afw.image.PARENT], 0.) 

self.assertEqual(ma3[x, y, lsst.afw.image.PARENT], 0.) 

self.assertEqual(va3[x, y, lsst.afw.image.PARENT], 0.) 

 

cat3 = lsst.afw.table.SourceCatalog.readFits( 

fn, flags=lsst.afw.table.SOURCE_IO_NO_HEAVY_FOOTPRINTS) 

for src in cat3: 

self.assertFalse(src.getFootprint().isHeavy()) 

cat4 = lsst.afw.table.SourceCatalog.readFits( 

fn, flags=lsst.afw.table.SOURCE_IO_NO_FOOTPRINTS) 

for src in cat4: 

self.assertIsNone(src.getFootprint()) 

 

self.catalog.writeFits( 

fn, flags=lsst.afw.table.SOURCE_IO_NO_HEAVY_FOOTPRINTS) 

cat5 = lsst.afw.table.SourceCatalog.readFits(fn) 

for src in cat5: 

self.assertFalse(src.getFootprint().isHeavy()) 

 

self.catalog.writeFits( 

fn, flags=lsst.afw.table.SOURCE_IO_NO_FOOTPRINTS) 

cat6 = lsst.afw.table.SourceCatalog.readFits(fn) 

for src in cat6: 

self.assertIsNone(src.getFootprint()) 

 

def testIdFactory(self): 

expId = int(1257198) 

reserved = 32 

factory = lsst.afw.table.IdFactory.makeSource(expId, reserved) 

id1 = factory() 

id2 = factory() 

self.assertEqual(id2 - id1, 1) 

factory.notify(0xFFFFFFFF) 

with self.assertRaises(lsst.pex.exceptions.LengthError): 

factory() 

with self.assertRaises(lsst.pex.exceptions.InvalidParameterError): 

factory.notify(0x1FFFFFFFF) 

with self.assertRaises(lsst.pex.exceptions.InvalidParameterError): 

lsst.afw.table.IdFactory.makeSource(0x1FFFFFFFF, reserved) 

 

def testFamilies(self): 

self.catalog.sort() 

parents = self.catalog.getChildren(0) 

self.assertEqual(list(parents), list(self.catalog)) 

parentKey = lsst.afw.table.SourceTable.getParentKey() 

for parent in parents: 

self.assertEqual(parent.get(parentKey), 0) 

for i in range(10): 

child = self.catalog.addNew() 

self.fillRecord(child) 

child.set(parentKey, parent.getId()) 

for parent in parents: 

children, ids = self.catalog.getChildren( 

parent.getId(), [record.getId() for record in self.catalog]) 

self.assertEqual(len(children), 10) 

self.assertEqual(len(children), len(ids)) 

for child, id in zip(children, ids): 

self.assertEqual(child.getParent(), parent.getId()) 

self.assertEqual(child.getId(), id) 

 

# Check detection of unsorted catalog 

self.catalog.sort(self.instFluxKey) 

with self.assertRaises(AssertionError): 

self.catalog.getChildren(0) 

self.catalog.sort(parentKey) 

self.catalog.getChildren(0) # Just care this succeeds 

 

def testFitsReadVersion0Compatibility(self): 

cat = lsst.afw.table.SourceCatalog.readFits(os.path.join(testPath, "data/empty-v0.fits")) 

self.assertTrue(cat.getPsfFluxSlot().isValid()) 

self.assertTrue(cat.getApFluxSlot().isValid()) 

self.assertTrue(cat.getGaussianFluxSlot().isValid()) 

self.assertTrue(cat.getModelFluxSlot().isValid()) 

self.assertTrue(cat.getCentroidSlot().isValid()) 

self.assertTrue(cat.getShapeSlot().isValid()) 

self.assertEqual(cat.getPsfFluxSlot().getMeasKey(), 

cat.schema.find("flux_psf").key) 

self.assertEqual(cat.getApFluxSlot().getMeasKey(), 

cat.schema.find("flux_sinc").key) 

self.assertEqual(cat.getGaussianFluxSlot().getMeasKey(), 

cat.schema.find("flux_naive").key) 

self.assertEqual(cat.getModelFluxSlot().getMeasKey(), 

cat.schema.find("cmodel_flux").key) 

self.assertEqual(cat.getCentroidSlot().getMeasKey().getX(), 

cat.schema.find("centroid_sdss_x").key) 

self.assertEqual(cat.getCentroidSlot().getMeasKey().getY(), 

cat.schema.find("centroid_sdss_y").key) 

self.assertEqual(cat.getShapeSlot().getMeasKey().getIxx(), 

cat.schema.find("shape_hsm_moments_xx").key) 

self.assertEqual(cat.getShapeSlot().getMeasKey().getIyy(), 

cat.schema.find("shape_hsm_moments_yy").key) 

self.assertEqual(cat.getShapeSlot().getMeasKey().getIxy(), 

cat.schema.find("shape_hsm_moments_xy").key) 

self.assertEqual(cat.getPsfFluxSlot().getErrKey(), 

cat.schema.find("flux_psf_err").key) 

self.assertEqual(cat.getApFluxSlot().getErrKey(), 

cat.schema.find("flux_sinc_err").key) 

self.assertEqual(cat.getGaussianFluxSlot().getErrKey(), 

cat.schema.find("flux_naive_err").key) 

self.assertEqual(cat.getModelFluxSlot().getErrKey(), 

cat.schema.find("cmodel_flux_err").key) 

self.assertEqual( 

cat.getCentroidSlot().getErrKey(), 

lsst.afw.table.CovarianceMatrix2fKey(cat.schema["centroid_sdss_err"], ["x", "y"])) 

self.assertEqual( 

cat.getShapeSlot().getErrKey(), 

lsst.afw.table.CovarianceMatrix3fKey(cat.schema["shape_hsm_moments_err"], ["xx", "yy", "xy"])) 

self.assertEqual(cat.getPsfFluxSlot().getFlagKey(), 

cat.schema.find("flux_psf_flags").key) 

self.assertEqual(cat.getApFluxSlot().getFlagKey(), 

cat.schema.find("flux_sinc_flags").key) 

self.assertEqual(cat.getGaussianFluxSlot().getFlagKey(), 

cat.schema.find("flux_naive_flags").key) 

self.assertEqual(cat.getModelFluxSlot().getFlagKey(), 

cat.schema.find("cmodel_flux_flags").key) 

self.assertEqual(cat.getCentroidSlot().getFlagKey(), 

cat.schema.find("centroid_sdss_flags").key) 

self.assertEqual(cat.getShapeSlot().getFlagKey(), 

cat.schema.find("shape_hsm_moments_flags").key) 

 

def testFitsReadVersion1Compatibility(self): 

"""Test reading of catalogs with version 1 schema 

 

Version 1 catalogs need to have added aliases from Sigma->Err and 

from `_flux`->`_instFlux`. 

""" 

cat = lsst.afw.table.SourceCatalog.readFits( 

os.path.join(testPath, "data", "sourceTable-v1.fits")) 

self.assertEqual( 

cat.getCentroidSlot().getErrKey(), 

lsst.afw.table.CovarianceMatrix2fKey( 

cat.schema["slot_Centroid"], 

["x", "y"])) 

self.assertEqual( 

cat.getShapeSlot().getErrKey(), 

lsst.afw.table.CovarianceMatrix3fKey(cat.schema["slot_Shape"], ["xx", "yy", "xy"])) 

# check the flux->instFlux conversion 

self.assertEqual(cat.schema["a_flux"].asKey(), cat.schema["a_instFlux"].asKey()) 

self.assertEqual(cat.schema["a_fluxSigma"].asKey(), cat.schema["a_instFluxErr"].asKey()) 

 

def testFitsReadVersion2CompatibilityRealSourceCatalog(self): 

"""DM-15891: some fields were getting aliases they shouldn't have.""" 

cat = lsst.afw.table.SourceCatalog.readFits( 

os.path.join(testPath, "data", "sourceCatalog-hsc-v2.fits")) 

self.assertNotIn('base_SdssShape_flux_xxinstFlux', cat.schema) 

self.assertIn('base_SdssShape_instFlux_xx_Cov', cat.schema) 

self.assertNotIn('base_Blendedness_abs_flux_cinstFlux', cat.schema) 

 

def testFitsReadVersion2CompatibilityRealCoaddMeasCatalog(self): 

"""DM-16068: some fields were not getting aliases they should have 

 

In particular, the alias setting relies on flux fields having their 

units set properly. Prior to a resolution of DM-16068, the units 

were not getting set for several CModel flux fields and one deblender 

field (deblend_psfFlux), and thus were not getting the 

`_flux`->`_instFlux` aliases set. 

 

NOTE: this test will (is meant to) fail on the read until DM-16068 is 

resolved. The error is: 

 

lsst::pex::exceptions::NotFoundError: 'Field or subfield with 

name 'modelfit_CModel_instFlux' not found with type 'D'.' 

""" 

cat = lsst.afw.table.SourceCatalog.readFits( 

os.path.join(testPath, "data", "deepCoadd_meas_HSC_v2.fits")) 

self.assertIn('modelfit_CModel_instFlux', cat.schema) 

self.assertIn('modelfit_CModel_instFluxErr', cat.schema) 

self.assertIn('modelfit_CModel_instFlux_inner', cat.schema) 

self.assertIn('modelfit_CModel_dev_instFlux_inner', cat.schema) 

self.assertIn('modelfit_CModel_exp_instFlux_inner', cat.schema) 

self.assertIn('modelfit_CModel_initial_instFlux_inner', cat.schema) 

 

def testFitsVersion2Compatibility(self): 

"""Test reading of catalogs with version 2 schema 

 

Version 2 catalogs need to have added aliases from `_flux`->`_instFlux`. 

""" 

cat = lsst.afw.table.SourceCatalog.readFits(os.path.join(testPath, "data", "sourceTable-v2.fits")) 

# check the flux->instFlux conversion 

self.assertEqual(cat.schema["a_flux"].asKey(), cat.schema["a_instFlux"].asKey()) 

self.assertEqual(cat.schema["a_fluxErr"].asKey(), cat.schema["a_instFluxErr"].asKey()) 

 

def testDM1083(self): 

schema = lsst.afw.table.SourceTable.makeMinimalSchema() 

st = lsst.afw.table.SourceTable.make(schema) 

cat = lsst.afw.table.SourceCatalog(st) 

tmp = lsst.afw.table.SourceCatalog(cat.getTable()) 

record = tmp.addNew() 

cat.extend(tmp) 

self.assertEqual(cat[0].getId(), record.getId()) 

# check that the same record is in both catalogs (not a copy) 

record.setId(15) 

self.assertEqual(cat[0].getId(), record.getId()) 

 

def testSlotUndefine(self): 

"""Test that we can correctly define and undefine a slot after a SourceTable has been created""" 

schema = lsst.afw.table.SourceTable.makeMinimalSchema() 

key = schema.addField("a_instFlux", type=np.float64, doc="flux field") 

table = lsst.afw.table.SourceTable.make(schema) 

table.definePsfFlux("a") 

self.assertEqual(table.getPsfFluxSlot().getMeasKey(), key) 

table.schema.getAliasMap().erase("slot_PsfFlux") 

self.assertFalse(table.getPsfFluxSlot().isValid()) 

 

def testOldFootprintPersistence(self): 

"""Test that we can still read SourceCatalogs with (Heavy)Footprints saved by an older 

version of the pipeline with a different format. 

""" 

filename = os.path.join(testPath, "data", "old-footprint-persistence.fits") 

catalog1 = lsst.afw.table.SourceCatalog.readFits(filename) 

self.assertEqual(len(catalog1), 2) 

with self.assertRaises(LookupError): 

catalog1.schema.find("footprint") 

fp1 = catalog1[0].getFootprint() 

fp2 = catalog1[1].getFootprint() 

self.assertEqual(fp1.getArea(), 495) 

self.assertEqual(fp2.getArea(), 767) 

self.assertFalse(fp1.isHeavy()) 

self.assertTrue(fp2.isHeavy()) 

self.assertEqual(len(fp1.getSpans()), 29) 

self.assertEqual(len(fp2.getSpans()), 44) 

self.assertEqual(len(fp1.getPeaks()), 1) 

self.assertEqual(len(fp2.getPeaks()), 1) 

self.assertEqual(fp1.getBBox(), 

lsst.geom.Box2I(lsst.geom.Point2I(129, 2), lsst.geom.Extent2I(25, 29))) 

self.assertEqual(fp2.getBBox(), 

lsst.geom.Box2I(lsst.geom.Point2I(1184, 2), lsst.geom.Extent2I(78, 38))) 

hfp = lsst.afw.detection.HeavyFootprintF(fp2) 

self.assertEqual(len(hfp.getImageArray()), fp2.getArea()) 

self.assertEqual(len(hfp.getMaskArray()), fp2.getArea()) 

self.assertEqual(len(hfp.getVarianceArray()), fp2.getArea()) 

catalog2 = lsst.afw.table.SourceCatalog.readFits( 

filename, flags=lsst.afw.table.SOURCE_IO_NO_HEAVY_FOOTPRINTS) 

self.assertEqual(list(fp1.getSpans()), 

list(catalog2[0].getFootprint().getSpans())) 

self.assertEqual(list(fp2.getSpans()), 

list(catalog2[1].getFootprint().getSpans())) 

self.assertFalse(catalog2[1].getFootprint().isHeavy()) 

catalog3 = lsst.afw.table.SourceCatalog.readFits( 

filename, flags=lsst.afw.table.SOURCE_IO_NO_FOOTPRINTS) 

self.assertEqual(catalog3[0].getFootprint(), None) 

self.assertEqual(catalog3[1].getFootprint(), None) 

 

def _testFluxSlot(self, slotName): 

"""Demonstrate that we can create & use the named Flux slot.""" 

schema = lsst.afw.table.SourceTable.makeMinimalSchema() 

baseName = "afw_Test" 

instFluxKey = schema.addField("%s_instFlux" % (baseName,), type=np.float64, doc="flux") 

errKey = schema.addField("%s_instFluxErr" % (baseName,), type=np.float64, doc="flux uncertainty") 

flagKey = schema.addField("%s_flag" % (baseName,), type="Flag", doc="flux flag") 

catalog = lsst.afw.table.SourceCatalog(schema) 

table = catalog.table 

 

# Initially, the slot is undefined. 

self.assertFalse(getattr(table, "get%sSlot" % (slotName,))().isValid()) 

 

# After definition, it maps to the keys defined above. 

getattr(table, "define%s" % (slotName,))(baseName) 

self.assertTrue(getattr(table, "get%sSlot" % (slotName,))().isValid()) 

self.assertEqual(getattr(table, "get%sSlot" % (slotName,))().getMeasKey(), instFluxKey) 

self.assertEqual(getattr(table, "get%sSlot" % (slotName,))().getErrKey(), errKey) 

self.assertEqual(getattr(table, "get%sSlot" % (slotName,))().getFlagKey(), flagKey) 

 

# We should be able to retrieve arbitrary values set in records. 

record = catalog.addNew() 

instFlux, err, flag = 10.0, 1.0, False 

record.set(instFluxKey, instFlux) 

record.set(errKey, err) 

record.set(flagKey, flag) 

instFluxName = slotName.replace("Flux", "InstFlux") 

self.assertEqual(getattr(record, "get%s" % (instFluxName,))(), instFlux) 

self.assertEqual(getattr(record, "get%sErr" % (instFluxName,))(), err) 

self.assertEqual(getattr(record, "get%sFlag" % (slotName,))(), flag) 

 

# Should also be able to retrieve them as columns from the catalog 

self.assertEqual(getattr(catalog, f"get{instFluxName}")()[0], instFlux) 

self.assertEqual(getattr(catalog, f"get{instFluxName}Err")()[0], err) 

 

# And we should be able to delete the slot, breaking the mapping. 

table.schema.getAliasMap().erase("slot_%s" % (slotName,)) 

self.assertFalse(getattr(table, "get%sSlot" % (slotName,))().isValid()) 

self.assertNotEqual(getattr(table, "get%sSlot" % (slotName,))().getMeasKey(), instFluxKey) 

self.assertNotEqual(getattr(table, "get%sSlot" % (slotName,))().getErrKey(), errKey) 

self.assertNotEqual(getattr(table, "get%sSlot" % (slotName,))().getFlagKey(), flagKey) 

 

# When the slot has been deleted, attempting to access it should 

# throw a LogicError. 

with self.assertRaises(lsst.pex.exceptions.LogicError): 

getattr(catalog, f"get{instFluxName}")() 

with self.assertRaises(lsst.pex.exceptions.LogicError): 

getattr(catalog, f"get{instFluxName}Err")() 

 

def testFluxSlots(self): 

"""Check that all the expected flux slots are present & correct.""" 

for slotName in ["ApFlux", "CalibFlux", "GaussianFlux", "ModelFlux", 

"PsfFlux"]: 

self._testFluxSlot(slotName) 

 

# But, of course, we should not accept a slot which hasn't be defined. 

with self.assertRaises(AttributeError): 

self._testFluxSlot("NotExtantFlux") 

 

def testStr(self): 

"""Check that the str() produced on a catalog contains expected things.""" 

string = str(self.catalog) 

for field in ('id', 'coord_ra', 'coord_dec'): 

self.assertIn(field, string) 

 

def testRepr(self): 

"""Check that the repr() produced on a catalog contains expected things.""" 

string = repr(self.catalog) 

self.assertIn(str(type(self.catalog)), string) 

for field in ('id', 'coord_ra', 'coord_dec'): 

self.assertIn(field, string) 

 

def testStrNonContiguous(self): 

"""Check that str() doesn't fail on non-contiguous tables.""" 

del self.catalog[1] 

string = str(self.catalog) 

self.assertIn('Non-contiguous afw.Catalog of 2 rows.', string) 

for field in ('id', 'coord_ra', 'coord_dec'): 

self.assertIn(field, string) 

 

def testRecordStr(self): 

"""Test that str(record) contains expected things.""" 

string = str(self.catalog[0]) 

for field in ('id: 50', 'coord_ra: nan', 'coord_dec: nan'): 

self.assertIn(field, string) 

 

def testRecordRepr(self): 

"""Test that repr(record) contains expected things.""" 

string = repr(self.catalog[0]) 

self.assertIn(str(type(self.catalog[0])), string) 

for field in ('id: 50', 'coord_ra: nan', 'coord_dec: nan'): 

self.assertIn(field, string) 

 

def testGetNonContiguous(self): 

"""Check that we can index on non-contiguous tables""" 

# Make a non-contiguous catalog 

nonContiguous = type(self.catalog)(self.catalog.table) 

for rr in reversed(self.catalog): 

nonContiguous.append(rr) 

num = len(self.catalog) 

# Check assumptions 

self.assertFalse(nonContiguous.isContiguous()) # We managed to produce a non-contiguous catalog 

self.assertEqual(len(set(self.catalog["id"])), num) # ID values are unique 

# Indexing with boolean array 

select = np.zeros(num, dtype=bool) 

select[1] = True 

self.assertEqual(nonContiguous[np.flip(select, 0)]["id"], self.catalog[select]["id"]) 

# Extracting a number column 

column = "a_instFlux" 

array = nonContiguous[column] 

self.assertFloatsEqual(np.flip(array, 0), self.catalog[column]) 

with self.assertRaises(ValueError): 

array[1] = 1.2345 # Should be immutable 

# Extracting a flag column 

column = "a_flag" 

array = nonContiguous[column] 

np.testing.assert_equal(np.flip(array, 0), self.catalog[column]) 

with self.assertRaises(ValueError): 

array[1] = True # Should be immutable 

 

 

class MemoryTester(lsst.utils.tests.MemoryTestCase): 

pass 

 

 

def setup_module(module): 

lsst.utils.tests.init() 

 

 

743 ↛ 744line 743 didn't jump to line 744, because the condition on line 743 was never trueif __name__ == "__main__": 

lsst.utils.tests.init() 

unittest.main()