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

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

# This file is part of ip_isr. 

# 

# 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/>. 

 

import math 

import numpy 

 

import lsst.geom 

import lsst.afw.image as afwImage 

import lsst.afw.math as afwMath 

import lsst.pex.config as pexConfig 

import lsst.pipe.base as pipeBase 

import lsst.pipe.base.connectionTypes as cT 

 

from contextlib import contextmanager 

from lsstDebug import getDebugFrame 

 

from lsst.afw.cameraGeom import (PIXELS, FOCAL_PLANE, NullLinearityType, 

ReadoutCorner) 

from lsst.afw.display import getDisplay 

from lsst.afw.geom import Polygon 

from lsst.daf.persistence import ButlerDataRef 

from lsst.daf.persistence.butler import NoResults 

from lsst.meas.algorithms.detection import SourceDetectionTask 

from lsst.meas.algorithms import Defects 

 

from . import isrFunctions 

from . import isrQa 

from . import linearize 

 

from .assembleCcdTask import AssembleCcdTask 

from .crosstalk import CrosstalkTask 

from .fringe import FringeTask 

from .isr import maskNans 

from .masking import MaskingTask 

from .straylight import StrayLightTask 

from .vignette import VignetteTask 

 

 

__all__ = ["IsrTask", "IsrTaskConfig", "RunIsrTask", "RunIsrConfig"] 

 

 

class IsrTaskConnections(pipeBase.PipelineTaskConnections, 

dimensions={"instrument", "visit", "detector"}, 

defaultTemplates={}): 

ccdExposure = cT.PrerequisiteInput( 

name="raw", 

doc="Input exposure to process.", 

storageClass="Exposure", 

dimensions=["instrument", "visit", "detector"], 

) 

camera = cT.PrerequisiteInput( 

name="camera", 

storageClass="Camera", 

doc="Input camera to construct complete exposures.", 

dimensions=["instrument", "calibration_label"], 

) 

bias = cT.PrerequisiteInput( 

name="bias", 

doc="Input bias calibration.", 

storageClass="ImageF", 

dimensions=["instrument", "calibration_label", "detector"], 

) 

dark = cT.PrerequisiteInput( 

name='dark', 

doc="Input dark calibration.", 

storageClass="ImageF", 

dimensions=["instrument", "calibration_label", "detector"], 

) 

flat = cT.PrerequisiteInput( 

name="flat", 

doc="Input flat calibration.", 

storageClass="MaskedImageF", 

dimensions=["instrument", "physical_filter", "calibration_label", "detector"], 

) 

bfKernel = cT.PrerequisiteInput( 

name='bfKernel', 

doc="Input brighter-fatter kernel.", 

storageClass="NumpyArray", 

dimensions=["instrument", "calibration_label"], 

) 

defects = cT.PrerequisiteInput( 

name='defects', 

doc="Input defect tables.", 

storageClass="DefectsList", 

dimensions=["instrument", "calibration_label", "detector"], 

) 

opticsTransmission = cT.PrerequisiteInput( 

name="transmission_optics", 

storageClass="TransmissionCurve", 

doc="Transmission curve due to the optics.", 

dimensions=["instrument", "calibration_label"], 

) 

filterTransmission = cT.PrerequisiteInput( 

name="transmission_filter", 

storageClass="TransmissionCurve", 

doc="Transmission curve due to the filter.", 

dimensions=["instrument", "physical_filter", "calibration_label"], 

) 

sensorTransmission = cT.PrerequisiteInput( 

name="transmission_sensor", 

storageClass="TransmissionCurve", 

doc="Transmission curve due to the sensor.", 

dimensions=["instrument", "calibration_label", "detector"], 

) 

atmosphereTransmission = cT.PrerequisiteInput( 

name="transmission_atmosphere", 

storageClass="TransmissionCurve", 

doc="Transmission curve due to the atmosphere.", 

dimensions=["instrument"], 

) 

illumMaskedImage = cT.PrerequisiteInput( 

name="illum", 

doc="Input illumination correction.", 

storageClass="MaskedImageF", 

dimensions=["instrument", "physical_filter", "calibration_label", "detector"], 

) 

 

outputExposure = cT.Output( 

name='postISRCCD', 

doc="Output ISR processed exposure.", 

storageClass="ExposureF", 

dimensions=["instrument", "visit", "detector"], 

) 

preInterpExposure = cT.Output( 

name='preInterpISRCCD', 

doc="Output ISR processed exposure, with pixels left uninterpolated.", 

storageClass="ExposureF", 

dimensions=["instrument", "visit", "detector"], 

) 

outputOssThumbnail = cT.Output( 

name="OssThumb", 

doc="Output Overscan-subtracted thumbnail image.", 

storageClass="Thumbnail", 

dimensions=["instrument", "visit", "detector"], 

) 

outputFlattenedThumbnail = cT.Output( 

name="FlattenedThumb", 

doc="Output flat-corrected thumbnail image.", 

storageClass="Thumbnail", 

dimensions=["instrument", "visit", "detector"], 

) 

 

def __init__(self, *, config=None): 

super().__init__(config=config) 

 

if config.doBias is not True: 

self.prerequisiteInputs.discard("bias") 

if config.doLinearize is not True: 

self.prerequisiteInputs.discard("linearizer") 

if config.doCrosstalk is not True: 

self.prerequisiteInputs.discard("crosstalkSources") 

if config.doBrighterFatter is not True: 

self.prerequisiteInputs.discard("bfKernel") 

if config.doDefect is not True: 

self.prerequisiteInputs.discard("defects") 

if config.doDark is not True: 

self.prerequisiteInputs.discard("dark") 

if config.doFlat is not True: 

self.prerequisiteInputs.discard("flat") 

if config.doAttachTransmissionCurve is not True: 

self.prerequisiteInputs.discard("opticsTransmission") 

self.prerequisiteInputs.discard("filterTransmission") 

self.prerequisiteInputs.discard("sensorTransmission") 

self.prerequisiteInputs.discard("atmosphereTransmission") 

if config.doUseOpticsTransmission is not True: 

self.prerequisiteInputs.discard("opticsTransmission") 

if config.doUseFilterTransmission is not True: 

self.prerequisiteInputs.discard("filterTransmission") 

if config.doUseSensorTransmission is not True: 

self.prerequisiteInputs.discard("sensorTransmission") 

if config.doUseAtmosphereTransmission is not True: 

self.prerequisiteInputs.discard("atmosphereTransmission") 

if config.doIlluminationCorrection is not True: 

self.prerequisiteInputs.discard("illumMaskedImage") 

 

if config.doWrite is not True: 

self.outputs.discard("outputExposure") 

self.outputs.discard("preInterpExposure") 

self.outputs.discard("outputFlattenedThumbnail") 

self.outputs.discard("outputOssThumbnail") 

if config.doSaveInterpPixels is not True: 

self.outputs.discard("preInterpExposure") 

if config.qa.doThumbnailOss is not True: 

self.outputs.discard("outputOssThumbnail") 

if config.qa.doThumbnailFlattened is not True: 

self.outputs.discard("outputFlattenedThumbnail") 

 

 

class IsrTaskConfig(pipeBase.PipelineTaskConfig, 

pipelineConnections=IsrTaskConnections): 

"""Configuration parameters for IsrTask. 

 

Items are grouped in the order in which they are executed by the task. 

""" 

datasetType = pexConfig.Field( 

dtype=str, 

doc="Dataset type for input data; users will typically leave this alone, " 

"but camera-specific ISR tasks will override it", 

default="raw", 

) 

 

fallbackFilterName = pexConfig.Field( 

dtype=str, 

doc="Fallback default filter name for calibrations.", 

optional=True 

) 

expectWcs = pexConfig.Field( 

dtype=bool, 

default=True, 

doc="Expect input science images to have a WCS (set False for e.g. spectrographs)." 

) 

fwhm = pexConfig.Field( 

dtype=float, 

doc="FWHM of PSF in arcseconds.", 

default=1.0, 

) 

qa = pexConfig.ConfigField( 

dtype=isrQa.IsrQaConfig, 

doc="QA related configuration options.", 

) 

 

# Image conversion configuration 

doConvertIntToFloat = pexConfig.Field( 

dtype=bool, 

doc="Convert integer raw images to floating point values?", 

default=True, 

) 

 

# Saturated pixel handling. 

doSaturation = pexConfig.Field( 

dtype=bool, 

doc="Mask saturated pixels? NB: this is totally independent of the" 

" interpolation option - this is ONLY setting the bits in the mask." 

" To have them interpolated make sure doSaturationInterpolation=True", 

default=True, 

) 

saturatedMaskName = pexConfig.Field( 

dtype=str, 

doc="Name of mask plane to use in saturation detection and interpolation", 

default="SAT", 

) 

saturation = pexConfig.Field( 

dtype=float, 

doc="The saturation level to use if no Detector is present in the Exposure (ignored if NaN)", 

default=float("NaN"), 

) 

growSaturationFootprintSize = pexConfig.Field( 

dtype=int, 

doc="Number of pixels by which to grow the saturation footprints", 

default=1, 

) 

 

# Suspect pixel handling. 

doSuspect = pexConfig.Field( 

dtype=bool, 

doc="Mask suspect pixels?", 

default=False, 

) 

suspectMaskName = pexConfig.Field( 

dtype=str, 

doc="Name of mask plane to use for suspect pixels", 

default="SUSPECT", 

) 

numEdgeSuspect = pexConfig.Field( 

dtype=int, 

doc="Number of edge pixels to be flagged as untrustworthy.", 

default=0, 

) 

 

# Initial masking options. 

doSetBadRegions = pexConfig.Field( 

dtype=bool, 

doc="Should we set the level of all BAD patches of the chip to the chip's average value?", 

default=True, 

) 

badStatistic = pexConfig.ChoiceField( 

dtype=str, 

doc="How to estimate the average value for BAD regions.", 

default='MEANCLIP', 

allowed={ 

"MEANCLIP": "Correct using the (clipped) mean of good data", 

"MEDIAN": "Correct using the median of the good data", 

}, 

) 

 

# Overscan subtraction configuration. 

doOverscan = pexConfig.Field( 

dtype=bool, 

doc="Do overscan subtraction?", 

default=True, 

) 

overscanFitType = pexConfig.ChoiceField( 

dtype=str, 

doc="The method for fitting the overscan bias level.", 

default='MEDIAN', 

allowed={ 

"POLY": "Fit ordinary polynomial to the longest axis of the overscan region", 

"CHEB": "Fit Chebyshev polynomial to the longest axis of the overscan region", 

"LEG": "Fit Legendre polynomial to the longest axis of the overscan region", 

"NATURAL_SPLINE": "Fit natural spline to the longest axis of the overscan region", 

"CUBIC_SPLINE": "Fit cubic spline to the longest axis of the overscan region", 

"AKIMA_SPLINE": "Fit Akima spline to the longest axis of the overscan region", 

"MEAN": "Correct using the mean of the overscan region", 

"MEANCLIP": "Correct using a clipped mean of the overscan region", 

"MEDIAN": "Correct using the median of the overscan region", 

}, 

) 

overscanOrder = pexConfig.Field( 

dtype=int, 

doc=("Order of polynomial or to fit if overscan fit type is a polynomial, " + 

"or number of spline knots if overscan fit type is a spline."), 

default=1, 

) 

