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

# 

# LSST Data Management System 

# Copyright 2008-2015 AURA/LSST. 

# 

# 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 <https://www.lsstcorp.org/LegalNotices/>. 

# 

import os 

import shutil 

import unittest 

import tempfile 

 

import lsst.utils 

import lsst.pipe.base as pipeBase 

import lsst.obs.test 

from lsst.log import Log 

 

ObsTestDir = lsst.utils.getPackageDir("obs_test") 

DataPath = os.path.join(ObsTestDir, "data", "input") 

 

 

class ExampleTask(pipeBase.CmdLineTask): 

ConfigClass = lsst.obs.test.TestConfig 

_DefaultName = "test" 

 

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

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

self.dataRefList = [] 

self.numProcessed = 0 

self.metadata.set("numProcessed", self.numProcessed) 

 

@pipeBase.timeMethod 

def runDataRef(self, dataRef): 

if self.config.doFail: 

raise pipeBase.TaskError("Failed by request: config.doFail is true") 

self.dataRefList.append(dataRef) 

self.numProcessed += 1 

self.metadata.set("numProcessed", self.numProcessed) 

return pipeBase.Struct( 

numProcessed=self.numProcessed, 

) 

 

 

class CannotConstructTask(ExampleTask): 

"""A task that cannot be constructed; used to test error handling 

""" 

 

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

raise RuntimeError("This task cannot be constructed") 

 

 

class NoMultiprocessTask(ExampleTask): 

"""Version of ExampleTask that does not support multiprocessing""" 

canMultiprocess = False 

 

 

class LegacyTask(ExampleTask): 

"""Version of ExampleTask with `run` as entry point rather than 

`runDataRef` 

""" 

RunnerClass = pipeBase.LegacyTaskRunner 

 

def run(self, dataRef): 

results = self.runDataRef(dataRef) 

resultsToBeAdded = pipeBase.Struct(didEnterRun=True) 

results.mergeItems(resultsToBeAdded, "didEnterRun") 

return results 

 

 

class CmdLineTaskTestCase(unittest.TestCase): 

"""A test case for CmdLineTask 

""" 

 

def setUp(self): 

os.environ.pop("PIPE_INPUT_ROOT", None) 

os.environ.pop("PIPE_CALIB_ROOT", None) 

os.environ.pop("PIPE_OUTPUT_ROOT", None) 

self.outPath = tempfile.mkdtemp() 

 

def tearDown(self): 

try: 

shutil.rmtree(self.outPath) 

except Exception: 

print("WARNING: failed to remove temporary dir %r" % (self.outPath,)) 

del self.outPath 

 

def testBasics(self): 

"""Test basic construction and use of a command-line task 

""" 

retVal = ExampleTask.parseAndRun(args=[DataPath, "--output", self.outPath, "--id", "visit=1"]) 

self.assertEqual(retVal.resultList, [pipeBase.Struct(exitStatus=0)]) 

task = ExampleTask(config=retVal.parsedCmd.config) 

parsedCmd = retVal.parsedCmd 

self.assertEqual(len(parsedCmd.id.refList), 1) 

dataRef = parsedCmd.id.refList[0] 

dataId = dataRef.dataId 

self.assertEqual(dataId["visit"], 1) 

self.assertEqual(task.getName(), "test") 

config = dataRef.get("test_config", immediate=True) 

self.assertEqual(config, task.config) 

metadata = dataRef.get("test_metadata", immediate=True) 

self.assertEqual(metadata.getScalar("test.numProcessed"), 1) 

 

def testOverrides(self): 

"""Test config and log override 

""" 

config = ExampleTask.ConfigClass() 

config.floatField = -99.9 

log = Log.getLogger("cmdLineTask") 

retVal = ExampleTask.parseAndRun( 

args=[DataPath, "--output", self.outPath, "--id", "visit=2"], 

config=config, 

log=log 

) 

self.assertEqual(retVal.parsedCmd.config.floatField, -99.9) 

self.assertIs(retVal.parsedCmd.log, log) 

 

def testDoReturnResults(self): 

"""Test the doReturnResults flag 

""" 

retVal = ExampleTask.parseAndRun(args=[DataPath, "--output", self.outPath, 

"--id", "visit=3", "filter=r"], doReturnResults=True) 

self.assertEqual(len(retVal.resultList), 1) 

result = retVal.resultList[0] 

self.assertEqual(result.metadata.getScalar("numProcessed"), 1) 

self.assertEqual(result.result.numProcessed, 1) 

 

def testDoReturnResultsOnFailure(self): 

retVal = ExampleTask.parseAndRun(args=[DataPath, "--output", self.outPath, 

"--id", "visit=3", "filter=r", "--config", "doFail=True", 

"--clobber-config", "--noExit"], doReturnResults=True) 

self.assertEqual(len(retVal.resultList), 1) 

result = retVal.resultList[0] 

self.assertEqual(result.metadata.getScalar("numProcessed"), 0) 

self.assertEqual(retVal.resultList[0].result, None) 

 

def testBackupConfig(self): 

"""Test backup config file creation 

""" 

ExampleTask.parseAndRun(args=[DataPath, "--output", self.outPath, "--id", "visit=3", "filter=r"]) 

