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

#!/usr/bin/env python 

 

# 

# LSST Data Management System 

# Copyright 2016 LSST Corporation. 

# 

# This product includes software developed by the 

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

# 

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

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

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

# (at your option) any later version. 

# 

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

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

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

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

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

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

# 

from past.builtins import basestring 

import sys 

import pickle 

import importlib 

import os 

import urllib.parse 

import glob 

import shutil 

import yaml 

 

from . import (LogicalLocation, Persistence, Policy, StorageList, 

StorageInterface, Storage, ButlerLocation, 

NoRepositroyAtRoot, RepositoryCfg, doImport) 

from lsst.log import Log 

import lsst.pex.policy as pexPolicy 

from .safeFileIo import SafeFilename, safeMakeDir 

 

 

__all__ = ["PosixStorage"] 

 

 

class PosixStorage(StorageInterface): 

"""Defines the interface for a storage location on the local filesystem. 

 

Parameters 

---------- 

uri : string 

URI or path that is used as the storage location. 

create : bool 

If True a new repository will be created at the root location if it 

does not exist. If False then a new repository will not be created. 

 

Raises 

------ 

NoRepositroyAtRoot 

If create is False and a repository does not exist at the root 

specified by uri then NoRepositroyAtRoot is raised. 

""" 

 

def __init__(self, uri, create): 

self.log = Log.getLogger("daf.persistence.butler") 

self.root = self._pathFromURI(uri) 

if self.root and not os.path.exists(self.root): 

67 ↛ 68line 67 didn't jump to line 68, because the condition on line 67 was never true if not create: 

raise NoRepositroyAtRoot("No repository at {}".format(uri)) 

safeMakeDir(self.root) 

 

self.persistence = self.getPersistence() 

 

@staticmethod 

def getPersistence(): 

# Always use an empty Persistence policy until we can get rid of it 

persistencePolicy = pexPolicy.Policy() 

return Persistence.getPersistence(persistencePolicy) 

 

def __repr__(self): 

return 'PosixStorage(root=%s)' % self.root 

 

@staticmethod 

def _pathFromURI(uri): 

"""Get the path part of the URI""" 

return urllib.parse.urlparse(uri).path 

 

@staticmethod 

def relativePath(fromPath, toPath): 

"""Get a relative path from a location to a location. 

 

Parameters 

---------- 

fromPath : string 

A path at which to start. It can be a relative path or an 

absolute path. 

toPath : string 

A target location. It can be a relative path or an absolute path. 

 

Returns 

------- 

string 

A relative path that describes the path from fromPath to toPath. 

""" 

fromPath = os.path.realpath(fromPath) 

return os.path.relpath(toPath, fromPath) 

 

@staticmethod 

def absolutePath(fromPath, relativePath): 

"""Get an absolute path for the path from fromUri to toUri 

 

Parameters 

---------- 

fromPath : the starting location 

A location at which to start. It can be a relative path or an 

absolute path. 

relativePath : the location relative to fromPath 

A relative path. 

 

Returns 

------- 

string 

Path that is an absolute path representation of fromPath + 

relativePath, if one exists. If relativePath is absolute or if 

fromPath is not related to relativePath then relativePath will be 

returned. 

""" 

if os.path.isabs(relativePath): 

return relativePath 

fromPath = os.path.realpath(fromPath) 

return os.path.normpath(os.path.join(fromPath, relativePath)) 

 

@staticmethod 

def getRepositoryCfg(uri): 

"""Get a persisted RepositoryCfg 

 

Parameters 

---------- 

uri : URI or path to a RepositoryCfg 

Description 

 

Returns 

------- 

A RepositoryCfg instance or None 

""" 

storage = Storage.makeFromURI(uri) 

location = ButlerLocation(pythonType=RepositoryCfg, 

cppType=None, 

storageName=None, 

locationList='repositoryCfg.yaml', 

dataId={}, 

mapper=None, 

storage=storage, 

usedDataId=None, 

datasetType=None) 