overscanNumSigmaClip = pexConfig.Field( 

dtype=float, 

doc="Rejection threshold (sigma) for collapsing overscan before fit", 

default=3.0, 

) 

overscanIsInt = pexConfig.Field( 

dtype=bool, 

doc="Treat overscan as an integer image for purposes of overscan.FitType=MEDIAN", 

default=True, 

) 

overscanNumLeadingColumnsToSkip = pexConfig.Field( 

dtype=int, 

doc="Number of columns to skip in overscan, i.e. those closest to amplifier", 

default=0, 

) 

overscanNumTrailingColumnsToSkip = pexConfig.Field( 

dtype=int, 

doc="Number of columns to skip in overscan, i.e. those farthest from amplifier", 

default=0, 

) 

352 ↛ exitline 355 didn't finish the lambda on line 355 overscanMaxDev = pexConfig.Field( 

dtype=float, 

doc="Maximum deviation from the median for overscan", 

default=1000.0, check=lambda x: x > 0 

) 

overscanBiasJump = pexConfig.Field( 

dtype=bool, 

doc="Fit the overscan in a piecewise-fashion to correct for bias jumps?", 

default=False, 

) 

overscanBiasJumpKeyword = pexConfig.Field( 

dtype=str, 

doc="Header keyword containing information about devices.", 

default="NO_SUCH_KEY", 

) 

overscanBiasJumpDevices = pexConfig.ListField( 

dtype=str, 

doc="List of devices that need piecewise overscan correction.", 

default=(), 

) 

overscanBiasJumpLocation = pexConfig.Field( 

dtype=int, 

doc="Location of bias jump along y-axis.", 

default=0, 

) 

 

# Amplifier to CCD assembly configuration 

doAssembleCcd = pexConfig.Field( 

dtype=bool, 

default=True, 

doc="Assemble amp-level exposures into a ccd-level exposure?" 

) 

assembleCcd = pexConfig.ConfigurableField( 

target=AssembleCcdTask, 

doc="CCD assembly task", 

) 

 

# General calibration configuration. 

doAssembleIsrExposures = pexConfig.Field( 

dtype=bool, 

default=False, 

doc="Assemble amp-level calibration exposures into ccd-level exposure?" 

) 

doTrimToMatchCalib = pexConfig.Field( 

dtype=bool, 

default=False, 

doc="Trim raw data to match calibration bounding boxes?" 

) 

 

# Bias subtraction. 

doBias = pexConfig.Field( 

dtype=bool, 

doc="Apply bias frame correction?", 

default=True, 

) 

biasDataProductName = pexConfig.Field( 

dtype=str, 

doc="Name of the bias data product", 

default="bias", 

) 

 

# Variance construction 

doVariance = pexConfig.Field( 

dtype=bool, 

doc="Calculate variance?", 

default=True 

) 

gain = pexConfig.Field( 

dtype=float, 

doc="The gain to use if no Detector is present in the Exposure (ignored if NaN)", 

default=float("NaN"), 

) 

readNoise = pexConfig.Field( 

dtype=float, 

doc="The read noise to use if no Detector is present in the Exposure", 

default=0.0, 

) 

doEmpiricalReadNoise = pexConfig.Field( 

dtype=bool, 

default=False, 

doc="Calculate empirical read noise instead of value from AmpInfo data?" 

) 

 

# Linearization. 

doLinearize = pexConfig.Field( 

dtype=bool, 

doc="Correct for nonlinearity of the detector's response?", 

default=True, 

) 

 

# Crosstalk. 

doCrosstalk = pexConfig.Field( 

dtype=bool, 

doc="Apply intra-CCD crosstalk correction?", 

default=False, 

) 

doCrosstalkBeforeAssemble = pexConfig.Field( 

dtype=bool, 

doc="Apply crosstalk correction before CCD assembly, and before trimming?", 

default=False, 

) 

crosstalk = pexConfig.ConfigurableField( 

target=CrosstalkTask, 

doc="Intra-CCD crosstalk correction", 

) 

 

# Masking options. 

doDefect = pexConfig.Field( 

dtype=bool, 

doc="Apply correction for CCD defects, e.g. hot pixels?", 

default=True, 

) 

doNanMasking = pexConfig.Field( 

dtype=bool, 

doc="Mask NAN pixels?", 

default=True, 

) 

doWidenSaturationTrails = pexConfig.Field( 

dtype=bool, 

doc="Widen bleed trails based on their width?", 

default=True 

) 

 

# Brighter-Fatter correction. 

doBrighterFatter = pexConfig.Field( 

dtype=bool, 

default=False, 

doc="Apply the brighter fatter correction" 

) 

brighterFatterLevel = pexConfig.ChoiceField( 

dtype=str, 

default="DETECTOR", 

doc="The level at which to correct for brighter-fatter.", 

allowed={ 

"AMP": "Every amplifier treated separately.", 

"DETECTOR": "One kernel per detector", 

} 

) 

brighterFatterKernelFile = pexConfig.Field( 

dtype=str, 

default='', 

doc="Kernel file used for the brighter fatter correction" 

) 

brighterFatterMaxIter = pexConfig.Field( 

dtype=int, 

default=10, 

doc="Maximum number of iterations for the brighter fatter correction" 

) 

brighterFatterThreshold = pexConfig.Field( 

dtype=float, 

default=1000, 

doc="Threshold used to stop iterating the brighter fatter correction. It is the " 

" absolute value of the difference between the current corrected image and the one" 

" from the previous iteration summed over all the pixels." 

) 

brighterFatterApplyGain = pexConfig.Field( 

dtype=bool, 

default=True, 

doc="Should the gain be applied when applying the brighter fatter correction?" 

) 

 

# Dark subtraction. 

doDark = pexConfig.Field( 

dtype=bool, 

doc="Apply dark frame correction?", 

default=True, 

) 

darkDataProductName = pexConfig.Field( 

dtype=str, 

doc="Name of the dark data product", 

default="dark", 

) 

 

# Camera-specific stray light removal. 

doStrayLight = pexConfig.Field( 

dtype=bool, 

doc="Subtract stray light in the y-band (due to encoder LEDs)?", 

default=False, 

) 

strayLight = pexConfig.ConfigurableField( 

target=StrayLightTask, 

doc="y-band stray light correction" 

) 

 

# Flat correction. 

doFlat = pexConfig.Field( 

dtype=bool, 

doc="Apply flat field correction?", 

default=True, 

) 

flatDataProductName = pexConfig.Field( 

dtype=str, 

doc="Name of the flat data product", 

default="flat", 

) 

flatScalingType = pexConfig.ChoiceField( 

dtype=str, 

doc="The method for scaling the flat on the fly.", 

default='USER', 

allowed={ 

"USER": "Scale by flatUserScale", 

"MEAN": "Scale by the inverse of the mean", 

"MEDIAN": "Scale by the inverse of the median", 

}, 

) 

flatUserScale = pexConfig.Field( 

dtype=float, 

doc="If flatScalingType is 'USER' then scale flat by this amount; ignored otherwise", 

default=1.0, 

) 

doTweakFlat = pexConfig.Field( 

dtype=bool, 

doc="Tweak flats to match observed amplifier ratios?", 

default=False 

) 

 

# Amplifier normalization based on gains instead of using flats configuration. 

doApplyGains = pexConfig.Field( 

dtype=bool, 

doc="Correct the amplifiers for their gains instead of applying flat correction", 

default=False, 

) 

normalizeGains = pexConfig.Field( 

dtype=bool, 

doc="Normalize all the amplifiers in each CCD to have the same median value.", 

default=False, 

) 

 

# Fringe correction. 

doFringe = pexConfig.Field( 

dtype=bool, 

doc="Apply fringe correction?", 

default=True, 

) 

fringe = pexConfig.ConfigurableField( 

target=FringeTask, 

doc="Fringe subtraction task", 

) 

fringeAfterFlat = pexConfig.Field( 

dtype=bool, 

doc="Do fringe subtraction after flat-fielding?", 

default=True, 

) 

 

# Distortion model application. 

doAddDistortionModel = pexConfig.Field( 

dtype=bool, 

doc="Apply a distortion model based on camera geometry to the WCS?", 

default=True, 

deprecated=("Camera geometry is incorporated when reading the raw files." 

" This option no longer is used, and will be removed after v19.") 

) 

 

# Initial CCD-level background statistics options. 

doMeasureBackground = pexConfig.Field( 

dtype=bool, 

doc="Measure the background level on the reduced image?", 

default=False, 

) 

 

# Camera-specific masking configuration. 

doCameraSpecificMasking = pexConfig.Field( 

dtype=bool, 

doc="Mask camera-specific bad regions?", 

default=False, 

) 

masking = pexConfig.ConfigurableField( 

target=MaskingTask, 

doc="Masking task." 

) 

 

# Interpolation options. 

 

doInterpolate = pexConfig.Field( 

dtype=bool, 

doc="Interpolate masked pixels?", 

default=True, 

) 

doSaturationInterpolation = pexConfig.Field( 

dtype=bool, 

doc="Perform interpolation over pixels masked as saturated?" 

" NB: This is independent of doSaturation; if that is False this plane" 

" will likely be blank, resulting in a no-op here.", 

default=True, 

) 

doNanInterpolation = pexConfig.Field( 

dtype=bool, 

doc="Perform interpolation over pixels masked as NaN?" 

" NB: This is independent of doNanMasking; if that is False this plane" 

" will likely be blank, resulting in a no-op here.", 

default=True, 

) 

doNanInterpAfterFlat = pexConfig.Field( 

dtype=bool, 

doc=("If True, ensure we interpolate NaNs after flat-fielding, even if we " 

"also have to interpolate them before flat-fielding."), 

default=False, 

) 

maskListToInterpolate = pexConfig.ListField( 

dtype=str, 

doc="List of mask planes that should be interpolated.", 

default=['SAT', 'BAD', 'UNMASKEDNAN'], 

) 

doSaveInterpPixels = pexConfig.Field( 

dtype=bool, 

doc="Save a copy of the pre-interpolated pixel values?", 

default=False, 

) 

 

# Default photometric calibration options. 

fluxMag0T1 = pexConfig.DictField( 

keytype=str, 

itemtype=float, 

doc="The approximate flux of a zero-magnitude object in a one-second exposure, per filter.", 

default=dict((f, pow(10.0, 0.4*m)) for f, m in (("Unknown", 28.0), 

)) 

) 

defaultFluxMag0T1 = pexConfig.Field( 

dtype=float, 

doc="Default value for fluxMag0T1 (for an unrecognized filter).", 

default=pow(10.0, 0.4*28.0) 

) 

 

# Vignette correction configuration. 

doVignette = pexConfig.Field( 

dtype=bool, 

doc="Apply vignetting parameters?", 

default=False, 

) 

vignette = pexConfig.ConfigurableField( 

target=VignetteTask, 

doc="Vignetting task.", 

) 

 

# Transmission curve configuration. 

doAttachTransmissionCurve = pexConfig.Field( 

dtype=bool, 

default=False, 

doc="Construct and attach a wavelength-dependent throughput curve for this CCD image?" 

) 

doUseOpticsTransmission = pexConfig.Field( 

dtype=bool, 

default=True, 

doc="Load and use transmission_optics (if doAttachTransmissionCurve is True)?" 

) 

