Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

# 

# LSST Data Management System 

# Copyright 2008, 2009, 2010 LSST Corporation. 

# 

# This product includes software developed by the 

# LSST Project (http://www.lsst.org/). 

# 

# 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 LSST License Statement and 

# the GNU General Public License along with this program. If not, 

# see <http://www.lsstcorp.org/LegalNotices/>. 

# 

import math 

import re 

import unittest 

 

import numpy as np 

from numpy.testing import assert_allclose 

 

import lsst.utils.tests 

import lsst.pex.exceptions as pexExcept 

import lsst.geom 

import lsst.afw.image as afwImage 

import lsst.afw.math as afwMath 

 

 

def makeGaussianKernelList(kWidth, kHeight, gaussParamsList): 

"""Create a list of gaussian kernels. 

 

This is useful for constructing a LinearCombinationKernel. 

 

Inputs: 

- kWidth, kHeight: width and height of kernel 

- gaussParamsList: a list of parameters for GaussianFunction2D (each a 3-tuple of floats) 

""" 

kVec = [] 

for majorSigma, minorSigma, angle in gaussParamsList: 

kFunc = afwMath.GaussianFunction2D(majorSigma, minorSigma, angle) 

kVec.append(afwMath.AnalyticKernel(kWidth, kHeight, kFunc)) 

return kVec 

 

 

def makeDeltaFunctionKernelList(kWidth, kHeight): 

"""Create a list of delta function kernels 

 

This is useful for constructing a LinearCombinationKernel. 

""" 

kVec = [] 

for activeCol in range(kWidth): 

for activeRow in range(kHeight): 

kVec.append(afwMath.DeltaFunctionKernel( 

kWidth, kHeight, lsst.geom.Point2I(activeCol, activeRow))) 

return kVec 

 

 

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

"""A test case for Kernels""" 

 

def testAnalyticKernel(self): 

"""Test AnalyticKernel using a Gaussian function 

""" 

kWidth = 5 

kHeight = 8 

 

gaussFunc = afwMath.GaussianFunction2D(1.0, 1.0, 0.0) 

kernel = afwMath.AnalyticKernel(kWidth, kHeight, gaussFunc) 

self.basicTests(kernel, 3, dimMustMatch=False) 

 

kernelResized = self.verifyResized(kernel) 

self.basicTests(kernelResized, 3, dimMustMatch=False) 

 

fArr = np.zeros( 

shape=[kernel.getWidth(), kernel.getHeight()], dtype=float) 

for xsigma in (0.1, 1.0, 3.0): 

for ysigma in (0.1, 1.0, 3.0): 

gaussFunc.setParameters((xsigma, ysigma, 0.0)) 

# compute array of function values and normalize 

for row in range(kernel.getHeight()): 

y = row - kernel.getCtrY() 

for col in range(kernel.getWidth()): 

x = col - kernel.getCtrX() 

fArr[col, row] = gaussFunc(x, y) 

fArr /= fArr.sum() 

 

kernel.setKernelParameters((xsigma, ysigma, 0.0)) 

kImage = afwImage.ImageD(kernel.getDimensions()) 

kernel.computeImage(kImage, True) 

 

kArr = kImage.getArray().transpose() 

99 ↛ 100line 99 didn't jump to line 100, because the condition on line 99 was never true if not np.allclose(fArr, kArr): 

self.fail("%s = %s != %s for xsigma=%s, ysigma=%s" % 

(kernel.__class__.__name__, kArr, fArr, xsigma, ysigma)) 

 

kernel.setKernelParameters((0.5, 1.1, 0.3)) 

kernelClone = kernel.clone() 

errStr = self.compareKernels(kernel, kernelClone) 

106 ↛ 107line 106 didn't jump to line 107, because the condition on line 106 was never true if errStr: 

self.fail(errStr) 

 

kernel.setKernelParameters((1.5, 0.2, 0.7)) 

errStr = self.compareKernels(kernel, kernelClone) 

111 ↛ 112line 111 didn't jump to line 112, because the condition on line 111 was never true if not errStr: 

self.fail( 

"Clone was modified by changing original's kernel parameters") 

 

self.verifyCache(kernel, hasCache=False) 

 

def verifyResized(self, kernel, testClip=True, oddPadRaises=False): 

"""Verify kernels can be resized properly. 

 

Parameters 

---------- 

testClip : bool 

Test whether a kernel can be safely resized such that one 

dimension is shorter than original. 

oddPadRaises : bool 

Test that attempting to resize by an odd number of pixels raises 

an InvalidParameterError. 

Fixed/Delta Kernels cannot be resized by an odd amount because 

they are padded/clipped rather than reevalutated like Analytic Kernels. 

 

Returns 

------- 

kernelResized: `Kernel` 

The last resized Kernel that was instantiated and tested 

""" 

 

kWidth, kHeight = kernel.getDimensions() 

 

badDims = [(0, 0), (0, 1), (1, 0), (-1, 1), (3, -3)] # impossible kernel dimensions 

goodPads = [(0, 0), (4, 2), (2, 4)] # all kernels can resize by even, non-negative number of pixels 

oddPads = [(3, 3), (1, 3), (3, 2), (0, 3)] # at least one padding dimension is odd 

clippingPads = [(-2, -2), (2, -2), (-2, 2)] # at least one dimension is smaller than orig 

 

if oddPadRaises: 

badDims.extend([(kWidth + w, kHeight + h) for (w, h) in oddPads]) 

else: 

goodPads.extend(oddPads) 

 

if testClip: 

goodPads.extend(clippingPads) 

 

# Check that error is raised when bad dimensions specified (and optionally odd padding amounts) 

