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

from builtins import zip 

from builtins import range 

import numpy as np 

 

from .baseMetric import BaseMetric 

 

__all__ = ['BaseMoMetric', 'NObsMetric', 'NObsNoSinglesMetric', 

'NNightsMetric', 'ObsArcMetric', 

'DiscoveryMetric', 'Discovery_N_ChancesMetric', 'Discovery_N_ObsMetric', 

'Discovery_TimeMetric', 'Discovery_RADecMetric', 'Discovery_EcLonLatMetric', 

'Discovery_VelocityMetric', 

'ActivityOverTimeMetric', 'ActivityOverPeriodMetric', 

'DiscoveryChancesMetric', 'MagicDiscoveryMetric', 

'HighVelocityMetric', 'HighVelocityNightsMetric', 

'LightcurveInversionMetric', 'ColorDeterminationMetric', 

'PeakVMagMetric', 'KnownObjectsMetric'] 

 

 

class BaseMoMetric(BaseMetric): 

"""Base class for the moving object metrics.""" 

 

def __init__(self, cols=None, metricName=None, units='#', badval=0, 

comment=None, childMetrics=None, 

appMagCol='appMag', appMagVCol='appMagV', m5Col='fiveSigmaDepth', 

nightCol='night', expMJDCol='expMJD', 

snrCol='SNR', visCol='vis', 

raCol='ra', decCol='dec', seeingCol='FWHMgeom', 

expTimeCol='visitExpTime', filterCol='filter'): 

# Set metric name. 

self.name = metricName 

31 ↛ 34line 31 didn't jump to line 34, because the condition on line 31 was never false if self.name is None: 

self.name = self.__class__.__name__.replace('Metric', '', 1) 

# Set badval and units, leave space for 'comment' (tied to displayDict). 

self.badval = badval 

self.units = units 

self.comment = comment 

# Set some commonly used column names. 

self.m5Col = m5Col 

self.appMagCol = appMagCol 

self.appMagVCol = appMagVCol 

self.nightCol = nightCol 

self.expMJDCol = expMJDCol 

self.snrCol = snrCol 

self.visCol = visCol 

self.raCol = raCol 

self.decCol = decCol 

self.seeingCol = seeingCol 

self.expTimeCol = expTimeCol 

self.filterCol = filterCol 

self.colsReq = [self.appMagCol, self.m5Col, 

self.nightCol, self.expMJDCol, 

self.snrCol, self.visCol] 

53 ↛ 54line 53 didn't jump to line 54, because the condition on line 53 was never true if cols is not None: 

for col in cols: 

self.colsReq.append(col) 

 

if childMetrics is None: 

try: 

59 ↛ 60,   59 ↛ 702 missed branches: 1) line 59 didn't jump to line 60, because the condition on line 59 was never true, 2) line 59 didn't jump to line 70, because the condition on line 59 was never false if not isinstance(self.childMetrics, dict): 

raise ValueError('self.childMetrics must be a dictionary (possibly empty)') 

except AttributeError: 

self.childMetrics = {} 

self.metricDtype = 'float' 

else: 

65 ↛ 66line 65 didn't jump to line 66, because the condition on line 65 was never true if not isinstance(childMetrics, dict): 

raise ValueError('childmetrics must be provided as a dictionary.') 

self.childMetrics = childMetrics 

self.metricDtype = 'object' 

 

self.shape = 1 

 

def run(self, ssoObs, orb, Hval): 

"""Calculate the metric value. 

 

Parameters 

---------- 

ssoObs: np.ndarray 

The input data to the metric (same as the parent metric). 

orb: np.ndarray 

The information about the orbit for which the metric is being calculated. 

Hval : float 

The H value for which the metric is being calculated. 

 

Returns 

------- 

float or np.ndarray or dict 

""" 

raise NotImplementedError 

 

 

class BaseChildMetric(BaseMoMetric): 

"""Base class for child metrics. 

 

Parameters 

---------- 

parentDiscoveryMetric: BaseMoMetric 

The 'parent' metric which generated the metric data used to calculate this 'child' metric. 

badval: float, opt 

Value to return when metric cannot be calculated. 

""" 

def __init__(self, parentDiscoveryMetric, badval=0, **kwargs): 

super(BaseChildMetric, self).__init__(badval=badval, **kwargs) 

self.parentMetric = parentDiscoveryMetric 

self.childMetrics = {} 

105 ↛ 106line 105 didn't jump to line 106, because the condition on line 105 was never true if 'metricDtype' in kwargs: 

self.metricDtype = kwargs['metricDtype'] 

else: 

self.metricDtype = 'float' 

 

def run(self, ssoObs, orb, Hval, metricValues): 

"""Calculate the child metric value. 

 

Parameters 

---------- 

ssoObs: np.ndarray 

The input data to the metric (same as the parent metric). 

orb: np.ndarray 

The information about the orbit for which the metric is being calculated. 

Hval : float 

The H value for which the metric is being calculated. 

metricValues : dict or np.ndarray 

The return value from the parent metric. 

 

Returns 

------- 

float 

""" 