doUseFilterTransmission = pexConfig.Field( 

dtype=bool, 

default=True, 

doc="Load and use transmission_filter (if doAttachTransmissionCurve is True)?" 

) 

doUseSensorTransmission = pexConfig.Field( 

dtype=bool, 

default=True, 

doc="Load and use transmission_sensor (if doAttachTransmissionCurve is True)?" 

) 

doUseAtmosphereTransmission = pexConfig.Field( 

dtype=bool, 

default=True, 

doc="Load and use transmission_atmosphere (if doAttachTransmissionCurve is True)?" 

) 

 

# Illumination correction. 

doIlluminationCorrection = pexConfig.Field( 

dtype=bool, 

default=False, 

doc="Perform illumination correction?" 

) 

illuminationCorrectionDataProductName = pexConfig.Field( 

dtype=str, 

doc="Name of the illumination correction data product.", 

default="illumcor", 

) 

illumScale = pexConfig.Field( 

dtype=float, 

doc="Scale factor for the illumination correction.", 

default=1.0, 

) 

illumFilters = pexConfig.ListField( 

dtype=str, 

default=[], 

doc="Only perform illumination correction for these filters." 

) 

 

# Write the outputs to disk. If ISR is run as a subtask, this may not be needed. 

doWrite = pexConfig.Field( 

dtype=bool, 

doc="Persist postISRCCD?", 

default=True, 

) 

 

def validate(self): 

super().validate() 

if self.doFlat and self.doApplyGains: 

raise ValueError("You may not specify both doFlat and doApplyGains") 

if self.doSaturationInterpolation and "SAT" not in self.maskListToInterpolate: 

self.config.maskListToInterpolate.append("SAT") 

if self.doNanInterpolation and "UNMASKEDNAN" not in self.maskListToInterpolate: 

self.config.maskListToInterpolate.append("UNMASKEDNAN") 

 

 

class IsrTask(pipeBase.PipelineTask, pipeBase.CmdLineTask): 

"""Apply common instrument signature correction algorithms to a raw frame. 

 

The process for correcting imaging data is very similar from 

camera to camera. This task provides a vanilla implementation of 

doing these corrections, including the ability to turn certain 

corrections off if they are not needed. The inputs to the primary 

method, `run()`, are a raw exposure to be corrected and the 

calibration data products. The raw input is a single chip sized 

mosaic of all amps including overscans and other non-science 

pixels. The method `runDataRef()` identifies and defines the 

calibration data products, and is intended for use by a 

`lsst.pipe.base.cmdLineTask.CmdLineTask` and takes as input only a 

`daf.persistence.butlerSubset.ButlerDataRef`. This task may be 

subclassed for different camera, although the most camera specific 

methods have been split into subtasks that can be redirected 

appropriately. 

 

The __init__ method sets up the subtasks for ISR processing, using 

the defaults from `lsst.ip.isr`. 

 

Parameters 

---------- 

args : `list` 

Positional arguments passed to the Task constructor. None used at this time. 

kwargs : `dict`, optional 

Keyword arguments passed on to the Task constructor. None used at this time. 

""" 

ConfigClass = IsrTaskConfig 

_DefaultName = "isr" 

 

def __init__(self, **kwargs): 

super().__init__(**kwargs) 

self.makeSubtask("assembleCcd") 

self.makeSubtask("crosstalk") 

self.makeSubtask("strayLight") 

self.makeSubtask("fringe") 

self.makeSubtask("masking") 

self.makeSubtask("vignette") 

 

def runQuantum(self, butlerQC, inputRefs, outputRefs): 

inputs = butlerQC.get(inputRefs) 

 

try: 

inputs['detectorNum'] = inputRefs.ccdExposure.dataId['detector'] 

except Exception as e: 

raise ValueError("Failure to find valid detectorNum value for Dataset %s: %s." % 

(inputRefs, e)) 

 

inputs['isGen3'] = True 

 

if self.config.doLinearize is True: 

if 'linearizer' not in inputs: 

detector = inputs['ccdExposure'].getDetector() 

linearityName = detector.getAmplifiers()[0].getLinearityType() 

inputs['linearizer'] = linearize.getLinearityTypeByName(linearityName)() 

 

if self.config.doDefect is True: 

if "defects" in inputs and inputs['defects'] is not None: 

# defects is loaded as a BaseCatalog with columns x0, y0, width, height. 

# masking expects a list of defects defined by their bounding box 

if not isinstance(inputs["defects"], Defects): 

inputs["defects"] = Defects.fromTable(inputs["defects"]) 

 

# Broken: DM-17169 

# ci_hsc does not use crosstalkSources, as it's intra-CCD CT only. This needs to be 

# fixed for non-HSC cameras in the future. 

# inputs['crosstalkSources'] = (self.crosstalk.prepCrosstalk(inputsIds['ccdExposure']) 

# if self.config.doCrosstalk else None) 

 

# Broken: DM-17152 

# Fringes are not tested to be handled correctly by Gen3 butler. 

# inputs['fringes'] = (self.fringe.readFringes(inputsIds['ccdExposure'], 

# assembler=self.assembleCcd 

# if self.config.doAssembleIsrExposures else None) 

# if self.config.doFringe and 

# self.fringe.checkFilter(inputs['ccdExposure']) 

# else pipeBase.Struct(fringes=None)) 

 

outputs = self.run(**inputs) 

butlerQC.put(outputs, outputRefs) 

 

def readIsrData(self, dataRef, rawExposure): 

"""!Retrieve necessary frames for instrument signature removal. 

 

Pre-fetching all required ISR data products limits the IO 

required by the ISR. Any conflict between the calibration data 

available and that needed for ISR is also detected prior to 

doing processing, allowing it to fail quickly. 

 

Parameters 

---------- 

dataRef : `daf.persistence.butlerSubset.ButlerDataRef` 

Butler reference of the detector data to be processed 

rawExposure : `afw.image.Exposure` 

The raw exposure that will later be corrected with the 

retrieved calibration data; should not be modified in this 

method. 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Result struct with components (which may be `None`): 

- ``bias``: bias calibration frame (`afw.image.Exposure`) 

- ``linearizer``: functor for linearization (`ip.isr.linearize.LinearizeBase`) 

- ``crosstalkSources``: list of possible crosstalk sources (`list`) 

- ``dark``: dark calibration frame (`afw.image.Exposure`) 

- ``flat``: flat calibration frame (`afw.image.Exposure`) 

- ``bfKernel``: Brighter-Fatter kernel (`numpy.ndarray`) 

- ``defects``: list of defects (`lsst.meas.algorithms.Defects`) 

- ``fringes``: `lsst.pipe.base.Struct` with components: 

- ``fringes``: fringe calibration frame (`afw.image.Exposure`) 

- ``seed``: random seed derived from the ccdExposureId for random 

number generator (`uint32`). 

- ``opticsTransmission``: `lsst.afw.image.TransmissionCurve` 

A ``TransmissionCurve`` that represents the throughput of the optics, 

to be evaluated in focal-plane coordinates. 

- ``filterTransmission`` : `lsst.afw.image.TransmissionCurve` 

A ``TransmissionCurve`` that represents the throughput of the filter 

itself, to be evaluated in focal-plane coordinates. 

- ``sensorTransmission`` : `lsst.afw.image.TransmissionCurve` 

A ``TransmissionCurve`` that represents the throughput of the sensor 

itself, to be evaluated in post-assembly trimmed detector coordinates. 

- ``atmosphereTransmission`` : `lsst.afw.image.TransmissionCurve` 

A ``TransmissionCurve`` that represents the throughput of the 

atmosphere, assumed to be spatially constant. 

- ``strayLightData`` : `object` 

An opaque object containing calibration information for 

stray-light correction. If `None`, no correction will be 

performed. 

- ``illumMaskedImage`` : illumination correction image (`lsst.afw.image.MaskedImage`) 

 

Raises 

------ 

NotImplementedError : 

Raised if a per-amplifier brighter-fatter kernel is requested by the configuration. 

""" 

ccd = rawExposure.getDetector() 

filterName = afwImage.Filter(rawExposure.getFilter().getId()).getName() # Canonical name for filter 

rawExposure.mask.addMaskPlane("UNMASKEDNAN") # needed to match pre DM-15862 processing. 

biasExposure = (self.getIsrExposure(dataRef, self.config.biasDataProductName) 

if self.config.doBias else None) 

# immediate=True required for functors and linearizers are functors; see ticket DM-6515 

linearizer = (dataRef.get("linearizer", immediate=True) 

if self.doLinearize(ccd) else None) 

crosstalkSources = (self.crosstalk.prepCrosstalk(dataRef) 

if self.config.doCrosstalk else None) 

darkExposure = (self.getIsrExposure(dataRef, self.config.darkDataProductName) 

if self.config.doDark else None) 

flatExposure = (self.getIsrExposure(dataRef, self.config.flatDataProductName) 

if self.config.doFlat else None) 

 

brighterFatterKernel = None 

if self.config.doBrighterFatter is True: 

 

# Use the new-style cp_pipe version of the kernel is it exists. 

try: 

brighterFatterKernel = dataRef.get("brighterFatterKernel") 

except NoResults: 

# Fall back to the old-style numpy-ndarray style kernel if necessary. 

try: 

brighterFatterKernel = dataRef.get("bfKernel") 

except NoResults: 

brighterFatterKernel = None 

if brighterFatterKernel is not None and not isinstance(brighterFatterKernel, numpy.ndarray): 

# If the kernel is not an ndarray, it's the cp_pipe version, so extract the kernel for 

# this detector, or raise an error. 

if self.config.brighterFatterLevel == 'DETECTOR': 

brighterFatterKernel = brighterFatterKernel.kernel[ccd.getId()] 

else: 

# TODO DM-15631 for implementing this 

raise NotImplementedError("Per-amplifier brighter-fatter correction not implemented") 

 

defectList = (dataRef.get("defects") 

if self.config.doDefect else None) 

fringeStruct = (self.fringe.readFringes(dataRef, assembler=self.assembleCcd 

if self.config.doAssembleIsrExposures else None) 

if self.config.doFringe and self.fringe.checkFilter(rawExposure) 

else pipeBase.Struct(fringes=None)) 

 

if self.config.doAttachTransmissionCurve: 

opticsTransmission = (dataRef.get("transmission_optics") 

if self.config.doUseOpticsTransmission else None) 

filterTransmission = (dataRef.get("transmission_filter") 

if self.config.doUseFilterTransmission else None) 

sensorTransmission = (dataRef.get("transmission_sensor") 

if self.config.doUseSensorTransmission else None) 

atmosphereTransmission = (dataRef.get("transmission_atmosphere") 

if self.config.doUseAtmosphereTransmission else None) 

else: 

opticsTransmission = None 

filterTransmission = None 

sensorTransmission = None 

atmosphereTransmission = None 

 

if self.config.doStrayLight: 

strayLightData = self.strayLight.readIsrData(dataRef, rawExposure) 

else: 

strayLightData = None 

 

illumMaskedImage = (self.getIsrExposure(dataRef, 

self.config.illuminationCorrectionDataProductName).getMaskedImage() 

if (self.config.doIlluminationCorrection and 

filterName in self.config.illumFilters) 

else None) 

 

# Struct should include only kwargs to run() 