return storage.read(location) 

 

@staticmethod 

def putRepositoryCfg(cfg, loc=None): 

storage = Storage.makeFromURI(cfg.root if loc is None else loc, create=True) 

location = ButlerLocation(pythonType=RepositoryCfg, 

cppType=None, 

storageName=None, 

locationList='repositoryCfg.yaml', 

dataId={}, 

mapper=None, 

storage=storage, 

usedDataId=None, 

datasetType=None) 

storage.write(location, cfg) 

 

@staticmethod 

def getMapperClass(root): 

"""Get the mapper class associated with a repository root. 

 

Supports the legacy _parent symlink search (which was only ever posix-only. This should not be used by 

new code and repositories; they should use the Repository parentCfg mechanism. 

 

Parameters 

---------- 

root : string 

The location of a persisted ReositoryCfg is (new style repos), or 

the location where a _mapper file is (old style repos). 

 

Returns 

------- 

A class object or a class instance, depending on the state of the 

mapper when the repository was created. 

""" 

189 ↛ 190line 189 didn't jump to line 190, because the condition on line 189 was never true if not (root): 

return None 

 

cfg = PosixStorage.getRepositoryCfg(root) 

193 ↛ 194line 193 didn't jump to line 194, because the condition on line 193 was never true if cfg is not None: 

return cfg.mapper 

 

# Find a "_mapper" file containing the mapper class name 

basePath = root 

mapperFile = "_mapper" 

while not os.path.exists(os.path.join(basePath, mapperFile)): 

# Break abstraction by following _parent links from CameraMapper 

201 ↛ 204line 201 didn't jump to line 204, because the condition on line 201 was never false if os.path.exists(os.path.join(basePath, "_parent")): 

basePath = os.path.join(basePath, "_parent") 

else: 

mapperFile = None 

break 

 

207 ↛ 220line 207 didn't jump to line 220, because the condition on line 207 was never false if mapperFile is not None: 

mapperFile = os.path.join(basePath, mapperFile) 

 

# Read the name of the mapper class and instantiate it 

with open(mapperFile, "r") as f: 

mapperName = f.readline().strip() 

components = mapperName.split(".") 

214 ↛ 215line 214 didn't jump to line 215, because the condition on line 214 was never true if len(components) <= 1: 

raise RuntimeError("Unqualified mapper name %s in %s" % 

(mapperName, mapperFile)) 

pkg = importlib.import_module(".".join(components[:-1])) 

return getattr(pkg, components[-1]) 

 

return None 

 

@staticmethod 

def getParentSymlinkPath(root): 

"""For Butler V1 Repositories only, if a _parent symlink exists, get the location pointed to by the 

symlink. 

 

Parameters 

---------- 

root : string 

A path to the folder on the local filesystem. 

 

Returns 

------- 

string or None 

A path to the parent folder indicated by the _parent symlink, or None if there is no _parent 

symlink at root. 

""" 

linkpath = os.path.join(root, '_parent') 

if os.path.exists(linkpath): 

try: 

return os.readlink(os.path.join(root, '_parent')) 

except OSError: 

# some of the unit tests rely on a folder called _parent instead of a symlink to aother 

# location. Allow that; return the path of that folder. 

return os.path.join(root, '_parent') 

return None 

 

def write(self, butlerLocation, obj): 

"""Writes an object to a location and persistence format specified by 

ButlerLocation 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location & formatting for the object to be written. 

obj : object instance 

The object to be written. 

""" 

self.log.debug("Put location=%s obj=%s", butlerLocation, obj) 

 

writeFormatter = self.getWriteFormatter(butlerLocation.getStorageName()) 

if not writeFormatter: 

writeFormatter = self.getWriteFormatter(butlerLocation.getPythonType()) 

264 ↛ 268line 264 didn't jump to line 268, because the condition on line 264 was never false if writeFormatter: 

