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

# This file is part of pipe_tasks. 

# 

# LSST Data Management System 

# This product includes software developed by the 

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

# See COPYRIGHT file at the top of the source tree. 

# 

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

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

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

# (at your option) any later version. 

# 

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

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

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

# You should have received a copy of the LSST License Statement and 

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

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

# 

import os 

import numpy 

import warnings 

import lsst.pex.config as pexConfig 

import lsst.pex.exceptions as pexExceptions 

import lsst.afw.geom as afwGeom 

import lsst.afw.image as afwImage 

import lsst.afw.math as afwMath 

import lsst.afw.table as afwTable 

import lsst.afw.detection as afwDet 

import lsst.coadd.utils as coaddUtils 

import lsst.pipe.base as pipeBase 

import lsst.meas.algorithms as measAlg 

import lsst.log as log 

import lsstDebug 

from .coaddBase import CoaddBaseTask, SelectDataIdContainer, makeSkyInfo 

from .interpImage import InterpImageTask 

from .scaleZeroPoint import ScaleZeroPointTask 

from .coaddHelpers import groupPatchExposures, getGroupDataRef 

from .scaleVariance import ScaleVarianceTask 

from lsst.meas.algorithms import SourceDetectionTask 

from lsst.pipe.base.shims import ShimButler 

 

__all__ = ["AssembleCoaddTask", "AssembleCoaddConfig", "SafeClipAssembleCoaddTask", 

"SafeClipAssembleCoaddConfig", "CompareWarpAssembleCoaddTask", "CompareWarpAssembleCoaddConfig"] 

 

 

class AssembleCoaddConfig(CoaddBaseTask.ConfigClass, pipeBase.PipelineTaskConfig): 

"""Configuration parameters for the `AssembleCoaddTask`. 

 

Notes 

----- 

The `doMaskBrightObjects` and `brightObjectMaskName` configuration options 

only set the bitplane config.brightObjectMaskName. To make this useful you 

*must* also configure the flags.pixel algorithm, for example by adding 

 

.. code-block:: none 

 

config.measurement.plugins["base_PixelFlags"].masksFpCenter.append("BRIGHT_OBJECT") 

config.measurement.plugins["base_PixelFlags"].masksFpAnywhere.append("BRIGHT_OBJECT") 

 

to your measureCoaddSources.py and forcedPhotCoadd.py config overrides. 

""" 

warpType = pexConfig.Field( 

doc="Warp name: one of 'direct' or 'psfMatched'", 

dtype=str, 

default="direct", 

) 

subregionSize = pexConfig.ListField( 

dtype=int, 

doc="Width, height of stack subregion size; " 

"make small enough that a full stack of images will fit into memory at once.", 

length=2, 

default=(2000, 2000), 

) 

statistic = pexConfig.Field( 

dtype=str, 

doc="Main stacking statistic for aggregating over the epochs.", 

default="MEANCLIP", 

) 

doSigmaClip = pexConfig.Field( 

dtype=bool, 

doc="Perform sigma clipped outlier rejection with MEANCLIP statistic? (DEPRECATED)", 

default=False, 

) 

sigmaClip = pexConfig.Field( 

dtype=float, 

doc="Sigma for outlier rejection; ignored if non-clipping statistic selected.", 

default=3.0, 

) 

clipIter = pexConfig.Field( 

dtype=int, 

doc="Number of iterations of outlier rejection; ignored if non-clipping statistic selected.", 

default=2, 

) 

calcErrorFromInputVariance = pexConfig.Field( 

dtype=bool, 

doc="Calculate coadd variance from input variance by stacking statistic." 

"Passed to StatisticsControl.setCalcErrorFromInputVariance()", 

default=True, 

) 

scaleZeroPoint = pexConfig.ConfigurableField( 

target=ScaleZeroPointTask, 

doc="Task to adjust the photometric zero point of the coadd temp exposures", 

) 

doInterp = pexConfig.Field( 

doc="Interpolate over NaN pixels? Also extrapolate, if necessary, but the results are ugly.", 

dtype=bool, 

default=True, 

) 

interpImage = pexConfig.ConfigurableField( 

target=InterpImageTask, 

doc="Task to interpolate (and extrapolate) over NaN pixels", 

) 

doWrite = pexConfig.Field( 

doc="Persist coadd?", 

dtype=bool, 

default=True, 

) 

doNImage = pexConfig.Field( 

doc="Create image of number of contributing exposures for each pixel", 

dtype=bool, 

default=False, 

) 

doUsePsfMatchedPolygons = pexConfig.Field( 

doc="Use ValidPolygons from shrunk Psf-Matched Calexps? Should be set to True by CompareWarp only.", 

dtype=bool, 

default=False, 

) 

maskPropagationThresholds = pexConfig.DictField( 

keytype=str, 

itemtype=float, 

doc=("Threshold (in fractional weight) of rejection at which we propagate a mask plane to " 

"the coadd; that is, we set the mask bit on the coadd if the fraction the rejected frames " 

"would have contributed exceeds this value."), 

default={"SAT": 0.1}, 

) 

removeMaskPlanes = pexConfig.ListField(dtype=str, default=["NOT_DEBLENDED"], 

doc="Mask planes to remove before coadding") 

doMaskBrightObjects = pexConfig.Field(dtype=bool, default=False, 

doc="Set mask and flag bits for bright objects?") 

brightObjectMaskName = pexConfig.Field(dtype=str, default="BRIGHT_OBJECT", 

doc="Name of mask bit used for bright objects") 

coaddPsf = pexConfig.ConfigField( 

doc="Configuration for CoaddPsf", 

dtype=measAlg.CoaddPsfConfig, 

) 

doAttachTransmissionCurve = pexConfig.Field( 

dtype=bool, default=False, optional=False, 

doc=("Attach a piecewise TransmissionCurve for the coadd? " 

"(requires all input Exposures to have TransmissionCurves).") 

) 

inputWarps = pipeBase.InputDatasetField( 

doc=("Input list of warps to be assemebled i.e. stacked." 

"WarpType (e.g. direct, psfMatched) is controlled by we warpType config parameter"), 

nameTemplate="{inputCoaddName}Coadd_{warpType}Warp", 

storageClass="ExposureF", 

dimensions=("tract", "patch", "skymap", "visit", "instrument"), 

manualLoad=True, 

) 

skyMap = pipeBase.InputDatasetField( 

doc="Input definition of geometry/bbox and projection/wcs for coadded exposures", 

nameTemplate="{inputCoaddName}Coadd_skyMap", 

storageClass="SkyMap", 

dimensions=("skymap", ), 

scalar=True 

) 

brightObjectMask = pipeBase.InputDatasetField( 

doc=("Input Bright Object Mask mask produced with external catalogs to be applied to the mask plane" 

" BRIGHT_OBJECT."), 

name="brightObjectMask", 

storageClass="ObjectMaskCatalog", 

dimensions=("tract", "patch", "skymap", "abstract_filter"), 

scalar=True 

) 

coaddExposure = pipeBase.OutputDatasetField( 

doc="Output coadded exposure, produced by stacking input warps", 

nameTemplate="{outputCoaddName}Coadd", 

storageClass="ExposureF", 

dimensions=("tract", "patch", "skymap", "abstract_filter"), 

scalar=True 

) 

nImage = pipeBase.OutputDatasetField( 

doc="Output image of number of input images per pixel", 

nameTemplate="{outputCoaddName}Coadd_nImage", 

storageClass="ImageU", 

dimensions=("tract", "patch", "skymap", "abstract_filter"), 

scalar=True 

) 

 

hasFakes = pexConfig.Field( 

dtype=bool, 

default=False, 

doc="Should be set to True if fake sources have been inserted into the input data." 

) 

 

def setDefaults(self): 

super().setDefaults() 

self.badMaskPlanes = ["NO_DATA", "BAD", "SAT", "EDGE"] 

self.formatTemplateNames({"inputCoaddName": "deep", "outputCoaddName": "deep", 

"warpType": self.warpType}) 

self.quantum.dimensions = ("tract", "patch", "abstract_filter", "skymap") 

 

def validate(self): 

super().validate() 

if self.doPsfMatch: 

# Backwards compatibility. 

# Configs do not have loggers 

log.warn("Config doPsfMatch deprecated. Setting warpType='psfMatched'") 

self.warpType = 'psfMatched' 

if self.doSigmaClip and self.statistic != "MEANCLIP": 

log.warn('doSigmaClip deprecated. To replicate behavior, setting statistic to "MEANCLIP"') 

self.statistic = "MEANCLIP" 

if self.doInterp and self.statistic not in ['MEAN', 'MEDIAN', 'MEANCLIP', 'VARIANCE', 'VARIANCECLIP']: 

raise ValueError("Must set doInterp=False for statistic=%s, which does not " 

"compute and set a non-zero coadd variance estimate." % (self.statistic)) 

 

unstackableStats = ['NOTHING', 'ERROR', 'ORMASK'] 

if not hasattr(afwMath.Property, self.statistic) or self.statistic in unstackableStats: 

stackableStats = [str(k) for k in afwMath.Property.__members__.keys() 

if str(k) not in unstackableStats] 

raise ValueError("statistic %s is not allowed. Please choose one of %s." 

% (self.statistic, stackableStats)) 

 

 

class AssembleCoaddTask(CoaddBaseTask, pipeBase.PipelineTask): 

"""Assemble a coadded image from a set of warps (coadded temporary exposures). 

 

We want to assemble a coadded image from a set of Warps (also called 

coadded temporary exposures or ``coaddTempExps``). 

Each input Warp covers a patch on the sky and corresponds to a single 

run/visit/exposure of the covered patch. We provide the task with a list 

of Warps (``selectDataList``) from which it selects Warps that cover the 

specified patch (pointed at by ``dataRef``). 

Each Warp that goes into a coadd will typically have an independent 

photometric zero-point. Therefore, we must scale each Warp to set it to 

a common photometric zeropoint. WarpType may be one of 'direct' or 

'psfMatched', and the boolean configs `config.makeDirect` and 

`config.makePsfMatched` set which of the warp types will be coadded. 

The coadd is computed as a mean with optional outlier rejection. 

Criteria for outlier rejection are set in `AssembleCoaddConfig`. 

Finally, Warps can have bad 'NaN' pixels which received no input from the 

source calExps. We interpolate over these bad (NaN) pixels. 

 

`AssembleCoaddTask` uses several sub-tasks. These are 

 

- `ScaleZeroPointTask` 

- create and use an ``imageScaler`` object to scale the photometric zeropoint for each Warp 

- `InterpImageTask` 

- interpolate across bad pixels (NaN) in the final coadd 

 

You can retarget these subtasks if you wish. 

 

Notes 

----- 

The `lsst.pipe.base.cmdLineTask.CmdLineTask` interface supports a 

flag ``-d`` to import ``debug.py`` from your ``PYTHONPATH``; see 

`baseDebug` for more about ``debug.py`` files. `AssembleCoaddTask` has 

no debug variables of its own. Some of the subtasks may support debug 

variables. See the documentation for the subtasks for further information. 

 

Examples 

-------- 

`AssembleCoaddTask` assembles a set of warped images into a coadded image. 

The `AssembleCoaddTask` can be invoked by running ``assembleCoadd.py`` 

with the flag '--legacyCoadd'. Usage of assembleCoadd.py expects two 

inputs: a data reference to the tract patch and filter to be coadded, and 

a list of Warps to attempt to coadd. These are specified using ``--id`` and 

``--selectId``, respectively: 

 

.. code-block:: none 

 

--id = [KEY=VALUE1[^VALUE2[^VALUE3...] [KEY=VALUE1[^VALUE2[^VALUE3...] ...]] 

--selectId [KEY=VALUE1[^VALUE2[^VALUE3...] [KEY=VALUE1[^VALUE2[^VALUE3...] ...]] 

 

Only the Warps that cover the specified tract and patch will be coadded. 

A list of the available optional arguments can be obtained by calling 

``assembleCoadd.py`` with the ``--help`` command line argument: 

 

.. code-block:: none 

 

assembleCoadd.py --help 

 

To demonstrate usage of the `AssembleCoaddTask` in the larger context of 

multi-band processing, we will generate the HSC-I & -R band coadds from 

HSC engineering test data provided in the ``ci_hsc`` package. To begin, 

assuming that the lsst stack has been already set up, we must set up the 

obs_subaru and ``ci_hsc`` packages. This defines the environment variable 

``$CI_HSC_DIR`` and points at the location of the package. The raw HSC 

data live in the ``$CI_HSC_DIR/raw directory``. To begin assembling the 

coadds, we must first 

 

- processCcd 

- process the individual ccds in $CI_HSC_RAW to produce calibrated exposures 

- makeSkyMap 

- create a skymap that covers the area of the sky present in the raw exposures 

- makeCoaddTempExp 

- warp the individual calibrated exposures to the tangent plane of the coadd 

 

We can perform all of these steps by running 

 

.. code-block:: none 

 

$CI_HSC_DIR scons warp-903986 warp-904014 warp-903990 warp-904010 warp-903988 

 

This will produce warped exposures for each visit. To coadd the warped 

data, we call assembleCoadd.py as follows: 

 

.. code-block:: none 

 

assembleCoadd.py --legacyCoadd $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-I \ 

--selectId visit=903986 ccd=16 --selectId visit=903986 ccd=22 --selectId visit=903986 ccd=23 \ 

--selectId visit=903986 ccd=100 --selectId visit=904014 ccd=1 --selectId visit=904014 ccd=6 \ 

--selectId visit=904014 ccd=12 --selectId visit=903990 ccd=18 --selectId visit=903990 ccd=25 \ 

--selectId visit=904010 ccd=4 --selectId visit=904010 ccd=10 --selectId visit=904010 ccd=100 \ 

--selectId visit=903988 ccd=16 --selectId visit=903988 ccd=17 --selectId visit=903988 ccd=23 \ 

--selectId visit=903988 ccd=24 

 

that will process the HSC-I band data. The results are written in 

``$CI_HSC_DIR/DATA/deepCoadd-results/HSC-I``. 

 

You may also choose to run: 

 

.. code-block:: none 

 

scons warp-903334 warp-903336 warp-903338 warp-903342 warp-903344 warp-903346 

assembleCoadd.py --legacyCoadd $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-R \ 

--selectId visit=903334 ccd=16 --selectId visit=903334 ccd=22 --selectId visit=903334 ccd=23 \ 

--selectId visit=903334 ccd=100 --selectId visit=903336 ccd=17 --selectId visit=903336 ccd=24 \ 

--selectId visit=903338 ccd=18 --selectId visit=903338 ccd=25 --selectId visit=903342 ccd=4 \ 

--selectId visit=903342 ccd=10 --selectId visit=903342 ccd=100 --selectId visit=903344 ccd=0 \ 

--selectId visit=903344 ccd=5 --selectId visit=903344 ccd=11 --selectId visit=903346 ccd=1 \ 

--selectId visit=903346 ccd=6 --selectId visit=903346 ccd=12 

 

to generate the coadd for the HSC-R band if you are interested in 

following multiBand Coadd processing as discussed in `pipeTasks_multiBand` 

(but note that normally, one would use the `SafeClipAssembleCoaddTask` 

rather than `AssembleCoaddTask` to make the coadd. 

""" 