raise NotImplementedError 

 

 

class NObsMetric(BaseMoMetric): 

""" 

Count the total number of observations where an object was 'visible'. 

""" 

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

""" 

@ snrLimit .. if snrLimit is None, this uses the _calcVis method/completeness 

if snrLimit is not None, this uses that value as a cutoff instead. 

""" 

super(NObsMetric, self).__init__(**kwargs) 

self.snrLimit = snrLimit 

 

def run(self, ssoObs, orb, Hval): 

if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

return vis.size 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

return vis.size 

 

 

class NObsNoSinglesMetric(BaseMoMetric): 

""" 

Count the number of observations for an object, but don't 

include any observations where it was a single observation on a night. 

""" 

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

super(NObsNoSinglesMetric, self).__init__(**kwargs) 

self.snrLimit = snrLimit 

 

def run(self, ssoObs, orb, Hval): 

162 ↛ 165line 162 didn't jump to line 165, because the condition on line 162 was never false if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

166 ↛ 167line 166 didn't jump to line 167, because the condition on line 166 was never true if len(vis) == 0: 

return 0 

nights = ssoObs[self.nightCol][vis] 

nights = nights.astype('int') 

ncounts = np.bincount(nights) 

nobs = ncounts[np.where(ncounts > 1)].sum() 

return nobs 

 

 

class NNightsMetric(BaseMoMetric): 

"""Count the number of distinct nights an object is observed. 

""" 

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

""" 

@ snrLimit : if SNRlimit is None, this uses _calcVis method/completeness 

else if snrLimit is not None, it uses that value as a cutoff. 

""" 

super(NNightsMetric, self).__init__(**kwargs) 

self.snrLimit = snrLimit 

 

def run(self, ssoObs, orb, Hval): 

if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

191 ↛ 192line 191 didn't jump to line 192, because the condition on line 191 was never true if len(vis) == 0: 

return 0 

nights = len(np.unique(ssoObs[self.nightCol][vis])) 

return nights 

 

class ObsArcMetric(BaseMoMetric): 

"""Calculate the difference between the first and last observation of an object. 

""" 

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

super(ObsArcMetric, self).__init__(**kwargs) 

self.snrLimit = snrLimit 

 

def run(self, ssoObs, orb, Hval): 

if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

208 ↛ 209line 208 didn't jump to line 209, because the condition on line 208 was never true if len(vis) == 0: 

return 0 

arc = ssoObs[self.expMJDCol][vis].max() - ssoObs[self.expMJDCol][vis].min() 

return arc 

 

class DiscoveryMetric(BaseMoMetric): 

"""Identify the discovery opportunities for an object.""" 

def __init__(self, nObsPerNight=2, 

tMin=5./60.0/24.0, tMax=90./60./24.0, 

nNightsPerWindow=3, tWindow=15, 

snrLimit=None, badval=None, **kwargs): 

""" 

@ nObsPerNight = number of observations per night required for tracklet 

@ tMin = min time start/finish for the tracklet (days) 

@ tMax = max time start/finish for the tracklet (days) 

@ nNightsPerWindow = number of nights with observations required for track 

@ tWindow = max number of nights in track (days) 

@ snrLimit .. if snrLimit is None then uses 'completeness' calculation in 'vis' column. 

.. if snrLimit is not None, then uses this SNR value as a cutoff. 

""" 

# Define anything needed by the child metrics first. 

self.snrLimit = snrLimit 

self.childMetrics = {'N_Chances': Discovery_N_ChancesMetric(self), 

'N_Obs': Discovery_N_ObsMetric(self), 

'Time': Discovery_TimeMetric(self), 

'RADec': Discovery_RADecMetric(self), 

'EcLonLat': Discovery_EcLonLatMetric(self)} 

# Set up for inheriting from __init__. 

super(DiscoveryMetric, self).__init__(childMetrics=self.childMetrics, badval=badval, **kwargs) 

# Define anything needed for this metric. 

self.nObsPerNight = nObsPerNight 

self.tMin = tMin 

self.tMax = tMax 

self.nNightsPerWindow = nNightsPerWindow 

self.tWindow = tWindow 

 

def run(self, ssoObs, orb, Hval): 

245 ↛ 248line 245 didn't jump to line 248, because the condition on line 245 was never false if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

249 ↛ 250line 249 didn't jump to line 250, because the condition on line 249 was never true if len(vis) == 0: 

return self.badval 

# Identify discovery opportunities. 

# Identify visits where the 'night' changes. 

visSort = np.argsort(ssoObs[self.expMJDCol][vis]) 

nights = ssoObs[self.nightCol][vis][visSort] 

#print 'all nights', nights 

n = np.unique(nights) 

# Identify all the indexes where the night changes in value. 

nIdx = np.searchsorted(nights, n) 

#print 'nightchanges', nights[nIdx] 