writeFormatter(butlerLocation, obj) 

return 

 

raise(RuntimeError("No formatter for location:{}".format(butlerLocation))) 

 

def read(self, butlerLocation): 

"""Read from a butlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location & formatting for the object(s) to be read. 

 

Returns 

------- 

A list of objects as described by the butler location. One item for 

each location in butlerLocation.getLocations() 

""" 

readFormatter = self.getReadFormatter(butlerLocation.getStorageName()) 

if not readFormatter: 

readFormatter = self.getReadFormatter(butlerLocation.getPythonType()) 

286 ↛ 289line 286 didn't jump to line 289, because the condition on line 286 was never false if readFormatter: 

return readFormatter(butlerLocation) 

 

raise(RuntimeError("No formatter for location:{}".format(butlerLocation))) 

 

def butlerLocationExists(self, location): 

"""Implementation of PosixStorage.exists for ButlerLocation objects. 

""" 

storageName = location.getStorageName() 

295 ↛ 298line 295 didn't jump to line 298, because the condition on line 295 was never true if storageName not in ('BoostStorage', 'FitsStorage', 'PafStorage', 

'PickleStorage', 'ConfigStorage', 'FitsCatalogStorage', 

'YamlStorage', 'ParquetStorage', 'MatplotlibStorage'): 

self.log.warn("butlerLocationExists for non-supported storage %s" % location) 

return False 

for locationString in location.getLocations(): 

logLoc = LogicalLocation(locationString, location.getAdditionalData()).locString() 

obj = self.instanceSearch(path=logLoc) 

if obj: 

return True 

return False 

 

def exists(self, location): 

"""Check if location exists. 

 

Parameters 

---------- 

location : ButlerLocation or string 

A a string or a ButlerLocation that describes the location of an 

object in this storage. 

 

Returns 

------- 

bool 

True if exists, else False. 

""" 

321 ↛ 324line 321 didn't jump to line 324, because the condition on line 321 was never false if isinstance(location, ButlerLocation): 

return self.butlerLocationExists(location) 

 

obj = self.instanceSearch(path=location) 

return bool(obj) 

 

def locationWithRoot(self, location): 

"""Get the full path to the location. 

 

:param location: 

:return: 

""" 

return os.path.join(self.root, location) 

 

@staticmethod 

def v1RepoExists(root): 

"""Test if a Version 1 Repository exists. 

 

Version 1 Repositories only exist in posix storages, do not have a 

RepositoryCfg file, and contain either a registry.sqlite3 file, a 

_mapper file, or a _parent link. 

 

Parameters 

---------- 

root : string 

A path to a folder on the local filesystem. 

 

Returns 

------- 

bool 

True if the repository at root exists, else False. 

""" 

return os.path.exists(root) and ( 

os.path.exists(os.path.join(root, "registry.sqlite3")) or 

os.path.exists(os.path.join(root, "_mapper")) or 

os.path.exists(os.path.join(root, "_parent")) 

) 

 

def copyFile(self, fromLocation, toLocation): 

"""Copy a file from one location to another on the local filesystem. 

 

Parameters 

---------- 

fromLocation : path 

Path and name of existing file. 

toLocation : path 

Path and name of new file. 

 

Returns 

------- 

None 

""" 

shutil.copy(os.path.join(self.root, fromLocation), os.path.join(self.root, toLocation)) 

 

def getLocalFile(self, path): 

"""Get a handle to a local copy of the file, downloading it to a 

temporary if needed. 

 

Parameters 

---------- 

A path the the file in storage, relative to root. 

 

Returns 

------- 

A handle to a local copy of the file. If storage is remote it will be 

a temporary file. If storage is local it may be the original file or 

a temporary file. The file name can be gotten via the 'name' property 

of the returned object. 

""" 

p = os.path.join(self.root, path) 

try: 

return open(p) 

except IOError as e: 

