Coverage for python/lsst/ap/pipe/cmCampaignToBps.py: 89%

126 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 11:19 +0000

1# This file is part of ap_pipe. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

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

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

7# for details of code ownership. 

8# 

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

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

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

12# (at your option) any later version. 

13# 

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

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

16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

17# GNU General Public License for more details. 

18# 

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

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

21 

22"""Build a standalone BPS submission file from one step of a CM Service 

23campaign definition. 

24 

25The generated BPS yaml is not intended to be used directly, but is a 

26representation of the submission used by Campaign Management. This script is 

27called when building ``ap_pipe`` and generates 

28``bps/LSSTCam/bps_Daytime.yaml`` and 

29``bps/LSSTCam/bps_Daytime-DECam-templates.yaml``, one per campaign step. 

30 

31The standalone submissions of a campaign's steps share one output collection 

32and must be submitted in campaign order, each after the previous one has 

33finished. 

34 

35Examples 

36-------- 

37Rebuild the submission of the Daytime AP ``AP_PIPE`` step from the package 

38root: 

39 

40.. code-block:: bash 

41 

42 python -m lsst.ap.pipe.cmCampaignToBps \\ 

43 scripts/LSSTCam/ap_daytime_cm_campaign.yaml \\ 

44 bps/LSSTCam/bps_Daytime.yaml --step AP_PIPE 

45 

46``scons bps/LSSTCam/bps_Daytime.yaml`` runs the same command. 

47""" 

48 

49__all__ = ["makeBpsConfig", "readCampaign", "writeBpsConfig", "main"] 

50 

51import argparse 

52import pathlib 

53import re 

54 

55import yaml 

56 

57# CM template expressions, without whitespace, that evaluate to the 

58# campaign's day_obs. 

59_DAY_OBS_EXPRESSIONS = frozenset({"yesterday|as_day_obs", "day_obs"}) 

60_TEMPLATE_PATTERN = re.compile(r"\$\{\{(.*?)\}\}") 

61# CM manifest variables are wrapped in {{}}, which CM renders from a step's 

62# configuration. 

63_MANIFEST_PATTERN = re.compile(r"(?<!\$)\{\{(.*?)\}\}") 

64 

65# CM Service defaults for manifest fields the campaign may omit; see the 

66# WmsSpec and FacilitySpec models in lsst-dm/cm-service. 

67_WMS_DEFAULTS = { 

68 "service_class": "lsst.ctrl.bps.htcondor.HTCondorService", 

69 "auto_provision": False, 

70 "provisioned_node_count": 10, 

71 "provisioned_cpu_count": 16, 

72 "provisioned_max_wall_time": "0-1:00:00", 

73 "provisioned_idle_time": 900, 

74 "provisioned_check_interval": 600, 

75 "provisioned_extra_arguments": [], 

76 "auto_release": True, 

77 "auto_release_expr": "HoldReasonCode >= 6", 

78} 

79_SITE_DEFAULTS = { 

80 "facility": "SLAC", 

81 "provisioned_platform": "s3df", 

82 "provisioned_queue": "milano", 

83 "provisioned_account_group": "rubin:developers", 

84} 

85_AGGREGATE_DEFAULT = ["--output {submitPath}/{uniqProcName}_prov.qg"] 

86 

87# BPS manifest list fields and the BPS keys that take them joined by spaces. 

88_EXTRA_OPTIONS = { 

89 "extra_init_options": "extraInitOptions", 

90 "extra_qgraph_options": "extraQgraphOptions", 

91 "extra_run_quantum_options": "extraRunQuantumOptions", 

92 "extra_update_qgraph_options": "extraUpdateQgraphOptions", 

93} 

94 

95_HEADER = """\ 

96# Generated by `scons` from {source}; edit that file instead. 

97# 

98# Example BPS submission of the {step} step of the CM Service campaign. 

99# Submit the steps in campaign order, each after the previous one has 

100# finished. Set the day_obs to process in a wrapper file and submit that: 

101# 

102# includeConfigs: 

103# - ${{AP_PIPE_DIR}}/{target} 

104# dayObs: 20261112 

105# 

106""" 

107 

108 

109def _replaceTemplate(match): 

110 if "".join(match.group(1).split()) not in _DAY_OBS_EXPRESSIONS: 

111 raise ValueError(f"Unsupported CM template expression: {match.group(0)}") 

112 return "{dayObs}" 

113 

114 

115def _renderTemplates(value): 

116 """Replace the CM day_obs template expressions in all strings of a 

117 YAML object with the BPS variable ``{dayObs}``. 

118 """ 

119 if isinstance(value, str): 

120 return _TEMPLATE_PATTERN.sub(_replaceTemplate, value) 

121 if isinstance(value, list): 

122 return [_renderTemplates(item) for item in value] 

123 if isinstance(value, dict): 

124 return {key: _renderTemplates(item) for key, item in value.items()} 

125 return value 

126 

127 

128def _selectManifest(documents, kind): 

129 """Return the single manifest of a kind, or the one marked default.""" 

