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

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

# 

# This file is part of fgcmcal. 

# 

# Developed for the LSST Data Management System. 

# This product includes software developed by the LSST Project 

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

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

# for details of code ownership. 

# 

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

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

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

# (at your option) any later version. 

# 

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

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

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

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

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

"""Perform a single fit cycle of FGCM. 

 

This task runs a single "fit cycle" of fgcm. Prior to running this task 

one must run both fgcmMakeLut (to construct the atmosphere and instrumental 

look-up-table) and fgcmBuildStars (to extract visits and star observations 

for the global fit). 

 

The fgcmFitCycle is meant to be run multiple times, and is tracked by the 

'cycleNumber'. After each run of the fit cycle, diagnostic plots should 

be inspected to set parameters for outlier rejection on the following 

cycle. Please see the fgcmcal Cookbook for details. 

""" 

 

import sys 

import traceback 

 

import numpy as np 

 

import lsst.pex.config as pexConfig 

import lsst.pipe.base as pipeBase 

import lsst.afw.table as afwTable 

 

from .utilities import makeConfigDict, translateFgcmLut, translateVisitCatalog 

from .utilities import computeCcdOffsets, makeZptSchema, makeZptCat 

from .utilities import makeAtmSchema, makeAtmCat, makeStdSchema, makeStdCat 

 

import fgcm 

 

__all__ = ['FgcmFitCycleConfig', 'FgcmFitCycleTask', 'FgcmFitCycleRunner'] 

 

 

class FgcmFitCycleConfig(pexConfig.Config): 

"""Config for FgcmFitCycle""" 

 

bands = pexConfig.ListField( 

doc="Bands to run calibration (in wavelength order)", 

dtype=str, 

default=("NO_DATA",), 

) 

fitFlag = pexConfig.ListField( 

doc=("Flag for which bands are directly constrained in the FGCM fit. " 

"Bands set to 0 will have the atmosphere constrained from observations " 

"in other bands on the same night."), 

dtype=int, 

default=(0,), 

) 

requiredFlag = pexConfig.ListField( 

doc=("Flag for which bands are required for a star to be considered a calibration " 

"star in the FGCM fit. Typically this should be the same as fitFlag."), 

dtype=int, 

default=(0,), 

) 

filterMap = pexConfig.DictField( 

doc="Mapping from 'filterName' to band.", 

keytype=str, 

itemtype=str, 

default={}, 

) 

doReferenceCalibration = pexConfig.Field( 

doc="Use reference catalog as additional constraint on calibration", 

dtype=bool, 

default=True, 

) 

refStarSnMin = pexConfig.Field( 

doc="Reference star signal-to-noise minimum to use in calibration. Set to <=0 for no cut.", 

dtype=float, 

default=50.0, 

) 

refStarOutlierNSig = pexConfig.Field( 

doc=("Number of sigma compared to average mag for reference star to be considered an outlier. " 

"Computed per-band, and if it is an outlier in any band it is rejected from fits."), 

dtype=float, 

default=4.0, 

) 

applyRefStarColorCuts = pexConfig.Field( 

doc="Apply color cuts to reference stars?", 

dtype=bool, 

default=True, 

) 

nCore = pexConfig.Field( 

doc="Number of cores to use", 

dtype=int, 

default=4, 

) 

nStarPerRun = pexConfig.Field( 

doc="Number of stars to run in each chunk", 

dtype=int, 

default=200000, 

) 

nExpPerRun = pexConfig.Field( 

doc="Number of exposures to run in each chunk", 

dtype=int, 

default=1000, 

) 

reserveFraction = pexConfig.Field( 

doc="Fraction of stars to reserve for testing", 

dtype=float, 

default=0.1, 

) 

freezeStdAtmosphere = pexConfig.Field( 

doc="Freeze atmosphere parameters to standard (for testing)", 

dtype=bool, 

default=False, 

) 

precomputeSuperStarInitialCycle = pexConfig.Field( 

doc="Precompute superstar flat for initial cycle", 

dtype=bool, 

default=False, 

) 

superStarSubCcd = pexConfig.Field( 

doc="Compute superstar flat on sub-ccd scale", 

dtype=bool, 

default=True, 

) 

superStarSubCcdChebyshevOrder = pexConfig.Field( 

doc=("Order of the 2D chebyshev polynomials for sub-ccd superstar fit. " 

"Global default is first-order polynomials, and should be overridden " 

"on a camera-by-camera basis depending on the ISR."), 

dtype=int, 

default=1, 

) 

superStarSubCcdTriangular = pexConfig.Field( 

doc=("Should the sub-ccd superstar chebyshev matrix be triangular to " 

"suppress high-order cross terms?"), 

dtype=bool, 

default=False, 

) 

superStarSigmaClip = pexConfig.Field( 

doc="Number of sigma to clip outliers when selecting for superstar flats", 

dtype=float, 

default=5.0, 

) 

ccdGraySubCcd = pexConfig.Field( 

doc="Compute CCD gray terms on sub-ccd scale", 

dtype=bool, 

default=False, 

) 

ccdGraySubCcdChebyshevOrder = pexConfig.Field( 

doc="Order of the 2D chebyshev polynomials for sub-ccd gray fit.", 

dtype=int, 

default=1, 

) 

ccdGraySubCcdTriangular = pexConfig.Field( 

doc=("Should the sub-ccd gray chebyshev matrix be triangular to " 

"suppress high-order cross terms?"), 

dtype=bool, 

default=True, 

) 

cycleNumber = pexConfig.Field( 

doc=("FGCM fit cycle number. This is automatically incremented after each run " 

"and stage of outlier rejection. See cookbook for details."), 

dtype=int, 

default=None, 

) 

isFinalCycle = pexConfig.Field( 

doc=("Is this the final cycle of the fitting? Will automatically compute final " 

"selection of stars and photometric exposures, and will output zeropoints " 

"and standard stars for use in fgcmOutputProducts"), 

dtype=bool, 

default=False, 

) 

maxIterBeforeFinalCycle = pexConfig.Field( 

doc=("Maximum fit iterations, prior to final cycle. The number of iterations " 

"will always be 0 in the final cycle for cleanup and final selection."), 

dtype=int, 

default=50, 

) 

utBoundary = pexConfig.Field( 

doc="Boundary (in UTC) from day-to-day", 

dtype=float, 

default=None, 

) 

washMjds = pexConfig.ListField( 

doc="Mirror wash MJDs", 

dtype=float, 

default=(0.0,), 

) 

epochMjds = pexConfig.ListField( 

doc="Epoch boundaries in MJD", 

dtype=float, 

default=(0.0,), 

) 

minObsPerBand = pexConfig.Field( 

doc="Minimum good observations per band", 

dtype=int, 

default=2, 

) 

# TODO: When DM-16511 is done, it will be possible to get the 

# telescope latitude directly from the camera. 

latitude = pexConfig.Field( 

doc="Observatory latitude", 

dtype=float, 

default=None, 

) 