394 ↛ 397line 394 didn't jump to line 397, because the condition on line 394 was never false if e.errno == 2: # 'No such file or directory' 

return None 

else: 

raise e 

 

def instanceSearch(self, path): 

"""Search for the given path in this storage instance. 

 

If the path contains an HDU indicator (a number in brackets before the 

dot, e.g. 'foo.fits[1]', this will be stripped when searching and so 

will match filenames without the HDU indicator, e.g. 'foo.fits'. The 

path returned WILL contain the indicator though, e.g. ['foo.fits[1]']. 

 

Parameters 

---------- 

path : string 

A filename (and optionally prefix path) to search for within root. 

 

Returns 

------- 

string or None 

The location that was found, or None if no location was found. 

""" 

return self.search(self.root, path) 

 

@staticmethod 

def search(root, path, searchParents=False): 

"""Look for the given path in the current root. 

 

Also supports searching for the path in Butler v1 repositories by 

following the Butler v1 _parent symlink 

 

If the path contains an HDU indicator (a number in brackets, e.g. 

'foo.fits[1]', this will be stripped when searching and so 

will match filenames without the HDU indicator, e.g. 'foo.fits'. The 

path returned WILL contain the indicator though, e.g. ['foo.fits[1]']. 

 

Parameters 

---------- 

root : string 

The path to the root directory. 

path : string 

The path to the file within the root directory. 

searchParents : bool, optional 

For Butler v1 repositories only, if true and a _parent symlink 

exists, then the directory at _parent will be searched if the file 

is not found in the root repository. Will continue searching the 

parent of the parent until the file is found or no additional 

parent exists. 

 

Returns 

------- 

string or None 

The location that was found, or None if no location was found. 

""" 

# Separate path into a root-equivalent prefix (in dir) and the rest 

# (left in path) 

rootDir = root 

# First remove trailing slashes (#2527) 

453 ↛ 454line 453 didn't jump to line 454, because the condition on line 453 was never true while len(rootDir) > 1 and rootDir[-1] == '/': 

rootDir = rootDir[:-1] 

 

if path.startswith(rootDir + "/"): 

# Common case; we have the same root prefix string 

path = path[len(rootDir + '/'):] 

pathPrefix = rootDir 

460 ↛ 461line 460 didn't jump to line 461, because the condition on line 460 was never true elif rootDir == "/" and path.startswith("/"): 

path = path[1:] 

pathPrefix = None 

else: 

# Search for prefix that is the same as root 

pathPrefix = os.path.dirname(path) 

while pathPrefix != "" and pathPrefix != "/": 

467 ↛ 468line 467 didn't jump to line 468, because the condition on line 467 was never true if os.path.realpath(pathPrefix) == os.path.realpath(root): 

break 

pathPrefix = os.path.dirname(pathPrefix) 

470 ↛ 471line 470 didn't jump to line 471, because the condition on line 470 was never true if pathPrefix == "/": 

path = path[1:] 

472 ↛ 473line 472 didn't jump to line 473, because the condition on line 472 was never true elif pathPrefix != "": 

path = path[len(pathPrefix)+1:] 

 

# Now search for the path in the root or its parents 

# Strip off any cfitsio bracketed extension if present 

strippedPath = path 

pathStripped = None 

firstBracket = path.find("[") 

if firstBracket != -1: 

strippedPath = path[:firstBracket] 

pathStripped = path[firstBracket:] 

 

dir = rootDir 

while True: 

paths = glob.glob(os.path.join(dir, strippedPath)) 

if len(paths) > 0: 

if pathPrefix != rootDir: 

paths = [p[len(rootDir+'/'):] for p in paths] 

if pathStripped is not None: 

paths = [p + pathStripped for p in paths] 

return paths 

if searchParents: 

dir = os.path.join(dir, "_parent") 

if not os.path.exists(dir): 

return None 

else: 

return None 

 

@staticmethod 

def storageExists(uri): 