# Count the number of observations per night (except last night) 

obsPerNight = (nIdx - np.roll(nIdx, 1))[1:] 

# Add the number of observations on the last night. 

obsLastNight = np.array([len(nights) - nIdx[-1]]) 

obsPerNight = np.concatenate((obsPerNight, obsLastNight)) 

# Find the nights with more than nObsPerNight. 

nWithXObs = n[np.where(obsPerNight >= self.nObsPerNight)] 

nIdxMany = np.searchsorted(nights, nWithXObs) 

nIdxManyEnd = np.searchsorted(nights, nWithXObs, side='right') - 1 

# Check that nObsPerNight observations are within tMin/tMax 

timesStart = ssoObs[self.expMJDCol][vis][visSort][nIdxMany] 

timesEnd = ssoObs[self.expMJDCol][vis][visSort][nIdxManyEnd] 

# Identify the nights with 'clearly good' observations. 

good = np.where((timesEnd - timesStart >= self.tMin) & (timesEnd - timesStart <= self.tMax), 1, 0) 

# Identify the nights where we need more investigation (a subset of the visits may be within the interval). 

check = np.where((good==0) & (nIdxManyEnd + 1 - nIdxMany > self.nObsPerNight) & (timesEnd-timesStart > self.tMax))[0] 

for i, j, c in zip(visSort[nIdxMany][check], visSort[nIdxManyEnd][check], check): 

t = ssoObs[self.expMJDCol][vis][visSort][i:j+1] 

dtimes = (np.roll(t, 1- self.nObsPerNight) - t)[:-1] 

tidx = np.where((dtimes >= self.tMin) & (dtimes <= self.tMax))[0] 

280 ↛ 276line 280 didn't jump to line 276, because the condition on line 280 was never false if len(tidx) > 0: 

good[c] = 1 

# 'good' provides mask for observations which could count as 'good to make tracklets' against ssoObs[visSort][nIdxMany] 

# Now identify tracklets which can make tracks. 

goodIdx = visSort[nIdxMany][good == 1] 

goodIdxEnds = visSort[nIdxManyEnd][good == 1] 

#print 'good tracklets', nights[goodIdx] 

287 ↛ 288line 287 didn't jump to line 288, because the condition on line 287 was never true if len(goodIdx) < self.nNightsPerWindow: 

return self.badval 

deltaNights = np.roll(ssoObs[self.nightCol][vis][goodIdx], 1 - self.nNightsPerWindow) - ssoObs[self.nightCol][vis][goodIdx] 

# Identify the index in ssoObs[vis][goodIdx] (sorted by expMJD) where the discovery opportunity starts. 

startIdxs = np.where((deltaNights >= 0) & (deltaNights <= self.tWindow))[0] 

# Identify the index where the discovery opportunity ends. 

endIdxs = np.zeros(len(startIdxs), dtype='int') 

for i, sIdx in enumerate(startIdxs): 

inWindow = np.where(ssoObs[self.nightCol][vis][goodIdx] - ssoObs[self.nightCol][vis][goodIdx][sIdx] <= self.tWindow)[0] 

endIdxs[i] = np.array([inWindow.max()]) 

# Convert back to index based on ssoObs[vis] (sorted by expMJD). 

startIdxs = goodIdx[startIdxs] 

endIdxs = goodIdxEnds[endIdxs] 

#print 'start', startIdxs, nights[startIdxs]#, orb['objId'], Hval 

#print 'end', endIdxs, nights[endIdxs]#, orb['objId'], Hval 

return {'start':startIdxs, 'end':endIdxs, 'trackletNights':ssoObs[self.nightCol][vis][goodIdx]} 

 

 

class Discovery_N_ChancesMetric(BaseChildMetric): 

"""Child metric to be used with DiscoveryMetric. 

Calculates total number of discovery opportunities in a window between nightStart / nightEnd. 

""" 

def __init__(self, parentDiscoveryMetric, nightStart=None, nightEnd=None, badval=0, **kwargs): 

super(Discovery_N_ChancesMetric, self).__init__(parentDiscoveryMetric, badval=badval, **kwargs) 

311 ↛ 314line 311 didn't jump to line 314, because the condition on line 311 was never false if nightStart is None: 

self.nightStart = 0 

else: 

self.nightStart = nightStart 

self.nightEnd = nightEnd 

self.snrLimit = parentDiscoveryMetric.snrLimit 

# Update the metric name to use the nightStart/nightEnd values, if an overriding name is not given. 

318 ↛ exitline 318 didn't return from function '__init__', because the condition on line 318 was never false if 'metricName' not in kwargs: 

319 ↛ 320line 319 didn't jump to line 320, because the condition on line 319 was never true if nightStart is not None: 

self.name = self.name + '_n%d' % (nightStart) 

321 ↛ 322line 321 didn't jump to line 322, because the condition on line 321 was never true if nightEnd is not None: 

self.name = self.name + '_n%d' % (nightEnd) 

 