pixelScale = pexConfig.Field( 

doc="Pixel scale (arcsec/pixel) (temporary)", 

dtype=float, 

deprecated=("This field is no longer used, and has been deprecated by DM-16490. " 

"It will be removed after v19."), 

optional=True, 

) 

brightObsGrayMax = pexConfig.Field( 

doc="Maximum gray extinction to be considered bright observation", 

dtype=float, 

default=0.15, 

) 

minStarPerCcd = pexConfig.Field( 

doc=("Minimum number of good stars per CCD to be used in calibration fit. " 

"CCDs with fewer stars will have their calibration estimated from other " 

"CCDs in the same visit, with zeropoint error increased accordingly."), 

dtype=int, 

default=5, 

) 

minCcdPerExp = pexConfig.Field( 

doc=("Minimum number of good CCDs per exposure/visit to be used in calibration fit. " 

"Visits with fewer good CCDs will have CCD zeropoints estimated where possible."), 

dtype=int, 

default=5, 

) 

maxCcdGrayErr = pexConfig.Field( 

doc="Maximum error on CCD gray offset to be considered photometric", 

dtype=float, 

default=0.05, 

) 

minStarPerExp = pexConfig.Field( 

doc=("Minimum number of good stars per exposure/visit to be used in calibration fit. " 

"Visits with fewer good stars will have CCD zeropoints estimated where possible."), 

dtype=int, 

default=600, 

) 

minExpPerNight = pexConfig.Field( 

doc="Minimum number of good exposures/visits to consider a partly photometric night", 

dtype=int, 

default=10, 

) 

expGrayInitialCut = pexConfig.Field( 

doc=("Maximum exposure/visit gray value for initial selection of possible photometric " 

"observations."), 

dtype=float, 

default=-0.25, 

) 

expGrayPhotometricCut = pexConfig.ListField( 

doc=("Maximum (negative) exposure gray for a visit to be considered photometric. " 

"There will be one value per band."), 

dtype=float, 

default=(0.0,), 

) 

expGrayHighCut = pexConfig.ListField( 

doc=("Maximum (positive) exposure gray for a visit to be considered photometric. " 

"There will be one value per band."), 

dtype=float, 

default=(0.0,), 

) 

expGrayRecoverCut = pexConfig.Field( 

doc=("Maximum (negative) exposure gray to be able to recover bad ccds via interpolation. " 

"Visits with more gray extinction will only get CCD zeropoints if there are " 

"sufficient star observations (minStarPerCcd) on that CCD."), 

dtype=float, 

default=-1.0, 

) 

expVarGrayPhotometricCut = pexConfig.Field( 

doc="Maximum exposure variance to be considered possibly photometric", 

dtype=float, 

default=0.0005, 

) 

expGrayErrRecoverCut = pexConfig.Field( 

doc=("Maximum exposure gray error to be able to recover bad ccds via interpolation. " 

"Visits with more gray variance will only get CCD zeropoints if there are " 

"sufficient star observations (minStarPerCcd) on that CCD."), 

dtype=float, 

default=0.05, 

) 

aperCorrFitNBins = pexConfig.Field( 

doc="Aperture correction number of bins", 

dtype=int, 

default=None, 

) 

sedFudgeFactors = pexConfig.ListField( 

doc="Fudge factors for computing linear SED from colors", 

dtype=float, 

default=(0,), 

) 

sigFgcmMaxErr = pexConfig.Field( 

doc="Maximum mag error for fitting sigma_FGCM", 

dtype=float, 

default=0.01, 

) 

sigFgcmMaxEGray = pexConfig.Field( 

doc="Maximum (absolute) gray value for observation in sigma_FGCM", 

dtype=float, 

default=0.05, 

) 

ccdGrayMaxStarErr = pexConfig.Field( 

doc="Maximum error on a star observation to use in ccd gray computation", 

dtype=float, 

default=0.10, 

) 

approxThroughput = pexConfig.ListField( 

doc="Approximate overall throughput at start of calibration observations", 

dtype=float, 

default=(1.0, ), 

) 

sigmaCalRange = pexConfig.ListField( 

doc="Allowed range for systematic error floor estimation", 

dtype=float, 

default=(0.001, 0.003), 

) 

sigmaCalFitPercentile = pexConfig.ListField( 

doc="Magnitude percentile range to fit systematic error floor", 

dtype=float, 

default=(0.05, 0.15), 

) 

sigmaCalPlotPercentile = pexConfig.ListField( 

doc="Magnitude percentile range to plot systematic error floor", 

dtype=float, 

default=(0.05, 0.95), 

) 

sigma0Phot = pexConfig.Field( 

doc="Systematic error floor for all zeropoints", 

dtype=float, 

default=0.003, 

) 

mapLongitudeRef = pexConfig.Field( 

doc="Reference longitude for plotting maps", 

dtype=float, 

default=0.0, 

) 

mapNSide = pexConfig.Field( 

doc="Healpix nside for plotting maps", 

dtype=int, 

default=256, 

) 

outfileBase = pexConfig.Field( 

doc="Filename start for plot output files", 

dtype=str, 

default=None, 

) 

starColorCuts = pexConfig.ListField( 

doc="Encoded star-color cuts (to be cleaned up)", 

dtype=str, 

default=("NO_DATA",), 

) 

colorSplitIndices = pexConfig.ListField( 

doc="Band indices to use to split stars by color", 

dtype=int, 

default=None, 

) 

modelMagErrors = pexConfig.Field( 

doc="Should FGCM model the magnitude errors from sky/fwhm? (False means trust inputs)", 

dtype=bool, 

default=True, 

) 

useQuadraticPwv = pexConfig.Field( 

doc="Model PWV with a quadratic term for variation through the night?", 

dtype=bool, 

default=False, 

) 

instrumentParsPerBand = pexConfig.Field( 

doc=("Model instrumental parameters per band? " 

"Otherwise, instrumental parameters (QE changes with time) are " 

"shared among all bands."), 

dtype=bool, 

default=False, 

) 

instrumentSlopeMinDeltaT = pexConfig.Field( 

doc=("Minimum time change (in days) between observations to use in constraining " 

"instrument slope."), 

dtype=float, 

default=20.0, 

) 

fitMirrorChromaticity = pexConfig.Field( 

doc="Fit (intraband) mirror chromatic term?", 

dtype=bool, 

default=False, 

) 

coatingMjds = pexConfig.ListField( 

doc="Mirror coating dates in MJD", 

dtype=float, 

default=(0.0,), 

) 

outputStandardsBeforeFinalCycle = pexConfig.Field( 

doc="Output standard stars prior to final cycle? Used in debugging.", 

dtype=bool, 

default=False, 

) 

outputZeropointsBeforeFinalCycle = pexConfig.Field( 

doc="Output standard stars prior to final cycle? Used in debugging.", 

dtype=bool, 

default=False, 

) 