"""Ask if a storage at the location described by uri exists 

 

Parameters 

---------- 

root : string 

URI to the the root location of the storage 

 

Returns 

------- 

bool 

True if the storage exists, false if not 

""" 

return os.path.exists(PosixStorage._pathFromURI(uri)) 

 

 

def readConfigStorage(butlerLocation): 

"""Read an lsst.pex.config.Config from a butlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object(s) to be read. 

 

Returns 

------- 

A list of objects as described by the butler location. One item for 

each location in butlerLocation.getLocations() 

""" 

results = [] 

for locationString in butlerLocation.getLocations(): 

locStringWithRoot = os.path.join(butlerLocation.getStorage().root, locationString) 

logLoc = LogicalLocation(locStringWithRoot, butlerLocation.getAdditionalData()) 

if not os.path.exists(logLoc.locString()): 

raise RuntimeError("No such config file: " + logLoc.locString()) 

pythonType = butlerLocation.getPythonType() 

if pythonType is not None: 

if isinstance(pythonType, basestring): 

pythonType = doImport(pythonType) 

finalItem = pythonType() 

finalItem.load(logLoc.locString()) 

results.append(finalItem) 

return results 

 

 

def writeConfigStorage(butlerLocation, obj): 

"""Writes an lsst.pex.config.Config object to a location specified by 

ButlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object to be written. 

obj : object instance 

The object to be written. 

""" 

filename = os.path.join(butlerLocation.getStorage().root, butlerLocation.getLocations()[0]) 

with SafeFilename(filename) as locationString: 

logLoc = LogicalLocation(locationString, butlerLocation.getAdditionalData()) 

obj.save(logLoc.locString()) 

 

 

def readFitsStorage(butlerLocation): 

"""Read a FITS image from a butlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object(s) to be read. 

 

Returns 

------- 

A list of objects as described by the butler location. One item for 

each location in butlerLocation.getLocations() 

""" 

results = [] 

for locationString in butlerLocation.getLocations(): 

locStringWithRoot = os.path.join(butlerLocation.getStorage().root, locationString) 

logLoc = LogicalLocation(locStringWithRoot, butlerLocation.getAdditionalData()) 

storageList = StorageList() 

storage = PosixStorage.getPersistence().getRetrieveStorage(butlerLocation.getStorageName(), 

logLoc) 

storageList.append(storage) 

finalItem = PosixStorage.getPersistence().unsafeRetrieve( 

butlerLocation.getCppType(), storageList, butlerLocation.getAdditionalData()) 

results.append(finalItem) 

return results 

 

 

def writeFitsStorage(butlerLocation, obj): 

"""Writes an object to a FITS file specified by ButlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object to be written. 

obj : object instance 

The object to be written. 

""" 

location = butlerLocation.getLocations()[0] 

with SafeFilename(os.path.join(butlerLocation.getStorage().root, location)) as locationString: 

logLoc = LogicalLocation(locationString, butlerLocation.getAdditionalData()) 

# Create a list of Storages for the item. 

storageList = StorageList() 

storage = PosixStorage.getPersistence().getPersistStorage(butlerLocation.getStorageName(), logLoc) 

storageList.append(storage) 

persistence = PosixStorage.getPersistence() 

if hasattr(obj, '__deref__'): 

# We have a smart pointer, so dereference it. 

persistence.persist(obj.__deref__(), storageList, butlerLocation.getAdditionalData()) 

else: 

persistence.persist(obj, storageList, butlerLocation.getAdditionalData()) 

 

 

def readParquetStorage(butlerLocation): 

"""Read a catalog from a Parquet file specified by ButlerLocation. 

 

The object returned by this is expected to be a subtype 

of `ParquetTable`, which is a thin wrapper to `pyarrow.ParquetFile` 

that allows for lazy loading of the data. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object(s) to be read. 

 

Returns 

------- 

A list of objects as described by the butler location. One item for 

each location in butlerLocation.getLocations() 

""" 

results = [] 