def run(self, ssoObs, orb, Hval, metricValues): 

"""Return the number of different discovery chances we had for each object/H combination. 

""" 

327 ↛ 330line 327 didn't jump to line 330, because the condition on line 327 was never false if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

331 ↛ 332line 331 didn't jump to line 332, because the condition on line 331 was never true if len(vis) == 0: 

return self.badval 

visSort = np.argsort(ssoObs[self.expMJDCol][vis]) 

nights = ssoObs[self.nightCol][vis][visSort] 

startNights = nights[metricValues['start']] 

endNights = nights[metricValues['end']] 

337 ↛ 340line 337 didn't jump to line 340, because the condition on line 337 was never false if self.nightEnd is None: 

valid = np.where(startNights >= self.nightStart)[0] 

else: 

valid = np.where((startNights >= self.nightStart) & (endNights <= self.nightEnd))[0] 

return len(valid) 

 

 

class Discovery_N_ObsMetric(BaseChildMetric): 

"""Calculates the number of observations in the i-th discovery track. 

""" 

def __init__(self, parentDiscoveryMetric, i=0, badval=0, **kwargs): 

super(Discovery_N_ObsMetric, self).__init__(parentDiscoveryMetric, badval=badval, **kwargs) 

# The number of the discovery chance to use. 

self.i = i 

 

def run(self, ssoObs, orb, Hval, metricValues): 

353 ↛ 354line 353 didn't jump to line 354, because the condition on line 353 was never true if self.i >= len(metricValues['start']): 

return 0 

startIdx = metricValues['start'][self.i] 

endIdx = metricValues['end'][self.i] 

nobs = endIdx - startIdx 

return nobs 

 

 

class Discovery_TimeMetric(BaseChildMetric): 

"""Returns the time of the i-th discovery opportunity. 

""" 

def __init__(self, parentDiscoveryMetric, i=0, tStart=None, badval=-999, **kwargs): 

super(Discovery_TimeMetric, self).__init__(parentDiscoveryMetric, badval=badval, **kwargs) 

self.i = i 

self.tStart = tStart 

self.snrLimit = parentDiscoveryMetric.snrLimit 

 

def run(self, ssoObs, orb, Hval, metricValues): 

371 ↛ 372line 371 didn't jump to line 372, because the condition on line 371 was never true if self.i>=len(metricValues['start']): 

return self.badval 

373 ↛ 376line 373 didn't jump to line 376, because the condition on line 373 was never false if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

377 ↛ 378line 377 didn't jump to line 378, because the condition on line 377 was never true if len(vis) == 0: 

return self.badval 

visSort = np.argsort(ssoObs[self.expMJDCol][vis]) 

times = ssoObs[self.expMJDCol][vis][visSort] 

startIdx = metricValues['start'][self.i] 

tDisc = times[startIdx] 

383 ↛ 384line 383 didn't jump to line 384, because the condition on line 383 was never true if self.tStart is not None: 

tDisc = tDisc - self.tStart 

return tDisc 

 

 

class Discovery_RADecMetric(BaseChildMetric): 

"""Returns the RA/Dec of the i-th discovery opportunity. 

""" 

def __init__(self, parentDiscoveryMetric, i=0, badval=None, **kwargs): 

super(Discovery_RADecMetric, self).__init__(parentDiscoveryMetric, badval=badval, **kwargs) 

self.i = i 

self.snrLimit = parentDiscoveryMetric.snrLimit 

self.metricDtype = 'object' 

 

def run(self, ssoObs, orb, Hval, metricValues): 

398 ↛ 399line 398 didn't jump to line 399, because the condition on line 398 was never true if self.i>=len(metricValues['start']): 

return self.badval 

400 ↛ 403line 400 didn't jump to line 403, because the condition on line 400 was never false if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

404 ↛ 405line 404 didn't jump to line 405, because the condition on line 404 was never true if len(vis) == 0: 

return self.badval 

visSort = np.argsort(ssoObs[self.expMJDCol][vis]) 

ra = ssoObs[self.raCol][vis][visSort] 

dec = ssoObs[self.decCol][vis][visSort] 

startIdx = metricValues['start'][self.i] 

return (ra[startIdx], dec[startIdx]) 

 

class Discovery_EcLonLatMetric(BaseChildMetric): 

"""Returns the ecliptic lon/lat and solar elongation (in degrees) of the i-th discovery opportunity. 

""" 

def __init__(self, parentDiscoveryMetric, i=0, badval=None, **kwargs): 

super(Discovery_EcLonLatMetric, self).__init__(parentDiscoveryMetric, badval=badval, **kwargs) 

self.i = i 

self.snrLimit = parentDiscoveryMetric.snrLimit 

self.metricDtype = 'object' 

 

def run(self, ssoObs, orb, Hval, metricValues): 

422 ↛ 423line 422 didn't jump to line 423, because the condition on line 422 was never true if self.i>=len(metricValues['start']): 

return self.badval 