useRepeatabilityForExpGrayCuts = pexConfig.Field( 

doc=("Use star repeatability (instead of exposures) for computing photometric " 

"cuts? Recommended for tract/small scale modes."), 

dtype=bool, 

default=False, 

) 

quietMode = pexConfig.Field( 

doc="Be less verbose with logging.", 

dtype=bool, 

default=False, 

) 

 

def setDefaults(self): 

pass 

 

 

class FgcmFitCycleRunner(pipeBase.ButlerInitializedTaskRunner): 

"""Subclass of TaskRunner for fgcmFitCycleTask 

 

fgcmFitCycleTask.run() takes one argument, the butler, and uses 

stars and visits previously extracted from dataRefs by 

fgcmBuildStars. 

This Runner does not perform any dataRef parallelization, but the FGCM 

code called by the Task uses python multiprocessing (see the "ncores" 

config option). 

""" 

 

@staticmethod 

def getTargetList(parsedCmd): 

""" 

Return a list with one element, the butler. 

""" 

return [parsedCmd.butler] 

 

def __call__(self, butler): 

""" 

Parameters 

---------- 

butler: `lsst.daf.persistence.Butler` 

 

Returns 

------- 

exitStatus: `list` with `pipeBase.Struct` 

exitStatus (0: success; 1: failure) 

""" 

 

task = self.TaskClass(config=self.config, log=self.log) 

 

exitStatus = 0 

if self.doRaise: 

task.runDataRef(butler) 

else: 

try: 

task.runDataRef(butler) 

except Exception as e: 

exitStatus = 1 

task.log.fatal("Failed: %s" % e) 

if not isinstance(e, pipeBase.TaskError): 

traceback.print_exc(file=sys.stderr) 

 

task.writeMetadata(butler) 

 

# The task does not return any results: 

return [pipeBase.Struct(exitStatus=exitStatus)] 

 

def run(self, parsedCmd): 

""" 

Run the task, with no multiprocessing 

 

Parameters 

---------- 

parsedCmd: ArgumentParser parsed command line 

""" 

 

resultList = [] 

 

if self.precall(parsedCmd): 

targetList = self.getTargetList(parsedCmd) 

# make sure that we only get 1 

resultList = self(targetList[0]) 

 

return resultList 

 

 

class FgcmFitCycleTask(pipeBase.CmdLineTask): 

""" 

Run Single fit cycle for FGCM global calibration 

""" 

 

ConfigClass = FgcmFitCycleConfig 

RunnerClass = FgcmFitCycleRunner 

_DefaultName = "fgcmFitCycle" 

 

def __init__(self, butler=None, **kwargs): 

""" 

Instantiate an fgcmFitCycle. 

 

Parameters 

---------- 

butler : `lsst.daf.persistence.Butler` 

""" 

 

pipeBase.CmdLineTask.__init__(self, **kwargs) 

 

# no saving of metadata for now 

def _getMetadataName(self): 

return None 

 

@pipeBase.timeMethod 

def runDataRef(self, butler): 

""" 

Run a single fit cycle for FGCM 

 

Parameters 

---------- 

butler: `lsst.daf.persistence.Butler` 

""" 

 

self._fgcmFitCycle(butler) 

 

def writeConfig(self, butler, clobber=False, doBackup=True): 

"""Write the configuration used for processing the data, or check that an existing 

one is equal to the new one if present. This is an override of the regular 

version from pipe_base that knows about fgcmcycle. 

 

Parameters 

---------- 

butler : `lsst.daf.persistence.Butler` 

Data butler used to write the config. The config is written to dataset type 

`CmdLineTask._getConfigName`. 

clobber : `bool`, optional 

A boolean flag that controls what happens if a config already has been saved: 

- `True`: overwrite or rename the existing config, depending on ``doBackup``. 

- `False`: raise `TaskError` if this config does not match the existing config. 

doBackup : `bool`, optional 

Set to `True` to backup the config files if clobbering. 

""" 

configName = self._getConfigName() 

if configName is None: 

return 

if clobber: 

butler.put(self.config, configName, doBackup=doBackup, fgcmcycle=self.config.cycleNumber) 

elif butler.datasetExists(configName, write=True, fgcmcycle=self.config.cycleNumber): 

# this may be subject to a race condition; see #2789 

try: 

oldConfig = butler.get(configName, immediate=True, fgcmcycle=self.config.cycleNumber) 

except Exception as exc: 

raise type(exc)("Unable to read stored config file %s (%s); consider using --clobber-config" % 

(configName, exc)) 

 

def logConfigMismatch(msg): 

self.log.fatal("Comparing configuration: %s", msg) 

 

if not self.config.compare(oldConfig, shortcut=False, output=logConfigMismatch): 

raise pipeBase.TaskError( 

("Config does not match existing task config %r on disk; tasks configurations " + 

"must be consistent within the same output repo (override with --clobber-config)") % 

(configName,)) 

else: 

butler.put(self.config, configName, fgcmcycle=self.config.cycleNumber) 

 

def _fgcmFitCycle(self, butler): 

""" 

Run the fit cycle 

 

Parameters 

---------- 

butler: `lsst.daf.persistence.Butler` 

""" 

 

self._checkDatasetsExist(butler) 

 

# Set defaults on whether to output standards and zeropoints 

self.maxIter = self.config.maxIterBeforeFinalCycle 

self.outputStandards = self.config.outputStandardsBeforeFinalCycle 

self.outputZeropoints = self.config.outputZeropointsBeforeFinalCycle 

self.resetFitParameters = True 

 

if self.config.isFinalCycle: 

# This is the final fit cycle, so we do not want to reset fit 

# parameters, we want to run a final "clean-up" with 0 fit iterations, 

# and we always want to output standards and zeropoints 

self.maxIter = 0 

self.outputStandards = True 

self.outputZeropoints = True 

self.resetFitParameters = False 

 

camera = butler.get('camera') 

configDict = makeConfigDict(self.config, self.log, camera, 

self.maxIter, self.resetFitParameters, 

self.outputZeropoints) 

 

lutCat = butler.get('fgcmLookUpTable') 

fgcmLut, lutIndexVals, lutStd = translateFgcmLut(lutCat, dict(self.config.filterMap)) 

del lutCat 

 

# next we need the exposure/visit information 

 

# fgcmExpInfo = self._loadVisitCatalog(butler) 

visitCat = butler.get('fgcmVisitCatalog') 

fgcmExpInfo = translateVisitCatalog(visitCat) 

del visitCat 

 

# Use the first orientation. 

# TODO: DM-21215 will generalize to arbitrary camera orientations 

ccdOffsets = computeCcdOffsets(camera, fgcmExpInfo['TELROT'][0]) 

 

noFitsDict = {'lutIndex': lutIndexVals, 

'lutStd': lutStd, 

'expInfo': fgcmExpInfo, 

'ccdOffsets': ccdOffsets} 

 

# set up the fitter object 