for badWidth, badHeight in badDims: 

with self.assertRaises(pexExcept.InvalidParameterError): 

kernelResized = kernel.resized(badWidth, badHeight) 

 

# Check that resizing is successful 

for padX, padY in goodPads: 

# Do not test if padding will make resized kernel smaller than 0 

160 ↛ 161line 160 didn't jump to line 161, because the condition on line 160 was never true if kWidth <= -padX or kHeight <= -padY: 

with self.assertRaises(pexExcept.InvalidParameterError): 

kernelResized = kernel.resized(kWidth + padX, kHeight + padY) 

kernelResized = kernel.resized(kWidth + padX, kHeight + padY) 

self.assertEqual(kernel.getWidth() + padX, kernelResized.getWidth()) 

self.assertEqual(kernel.getHeight() + padY, kernelResized.getHeight()) 

errStr = self.compareResizedKernels(kernel, kernelResized) 

167 ↛ 168line 167 didn't jump to line 168, because the condition on line 167 was never true if errStr: 

self.fail(errStr) 

 

return kernelResized 

 

def verifyCache(self, kernel, hasCache=False): 

"""Verify the kernel cache 

 

@param kernel: kernel to test 

@param hasCache: set True if this kind of kernel supports a cache, False otherwise 

""" 

for cacheSize in (0, 100, 2000): 

kernel.computeCache(cacheSize) 

self.assertEqual(kernel.getCacheSize(), 

cacheSize if hasCache else 0) 

kernelCopy = kernel.clone() 

self.assertEqual(kernelCopy.getCacheSize(), kernel.getCacheSize()) 

 

def testShrinkGrowBBox(self): 

"""Test Kernel methods shrinkBBox and growBBox 

""" 

boxStart = lsst.geom.Point2I(3, -3) 

for kWidth in (1, 2, 6): 

for kHeight in (1, 2, 5): 

for deltaWidth in (-1, 0, 1, 20): 

fullWidth = kWidth + deltaWidth 

for deltaHeight in (-1, 0, 1, 20): 

fullHeight = kHeight + deltaHeight 

kernel = afwMath.DeltaFunctionKernel( 

kWidth, kHeight, lsst.geom.Point2I(0, 0)) 

fullBBox = lsst.geom.Box2I( 

boxStart, lsst.geom.Extent2I(fullWidth, fullHeight)) 

if (fullWidth < kWidth) or (fullHeight < kHeight): 

self.assertRaises( 

Exception, kernel.shrinkBBox, fullBBox) 

continue 

 

shrunkBBox = kernel.shrinkBBox(fullBBox) 

self.assertEqual(shrunkBBox.getWidth(), 

fullWidth + 1 - kWidth) 

self.assertEqual(shrunkBBox.getHeight(), 

fullHeight + 1 - kHeight) 

self.assertEqual(shrunkBBox.getMinX(), 

boxStart[0] + kernel.getCtrX()) 

self.assertEqual(shrunkBBox.getMinY(), 

boxStart[1] + kernel.getCtrY()) 

newFullBBox = kernel.growBBox(shrunkBBox) 

self.assertEqual(newFullBBox, fullBBox, 

"growBBox(shrinkBBox(x)) != x") 

 

def testDeltaFunctionKernel(self): 

"""Test DeltaFunctionKernel 

""" 

for kWidth in range(1, 4): 

for kHeight in range(1, 4): 

for activeCol in range(kWidth): 

for activeRow in range(kHeight): 

kernel = afwMath.DeltaFunctionKernel(kWidth, kHeight, 

lsst.geom.Point2I(activeCol, activeRow)) 

kImage = afwImage.ImageD(kernel.getDimensions()) 

kSum = kernel.computeImage(kImage, False) 

self.assertEqual(kSum, 1.0) 

kArr = kImage.getArray().transpose() 

self.assertEqual(kArr[activeCol, activeRow], 1.0) 

kArr[activeCol, activeRow] = 0.0 

self.assertEqual(kArr.sum(), 0.0) 

 

errStr = self.compareKernels(kernel, kernel.clone()) 

235 ↛ 236line 235 didn't jump to line 236, because the condition on line 235 was never true if errStr: 

self.fail(errStr) 

 

self.assertRaises(pexExcept.InvalidParameterError, 

afwMath.DeltaFunctionKernel, 0, kHeight, lsst.geom.Point2I(kWidth, kHeight)) 

self.assertRaises(pexExcept.InvalidParameterError, 

afwMath.DeltaFunctionKernel, kWidth, 0, lsst.geom.Point2I(kWidth, kHeight)) 

 

kernel = afwMath.DeltaFunctionKernel(5, 6, lsst.geom.Point2I(1, 1)) 

self.basicTests(kernel, 0) 

 

kernelResized = self.verifyResized(kernel, oddPadRaises=True) 

self.basicTests(kernelResized, 0) 

self.verifyCache(kernel, hasCache=False) 

 

def testFixedKernel(self): 

"""Test FixedKernel using a ramp function 

""" 

kWidth = 5 

kHeight = 6 

 

inArr = np.arange(kWidth * kHeight, dtype=float) 

inArr.shape = [kWidth, kHeight] 

 

inImage = afwImage.ImageD(lsst.geom.Extent2I(kWidth, kHeight)) 

for row in range(inImage.getHeight()): 

for col in range(inImage.getWidth()): 

inImage[col, row, afwImage.LOCAL] = inArr[col, row] 

 

kernel = afwMath.FixedKernel(inImage) 

self.basicTests(kernel, 0) 

 

kernelResized = self.verifyResized(kernel, oddPadRaises=True) 