424 ↛ 427line 424 didn't jump to line 427, because the condition on line 424 was never false if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

428 ↛ 429line 428 didn't jump to line 429, because the condition on line 428 was never true if len(vis) == 0: 

return self.badval 

visSort = np.argsort(ssoObs[self.expMJDCol][vis]) 

ecLon = ssoObs['ecLon'][vis][visSort] 

ecLat = ssoObs['ecLat'][vis][visSort] 

solarElong = ssoObs['solarElong'][vis][visSort] 

startIdx = metricValues['start'][self.i] 

return (ecLon[startIdx], ecLat[startIdx], solarElong[startIdx]) 

 

class Discovery_VelocityMetric(BaseChildMetric): 

"""Returns the sky velocity of the i-th discovery opportunity. 

""" 

def __init__(self, parentDiscoveryMetric, i=0, badval=-999, **kwargs): 

super(Discovery_VelocityMetric, self).__init__(parentDiscoveryMetric, badval=badval, **kwargs) 

self.i = i 

self.snrLimit = parentDiscoveryMetric.snrLimit 

 

def run(self, ssoObs, orb, Hval, metricValues): 

if self.i>=len(metricValues['start']): 

return self.badval 

if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

if len(vis) == 0: 

return self.badval 

visSort = np.argsort(ssoObs[self.expMJDCol][vis]) 

velocity = ssoObs['velocity'][vis][visSort] 

startIdx = metricValues['start'][self.i] 

return velocity[startIdx] 

 

class ActivityOverTimeMetric(BaseMoMetric): 

""" 

Count the time periods where we would have a chance to detect activity on 

a moving object. 

Splits observations into time periods set by 'window', then looks for observations within each window, 

and reports what fraction of the total windows receive 'nObs' visits. 

""" 

def __init__(self, window, snrLimit=5, surveyYears=10.0, metricName=None, **kwargs): 

if metricName is None: 

metricName = 'Chance of detecting activity lasting %.0f days' %(window) 

super(ActivityOverTimeMetric, self).__init__(metricName=metricName, **kwargs) 

self.snrLimit = snrLimit 

self.window = window 

self.surveyYears = surveyYears 

self.windowBins = np.arange(0, self.surveyYears*365 + self.window/2.0, self.window) 

self.nWindows = len(self.windowBins) 

self.units = '%.1f Day Windows' %(self.window) 

 

def run(self, ssoObs, orb, Hval): 

# For cometary activity, expect activity at the same point in its orbit at the same time, mostly 

# For collisions, expect activity at random times 

if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

if len(vis) == 0: 

return self.badval 

n, b = np.histogram(ssoObs[vis][self.nightCol], bins=self.windowBins) 

activityWindows = np.where(n>0)[0].size 

return activityWindows / float(self.nWindows) 

 

 

class ActivityOverPeriodMetric(BaseMoMetric): 

""" 

Count the fraction of the orbit (when split into nBins) that receive 

observations, in order to have a chance to detect activity. 

""" 

def __init__(self, binsize, snrLimit=5, 

qCol='q', eCol='e', tPeriCol='tPeri', metricName=None, **kwargs): 

""" 

@ binsize : size of orbit slice, in degrees. 

""" 

if metricName is None: 

metricName = 'Chance of detecting activity in %.1f of the orbit' %(window) 

super(ActivityOverPeriodMetric, self).__init__(metricName=metricName, **kwargs) 

self.qCol = qCol 

self.eCol = eCol 

self.tPeriCol = tPeriCol 

self.snrLimit = snrLimit 

self.binsize = np.radians(binsize) 

self.anomalyBins = np.arange(0, 2 * np.pi + self.binsize / 2.0, self.binsize) 

self.nBins = len(self.anomalyBins) 

self.units = '%.1f deg' %(np.degrees(self.binsize)) 

 

def run(self, ssoObs, orb, Hval): 

# For cometary activity, expect activity at the same point in its orbit at the same time, mostly 

# For collisions, expect activity at random times 

a = orb[self.qCol] / (1 - orb[self.eCol]) 

period = np.power(a, 3./2.) * 365.25 

anomaly = ((ssoObs[self.expMJDCol] - orb[self.tPeriCol]) / period) % (2 * np.pi) 

if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

if len(vis) == 0: 

return self.badval 

n, b = np.histogram(anomaly[vis], bins=self.anomalyBins) 

activityWindows = np.where(n>0)[0].size 

return activityWindows / float(self.nBins) 

 

 

class DiscoveryChancesMetric(BaseMoMetric): 

"""Count the number of discovery opportunities for an object. 

 

Superseded by the DiscoveryMetric + NChances child metric. 

""" 

def __init__(self, nObsPerNight=2, tNight=90./60./24., 

nNightsPerWindow=3, tWindow=15, snrLimit=None, 

**kwargs): 