fgcmFitCycle = fgcm.FgcmFitCycle(configDict, useFits=False, 

noFitsDict=noFitsDict, noOutput=True) 

 

# create the parameter object 

if (fgcmFitCycle.initialCycle): 

# cycle = 0, initial cycle 

fgcmPars = fgcm.FgcmParameters.newParsWithArrays(fgcmFitCycle.fgcmConfig, 

fgcmLut, 

fgcmExpInfo) 

else: 

inParInfo, inParams, inSuperStar = self._loadParameters(butler) 

fgcmPars = fgcm.FgcmParameters.loadParsWithArrays(fgcmFitCycle.fgcmConfig, 

fgcmExpInfo, 

inParInfo, 

inParams, 

inSuperStar) 

 

lastCycle = configDict['cycleNumber'] - 1 

 

# set up the stars... 

fgcmStars = fgcm.FgcmStars(fgcmFitCycle.fgcmConfig) 

 

starObs = butler.get('fgcmStarObservations') 

starIds = butler.get('fgcmStarIds') 

starIndices = butler.get('fgcmStarIndices') 

 

# grab the flagged stars if available 

if butler.datasetExists('fgcmFlaggedStars', fgcmcycle=lastCycle): 

flaggedStars = butler.get('fgcmFlaggedStars', fgcmcycle=lastCycle) 

flagId = flaggedStars['objId'][:] 

flagFlag = flaggedStars['objFlag'][:] 

else: 

flagId = None 

flagFlag = None 

 

if self.config.doReferenceCalibration: 

refStars = butler.get('fgcmReferenceStars') 

refId = refStars['fgcm_id'][:] 

refMag = refStars['refMag'][:, :] 

refMagErr = refStars['refMagErr'][:, :] 

else: 

refId = None 

refMag = None 

refMagErr = None 

 

# match star observations to visits 

# Only those star observations that match visits from fgcmExpInfo['VISIT'] will 

# actually be transferred into fgcm using the indexing below. 

visitIndex = np.searchsorted(fgcmExpInfo['VISIT'], starObs['visit'][starIndices['obsIndex']]) 

 

# The fgcmStars.loadStars method will copy all the star information into 

# special shared memory objects that will not blow up the memory usage when 

# used with python multiprocessing. Once all the numbers are copied, 

# it is necessary to release all references to the objects that previously 

# stored the data to ensure that the garbage collector can clear the memory, 

# and ensure that this memory is not copied when multiprocessing kicks in. 

 

# We determine the conversion from the native units (typically radians) to 

# degrees for the first star. This allows us to treat coord_ra/coord_dec as 

# numpy arrays rather than Angles, which would we approximately 600x slower. 

conv = starObs[0]['ra'].asDegrees() / float(starObs[0]['ra']) 

 

fgcmStars.loadStars(fgcmPars, 

starObs['visit'][starIndices['obsIndex']], 

starObs['ccd'][starIndices['obsIndex']], 

starObs['ra'][starIndices['obsIndex']] * conv, 

starObs['dec'][starIndices['obsIndex']] * conv, 

starObs['instMag'][starIndices['obsIndex']], 

starObs['instMagErr'][starIndices['obsIndex']], 

fgcmExpInfo['FILTERNAME'][visitIndex], 

starIds['fgcm_id'][:], 

starIds['ra'][:], 

starIds['dec'][:], 

starIds['obsArrIndex'][:], 

starIds['nObs'][:], 

obsX=starObs['x'][starIndices['obsIndex']], 

obsY=starObs['y'][starIndices['obsIndex']], 

refID=refId, 

refMag=refMag, 

refMagErr=refMagErr, 

flagID=flagId, 

flagFlag=flagFlag, 

computeNobs=True) 

 

# Release all references to temporary objects holding star data (see above) 

starObs = None 

starIds = None 

starIndices = None 

flagId = None 

flagFlag = None 

flaggedStars = None 

refStars = None 

 

# and set the bits in the cycle object 

fgcmFitCycle.setLUT(fgcmLut) 

fgcmFitCycle.setStars(fgcmStars) 

fgcmFitCycle.setPars(fgcmPars) 

 

# finish the setup 

fgcmFitCycle.finishSetup() 

 

# and run 

fgcmFitCycle.run() 

 

################## 

# Persistance 

################## 

 

self._persistFgcmDatasets(butler, fgcmFitCycle) 

 

# Output the config for the next cycle 

# We need to make a copy since the input one has been frozen 

 

outConfig = FgcmFitCycleConfig() 

outConfig.update(**self.config.toDict()) 

 

outConfig.cycleNumber += 1 

outConfig.precomputeSuperStarInitialCycle = False 

outConfig.freezeStdAtmosphere = False 

outConfig.expGrayPhotometricCut[:] = fgcmFitCycle.updatedPhotometricCut 

outConfig.expGrayHighCut[:] = fgcmFitCycle.updatedHighCut 

configFileName = '%s_cycle%02d_config.py' % (outConfig.outfileBase, 

outConfig.cycleNumber) 

outConfig.save(configFileName) 

 

if self.config.isFinalCycle == 1: 

# We are done, ready to output products 

self.log.info("Everything is in place to run fgcmOutputProducts.py") 

else: 

self.log.info("Saved config for next cycle to %s" % (configFileName)) 

self.log.info("Be sure to look at:") 

self.log.info(" config.expGrayPhotometricCut") 

self.log.info(" config.expGrayHighCut") 

self.log.info("If you are satisfied with the fit, please set:") 

self.log.info(" config.isFinalCycle = True") 

 

def _checkDatasetsExist(self, butler): 

""" 

Check if necessary datasets exist to run fgcmFitCycle 

 

Parameters 

---------- 

butler: `lsst.daf.persistence.Butler` 

 

Raises 

------ 

RuntimeError 

If any of fgcmVisitCatalog, fgcmStarObservations, fgcmStarIds, 

fgcmStarIndices, fgcmLookUpTable datasets do not exist. 

If cycleNumber > 0, then also checks for fgcmFitParameters, 

fgcmFlaggedStars. 

""" 

 

if not butler.datasetExists('fgcmVisitCatalog'): 

raise RuntimeError("Could not find fgcmVisitCatalog in repo!") 

if not butler.datasetExists('fgcmStarObservations'): 

raise RuntimeError("Could not find fgcmStarObservations in repo!") 

if not butler.datasetExists('fgcmStarIds'): 

raise RuntimeError("Could not find fgcmStarIds in repo!") 

if not butler.datasetExists('fgcmStarIndices'): 

raise RuntimeError("Could not find fgcmStarIndices in repo!") 

if not butler.datasetExists('fgcmLookUpTable'): 

raise RuntimeError("Could not find fgcmLookUpTable in repo!") 

 

# Need additional datasets if we are not the initial cycle 

if (self.config.cycleNumber > 0): 

if not butler.datasetExists('fgcmFitParameters', 

fgcmcycle=self.config.cycleNumber-1): 