self.basicTests(kernelResized, 0) 

 

outImage = afwImage.ImageD(kernel.getDimensions()) 

kernel.computeImage(outImage, False) 

 

outArr = outImage.getArray().transpose() 

274 ↛ 275line 274 didn't jump to line 275, because the condition on line 274 was never true if not np.allclose(inArr, outArr): 

self.fail("%s = %s != %s (not normalized)" % 

(kernel.__class__.__name__, inArr, outArr)) 

 

normInArr = inArr / inArr.sum() 

normOutImage = afwImage.ImageD(kernel.getDimensions()) 

kernel.computeImage(normOutImage, True) 

normOutArr = normOutImage.getArray().transpose() 

282 ↛ 283line 282 didn't jump to line 283, because the condition on line 282 was never true if not np.allclose(normOutArr, normInArr): 

self.fail("%s = %s != %s (normalized)" % 

(kernel.__class__.__name__, normInArr, normOutArr)) 

 

errStr = self.compareKernels(kernel, kernel.clone()) 

287 ↛ 288line 287 didn't jump to line 288, because the condition on line 287 was never true if errStr: 

self.fail(errStr) 

 

self.verifyCache(kernel, hasCache=False) 

 

def testLinearCombinationKernelDelta(self): 

"""Test LinearCombinationKernel using a set of delta basis functions 

""" 

kWidth = 3 

kHeight = 2 

 

# create list of kernels 

basisKernelList = makeDeltaFunctionKernelList(kWidth, kHeight) 

basisImArrList = [] 

for basisKernel in basisKernelList: 

basisImage = afwImage.ImageD(basisKernel.getDimensions()) 

basisKernel.computeImage(basisImage, True) 

basisImArrList.append(basisImage.getArray()) 

 

kParams = [0.0]*len(basisKernelList) 

kernel = afwMath.LinearCombinationKernel(basisKernelList, kParams) 

self.assertTrue(kernel.isDeltaFunctionBasis()) 

self.basicTests(kernel, len(kParams)) 

kernelResized = self.verifyResized(kernel, testClip=False, oddPadRaises=True) 

self.basicTests(kernelResized, len(kParams)) 

for ii in range(len(basisKernelList)): 

kParams = [0.0]*len(basisKernelList) 

kParams[ii] = 1.0 

kernel.setKernelParameters(kParams) 

kIm = afwImage.ImageD(kernel.getDimensions()) 

kernel.computeImage(kIm, True) 

kImArr = kIm.getArray() 

319 ↛ 320line 319 didn't jump to line 320, because the condition on line 319 was never true if not np.allclose(kImArr, basisImArrList[ii]): 

self.fail("%s = %s != %s for the %s'th basis kernel" % 

(kernel.__class__.__name__, kImArr, basisImArrList[ii], ii)) 

 

kernelClone = kernel.clone() 

errStr = self.compareKernels(kernel, kernelClone) 

325 ↛ 326line 325 didn't jump to line 326, because the condition on line 325 was never true if errStr: 

self.fail(errStr) 

 

self.verifyCache(kernel, hasCache=False) 

 

def testComputeImageRaise(self): 

"""Test Kernel.computeImage raises OverflowException iff doNormalize True and kernel sum exactly 0 

""" 

kWidth = 4 

kHeight = 3 

 

polyFunc1 = afwMath.PolynomialFunction1D(0) 

polyFunc2 = afwMath.PolynomialFunction2D(0) 

analKernel = afwMath.AnalyticKernel(kWidth, kHeight, polyFunc2) 

kImage = afwImage.ImageD(analKernel.getDimensions()) 

for coeff in (-1, -1e-99, 0, 1e99, 1): 

analKernel.setKernelParameters([coeff]) 

 

analKernel.computeImage(kImage, False) 

fixedKernel = afwMath.FixedKernel(kImage) 

 

sepKernel = afwMath.SeparableKernel( 

kWidth, kHeight, polyFunc1, polyFunc1) 

sepKernel.setKernelParameters([coeff, coeff]) 

 

kernelList = [] 

kernelList.append(analKernel) 

lcKernel = afwMath.LinearCombinationKernel(kernelList, [1]) 

self.assertFalse(lcKernel.isDeltaFunctionBasis()) 

 

doRaise = (coeff == 0) 

self.basicTestComputeImageRaise( 

analKernel, doRaise, "AnalyticKernel") 

self.basicTestComputeImageRaise( 

fixedKernel, doRaise, "FixedKernel") 

self.basicTestComputeImageRaise( 

sepKernel, doRaise, "SeparableKernel") 

self.basicTestComputeImageRaise( 

lcKernel, doRaise, "LinearCombinationKernel") 

 

lcKernel.setKernelParameters([0]) 

self.basicTestComputeImageRaise( 

lcKernel, True, "LinearCombinationKernel") 

 

def testLinearCombinationKernelAnalytic(self): 

"""Test LinearCombinationKernel using analytic basis kernels. 

 

The basis kernels are mutable so that we can verify that the 

LinearCombinationKernel has private copies of the basis kernels. 

""" 

kWidth = 5 

kHeight = 8 

 

# create list of kernels 

basisImArrList = [] 

basisKernelList = [] 

for basisKernelParams in [(1.2, 0.3, 1.570796), (1.0, 0.2, 0.0)]: 

basisKernelFunction = afwMath.GaussianFunction2D( 

*basisKernelParams) 

basisKernel = afwMath.AnalyticKernel( 

kWidth, kHeight, basisKernelFunction) 

basisImage = afwImage.ImageD(basisKernel.getDimensions()) 

basisKernel.computeImage(basisImage, True) 