""" 

@ nObsPerNight = number of observations per night required for tracklet 

@ tNight = max time start/finish for the tracklet (days) 

@ nNightsPerWindow = number of nights with observations required for track 

@ tWindow = max number of nights in track (days) 

@ snrLimit .. if snrLimit is None then uses 'completeness' calculation, 

.. if snrLimit is not None, then uses this value as a cutoff. 

""" 

super(DiscoveryChancesMetric, self).__init__(**kwargs) 

self.snrLimit = snrLimit 

self.nObsPerNight = nObsPerNight 

self.tNight = tNight 

self.nNightsPerWindow = nNightsPerWindow 

self.tWindow = tWindow 

self.gamma = 0.038 

self.sigma = 0.12 

self.badval = 0 

 

def run(self, ssoObs, orb, Hval): 

"""SsoObs = Dataframe, orb=Dataframe, Hval=single number.""" 

# Calculate visibility for this orbit at this H. 

559 ↛ 562line 559 didn't jump to line 562, because the condition on line 559 was never false if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

563 ↛ 564line 563 didn't jump to line 564, because the condition on line 563 was never true if len(vis) == 0: 

return self.badval 

else: 

# Now to identify where observations meet the timing requirements. 

# Identify visits where the 'night' changes. 

visSort = np.argsort(ssoObs[self.expMJDCol][vis]) 

nights = ssoObs[self.nightCol][vis][visSort] 

#print 'all nights', nights 

n = np.unique(nights) 

# Identify all the indexes where the night changes (swap from one night to next) 

nIdx = np.searchsorted(nights, n) 

# Count the number of observations per night (except last night) 

obsPerNight = (nIdx - np.roll(nIdx, 1))[1:] 

# Add the number of observations on the last night. 

obsLastNight = np.array([len(nights) - nIdx[-1]]) 

obsPerNight = np.concatenate((obsPerNight, obsLastNight)) 

# Find the nights with at least nObsPerNight visits. 

nWithXObs = n[np.where(obsPerNight >= self.nObsPerNight)] 

nIdxMany = np.searchsorted(nights, nWithXObs) 

nIdxManyEnd = np.searchsorted(nights, nWithXObs, side='right') - 1 

# Check that nObsPerNight observations are within tNight 

timesStart = ssoObs[self.expMJDCol][vis][visSort][nIdxMany] 

timesEnd = ssoObs[self.expMJDCol][vis][visSort][nIdxManyEnd] 

# Identify the nights with 'clearly good' observations. 

good = np.where(timesEnd - timesStart <= self.tNight, 1, 0) 

# Identify the nights where we need more investigation 

# (a subset of the visits may be within the interval). 

check = np.where((good==0) & (nIdxManyEnd + 1 - nIdxMany > self.nObsPerNight) & 

(timesEnd - timesStart > self.tNight))[0] 

for i, j, c in zip(visSort[nIdxMany][check], visSort[nIdxManyEnd][check], check): 

t = ssoObs[self.expMJDCol][vis][visSort][i:j+1] 

dtimes = (np.roll(t, 1- self.nObsPerNight) - t)[:-1] 

595 ↛ 592line 595 didn't jump to line 592, because the condition on line 595 was never false if np.any(dtimes <= self.tNight): 

good[c] = 1 

# 'good' provides mask for observations which could count as 'good to make tracklets' 

# against ssoObs[visSort][nIdxMany] 

# Now identify tracklets which can make tracks. 

goodIdx = visSort[nIdxMany][good == 1] 

#print 'good tracklet nights', ssoObs[self.nightCol][goodIdx] 

# Now (with indexes of start of 'good' nights with nObsPerNight within tNight), 

# look at the intervals between 'good' nights (for tracks) 

604 ↛ 605line 604 didn't jump to line 605, because the condition on line 604 was never true if len(goodIdx) < self.nNightsPerWindow: 

discoveryChances = self.badval 

else: 

dnights = (np.roll(ssoObs[self.nightCol][vis][goodIdx], 1-self.nNightsPerWindow) - 

ssoObs[self.nightCol][vis][goodIdx]) 

discoveryChances = len(np.where((dnights >= 0) & (dnights <= self.tWindow))[0]) 

return discoveryChances 

 

 

class MagicDiscoveryMetric(BaseMoMetric): 

"""Count the number of discovery opportunities with very good software. 

""" 

def __init__(self, nObs=6, tWindow=60, snrLimit=None, **kwargs): 

""" 

@ nObs = the total number of observations required for 'discovery' 

@ tWindow = the timespan of the discovery window. 

@ snrLimit .. if snrLimit is None then uses 'completeness' calculation, 

.. if snrLimit is not None, then uses this value as a cutoff. 

""" 

super(MagicDiscoveryMetric, self).__init__(**kwargs) 

self.snrLimit = snrLimit 

self.nObs = nObs 

self.tWindow = tWindow 

self.badval = 0 

 

def run(self, ssoObs, orb, Hval): 

"""SsoObs = Dataframe, orb=Dataframe, Hval=single number.""" 

# Calculate visibility for this orbit at this H. 

632 ↛ 635line 632 didn't jump to line 635, because the condition on line 632 was never false if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