return pipeBase.Struct(bias=biasExposure, 

linearizer=linearizer, 

crosstalkSources=crosstalkSources, 

dark=darkExposure, 

flat=flatExposure, 

bfKernel=brighterFatterKernel, 

defects=defectList, 

fringes=fringeStruct, 

opticsTransmission=opticsTransmission, 

filterTransmission=filterTransmission, 

sensorTransmission=sensorTransmission, 

atmosphereTransmission=atmosphereTransmission, 

strayLightData=strayLightData, 

illumMaskedImage=illumMaskedImage 

) 

 

@pipeBase.timeMethod 

def run(self, ccdExposure, camera=None, bias=None, linearizer=None, crosstalkSources=None, 

dark=None, flat=None, bfKernel=None, defects=None, fringes=pipeBase.Struct(fringes=None), 

opticsTransmission=None, filterTransmission=None, 

sensorTransmission=None, atmosphereTransmission=None, 

detectorNum=None, strayLightData=None, illumMaskedImage=None, 

isGen3=False, 

): 

"""!Perform instrument signature removal on an exposure. 

 

Steps included in the ISR processing, in order performed, are: 

- saturation and suspect pixel masking 

- overscan subtraction 

- CCD assembly of individual amplifiers 

- bias subtraction 

- variance image construction 

- linearization of non-linear response 

- crosstalk masking 

- brighter-fatter correction 

- dark subtraction 

- fringe correction 

- stray light subtraction 

- flat correction 

- masking of known defects and camera specific features 

- vignette calculation 

- appending transmission curve and distortion model 

 

Parameters 

---------- 

ccdExposure : `lsst.afw.image.Exposure` 

The raw exposure that is to be run through ISR. The 

exposure is modified by this method. 

camera : `lsst.afw.cameraGeom.Camera`, optional 

The camera geometry for this exposure. Used to select the 

distortion model appropriate for this data. 

bias : `lsst.afw.image.Exposure`, optional 

Bias calibration frame. 

linearizer : `lsst.ip.isr.linearize.LinearizeBase`, optional 

Functor for linearization. 

crosstalkSources : `list`, optional 

List of possible crosstalk sources. 

dark : `lsst.afw.image.Exposure`, optional 

Dark calibration frame. 

flat : `lsst.afw.image.Exposure`, optional 

Flat calibration frame. 

bfKernel : `numpy.ndarray`, optional 

Brighter-fatter kernel. 

defects : `lsst.meas.algorithms.Defects`, optional 

List of defects. 

fringes : `lsst.pipe.base.Struct`, optional 

Struct containing the fringe correction data, with 

elements: 

- ``fringes``: fringe calibration frame (`afw.image.Exposure`) 

- ``seed``: random seed derived from the ccdExposureId for random 

number generator (`uint32`) 

opticsTransmission: `lsst.afw.image.TransmissionCurve`, optional 

A ``TransmissionCurve`` that represents the throughput of the optics, 

to be evaluated in focal-plane coordinates. 

filterTransmission : `lsst.afw.image.TransmissionCurve` 

A ``TransmissionCurve`` that represents the throughput of the filter 

itself, to be evaluated in focal-plane coordinates. 

sensorTransmission : `lsst.afw.image.TransmissionCurve` 

A ``TransmissionCurve`` that represents the throughput of the sensor 

itself, to be evaluated in post-assembly trimmed detector coordinates. 

atmosphereTransmission : `lsst.afw.image.TransmissionCurve` 

A ``TransmissionCurve`` that represents the throughput of the 

atmosphere, assumed to be spatially constant. 

detectorNum : `int`, optional 

The integer number for the detector to process. 

isGen3 : bool, optional 

Flag this call to run() as using the Gen3 butler environment. 

strayLightData : `object`, optional 

Opaque object containing calibration information for stray-light 

correction. If `None`, no correction will be performed. 

illumMaskedImage : `lsst.afw.image.MaskedImage`, optional 

Illumination correction image. 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Result struct with component: 

- ``exposure`` : `afw.image.Exposure` 

The fully ISR corrected exposure. 

- ``outputExposure`` : `afw.image.Exposure` 

An alias for `exposure` 

- ``ossThumb`` : `numpy.ndarray` 

Thumbnail image of the exposure after overscan subtraction. 

- ``flattenedThumb`` : `numpy.ndarray` 

Thumbnail image of the exposure after flat-field correction. 

 

Raises 

------ 

RuntimeError 

Raised if a configuration option is set to True, but the 

required calibration data has not been specified. 

 

Notes 

----- 

The current processed exposure can be viewed by setting the 

appropriate lsstDebug entries in the `debug.display` 

dictionary. The names of these entries correspond to some of 

the IsrTaskConfig Boolean options, with the value denoting the 

frame to use. The exposure is shown inside the matching 

option check and after the processing of that step has 

finished. The steps with debug points are: 

 

doAssembleCcd 

doBias 

doCrosstalk 

doBrighterFatter 

doDark 

doFringe 

doStrayLight 

doFlat 

 

In addition, setting the "postISRCCD" entry displays the 

exposure after all ISR processing has finished. 

 

""" 

 

if isGen3 is True: 

# Gen3 currently cannot automatically do configuration overrides. 

# DM-15257 looks to discuss this issue. 

 

self.config.doFringe = False 

 

# Configure input exposures; 

if detectorNum is None: 

raise RuntimeError("Must supply the detectorNum if running as Gen3.") 

 

ccdExposure = self.ensureExposure(ccdExposure, camera, detectorNum) 

bias = self.ensureExposure(bias, camera, detectorNum) 

dark = self.ensureExposure(dark, camera, detectorNum) 

flat = self.ensureExposure(flat, camera, detectorNum) 

else: 

if isinstance(ccdExposure, ButlerDataRef): 

return self.runDataRef(ccdExposure) 

 

ccd = ccdExposure.getDetector() 

filterName = afwImage.Filter(ccdExposure.getFilter().getId()).getName() # Canonical name for filter 

 

if not ccd: 

assert not self.config.doAssembleCcd, "You need a Detector to run assembleCcd." 

ccd = [FakeAmp(ccdExposure, self.config)] 

 

# Validate Input 

if self.config.doBias and bias is None: 

raise RuntimeError("Must supply a bias exposure if config.doBias=True.") 

if self.doLinearize(ccd) and linearizer is None: 

raise RuntimeError("Must supply a linearizer if config.doLinearize=True for this detector.") 

if self.config.doBrighterFatter and bfKernel is None: 

raise RuntimeError("Must supply a kernel if config.doBrighterFatter=True.") 

if self.config.doDark and dark is None: 

raise RuntimeError("Must supply a dark exposure if config.doDark=True.") 

if self.config.doFlat and flat is None: 

raise RuntimeError("Must supply a flat exposure if config.doFlat=True.") 

if self.config.doDefect and defects is None: 

raise RuntimeError("Must supply defects if config.doDefect=True.") 

if (self.config.doFringe and filterName in self.fringe.config.filters and 

fringes.fringes is None): 

# The `fringes` object needs to be a pipeBase.Struct, as 

# we use it as a `dict` for the parameters of 

# `FringeTask.run()`. The `fringes.fringes` `list` may 

# not be `None` if `doFringe=True`. Otherwise, raise. 

raise RuntimeError("Must supply fringe exposure as a pipeBase.Struct.") 

if (self.config.doIlluminationCorrection and filterName in self.config.illumFilters and 

illumMaskedImage is None): 

raise RuntimeError("Must supply an illumcor if config.doIlluminationCorrection=True.") 

 

# Begin ISR processing. 

if self.config.doConvertIntToFloat: 

self.log.info("Converting exposure to floating point values.") 

ccdExposure = self.convertIntToFloat(ccdExposure) 

 

# Amplifier level processing. 

overscans = [] 

for amp in ccd: 

# if ccdExposure is one amp, check for coverage to prevent performing ops multiple times 

if ccdExposure.getBBox().contains(amp.getBBox()): 

# Check for fully masked bad amplifiers, and generate masks for SUSPECT and SATURATED values. 

badAmp = self.maskAmplifier(ccdExposure, amp, defects) 

 

if self.config.doOverscan and not badAmp: 

# Overscan correction on amp-by-amp basis. 

overscanResults = self.overscanCorrection(ccdExposure, amp) 

self.log.debug("Corrected overscan for amplifier %s.", amp.getName()) 

if overscanResults is not None and \ 

self.config.qa is not None and self.config.qa.saveStats is True: 

if isinstance(overscanResults.overscanFit, float): 

qaMedian = overscanResults.overscanFit 

qaStdev = float("NaN") 

else: 

qaStats = afwMath.makeStatistics(overscanResults.overscanFit, 

afwMath.MEDIAN | afwMath.STDEVCLIP) 

qaMedian = qaStats.getValue(afwMath.MEDIAN) 

qaStdev = qaStats.getValue(afwMath.STDEVCLIP) 

 

self.metadata.set(f"ISR OSCAN {amp.getName()} MEDIAN", qaMedian) 

self.metadata.set(f"ISR OSCAN {amp.getName()} STDEV", qaStdev) 

self.log.debug(" Overscan stats for amplifer %s: %f +/- %f", 

amp.getName(), qaMedian, qaStdev) 

ccdExposure.getMetadata().set('OVERSCAN', "Overscan corrected") 

else: 

if badAmp: 

self.log.warn("Amplifier %s is bad.", amp.getName()) 

overscanResults = None 

 

overscans.append(overscanResults if overscanResults is not None else None) 

else: 

self.log.info("Skipped OSCAN for %s.", amp.getName()) 

 

if self.config.doCrosstalk and self.config.doCrosstalkBeforeAssemble: 

self.log.info("Applying crosstalk correction.") 

self.crosstalk.run(ccdExposure, crosstalkSources=crosstalkSources) 

self.debugView(ccdExposure, "doCrosstalk") 

 

if self.config.doAssembleCcd: 

self.log.info("Assembling CCD from amplifiers.") 

ccdExposure = self.assembleCcd.assembleCcd(ccdExposure) 

 

if self.config.expectWcs and not ccdExposure.getWcs(): 

self.log.warn("No WCS found in input exposure.") 

self.debugView(ccdExposure, "doAssembleCcd") 

 

ossThumb = None 

if self.config.qa.doThumbnailOss: 

ossThumb = isrQa.makeThumbnail(ccdExposure, isrQaConfig=self.config.qa) 

 

if self.config.doBias: 

self.log.info("Applying bias correction.") 

isrFunctions.biasCorrection(ccdExposure.getMaskedImage(), bias.getMaskedImage(), 

trimToFit=self.config.doTrimToMatchCalib) 

self.debugView(ccdExposure, "doBias") 

 

if self.config.doVariance: 

for amp, overscanResults in zip(ccd, overscans): 

if ccdExposure.getBBox().contains(amp.getBBox()): 

self.log.debug("Constructing variance map for amplifer %s.", amp.getName()) 

ampExposure = ccdExposure.Factory(ccdExposure, amp.getBBox()) 

if overscanResults is not None: 

self.updateVariance(ampExposure, amp, 

overscanImage=overscanResults.overscanImage) 

else: 

self.updateVariance(ampExposure, amp, 

overscanImage=None) 

if self.config.qa is not None and self.config.qa.saveStats is True: 

qaStats = afwMath.makeStatistics(ampExposure.getVariance(), 

afwMath.MEDIAN | afwMath.STDEVCLIP) 