basisImArrList.append(basisImage.getArray()) 

basisKernelList.append(basisKernel) 

 

kParams = [0.0]*len(basisKernelList) 

kernel = afwMath.LinearCombinationKernel(basisKernelList, kParams) 

self.assertTrue(not kernel.isDeltaFunctionBasis()) 

self.basicTests(kernel, len(kParams)) 

 

kernelResized = self.verifyResized(kernel) 

self.basicTests(kernelResized, len(kParams)) 

 

# make sure the linear combination kernel has private copies of its basis kernels 

# by altering the local basis kernels and making sure the new images do 

# NOT match 

modBasisImArrList = [] 

for basisKernel in basisKernelList: 

basisKernel.setKernelParameters((0.4, 0.5, 0.6)) 

modBasisImage = afwImage.ImageD(basisKernel.getDimensions()) 

basisKernel.computeImage(modBasisImage, True) 

modBasisImArrList.append(modBasisImage.getArray()) 

 

for ii in range(len(basisKernelList)): 

kParams = [0.0]*len(basisKernelList) 

kParams[ii] = 1.0 

kernel.setKernelParameters(kParams) 

kIm = afwImage.ImageD(kernel.getDimensions()) 

kernel.computeImage(kIm, True) 

kImArr = kIm.getArray() 

416 ↛ 417line 416 didn't jump to line 417, because the condition on line 416 was never true if not np.allclose(kImArr, basisImArrList[ii]): 

self.fail("%s = %s != %s for the %s'th basis kernel" % 

(kernel.__class__.__name__, kImArr, basisImArrList[ii], ii)) 

419 ↛ 420line 419 didn't jump to line 420, because the condition on line 419 was never true if np.allclose(kImArr, modBasisImArrList[ii]): 

self.fail("%s = %s == %s for *modified* %s'th basis kernel" % 

(kernel.__class__.__name__, kImArr, modBasisImArrList[ii], ii)) 

 

kernelClone = kernel.clone() 

errStr = self.compareKernels(kernel, kernelClone) 

425 ↛ 426line 425 didn't jump to line 426, because the condition on line 425 was never true if errStr: 

self.fail(errStr) 

 

self.verifyCache(kernel, hasCache=False) 

 

def testSeparableKernel(self): 

"""Test SeparableKernel using a Gaussian function 

""" 

kWidth = 5 

kHeight = 8 

 

gaussFunc1 = afwMath.GaussianFunction1D(1.0) 

kernel = afwMath.SeparableKernel( 

kWidth, kHeight, gaussFunc1, gaussFunc1) 

self.basicTests(kernel, 2) 

 

kernelResized = self.verifyResized(kernel) 

self.basicTests(kernelResized, 2) 

 

fArr = np.zeros( 

shape=[kernel.getWidth(), kernel.getHeight()], dtype=float) 

gaussFunc = afwMath.GaussianFunction2D(1.0, 1.0, 0.0) 

for xsigma in (0.1, 1.0, 3.0): 

gaussFunc1.setParameters((xsigma,)) 

for ysigma in (0.1, 1.0, 3.0): 

gaussFunc.setParameters((xsigma, ysigma, 0.0)) 

# compute array of function values and normalize 

for row in range(kernel.getHeight()): 

y = row - kernel.getCtrY() 

for col in range(kernel.getWidth()): 

x = col - kernel.getCtrX() 

fArr[col, row] = gaussFunc(x, y) 

fArr /= fArr.sum() 

 

kernel.setKernelParameters((xsigma, ysigma)) 

kImage = afwImage.ImageD(kernel.getDimensions()) 

kernel.computeImage(kImage, True) 

kArr = kImage.getArray().transpose() 

463 ↛ 464line 463 didn't jump to line 464, because the condition on line 463 was never true if not np.allclose(fArr, kArr): 

self.fail("%s = %s != %s for xsigma=%s, ysigma=%s" % 

(kernel.__class__.__name__, kArr, fArr, xsigma, ysigma)) 

kernelClone = kernel.clone() 

errStr = self.compareKernels(kernel, kernelClone) 

468 ↛ 469line 468 didn't jump to line 469, because the condition on line 468 was never true if errStr: 

self.fail(errStr) 

 

kernel.setKernelParameters((1.2, 0.6)) 

errStr = self.compareKernels(kernel, kernelClone) 

473 ↛ 474line 473 didn't jump to line 474, because the condition on line 473 was never true if not errStr: 

self.fail( 

"Clone was modified by changing original's kernel parameters") 

 

self.verifyCache(kernel, hasCache=True) 

 

def testMakeBadKernels(self): 

"""Attempt to make various invalid kernels; make sure the constructor shows an exception 

""" 

kWidth = 4 

kHeight = 3 

 

gaussFunc1 = afwMath.GaussianFunction1D(1.0) 

gaussFunc2 = afwMath.GaussianFunction2D(1.0, 1.0, 0.0) 

spFunc = afwMath.PolynomialFunction2D(1) 

kernelList = [] 

kernelList.append(afwMath.FixedKernel( 

afwImage.ImageD(lsst.geom.Extent2I(kWidth, kHeight), 0.1))) 

kernelList.append(afwMath.FixedKernel( 

afwImage.ImageD(lsst.geom.Extent2I(kWidth, kHeight), 0.2))) 

 

for numKernelParams in (2, 4): 

spFuncList = [] 

for ii in range(numKernelParams): 

spFuncList.append(spFunc.clone()) 

try: 

afwMath.AnalyticKernel(kWidth, kHeight, gaussFunc2, spFuncList) 

self.fail("Should have failed with wrong # of spatial functions") 

except pexExcept.Exception: 