ConfigClass = AssembleCoaddConfig 

_DefaultName = "assembleCoadd" 

 

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

# TODO: DM-17415 better way to handle previously allowed passed args e.g.`AssembleCoaddTask(config)` 

if args: 

argNames = ["config", "name", "parentTask", "log"] 

kwargs.update({k: v for k, v in zip(argNames, args)}) 

warnings.warn("AssembleCoadd received positional args, and casting them as kwargs: %s. " 

"PipelineTask will not take positional args" % argNames, FutureWarning) 

 

super().__init__(**kwargs) 

self.makeSubtask("interpImage") 

self.makeSubtask("scaleZeroPoint") 

 

if self.config.doMaskBrightObjects: 

mask = afwImage.Mask() 

try: 

self.brightObjectBitmask = 1 << mask.addMaskPlane(self.config.brightObjectMaskName) 

except pexExceptions.LsstCppException: 

raise RuntimeError("Unable to define mask plane for bright objects; planes used are %s" % 

mask.getMaskPlaneDict().keys()) 

del mask 

 

self.warpType = self.config.warpType 

 

@classmethod 

def getOutputDatasetTypes(cls, config): 

"""Return output dataset type descriptors 

 

Remove output dataset types not produced by the Task 

""" 

outputTypeDict = super().getOutputDatasetTypes(config) 

if not config.doNImage: 

outputTypeDict.pop("nImage", None) 

return outputTypeDict 

 

@classmethod 

def getInputDatasetTypes(cls, config): 

"""Return input dataset type descriptors 

 

Remove input dataset types not used by the Task 

""" 

inputTypeDict = super().getInputDatasetTypes(config) 

if not config.doMaskBrightObjects: 

inputTypeDict.pop("brightObjectMask", None) 

return inputTypeDict 

 

@classmethod 

def getPrerequisiteDatasetTypes(cls, config): 

return frozenset(["brightObjectMask"]) 

 

def adaptArgsAndRun(self, inputData, inputDataIds, outputDataIds, butler): 

"""Assemble a coadd from a set of Warps. 

 

PipelineTask (Gen3) entry point to Coadd a set of Warps. 

Analogous to `runDataRef`, it prepares all the data products to be 

passed to `run`, and processes the results before returning to struct 

of results to be written out. AssembleCoadd cannot fit all Warps in memory. 

Therefore, its inputs are accessed subregion by subregion 

by the `lsst.daf.butler.ShimButler` that quacks like a Gen2 

`lsst.daf.persistence.Butler`. Updates to this method should 

correspond to an update in `runDataRef` while both entry points 

are used. 

 

Parameters 

---------- 

inputData : `dict` 

Keys are the names of the configs describing input dataset types. 

Values are input Python-domain data objects (or lists of objects) 

retrieved from data butler. 

inputDataIds : `dict` 

Keys are the names of the configs describing input dataset types. 

Values are DataIds (or lists of DataIds) that task consumes for 

corresponding dataset type. 

outputDataIds : `dict` 

Keys are the names of the configs describing input dataset types. 

Values are DataIds (or lists of DataIds) that task is to produce 

for corresponding dataset type. 

butler : `lsst.daf.butler.Butler` 

Gen3 Butler object for fetching additional data products before 

running the Task 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Result struct with components: 

 

- ``coaddExposure`` : coadded exposure (``lsst.afw.image.Exposure``) 

- ``nImage``: N Image (``lsst.afw.image.Image``) 

""" 

# Construct skyInfo expected by run 

# Do not remove skyMap from inputData in case makeSupplementaryDataGen3 needs it 

skyMap = inputData["skyMap"] 

outputDataId = next(iter(outputDataIds.values())) 

inputData['skyInfo'] = makeSkyInfo(skyMap, 

tractId=outputDataId['tract'], 

patchId=outputDataId['patch']) 

 

# Construct list of input Shim DataRefs that quack like Gen2 DataRefs 

butlerShim = ShimButler(butler) 

warpRefList = [butlerShim.dataRef(self.config.inputWarps.name, dataId=dataId) 

for dataId in inputDataIds['inputWarps']] 

 

# Construct output Shim DataRef 

patchRef = butlerShim.dataRef(self.config.coaddExposure.name, dataId=outputDataIds['coaddExposure']) 

 

# Perform same middle steps as `runDataRef` does 

inputs = self.prepareInputs(warpRefList) 

self.log.info("Found %d %s", len(inputs.tempExpRefList), 

self.getTempExpDatasetName(self.warpType)) 

if len(inputs.tempExpRefList) == 0: 

self.log.warn("No coadd temporary exposures found") 

return 

 

supplementaryData = self.makeSupplementaryDataGen3(inputData, inputDataIds, outputDataIds, butler) 

 

retStruct = self.run(inputData['skyInfo'], inputs.tempExpRefList, inputs.imageScalerList, 

inputs.weightList, supplementaryData=supplementaryData) 

 

self.processResults(retStruct.coaddExposure, patchRef) 

return retStruct 

 

@pipeBase.timeMethod 

def runDataRef(self, dataRef, selectDataList=None, warpRefList=None): 

"""Assemble a coadd from a set of Warps. 

 

Pipebase.CmdlineTask entry point to Coadd a set of Warps. 

Compute weights to be applied to each Warp and 

find scalings to match the photometric zeropoint to a reference Warp. 

Assemble the Warps using `run`. Interpolate over NaNs and 

optionally write the coadd to disk. Return the coadded exposure. 

 

Parameters 

---------- 

dataRef : `lsst.daf.persistence.butlerSubset.ButlerDataRef` 

Data reference defining the patch for coaddition and the 

reference Warp (if ``config.autoReference=False``). 

Used to access the following data products: 

- ``self.config.coaddName + "Coadd_skyMap"`` 

- ``self.config.coaddName + "Coadd_ + <warpType> + "Warp"`` (optionally) 

- ``self.config.coaddName + "Coadd"`` 

selectDataList : `list` 

List of data references to Calexps. Data to be coadded will be 

selected from this list based on overlap with the patch defined 

by dataRef, grouped by visit, and converted to a list of data 

references to warps. 

warpRefList : `list` 

List of data references to Warps to be coadded. 

Note: `warpRefList` is just the new name for `tempExpRefList`. 

 

Returns 

------- 

retStruct : `lsst.pipe.base.Struct` 

Result struct with components: 

 

- ``coaddExposure``: coadded exposure (``Exposure``). 

- ``nImage``: exposure count image (``Image``). 

""" 

if selectDataList and warpRefList: 

raise RuntimeError("runDataRef received both a selectDataList and warpRefList, " 

"and which to use is ambiguous. Please pass only one.") 

 

skyInfo = self.getSkyInfo(dataRef) 

if warpRefList is None: 

calExpRefList = self.selectExposures(dataRef, skyInfo, selectDataList=selectDataList) 

if len(calExpRefList) == 0: 

self.log.warn("No exposures to coadd") 

return 

self.log.info("Coadding %d exposures", len(calExpRefList)) 

 

warpRefList = self.getTempExpRefList(dataRef, calExpRefList) 

 

inputData = self.prepareInputs(warpRefList) 

self.log.info("Found %d %s", len(inputData.tempExpRefList), 

self.getTempExpDatasetName(self.warpType)) 

if len(inputData.tempExpRefList) == 0: 

self.log.warn("No coadd temporary exposures found") 

return 

 

supplementaryData = self.makeSupplementaryData(dataRef, warpRefList=inputData.tempExpRefList) 

 

retStruct = self.run(skyInfo, inputData.tempExpRefList, inputData.imageScalerList, 

inputData.weightList, supplementaryData=supplementaryData) 

 

self.processResults(retStruct.coaddExposure, dataRef) 

if self.config.doWrite: 

if self.getCoaddDatasetName(self.warpType) == "deepCoadd" and self.config.hasFakes: 

coaddDatasetName = "fakes_" + self.getCoaddDatasetName(self.warpType) 

else: 

coaddDatasetName = self.getCoaddDatasetName(self.warpType) 

self.log.info("Persisting %s" % coaddDatasetName) 

dataRef.put(retStruct.coaddExposure, coaddDatasetName) 

if self.config.doNImage and retStruct.nImage is not None: 

dataRef.put(retStruct.nImage, self.getCoaddDatasetName(self.warpType) + '_nImage') 

 

return retStruct 

 

def processResults(self, coaddExposure, dataRef): 

"""Interpolate over missing data and mask bright stars. 

 

Parameters 

---------- 

coaddExposure : `lsst.afw.image.Exposure` 

The coadded exposure to process. 

dataRef : `lsst.daf.persistence.ButlerDataRef` 

Butler data reference for supplementary data. 

""" 

if self.config.doInterp: 

self.interpImage.run(coaddExposure.getMaskedImage(), planeName="NO_DATA") 

# The variance must be positive; work around for DM-3201. 

varArray = coaddExposure.variance.array 

with numpy.errstate(invalid="ignore"): 

varArray[:] = numpy.where(varArray > 0, varArray, numpy.inf) 

 

if self.config.doMaskBrightObjects: 

brightObjectMasks = self.readBrightObjectMasks(dataRef) 

self.setBrightObjectMasks(coaddExposure, dataRef.dataId, brightObjectMasks) 

 

def makeSupplementaryData(self, dataRef, selectDataList=None, warpRefList=None): 

"""Make additional inputs to run() specific to subclasses (Gen2) 

 

Duplicates interface of `runDataRef` method 

Available to be implemented by subclasses only if they need the 

coadd dataRef for performing preliminary processing before 

assembling the coadd. 

 

Parameters 

---------- 

dataRef : `lsst.daf.persistence.ButlerDataRef` 

Butler data reference for supplementary data. 

selectDataList : `list` 

List of data references to Warps. 

""" 

pass 

 

def makeSupplementaryDataGen3(self, inputData, inputDataIds, outputDataIds, butler): 

"""Make additional inputs to run() specific to subclasses (Gen3) 

 

Duplicates interface of`adaptArgsAndRun` method. 

Available to be implemented by subclasses only if they need the 

coadd dataRef for performing preliminary processing before 

assembling the coadd. 

 

Parameters 

---------- 

inputData : `dict` 

Keys are the names of the configs describing input dataset types. 

Values are input Python-domain data objects (or lists of objects) 

retrieved from data butler. 

inputDataIds : `dict` 

Keys are the names of the configs describing input dataset types. 

Values are DataIds (or lists of DataIds) that task consumes for 

corresponding dataset type. 

DataIds are guaranteed to match data objects in ``inputData``. 

outputDataIds : `dict` 

Keys are the names of the configs describing input dataset types. 

Values are DataIds (or lists of DataIds) that task is to produce 

for corresponding dataset type. 

butler : `lsst.daf.butler.Butler` 

Gen3 Butler object for fetching additional data products before 

running the Task 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Contains whatever additional data the subclass's `run` method needs 

""" 

pass 

 

def getTempExpRefList(self, patchRef, calExpRefList): 