# Rerun with --clobber-config to ensure backup config file is created 

ExampleTask.parseAndRun(args=[DataPath, "--output", self.outPath, "--id", "visit=3", "filter=r", 

"--config", "floatField=-99.9", "--clobber-config"]) 

# Ensure backup config file was created 

self.assertTrue(os.path.exists(os.path.join( 

self.outPath, "config", ExampleTask._DefaultName + ".py~1"))) 

 

def testNoBackupConfig(self): 

"""Test no backup config file creation 

""" 

ExampleTask.parseAndRun(args=[DataPath, "--output", self.outPath, "--id", "visit=3", "filter=r"]) 

# Rerun with --clobber-config and --no-backup-config to ensure backup config file is NOT created 

ExampleTask.parseAndRun(args=[DataPath, "--output", self.outPath, "--id", "visit=3", "filter=r", 

"--config", "floatField=-99.9", "--clobber-config", 

"--no-backup-config"]) 

# Ensure backup config file was NOT created 

self.assertFalse( 

os.path.exists(os.path.join(self.outPath, "config", ExampleTask._DefaultName + ".py~1"))) 

 

def testMultiprocess(self): 

"""Test multiprocessing at a very minimal level 

""" 

for TaskClass in (ExampleTask, NoMultiprocessTask): 

result = TaskClass.parseAndRun(args=[DataPath, "--output", self.outPath, 

"-j", "5", "--id", "visit=2", "filter=r"]) 

self.assertEqual(result.taskRunner.numProcesses, 5 if TaskClass.canMultiprocess else 1) 

 

def testCannotConstructTask(self): 

"""Test error handling when a task cannot be constructed 

""" 

for doRaise in (False, True): 

args = [DataPath, "--output", self.outPath, "--id", "visit=1"] 

if doRaise: 

args.append("--doraise") 

with self.assertRaises(RuntimeError): 

CannotConstructTask.parseAndRun(args=args) 

 

def testLegacyTask(self): 

"""Test error handling when a task cannot be constructed 

""" 

retVal = LegacyTask.parseAndRun(args=[DataPath, "--output", self.outPath, 

"--id", "visit=3", "filter=r"], doReturnResults=True) 

self.assertEqual(retVal.resultList[0].result.didEnterRun, True) 

 

 

class EaxmpleMultipleIdTaskRunner(pipeBase.TaskRunner): 

"""TaskRunner to get multiple identifiers down into a Task""" 

@staticmethod 

def getTargetList(parsedCmd): 

"""We want our Task to process one dataRef from each identifier at a time""" 

return list(zip(parsedCmd.one.refList, parsedCmd.two.refList)) 

 

def __call__(self, target): 

"""Send results from the Task back so we can inspect 

 

For this test case with obs_test, we know that the results are picklable 

and small, so returning something is not a problem. 

""" 

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

return task.runDataRef(target) 

 

 

class ExampleMultipleIdTask(pipeBase.CmdLineTask): 

_DefaultName = "test" 

ConfigClass = lsst.obs.test.TestConfig 

RunnerClass = EaxmpleMultipleIdTaskRunner 

 

@classmethod 

def _makeArgumentParser(cls): 

"""We want an argument parser that has multiple identifiers""" 

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

parser.add_id_argument("--one", "raw", "data identifier one", level="sensor") 

parser.add_id_argument("--two", "raw", "data identifier two", level="sensor") 

return parser 

 

def runDataRef(self, data): 

"""Our Task just spits back what's in the dataRefs.""" 

oneRef = data[0] 

twoRef = data[1] 

return oneRef.get("raw", snap=0, channel="0,0"), twoRef.get("raw", snap=0, channel="0,0") 

 

 

class MultipleIdTaskTestCase(unittest.TestCase): 

"""A test case for CmdLineTask using multiple identifiers 

 

Tests implementation of ticket 2144, and demonstrates how 

to get results from multiple identifiers down into a Task. 

""" 

 

def setUp(self): 

os.environ.pop("PIPE_INPUT_ROOT", None) 

os.environ.pop("PIPE_CALIB_ROOT", None) 

os.environ.pop("PIPE_OUTPUT_ROOT", None) 

self.outPath = tempfile.mkdtemp() 

 

def tearDown(self): 

try: 

shutil.rmtree(self.outPath) 

except Exception: 

print("WARNING: failed to remove temporary dir %r" % (self.outPath,)) 

del self.outPath 

 

def testMultiple(self): 

"""Test use of a CmdLineTask with multiple identifiers""" 

args = [DataPath, "--output", self.outPath, 

"--one", "visit=1", "filter=g", 

"--two", "visit=2", "filter=g", 

] 

retVal = ExampleMultipleIdTask.parseAndRun(args=args) 

self.assertEqual(len(retVal.resultList), 1) 

 

 

class MyMemoryTestCase(lsst.utils.tests.MemoryTestCase): 

pass 

 

 

def setup_module(module): 

lsst.utils.tests.init() 

 

 

275 ↛ 276line 275 didn't jump to line 276, because the condition on line 275 was never trueif __name__ == "__main__": 

lsst.utils.tests.init() 

unittest.main()