636 ↛ 637line 636 didn't jump to line 637, because the condition on line 636 was never true if len(vis) == 0: 

return self.badval 

tNights = np.sort(ssoObs[self.nightCol][vis]) 

deltaNights = np.roll(tNights, 1-self.nObs) - tNights 

nDisc = np.where((deltaNights < self.tWindow) & (deltaNights >= 0))[0].size 

return nDisc 

 

class HighVelocityMetric(BaseMoMetric): 

""" 

Count the number of times an asteroid is observed with a velocity high enough to make it appear 

trailed by a factor of (psfFactor)*PSF - i.e. velocity >= psfFactor * seeing / visitExpTime. 

Simply counts the total number of observations with high velocity. 

""" 

def __init__(self, psfFactor=2.0, snrLimit=None, velocityCol='velocity', **kwargs): 

""" 

@ psfFactor = factor to multiply seeing/visitExpTime by 

(velocity(deg/day) >= 24*psfFactor*seeing(")/visitExptime(s)) 

""" 

super(HighVelocityMetric, self).__init__(**kwargs) 

self.velocityCol = velocityCol 

self.snrLimit = snrLimit 

self.psfFactor = psfFactor 

self.badval = 0 

 

def run(self, ssoObs, orb, Hval): 

661 ↛ 664line 661 didn't jump to line 664, because the condition on line 661 was never false if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

665 ↛ 666line 665 didn't jump to line 666, because the condition on line 665 was never true if len(vis) == 0: 

return self.badval 

highVelocityObs = np.where(ssoObs[self.velocityCol][vis] >= 

(24.* self.psfFactor * ssoObs[self.seeingCol][vis] / 

ssoObs[self.expTimeCol][vis]))[0] 

return highVelocityObs.size 

 

class HighVelocityNightsMetric(BaseMoMetric): 

""" 

Count the number of times an asteroid is observed with a velocity high enough to make it appear 

trailed by a factor of (psfFactor)*PSF - i.e. velocity >= psfFactor * seeing / visitExpTime, 

where we require nObsPerNight observations within a given night. 

Counts the total number of nights with enough high-velocity observations. 

""" 

def __init__(self, psfFactor=2.0, nObsPerNight=2, snrLimit=None, velocityCol='velocity', **kwargs): 

""" 

@ psfFactor = factor to multiply seeing/visitExpTime by 

(velocity(deg/day) >= 24*psfFactor*seeing(")/visitExptime(s)) 

@ nObsPerNight = number of observations required per night 

""" 

super(HighVelocityNightsMetric, self).__init__(**kwargs) 

self.velocityCol = velocityCol 

self.snrLimit = snrLimit 

self.psfFactor = psfFactor 

self.nObsPerNight = nObsPerNight 

self.badval = 0 

 

def run(self, ssoObs, orb, Hval): 

693 ↛ 696line 693 didn't jump to line 696, because the condition on line 693 was never false if self.snrLimit is not None: 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

else: 

vis = np.where(ssoObs[self.visCol] > 0)[0] 

697 ↛ 698line 697 didn't jump to line 698, because the condition on line 697 was never true if len(vis) == 0: 

return self.badval 

highVelocityObs = np.where(ssoObs[self.velocityCol][vis] >= 

(24. * self.psfFactor * ssoObs[self.seeingCol][vis] 

/ ssoObs[self.expTimeCol][vis]))[0] 

if len(highVelocityObs) == 0: 

return self.badval 

nights = ssoObs[self.nightCol][vis][highVelocityObs] 

n = np.unique(nights) 

nIdx = np.searchsorted(nights, n) 

# Count the number of observations per night (except last night) 

obsPerNight = (nIdx - np.roll(nIdx, 1))[1:] 

# Add the number of observations on the last night. 

obsLastNight = np.array([len(nights) - nIdx[-1]]) 

obsPerNight = np.concatenate((obsPerNight, obsLastNight)) 

# Find the nights with at least nObsPerNight visits 

# (this is already looking at only high velocity observations). 

nWithXObs = n[np.where(obsPerNight >= self.nObsPerNight)] 

return nWithXObs.size 

 

 

class LightcurveInversionMetric(BaseMoMetric): 

"""Identify objects which would have observations suitable to do lightcurve inversion. 

 

This is roughly defined as objects which have more than nObs observations with SNR greater than snrLimit, 

within nDays. 

""" 

def __init__(self, nObs=100, snrLimit=20., nDays=5*365, **kwargs): 

super(LightcurveInversionMetric, self).__init__(**kwargs) 

self.nObs = nObs 

self.snrLimit = snrLimit 

self.nDays = nDays 

self.badval = -666 

 

def run(self, ssoObs, orb, Hval): 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

if len(vis) < self.nObs: 

return 0 

nights = ssoObs[self.nightCol][vis] 

ncounts = np.bincount(nights) 

# ncounts covers the range = np.arange(nights.min(), nights.max() + 1, 1) 