"""Generate list data references corresponding to warped exposures 

that lie within the patch to be coadded. 

 

Parameters 

---------- 

patchRef : `dataRef` 

Data reference for patch. 

calExpRefList : `list` 

List of data references for input calexps. 

 

Returns 

------- 

tempExpRefList : `list` 

List of Warp/CoaddTempExp data references. 

""" 

butler = patchRef.getButler() 

groupData = groupPatchExposures(patchRef, calExpRefList, self.getCoaddDatasetName(self.warpType), 

self.getTempExpDatasetName(self.warpType)) 

tempExpRefList = [getGroupDataRef(butler, self.getTempExpDatasetName(self.warpType), 

g, groupData.keys) for 

g in groupData.groups.keys()] 

return tempExpRefList 

 

def prepareInputs(self, refList): 

"""Prepare the input warps for coaddition by measuring the weight for 

each warp and the scaling for the photometric zero point. 

 

Each Warp has its own photometric zeropoint and background variance. 

Before coadding these Warps together, compute a scale factor to 

normalize the photometric zeropoint and compute the weight for each Warp. 

 

Parameters 

---------- 

refList : `list` 

List of data references to tempExp 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Result struct with components: 

 

- ``tempExprefList``: `list` of data references to tempExp. 

- ``weightList``: `list` of weightings. 

- ``imageScalerList``: `list` of image scalers. 

""" 

statsCtrl = afwMath.StatisticsControl() 

statsCtrl.setNumSigmaClip(self.config.sigmaClip) 

statsCtrl.setNumIter(self.config.clipIter) 

statsCtrl.setAndMask(self.getBadPixelMask()) 

statsCtrl.setNanSafe(True) 

# compute tempExpRefList: a list of tempExpRef that actually exist 

# and weightList: a list of the weight of the associated coadd tempExp 

# and imageScalerList: a list of scale factors for the associated coadd tempExp 

tempExpRefList = [] 

weightList = [] 

imageScalerList = [] 

tempExpName = self.getTempExpDatasetName(self.warpType) 

for tempExpRef in refList: 

if not tempExpRef.datasetExists(tempExpName): 

self.log.warn("Could not find %s %s; skipping it", tempExpName, tempExpRef.dataId) 

continue 

 

tempExp = tempExpRef.get(tempExpName, immediate=True) 

# Ignore any input warp that is empty of data 

if numpy.isnan(tempExp.image.array).all(): 

continue 

maskedImage = tempExp.getMaskedImage() 

imageScaler = self.scaleZeroPoint.computeImageScaler( 

exposure=tempExp, 

dataRef=tempExpRef, 

) 

try: 

imageScaler.scaleMaskedImage(maskedImage) 

except Exception as e: 

self.log.warn("Scaling failed for %s (skipping it): %s", tempExpRef.dataId, e) 

continue 

statObj = afwMath.makeStatistics(maskedImage.getVariance(), maskedImage.getMask(), 

afwMath.MEANCLIP, statsCtrl) 

meanVar, meanVarErr = statObj.getResult(afwMath.MEANCLIP) 

weight = 1.0 / float(meanVar) 

if not numpy.isfinite(weight): 

self.log.warn("Non-finite weight for %s: skipping", tempExpRef.dataId) 

continue 

self.log.info("Weight of %s %s = %0.3f", tempExpName, tempExpRef.dataId, weight) 

 

del maskedImage 

del tempExp 

 

tempExpRefList.append(tempExpRef) 

weightList.append(weight) 

imageScalerList.append(imageScaler) 

 

return pipeBase.Struct(tempExpRefList=tempExpRefList, weightList=weightList, 

imageScalerList=imageScalerList) 

 

def prepareStats(self, mask=None): 

"""Prepare the statistics for coadding images. 

 

Parameters 

---------- 

mask : `int`, optional 

Bit mask value to exclude from coaddition. 

 

Returns 

------- 

stats : `lsst.pipe.base.Struct` 

Statistics structure with the following fields: 

 

- ``statsCtrl``: Statistics control object for coadd 

(`lsst.afw.math.StatisticsControl`) 

- ``statsFlags``: Statistic for coadd (`lsst.afw.math.Property`) 

""" 

if mask is None: 

mask = self.getBadPixelMask() 

statsCtrl = afwMath.StatisticsControl() 

statsCtrl.setNumSigmaClip(self.config.sigmaClip) 

statsCtrl.setNumIter(self.config.clipIter) 

statsCtrl.setAndMask(mask) 

statsCtrl.setNanSafe(True) 

statsCtrl.setWeighted(True) 

statsCtrl.setCalcErrorFromInputVariance(self.config.calcErrorFromInputVariance) 

for plane, threshold in self.config.maskPropagationThresholds.items(): 

bit = afwImage.Mask.getMaskPlane(plane) 

statsCtrl.setMaskPropagationThreshold(bit, threshold) 

statsFlags = afwMath.stringToStatisticsProperty(self.config.statistic) 

return pipeBase.Struct(ctrl=statsCtrl, flags=statsFlags) 

 

def run(self, skyInfo, tempExpRefList, imageScalerList, weightList, 

altMaskList=None, mask=None, supplementaryData=None): 

"""Assemble a coadd from input warps 

 

Assemble the coadd using the provided list of coaddTempExps. Since 

the full coadd covers a patch (a large area), the assembly is 

performed over small areas on the image at a time in order to 

conserve memory usage. Iterate over subregions within the outer 

bbox of the patch using `assembleSubregion` to stack the corresponding 

subregions from the coaddTempExps with the statistic specified. 

Set the edge bits the coadd mask based on the weight map. 

 

Parameters 

---------- 

skyInfo : `lsst.pipe.base.Struct` 

Struct with geometric information about the patch. 

tempExpRefList : `list` 

List of data references to Warps (previously called CoaddTempExps). 

imageScalerList : `list` 

List of image scalers. 

weightList : `list` 

List of weights 

altMaskList : `list`, optional 

List of alternate masks to use rather than those stored with 

tempExp. 

mask : `int`, optional 

Bit mask value to exclude from coaddition. 

supplementaryData : lsst.pipe.base.Struct, optional 

Struct with additional data products needed to assemble coadd. 

Only used by subclasses that implement `makeSupplementaryData` 

and override `run`. 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Result struct with components: 

 

- ``coaddExposure``: coadded exposure (``lsst.afw.image.Exposure``). 

- ``nImage``: exposure count image (``lsst.afw.image.Image``). 

""" 

tempExpName = self.getTempExpDatasetName(self.warpType) 

self.log.info("Assembling %s %s", len(tempExpRefList), tempExpName) 

stats = self.prepareStats(mask=mask) 

 

if altMaskList is None: 

altMaskList = [None]*len(tempExpRefList) 

 

coaddExposure = afwImage.ExposureF(skyInfo.bbox, skyInfo.wcs) 

coaddExposure.setPhotoCalib(self.scaleZeroPoint.getPhotoCalib()) 

coaddExposure.getInfo().setCoaddInputs(self.inputRecorder.makeCoaddInputs()) 

self.assembleMetadata(coaddExposure, tempExpRefList, weightList) 

coaddMaskedImage = coaddExposure.getMaskedImage() 

subregionSizeArr = self.config.subregionSize 

subregionSize = afwGeom.Extent2I(subregionSizeArr[0], subregionSizeArr[1]) 

# if nImage is requested, create a zero one which can be passed to assembleSubregion 

if self.config.doNImage: 

nImage = afwImage.ImageU(skyInfo.bbox) 

else: 

nImage = None 

for subBBox in self._subBBoxIter(skyInfo.bbox, subregionSize): 

try: 

self.assembleSubregion(coaddExposure, subBBox, tempExpRefList, imageScalerList, 

weightList, altMaskList, stats.flags, stats.ctrl, 

nImage=nImage) 

except Exception as e: 

self.log.fatal("Cannot compute coadd %s: %s", subBBox, e) 

 

self.setInexactPsf(coaddMaskedImage.getMask()) 

# Despite the name, the following doesn't really deal with "EDGE" pixels: it identifies 

# pixels that didn't receive any unmasked inputs (as occurs around the edge of the field). 

coaddUtils.setCoaddEdgeBits(coaddMaskedImage.getMask(), coaddMaskedImage.getVariance()) 

return pipeBase.Struct(coaddExposure=coaddExposure, nImage=nImage) 

 

def assembleMetadata(self, coaddExposure, tempExpRefList, weightList): 

"""Set the metadata for the coadd. 

 

This basic implementation sets the filter from the first input. 

 

Parameters 

---------- 

coaddExposure : `lsst.afw.image.Exposure` 

The target exposure for the coadd. 

tempExpRefList : `list` 

List of data references to tempExp. 

weightList : `list` 

List of weights. 

""" 

assert len(tempExpRefList) == len(weightList), "Length mismatch" 

tempExpName = self.getTempExpDatasetName(self.warpType) 

# We load a single pixel of each coaddTempExp, because we just want to get at the metadata 

# (and we need more than just the PropertySet that contains the header), which is not possible 

# with the current butler (see #2777). 

tempExpList = [tempExpRef.get(tempExpName + "_sub", 

bbox=afwGeom.Box2I(coaddExposure.getBBox().getMin(), 

afwGeom.Extent2I(1, 1)), immediate=True) 

for tempExpRef in tempExpRefList] 

numCcds = sum(len(tempExp.getInfo().getCoaddInputs().ccds) for tempExp in tempExpList) 

 

coaddExposure.setFilter(tempExpList[0].getFilter()) 

coaddInputs = coaddExposure.getInfo().getCoaddInputs() 

coaddInputs.ccds.reserve(numCcds) 

coaddInputs.visits.reserve(len(tempExpList)) 

 

for tempExp, weight in zip(tempExpList, weightList): 

self.inputRecorder.addVisitToCoadd(coaddInputs, tempExp, weight) 

 

if self.config.doUsePsfMatchedPolygons: 

self.shrinkValidPolygons(coaddInputs) 

 

coaddInputs.visits.sort() 

if self.warpType == "psfMatched": 

# The modelPsf BBox for a psfMatchedWarp/coaddTempExp was dynamically defined by 

# ModelPsfMatchTask as the square box bounding its spatially-variable, pre-matched WarpedPsf. 

# Likewise, set the PSF of a PSF-Matched Coadd to the modelPsf 

# having the maximum width (sufficient because square) 

modelPsfList = [tempExp.getPsf() for tempExp in tempExpList] 

modelPsfWidthList = [modelPsf.computeBBox().getWidth() for modelPsf in modelPsfList] 

psf = modelPsfList[modelPsfWidthList.index(max(modelPsfWidthList))] 

else: 

psf = measAlg.CoaddPsf(coaddInputs.ccds, coaddExposure.getWcs(), 

self.config.coaddPsf.makeControl()) 

coaddExposure.setPsf(psf) 

apCorrMap = measAlg.makeCoaddApCorrMap(coaddInputs.ccds, coaddExposure.getBBox(afwImage.PARENT), 

coaddExposure.getWcs()) 

coaddExposure.getInfo().setApCorrMap(apCorrMap) 

if self.config.doAttachTransmissionCurve: 

transmissionCurve = measAlg.makeCoaddTransmissionCurve(coaddExposure.getWcs(), coaddInputs.ccds) 

coaddExposure.getInfo().setTransmissionCurve(transmissionCurve) 

 

def assembleSubregion(self, coaddExposure, bbox, tempExpRefList, imageScalerList, weightList, 

altMaskList, statsFlags, statsCtrl, nImage=None): 

"""Assemble the coadd for a sub-region. 

 

For each coaddTempExp, check for (and swap in) an alternative mask 

if one is passed. Remove mask planes listed in 

`config.removeMaskPlanes`. Finally, stack the actual exposures using 

`lsst.afw.math.statisticsStack` with the statistic specified by 

statsFlags. Typically, the statsFlag will be one of lsst.afw.math.MEAN for 

a mean-stack or `lsst.afw.math.MEANCLIP` for outlier rejection using 

an N-sigma clipped mean where N and iterations are specified by 

statsCtrl. Assign the stacked subregion back to the coadd. 

 

Parameters 

---------- 

coaddExposure : `lsst.afw.image.Exposure` 

The target exposure for the coadd. 

bbox : `lsst.afw.geom.Box` 

Sub-region to coadd. 

tempExpRefList : `list` 

List of data reference to tempExp. 

imageScalerList : `list` 

List of image scalers. 

weightList : `list` 

List of weights. 

altMaskList : `list` 

List of alternate masks to use rather than those stored with 

tempExp, or None. Each element is dict with keys = mask plane 

name to which to add the spans. 

statsFlags : `lsst.afw.math.Property` 

Property object for statistic for coadd. 

statsCtrl : `lsst.afw.math.StatisticsControl` 

Statistics control object for coadd. 

nImage : `lsst.afw.image.ImageU`, optional 

Keeps track of exposure count for each pixel. 

""" 

self.log.debug("Computing coadd over %s", bbox) 

tempExpName = self.getTempExpDatasetName(self.warpType) 

coaddExposure.mask.addMaskPlane("REJECTED") 