self.metadata.set(f"ISR VARIANCE {amp.getName()} MEDIAN", 

qaStats.getValue(afwMath.MEDIAN)) 

self.metadata.set(f"ISR VARIANCE {amp.getName()} STDEV", 

qaStats.getValue(afwMath.STDEVCLIP)) 

self.log.debug(" Variance stats for amplifer %s: %f +/- %f.", 

amp.getName(), qaStats.getValue(afwMath.MEDIAN), 

qaStats.getValue(afwMath.STDEVCLIP)) 

 

if self.doLinearize(ccd): 

self.log.info("Applying linearizer.") 

linearizer(image=ccdExposure.getMaskedImage().getImage(), detector=ccd, log=self.log) 

 

if self.config.doCrosstalk and not self.config.doCrosstalkBeforeAssemble: 

self.log.info("Applying crosstalk correction.") 

self.crosstalk.run(ccdExposure, crosstalkSources=crosstalkSources, isTrimmed=True) 

self.debugView(ccdExposure, "doCrosstalk") 

 

# Masking block. Optionally mask known defects, NAN pixels, widen trails, and do 

# anything else the camera needs. Saturated and suspect pixels have already been masked. 

if self.config.doDefect: 

self.log.info("Masking defects.") 

self.maskDefect(ccdExposure, defects) 

 

if self.config.numEdgeSuspect > 0: 

self.log.info("Masking edges as SUSPECT.") 

self.maskEdges(ccdExposure, numEdgePixels=self.config.numEdgeSuspect, 

maskPlane="SUSPECT") 

 

if self.config.doNanMasking: 

self.log.info("Masking NAN value pixels.") 

self.maskNan(ccdExposure) 

 

if self.config.doWidenSaturationTrails: 

self.log.info("Widening saturation trails.") 

isrFunctions.widenSaturationTrails(ccdExposure.getMaskedImage().getMask()) 

 

if self.config.doCameraSpecificMasking: 

self.log.info("Masking regions for camera specific reasons.") 

self.masking.run(ccdExposure) 

 

if self.config.doBrighterFatter: 

# We need to apply flats and darks before we can interpolate, and we 

# need to interpolate before we do B-F, but we do B-F without the 

# flats and darks applied so we can work in units of electrons or holes. 

# This context manager applies and then removes the darks and flats. 

# 

# We also do not want to interpolate values here, so operate on temporary 

# images so we can apply only the BF-correction and roll back the 

# interpolation. 

interpExp = ccdExposure.clone() 

with self.flatContext(interpExp, flat, dark): 

isrFunctions.interpolateFromMask( 

maskedImage=interpExp.getMaskedImage(), 

fwhm=self.config.fwhm, 

growSaturatedFootprints=self.config.growSaturationFootprintSize, 

maskNameList=self.config.maskListToInterpolate 

) 

bfExp = interpExp.clone() 

 

self.log.info("Applying brighter fatter correction.") 

bfResults = isrFunctions.brighterFatterCorrection(bfExp, bfKernel, 

self.config.brighterFatterMaxIter, 

self.config.brighterFatterThreshold, 

self.config.brighterFatterApplyGain 

) 

if bfResults[1] == self.config.brighterFatterMaxIter: 

self.log.warn("Brighter fatter correction did not converge, final difference %f.", 

bfResults[0]) 

else: 

self.log.info("Finished brighter fatter correction in %d iterations.", 

bfResults[1]) 

image = ccdExposure.getMaskedImage().getImage() 

bfCorr = bfExp.getMaskedImage().getImage() 

bfCorr -= interpExp.getMaskedImage().getImage() 

image += bfCorr 

 

# Applying the brighter-fatter correction applies a 

# convolution to the science image. At the edges this 

# convolution may not have sufficient valid pixels to 

# produce a valid correction. Mark pixels within the size 

# of the brighter-fatter kernel as EDGE to warn of this 

# fact. 

self.maskEdges(ccdExposure, numEdgePixels=numpy.max(bfKernel.shape) // 2, 

maskPlane="EDGE") 

self.log.warn("Ensuring image edges are masked as SUSPECT to the brighter-fatter kernel size.") 

 

self.debugView(ccdExposure, "doBrighterFatter") 

 

if self.config.doDark: 

self.log.info("Applying dark correction.") 

self.darkCorrection(ccdExposure, dark) 

self.debugView(ccdExposure, "doDark") 

 

if self.config.doFringe and not self.config.fringeAfterFlat: 

self.log.info("Applying fringe correction before flat.") 

self.fringe.run(ccdExposure, **fringes.getDict()) 

self.debugView(ccdExposure, "doFringe") 

 

if self.config.doStrayLight: 

if strayLightData is not None: 

self.log.info("Applying stray light correction.") 

self.strayLight.run(ccdExposure, strayLightData) 

self.debugView(ccdExposure, "doStrayLight") 

else: 

self.log.debug("Skipping stray light correction: no data found for this image.") 

 

if self.config.doFlat: 

self.log.info("Applying flat correction.") 

self.flatCorrection(ccdExposure, flat) 

self.debugView(ccdExposure, "doFlat") 

 

if self.config.doApplyGains: 

self.log.info("Applying gain correction instead of flat.") 

isrFunctions.applyGains(ccdExposure, self.config.normalizeGains) 

 

if self.config.doFringe and self.config.fringeAfterFlat: 

self.log.info("Applying fringe correction after flat.") 

self.fringe.run(ccdExposure, **fringes.getDict()) 

 

if self.config.doVignette: 

self.log.info("Constructing Vignette polygon.") 

self.vignettePolygon = self.vignette.run(ccdExposure) 

 

if self.config.vignette.doWriteVignettePolygon: 

self.setValidPolygonIntersect(ccdExposure, self.vignettePolygon) 

 

if self.config.doAttachTransmissionCurve: 

self.log.info("Adding transmission curves.") 

isrFunctions.attachTransmissionCurve(ccdExposure, opticsTransmission=opticsTransmission, 

filterTransmission=filterTransmission, 

sensorTransmission=sensorTransmission, 

atmosphereTransmission=atmosphereTransmission) 

 

flattenedThumb = None 

if self.config.qa.doThumbnailFlattened: 

flattenedThumb = isrQa.makeThumbnail(ccdExposure, isrQaConfig=self.config.qa) 

 

if self.config.doIlluminationCorrection and filterName in self.config.illumFilters: 

self.log.info("Performing illumination correction.") 

isrFunctions.illuminationCorrection(ccdExposure.getMaskedImage(), 

illumMaskedImage, illumScale=self.config.illumScale, 

trimToFit=self.config.doTrimToMatchCalib) 

 

preInterpExp = None 

if self.config.doSaveInterpPixels: 

preInterpExp = ccdExposure.clone() 

 

# Reset and interpolate bad pixels. 

# 

# Large contiguous bad regions (which should have the BAD mask 

# bit set) should have their values set to the image median. 

# This group should include defects and bad amplifiers. As the 

# area covered by these defects are large, there's little 

# reason to expect that interpolation would provide a more 

# useful value. 

# 

# Smaller defects can be safely interpolated after the larger 

# regions have had their pixel values reset. This ensures 

# that the remaining defects adjacent to bad amplifiers (as an 

# example) do not attempt to interpolate extreme values. 

if self.config.doSetBadRegions: 

badPixelCount, badPixelValue = isrFunctions.setBadRegions(ccdExposure) 

if badPixelCount > 0: 

self.log.info("Set %d BAD pixels to %f.", badPixelCount, badPixelValue) 

 

if self.config.doInterpolate: 

self.log.info("Interpolating masked pixels.") 

isrFunctions.interpolateFromMask( 

maskedImage=ccdExposure.getMaskedImage(), 

fwhm=self.config.fwhm, 

growSaturatedFootprints=self.config.growSaturationFootprintSize, 

maskNameList=list(self.config.maskListToInterpolate) 

) 

 

self.roughZeroPoint(ccdExposure) 

 

if self.config.doMeasureBackground: 

self.log.info("Measuring background level.") 

self.measureBackground(ccdExposure, self.config.qa) 

 

if self.config.qa is not None and self.config.qa.saveStats is True: 

for amp in ccd: 

ampExposure = ccdExposure.Factory(ccdExposure, amp.getBBox()) 

qaStats = afwMath.makeStatistics(ampExposure.getImage(), 

afwMath.MEDIAN | afwMath.STDEVCLIP) 

self.metadata.set("ISR BACKGROUND {} MEDIAN".format(amp.getName()), 

qaStats.getValue(afwMath.MEDIAN)) 

self.metadata.set("ISR BACKGROUND {} STDEV".format(amp.getName()), 

qaStats.getValue(afwMath.STDEVCLIP)) 

self.log.debug(" Background stats for amplifer %s: %f +/- %f", 

amp.getName(), qaStats.getValue(afwMath.MEDIAN), 

qaStats.getValue(afwMath.STDEVCLIP)) 

 

self.debugView(ccdExposure, "postISRCCD") 

 

return pipeBase.Struct( 

exposure=ccdExposure, 

ossThumb=ossThumb, 

flattenedThumb=flattenedThumb, 

 

preInterpolatedExposure=preInterpExp, 

outputExposure=ccdExposure, 

outputOssThumbnail=ossThumb, 

outputFlattenedThumbnail=flattenedThumb, 

) 

 

@pipeBase.timeMethod 

def runDataRef(self, sensorRef): 

"""Perform instrument signature removal on a ButlerDataRef of a Sensor. 

 

This method contains the `CmdLineTask` interface to the ISR 

processing. All IO is handled here, freeing the `run()` method 

to manage only pixel-level calculations. The steps performed 

are: 

- Read in necessary detrending/isr/calibration data. 

- Process raw exposure in `run()`. 

- Persist the ISR-corrected exposure as "postISRCCD" if 

config.doWrite=True. 

 

Parameters 

---------- 

sensorRef : `daf.persistence.butlerSubset.ButlerDataRef` 

DataRef of the detector data to be processed 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Result struct with component: 

- ``exposure`` : `afw.image.Exposure` 

The fully ISR corrected exposure. 

 

Raises 

------ 

RuntimeError 

Raised if a configuration option is set to True, but the 

required calibration data does not exist. 

 

""" 

self.log.info("Performing ISR on sensor %s.", sensorRef.dataId) 

 

ccdExposure = sensorRef.get(self.config.datasetType) 

 

camera = sensorRef.get("camera") 

isrData = self.readIsrData(sensorRef, ccdExposure) 

 

result = self.run(ccdExposure, camera=camera, **isrData.getDict()) 

 

if self.config.doWrite: 

sensorRef.put(result.exposure, "postISRCCD") 

if result.preInterpolatedExposure is not None: 

sensorRef.put(result.preInterpolatedExposure, "postISRCCD_uninterpolated") 

if result.ossThumb is not None: 

isrQa.writeThumbnail(sensorRef, result.ossThumb, "ossThumb") 

if result.flattenedThumb is not None: 

isrQa.writeThumbnail(sensorRef, result.flattenedThumb, "flattenedThumb") 

 

return result 

 

def getIsrExposure(self, dataRef, datasetType, immediate=True): 