raise RuntimeError("Could not find fgcmFitParameters for previous cycle (%d) in repo!" % 

(self.config.cycleNumber-1)) 

if not butler.datasetExists('fgcmFlaggedStars', 

fgcmcycle=self.config.cycleNumber-1): 

raise RuntimeError("Could not find fgcmFlaggedStars for previous cycle (%d) in repo!" % 

(self.config.cycleNumber-1)) 

 

# And additional dataset if we want reference calibration 

if self.config.doReferenceCalibration: 

if not butler.datasetExists('fgcmReferenceStars'): 

raise RuntimeError("Could not find fgcmReferenceStars in repo, and " 

"doReferenceCalibration is True.") 

 

def _loadParameters(self, butler): 

""" 

Load FGCM parameters from a previous fit cycle 

 

Parameters 

---------- 

butler: `lsst.daf.persistence.Butler` 

 

Returns 

------- 

inParInfo: `numpy.ndarray` 

Numpy array parameter information formatted for input to fgcm 

inParameters: `numpy.ndarray` 

Numpy array parameter values formatted for input to fgcm 

inSuperStar: `numpy.array` 

Superstar flat formatted for input to fgcm 

""" 

 

# note that we already checked that this is available 

parCat = butler.get('fgcmFitParameters', fgcmcycle=self.config.cycleNumber-1) 

 

parLutFilterNames = np.array(parCat[0]['lutFilterNames'].split(',')) 

parFitBands = np.array(parCat[0]['fitBands'].split(',')) 

parNotFitBands = np.array(parCat[0]['notFitBands'].split(',')) 

 

inParInfo = np.zeros(1, dtype=[('NCCD', 'i4'), 

('LUTFILTERNAMES', parLutFilterNames.dtype.str, 

parLutFilterNames.size), 

('FITBANDS', parFitBands.dtype.str, parFitBands.size), 

('NOTFITBANDS', parNotFitBands.dtype.str, parNotFitBands.size), 

('LNTAUUNIT', 'f8'), 

('LNTAUSLOPEUNIT', 'f8'), 

('ALPHAUNIT', 'f8'), 

('LNPWVUNIT', 'f8'), 

('LNPWVSLOPEUNIT', 'f8'), 

('LNPWVQUADRATICUNIT', 'f8'), 

('LNPWVGLOBALUNIT', 'f8'), 

('O3UNIT', 'f8'), 

('QESYSUNIT', 'f8'), 

('FILTEROFFSETUNIT', 'f8'), 

('HASEXTERNALPWV', 'i2'), 

('HASEXTERNALTAU', 'i2')]) 

inParInfo['NCCD'] = parCat['nCcd'] 

inParInfo['LUTFILTERNAMES'][:] = parLutFilterNames 

inParInfo['FITBANDS'][:] = parFitBands 

inParInfo['NOTFITBANDS'][:] = parNotFitBands 

inParInfo['HASEXTERNALPWV'] = parCat['hasExternalPwv'] 

inParInfo['HASEXTERNALTAU'] = parCat['hasExternalTau'] 

 

inParams = np.zeros(1, dtype=[('PARALPHA', 'f8', parCat['parAlpha'].size), 

('PARO3', 'f8', parCat['parO3'].size), 

('PARLNTAUINTERCEPT', 'f8', 

parCat['parLnTauIntercept'].size), 

('PARLNTAUSLOPE', 'f8', 

parCat['parLnTauSlope'].size), 

('PARLNPWVINTERCEPT', 'f8', 

parCat['parLnPwvIntercept'].size), 

('PARLNPWVSLOPE', 'f8', 

parCat['parLnPwvSlope'].size), 

('PARLNPWVQUADRATIC', 'f8', 

parCat['parLnPwvQuadratic'].size), 

('PARQESYSINTERCEPT', 'f8', 

parCat['parQeSysIntercept'].size), 

('COMPQESYSSLOPE', 'f8', 

parCat['compQeSysSlope'].size), 

('PARFILTEROFFSET', 'f8', 

parCat['parFilterOffset'].size), 

('PARFILTEROFFSETFITFLAG', 'i2', 

parCat['parFilterOffsetFitFlag'].size), 

('PARRETRIEVEDLNPWVSCALE', 'f8'), 

('PARRETRIEVEDLNPWVOFFSET', 'f8'), 

('PARRETRIEVEDLNPWVNIGHTLYOFFSET', 'f8', 

parCat['parRetrievedLnPwvNightlyOffset'].size), 

('COMPABSTHROUGHPUT', 'f8', 

parCat['compAbsThroughput'].size), 

('COMPREFOFFSET', 'f8', 

parCat['compRefOffset'].size), 

('COMPREFSIGMA', 'f8', 

parCat['compRefSigma'].size), 

('COMPMIRRORCHROMATICITY', 'f8', 

parCat['compMirrorChromaticity'].size), 

('MIRRORCHROMATICITYPIVOT', 'f8', 

parCat['mirrorChromaticityPivot'].size), 

('COMPAPERCORRPIVOT', 'f8', 

parCat['compAperCorrPivot'].size), 

('COMPAPERCORRSLOPE', 'f8', 

parCat['compAperCorrSlope'].size), 

('COMPAPERCORRSLOPEERR', 'f8', 

parCat['compAperCorrSlopeErr'].size), 

('COMPAPERCORRRANGE', 'f8', 

parCat['compAperCorrRange'].size), 

('COMPMODELERREXPTIMEPIVOT', 'f8', 

parCat['compModelErrExptimePivot'].size), 

('COMPMODELERRFWHMPIVOT', 'f8', 

parCat['compModelErrFwhmPivot'].size), 

('COMPMODELERRSKYPIVOT', 'f8', 

parCat['compModelErrSkyPivot'].size), 

('COMPMODELERRPARS', 'f8', 

parCat['compModelErrPars'].size), 

('COMPEXPGRAY', 'f8', 

parCat['compExpGray'].size), 

('COMPVARGRAY', 'f8', 

parCat['compVarGray'].size), 

('COMPNGOODSTARPEREXP', 'i4', 

parCat['compNGoodStarPerExp'].size), 

('COMPSIGFGCM', 'f8', 

parCat['compSigFgcm'].size), 

('COMPSIGMACAL', 'f8', 

parCat['compSigmaCal'].size), 

('COMPRETRIEVEDLNPWV', 'f8', 

parCat['compRetrievedLnPwv'].size), 

('COMPRETRIEVEDLNPWVRAW', 'f8', 

parCat['compRetrievedLnPwvRaw'].size), 

('COMPRETRIEVEDLNPWVFLAG', 'i2', 

parCat['compRetrievedLnPwvFlag'].size), 

('COMPRETRIEVEDTAUNIGHT', 'f8', 

parCat['compRetrievedTauNight'].size)]) 

 

inParams['PARALPHA'][:] = parCat['parAlpha'][0, :] 

inParams['PARO3'][:] = parCat['parO3'][0, :] 