pass 

 

for numKernelParams in (1, 3): 

spFuncList = [] 

for ii in range(numKernelParams): 

spFuncList.append(spFunc.clone()) 

try: 

afwMath.LinearCombinationKernel(kernelList, spFuncList) 

self.fail("Should have failed with wrong # of spatial functions") 

except pexExcept.Exception: 

pass 

kParamList = [0.2]*numKernelParams 

try: 

afwMath.LinearCombinationKernel(kernelList, kParamList) 

self.fail("Should have failed with wrong # of kernel parameters") 

except pexExcept.Exception: 

pass 

try: 

afwMath.SeparableKernel( 

kWidth, kHeight, gaussFunc1, gaussFunc1, spFuncList) 

self.fail("Should have failed with wrong # of spatial functions") 

except pexExcept.Exception: 

pass 

 

for pointX in range(-1, kWidth+2): 

for pointY in range(-1, kHeight+2): 

if (0 <= pointX < kWidth) and (0 <= pointY < kHeight): 

continue 

try: 

afwMath.DeltaFunctionKernel( 

kWidth, kHeight, lsst.geom.Point2I(pointX, pointY)) 

self.fail("Should have failed with point not on kernel") 

except pexExcept.Exception: 

pass 

 

def testSVAnalyticKernel(self): 

"""Test spatially varying AnalyticKernel using a Gaussian function 

 

Just tests cloning. 

""" 

kWidth = 5 

kHeight = 8 

 

# spatial model 

spFunc = afwMath.PolynomialFunction2D(1) 

 

# spatial parameters are a list of entries, one per kernel parameter; 

# each entry is a list of spatial parameters 

sParams = ( 

(1.0, 1.0, 0.0), 

(1.0, 0.0, 1.0), 

(0.5, 0.5, 0.5), 

) 

 

gaussFunc = afwMath.GaussianFunction2D(1.0, 1.0, 0.0) 

kernel = afwMath.AnalyticKernel(kWidth, kHeight, gaussFunc, spFunc) 

kernel.setSpatialParameters(sParams) 

 

kernelClone = kernel.clone() 

errStr = self.compareKernels(kernel, kernelClone) 

562 ↛ 563line 562 didn't jump to line 563, because the condition on line 562 was never true if errStr: 

self.fail(errStr) 

 

newSParams = ( 

(0.1, 0.2, 0.5), 

(0.1, 0.5, 0.2), 

(0.2, 0.3, 0.3), 

) 

kernel.setSpatialParameters(newSParams) 

errStr = self.compareKernels(kernel, kernelClone) 

572 ↛ 573line 572 didn't jump to line 573, because the condition on line 572 was never true if not errStr: 

self.fail( 

"Clone was modified by changing original's spatial parameters") 

 

# 

# check that we can construct a FixedKernel from a LinearCombinationKernel 

# 

x, y = 100, 200 

kernel2 = afwMath.FixedKernel(kernel, lsst.geom.PointD(x, y)) 

 

self.assertTrue(re.search("AnalyticKernel", kernel.toString())) 

self.assertFalse(kernel2.isSpatiallyVarying()) 

 

self.assertTrue(re.search("FixedKernel", kernel2.toString())) 

self.assertTrue(kernel.isSpatiallyVarying()) 

 

kim = afwImage.ImageD(kernel.getDimensions()) 

kernel.computeImage(kim, True, x, y) 

 

kim2 = afwImage.ImageD(kernel2.getDimensions()) 

kernel2.computeImage(kim2, True) 

 

assert_allclose(kim.getArray(), kim2.getArray()) 

 

def testSVLinearCombinationKernelFixed(self): 

"""Test a spatially varying LinearCombinationKernel whose bases are FixedKernels""" 

kWidth = 3 

kHeight = 2 

 

# create image arrays for the basis kernels 

basisImArrList = [] 

imArr = np.zeros((kWidth, kHeight), dtype=float) 

imArr += 0.1 