"""!Retrieve a calibration dataset for removing instrument signature. 

 

Parameters 

---------- 

 

dataRef : `daf.persistence.butlerSubset.ButlerDataRef` 

DataRef of the detector data to find calibration datasets 

for. 

datasetType : `str` 

Type of dataset to retrieve (e.g. 'bias', 'flat', etc). 

immediate : `Bool` 

If True, disable butler proxies to enable error handling 

within this routine. 

 

Returns 

------- 

exposure : `lsst.afw.image.Exposure` 

Requested calibration frame. 

 

Raises 

------ 

RuntimeError 

Raised if no matching calibration frame can be found. 

""" 

try: 

exp = dataRef.get(datasetType, immediate=immediate) 

except Exception as exc1: 

if not self.config.fallbackFilterName: 

raise RuntimeError("Unable to retrieve %s for %s: %s." % (datasetType, dataRef.dataId, exc1)) 

try: 

exp = dataRef.get(datasetType, filter=self.config.fallbackFilterName, immediate=immediate) 

except Exception as exc2: 

raise RuntimeError("Unable to retrieve %s for %s, even with fallback filter %s: %s AND %s." % 

(datasetType, dataRef.dataId, self.config.fallbackFilterName, exc1, exc2)) 

self.log.warn("Using fallback calibration from filter %s.", self.config.fallbackFilterName) 

 

if self.config.doAssembleIsrExposures: 

exp = self.assembleCcd.assembleCcd(exp) 

return exp 

 

def ensureExposure(self, inputExp, camera, detectorNum): 

"""Ensure that the data returned by Butler is a fully constructed exposure. 

 

ISR requires exposure-level image data for historical reasons, so if we did 

not recieve that from Butler, construct it from what we have, modifying the 

input in place. 

 

Parameters 

---------- 

inputExp : `lsst.afw.image.Exposure`, `lsst.afw.image.DecoratedImageU`, or 

`lsst.afw.image.ImageF` 

The input data structure obtained from Butler. 

camera : `lsst.afw.cameraGeom.camera` 

The camera associated with the image. Used to find the appropriate 

detector. 

detectorNum : `int` 

The detector this exposure should match. 

 

Returns 

------- 

inputExp : `lsst.afw.image.Exposure` 

The re-constructed exposure, with appropriate detector parameters. 

 

Raises 

------ 

TypeError 

Raised if the input data cannot be used to construct an exposure. 

""" 

if isinstance(inputExp, afwImage.DecoratedImageU): 

inputExp = afwImage.makeExposure(afwImage.makeMaskedImage(inputExp)) 

elif isinstance(inputExp, afwImage.ImageF): 

inputExp = afwImage.makeExposure(afwImage.makeMaskedImage(inputExp)) 

elif isinstance(inputExp, afwImage.MaskedImageF): 

inputExp = afwImage.makeExposure(inputExp) 

elif isinstance(inputExp, afwImage.Exposure): 

pass 

elif inputExp is None: 

# Assume this will be caught by the setup if it is a problem. 

return inputExp 

else: 

raise TypeError("Input Exposure is not known type in isrTask.ensureExposure: %s." % 

(type(inputExp), )) 

 

if inputExp.getDetector() is None: 

inputExp.setDetector(camera[detectorNum]) 

 

return inputExp 

 

def convertIntToFloat(self, exposure): 

"""Convert exposure image from uint16 to float. 

 

If the exposure does not need to be converted, the input is 

immediately returned. For exposures that are converted to use 

floating point pixels, the variance is set to unity and the 

mask to zero. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

The raw exposure to be converted. 

 

Returns 

------- 

newexposure : `lsst.afw.image.Exposure` 

The input ``exposure``, converted to floating point pixels. 

 

Raises 

------ 

RuntimeError 

Raised if the exposure type cannot be converted to float. 

 

""" 

if isinstance(exposure, afwImage.ExposureF): 

# Nothing to be done 

self.log.debug("Exposure already of type float.") 

return exposure 

if not hasattr(exposure, "convertF"): 

raise RuntimeError("Unable to convert exposure (%s) to float." % type(exposure)) 

 

newexposure = exposure.convertF() 

newexposure.variance[:] = 1 

newexposure.mask[:] = 0x0 

 

return newexposure 

 

def maskAmplifier(self, ccdExposure, amp, defects): 

"""Identify bad amplifiers, saturated and suspect pixels. 

 

Parameters 

---------- 

ccdExposure : `lsst.afw.image.Exposure` 

Input exposure to be masked. 

amp : `lsst.afw.table.AmpInfoCatalog` 

Catalog of parameters defining the amplifier on this 

exposure to mask. 

defects : `lsst.meas.algorithms.Defects` 

List of defects. Used to determine if the entire 

amplifier is bad. 

 

Returns 

------- 

badAmp : `Bool` 

If this is true, the entire amplifier area is covered by 

defects and unusable. 

 

""" 

maskedImage = ccdExposure.getMaskedImage() 

 

badAmp = False 

 

# Check if entire amp region is defined as a defect (need to use amp.getBBox() for correct 

# comparison with current defects definition. 

if defects is not None: 

badAmp = bool(sum([v.getBBox().contains(amp.getBBox()) for v in defects])) 

 

# In the case of a bad amp, we will set mask to "BAD" (here use amp.getRawBBox() for correct 

# association with pixels in current ccdExposure). 

if badAmp: 

dataView = afwImage.MaskedImageF(maskedImage, amp.getRawBBox(), 

afwImage.PARENT) 

maskView = dataView.getMask() 

maskView |= maskView.getPlaneBitMask("BAD") 

del maskView 

return badAmp 

 

# Mask remaining defects after assembleCcd() to allow for defects that cross amplifier boundaries. 

# Saturation and suspect pixels can be masked now, though. 

limits = dict() 

if self.config.doSaturation and not badAmp: 

limits.update({self.config.saturatedMaskName: amp.getSaturation()}) 

if self.config.doSuspect and not badAmp: 

limits.update({self.config.suspectMaskName: amp.getSuspectLevel()}) 

if math.isfinite(self.config.saturation): 

limits.update({self.config.saturatedMaskName: self.config.saturation}) 

 

for maskName, maskThreshold in limits.items(): 

if not math.isnan(maskThreshold): 

dataView = maskedImage.Factory(maskedImage, amp.getRawBBox()) 

isrFunctions.makeThresholdMask( 

maskedImage=dataView, 

threshold=maskThreshold, 

growFootprints=0, 

maskName=maskName 

) 

 

# Determine if we've fully masked this amplifier with SUSPECT and SAT pixels. 

maskView = afwImage.Mask(maskedImage.getMask(), amp.getRawDataBBox(), 

afwImage.PARENT) 

maskVal = maskView.getPlaneBitMask([self.config.saturatedMaskName, 

self.config.suspectMaskName]) 

if numpy.all(maskView.getArray() & maskVal > 0): 

badAmp = True 

maskView |= maskView.getPlaneBitMask("BAD") 

 

return badAmp 

 

def overscanCorrection(self, ccdExposure, amp): 

"""Apply overscan correction in place. 

 

This method does initial pixel rejection of the overscan 

region. The overscan can also be optionally segmented to 

allow for discontinuous overscan responses to be fit 

separately. The actual overscan subtraction is performed by 

the `lsst.ip.isr.isrFunctions.overscanCorrection` function, 

which is called here after the amplifier is preprocessed. 

 

Parameters 

---------- 

ccdExposure : `lsst.afw.image.Exposure` 

Exposure to have overscan correction performed. 

amp : `lsst.afw.table.AmpInfoCatalog` 

The amplifier to consider while correcting the overscan. 

 

Returns 

------- 

overscanResults : `lsst.pipe.base.Struct` 

Result struct with components: 

- ``imageFit`` : scalar or `lsst.afw.image.Image` 

Value or fit subtracted from the amplifier image data. 

- ``overscanFit`` : scalar or `lsst.afw.image.Image` 

Value or fit subtracted from the overscan image data. 

- ``overscanImage`` : `lsst.afw.image.Image` 

Image of the overscan region with the overscan 

correction applied. This quantity is used to estimate 

the amplifier read noise empirically. 

 

Raises 

------ 

RuntimeError 

Raised if the ``amp`` does not contain raw pixel information. 

 

See Also 

-------- 

lsst.ip.isr.isrFunctions.overscanCorrection 

""" 

if not amp.getHasRawInfo(): 

raise RuntimeError("This method must be executed on an amp with raw information.") 

 

if amp.getRawHorizontalOverscanBBox().isEmpty(): 

self.log.info("ISR_OSCAN: No overscan region. Not performing overscan correction.") 

return None 

 

statControl = afwMath.StatisticsControl() 

statControl.setAndMask(ccdExposure.mask.getPlaneBitMask("SAT")) 

 

# Determine the bounding boxes 

dataBBox = amp.getRawDataBBox() 

oscanBBox = amp.getRawHorizontalOverscanBBox() 

dx0 = 0 

dx1 = 0 

 

prescanBBox = amp.getRawPrescanBBox() 

if (oscanBBox.getBeginX() > prescanBBox.getBeginX()): # amp is at the right 

dx0 += self.config.overscanNumLeadingColumnsToSkip 

dx1 -= self.config.overscanNumTrailingColumnsToSkip 

else: 

dx0 += self.config.overscanNumTrailingColumnsToSkip 

dx1 -= self.config.overscanNumLeadingColumnsToSkip 

 

# Determine if we need to work on subregions of the amplifier and overscan. 

imageBBoxes = [] 

overscanBBoxes = [] 

 

if ((self.config.overscanBiasJump and 

self.config.overscanBiasJumpLocation) and 

(ccdExposure.getMetadata().exists(self.config.overscanBiasJumpKeyword) and 

ccdExposure.getMetadata().getScalar(self.config.overscanBiasJumpKeyword) in 

self.config.overscanBiasJumpDevices)): 

if amp.getReadoutCorner() in (ReadoutCorner.LL, ReadoutCorner.LR): 

yLower = self.config.overscanBiasJumpLocation 

yUpper = dataBBox.getHeight() - yLower 

else: 

yUpper = self.config.overscanBiasJumpLocation 

yLower = dataBBox.getHeight() - yUpper 

 

imageBBoxes.append(lsst.geom.Box2I(dataBBox.getBegin(), 

lsst.geom.Extent2I(dataBBox.getWidth(), yLower))) 

overscanBBoxes.append(lsst.geom.Box2I(oscanBBox.getBegin() + 

lsst.geom.Extent2I(dx0, 0), 

lsst.geom.Extent2I(oscanBBox.getWidth() - dx0 + dx1, 

yLower))) 

 

imageBBoxes.append(lsst.geom.Box2I(dataBBox.getBegin() + lsst.geom.Extent2I(0, yLower), 

lsst.geom.Extent2I(dataBBox.getWidth(), yUpper))) 

overscanBBoxes.append(lsst.geom.Box2I(oscanBBox.getBegin() + lsst.geom.Extent2I(dx0, yLower), 

lsst.geom.Extent2I(oscanBBox.getWidth() - dx0 + dx1, 

yUpper))) 

else: 

imageBBoxes.append(lsst.geom.Box2I(dataBBox.getBegin(), 

lsst.geom.Extent2I(dataBBox.getWidth(), dataBBox.getHeight()))) 

overscanBBoxes.append(lsst.geom.Box2I(oscanBBox.getBegin() + lsst.geom.Extent2I(dx0, 0), 

lsst.geom.Extent2I(oscanBBox.getWidth() - dx0 + dx1, 

oscanBBox.getHeight()))) 

 