additionalData = butlerLocation.getAdditionalData() 

 

for locationString in butlerLocation.getLocations(): 

locStringWithRoot = os.path.join(butlerLocation.getStorage().root, locationString) 

logLoc = LogicalLocation(locStringWithRoot, additionalData) 

if not os.path.exists(logLoc.locString()): 

raise RuntimeError("No such parquet file: " + logLoc.locString()) 

 

pythonType = butlerLocation.getPythonType() 

if pythonType is not None: 

if isinstance(pythonType, basestring): 

pythonType = doImport(pythonType) 

 

filename = logLoc.locString() 

 

# pythonType will be ParquetTable (or perhaps MultilevelParquetTable) 

# filename should be the first kwarg, but being explicit here. 

results.append(pythonType(filename=filename)) 

 

return results 

 

 

def writeParquetStorage(butlerLocation, obj): 

"""Writes pandas dataframe to parquet file. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object(s) to be read. 

obj : `lsst.qa.explorer.parquetTable.ParquetTable` 

Wrapped DataFrame to write. 

 

""" 

additionalData = butlerLocation.getAdditionalData() 

locations = butlerLocation.getLocations() 

with SafeFilename(os.path.join(butlerLocation.getStorage().root, locations[0])) as locationString: 

logLoc = LogicalLocation(locationString, additionalData) 

filename = logLoc.locString() 

obj.write(filename) 

 

 

def writeYamlStorage(butlerLocation, obj): 

"""Writes an object to a YAML file specified by ButlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object to be written. 

obj : object instance 

The object to be written. 

""" 

additionalData = butlerLocation.getAdditionalData() 

locations = butlerLocation.getLocations() 

with SafeFilename(os.path.join(butlerLocation.getStorage().root, locations[0])) as locationString: 

logLoc = LogicalLocation(locationString, additionalData) 

with open(logLoc.locString(), "w") as outfile: 

yaml.dump(obj, outfile) 

 

 

def readPickleStorage(butlerLocation): 

"""Read an object from a pickle file specified by ButlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object(s) to be read. 

 

Returns 

------- 

A list of objects as described by the butler location. One item for 

each location in butlerLocation.getLocations() 

""" 

# Create a list of Storages for the item. 

results = [] 

additionalData = butlerLocation.getAdditionalData() 

for locationString in butlerLocation.getLocations(): 

locStringWithRoot = os.path.join(butlerLocation.getStorage().root, locationString) 

logLoc = LogicalLocation(locStringWithRoot, additionalData) 

711 ↛ 712line 711 didn't jump to line 712, because the condition on line 711 was never true if not os.path.exists(logLoc.locString()): 

raise RuntimeError("No such pickle file: " + logLoc.locString()) 

with open(logLoc.locString(), "rb") as infile: 

# py3: We have to specify encoding since some files were written 

# by python2, and 'latin1' manages that conversion safely. See: 

# http://stackoverflow.com/questions/28218466/unpickling-a-python-2-object-with-python-3/28218598#28218598 

717 ↛ 720line 717 didn't jump to line 720, because the condition on line 717 was never false if sys.version_info.major >= 3: 

finalItem = pickle.load(infile, encoding="latin1") 

else: 

finalItem = pickle.load(infile) 

results.append(finalItem) 

return results 

 

 

def writePickleStorage(butlerLocation, obj): 

"""Writes an object to a pickle file specified by ButlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object to be written. 

obj : object instance 

The object to be written. 

""" 

additionalData = butlerLocation.getAdditionalData() 

locations = butlerLocation.getLocations() 

with SafeFilename(os.path.join(butlerLocation.getStorage().root, locations[0])) as locationString: 

logLoc = LogicalLocation(locationString, additionalData) 

with open(logLoc.locString(), "wb") as outfile: 

pickle.dump(obj, outfile, pickle.HIGHEST_PROTOCOL) 

 

 

def readFitsCatalogStorage(butlerLocation): 