130 candidates = [doc for doc in documents if doc.get("kind") == kind] 

131 if len(candidates) > 1: 

132 candidates = [doc for doc in candidates if doc.get("metadata", {}).get("default")] 

133 if len(candidates) != 1: 

134 raise ValueError(f"Campaign needs exactly one {kind!r} manifest, or one marked default.") 

135 return _renderTemplates(candidates[0]) 

136 

137 

138def _selectStep(documents, name): 

139 """Return the step node with a name, or the only step if name is 

140 `None`. 

141 """ 

142 steps = [ 

143 doc for doc in documents 

144 if doc.get("kind") == "node" and doc.get("metadata", {}).get("kind") == "step" 

145 ] 

146 if name is not None: 

147 steps = [doc for doc in steps if doc["metadata"].get("name") == name] 

148 if len(steps) != 1: 

149 raise ValueError(f"Campaign needs exactly one step node named {name!r}; found {len(steps)}.") 

150 elif len(steps) != 1: 

151 raise ValueError(f"Campaign has {len(steps)} step nodes; name the one to convert.") 

152 return _renderTemplates(steps[0]) 

153 

154 

155def _renderManifestVariables(value, variables): 

156 """Replace the CM manifest variables in all strings of a YAML object. 

157 

158 Parameters 

159 ---------- 

160 value : `object` 

161 YAML object to render. 

162 variables : `dict` [`str`, `str`] 

163 Values of the supported variables, keyed by their names without 

164 whitespace. 

165 

166 Returns 

167 ------- 

168 rendered : `object` 

169 A copy of ``value`` with the variables replaced. 

170 

171 Raises 

172 ------ 

173 ValueError 

174 Raised if ``value`` uses a variable not in ``variables``. 

175 """ 

176 def replace(match): 

177 name = "".join(match.group(1).split()) 

178 if name not in variables: 

179 raise ValueError(f"Unsupported CM manifest variable: {match.group(0)}") 

180 return variables[name] 

181 

182 if isinstance(value, str): 

183 return _MANIFEST_PATTERN.sub(replace, value) 

184 if isinstance(value, list): 

185 return [_renderManifestVariables(item, variables) for item in value] 

186 if isinstance(value, dict): 

187 return {key: _renderManifestVariables(item, variables) for key, item in value.items()} 

188 return value 

189 

190 

191def _asList(value): 

192 if value is None: 

193 return [] 

194 if isinstance(value, str): 194 ↛ 195line 194 didn't jump to line 195 because the condition on line 194 was never true

195 return [value] 

196 return list(value) 

197 

198 

199def readCampaign(path): 

200 """Read the manifests of a CM Service campaign definition. 

201 

202 Parameters 

203 ---------- 

204 path : `str` 

205 Multi-document campaign YAML file. 

206 

207 Returns 

208 ------- 

209 documents : `list` [`dict`] 

210 The non-empty YAML documents, in file order. 

211 """ 

212 with open(path) as stream: 

213 return [doc for doc in yaml.safe_load_all(stream) if doc] 

214 

215 

216def makeBpsConfig(documents, step=None): 

217 """Build a BPS submission config for one step of a CM Service campaign. 

218 

219 Parameters 

220 ---------- 

221 documents : `list` [`dict`] 

222 Campaign manifests, as returned by `readCampaign`. The campaign must 

223 have one ``bps``, ``butler``, ``lsst``, ``wms`` and ``site`` manifest 

224 each (or one of each kind marked default). 

225 step : `str`, optional 

226 Name of the step node to convert. May be omitted if the campaign has 

227 only one step. 

228 

229 Returns 

230 ------- 

231 config : `dict` 

232 BPS configuration, in the key order CM Service writes it. 

233 

234 Raises 

235 ------ 

236 ValueError 

237 Raised if the campaign does not have the manifests listed above or in 

238 the step, or uses a CM template expression other than the campaign's 

239 day_obs, or a CM manifest variable other than 

240 ``butler.collections.step_input``. 

241 

242 Notes 

243 ----- 

244 CM sets a step's input collection to a chain of the outputs of earlier 

245 steps and the campaign input. The standalone submissions of all steps 

246 share one output collection, which by the time a step runs holds the same 

247 collections, so ``butler.collections.step_input`` is rendered as that 

248 output collection. 

249 """ 

250 campaign = _selectManifest(documents, "campaign") 

251 stepNode = _selectStep(documents, step) 

252 lsst = _selectManifest(documents, "lsst")["spec"] 

253 butler = _selectManifest(documents, "butler")["spec"] 

254 wms = _WMS_DEFAULTS | _selectManifest(documents, "wms")["spec"] 

255 site = _SITE_DEFAULTS | _selectManifest(documents, "site")["spec"] 

256 # Step-level BPS settings take precedence over the campaign manifest. 

257 bps = _selectManifest(documents, "bps")["spec"] | (stepNode["spec"].get("bps") or {}) 

258 bps = _renderManifestVariables( 

259 bps, {"butler.collections.step_input": butler["collections"]["campaign_public_output"]} 

260 ) 

261 

262 config = {} 