coaddExposure.mask.addMaskPlane("CLIPPED") 

coaddExposure.mask.addMaskPlane("SENSOR_EDGE") 

maskMap = self.setRejectedMaskMapping(statsCtrl) 

clipped = afwImage.Mask.getPlaneBitMask("CLIPPED") 

maskedImageList = [] 

if nImage is not None: 

subNImage = afwImage.ImageU(bbox.getWidth(), bbox.getHeight()) 

for tempExpRef, imageScaler, altMask in zip(tempExpRefList, imageScalerList, altMaskList): 

exposure = tempExpRef.get(tempExpName + "_sub", bbox=bbox) 

maskedImage = exposure.getMaskedImage() 

mask = maskedImage.getMask() 

if altMask is not None: 

self.applyAltMaskPlanes(mask, altMask) 

imageScaler.scaleMaskedImage(maskedImage) 

 

# Add 1 for each pixel which is not excluded by the exclude mask. 

# In legacyCoadd, pixels may also be excluded by afwMath.statisticsStack. 

if nImage is not None: 

subNImage.getArray()[maskedImage.getMask().getArray() & statsCtrl.getAndMask() == 0] += 1 

if self.config.removeMaskPlanes: 

self.removeMaskPlanes(maskedImage) 

maskedImageList.append(maskedImage) 

 

with self.timer("stack"): 

coaddSubregion = afwMath.statisticsStack(maskedImageList, statsFlags, statsCtrl, weightList, 

clipped, # also set output to CLIPPED if sigma-clipped 

maskMap) 

coaddExposure.maskedImage.assign(coaddSubregion, bbox) 

if nImage is not None: 

nImage.assign(subNImage, bbox) 

 

def removeMaskPlanes(self, maskedImage): 

"""Unset the mask of an image for mask planes specified in the config. 

 

Parameters 

---------- 

maskedImage : `lsst.afw.image.MaskedImage` 

The masked image to be modified. 

""" 

mask = maskedImage.getMask() 

for maskPlane in self.config.removeMaskPlanes: 

try: 

mask &= ~mask.getPlaneBitMask(maskPlane) 

except pexExceptions.InvalidParameterError: 

self.log.debug("Unable to remove mask plane %s: no mask plane with that name was found.", 

maskPlane) 

 

@staticmethod 

def setRejectedMaskMapping(statsCtrl): 

"""Map certain mask planes of the warps to new planes for the coadd. 

 

If a pixel is rejected due to a mask value other than EDGE, NO_DATA, 

or CLIPPED, set it to REJECTED on the coadd. 

If a pixel is rejected due to EDGE, set the coadd pixel to SENSOR_EDGE. 

If a pixel is rejected due to CLIPPED, set the coadd pixel to CLIPPED. 

 

Parameters 

---------- 

statsCtrl : `lsst.afw.math.StatisticsControl` 

Statistics control object for coadd 

 

Returns 

------- 

maskMap : `list` of `tuple` of `int` 

A list of mappings of mask planes of the warped exposures to 

mask planes of the coadd. 

""" 

edge = afwImage.Mask.getPlaneBitMask("EDGE") 

noData = afwImage.Mask.getPlaneBitMask("NO_DATA") 

clipped = afwImage.Mask.getPlaneBitMask("CLIPPED") 

toReject = statsCtrl.getAndMask() & (~noData) & (~edge) & (~clipped) 

maskMap = [(toReject, afwImage.Mask.getPlaneBitMask("REJECTED")), 

(edge, afwImage.Mask.getPlaneBitMask("SENSOR_EDGE")), 

(clipped, clipped)] 

return maskMap 

 

def applyAltMaskPlanes(self, mask, altMaskSpans): 

"""Apply in place alt mask formatted as SpanSets to a mask. 

 

Parameters 

---------- 

mask : `lsst.afw.image.Mask` 

Original mask. 

altMaskSpans : `dict` 

SpanSet lists to apply. Each element contains the new mask 

plane name (e.g. "CLIPPED and/or "NO_DATA") as the key, 

and list of SpanSets to apply to the mask. 

 

Returns 

------- 

mask : `lsst.afw.image.Mask` 

Updated mask. 

""" 

if self.config.doUsePsfMatchedPolygons: 

if ("NO_DATA" in altMaskSpans) and ("NO_DATA" in self.config.badMaskPlanes): 

# Clear away any other masks outside the validPolygons. These pixels are no longer 

# contributing to inexact PSFs, and will still be rejected because of NO_DATA 

# self.config.doUsePsfMatchedPolygons should be True only in CompareWarpAssemble 

# This mask-clearing step must only occur *before* applying the new masks below 

for spanSet in altMaskSpans['NO_DATA']: 

spanSet.clippedTo(mask.getBBox()).clearMask(mask, self.getBadPixelMask()) 

 

for plane, spanSetList in altMaskSpans.items(): 

maskClipValue = mask.addMaskPlane(plane) 

for spanSet in spanSetList: 

spanSet.clippedTo(mask.getBBox()).setMask(mask, 2**maskClipValue) 

return mask 

 

def shrinkValidPolygons(self, coaddInputs): 

"""Shrink coaddInputs' ccds' ValidPolygons in place. 

 

Either modify each ccd's validPolygon in place, or if CoaddInputs 

does not have a validPolygon, create one from its bbox. 

 

Parameters 

---------- 

coaddInputs : `lsst.afw.image.coaddInputs` 

Original mask. 

 

""" 

for ccd in coaddInputs.ccds: 

polyOrig = ccd.getValidPolygon() 

validPolyBBox = polyOrig.getBBox() if polyOrig else ccd.getBBox() 