inParams['PARLNTAUINTERCEPT'][:] = parCat['parLnTauIntercept'][0, :] 

inParams['PARLNTAUSLOPE'][:] = parCat['parLnTauSlope'][0, :] 

inParams['PARLNPWVINTERCEPT'][:] = parCat['parLnPwvIntercept'][0, :] 

inParams['PARLNPWVSLOPE'][:] = parCat['parLnPwvSlope'][0, :] 

inParams['PARLNPWVQUADRATIC'][:] = parCat['parLnPwvQuadratic'][0, :] 

inParams['PARQESYSINTERCEPT'][:] = parCat['parQeSysIntercept'][0, :] 

inParams['COMPQESYSSLOPE'][:] = parCat['compQeSysSlope'][0, :] 

inParams['PARFILTEROFFSET'][:] = parCat['parFilterOffset'][0, :] 

inParams['PARFILTEROFFSETFITFLAG'][:] = parCat['parFilterOffsetFitFlag'][0, :] 

inParams['PARRETRIEVEDLNPWVSCALE'] = parCat['parRetrievedLnPwvScale'] 

inParams['PARRETRIEVEDLNPWVOFFSET'] = parCat['parRetrievedLnPwvOffset'] 

inParams['PARRETRIEVEDLNPWVNIGHTLYOFFSET'][:] = parCat['parRetrievedLnPwvNightlyOffset'][0, :] 

inParams['COMPABSTHROUGHPUT'][:] = parCat['compAbsThroughput'][0, :] 

inParams['COMPREFOFFSET'][:] = parCat['compRefOffset'][0, :] 

inParams['COMPREFSIGMA'][:] = parCat['compRefSigma'][0, :] 

inParams['COMPMIRRORCHROMATICITY'][:] = parCat['compMirrorChromaticity'][0, :] 

inParams['MIRRORCHROMATICITYPIVOT'][:] = parCat['mirrorChromaticityPivot'][0, :] 

inParams['COMPAPERCORRPIVOT'][:] = parCat['compAperCorrPivot'][0, :] 

inParams['COMPAPERCORRSLOPE'][:] = parCat['compAperCorrSlope'][0, :] 

inParams['COMPAPERCORRSLOPEERR'][:] = parCat['compAperCorrSlopeErr'][0, :] 

inParams['COMPAPERCORRRANGE'][:] = parCat['compAperCorrRange'][0, :] 

inParams['COMPMODELERREXPTIMEPIVOT'][:] = parCat['compModelErrExptimePivot'][0, :] 

inParams['COMPMODELERRFWHMPIVOT'][:] = parCat['compModelErrFwhmPivot'][0, :] 

inParams['COMPMODELERRSKYPIVOT'][:] = parCat['compModelErrSkyPivot'][0, :] 

inParams['COMPMODELERRPARS'][:] = parCat['compModelErrPars'][0, :] 

inParams['COMPEXPGRAY'][:] = parCat['compExpGray'][0, :] 

inParams['COMPVARGRAY'][:] = parCat['compVarGray'][0, :] 

inParams['COMPNGOODSTARPEREXP'][:] = parCat['compNGoodStarPerExp'][0, :] 

inParams['COMPSIGFGCM'][:] = parCat['compSigFgcm'][0, :] 

inParams['COMPSIGMACAL'][:] = parCat['compSigmaCal'][0, :] 

inParams['COMPRETRIEVEDLNPWV'][:] = parCat['compRetrievedLnPwv'][0, :] 

inParams['COMPRETRIEVEDLNPWVRAW'][:] = parCat['compRetrievedLnPwvRaw'][0, :] 

inParams['COMPRETRIEVEDLNPWVFLAG'][:] = parCat['compRetrievedLnPwvFlag'][0, :] 

inParams['COMPRETRIEVEDTAUNIGHT'][:] = parCat['compRetrievedTauNight'][0, :] 

 

inSuperStar = np.zeros(parCat['superstarSize'][0, :], dtype='f8') 

inSuperStar[:, :, :, :] = parCat['superstar'][0, :].reshape(inSuperStar.shape) 

 

return (inParInfo, inParams, inSuperStar) 

 

def _persistFgcmDatasets(self, butler, fgcmFitCycle): 

""" 

Persist FGCM datasets through the butler. 

 

Parameters 

---------- 

butler: `lsst.daf.persistence.Butler` 

fgcmFitCycle: `lsst.fgcm.FgcmFitCycle` 

Fgcm Fit cycle object 

""" 

 

# Save the parameters 

parInfo, pars = fgcmFitCycle.fgcmPars.parsToArrays() 

 

parSchema = afwTable.Schema() 

 

comma = ',' 

lutFilterNameString = comma.join([n.decode('utf-8') 

for n in parInfo['LUTFILTERNAMES'][0]]) 

fitBandString = comma.join([n.decode('utf-8') 

for n in parInfo['FITBANDS'][0]]) 

notFitBandString = comma.join([n.decode('utf-8') 

for n in parInfo['NOTFITBANDS'][0]]) 

 

parSchema = self._makeParSchema(parInfo, pars, fgcmFitCycle.fgcmPars.parSuperStarFlat, 

lutFilterNameString, fitBandString, notFitBandString) 

parCat = self._makeParCatalog(parSchema, parInfo, pars, 

fgcmFitCycle.fgcmPars.parSuperStarFlat, 

lutFilterNameString, fitBandString, notFitBandString) 

 

butler.put(parCat, 'fgcmFitParameters', fgcmcycle=self.config.cycleNumber) 

 

# Save the indices of the flagged stars 

# (stars that have been (a) reserved from the fit for testing and 

# (b) bad stars that have failed quality checks.) 

flagStarSchema = self._makeFlagStarSchema() 

flagStarStruct = fgcmFitCycle.fgcmStars.getFlagStarIndices() 

flagStarCat = self._makeFlagStarCat(flagStarSchema, flagStarStruct) 

 

butler.put(flagStarCat, 'fgcmFlaggedStars', fgcmcycle=self.config.cycleNumber) 

 

# Save the zeropoint information and atmospheres only if desired 

if self.outputZeropoints: 

if self.config.superStarSubCcd or self.config.ccdGraySubCcd: 

chebSize = fgcmFitCycle.fgcmZpts.zpStruct['FGCM_FZPT_CHEB'].shape[1] 

else: 

chebSize = 0 

zptSchema = makeZptSchema(chebSize) 

zptCat = makeZptCat(zptSchema, fgcmFitCycle.fgcmZpts.zpStruct) 

 

butler.put(zptCat, 'fgcmZeropoints', fgcmcycle=self.config.cycleNumber) 

 

# Save atmosphere values 

# These are generated by the same code that generates zeropoints 

atmSchema = makeAtmSchema() 

atmCat = makeAtmCat(atmSchema, fgcmFitCycle.fgcmZpts.atmStruct) 

 

butler.put(atmCat, 'fgcmAtmosphereParameters', fgcmcycle=self.config.cycleNumber) 

 