263 for key in ("project", "campaign"): 

264 if lsst.get(key): 

265 config[key] = lsst[key] 

266 if bps.get("variables"): 266 ↛ 267line 266 didn't jump to line 267 because the condition on line 266 was never true

267 config.update({key: str(value) for key, value in bps["variables"].items()}) 

268 

269 config["pipelineYaml"] = bps["pipeline_yaml"] 

270 includes = [] 

271 for manifest in (lsst, bps, butler, wms, site): 

272 for include in _asList(manifest.get("include_files")): 

273 if include not in includes: 

274 includes.append(include) 

275 if includes: 275 ↛ 280line 275 didn't jump to line 280 because the condition on line 275 was always true

276 config["includeConfigs"] = includes 

277 

278 # CM exports the lsst manifest environment in the shell that runs 

279 # `bps submit`; a standalone submission needs it in the jobs. 

280 environment = (lsst.get("environment") or {}) | (bps.get("environment") or {}) 

281 if environment: 

282 config["environment"] = {key: str(value) for key, value in environment.items()} 

283 

284 collections = butler["collections"] 

285 config["payload"] = { 

286 "payloadName": campaign["metadata"]["name"], 

287 "butlerConfig": butler["repo"], 

288 "inCollection": ",".join(_asList(collections["campaign_input"])), 

289 "output": collections["campaign_public_output"], 

290 "dataQuery": " AND ".join(butler["predicates"]), 

291 } 

292 for field, key in _EXTRA_OPTIONS.items(): 

293 if bps.get(field): 

294 config[key] = " ".join(bps[field]) 

295 if bps.get("clustering"): 295 ↛ 296line 295 didn't jump to line 296 because the condition on line 295 was never true

296 config["cluster"] = bps["clustering"] 

297 

298 config["extraAggregateOptions"] = " ".join(bps.get("extra_aggregate_options") or _AGGREGATE_DEFAULT) 

299 config.update(bps.get("literals") or {}) 

300 

301 config["wmsServiceClass"] = wms["service_class"] 

302 config["computeSite"] = site["facility"] 

303 config.update(site.get("literals") or {}) 

304 if wms["auto_release"]: 304 ↛ 306line 304 didn't jump to line 306 because the condition on line 304 was always true

305 config["releaseExpr"] = wms["auto_release_expr"] 

306 if wms.get("batch_name"): 306 ↛ 307line 306 didn't jump to line 307 because the condition on line 306 was never true

307 config["nodeset"] = wms["batch_name"] 

308 if wms["auto_provision"]: 308 ↛ 321line 308 didn't jump to line 321 because the condition on line 308 was always true

309 extraOptions = [f"--cpu {wms['provisioned_cpu_count']}", *wms["provisioned_extra_arguments"]] 

310 config["provisionResources"] = True 

311 config["provisioning"] = { 

312 "provisioningNodeCount": wms["provisioned_node_count"], 

313 "provisioningMaxIdleTime": wms["provisioned_idle_time"], 

314 "provisioningMaxWallTime": wms["provisioned_max_wall_time"], 

315 "provisioningCheckInterval": wms["provisioned_check_interval"], 

316 "provisioningQueue": site["provisioned_queue"], 

317 "provisioningAccountingUser": site["provisioned_account_group"], 

318 "provisioningPlatform": site["provisioned_platform"], 

319 "provisioningExtraOptions": " ".join(extraOptions), 

320 } 

321 return config 

322 

323 

324def writeBpsConfig(config, path, source, step): 

325 """Write a BPS config made by `makeBpsConfig` with a usage header. 

326 

327 Parameters 

328 ---------- 

329 config : `dict` 

330 BPS configuration. 

331 path : `str` 

332 Output file, relative to the package root to give a usable header. 

333 Missing parent directories are created. 

334 source : `str` 

335 Campaign file the config was made from, named in the header. 

336 step : `str` 

337 Name of the campaign step the config was made from, named in the 

338 header. 

339 """ 

340 pathlib.Path(path).parent.mkdir(parents=True, exist_ok=True) 

341 with open(path, "w") as stream: 

342 stream.write(_HEADER.format(source=source, target=path, step=step)) 

343 yaml.safe_dump(config, stream, sort_keys=False, width=4096) 

344 

345 

346def main(argv=None): 

347 parser = argparse.ArgumentParser( 

348 description="Build a standalone BPS submission file from one step of a CM Service campaign." 

349 ) 

350 parser.add_argument("campaign", help="CM Service campaign definition YAML.") 

351 parser.add_argument("output", help="BPS submission YAML to write.") 

352 parser.add_argument("--step", help="Step node to convert; required if the campaign has several.") 

353 args = parser.parse_args(argv) 

354 

355 documents = readCampaign(args.campaign) 

356 step = _selectStep(documents, args.step)["metadata"]["name"] 

357 writeBpsConfig(makeBpsConfig(documents, step), args.output, args.campaign, step) 

358 

359 

360if __name__ == "__main__": 360 ↛ 361line 360 didn't jump to line 361 because the condition on line 360 was never true

361 main()