"""Read a catalog from a FITS table specified by ButlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object(s) to be read. 

 

Returns 

------- 

A list of objects as described by the butler location. One item for 

each location in butlerLocation.getLocations() 

""" 

pythonType = butlerLocation.getPythonType() 

if pythonType is not None: 

if isinstance(pythonType, basestring): 

pythonType = doImport(pythonType) 

results = [] 

additionalData = butlerLocation.getAdditionalData() 

for locationString in butlerLocation.getLocations(): 

locStringWithRoot = os.path.join(butlerLocation.getStorage().root, locationString) 

logLoc = LogicalLocation(locStringWithRoot, additionalData) 

if not os.path.exists(logLoc.locString()): 

raise RuntimeError("No such FITS catalog file: " + logLoc.locString()) 

kwds = {} 

if additionalData.exists("hdu"): 

kwds["hdu"] = additionalData.getInt("hdu") 

if additionalData.exists("flags"): 

kwds["flags"] = additionalData.getInt("flags") 

finalItem = pythonType.readFits(logLoc.locString(), **kwds) 

results.append(finalItem) 

return results 

 

 

def writeFitsCatalogStorage(butlerLocation, obj): 

"""Writes a catalog to a FITS table specified by ButlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object to be written. 

obj : object instance 

The object to be written. 

""" 

additionalData = butlerLocation.getAdditionalData() 

locations = butlerLocation.getLocations() 

with SafeFilename(os.path.join(butlerLocation.getStorage().root, locations[0])) as locationString: 

logLoc = LogicalLocation(locationString, additionalData) 

if additionalData.exists("flags"): 

kwds = dict(flags=additionalData.getInt("flags")) 

else: 

kwds = {} 

obj.writeFits(logLoc.locString(), **kwds) 

 

 

def readMatplotlibStorage(butlerLocation): 

"""Read from a butlerLocation (always fails for this storage type). 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object(s) to be read. 

 

Returns 

------- 

A list of objects as described by the butler location. One item for 

each location in butlerLocation.getLocations() 

""" 

raise NotImplementedError("Figures saved with MatplotlibStorage cannot be retreived using the Butler.") 

 

 

def writeMatplotlibStorage(butlerLocation, obj): 

"""Writes a matplotlib.figure.Figure to a location, using the template's 

filename suffix to infer the file format. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object to be written. 

obj : matplotlib.figure.Figure 

The object to be written. 

""" 

additionalData = butlerLocation.getAdditionalData() 

locations = butlerLocation.getLocations() 

with SafeFilename(os.path.join(butlerLocation.getStorage().root, locations[0])) as locationString: 

logLoc = LogicalLocation(locationString, additionalData) 

# SafeFilename appends a random suffix, which corrupts the extension 

# matplotlib uses to guess the file format. 

# Instead, we extract the extension from the original location 

# and pass that as the format directly. 

_, ext = os.path.splitext(locations[0]) 

if ext: 

ext = ext[1:] # strip off leading '.' 

else: 

# If there is no extension, we let matplotlib fall back to its 

# default. 

ext = None 

obj.savefig(logLoc.locString(), format=ext) 

 

 

def readPafStorage(butlerLocation): 

"""Read a policy from a PAF file specified by a ButlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object(s) to be read. 

 

Returns 

------- 

A list of objects as described by the butler location. One item for 

each location in butlerLocation.getLocations() 

""" 

results = [] 

for locationString in butlerLocation.getLocations(): 

logLoc = LogicalLocation(butlerLocation.getStorage().locationWithRoot(locationString), 

butlerLocation.getAdditionalData()) 

finalItem = pexPolicy.Policy.createPolicy(logLoc.locString()) 

results.append(finalItem) 

return results 

 

 

def readYamlStorage(butlerLocation): 

"""Read an object from a YAML file specified by a butlerLocation. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object(s) to be read. 

 

Returns 

------- 

A list of objects as described by the butler location. One item for 

each location in butlerLocation.getLocations() 

""" 