validPolyBBox.grow(-self.config.matchingKernelSize//2) 

if polyOrig: 

validPolygon = polyOrig.intersectionSingle(validPolyBBox) 

else: 

validPolygon = afwGeom.polygon.Polygon(afwGeom.Box2D(validPolyBBox)) 

ccd.setValidPolygon(validPolygon) 

 

def readBrightObjectMasks(self, dataRef): 

"""Retrieve the bright object masks. 

 

Returns None on failure. 

 

Parameters 

---------- 

dataRef : `lsst.daf.persistence.butlerSubset.ButlerDataRef` 

A Butler dataRef. 

 

Returns 

------- 

result : `lsst.daf.persistence.butlerSubset.ButlerDataRef` 

Bright object mask from the Butler object, or None if it cannot 

be retrieved. 

""" 

try: 

return dataRef.get("brightObjectMask", immediate=True) 

except Exception as e: 

self.log.warn("Unable to read brightObjectMask for %s: %s", dataRef.dataId, e) 

return None 

 

def setBrightObjectMasks(self, exposure, dataId, brightObjectMasks): 

"""Set the bright object masks. 

 

Parameters 

---------- 

exposure : `lsst.afw.image.Exposure` 

Exposure under consideration. 

dataId : `lsst.daf.persistence.dataId` 

Data identifier dict for patch. 

brightObjectMasks : `lsst.afw.table` 

Table of bright objects to mask. 

""" 

 

if brightObjectMasks is None: 

self.log.warn("Unable to apply bright object mask: none supplied") 

return 

self.log.info("Applying %d bright object masks to %s", len(brightObjectMasks), dataId) 

mask = exposure.getMaskedImage().getMask() 

wcs = exposure.getWcs() 

plateScale = wcs.getPixelScale().asArcseconds() 

 

for rec in brightObjectMasks: 

center = afwGeom.PointI(wcs.skyToPixel(rec.getCoord())) 

if rec["type"] == "box": 

assert rec["angle"] == 0.0, ("Angle != 0 for mask object %s" % rec["id"]) 

width = rec["width"].asArcseconds()/plateScale # convert to pixels 

height = rec["height"].asArcseconds()/plateScale # convert to pixels 

 

halfSize = afwGeom.ExtentI(0.5*width, 0.5*height) 

bbox = afwGeom.Box2I(center - halfSize, center + halfSize) 

 

bbox = afwGeom.BoxI(afwGeom.PointI(int(center[0] - 0.5*width), int(center[1] - 0.5*height)), 

afwGeom.PointI(int(center[0] + 0.5*width), int(center[1] + 0.5*height))) 

spans = afwGeom.SpanSet(bbox) 

elif rec["type"] == "circle": 

radius = int(rec["radius"].asArcseconds()/plateScale) # convert to pixels 

spans = afwGeom.SpanSet.fromShape(radius, offset=center) 

else: 

self.log.warn("Unexpected region type %s at %s" % rec["type"], center) 

continue 

spans.clippedTo(mask.getBBox()).setMask(mask, self.brightObjectBitmask) 

 

def setInexactPsf(self, mask): 

"""Set INEXACT_PSF mask plane. 

 

If any of the input images isn't represented in the coadd (due to 

clipped pixels or chip gaps), the `CoaddPsf` will be inexact. Flag 

these pixels. 

 

Parameters 

---------- 

mask : `lsst.afw.image.Mask` 

Coadded exposure's mask, modified in-place. 

""" 

mask.addMaskPlane("INEXACT_PSF") 

inexactPsf = mask.getPlaneBitMask("INEXACT_PSF") 

sensorEdge = mask.getPlaneBitMask("SENSOR_EDGE") # chip edges (so PSF is discontinuous) 

clipped = mask.getPlaneBitMask("CLIPPED") # pixels clipped from coadd 

rejected = mask.getPlaneBitMask("REJECTED") # pixels rejected from coadd due to masks 

array = mask.getArray() 

selected = array & (sensorEdge | clipped | rejected) > 0 

array[selected] |= inexactPsf 

 

@classmethod 

def _makeArgumentParser(cls): 

"""Create an argument parser. 

""" 

parser = pipeBase.ArgumentParser(name=cls._DefaultName) 

parser.add_id_argument("--id", cls.ConfigClass().coaddName + "Coadd_" + 

cls.ConfigClass().warpType + "Warp", 

help="data ID, e.g. --id tract=12345 patch=1,2", 

ContainerClass=AssembleCoaddDataIdContainer) 

parser.add_id_argument("--selectId", "calexp", help="data ID, e.g. --selectId visit=6789 ccd=0..9", 

ContainerClass=SelectDataIdContainer) 

return parser 

 

@staticmethod 

def _subBBoxIter(bbox, subregionSize): 

"""Iterate over subregions of a bbox. 

 

Parameters 

---------- 

bbox : `lsst.afw.geom.Box2I` 

Bounding box over which to iterate. 

subregionSize: `lsst.afw.geom.Extent2I` 

Size of sub-bboxes. 

 

Yields 

------ 

subBBox : `lsst.afw.geom.Box2I` 

Next sub-bounding box of size ``subregionSize`` or smaller; each ``subBBox`` 

is contained within ``bbox``, so it may be smaller than ``subregionSize`` at 

the edges of ``bbox``, but it will never be empty. 

""" 

if bbox.isEmpty(): 

raise RuntimeError("bbox %s is empty" % (bbox,)) 

if subregionSize[0] < 1 or subregionSize[1] < 1: 

raise RuntimeError("subregionSize %s must be nonzero" % (subregionSize,)) 

 

for rowShift in range(0, bbox.getHeight(), subregionSize[1]): 

for colShift in range(0, bbox.getWidth(), subregionSize[0]): 

subBBox = afwGeom.Box2I(bbox.getMin() + afwGeom.Extent2I(colShift, rowShift), subregionSize) 

subBBox.clip(bbox) 

if subBBox.isEmpty(): 

raise RuntimeError("Bug: empty bbox! bbox=%s, subregionSize=%s, " 

"colShift=%s, rowShift=%s" % 

(bbox, subregionSize, colShift, rowShift)) 

yield subBBox 

 

 

class AssembleCoaddDataIdContainer(pipeBase.DataIdContainer): 

"""A version of `lsst.pipe.base.DataIdContainer` specialized for assembleCoadd. 

""" 

 

def makeDataRefList(self, namespace): 

"""Make self.refList from self.idList. 

 

Parameters 

---------- 

namespace 

Results of parsing command-line (with ``butler`` and ``log`` elements). 

""" 

datasetType = namespace.config.coaddName + "Coadd" 

keysCoadd = namespace.butler.getKeys(datasetType=datasetType, level=self.level) 

 

for dataId in self.idList: 

# tract and patch are required 

for key in keysCoadd: 

if key not in dataId: 

raise RuntimeError("--id must include " + key) 

 

dataRef = namespace.butler.dataRef( 

datasetType=datasetType, 

dataId=dataId, 

) 

self.refList.append(dataRef) 

 

 

def countMaskFromFootprint(mask, footprint, bitmask, ignoreMask): 

"""Function to count the number of pixels with a specific mask in a 

footprint. 

 

Find the intersection of mask & footprint. Count all pixels in the mask 

that are in the intersection that have bitmask set but do not have 

ignoreMask set. Return the count. 

 

Parameters 

---------- 

mask : `lsst.afw.image.Mask` 

Mask to define intersection region by. 

footprint : `lsst.afw.detection.Footprint` 

Footprint to define the intersection region by. 

bitmask 

Specific mask that we wish to count the number of occurances of. 

ignoreMask 

Pixels to not consider. 

 

Returns 

------- 

result : `int` 

Count of number of pixels in footprint with specified mask. 

""" 

bbox = footprint.getBBox() 

bbox.clip(mask.getBBox(afwImage.PARENT)) 

fp = afwImage.Mask(bbox) 

subMask = mask.Factory(mask, bbox, afwImage.PARENT) 

footprint.spans.setMask(fp, bitmask) 

return numpy.logical_and((subMask.getArray() & fp.getArray()) > 0, 

(subMask.getArray() & ignoreMask) == 0).sum() 

 

 

class SafeClipAssembleCoaddConfig(AssembleCoaddConfig): 

"""Configuration parameters for the SafeClipAssembleCoaddTask. 

""" 

clipDetection = pexConfig.ConfigurableField( 

target=SourceDetectionTask, 

doc="Detect sources on difference between unclipped and clipped coadd") 

minClipFootOverlap = pexConfig.Field( 

doc="Minimum fractional overlap of clipped footprint with visit DETECTED to be clipped", 

dtype=float, 

default=0.6 

) 

minClipFootOverlapSingle = pexConfig.Field( 

doc="Minimum fractional overlap of clipped footprint with visit DETECTED to be " 

"clipped when only one visit overlaps", 

dtype=float, 

default=0.5 

) 

minClipFootOverlapDouble = pexConfig.Field( 

doc="Minimum fractional overlap of clipped footprints with visit DETECTED to be " 

"clipped when two visits overlap", 

dtype=float, 

default=0.45 

) 

maxClipFootOverlapDouble = pexConfig.Field( 

doc="Maximum fractional overlap of clipped footprints with visit DETECTED when " 

"considering two visits", 

dtype=float, 

default=0.15 

) 

minBigOverlap = pexConfig.Field( 

doc="Minimum number of pixels in footprint to use DETECTED mask from the single visits " 

"when labeling clipped footprints", 

dtype=int, 

default=100 

) 

 

def setDefaults(self): 

"""Set default values for clipDetection. 

 

Notes 

----- 

The numeric values for these configuration parameters were 

empirically determined, future work may further refine them. 

""" 

AssembleCoaddConfig.setDefaults(self) 

self.clipDetection.doTempLocalBackground = False 

self.clipDetection.reEstimateBackground = False 

self.clipDetection.returnOriginalFootprints = False 

self.clipDetection.thresholdPolarity = "both" 

self.clipDetection.thresholdValue = 2 

self.clipDetection.nSigmaToGrow = 2 

self.clipDetection.minPixels = 4 

self.clipDetection.isotropicGrow = True 

self.clipDetection.thresholdType = "pixel_stdev" 

self.sigmaClip = 1.5 

self.clipIter = 3 

self.statistic = "MEAN" 

 

def validate(self): 

if self.doSigmaClip: 

log.warn("Additional Sigma-clipping not allowed in Safe-clipped Coadds. " 

"Ignoring doSigmaClip.") 

self.doSigmaClip = False 

if self.statistic != "MEAN": 

raise ValueError("Only MEAN statistic allowed for final stacking in SafeClipAssembleCoadd " 

"(%s chosen). Please set statistic to MEAN." 

% (self.statistic)) 

AssembleCoaddTask.ConfigClass.validate(self) 

 

 

class SafeClipAssembleCoaddTask(AssembleCoaddTask): 

"""Assemble a coadded image from a set of coadded temporary exposures, 

being careful to clip & flag areas with potential artifacts. 

 

In ``AssembleCoaddTask``, we compute the coadd as an clipped mean (i.e., 

we clip outliers). The problem with doing this is that when computing the 

coadd PSF at a given location, individual visit PSFs from visits with 

outlier pixels contribute to the coadd PSF and cannot be treated correctly. 

In this task, we correct for this behavior by creating a new 

``badMaskPlane`` 'CLIPPED'. We populate this plane on the input 

coaddTempExps and the final coadd where 

 

i. difference imaging suggests that there is an outlier and 

ii. this outlier appears on only one or two images. 

 

Such regions will not contribute to the final coadd. Furthermore, any 

routine to determine the coadd PSF can now be cognizant of clipped regions. 

Note that the algorithm implemented by this task is preliminary and works 

correctly for HSC data. Parameter modifications and or considerable 

redesigning of the algorithm is likley required for other surveys. 

 

``SafeClipAssembleCoaddTask`` uses a ``SourceDetectionTask`` 

"clipDetection" subtask and also sub-classes ``AssembleCoaddTask``. 

You can retarget the ``SourceDetectionTask`` "clipDetection" subtask 

if you wish. 

 

Notes 

----- 

The `lsst.pipe.base.cmdLineTask.CmdLineTask` interface supports a 

flag ``-d`` to import ``debug.py`` from your ``PYTHONPATH``; 

see `baseDebug` for more about ``debug.py`` files. 

`SafeClipAssembleCoaddTask` has no debug variables of its own. 

The ``SourceDetectionTask`` "clipDetection" subtasks may support debug 

variables. See the documetation for `SourceDetectionTask` "clipDetection" 

for further information. 

 

Examples 

-------- 

`SafeClipAssembleCoaddTask` assembles a set of warped ``coaddTempExp`` 

images into a coadded image. The `SafeClipAssembleCoaddTask` is invoked by 

running assembleCoadd.py *without* the flag '--legacyCoadd'. 

 

Usage of ``assembleCoadd.py`` expects a data reference to the tract patch 

and filter to be coadded (specified using 

'--id = [KEY=VALUE1[^VALUE2[^VALUE3...] [KEY=VALUE1[^VALUE2[^VALUE3...] ...]]') 

along with a list of coaddTempExps to attempt to coadd (specified using 

'--selectId [KEY=VALUE1[^VALUE2[^VALUE3...] [KEY=VALUE1[^VALUE2[^VALUE3...] ...]]'). 

Only the coaddTempExps that cover the specified tract and patch will be 

coadded. A list of the available optional arguments can be obtained by 

calling assembleCoadd.py with the --help command line argument: 

 

.. code-block:: none 

 

assembleCoadd.py --help 

 

To demonstrate usage of the `SafeClipAssembleCoaddTask` in the larger 

context of multi-band processing, we will generate the HSC-I & -R band 

coadds from HSC engineering test data provided in the ci_hsc package. 

To begin, assuming that the lsst stack has been already set up, we must 

set up the obs_subaru and ci_hsc packages. This defines the environment 

variable $CI_HSC_DIR and points at the location of the package. The raw 

HSC data live in the ``$CI_HSC_DIR/raw`` directory. To begin assembling 

the coadds, we must first 

 

- ``processCcd`` 

process the individual ccds in $CI_HSC_RAW to produce calibrated exposures 

- ``makeSkyMap`` 

create a skymap that covers the area of the sky present in the raw exposures 

- ``makeCoaddTempExp`` 

warp the individual calibrated exposures to the tangent plane of the coadd</DD> 

 

We can perform all of these steps by running 

 

.. code-block:: none 

 

$CI_HSC_DIR scons warp-903986 warp-904014 warp-903990 warp-904010 warp-903988 

 

This will produce warped coaddTempExps for each visit. To coadd the 

warped data, we call ``assembleCoadd.py`` as follows: 

 

.. code-block:: none 

 

assembleCoadd.py $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-I \ 

--selectId visit=903986 ccd=16 --selectId visit=903986 ccd=22 --selectId visit=903986 ccd=23 \ 

--selectId visit=903986 ccd=100--selectId visit=904014 ccd=1 --selectId visit=904014 ccd=6 \ 

--selectId visit=904014 ccd=12 --selectId visit=903990 ccd=18 --selectId visit=903990 ccd=25 \ 

--selectId visit=904010 ccd=4 --selectId visit=904010 ccd=10 --selectId visit=904010 ccd=100 \ 

--selectId visit=903988 ccd=16 --selectId visit=903988 ccd=17 --selectId visit=903988 ccd=23 \ 

--selectId visit=903988 ccd=24 

 

This will process the HSC-I band data. The results are written in 

``$CI_HSC_DIR/DATA/deepCoadd-results/HSC-I``. 

 

You may also choose to run: 

 

.. code-block:: none 

 

scons warp-903334 warp-903336 warp-903338 warp-903342 warp-903344 warp-903346 nnn 

assembleCoadd.py $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-R --selectId visit=903334 ccd=16 \ 

--selectId visit=903334 ccd=22 --selectId visit=903334 ccd=23 --selectId visit=903334 ccd=100 \ 

--selectId visit=903336 ccd=17 --selectId visit=903336 ccd=24 --selectId visit=903338 ccd=18 \ 

--selectId visit=903338 ccd=25 --selectId visit=903342 ccd=4 --selectId visit=903342 ccd=10 \ 

--selectId visit=903342 ccd=100 --selectId visit=903344 ccd=0 --selectId visit=903344 ccd=5 \ 

--selectId visit=903344 ccd=11 --selectId visit=903346 ccd=1 --selectId visit=903346 ccd=6 \ 

--selectId visit=903346 ccd=12 

 

to generate the coadd for the HSC-R band if you are interested in following 

multiBand Coadd processing as discussed in ``pipeTasks_multiBand``. 

""" 

ConfigClass = SafeClipAssembleCoaddConfig 

_DefaultName = "safeClipAssembleCoadd" 

 

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

AssembleCoaddTask.__init__(self, *args, **kwargs) 

schema = afwTable.SourceTable.makeMinimalSchema() 

self.makeSubtask("clipDetection", schema=schema) 

 

def run(self, skyInfo, tempExpRefList, imageScalerList, weightList, *args, **kwargs): 

"""Assemble the coadd for a region. 

 

Compute the difference of coadds created with and without outlier 

rejection to identify coadd pixels that have outlier values in some 

individual visits. 

Detect clipped regions on the difference image and mark these regions 

on the one or two individual coaddTempExps where they occur if there 

is significant overlap between the clipped region and a source. This 

leaves us with a set of footprints from the difference image that have 

been identified as having occured on just one or two individual visits. 

However, these footprints were generated from a difference image. It 

is conceivable for a large diffuse source to have become broken up 

into multiple footprints acrosss the coadd difference in this process. 

Determine the clipped region from all overlapping footprints from the 

detected sources in each visit - these are big footprints. 

Combine the small and big clipped footprints and mark them on a new 

bad mask plane. 

Generate the coadd using `AssembleCoaddTask.run` without outlier 

removal. Clipped footprints will no longer make it into the coadd 

because they are marked in the new bad mask plane. 

 

Parameters 

---------- 

skyInfo : `lsst.pipe.base.Struct` 

Patch geometry information, from getSkyInfo 

tempExpRefList : `list` 

List of data reference to tempExp 

imageScalerList : `list` 

List of image scalers 

weightList : `list` 

List of weights 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Result struct with components: 

 

- ``coaddExposure``: coadded exposure (``lsst.afw.image.Exposure``). 

- ``nImage``: exposure count image (``lsst.afw.image.Image``). 

 

Notes 

----- 

args and kwargs are passed but ignored in order to match the call 

signature expected by the parent task. 

""" 

exp = self.buildDifferenceImage(skyInfo, tempExpRefList, imageScalerList, weightList) 

mask = exp.getMaskedImage().getMask() 

mask.addMaskPlane("CLIPPED") 

 

result = self.detectClip(exp, tempExpRefList) 

 

self.log.info('Found %d clipped objects', len(result.clipFootprints)) 

 

maskClipValue = mask.getPlaneBitMask("CLIPPED") 

maskDetValue = mask.getPlaneBitMask("DETECTED") | mask.getPlaneBitMask("DETECTED_NEGATIVE") 

# Append big footprints from individual Warps to result.clipSpans 

bigFootprints = self.detectClipBig(result.clipSpans, result.clipFootprints, result.clipIndices, 

result.detectionFootprints, maskClipValue, maskDetValue, 

exp.getBBox()) 

# Create mask of the current clipped footprints 

maskClip = mask.Factory(mask.getBBox(afwImage.PARENT)) 

afwDet.setMaskFromFootprintList(maskClip, result.clipFootprints, maskClipValue) 

 

maskClipBig = maskClip.Factory(mask.getBBox(afwImage.PARENT)) 

afwDet.setMaskFromFootprintList(maskClipBig, bigFootprints, maskClipValue) 

maskClip |= maskClipBig 

 

# Assemble coadd from base class, but ignoring CLIPPED pixels 

badMaskPlanes = self.config.badMaskPlanes[:] 

badMaskPlanes.append("CLIPPED") 

badPixelMask = afwImage.Mask.getPlaneBitMask(badMaskPlanes) 

return AssembleCoaddTask.run(self, skyInfo, tempExpRefList, imageScalerList, weightList, 

result.clipSpans, mask=badPixelMask) 

 

def buildDifferenceImage(self, skyInfo, tempExpRefList, imageScalerList, weightList): 

"""Return an exposure that contains the difference between unclipped 

and clipped coadds. 

 

Generate a difference image between clipped and unclipped coadds. 

Compute the difference image by subtracting an outlier-clipped coadd 

from an outlier-unclipped coadd. Return the difference image. 

 

Parameters 

---------- 

skyInfo : `lsst.pipe.base.Struct` 

Patch geometry information, from getSkyInfo 

tempExpRefList : `list` 

List of data reference to tempExp 

imageScalerList : `list` 

List of image scalers 

weightList : `list` 

List of weights 

 

Returns 

------- 

exp : `lsst.afw.image.Exposure` 

Difference image of unclipped and clipped coadd wrapped in an Exposure 

""" 

# Clone and upcast self.config because current self.config is frozen 

config = AssembleCoaddConfig() 

# getattr necessary because subtasks do not survive Config.toDict() 

configIntersection = {k: getattr(self.config, k) 

for k, v in self.config.toDict().items() if (k in config.keys())} 

config.update(**configIntersection) 

 

# statistic MEAN copied from self.config.statistic, but for clarity explicitly assign 

config.statistic = 'MEAN' 

task = AssembleCoaddTask(config=config) 

coaddMean = task.run(skyInfo, tempExpRefList, imageScalerList, weightList).coaddExposure 

 

config.statistic = 'MEANCLIP' 

task = AssembleCoaddTask(config=config) 

coaddClip = task.run(skyInfo, tempExpRefList, imageScalerList, weightList).coaddExposure 

 

coaddDiff = coaddMean.getMaskedImage().Factory(coaddMean.getMaskedImage()) 

coaddDiff -= coaddClip.getMaskedImage() 

exp = afwImage.ExposureF(coaddDiff) 

exp.setPsf(coaddMean.getPsf()) 

return exp 

 

def detectClip(self, exp, tempExpRefList): 

"""Detect clipped regions on an exposure and set the mask on the 

individual tempExp masks. 

 

Detect footprints in the difference image after smoothing the 

difference image with a Gaussian kernal. Identify footprints that 

overlap with one or two input ``coaddTempExps`` by comparing the 

computed overlap fraction to thresholds set in the config. A different 

threshold is applied depending on the number of overlapping visits 

(restricted to one or two). If the overlap exceeds the thresholds, 

the footprint is considered "CLIPPED" and is marked as such on the 

coaddTempExp. Return a struct with the clipped footprints, the indices 

of the ``coaddTempExps`` that end up overlapping with the clipped 

footprints, and a list of new masks for the ``coaddTempExps``. 

 

Parameters 

---------- 

exp : `lsst.afw.image.Exposure` 

Exposure to run detection on. 

tempExpRefList : `list` 

List of data reference to tempExp. 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Result struct with components: 

 

- ``clipFootprints``: list of clipped footprints. 

- ``clipIndices``: indices for each ``clippedFootprint`` in 

``tempExpRefList``. 

- ``clipSpans``: List of dictionaries containing spanSet lists 

to clip. Each element contains the new maskplane name 

("CLIPPED") as the key and list of ``SpanSets`` as the value. 

- ``detectionFootprints``: List of DETECTED/DETECTED_NEGATIVE plane 

compressed into footprints. 

""" 

mask = exp.getMaskedImage().getMask() 

maskDetValue = mask.getPlaneBitMask("DETECTED") | mask.getPlaneBitMask("DETECTED_NEGATIVE") 

fpSet = self.clipDetection.detectFootprints(exp, doSmooth=True, clearMask=True) 

# Merge positive and negative together footprints together 

fpSet.positive.merge(fpSet.negative) 

footprints = fpSet.positive 

self.log.info('Found %d potential clipped objects', len(footprints.getFootprints())) 

ignoreMask = self.getBadPixelMask() 

 

clipFootprints = [] 

clipIndices = [] 

artifactSpanSets = [{'CLIPPED': list()} for _ in tempExpRefList] 

 

# for use by detectClipBig 

visitDetectionFootprints = [] 

 

dims = [len(tempExpRefList), len(footprints.getFootprints())] 

overlapDetArr = numpy.zeros(dims, dtype=numpy.uint16) 

ignoreArr = numpy.zeros(dims, dtype=numpy.uint16) 

 

# Loop over masks once and extract/store only relevant overlap metrics and detection footprints 

for i, warpRef in enumerate(tempExpRefList): 

tmpExpMask = warpRef.get(self.getTempExpDatasetName(self.warpType), 

immediate=True).getMaskedImage().getMask() 

maskVisitDet = tmpExpMask.Factory(tmpExpMask, tmpExpMask.getBBox(afwImage.PARENT), 

afwImage.PARENT, True) 

maskVisitDet &= maskDetValue 

visitFootprints = afwDet.FootprintSet(maskVisitDet, afwDet.Threshold(1)) 

visitDetectionFootprints.append(visitFootprints) 

 

for j, footprint in enumerate(footprints.getFootprints()): 

ignoreArr[i, j] = countMaskFromFootprint(tmpExpMask, footprint, ignoreMask, 0x0) 

overlapDetArr[i, j] = countMaskFromFootprint(tmpExpMask, footprint, maskDetValue, ignoreMask) 

 

# build a list of clipped spans for each visit 

for j, footprint in enumerate(footprints.getFootprints()): 

nPixel = footprint.getArea() 

overlap = [] # hold the overlap with each visit 

indexList = [] # index of visit in global list 

for i in range(len(tempExpRefList)): 

ignore = ignoreArr[i, j] 

overlapDet = overlapDetArr[i, j] 

totPixel = nPixel - ignore 

 

# If we have more bad pixels than detection skip 

if ignore > overlapDet or totPixel <= 0.5*nPixel or overlapDet == 0: 

continue 

overlap.append(overlapDet/float(totPixel)) 

indexList.append(i) 

 

overlap = numpy.array(overlap) 

if not len(overlap): 

continue 

 

keep = False # Should this footprint be marked as clipped? 

keepIndex = [] # Which tempExps does the clipped footprint belong to 

 

# If footprint only has one overlap use a lower threshold 

if len(overlap) == 1: 

if overlap[0] > self.config.minClipFootOverlapSingle: 

keep = True 

keepIndex = [0] 

else: 

# This is the general case where only visit should be clipped 

clipIndex = numpy.where(overlap > self.config.minClipFootOverlap)[0] 

if len(clipIndex) == 1: 

keep = True 

keepIndex = [clipIndex[0]] 

 

# Test if there are clipped objects that overlap two different visits 

clipIndex = numpy.where(overlap > self.config.minClipFootOverlapDouble)[0] 

if len(clipIndex) == 2 and len(overlap) > 3: 

clipIndexComp = numpy.where(overlap <= self.config.minClipFootOverlapDouble)[0] 

if numpy.max(overlap[clipIndexComp]) <= self.config.maxClipFootOverlapDouble: 

keep = True 

keepIndex = clipIndex 

 

if not keep: 

continue 

 

for index in keepIndex: 

globalIndex = indexList[index] 

artifactSpanSets[globalIndex]['CLIPPED'].append(footprint.spans) 

 

clipIndices.append(numpy.array(indexList)[keepIndex]) 

clipFootprints.append(footprint) 

 

return pipeBase.Struct(clipFootprints=clipFootprints, clipIndices=clipIndices, 

clipSpans=artifactSpanSets, detectionFootprints=visitDetectionFootprints) 

 

def detectClipBig(self, clipList, clipFootprints, clipIndices, detectionFootprints, 

maskClipValue, maskDetValue, coaddBBox): 

"""Return individual warp footprints for large artifacts and append 

them to ``clipList`` in place. 

 

Identify big footprints composed of many sources in the coadd 

difference that may have originated in a large diffuse source in the 

coadd. We do this by indentifying all clipped footprints that overlap 

significantly with each source in all the coaddTempExps. 

 

Parameters 

---------- 

clipList : `list` 

List of alt mask SpanSets with clipping information. Modified. 

clipFootprints : `list` 

List of clipped footprints. 

clipIndices : `list` 

List of which entries in tempExpClipList each footprint belongs to. 

maskClipValue 

Mask value of clipped pixels. 

maskDetValue 

Mask value of detected pixels. 

coaddBBox : `lsst.afw.geom.Box` 

BBox of the coadd and warps. 

 

Returns 

------- 

bigFootprintsCoadd : `list` 

List of big footprints 

""" 

bigFootprintsCoadd = [] 

ignoreMask = self.getBadPixelMask() 

for index, (clippedSpans, visitFootprints) in enumerate(zip(clipList, detectionFootprints)): 

maskVisitDet = afwImage.MaskX(coaddBBox, 0x0) 

for footprint in visitFootprints.getFootprints(): 

footprint.spans.setMask(maskVisitDet, maskDetValue) 

 

# build a mask of clipped footprints that are in this visit 

clippedFootprintsVisit = [] 

for foot, clipIndex in zip(clipFootprints, clipIndices): 

if index not in clipIndex: 

continue 

clippedFootprintsVisit.append(foot) 

maskVisitClip = maskVisitDet.Factory(maskVisitDet.getBBox(afwImage.PARENT)) 

afwDet.setMaskFromFootprintList(maskVisitClip, clippedFootprintsVisit, maskClipValue) 

 

bigFootprintsVisit = [] 

for foot in visitFootprints.getFootprints(): 

if foot.getArea() < self.config.minBigOverlap: 

continue 

nCount = countMaskFromFootprint(maskVisitClip, foot, maskClipValue, ignoreMask) 

if nCount > self.config.minBigOverlap: 

bigFootprintsVisit.append(foot) 

bigFootprintsCoadd.append(foot) 

 

for footprint in bigFootprintsVisit: 

clippedSpans["CLIPPED"].append(footprint.spans) 

 

return bigFootprintsCoadd 

 

 

class CompareWarpAssembleCoaddConfig(AssembleCoaddConfig): 

assembleStaticSkyModel = pexConfig.ConfigurableField( 

target=AssembleCoaddTask, 

doc="Task to assemble an artifact-free, PSF-matched Coadd to serve as a" 

" naive/first-iteration model of the static sky.", 

) 

detect = pexConfig.ConfigurableField( 

target=SourceDetectionTask, 

doc="Detect outlier sources on difference between each psfMatched warp and static sky model" 

) 

detectTemplate = pexConfig.ConfigurableField( 

target=SourceDetectionTask, 

doc="Detect sources on static sky model. Only used if doPreserveContainedBySource is True" 

) 

maxNumEpochs = pexConfig.Field( 

doc="Charactistic maximum local number of epochs/visits in which an artifact candidate can appear " 

"and still be masked. The effective maxNumEpochs is a broken linear function of local " 

"number of epochs (N): min(maxFractionEpochsLow*N, maxNumEpochs + maxFractionEpochsHigh*N). " 

"For each footprint detected on the image difference between the psfMatched warp and static sky " 

"model, if a significant fraction of pixels (defined by spatialThreshold) are residuals in more " 

"than the computed effective maxNumEpochs, the artifact candidate is deemed persistant rather " 

"than transient and not masked.", 

dtype=int, 

default=2 

) 

maxFractionEpochsLow = pexConfig.RangeField( 

doc="Fraction of local number of epochs (N) to use as effective maxNumEpochs for low N. " 

"Effective maxNumEpochs = " 

"min(maxFractionEpochsLow * N, maxNumEpochs + maxFractionEpochsHigh * N)", 

dtype=float, 

default=0.4, 

min=0., max=1., 

) 

maxFractionEpochsHigh = pexConfig.RangeField( 

doc="Fraction of local number of epochs (N) to use as effective maxNumEpochs for high N. " 

"Effective maxNumEpochs = " 

"min(maxFractionEpochsLow * N, maxNumEpochs + maxFractionEpochsHigh * N)", 

dtype=float, 

default=0.03, 

min=0., max=1., 

) 

spatialThreshold = pexConfig.RangeField( 

doc="Unitless fraction of pixels defining how much of the outlier region has to meet the " 

"temporal criteria. If 0, clip all. If 1, clip none.", 

dtype=float, 

default=0.5, 

min=0., max=1., 

inclusiveMin=True, inclusiveMax=True 

) 

doScaleWarpVariance = pexConfig.Field( 

doc="Rescale Warp variance plane using empirical noise?", 

dtype=bool, 

default=True, 

) 

scaleWarpVariance = pexConfig.ConfigurableField( 

target=ScaleVarianceTask, 

doc="Rescale variance on warps", 

) 

doPreserveContainedBySource = pexConfig.Field( 

doc="Rescue artifacts from clipping that completely lie within a footprint detected" 

"on the PsfMatched Template Coadd. Replicates a behavior of SafeClip.", 

dtype=bool, 

default=True, 

) 

doPrefilterArtifacts = pexConfig.Field( 

doc="Ignore artifact candidates that are mostly covered by the bad pixel mask, " 

"because they will be excluded anyway. This prevents them from contributing " 

"to the outlier epoch count image and potentially being labeled as persistant." 

"'Mostly' is defined by the config 'prefilterArtifactsRatio'.", 

dtype=bool, 

default=True 

) 

prefilterArtifactsMaskPlanes = pexConfig.ListField( 

doc="Prefilter artifact candidates that are mostly covered by these bad mask planes.", 

dtype=str, 

default=('NO_DATA', 'BAD', 'SAT', 'SUSPECT'), 

) 

prefilterArtifactsRatio = pexConfig.Field( 

doc="Prefilter artifact candidates with less than this fraction overlapping good pixels", 

dtype=float, 

default=0.05 

) 

psfMatchedWarps = pipeBase.InputDatasetField( 

doc=("PSF-Matched Warps are required by CompareWarp regardless of the coadd type requested. " 

"Only PSF-Matched Warps make sense for image subtraction. " 

"Therefore, they must be in the InputDatasetField and made available to the task."), 

nameTemplate="{inputCoaddName}Coadd_psfMatchedWarp", 

storageClass="ExposureF", 

dimensions=("tract", "patch", "skymap", "visit"), 

manualLoad=True 

) 

 

def setDefaults(self): 

AssembleCoaddConfig.setDefaults(self) 

self.statistic = 'MEAN' 

self.doUsePsfMatchedPolygons = True 

 

# Real EDGE removed by psfMatched NO_DATA border half the width of the matching kernel 

# CompareWarp applies psfMatched EDGE pixels to directWarps before assembling 

if "EDGE" in self.badMaskPlanes: 

self.badMaskPlanes.remove('EDGE') 

self.removeMaskPlanes.append('EDGE') 

self.assembleStaticSkyModel.badMaskPlanes = ["NO_DATA", ] 

self.assembleStaticSkyModel.warpType = 'psfMatched' 

self.assembleStaticSkyModel.statistic = 'MEANCLIP' 

self.assembleStaticSkyModel.sigmaClip = 2.5 

self.assembleStaticSkyModel.clipIter = 3 

self.assembleStaticSkyModel.calcErrorFromInputVariance = False 

self.assembleStaticSkyModel.doWrite = False 

self.detect.doTempLocalBackground = False 

self.detect.reEstimateBackground = False 

self.detect.returnOriginalFootprints = False 

self.detect.thresholdPolarity = "both" 

self.detect.thresholdValue = 5 

self.detect.nSigmaToGrow = 2 

self.detect.minPixels = 4 

self.detect.isotropicGrow = True 

self.detect.thresholdType = "pixel_stdev" 

self.detectTemplate.nSigmaToGrow = 2.0 

self.detectTemplate.doTempLocalBackground = False 

self.detectTemplate.reEstimateBackground = False 

self.detectTemplate.returnOriginalFootprints = False 

 

 

class CompareWarpAssembleCoaddTask(AssembleCoaddTask): 

"""Assemble a compareWarp coadded image from a set of warps 

by masking artifacts detected by comparing PSF-matched warps. 

 

In ``AssembleCoaddTask``, we compute the coadd as an clipped mean (i.e., 

we clip outliers). The problem with doing this is that when computing the 

coadd PSF at a given location, individual visit PSFs from visits with 

outlier pixels contribute to the coadd PSF and cannot be treated correctly. 

In this task, we correct for this behavior by creating a new badMaskPlane 

'CLIPPED' which marks pixels in the individual warps suspected to contain 

an artifact. We populate this plane on the input warps by comparing 

PSF-matched warps with a PSF-matched median coadd which serves as a 

model of the static sky. Any group of pixels that deviates from the 

PSF-matched template coadd by more than config.detect.threshold sigma, 

is an artifact candidate. The candidates are then filtered to remove 

variable sources and sources that are difficult to subtract such as 

bright stars. This filter is configured using the config parameters 

``temporalThreshold`` and ``spatialThreshold``. The temporalThreshold is 

the maximum fraction of epochs that the deviation can appear in and still 

be considered an artifact. The spatialThreshold is the maximum fraction of 

pixels in the footprint of the deviation that appear in other epochs 

(where other epochs is defined by the temporalThreshold). If the deviant 

region meets this criteria of having a significant percentage of pixels 

that deviate in only a few epochs, these pixels have the 'CLIPPED' bit 

set in the mask. These regions will not contribute to the final coadd. 

Furthermore, any routine to determine the coadd PSF can now be cognizant 

of clipped regions. Note that the algorithm implemented by this task is 

preliminary and works correctly for HSC data. Parameter modifications and 

or considerable redesigning of the algorithm is likley required for other 

surveys. 

 

``CompareWarpAssembleCoaddTask`` sub-classes 

``AssembleCoaddTask`` and instantiates ``AssembleCoaddTask`` 

as a subtask to generate the TemplateCoadd (the model of the static sky). 

 

Notes 

----- 

The `lsst.pipe.base.cmdLineTask.CmdLineTask` interface supports a 

flag ``-d`` to import ``debug.py`` from your ``PYTHONPATH``; see 

``baseDebug`` for more about ``debug.py`` files. 

 

This task supports the following debug variables: 

 

- ``saveCountIm`` 

If True then save the Epoch Count Image as a fits file in the `figPath` 

- ``figPath`` 

Path to save the debug fits images and figures 

 

For example, put something like: 

 

.. code-block:: python 

 

import lsstDebug 

def DebugInfo(name): 

di = lsstDebug.getInfo(name) 

if name == "lsst.pipe.tasks.assembleCoadd": 

di.saveCountIm = True 

di.figPath = "/desired/path/to/debugging/output/images" 

return di 

lsstDebug.Info = DebugInfo 

 

into your ``debug.py`` file and run ``assemebleCoadd.py`` with the 

``--debug`` flag. Some subtasks may have their own debug variables; 

see individual Task documentation. 

 

Examples 

-------- 

``CompareWarpAssembleCoaddTask`` assembles a set of warped images into a 

coadded image. The ``CompareWarpAssembleCoaddTask`` is invoked by running 

``assembleCoadd.py`` with the flag ``--compareWarpCoadd``. 

Usage of ``assembleCoadd.py`` expects a data reference to the tract patch 

and filter to be coadded (specified using 

'--id = [KEY=VALUE1[^VALUE2[^VALUE3...] [KEY=VALUE1[^VALUE2[^VALUE3...] ...]]') 

along with a list of coaddTempExps to attempt to coadd (specified using 

'--selectId [KEY=VALUE1[^VALUE2[^VALUE3...] [KEY=VALUE1[^VALUE2[^VALUE3...] ...]]'). 

Only the warps that cover the specified tract and patch will be coadded. 

A list of the available optional arguments can be obtained by calling 

``assembleCoadd.py`` with the ``--help`` command line argument: 

 

.. code-block:: none 

 

assembleCoadd.py --help 

 

To demonstrate usage of the ``CompareWarpAssembleCoaddTask`` in the larger 

context of multi-band processing, we will generate the HSC-I & -R band 

oadds from HSC engineering test data provided in the ``ci_hsc`` package. 

To begin, assuming that the lsst stack has been already set up, we must 

set up the ``obs_subaru`` and ``ci_hsc`` packages. 

This defines the environment variable ``$CI_HSC_DIR`` and points at the 

location of the package. The raw HSC data live in the ``$CI_HSC_DIR/raw`` 

directory. To begin assembling the coadds, we must first 

 

- processCcd 

process the individual ccds in $CI_HSC_RAW to produce calibrated exposures 

- makeSkyMap 

create a skymap that covers the area of the sky present in the raw exposures 

- makeCoaddTempExp 

warp the individual calibrated exposures to the tangent plane of the coadd 

 

We can perform all of these steps by running 

 

.. code-block:: none 

 

$CI_HSC_DIR scons warp-903986 warp-904014 warp-903990 warp-904010 warp-903988 

 

This will produce warped ``coaddTempExps`` for each visit. To coadd the 

warped data, we call ``assembleCoadd.py`` as follows: 

 

.. code-block:: none 

 

assembleCoadd.py --compareWarpCoadd $CI_HSC_DIR/DATA --id patch=5,4 tract=0 filter=HSC-I \ 

--selectId visit=903986 ccd=16 --selectId visit=903986 ccd=22 --selectId visit=903986 ccd=23 \ 

--selectId visit=903986 ccd=100 --selectId visit=904014 ccd=1 --selectId visit=904014 ccd=6 \ 

--selectId visit=904014 ccd=12 --selectId visit=903990 ccd=18 --selectId visit=903990 ccd=25 \ 

--selectId visit=904010 ccd=4 --selectId visit=904010 ccd=10 --selectId visit=904010 ccd=100 \ 

--selectId visit=903988 ccd=16 --selectId visit=903988 ccd=17 --selectId visit=903988 ccd=23 \ 

--selectId visit=903988 ccd=24 

 

This will process the HSC-I band data. The results are written in 

``$CI_HSC_DIR/DATA/deepCoadd-results/HSC-I``. 

""" 

ConfigClass = CompareWarpAssembleCoaddConfig 

_DefaultName = "compareWarpAssembleCoadd" 

 

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

AssembleCoaddTask.__init__(self, *args, **kwargs) 

self.makeSubtask("assembleStaticSkyModel") 

detectionSchema = afwTable.SourceTable.makeMinimalSchema() 

self.makeSubtask("detect", schema=detectionSchema) 

if self.config.doPreserveContainedBySource: 

self.makeSubtask("detectTemplate", schema=afwTable.SourceTable.makeMinimalSchema()) 

if self.config.doScaleWarpVariance: 

self.makeSubtask("scaleWarpVariance") 

 

def makeSupplementaryDataGen3(self, inputData, inputDataIds, outputDataIds, butler): 

"""Make inputs specific to Subclass with Gen 3 API 

 

Calls Gen3 `adaptArgsAndRun` instead of the Gen2 specific `runDataRef` 

 

Duplicates interface of`adaptArgsAndRun` method. 

Available to be implemented by subclasses only if they need the 

coadd dataRef for performing preliminary processing before 

assembling the coadd. 

 

Parameters 

---------- 

inputData : `dict` 

Keys are the names of the configs describing input dataset types. 

Values are input Python-domain data objects (or lists of objects) 

retrieved from data butler. 

inputDataIds : `dict` 

Keys are the names of the configs describing input dataset types. 

Values are DataIds (or lists of DataIds) that task consumes for 

corresponding dataset type. 

DataIds are guaranteed to match data objects in ``inputData``. 

outputDataIds : `dict` 

Keys are the names of the configs describing input dataset types. 

Values are DataIds (or lists of DataIds) that task is to produce 

for corresponding dataset type. 

butler : `lsst.daf.butler.Butler` 

Gen3 Butler object for fetching additional data products before 

running the Task 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Result struct with components: 

 

- ``templateCoadd`` : coadded exposure (``lsst.afw.image.Exposure``) 

- ``nImage``: N Image (``lsst.afw.image.Image``) 

 

 

""" 

templateCoadd = self.assembleStaticSkyModel.adaptArgsAndRun(inputData, inputDataIds, 

outputDataIds, butler) 

if templateCoadd is None: 

raise RuntimeError(self._noTemplateMessage(self.assembleStaticSkyModel.warpType)) 

 

return pipeBase.Struct(templateCoadd=templateCoadd.coaddExposure, 

nImage=templateCoadd.nImage) 

 

def makeSupplementaryData(self, dataRef, selectDataList=None, warpRefList=None): 

"""Make inputs specific to Subclass. 

 

Generate a templateCoadd to use as a native model of static sky to 

subtract from warps. 

 

Parameters 

---------- 

dataRef : `lsst.daf.persistence.butlerSubset.ButlerDataRef` 

Butler dataRef for supplementary data. 

selectDataList : `list` (optional) 

Optional List of data references to Calexps. 

warpRefList : `list` (optional) 

Optional List of data references to Warps. 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Result struct with components: 

 

- ``templateCoadd``: coadded exposure (``lsst.afw.image.Exposure``) 

- ``nImage``: N Image (``lsst.afw.image.Image``) 

""" 

templateCoadd = self.assembleStaticSkyModel.runDataRef(dataRef, selectDataList, warpRefList) 

if templateCoadd is None: 

raise RuntimeError(self._noTemplateMessage(self.assembleStaticSkyModel.warpType)) 

 

return pipeBase.Struct(templateCoadd=templateCoadd.coaddExposure, 

nImage=templateCoadd.nImage) 

 

def _noTemplateMessage(self, warpType): 

warpName = (warpType[0].upper() + warpType[1:]) 

message = """No %(warpName)s warps were found to build the template coadd which is 

required to run CompareWarpAssembleCoaddTask. To continue assembling this type of coadd, 

first either rerun makeCoaddTempExp with config.make%(warpName)s=True or 

coaddDriver with config.makeCoadTempExp.make%(warpName)s=True, before assembleCoadd. 

 

Alternatively, to use another algorithm with existing warps, retarget the CoaddDriverConfig to 

another algorithm like: 

 

from lsst.pipe.tasks.assembleCoadd import SafeClipAssembleCoaddTask 

config.assemble.retarget(SafeClipAssembleCoaddTask) 

""" % {"warpName": warpName} 

return message 

 

def run(self, skyInfo, tempExpRefList, imageScalerList, weightList, 

supplementaryData, *args, **kwargs): 

"""Assemble the coadd. 

 

Find artifacts and apply them to the warps' masks creating a list of 

alternative masks with a new "CLIPPED" plane and updated "NO_DATA" 

plane. Then pass these alternative masks to the base class's `run` 

method. 

 

Parameters 

---------- 

skyInfo : `lsst.pipe.base.Struct` 

Patch geometry information. 

tempExpRefList : `list` 

List of data references to warps. 

imageScalerList : `list` 

List of image scalers. 

weightList : `list` 

List of weights. 

supplementaryData : `lsst.pipe.base.Struct` 

This Struct must contain a ``templateCoadd`` that serves as the 

model of the static sky. 

 

Returns 

------- 

result : `lsst.pipe.base.Struct` 

Result struct with components: 

 

- ``coaddExposure``: coadded exposure (``lsst.afw.image.Exposure``). 

- ``nImage``: exposure count image (``lsst.afw.image.Image``), if requested. 

""" 

templateCoadd = supplementaryData.templateCoadd 

spanSetMaskList = self.findArtifacts(templateCoadd, tempExpRefList, imageScalerList) 

badMaskPlanes = self.config.badMaskPlanes[:] 

badMaskPlanes.append("CLIPPED") 

badPixelMask = afwImage.Mask.getPlaneBitMask(badMaskPlanes) 

 

result = AssembleCoaddTask.run(self, skyInfo, tempExpRefList, imageScalerList, weightList, 

spanSetMaskList, mask=badPixelMask) 

 

# Propagate PSF-matched EDGE pixels to coadd SENSOR_EDGE and INEXACT_PSF 

# Psf-Matching moves the real edge inwards 

self.applyAltEdgeMask(result.coaddExposure.maskedImage.mask, spanSetMaskList) 

return result 

 

def applyAltEdgeMask(self, mask, altMaskList): 

"""Propagate alt EDGE mask to SENSOR_EDGE AND INEXACT_PSF planes. 

 

Parameters 

---------- 

mask : `lsst.afw.image.Mask` 

Original mask. 

altMaskList : `list` 

List of Dicts containing ``spanSet`` lists. 

Each element contains the new mask plane name (e.g. "CLIPPED 

and/or "NO_DATA") as the key, and list of ``SpanSets`` to apply to 

the mask. 

""" 

maskValue = mask.getPlaneBitMask(["SENSOR_EDGE", "INEXACT_PSF"]) 

for visitMask in altMaskList: 

if "EDGE" in visitMask: 

for spanSet in visitMask['EDGE']: 

spanSet.clippedTo(mask.getBBox()).setMask(mask, maskValue) 

 

def findArtifacts(self, templateCoadd, tempExpRefList, imageScalerList): 

"""Find artifacts. 

 

Loop through warps twice. The first loop builds a map with the count 

of how many epochs each pixel deviates from the templateCoadd by more 

than ``config.chiThreshold`` sigma. The second loop takes each 

difference image and filters the artifacts detected in each using 

count map to filter out variable sources and sources that are 

difficult to subtract cleanly. 

 

Parameters 

---------- 

templateCoadd : `lsst.afw.image.Exposure` 

Exposure to serve as model of static sky. 

tempExpRefList : `list` 

List of data references to warps. 

imageScalerList : `list` 

List of image scalers. 

 

Returns 

------- 

altMasks : `list` 

List of dicts containing information about CLIPPED 

(i.e., artifacts), NO_DATA, and EDGE pixels. 

""" 

 

self.log.debug("Generating Count Image, and mask lists.") 

coaddBBox = templateCoadd.getBBox() 

slateIm = afwImage.ImageU(coaddBBox) 

epochCountImage = afwImage.ImageU(coaddBBox) 

nImage = afwImage.ImageU(coaddBBox) 

spanSetArtifactList = [] 

spanSetNoDataMaskList = [] 

spanSetEdgeList = [] 

badPixelMask = self.getBadPixelMask() 

 

# mask of the warp diffs should = that of only the warp 

templateCoadd.mask.clearAllMaskPlanes() 

 

if self.config.doPreserveContainedBySource: 

templateFootprints = self.detectTemplate.detectFootprints(templateCoadd) 

else: 

templateFootprints = None 

 

for warpRef, imageScaler in zip(tempExpRefList, imageScalerList): 

warpDiffExp = self._readAndComputeWarpDiff(warpRef, imageScaler, templateCoadd) 

if warpDiffExp is not None: 

# This nImage only approximates the final nImage because it uses the PSF-matched mask 

nImage.array += (numpy.isfinite(warpDiffExp.image.array) * 

((warpDiffExp.mask.array & badPixelMask) == 0)).astype(numpy.uint16) 

fpSet = self.detect.detectFootprints(warpDiffExp, doSmooth=False, clearMask=True) 

fpSet.positive.merge(fpSet.negative) 

footprints = fpSet.positive 

slateIm.set(0) 

spanSetList = [footprint.spans for footprint in footprints.getFootprints()] 

 

# Remove artifacts due to defects before they contribute to the epochCountImage 

if self.config.doPrefilterArtifacts: 

spanSetList = self.prefilterArtifacts(spanSetList, warpDiffExp) 

for spans in spanSetList: 

spans.setImage(slateIm, 1, doClip=True) 

epochCountImage += slateIm 

 

# PSF-Matched warps have less available area (~the matching kernel) because the calexps 

# undergo a second convolution. Pixels with data in the direct warp 

# but not in the PSF-matched warp will not have their artifacts detected. 

# NaNs from the PSF-matched warp therefore must be masked in the direct warp 

nans = numpy.where(numpy.isnan(warpDiffExp.maskedImage.image.array), 1, 0) 

nansMask = afwImage.makeMaskFromArray(nans.astype(afwImage.MaskPixel)) 

nansMask.setXY0(warpDiffExp.getXY0()) 

edgeMask = warpDiffExp.mask 

spanSetEdgeMask = afwGeom.SpanSet.fromMask(edgeMask, 

edgeMask.getPlaneBitMask("EDGE")).split() 

else: 

# If the directWarp has <1% coverage, the psfMatchedWarp can have 0% and not exist 

# In this case, mask the whole epoch 

nansMask = afwImage.MaskX(coaddBBox, 1) 

spanSetList = [] 

spanSetEdgeMask = [] 

 

spanSetNoDataMask = afwGeom.SpanSet.fromMask(nansMask).split() 

 

spanSetNoDataMaskList.append(spanSetNoDataMask) 

spanSetArtifactList.append(spanSetList) 

spanSetEdgeList.append(spanSetEdgeMask) 

 

if lsstDebug.Info(__name__).saveCountIm: 

path = self._dataRef2DebugPath("epochCountIm", tempExpRefList[0], coaddLevel=True) 

epochCountImage.writeFits(path) 

 

for i, spanSetList in enumerate(spanSetArtifactList): 

if spanSetList: 

filteredSpanSetList = self.filterArtifacts(spanSetList, epochCountImage, nImage, 

templateFootprints) 

spanSetArtifactList[i] = filteredSpanSetList 

 

altMasks = [] 

for artifacts, noData, edge in zip(spanSetArtifactList, spanSetNoDataMaskList, spanSetEdgeList): 

altMasks.append({'CLIPPED': artifacts, 

'NO_DATA': noData, 

'EDGE': edge}) 

return altMasks 

 

def prefilterArtifacts(self, spanSetList, exp): 

"""Remove artifact candidates covered by bad mask plane. 

 

Any future editing of the candidate list that does not depend on 

temporal information should go in this method. 

 

Parameters 

---------- 

spanSetList : `list` 

List of SpanSets representing artifact candidates. 

exp : `lsst.afw.image.Exposure` 

Exposure containing mask planes used to prefilter. 

 

Returns 

------- 

returnSpanSetList : `list` 

List of SpanSets with artifacts. 

""" 

badPixelMask = exp.mask.getPlaneBitMask(self.config.prefilterArtifactsMaskPlanes) 

goodArr = (exp.mask.array & badPixelMask) == 0 

returnSpanSetList = [] 

bbox = exp.getBBox() 

x0, y0 = exp.getXY0() 

for i, span in enumerate(spanSetList): 

y, x = span.clippedTo(bbox).indices() 

yIndexLocal = numpy.array(y) - y0 

xIndexLocal = numpy.array(x) - x0 

goodRatio = numpy.count_nonzero(goodArr[yIndexLocal, xIndexLocal])/span.getArea() 

if goodRatio > self.config.prefilterArtifactsRatio: 

returnSpanSetList.append(span) 

return returnSpanSetList 

 

def filterArtifacts(self, spanSetList, epochCountImage, nImage, footprintsToExclude=None): 

"""Filter artifact candidates. 

 

Parameters 

---------- 

spanSetList : `list` 

List of SpanSets representing artifact candidates. 

epochCountImage : `lsst.afw.image.Image` 

Image of accumulated number of warpDiff detections. 

nImage : `lsst.afw.image.Image` 

Image of the accumulated number of total epochs contributing. 

 

Returns 

------- 

maskSpanSetList : `list` 

List of SpanSets with artifacts. 

""" 

 

maskSpanSetList = [] 

x0, y0 = epochCountImage.getXY0() 

for i, span in enumerate(spanSetList): 

y, x = span.indices() 

yIdxLocal = [y1 - y0 for y1 in y] 

xIdxLocal = [x1 - x0 for x1 in x] 

outlierN = epochCountImage.array[yIdxLocal, xIdxLocal] 

totalN = nImage.array[yIdxLocal, xIdxLocal] 

 

# effectiveMaxNumEpochs is broken line (fraction of N) with characteristic config.maxNumEpochs 

effMaxNumEpochsHighN = (self.config.maxNumEpochs + 

self.config.maxFractionEpochsHigh*numpy.mean(totalN)) 

effMaxNumEpochsLowN = self.config.maxFractionEpochsLow * numpy.mean(totalN) 

effectiveMaxNumEpochs = int(min(effMaxNumEpochsLowN, effMaxNumEpochsHighN)) 

nPixelsBelowThreshold = numpy.count_nonzero((outlierN > 0) & 

(outlierN <= effectiveMaxNumEpochs)) 

percentBelowThreshold = nPixelsBelowThreshold / len(outlierN) 

if percentBelowThreshold > self.config.spatialThreshold: 

maskSpanSetList.append(span) 

 

if self.config.doPreserveContainedBySource and footprintsToExclude is not None: 

# If a candidate is contained by a footprint on the template coadd, do not clip 

filteredMaskSpanSetList = [] 

for span in maskSpanSetList: 

doKeep = True 

for footprint in footprintsToExclude.positive.getFootprints(): 

if footprint.spans.contains(span): 

doKeep = False 

break 

if doKeep: 

filteredMaskSpanSetList.append(span) 

maskSpanSetList = filteredMaskSpanSetList 

 

return maskSpanSetList 

 

def _readAndComputeWarpDiff(self, warpRef, imageScaler, templateCoadd): 

"""Fetch a warp from the butler and return a warpDiff. 

 

Parameters 

---------- 

warpRef : `lsst.daf.persistence.butlerSubset.ButlerDataRef` 

Butler dataRef for the warp. 

imageScaler : `lsst.pipe.tasks.scaleZeroPoint.ImageScaler` 

An image scaler object. 

templateCoadd : `lsst.afw.image.Exposure` 

Exposure to be substracted from the scaled warp. 

 

Returns 

------- 

warp : `lsst.afw.image.Exposure` 

Exposure of the image difference between the warp and template. 

""" 

 

# Warp comparison must use PSF-Matched Warps regardless of requested coadd warp type 

warpName = self.getTempExpDatasetName('psfMatched') 

if not warpRef.datasetExists(warpName): 

self.log.warn("Could not find %s %s; skipping it", warpName, warpRef.dataId) 

return None 

warp = warpRef.get(warpName, immediate=True) 

# direct image scaler OK for PSF-matched Warp 

imageScaler.scaleMaskedImage(warp.getMaskedImage()) 

mi = warp.getMaskedImage() 

if self.config.doScaleWarpVariance: 

try: 

self.scaleWarpVariance.run(mi) 

except Exception as exc: 

self.log.warn("Unable to rescale variance of warp (%s); leaving it as-is" % (exc,)) 

mi -= templateCoadd.getMaskedImage() 

return warp 

 

def _dataRef2DebugPath(self, prefix, warpRef, coaddLevel=False): 

"""Return a path to which to write debugging output. 

 

Creates a hyphen-delimited string of dataId values for simple filenames. 

 

Parameters 

---------- 

prefix : `str` 

Prefix for filename. 

warpRef : `lsst.daf.persistence.butlerSubset.ButlerDataRef` 

Butler dataRef to make the path from. 

coaddLevel : `bool`, optional. 

If True, include only coadd-level keys (e.g., 'tract', 'patch', 

'filter', but no 'visit'). 

 

Returns 

------- 

result : `str` 

Path for debugging output. 

""" 

if coaddLevel: 

keys = warpRef.getButler().getKeys(self.getCoaddDatasetName(self.warpType)) 

else: 

keys = warpRef.dataId.keys() 

keyList = sorted(keys, reverse=True) 

directory = lsstDebug.Info(__name__).figPath if lsstDebug.Info(__name__).figPath else "." 

filename = "%s-%s.fits" % (prefix, '-'.join([str(warpRef.dataId[k]) for k in keyList])) 

return os.path.join(directory, filename)