if self.nDays % 2 == 0: 

lWindow = self.nDays / 2 

rWindow = self.nDays / 2 

else: 

lWindow = int(self.nDays / 2) 

rWindow = int(self.nDays / 2) + 1 

found = 0 

for i in range(lWindow, len(ncounts) - rWindow): 

nobs = ncounts[i - lWindow:i + rWindow].sum() 

if nobs > self.nObs: 

found = 1 

break 

return found 

 

 

class ColorDeterminationMetric(BaseMoMetric): 

"""Identify objects which could have observations suitable to determine colors. 

 

This is roughly defined as objects which have more than nPairs pairs of observations 

with SNR greater than snrLimit, in bands bandOne and bandTwo, within nHours. 

""" 

def __init__(self, nPairs=1, snrLimit=10, nHours=2.0, bOne='g', bTwo='r', **kwargs): 

super(ColorDeterminationMetric, self).__init__(**kwargs) 

self.nPairs = nPairs 

self.snrLimit = snrLimit 

self.nHours = nHours 

self.bOne = bOne 

self.bTwo = bTwo 

self.badval = -666 

 

def run(self, ssoObs, orb, Hval): 

vis = np.where(ssoObs[self.snrCol] >= self.snrLimit)[0] 

if len(vis) < self.nPairs * 2: 

return 0 

bOneObs = np.where(ssoObs[self.filterCol][vis] == self.bOne)[0] 

bTwoObs = np.where(ssoObs[self.filterCol][vis] == self.bTwo)[0] 

timesbOne = ssoObs[self.expMJDCol][vis][bOneObs] 

timesbTwo = ssoObs[self.expMJDCol][vis][bTwoObs] 

if len(timesbOne) == 0 or len(timesbTwo) == 0: 

return 0 

dTime = self.nHours / 24.0 

# Calculate the time between the closest pairs of observations. 

inOrder = np.searchsorted(timesbOne, timesbTwo, 'right') 

inOrder = np.where(inOrder - 1 > 0, inOrder - 1, 0) 

dtPairs = timesbTwo - timesbOne[inOrder] 

if len(np.where(dtPairs < dTime)[0]) >= self.nPairs: 

found = 1 

else: 

found = 0 

return found 

 

 

class PeakVMagMetric(BaseMoMetric): 

"""Pull out the peak V magnitude of all observations of the object. 

""" 

def __init__(self, **kwargs): 

super(PeakVMagMetric, self).__init__(**kwargs) 

 

def run(self, ssoObs, orb, Hval): 

peakVmag = np.min(ssoObs[self.appMagVCol]) 

return peakVmag 

 

 

class KnownObjectsMetric(BaseMoMetric): 

"""Identify objects which could be classified as 'previously known' based on their peak V magnitude, 

returning the time at which each first reached that peak V magnitude. 

 

Parameters 

----------- 

elongThresh : float, opt 

The cutoff in solar elongation to consider an object 'visible'. Default 60 deg. 

vMagThresh1 : float, opt 

The magnitude threshhold for previously known objects. Default 20.0. 

This is calibrated using NEOs discovered in the last 15 years and assuming a current 25% completeness. 

vMagThresh2 : float, opt 

The magnitude threshhold for previously known objects. Default 22.0. 

This is based on assuming PS and other surveys will be efficient down to V=22. 

tSwitch : float, opt 

The time to switch between evaluating against vMagThresh1 to vMagThresh2. Default 57023 (start of 2015). 

""" 

def __init__(self, elongThresh=60., vMagThresh1=20.0, vMagThresh2=22.0, tSwitch=57023, 

elongCol='Elongation', expMJDCol='MJD(UTC)', **kwargs): 

super(KnownObjectsMetric, self).__init__(**kwargs) 

self.elongThresh = elongThresh 

self.elongCol = elongCol 

self.vMagThresh1 = vMagThresh1 

self.vMagThresh2 = vMagThresh2 

self.tSwitch = tSwitch 

self.expMJDCol = expMJDCol 

 

def run(self, ssoObs, orb, Hval): 

visible = np.where(ssoObs[self.elongCol] >= self.elongThresh, 1, 0) 

# Discovery before tSwitch? 

earlyObs = np.where((ssoObs[self.expMJDCol] < self.tSwitch) & visible)[0] 

overPeak = np.where(ssoObs[self.appMagVCol][earlyObs] <= self.vMagThresh1)[0] 

if len(overPeak) > 0: 

discoveryTime = ssoObs[self.expMJDCol][earlyObs][overPeak].min() 

else: 

lateObs = np.where((ssoObs[self.expMJDCol] >= self.tSwitch) & visible)[0] 

overPeak = np.where(ssoObs[self.appMagVCol][lateObs] <= self.vMagThresh2)[0] 

if len(overPeak) > 0: 

discoveryTime = ssoObs[self.expMJDCol][lateObs][overPeak].min() 

else: 

discoveryTime = self.badval 

return discoveryTime