results = [] 

for locationString in butlerLocation.getLocations(): 

logLoc = LogicalLocation(butlerLocation.getStorage().locationWithRoot(locationString), 

butlerLocation.getAdditionalData()) 

882 ↛ 883line 882 didn't jump to line 883, because the condition on line 882 was never true if not os.path.exists(logLoc.locString()): 

raise RuntimeError("No such YAML file: " + logLoc.locString()) 

# Butler Gen2 repository configurations are handled specially 

885 ↛ 886line 885 didn't jump to line 886, because the condition on line 885 was never true if butlerLocation.pythonType == 'lsst.daf.persistence.RepositoryCfg': 

finalItem = Policy(filePath=logLoc.locString()) 

else: 

with open(logLoc.locString(), "rb") as infile: 

finalItem = yaml.load(infile) 

results.append(finalItem) 

return results 

 

 

def readBoostStorage(butlerLocation): 

"""Read an object from a boost::serialization file. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object(s) to be read. 

 

Returns 

------- 

A list of objects as described by the butler location. One item for 

each location in butlerLocation.getLocations() 

""" 

results = [] 

additionalData = butlerLocation.getAdditionalData() 

for locationString in butlerLocation.getLocations(): 

logLoc = LogicalLocation(butlerLocation.getStorage().locationWithRoot(locationString), 

butlerLocation.getAdditionalData()) 

storageList = StorageList() 

storage = PosixStorage.getPersistence().getRetrieveStorage(butlerLocation.getStorageName(), logLoc) 

storageList.append(storage) 

finalItem = PosixStorage.getPersistence().unsafeRetrieve(butlerLocation.getCppType(), storageList, 

additionalData) 

results.append(finalItem) 

return results 

 

 

def writeBoostStorage(butlerLocation, obj): 

"""Writes an object via boost::serialization. 

 

Parameters 

---------- 

butlerLocation : ButlerLocation 

The location for the object to be written. 

obj : object instance 

The object to be written. 

""" 

additionalData = butlerLocation.getAdditionalData() 

location = butlerLocation.getStorage().locationWithRoot(butlerLocation.getLocations()[0]) 

with SafeFilename(location) as locationString: 

logLoc = LogicalLocation(locationString, additionalData) 

# Create a list of Storages for the item. 

storageList = StorageList() 

storage = PosixStorage.getPersistence().getPersistStorage(butlerLocation.getStorageName(), logLoc) 

storageList.append(storage) 

# Persist the item. 

if hasattr(obj, '__deref__'): 

# We have a smart pointer, so dereference it. 

PosixStorage.getPersistence().persist(obj.__deref__(), storageList, additionalData) 

else: 

PosixStorage.getPersistence().persist(obj, storageList, additionalData) 

 

 

PosixStorage.registerFormatters("FitsStorage", readFitsStorage, writeFitsStorage) 

PosixStorage.registerFormatters("ParquetStorage", readParquetStorage, writeParquetStorage) 

PosixStorage.registerFormatters("ConfigStorage", readConfigStorage, writeConfigStorage) 

PosixStorage.registerFormatters("PickleStorage", readPickleStorage, writePickleStorage) 

PosixStorage.registerFormatters("FitsCatalogStorage", readFitsCatalogStorage, writeFitsCatalogStorage) 

PosixStorage.registerFormatters("MatplotlibStorage", readMatplotlibStorage, writeMatplotlibStorage) 

PosixStorage.registerFormatters("PafStorage", readFormatter=readPafStorage) 

PosixStorage.registerFormatters("YamlStorage", readYamlStorage, writeYamlStorage) 

PosixStorage.registerFormatters("BoostStorage", readFitsStorage, writeFitsStorage) 

 

Storage.registerStorageClass(scheme='', cls=PosixStorage) 

Storage.registerStorageClass(scheme='file', cls=PosixStorage)