# Perform overscan correction on subregions, ensuring saturated pixels are masked. 

for imageBBox, overscanBBox in zip(imageBBoxes, overscanBBoxes): 

ampImage = ccdExposure.maskedImage[imageBBox] 

overscanImage = ccdExposure.maskedImage[overscanBBox] 

 

overscanArray = overscanImage.image.array 

median = numpy.ma.median(numpy.ma.masked_where(overscanImage.mask.array, overscanArray)) 

bad = numpy.where(numpy.abs(overscanArray - median) > self.config.overscanMaxDev) 

overscanImage.mask.array[bad] = overscanImage.mask.getPlaneBitMask("SAT") 

 

statControl = afwMath.StatisticsControl() 

statControl.setAndMask(ccdExposure.mask.getPlaneBitMask("SAT")) 

 

overscanResults = isrFunctions.overscanCorrection(ampMaskedImage=ampImage, 

overscanImage=overscanImage, 

fitType=self.config.overscanFitType, 

order=self.config.overscanOrder, 

collapseRej=self.config.overscanNumSigmaClip, 

statControl=statControl, 

overscanIsInt=self.config.overscanIsInt 

) 

 

# Measure average overscan levels and record them in the metadata. 

levelStat = afwMath.MEDIAN 

sigmaStat = afwMath.STDEVCLIP 

 

sctrl = afwMath.StatisticsControl(self.config.qa.flatness.clipSigma, 

self.config.qa.flatness.nIter) 

metadata = ccdExposure.getMetadata() 

ampNum = amp.getName() 

if self.config.overscanFitType in ("MEDIAN", "MEAN", "MEANCLIP"): 

metadata.set("ISR_OSCAN_LEVEL%s" % ampNum, overscanResults.overscanFit) 

metadata.set("ISR_OSCAN_SIGMA%s" % ampNum, 0.0) 

else: 

stats = afwMath.makeStatistics(overscanResults.overscanFit, levelStat | sigmaStat, sctrl) 

metadata.set("ISR_OSCAN_LEVEL%s" % ampNum, stats.getValue(levelStat)) 

metadata.set("ISR_OSCAN_SIGMA%s" % ampNum, stats.getValue(sigmaStat)) 

 

return overscanResults 

 

def updateVariance(self, ampExposure, amp, overscanImage=None): 

"""Set the variance plane using the amplifier gain and read noise 

 

The read noise is calculated from the ``overscanImage`` if the 

``doEmpiricalReadNoise`` option is set in the configuration; otherwise 

the value from the amplifier data is used. 

 

Parameters 

---------- 

ampExposure : `lsst.afw.image.Exposure` 

Exposure to process. 

amp : `lsst.afw.table.AmpInfoRecord` or `FakeAmp` 

Amplifier detector data. 

overscanImage : `lsst.afw.image.MaskedImage`, optional. 

Image of overscan, required only for empirical read noise. 

 

See also 

-------- 

lsst.ip.isr.isrFunctions.updateVariance 

""" 

maskPlanes = [self.config.saturatedMaskName, self.config.suspectMaskName] 

gain = amp.getGain() 

 

if math.isnan(gain): 

gain = 1.0 

self.log.warn("Gain set to NAN! Updating to 1.0 to generate Poisson variance.") 

elif gain <= 0: 

patchedGain = 1.0 

self.log.warn("Gain for amp %s == %g <= 0; setting to %f.", 

amp.getName(), gain, patchedGain) 

gain = patchedGain 

 

if self.config.doEmpiricalReadNoise and overscanImage is None: 

self.log.info("Overscan is none for EmpiricalReadNoise.") 

 

if self.config.doEmpiricalReadNoise and overscanImage is not None: 

stats = afwMath.StatisticsControl() 

stats.setAndMask(overscanImage.mask.getPlaneBitMask(maskPlanes)) 

readNoise = afwMath.makeStatistics(overscanImage, afwMath.STDEVCLIP, stats).getValue() 

self.log.info("Calculated empirical read noise for amp %s: %f.", 

amp.getName(), readNoise) 

else: 

readNoise = amp.getReadNoise() 

 

isrFunctions.updateVariance( 

maskedImage=ampExposure.getMaskedImage(), 

gain=gain, 

readNoise=readNoise, 

) 

 

def darkCorrection(self, exposure, darkExposure, invert=False): 

"""!Apply dark correction in place. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. 

darkExposure : `lsst.afw.image.Exposure` 

Dark exposure of the same size as ``exposure``. 

invert : `Bool`, optional 

If True, re-add the dark to an already corrected image. 

 

Raises 

------ 

RuntimeError 

Raised if either ``exposure`` or ``darkExposure`` do not 

have their dark time defined. 

 

See Also 

-------- 

lsst.ip.isr.isrFunctions.darkCorrection 

""" 

expScale = exposure.getInfo().getVisitInfo().getDarkTime() 

if math.isnan(expScale): 

raise RuntimeError("Exposure darktime is NAN.") 

if darkExposure.getInfo().getVisitInfo() is not None: 

darkScale = darkExposure.getInfo().getVisitInfo().getDarkTime() 

else: 

# DM-17444: darkExposure.getInfo.getVisitInfo() is None 

# so getDarkTime() does not exist. 

self.log.warn("darkExposure.getInfo().getVisitInfo() does not exist. Using darkScale = 1.0.") 

darkScale = 1.0 

 

if math.isnan(darkScale): 

raise RuntimeError("Dark calib darktime is NAN.") 

isrFunctions.darkCorrection( 

maskedImage=exposure.getMaskedImage(), 

darkMaskedImage=darkExposure.getMaskedImage(), 

expScale=expScale, 

darkScale=darkScale, 

invert=invert, 

trimToFit=self.config.doTrimToMatchCalib 

) 

 

def doLinearize(self, detector): 

"""!Check if linearization is needed for the detector cameraGeom. 

 

Checks config.doLinearize and the linearity type of the first 

amplifier. 

 

Parameters 

---------- 

detector : `lsst.afw.cameraGeom.Detector` 

Detector to get linearity type from. 

 

Returns 

------- 

doLinearize : `Bool` 

If True, linearization should be performed. 

""" 

return self.config.doLinearize and \ 

detector.getAmplifiers()[0].getLinearityType() != NullLinearityType 

 

def flatCorrection(self, exposure, flatExposure, invert=False): 

"""!Apply flat correction in place. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. 

flatExposure : `lsst.afw.image.Exposure` 

Flat exposure of the same size as ``exposure``. 

invert : `Bool`, optional 

If True, unflatten an already flattened image. 

 

See Also 

-------- 

lsst.ip.isr.isrFunctions.flatCorrection 

""" 

isrFunctions.flatCorrection( 

maskedImage=exposure.getMaskedImage(), 

flatMaskedImage=flatExposure.getMaskedImage(), 

scalingType=self.config.flatScalingType, 

userScale=self.config.flatUserScale, 

invert=invert, 

trimToFit=self.config.doTrimToMatchCalib 

) 

 

def saturationDetection(self, exposure, amp): 

"""!Detect saturated pixels and mask them using mask plane config.saturatedMaskName, in place. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. Only the amplifier DataSec is processed. 

amp : `lsst.afw.table.AmpInfoCatalog` 

Amplifier detector data. 

 

See Also 

-------- 

lsst.ip.isr.isrFunctions.makeThresholdMask 

""" 

if not math.isnan(amp.getSaturation()): 

maskedImage = exposure.getMaskedImage() 

dataView = maskedImage.Factory(maskedImage, amp.getRawBBox()) 

isrFunctions.makeThresholdMask( 

maskedImage=dataView, 

threshold=amp.getSaturation(), 

growFootprints=0, 

maskName=self.config.saturatedMaskName, 

) 

 

def saturationInterpolation(self, exposure): 

"""!Interpolate over saturated pixels, in place. 

 

This method should be called after `saturationDetection`, to 

ensure that the saturated pixels have been identified in the 

SAT mask. It should also be called after `assembleCcd`, since 

saturated regions may cross amplifier boundaries. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. 

 

See Also 

-------- 

lsst.ip.isr.isrTask.saturationDetection 

lsst.ip.isr.isrFunctions.interpolateFromMask 

""" 

isrFunctions.interpolateFromMask( 

maskedImage=exposure.getMaskedImage(), 

fwhm=self.config.fwhm, 

growSaturatedFootprints=self.config.growSaturationFootprintSize, 

maskNameList=list(self.config.saturatedMaskName), 

) 

 

def suspectDetection(self, exposure, amp): 

"""!Detect suspect pixels and mask them using mask plane config.suspectMaskName, in place. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. Only the amplifier DataSec is processed. 

amp : `lsst.afw.table.AmpInfoCatalog` 

Amplifier detector data. 

 

See Also 

-------- 

lsst.ip.isr.isrFunctions.makeThresholdMask 

 

Notes 

----- 

Suspect pixels are pixels whose value is greater than amp.getSuspectLevel(). 

This is intended to indicate pixels that may be affected by unknown systematics; 

for example if non-linearity corrections above a certain level are unstable 

then that would be a useful value for suspectLevel. A value of `nan` indicates 

that no such level exists and no pixels are to be masked as suspicious. 

""" 

suspectLevel = amp.getSuspectLevel() 

if math.isnan(suspectLevel): 

return 

 

maskedImage = exposure.getMaskedImage() 

dataView = maskedImage.Factory(maskedImage, amp.getRawBBox()) 

isrFunctions.makeThresholdMask( 

maskedImage=dataView, 

threshold=suspectLevel, 

growFootprints=0, 

maskName=self.config.suspectMaskName, 

) 

 

def maskDefect(self, exposure, defectBaseList): 

"""!Mask defects using mask plane "BAD", in place. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. 

defectBaseList : `lsst.meas.algorithms.Defects` or `list` of 

`lsst.afw.image.DefectBase`. 

List of defects to mask. 

 

Notes 

----- 

Call this after CCD assembly, since defects may cross amplifier boundaries. 

""" 

maskedImage = exposure.getMaskedImage() 

if not isinstance(defectBaseList, Defects): 

# Promotes DefectBase to Defect 

defectList = Defects(defectBaseList) 

else: 

defectList = defectBaseList 

defectList.maskPixels(maskedImage, maskName="BAD") 

 

def maskEdges(self, exposure, numEdgePixels=0, maskPlane="SUSPECT"): 

"""!Mask edge pixels with applicable mask plane. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. 

numEdgePixels : `int`, optional 

Number of edge pixels to mask. 

maskPlane : `str`, optional 

Mask plane name to use. 

""" 

maskedImage = exposure.getMaskedImage() 

maskBitMask = maskedImage.getMask().getPlaneBitMask(maskPlane) 

 

if numEdgePixels > 0: 

goodBBox = maskedImage.getBBox() 

# This makes a bbox numEdgeSuspect pixels smaller than the image on each side 

goodBBox.grow(-numEdgePixels) 

# Mask pixels outside goodBBox 

SourceDetectionTask.setEdgeBits( 

maskedImage, 

goodBBox, 

maskBitMask 

) 

 

def maskAndInterpolateDefects(self, exposure, defectBaseList): 