imArr[kWidth//2, :] = 0.9 

basisImArrList.append(imArr) 

imArr = np.zeros((kWidth, kHeight), dtype=float) 

imArr += 0.2 

imArr[:, kHeight//2] = 0.8 

basisImArrList.append(imArr) 

 

# create a list of basis kernels from the images 

basisKernelList = [] 

for basisImArr in basisImArrList: 

basisImage = afwImage.makeImageFromArray( 

basisImArr.transpose().copy()) 

kernel = afwMath.FixedKernel(basisImage) 

basisKernelList.append(kernel) 

 

# create spatially varying linear combination kernel 

spFunc = afwMath.PolynomialFunction2D(1) 

 

# spatial parameters are a list of entries, one per kernel parameter; 

# each entry is a list of spatial parameters 

sParams = ( 

(0.0, 1.0, 0.0), 

(0.0, 0.0, 1.0), 

) 

 

kernel = afwMath.LinearCombinationKernel(basisKernelList, spFunc) 

self.assertFalse(kernel.isDeltaFunctionBasis()) 

self.basicTests(kernel, 2, nSpatialParams=3) 

kernel.setSpatialParameters(sParams) 

kImage = afwImage.ImageD(lsst.geom.Extent2I(kWidth, kHeight)) 

for colPos, rowPos, coeff0, coeff1 in [ 

(0.0, 0.0, 0.0, 0.0), 

(1.0, 0.0, 1.0, 0.0), 

(0.0, 1.0, 0.0, 1.0), 

(1.0, 1.0, 1.0, 1.0), 

(0.5, 0.5, 0.5, 0.5), 

]: 

kernel.computeImage(kImage, False, colPos, rowPos) 

kImArr = kImage.getArray().transpose() 

refKImArr = (basisImArrList[0] * coeff0) + \ 

(basisImArrList[1] * coeff1) 

646 ↛ 647line 646 didn't jump to line 647, because the condition on line 646 was never true if not np.allclose(kImArr, refKImArr): 

self.fail("%s = %s != %s at colPos=%s, rowPos=%s" % 

(kernel.__class__.__name__, kImArr, refKImArr, colPos, rowPos)) 

 

sParams = ( 

(0.1, 1.0, 0.0), 

(0.1, 0.0, 1.0), 

) 

kernel.setSpatialParameters(sParams) 

kernelClone = kernel.clone() 

errStr = self.compareKernels(kernel, kernelClone) 

657 ↛ 658line 657 didn't jump to line 658, because the condition on line 657 was never true if errStr: 

self.fail(errStr) 

 

newSParams = ( 

(0.1, 0.2, 0.5), 

(0.1, 0.5, 0.2), 

) 

kernel.setSpatialParameters(newSParams) 

errStr = self.compareKernels(kernel, kernelClone) 

666 ↛ 667line 666 didn't jump to line 667, because the condition on line 666 was never true if not errStr: 

self.fail( 

"Clone was modified by changing original's spatial parameters") 

 

def testSVSeparableKernel(self): 

"""Test spatially varying SeparableKernel using a Gaussian function 

 

Just tests cloning. 

""" 

kWidth = 5 

kHeight = 8 

 

# spatial model 

spFunc = afwMath.PolynomialFunction2D(1) 

 

# spatial parameters are a list of entries, one per kernel parameter; 

# each entry is a list of spatial parameters 

sParams = ( 

(1.0, 1.0, 0.0), 

(1.0, 0.0, 1.0), 

) 

 

gaussFunc = afwMath.GaussianFunction1D(1.0) 

kernel = afwMath.SeparableKernel( 

kWidth, kHeight, gaussFunc, gaussFunc, spFunc) 

kernel.setSpatialParameters(sParams) 

 

kernelClone = kernel.clone() 

errStr = self.compareKernels(kernel, kernelClone) 

695 ↛ 696line 695 didn't jump to line 696, because the condition on line 695 was never true if errStr: 

self.fail(errStr) 

 

newSParams = ( 

(0.1, 0.2, 0.5), 

(0.1, 0.5, 0.2), 

) 

kernel.setSpatialParameters(newSParams) 

errStr = self.compareKernels(kernel, kernelClone) 

704 ↛ 705line 704 didn't jump to line 705, because the condition on line 704 was never true if not errStr: 

self.fail( 

"Clone was modified by changing original's spatial parameters") 

 

def testSetCtr(self): 

"""Test setCtrCol/Row""" 

kWidth = 3 

kHeight = 4 

 

gaussFunc = afwMath.GaussianFunction2D(1.0, 1.0, 0.0) 

kernel = afwMath.AnalyticKernel(kWidth, kHeight, gaussFunc) 

for xCtr in range(kWidth): 

kernel.setCtrX(xCtr) 

for yCtr in range(kHeight): 

kernel.setCtrY(yCtr) 

self.assertEqual(kernel.getCtrX(), xCtr) 

self.assertEqual(kernel.getCtrY(), yCtr) 

 

def testZeroSizeKernel(self): 

"""Creating a kernel with width or height < 1 should raise an exception. 

 

Note: this ignores the default constructors, which produce kernels with height = width = 0. 

The default constructors are only intended to support persistence, not to produce useful kernels. 

""" 

gaussFunc2D = afwMath.GaussianFunction2D(1.0, 1.0, 0.0) 

gaussFunc1D = afwMath.GaussianFunction1D(1.0) 

zeroPoint = lsst.geom.Point2I(0, 0) 

for kWidth in (-1, 0, 1): 

for kHeight in (-1, 0, 1): 

if (kHeight > 0) and (kWidth > 0): 

continue 

if (kHeight >= 0) and (kWidth >= 0): 

# don't try to create an image with negative dimensions 

blankImage = afwImage.ImageF( 

lsst.geom.Extent2I(kWidth, kHeight)) 

self.assertRaises( 

Exception, afwMath.FixedKernel, blankImage) 

self.assertRaises( 

Exception, afwMath.AnalyticKernel, kWidth, kHeight, gaussFunc2D) 

self.assertRaises(Exception, afwMath.SeparableKernel, 

kWidth, kHeight, gaussFunc1D, gaussFunc1D) 

self.assertRaises( 

Exception, afwMath.DeltaFunctionKernel, kWidth, kHeight, zeroPoint) 

 

def testRefactorDeltaLinearCombinationKernel(self): 

"""Test LinearCombinationKernel.refactor with delta function basis kernels 

""" 

kWidth = 4 

kHeight = 3 

 

for spOrder in (0, 1, 2): 

spFunc = afwMath.PolynomialFunction2D(spOrder) 

numSpParams = spFunc.getNParameters() 

 

basisKernelList = makeDeltaFunctionKernelList(kWidth, kHeight) 

kernel = afwMath.LinearCombinationKernel(basisKernelList, spFunc) 

 

numBasisKernels = kernel.getNKernelParameters() 

maxVal = 1.01 + ((numSpParams - 1) * 0.1) 

sParamList = [np.arange(kInd + 1.0, kInd + maxVal, 0.1) 

for kInd in range(numBasisKernels)] 

kernel.setSpatialParameters(sParamList) 

 

refKernel = kernel.refactor() 

self.assertTrue(refKernel) 

errStr = self.compareKernels( 

kernel, refKernel, compareParams=False) 

771 ↛ 772line 771 didn't jump to line 772, because the condition on line 771 was never true if errStr: 

self.fail("failed with %s for spOrder=%s (numSpCoeff=%s)" % 

(errStr, spOrder, numSpParams)) 

 

def testRefactorGaussianLinearCombinationKernel(self): 

"""Test LinearCombinationKernel.refactor with Gaussian basis kernels 

""" 

kWidth = 4 

kHeight = 3 

 

for spOrder in (0, 1, 2): 

spFunc = afwMath.PolynomialFunction2D(spOrder) 

numSpParams = spFunc.getNParameters() 

 

gaussParamsList = [ 

(1.5, 1.5, 0.0), 

(2.5, 1.5, 0.0), 

(2.5, 1.5, math.pi / 2.0), 

] 

gaussBasisKernelList = makeGaussianKernelList( 

kWidth, kHeight, gaussParamsList) 

kernel = afwMath.LinearCombinationKernel( 

gaussBasisKernelList, spFunc) 

 

numBasisKernels = kernel.getNKernelParameters() 

maxVal = 1.01 + ((numSpParams - 1) * 0.1) 

sParamList = [np.arange(kInd + 1.0, kInd + maxVal, 0.1) 

for kInd in range(numBasisKernels)] 

kernel.setSpatialParameters(sParamList) 

 

refKernel = kernel.refactor() 

self.assertTrue(refKernel) 

errStr = self.compareKernels( 

kernel, refKernel, compareParams=False) 

805 ↛ 806line 805 didn't jump to line 806, because the condition on line 805 was never true if errStr: 

self.fail("failed with %s for spOrder=%s; numSpCoeff=%s" % 

(errStr, spOrder, numSpParams)) 

 

def basicTests(self, kernel, nKernelParams, nSpatialParams=0, dimMustMatch=True): 

"""Basic tests of a kernel""" 

self.assertEqual(kernel.getNSpatialParameters(), nSpatialParams) 

self.assertEqual(kernel.getNKernelParameters(), nKernelParams) 

if nSpatialParams == 0: 

self.assertFalse(kernel.isSpatiallyVarying()) 

for ii in range(nKernelParams+5): 

self.assertRaises(pexExcept.InvalidParameterError, 

kernel.getSpatialFunction, ii) 

else: 

self.assertTrue(kernel.isSpatiallyVarying()) 

for ii in range(nKernelParams): 

kernel.getSpatialFunction(ii) 

for ii in range(nKernelParams, nKernelParams+5): 

self.assertRaises(pexExcept.InvalidParameterError, 

kernel.getSpatialFunction, ii) 

 

# test a range of numbers of parameters, including both valid and 

# invalid sized tuples. 

for nsp in range(nSpatialParams + 2): 

spatialParamsForOneKernel = [1.0]*nsp 

for nkp in range(nKernelParams + 2): 

spatialParams = [spatialParamsForOneKernel]*nkp 

if ((nkp == nKernelParams) and ((nsp == nSpatialParams) or (nkp == 0))): 

kernel.setSpatialParameters(spatialParams) 

if nsp == 0: 

# A non-spatially varying kernel returns an empty tuple, even though 

# it can only be set with a tuple of empty tuples, one 

# per kernel parameter. 

self.assertEqual(kernel.getSpatialParameters(), []) 

else: 

# a spatially varying kernel should return exactly what 

# we set it to be. 

self.assertEqual( 

kernel.getSpatialParameters(), spatialParams) 

else: 

with self.assertRaises(pexExcept.InvalidParameterError): 

kernel.setSpatialParameters(spatialParams) 

 

kernelDim = kernel.getDimensions() 

kernelCtr = kernel.getCtr() 

for dx in (-1, 0, 1): 

xDim = kernelDim.getX() + dx 

for dy in (-1, 0, 1): 

if dx == dy == 0: 

continue 

yDim = kernelDim.getY() + dy 

image = afwImage.ImageD(xDim, yDim) 

if (dx == dy == 0) or not dimMustMatch: 

ksum = kernel.computeImage(image, True) 

self.assertAlmostEqual(ksum, 1.0) 

llBorder = ((image.getDimensions() - 

kernelDim) / 2).truncate() 

predCtr = lsst.geom.Point2I(llBorder + kernelCtr) 

self.assertEqual(kernel.getCtr(), predCtr) 

else: 

self.assertRaises( 

Exception, kernel.computeImage, image, True) 

 

def basicTestComputeImageRaise(self, kernel, doRaise, kernelDescr=""): 

"""Test that computeImage either does or does not raise an exception, as appropriate 

""" 

kImage = afwImage.ImageD(kernel.getDimensions()) 

try: 

kernel.computeImage(kImage, True) 

874 ↛ 875line 874 didn't jump to line 875, because the condition on line 874 was never true if doRaise: 

self.fail(kernelDescr + 

".computeImage should have raised an exception") 

except pexExcept.Exception: 

878 ↛ 879line 878 didn't jump to line 879, because the condition on line 878 was never true if not doRaise: 

self.fail(kernelDescr + 

".computeImage should not have raised an exception") 

 

def compareResizedKernels(self, kernel1, kernel2): 

"""Compare kernels' parameters and images where overlapping, 

ignorning sizes and centers. 

 

return None if they match, else return a string describing 

all differences. 

""" 

retStrs = [] 

890 ↛ 891line 890 didn't jump to line 891, because the condition on line 890 was never true if kernel1.isSpatiallyVarying() != kernel2.isSpatiallyVarying(): 

retStrs.append("isSpatiallyVarying differs: %s != %s" % 

(kernel1.isSpatiallyVarying(), kernel2.isSpatiallyVarying())) 

retStrs = self._compareParams(kernel1, kernel2, retStrs) 

894 ↛ 895line 894 didn't jump to line 895, because the condition on line 894 was never true if retStrs: 

return "; ".join(retStrs) 

 

# New BBox; nothing is being modified. 

bboxIntersection = kernel1.getBBox() 

bboxIntersection.clip(kernel2.getBBox()) 

 

im1 = afwImage.ImageD(kernel1.getDimensions()) 

im2 = afwImage.ImageD(kernel2.getDimensions()) 

posList = self._makePositionList(kernel1) 

 

doNormalize = False 

for pos in posList: 

kernel1.computeImage(im1, doNormalize, pos[0], pos[1]) 

kernel2.computeImage(im2, doNormalize, pos[0], pos[1]) 

 

im1Intersection = afwImage.ImageD(im1, bboxIntersection) 

im2Intersection = afwImage.ImageD(im2, bboxIntersection) 

 

im1Arr = im1Intersection.getArray() 

im2Arr = im2Intersection.getArray() 

915 ↛ 916line 915 didn't jump to line 916, because the condition on line 915 was never true if not np.allclose(im1Arr, im2Arr): 

print("im1Arr =", im1Arr) 

print("im2Arr =", im2Arr) 

return "kernel images do not match at %s with doNormalize=%s" % (pos, doNormalize) 

 

def compareKernels(self, kernel1, kernel2, compareParams=True, newCtr1=(0, 0)): 

"""Compare two kernels; return None if they match, else return a string kernelDescribing a difference. 

 

kernel1: one kernel to test 

kernel2: the other kernel to test 

compareParams: compare spatial parameters and kernel parameters if they exist 

newCtr: if not None then set the center of kernel1 and see if it changes the center of kernel2 

""" 

retStrs = [] 

929 ↛ 930line 929 didn't jump to line 930, because the condition on line 929 was never true if kernel1.getDimensions() != kernel2.getDimensions(): 

retStrs.append("dimensions differ: %s != %s" % 

(kernel1.getDimensions(), kernel2.getDimensions())) 

ctr1 = kernel1.getCtrX(), kernel1.getCtrY() 

ctr2 = kernel2.getCtrX(), kernel2.getCtrY() 

if ctr1 != ctr2: 

retStrs.append("centers differ: %s != %s" % (ctr1, ctr2)) 

936 ↛ 937line 936 didn't jump to line 937, because the condition on line 936 was never true if kernel1.isSpatiallyVarying() != kernel2.isSpatiallyVarying(): 

retStrs.append("isSpatiallyVarying differs: %s != %s" % 

(kernel1.isSpatiallyVarying(), kernel2.isSpatiallyVarying())) 

 

if compareParams: 

retStrs = self._compareParams(kernel1, kernel2, retStrs) 

 

if retStrs: 

return "; ".join(retStrs) 

 

im1 = afwImage.ImageD(kernel1.getDimensions()) 

im2 = afwImage.ImageD(kernel2.getDimensions()) 

posList = self._makePositionList(kernel1) 

 

for doNormalize in (False, True): 

for pos in posList: 

kernel1.computeImage(im1, doNormalize, pos[0], pos[1]) 

kernel2.computeImage(im2, doNormalize, pos[0], pos[1]) 

im1Arr = im1.getArray() 

im2Arr = im2.getArray() 

956 ↛ 957line 956 didn't jump to line 957, because the condition on line 956 was never true if not np.allclose(im1Arr, im2Arr): 

print("im1Arr =", im1Arr) 

print("im2Arr =", im2Arr) 

return "kernel images do not match at %s with doNormalize=%s" % (pos, doNormalize) 

 

961 ↛ exitline 961 didn't return from function 'compareKernels', because the condition on line 961 was never false if newCtr1 is not None: 

kernel1.setCtrX(newCtr1[0]) 

kernel1.setCtrY(newCtr1[1]) 

newCtr2 = kernel2.getCtrX(), kernel2.getCtrY() 

965 ↛ 966line 965 didn't jump to line 966, because the condition on line 965 was never true if ctr2 != newCtr2: 

return "changing center of kernel1 to %s changed the center of kernel2 from %s to %s" % \ 

(newCtr1, ctr2, newCtr2) 

 

def _compareParams(self, kernel1, kernel2, retStrs=None): 

"""!Compare two kernels' Parameters""" 

if kernel1.getSpatialParameters() != kernel2.getSpatialParameters(): 

retStrs.append("spatial parameters differ: %s != %s" % 

(kernel1.getSpatialParameters(), kernel2.getSpatialParameters())) 

974 ↛ 975line 974 didn't jump to line 975, because the condition on line 974 was never true if kernel1.getNSpatialParameters() != kernel2.getNSpatialParameters(): 

retStrs.append("# spatial parameters differs: %s != %s" % 

(kernel1.getNSpatialParameters(), kernel2.getNSpatialParameters())) 

if not kernel1.isSpatiallyVarying() and hasattr(kernel1, "getKernelParameters"): 

if kernel1.getKernelParameters() != kernel2.getKernelParameters(): 

retStrs.append("kernel parameters differs: %s != %s" % 

(kernel1.getKernelParameters(), kernel2.getKernelParameters())) 

return retStrs 

 

def _makePositionList(self, kernel1): 

if kernel1.isSpatiallyVarying(): 

return [(0, 0), (200, 0), (0, 200), (200, 200)] 

else: 

return [(0, 0)] 

 

 

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

pass 

 

 

def setup_module(module): 

lsst.utils.tests.init() 

 

 

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

lsst.utils.tests.init() 

unittest.main()