# Save the standard stars (if configured) 

if self.outputStandards: 

stdSchema = makeStdSchema(len(self.config.bands)) 

stdStruct = fgcmFitCycle.fgcmStars.retrieveStdStarCatalog(fgcmFitCycle.fgcmPars) 

stdCat = makeStdCat(stdSchema, stdStruct) 

 

butler.put(stdCat, 'fgcmStandardStars', fgcmcycle=self.config.cycleNumber) 

 

def _makeParSchema(self, parInfo, pars, parSuperStarFlat, 

lutFilterNameString, fitBandString, notFitBandString): 

""" 

Make the parameter persistence schema 

 

Parameters 

---------- 

parInfo: `numpy.ndarray` 

Parameter information returned by fgcm 

pars: `numpy.ndarray` 

Parameter values returned by fgcm 

parSuperStarFlat: `numpy.array` 

Superstar flat values returned by fgcm 

lutFilterNameString: `str` 

Combined string of all the lutFilterNames 

fitBandString: `str` 

Combined string of all the fitBands 

notFitBandString: `str` 

Combined string of all the bands not used in the fit 

 

Returns 

------- 

parSchema: `afwTable.schema` 

""" 

 

parSchema = afwTable.Schema() 

 

# parameter info section 

parSchema.addField('nCcd', type=np.int32, doc='Number of CCDs') 

parSchema.addField('lutFilterNames', type=str, doc='LUT Filter names in parameter file', 

size=len(lutFilterNameString)) 

parSchema.addField('fitBands', type=str, doc='Bands that were fit', 

size=len(fitBandString)) 

parSchema.addField('notFitBands', type=str, doc='Bands that were not fit', 

size=len(notFitBandString)) 

parSchema.addField('lnTauUnit', type=np.float64, doc='Step units for ln(AOD)') 

parSchema.addField('lnTauSlopeUnit', type=np.float64, 

doc='Step units for ln(AOD) slope') 

parSchema.addField('alphaUnit', type=np.float64, doc='Step units for alpha') 

parSchema.addField('lnPwvUnit', type=np.float64, doc='Step units for ln(pwv)') 

parSchema.addField('lnPwvSlopeUnit', type=np.float64, 

doc='Step units for ln(pwv) slope') 

parSchema.addField('lnPwvQuadraticUnit', type=np.float64, 

doc='Step units for ln(pwv) quadratic term') 

parSchema.addField('lnPwvGlobalUnit', type=np.float64, 

doc='Step units for global ln(pwv) parameters') 

parSchema.addField('o3Unit', type=np.float64, doc='Step units for O3') 

parSchema.addField('qeSysUnit', type=np.float64, doc='Step units for mirror gray') 

parSchema.addField('filterOffsetUnit', type=np.float64, doc='Step units for filter offset') 

parSchema.addField('hasExternalPwv', type=np.int32, doc='Parameters fit using external pwv') 

parSchema.addField('hasExternalTau', type=np.int32, doc='Parameters fit using external tau') 

 

# parameter section 

parSchema.addField('parAlpha', type='ArrayD', doc='Alpha parameter vector', 

size=pars['PARALPHA'].size) 

parSchema.addField('parO3', type='ArrayD', doc='O3 parameter vector', 

size=pars['PARO3'].size) 

parSchema.addField('parLnTauIntercept', type='ArrayD', 

doc='ln(Tau) intercept parameter vector', 

size=pars['PARLNTAUINTERCEPT'].size) 

parSchema.addField('parLnTauSlope', type='ArrayD', 

doc='ln(Tau) slope parameter vector', 

size=pars['PARLNTAUSLOPE'].size) 

parSchema.addField('parLnPwvIntercept', type='ArrayD', doc='ln(pwv) intercept parameter vector', 

size=pars['PARLNPWVINTERCEPT'].size) 

parSchema.addField('parLnPwvSlope', type='ArrayD', doc='ln(pwv) slope parameter vector', 

size=pars['PARLNPWVSLOPE'].size) 

parSchema.addField('parLnPwvQuadratic', type='ArrayD', doc='ln(pwv) quadratic parameter vector', 

size=pars['PARLNPWVQUADRATIC'].size) 

parSchema.addField('parQeSysIntercept', type='ArrayD', doc='Mirror gray intercept parameter vector', 

size=pars['PARQESYSINTERCEPT'].size) 

parSchema.addField('compQeSysSlope', type='ArrayD', doc='Mirror gray slope parameter vector', 

size=pars[0]['COMPQESYSSLOPE'].size) 

parSchema.addField('parFilterOffset', type='ArrayD', doc='Filter offset parameter vector', 

size=pars['PARFILTEROFFSET'].size) 

parSchema.addField('parFilterOffsetFitFlag', type='ArrayI', doc='Filter offset parameter fit flag', 

size=pars['PARFILTEROFFSETFITFLAG'].size) 

parSchema.addField('parRetrievedLnPwvScale', type=np.float64, 

doc='Global scale for retrieved ln(pwv)') 

parSchema.addField('parRetrievedLnPwvOffset', type=np.float64, 

doc='Global offset for retrieved ln(pwv)') 

parSchema.addField('parRetrievedLnPwvNightlyOffset', type='ArrayD', 

doc='Nightly offset for retrieved ln(pwv)', 

size=pars['PARRETRIEVEDLNPWVNIGHTLYOFFSET'].size) 

parSchema.addField('compAbsThroughput', type='ArrayD', 

doc='Absolute throughput (relative to transmission curves)', 

size=pars['COMPABSTHROUGHPUT'].size) 

parSchema.addField('compRefOffset', type='ArrayD', 

doc='Offset between reference stars and calibrated stars', 

size=pars['COMPREFOFFSET'].size) 

parSchema.addField('compRefSigma', type='ArrayD', 

doc='Width of reference star/calibrated star distribution', 

size=pars['COMPREFSIGMA'].size) 

parSchema.addField('compMirrorChromaticity', type='ArrayD', 

doc='Computed mirror chromaticity terms', 

size=pars['COMPMIRRORCHROMATICITY'].size) 

parSchema.addField('mirrorChromaticityPivot', type='ArrayD', 

doc='Mirror chromaticity pivot mjd', 

size=pars['MIRRORCHROMATICITYPIVOT'].size) 

parSchema.addField('compAperCorrPivot', type='ArrayD', doc='Aperture correction pivot', 

size=pars['COMPAPERCORRPIVOT'].size) 

parSchema.addField('compAperCorrSlope', type='ArrayD', doc='Aperture correction slope', 

size=pars['COMPAPERCORRSLOPE'].size) 

parSchema.addField('compAperCorrSlopeErr', type='ArrayD', doc='Aperture correction slope error', 

size=pars['COMPAPERCORRSLOPEERR'].size) 

parSchema.addField('compAperCorrRange', type='ArrayD', doc='Aperture correction range', 

size=pars['COMPAPERCORRRANGE'].size) 