"""Mask and interpolate defects using mask plane "BAD", in place. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. 

defectBaseList : `lsst.meas.algorithms.Defects` or `list` of 

`lsst.afw.image.DefectBase`. 

List of defects to mask and interpolate. 

 

See Also 

-------- 

lsst.ip.isr.isrTask.maskDefect() 

""" 

self.maskDefect(exposure, defectBaseList) 

self.maskEdges(exposure, numEdgePixels=self.config.numEdgeSuspect, 

maskPlane="SUSPECT") 

isrFunctions.interpolateFromMask( 

maskedImage=exposure.getMaskedImage(), 

fwhm=self.config.fwhm, 

growSaturatedFootprints=0, 

maskNameList=["BAD"], 

) 

 

def maskNan(self, exposure): 

"""Mask NaNs using mask plane "UNMASKEDNAN", in place. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. 

 

Notes 

----- 

We mask over all NaNs, including those that are masked with 

other bits (because those may or may not be interpolated over 

later, and we want to remove all NaNs). Despite this 

behaviour, the "UNMASKEDNAN" mask plane is used to preserve 

the historical name. 

""" 

maskedImage = exposure.getMaskedImage() 

 

# Find and mask NaNs 

maskedImage.getMask().addMaskPlane("UNMASKEDNAN") 

maskVal = maskedImage.getMask().getPlaneBitMask("UNMASKEDNAN") 

numNans = maskNans(maskedImage, maskVal) 

self.metadata.set("NUMNANS", numNans) 

if numNans > 0: 

self.log.warn("There were %d unmasked NaNs.", numNans) 

 

def maskAndInterpolateNan(self, exposure): 

""""Mask and interpolate NaNs using mask plane "UNMASKEDNAN", in place. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. 

 

See Also 

-------- 

lsst.ip.isr.isrTask.maskNan() 

""" 

self.maskNan(exposure) 

isrFunctions.interpolateFromMask( 

maskedImage=exposure.getMaskedImage(), 

fwhm=self.config.fwhm, 

growSaturatedFootprints=0, 

maskNameList=["UNMASKEDNAN"], 

) 

 

def measureBackground(self, exposure, IsrQaConfig=None): 

"""Measure the image background in subgrids, for quality control purposes. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. 

IsrQaConfig : `lsst.ip.isr.isrQa.IsrQaConfig` 

Configuration object containing parameters on which background 

statistics and subgrids to use. 

""" 

if IsrQaConfig is not None: 

statsControl = afwMath.StatisticsControl(IsrQaConfig.flatness.clipSigma, 

IsrQaConfig.flatness.nIter) 

maskVal = exposure.getMaskedImage().getMask().getPlaneBitMask(["BAD", "SAT", "DETECTED"]) 

statsControl.setAndMask(maskVal) 

maskedImage = exposure.getMaskedImage() 

stats = afwMath.makeStatistics(maskedImage, afwMath.MEDIAN | afwMath.STDEVCLIP, statsControl) 

skyLevel = stats.getValue(afwMath.MEDIAN) 

skySigma = stats.getValue(afwMath.STDEVCLIP) 

self.log.info("Flattened sky level: %f +/- %f.", skyLevel, skySigma) 

metadata = exposure.getMetadata() 

metadata.set('SKYLEVEL', skyLevel) 

metadata.set('SKYSIGMA', skySigma) 

 

# calcluating flatlevel over the subgrids 

stat = afwMath.MEANCLIP if IsrQaConfig.flatness.doClip else afwMath.MEAN 

meshXHalf = int(IsrQaConfig.flatness.meshX/2.) 

meshYHalf = int(IsrQaConfig.flatness.meshY/2.) 

nX = int((exposure.getWidth() + meshXHalf) / IsrQaConfig.flatness.meshX) 

nY = int((exposure.getHeight() + meshYHalf) / IsrQaConfig.flatness.meshY) 

skyLevels = numpy.zeros((nX, nY)) 

 

for j in range(nY): 

yc = meshYHalf + j * IsrQaConfig.flatness.meshY 

for i in range(nX): 

xc = meshXHalf + i * IsrQaConfig.flatness.meshX 

 

xLLC = xc - meshXHalf 

yLLC = yc - meshYHalf 

xURC = xc + meshXHalf - 1 

yURC = yc + meshYHalf - 1 

 

bbox = lsst.geom.Box2I(lsst.geom.Point2I(xLLC, yLLC), lsst.geom.Point2I(xURC, yURC)) 

miMesh = maskedImage.Factory(exposure.getMaskedImage(), bbox, afwImage.LOCAL) 

 

skyLevels[i, j] = afwMath.makeStatistics(miMesh, stat, statsControl).getValue() 

 

good = numpy.where(numpy.isfinite(skyLevels)) 

skyMedian = numpy.median(skyLevels[good]) 

flatness = (skyLevels[good] - skyMedian) / skyMedian 

flatness_rms = numpy.std(flatness) 

flatness_pp = flatness.max() - flatness.min() if len(flatness) > 0 else numpy.nan 

 

self.log.info("Measuring sky levels in %dx%d grids: %f.", nX, nY, skyMedian) 

self.log.info("Sky flatness in %dx%d grids - pp: %f rms: %f.", 

nX, nY, flatness_pp, flatness_rms) 

 

metadata.set('FLATNESS_PP', float(flatness_pp)) 

metadata.set('FLATNESS_RMS', float(flatness_rms)) 

metadata.set('FLATNESS_NGRIDS', '%dx%d' % (nX, nY)) 

metadata.set('FLATNESS_MESHX', IsrQaConfig.flatness.meshX) 

metadata.set('FLATNESS_MESHY', IsrQaConfig.flatness.meshY) 

 

def roughZeroPoint(self, exposure): 

"""Set an approximate magnitude zero point for the exposure. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to process. 

""" 

filterName = afwImage.Filter(exposure.getFilter().getId()).getName() # Canonical name for filter 

if filterName in self.config.fluxMag0T1: 

fluxMag0 = self.config.fluxMag0T1[filterName] 

else: 

self.log.warn("No rough magnitude zero point set for filter %s.", filterName) 

fluxMag0 = self.config.defaultFluxMag0T1 

 

expTime = exposure.getInfo().getVisitInfo().getExposureTime() 

if not expTime > 0: # handle NaN as well as <= 0 

self.log.warn("Non-positive exposure time; skipping rough zero point.") 

return 

 

self.log.info("Setting rough magnitude zero point: %f", 2.5*math.log10(fluxMag0*expTime)) 

exposure.setPhotoCalib(afwImage.makePhotoCalibFromCalibZeroPoint(fluxMag0*expTime, 0.0)) 

 

def setValidPolygonIntersect(self, ccdExposure, fpPolygon): 

"""!Set the valid polygon as the intersection of fpPolygon and the ccd corners. 

 

Parameters 

---------- 

ccdExposure : `lsst.afw.image.Exposure` 

Exposure to process. 

fpPolygon : `lsst.afw.geom.Polygon` 

Polygon in focal plane coordinates. 

""" 

# Get ccd corners in focal plane coordinates 

ccd = ccdExposure.getDetector() 

fpCorners = ccd.getCorners(FOCAL_PLANE) 

ccdPolygon = Polygon(fpCorners) 

 

# Get intersection of ccd corners with fpPolygon 

intersect = ccdPolygon.intersectionSingle(fpPolygon) 

 

# Transform back to pixel positions and build new polygon 

ccdPoints = ccd.transform(intersect, FOCAL_PLANE, PIXELS) 

validPolygon = Polygon(ccdPoints) 

ccdExposure.getInfo().setValidPolygon(validPolygon) 

 

@contextmanager 

def flatContext(self, exp, flat, dark=None): 

"""Context manager that applies and removes flats and darks, 

if the task is configured to apply them. 

 

Parameters 

---------- 

exp : `lsst.afw.image.Exposure` 

Exposure to process. 

flat : `lsst.afw.image.Exposure` 

Flat exposure the same size as ``exp``. 

dark : `lsst.afw.image.Exposure`, optional 

Dark exposure the same size as ``exp``. 

 

Yields 

------ 

exp : `lsst.afw.image.Exposure` 

The flat and dark corrected exposure. 

""" 

if self.config.doDark and dark is not None: 

self.darkCorrection(exp, dark) 

if self.config.doFlat: 

self.flatCorrection(exp, flat) 

try: 

yield exp 

finally: 

if self.config.doFlat: 

self.flatCorrection(exp, flat, invert=True) 

if self.config.doDark and dark is not None: 

self.darkCorrection(exp, dark, invert=True) 

 

def debugView(self, exposure, stepname): 

"""Utility function to examine ISR exposure at different stages. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to view. 

stepname : `str` 

State of processing to view. 

""" 

frame = getDebugFrame(self._display, stepname) 

if frame: 

display = getDisplay(frame) 

display.scale('asinh', 'zscale') 

display.mtv(exposure) 

prompt = "Press Enter to continue [c]... " 

while True: 

ans = input(prompt).lower() 

if ans in ("", "c",): 

break 

 

 

class FakeAmp(object): 

"""A Detector-like object that supports returning gain and saturation level 

 

This is used when the input exposure does not have a detector. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure to generate a fake amplifier for. 

config : `lsst.ip.isr.isrTaskConfig` 

Configuration to apply to the fake amplifier. 

""" 

 

def __init__(self, exposure, config): 

self._bbox = exposure.getBBox(afwImage.LOCAL) 

self._RawHorizontalOverscanBBox = lsst.geom.Box2I() 

self._gain = config.gain 

self._readNoise = config.readNoise 

self._saturation = config.saturation 

 

def getBBox(self): 

return self._bbox 

 

def getRawBBox(self): 

return self._bbox 

 

def getHasRawInfo(self): 

return True # but see getRawHorizontalOverscanBBox() 

 

def getRawHorizontalOverscanBBox(self): 

return self._RawHorizontalOverscanBBox 

 

def getGain(self): 

return self._gain 

 

def getReadNoise(self): 

return self._readNoise 

 

def getSaturation(self): 

return self._saturation 

 

def getSuspectLevel(self): 

return float("NaN") 

 

 

class RunIsrConfig(pexConfig.Config): 

isr = pexConfig.ConfigurableField(target=IsrTask, doc="Instrument signature removal") 

 

 

class RunIsrTask(pipeBase.CmdLineTask): 

"""Task to wrap the default IsrTask to allow it to be retargeted. 

 

The standard IsrTask can be called directly from a command line 

program, but doing so removes the ability of the task to be 

retargeted. As most cameras override some set of the IsrTask 

methods, this would remove those data-specific methods in the 

output post-ISR images. This wrapping class fixes the issue, 

allowing identical post-ISR images to be generated by both the 

processCcd and isrTask code. 

""" 

ConfigClass = RunIsrConfig 

_DefaultName = "runIsr" 

 

def __init__(self, *args, **kwargs): 

super().__init__(*args, **kwargs) 

self.makeSubtask("isr") 

 

def runDataRef(self, dataRef): 

""" 

Parameters 

---------- 

dataRef : `lsst.daf.persistence.ButlerDataRef` 

data reference of the detector data to be processed 

 

Returns 

------- 

result : `pipeBase.Struct` 

Result struct with component: 

 

- exposure : `lsst.afw.image.Exposure` 

Post-ISR processed exposure. 

""" 

return self.isr.runDataRef(dataRef)