parSchema.addField('compModelErrExptimePivot', type='ArrayD', doc='Model error exptime pivot', 

size=pars['COMPMODELERREXPTIMEPIVOT'].size) 

parSchema.addField('compModelErrFwhmPivot', type='ArrayD', doc='Model error fwhm pivot', 

size=pars['COMPMODELERRFWHMPIVOT'].size) 

parSchema.addField('compModelErrSkyPivot', type='ArrayD', doc='Model error sky pivot', 

size=pars['COMPMODELERRSKYPIVOT'].size) 

parSchema.addField('compModelErrPars', type='ArrayD', doc='Model error parameters', 

size=pars['COMPMODELERRPARS'].size) 

parSchema.addField('compExpGray', type='ArrayD', doc='Computed exposure gray', 

size=pars['COMPEXPGRAY'].size) 

parSchema.addField('compVarGray', type='ArrayD', doc='Computed exposure variance', 

size=pars['COMPVARGRAY'].size) 

parSchema.addField('compNGoodStarPerExp', type='ArrayI', 

doc='Computed number of good stars per exposure', 

size=pars['COMPNGOODSTARPEREXP'].size) 

parSchema.addField('compSigFgcm', type='ArrayD', doc='Computed sigma_fgcm (intrinsic repeatability)', 

size=pars['COMPSIGFGCM'].size) 

parSchema.addField('compSigmaCal', type='ArrayD', doc='Computed sigma_cal (systematic error floor)', 

size=pars['COMPSIGMACAL'].size) 

parSchema.addField('compRetrievedLnPwv', type='ArrayD', doc='Retrieved ln(pwv) (smoothed)', 

size=pars['COMPRETRIEVEDLNPWV'].size) 

parSchema.addField('compRetrievedLnPwvRaw', type='ArrayD', doc='Retrieved ln(pwv) (raw)', 

size=pars['COMPRETRIEVEDLNPWVRAW'].size) 

parSchema.addField('compRetrievedLnPwvFlag', type='ArrayI', doc='Retrieved ln(pwv) Flag', 

size=pars['COMPRETRIEVEDLNPWVFLAG'].size) 

parSchema.addField('compRetrievedTauNight', type='ArrayD', doc='Retrieved tau (per night)', 

size=pars['COMPRETRIEVEDTAUNIGHT'].size) 

# superstarflat section 

parSchema.addField('superstarSize', type='ArrayI', doc='Superstar matrix size', 

size=4) 

parSchema.addField('superstar', type='ArrayD', doc='Superstar matrix (flattened)', 

size=parSuperStarFlat.size) 

 

return parSchema 

 

def _makeParCatalog(self, parSchema, parInfo, pars, parSuperStarFlat, 

lutFilterNameString, fitBandString, notFitBandString): 

""" 

Make the FGCM parameter catalog for persistence 

 

Parameters 

---------- 

parSchema: `lsst.afw.table.Schema` 

Parameter catalog schema 

pars: `numpy.ndarray` 

FGCM parameters to put into parCat 

parSuperStarFlat: `numpy.array` 

FGCM superstar flat array to put into parCat 

lutFilterNameString: `str` 

Combined string of all the lutFilterNames 

fitBandString: `str` 

Combined string of all the fitBands 

notFitBandString: `str` 

Combined string of all the bands not used in the fit 

 

Returns 

------- 

parCat: `afwTable.BasicCatalog` 

Atmosphere and instrumental model parameter catalog for persistence 

""" 

 

parCat = afwTable.BaseCatalog(parSchema) 

parCat.reserve(1) 

 

# The parameter catalog just has one row, with many columns for all the 

# atmosphere and instrument fit parameters 

rec = parCat.addNew() 

 

# info section 

rec['nCcd'] = parInfo['NCCD'] 

rec['lutFilterNames'] = lutFilterNameString 

rec['fitBands'] = fitBandString 

rec['notFitBands'] = notFitBandString 

# note these are not currently supported here. 

rec['hasExternalPwv'] = 0 

rec['hasExternalTau'] = 0 

 

# parameter section 

 

scalarNames = ['parRetrievedLnPwvScale', 'parRetrievedLnPwvOffset'] 

 

arrNames = ['parAlpha', 'parO3', 'parLnTauIntercept', 'parLnTauSlope', 

'parLnPwvIntercept', 'parLnPwvSlope', 'parLnPwvQuadratic', 

'parQeSysIntercept', 'compQeSysSlope', 

'parRetrievedLnPwvNightlyOffset', 'compAperCorrPivot', 

'parFilterOffset', 'parFilterOffsetFitFlag', 

'compAbsThroughput', 'compRefOffset', 'compRefSigma', 

'compMirrorChromaticity', 'mirrorChromaticityPivot', 

'compAperCorrSlope', 'compAperCorrSlopeErr', 'compAperCorrRange', 

'compModelErrExptimePivot', 'compModelErrFwhmPivot', 

'compModelErrSkyPivot', 'compModelErrPars', 

'compExpGray', 'compVarGray', 'compNGoodStarPerExp', 'compSigFgcm', 

'compSigmaCal', 

'compRetrievedLnPwv', 'compRetrievedLnPwvRaw', 'compRetrievedLnPwvFlag', 

'compRetrievedTauNight'] 

 

for scalarName in scalarNames: 

rec[scalarName] = pars[scalarName.upper()] 

 

for arrName in arrNames: 

rec[arrName][:] = np.atleast_1d(pars[0][arrName.upper()])[:] 

 

# superstar section 

rec['superstarSize'][:] = parSuperStarFlat.shape 

rec['superstar'][:] = parSuperStarFlat.flatten() 

 

return parCat 

 

def _makeFlagStarSchema(self): 

""" 

Make the flagged-stars schema 

 

Returns 

------- 

flagStarSchema: `lsst.afw.table.Schema` 

""" 

 

flagStarSchema = afwTable.Schema() 

 

flagStarSchema.addField('objId', type=np.int32, doc='FGCM object id') 

flagStarSchema.addField('objFlag', type=np.int32, doc='FGCM object flag') 

 

return flagStarSchema 

 

def _makeFlagStarCat(self, flagStarSchema, flagStarStruct): 

""" 

Make the flagged star catalog for persistence 

 

Parameters 

---------- 

flagStarSchema: `lsst.afw.table.Schema` 

Flagged star schema 

flagStarStruct: `numpy.ndarray` 

Flagged star structure from fgcm 

 

Returns 

------- 

flagStarCat: `lsst.afw.table.BaseCatalog` 

Flagged star catalog for persistence 

""" 

 

flagStarCat = afwTable.BaseCatalog(flagStarSchema) 

flagStarCat.reserve(flagStarStruct.size) 

for i in range(flagStarStruct.size): 

flagStarCat.addNew() 

 

flagStarCat['objId'][:] = flagStarStruct['OBJID'] 

flagStarCat['objFlag'][:] = flagStarStruct['OBJFLAG'] 

 

return flagStarCat