Coverage for python/lsst/summit/utils/tmaUtils.py: 20%

557 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-11-24 12:17 +0000

1# This file is part of summit_utils. 

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 

22import re 

23import enum 

24import itertools 

25import logging 

26import pandas as pd 

27import numpy as np 

28import humanize 

29from dataclasses import dataclass 

30from astropy.time import Time 

31from matplotlib.ticker import FuncFormatter 

32import matplotlib.dates as mdates 

33import matplotlib.pyplot as plt 

34from lsst.utils.iteration import ensure_iterable 

35 

36from .enums import AxisMotionState, PowerState 

37from .blockUtils import BlockParser 

38from .utils import getCurrentDayObs_int, dayObsIntToString 

39from .efdUtils import (getEfdData, 

40 makeEfdClient, 

41 efdTimestampToAstropy, 

42 COMMAND_ALIASES, 

43 getDayObsForTime, 

44 getDayObsStartTime, 

45 getDayObsEndTime, 

46 ) 

47 

48__all__ = ( 

49 'TMAStateMachine', 

50 'TMAEvent', 

51 'TMAEventMaker', 

52 'TMAState', 

53 'AxisMotionState', 

54 'PowerState', 

55 'getSlewsFromEventList', 

56 'getTracksFromEventList', 

57 'getTorqueMaxima', 

58) 

59 

60# we don't want to use `None` for a no data sentinel because dict.get('key') 

61# returns None if the key isn't present, and also we need to mark that the data 

62# was queried for and no data was found, whereas the key not being present 

63# means that we've not yet looked for the data. 

64NO_DATA_SENTINEL = "NODATA" 

65 

66 

67def getSlewsFromEventList(events): 

68 """Get the slew events from a list of TMAEvents. 

69 

70 Parameters 

71 ---------- 

72 events : `list` of `lsst.summit.utils.tmaUtils.TMAEvent` 

73 The list of events to filter. 

74 

75 Returns 

76 ------- 

77 events : `list` of `lsst.summit.utils.tmaUtils.TMAEvent` 

78 The filtered list of events. 

79 """ 

80 return [e for e in events if e.type == TMAState.SLEWING] 

81 

82 

83def getTracksFromEventList(events): 

84 """Get the tracking events from a list of TMAEvents. 

85 

86 Parameters 

87 ---------- 

88 events : `list` of `lsst.summit.utils.tmaUtils.TMAEvent` 

89 The list of events to filter. 

90 

91 Returns 

92 ------- 

93 events : `list` of `lsst.summit.utils.tmaUtils.TMAEvent` 

94 The filtered list of events. 

95 """ 

96 return [e for e in events if e.type == TMAState.TRACKING] 

97 

98 

99def getTorqueMaxima(table): 

100 """Print the maximum positive and negative azimuth and elevation torques. 

101 

102 Designed to be used with the table as downloaded from RubinTV. 

103 

104 Parameters 

105 ---------- 

106 table : `pd.DataFrame` 

107 The table of data to use, as generated by Rapid Analysis. 

108 """ 

109 for axis in ['elevation', 'azimuth']: 

110 col = f'Largest {axis} torque' 

111 maxPos = np.argmax(table[col]) 

112 maxVal = table[col].iloc[maxPos] 

113 print(f"Max positive {axis:9} torque during seqNum {maxPos:>4}: {maxVal/1000:>7.1f}kNm") 

114 minPos = np.argmin(table[col]) 

115 minVal = table[col].iloc[minPos] 

116 print(f"Max negative {axis:9} torque during seqNum {minPos:>4}: {minVal/1000:>7.1f}kNm") 

117 

118 

119def getAzimuthElevationDataForEvent(client, event, prePadding=0, postPadding=0): 

120 """Get the data for the az/el telemetry topics for a given TMAEvent. 

121 

122 Parameters 

123 ---------- 

124 client : `lsst_efd_client.efd_helper.EfdClient` 

125 The EFD client to use. 

126 event : `lsst.summit.utils.tmaUtils.TMAEvent` 

127 The event to get the data for. 

128 prePadding : `float`, optional 

129 The amount of time to pad the event with before the start time, in 

130 seconds. 

131 postPadding : `float`, optional 

132 The amount of time to pad the event with after the end time, in 

133 seconds. 

134 

135 Returns 

136 ------- 

137 azimuthData : `pd.DataFrame` 

138 The azimuth data for the specified event. 

139 elevationData : `pd.DataFrame` 

140 The elevation data for the specified event. 

141 """ 

142 azimuthData = getEfdData(client, 

143 'lsst.sal.MTMount.azimuth', 

144 event=event, 

145 prePadding=prePadding, 

146 postPadding=postPadding) 

147 elevationData = getEfdData(client, 

148 'lsst.sal.MTMount.elevation', 

149 event=event, 

150 prePadding=prePadding, 

151 postPadding=postPadding) 

152 

153 return azimuthData, elevationData 

154 

155 

156def plotEvent(client, event, fig=None, prePadding=0, postPadding=0, commands={}, 

157 azimuthData=None, elevationData=None): 

158 """Plot the TMA axis positions over the course of a given TMAEvent. 

159 

160 Plots the axis motion profiles for the given event, with optional padding 

161 at the start and end of the event. If the data is provided via the 

162 azimuthData and elevationData parameters, it will be used, otherwise it 

163 will be queried from the EFD. 

164 

165 Optionally plots any commands issued during or around the event, if these 

166 are supplied. Commands are supplied as a dictionary of the command topic 

167 strings, with values as astro.time.Time objects at which the command was 

168 issued. 

169 

170 Parameters 

171 ---------- 

172 client : `lsst_efd_client.efd_helper.EfdClient` 

173 The EFD client to use. 

174 event : `lsst.summit.utils.tmaUtils.TMAEvent` 

175 The event to plot. 

176 fig : `matplotlib.figure.Figure`, optional 

177 The figure to plot on. If not specified, a new figure will be created. 

178 prePadding : `float`, optional 

179 The amount of time to pad the event with before the start time, in 

180 seconds. 

181 postPadding : `float`, optional 

182 The amount of time to pad the event with after the end time, in 

183 seconds. 

184 commands : `dict` of `str` : `astropy.time.Time`, optional 

185 A dictionary of commands to plot on the figure. The keys are the topic 

186 names, and the values are the times at which the commands were sent. 

187 azimuthData : `pd.DataFrame`, optional 

188 The azimuth data to plot. If not specified, it will be queried from the 

189 EFD. 

190 elevationData : `pd.DataFrame`, optional 

191 The elevation data to plot. If not specified, it will be queried from 

192 the EFD. 

193 

194 Returns 

195 ------- 

196 fig : `matplotlib.figure.Figure` 

197 The figure on which the plot was made. 

198 """ 

199 def tickFormatter(value, tick_number): 

200 # Convert the value to a string without subtracting large numbers 

201 # tick_number is unused. 

202 return f"{value:.2f}" 

203 

204 # plot any commands we might have 

205 if not isinstance(commands, dict): 

206 raise TypeError('commands must be a dict of command names with values as' 

207 ' astropy.time.Time values') 

208 

209 if fig is None: 

210 fig = plt.figure(figsize=(10, 8)) 

211 log = logging.getLogger(__name__) 

212 log.warning("Making new matplotlib figure - if this is in a loop you're going to have a bad time." 

213 " Pass in a figure with fig = plt.figure(figsize=(10, 8)) to avoid this warning.") 

214 

215 fig.clear() 

216 ax1, ax2 = fig.subplots(2, 

217 sharex=True, 

218 gridspec_kw={'wspace': 0, 

219 'hspace': 0, 

220 'height_ratios': [2.5, 1]}) 

221 

222 if azimuthData is None or elevationData is None: 

223 azimuthData, elevationData = getAzimuthElevationDataForEvent(client, 

224 event, 

225 prePadding=prePadding, 

226 postPadding=postPadding) 

227 

228 # Use the native color cycle for the lines. Because they're on different 

229 # axes they don't cycle by themselves 

230 lineColors = [p['color'] for p in plt.rcParams['axes.prop_cycle']] 

231 colorCounter = 0 

232 

233 ax1.plot(azimuthData['actualPosition'], label='Azimuth position', c=lineColors[colorCounter]) 

234 colorCounter += 1 

235 ax1.yaxis.set_major_formatter(FuncFormatter(tickFormatter)) 

236 ax1.set_ylabel('Azimuth (degrees)') 

237 

238 ax1_twin = ax1.twinx() 

239 ax1_twin.plot(elevationData['actualPosition'], label='Elevation position', c=lineColors[colorCounter]) 

240 colorCounter += 1 

241 ax1_twin.yaxis.set_major_formatter(FuncFormatter(tickFormatter)) 

242 ax1_twin.set_ylabel('Elevation (degrees)') 

243 ax1.set_xticks([]) # remove x tick labels on the hidden upper x-axis 

244 

245 ax2_twin = ax2.twinx() 

246 ax2.plot(azimuthData['actualTorque'], label='Azimuth torque', c=lineColors[colorCounter]) 

247 colorCounter += 1 

248 ax2_twin.plot(elevationData['actualTorque'], label='Elevation torque', c=lineColors[colorCounter]) 

249 colorCounter += 1 

250 ax2.set_ylabel('Azimuth torque (Nm)') 

251 ax2_twin.set_ylabel('Elevation torque (Nm)') 

252 ax2.set_xlabel('Time (UTC)') # yes, it really is UTC, matplotlib converts this automatically! 

253 

254 # put the ticks at an angle, and right align with the tick marks 

255 ax2.set_xticks(ax2.get_xticks()) # needed to supress a user warning 

256 xlabels = ax2.get_xticks() 

257 ax2.set_xticklabels(xlabels, rotation=40, ha='right') 

258 ax2.xaxis.set_major_locator(mdates.AutoDateLocator()) 

259 ax2.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S')) 

260 

261 if prePadding or postPadding: 

262 # note the conversion to utc because the x-axis from the dataframe 

263 # already got automagically converted when plotting before, so this is 

264 # necessary for things to line up 

265 ax1_twin.axvline(event.begin.utc.datetime, c='k', ls='--', alpha=0.5, label='Event begin/end') 

266 ax1_twin.axvline(event.end.utc.datetime, c='k', ls='--', alpha=0.5) 

267 # extend lines down across lower plot, but do not re-add label 

268 ax2_twin.axvline(event.begin.utc.datetime, c='k', ls='--', alpha=0.5) 

269 ax2_twin.axvline(event.end.utc.datetime, c='k', ls='--', alpha=0.5) 

270 

271 for command, commandTime in commands.items(): 

272 # if commands weren't found, the item is set to None. This is common 

273 # for events so handle it gracefully and silently. The command finding 

274 # code logs about lack of commands found so no need to mention here. 

275 if commandTime is None: 

276 continue 

277 ax1_twin.axvline(commandTime.utc.datetime, c=lineColors[colorCounter], 

278 ls='--', alpha=0.75, label=f'{command}') 

279 # extend lines down across lower plot, but do not re-add label 

280 ax2_twin.axvline(commandTime.utc.datetime, c=lineColors[colorCounter], 

281 ls='--', alpha=0.75) 

282 colorCounter += 1 

283 

284 # combine the legends and put inside the plot 

285 handles1a, labels1a = ax1.get_legend_handles_labels() 

286 handles1b, labels1b = ax1_twin.get_legend_handles_labels() 

287 handles2a, labels2a = ax2.get_legend_handles_labels() 

288 handles2b, labels2b = ax2_twin.get_legend_handles_labels() 

289 

290 handles = handles1a + handles1b + handles2a + handles2b 

291 labels = labels1a + labels1b + labels2a + labels2b 

292 # ax2 is "in front" of ax1 because it has the vlines plotted on it, and 

293 # vlines are on ax2 so that they appear at the bottom of the legend, so 

294 # make sure to plot the legend on ax2, otherwise the vlines will go on top 

295 # of the otherwise-opaque legend. 

296 ax1_twin.legend(handles, labels, facecolor='white', framealpha=1) 

297 

298 # Add title with the event name, type etc 

299 dayObsStr = dayObsIntToString(event.dayObs) 

300 title = (f"{dayObsStr} - seqNum {event.seqNum} (version {event.version})" # top line, rest below 

301 f"\nDuration = {event.duration:.2f}s" 

302 f" Event type: {event.type.name}" 

303 f" End reason: {event.endReason.name}" 

304 ) 

305 ax1_twin.set_title(title) 

306 return fig 

307 

308 

309def getCommandsDuringEvent(client, event, commands=('raDecTarget'), log=None, doLog=True): 

310 """Get the commands issued during an event. 

311 

312 Get the times at which the specified commands were issued during the event. 

313 

314 Parameters 

315 ---------- 

316 client : `lsst_efd_client.efd_helper.EfdClient` 

317 The EFD client to use. 

318 event : `lsst.summit.utils.tmaUtils.TMAEvent` 

319 The event to plot. 

320 commands : `list` of `str`, optional 

321 The commands or command aliases to look for. Defaults to 

322 ['raDecTarget']. 

323 log : `logging.Logger`, optional 

324 The logger to use. If not specified, a new logger will be created if 

325 needed. 

326 doLog : `bool`, optional 

327 Whether to log messages. Defaults to True. 

328 

329 Returns 

330 ------- 

331 commands : `dict` of `str` : `astropy.time.Time` 

332 A dictionary of the commands and the times at which they were issued. 

333 """ 

334 # TODO: DM-40100 Add support for padding the event here to allow looking 

335 # for triggering commands before the event 

336 

337 # TODO: DM-40100 Change this to always return a list of times, and remove 

338 # warning about finding multiple commands. Remember to update docs and 

339 # plotting code. 

340 if log is None and doLog: 

341 log = logging.getLogger(__name__) 

342 

343 commands = ensure_iterable(commands) 

344 fullCommands = [c if c not in COMMAND_ALIASES else COMMAND_ALIASES[c] for c in commands] 

345 del commands # make sure we always use their full names 

346 

347 ret = {} 

348 for command in fullCommands: 

349 data = getEfdData(client, command, event=event, warn=False) 

350 if data.empty: 

351 if doLog: 

352 log.info(f'Found no command issued for {command} during event') 

353 ret[command] = None 

354 elif len(data) > 1: 

355 if doLog: 

356 log.warning(f'Found multiple commands issued for {command} during event, returning None') 

357 ret[command] = None 

358 else: 

359 assert len(data) == 1 # this must be true now 

360 commandTime = data.private_efdStamp 

361 ret[command] = Time(commandTime, format='unix') 

362 

363 return ret 

364 

365 

366def _initializeTma(tma): 

367 """Helper function to turn a TMA into a valid state for testing. 

368 

369 Do not call directly in normal usage or code, as this just arbitrarily 

370 sets values to make the TMA valid. 

371 

372 Parameters 

373 ---------- 

374 tma : `lsst.summit.utils.tmaUtils.TMAStateMachine` 

375 The TMA state machine model to initialize. 

376 """ 

377 tma._parts['azimuthInPosition'] = False 

378 tma._parts['azimuthMotionState'] = AxisMotionState.STOPPED 

379 tma._parts['azimuthSystemState'] = PowerState.ON 

380 tma._parts['elevationInPosition'] = False 

381 tma._parts['elevationMotionState'] = AxisMotionState.STOPPED 

382 tma._parts['elevationSystemState'] = PowerState.ON 

383 

384 

385@dataclass(kw_only=True, frozen=True) 

386class TMAEvent: 

387 """A movement event for the TMA. 

388 

389 Contains the dayObs on which the event occured, using the standard 

390 observatory definition of the dayObs, and the sequence number of the event, 

391 which is unique for each event on a given dayObs. 

392 

393 The event type can be either 'SLEWING' or 'TRACKING', defined as: 

394 - SLEWING: some part of the TMA is in motion 

395 - TRACKING: both axes are in position and tracking the sky 

396 

397 The end reason can be 'STOPPED', 'TRACKING', 'FAULT', 'SLEWING', or 'OFF'. 

398 - SLEWING: The previous event was a TRACKING event, and one or more of 

399 the TMA components either stopped being in position, or stopped 

400 moving, or went into fault, or was turned off, and hence we are now 

401 only slewing and no longer tracking the sky. 

402 - TRACKING: the TMA started tracking the sky when it wasn't previously. 

403 Usualy this would always be preceded by directly by a SLEWING 

404 event, but this is not strictly true, as the EUI seems to be able 

405 to make the TMA start tracking the sky without slewing first. 

406 - STOPPED: the components of the TMA transitioned to the STOPPED state. 

407 - FAULT: the TMA went into fault. 

408 - OFF: the TMA components were turned off. 

409 

410 Note that this class is not intended to be instantiated directly, but 

411 rather to be returned by the ``TMAEventMaker.getEvents()`` function. 

412 

413 Parameters 

414 ---------- 

415 dayObs : `int` 

416 The dayObs on which the event occured. 

417 seqNum : `int` 

418 The sequence number of the event, 

419 type : `lsst.summit.utils.tmaUtils.TMAState` 

420 The type of the event, either 'SLEWING' or 'TRACKING'. 

421 endReason : `lsst.summit.utils.tmaUtils.TMAState` 

422 The reason the event ended, either 'STOPPED', 'TRACKING', 'FAULT', 

423 'SLEWING', or 'OFF'. 

424 duration : `float` 

425 The duration of the event, in seconds. 

426 begin : `astropy.time.Time` 

427 The time the event began. 

428 end : `astropy.time.Time` 

429 The time the event ended. 

430 blockInfos : `list` of `lsst.summit.utils.tmaUtils.BlockInfo`, or `None` 

431 The block infomation, if any, relating to the event. Could be `None`, 

432 or one or more block informations. 

433 version : `int` 

434 The version of the TMAEvent class. Equality between events is only 

435 valid for a given version of the class. If the class definition 

436 changes, the time ranges can change, and hence the equality between 

437 events is ``False``. 

438 _startRow : `int` 

439 The first row in the merged EFD data which is part of the event. 

440 _endRow : `int` 

441 The last row in the merged EFD data which is part of the event. 

442 """ 

443 dayObs: int 

444 seqNum: int 

445 type: str # can be 'SLEWING', 'TRACKING' 

446 endReason: str # can be 'STOPPED', 'TRACKING', 'FAULT', 'SLEWING', 'OFF' 

447 duration: float # seconds 

448 begin: Time 

449 end: Time 

450 blockInfos: list = None 

451 version: int = 0 # update this number any time a code change which could change event definitions is made 

452 _startRow: int 

453 _endRow: int 

454 

455 def __lt__(self, other): 

456 if self.version != other.version: 

457 raise ValueError( 

458 f"Cannot compare TMAEvents with different versions: {self.version} != {other.version}" 

459 ) 

460 if self.dayObs < other.dayObs: 

461 return True 

462 elif self.dayObs == other.dayObs: 

463 return self.seqNum < other.seqNum 

464 return False 

465 

466 def __repr__(self): 

467 return ( 

468 f"TMAEvent(dayObs={self.dayObs}, seqNum={self.seqNum}, type={self.type!r}," 

469 f" endReason={self.endReason!r}, duration={self.duration}, begin={self.begin!r}," 

470 f" end={self.end!r}" 

471 ) 

472 

473 def _ipython_display_(self): 

474 print(self.__str__()) 

475 

476 def __str__(self): 

477 def indent(string): 

478 return '\n' + '\n'.join([' ' + s for s in string.splitlines()]) 

479 

480 blockInfoStr = 'None' 

481 if self.blockInfos is not None: 

482 blockInfoStr = ''.join(indent(str(i)) for i in self.blockInfos) 

483 

484 return ( 

485 f"dayObs: {self.dayObs}\n" 

486 f"seqNum: {self.seqNum}\n" 

487 f"type: {self.type.name}\n" 

488 f"endReason: {self.endReason.name}\n" 

489 f"duration: {self.duration}\n" 

490 f"begin: {self.begin!r}\n" 

491 f"end: {self.end!r}\n" 

492 f"blockInfos: {blockInfoStr}" 

493 ) 

494 

495 

496class TMAState(enum.IntEnum): 

497 """Overall state of the TMA. 

498 

499 States are defined as follows: 

500 

501 UNINITIALIZED 

502 We have not yet got data for all relevant components, so the overall 

503 state is undefined. 

504 STOPPED 

505 All components are on, and none are moving. 

506 TRACKING 

507 We are tracking the sky. 

508 SLEWING 

509 One or more components are moving, and one or more are not tracking the 

510 sky. This should probably be called MOVING, as it includes: slewing, 

511 MOVING_POINT_TO_POINT, and JOGGING. 

512 FAULT 

513 All (if engineeringMode) or any (if not engineeringMode) components are 

514 in fault. 

515 OFF 

516 All components are off. 

517 """ 

518 UNINITIALIZED = -1 

519 STOPPED = 0 

520 TRACKING = 1 

521 SLEWING = 2 

522 FAULT = 3 

523 OFF = 4 

524 

525 def __repr__(self): 

526 return f"TMAState.{self.name}" 

527 

528 

529def getAxisAndType(rowFor): 

530 """Get the axis the data relates to, and the type of data it contains. 

531 

532 Parameters 

533 ---------- 

534 rowFor : `str` 

535 The column in the dataframe denoting what this row is for, e.g. 

536 "elevationMotionState" or "azimuthInPosition", etc. 

537 

538 Returns 

539 ------- 

540 axis : `str` 

541 The axis the row is for, e.g. "azimuth", "elevation". 

542 rowType : `str` 

543 The type of the row, e.g. "MotionState", "SystemState", "InPosition". 

544 """ 

545 regex = r'(azimuth|elevation)(InPosition|MotionState|SystemState)$' # matches the end of the line 

546 matches = re.search(regex, rowFor) 

547 if matches is None: 

548 raise ValueError(f"Could not parse axis and rowType from {rowFor=}") 

549 axis = matches.group(1) 

550 rowType = matches.group(2) 

551 

552 assert rowFor.endswith(f"{axis}{rowType}") 

553 return axis, rowType 

554 

555 

556class ListViewOfDict: 

557 """A class to allow making lists which contain references to an underlying 

558 dictionary. 

559 

560 Normally, making a list of items from a dictionary would make a copy of the 

561 items, but this class allows making a list which contains references to the 

562 underlying dictionary items themselves. This is useful for making a list of 

563 components, such that they can be manipulated in their logical sets. 

564 """ 

565 def __init__(self, underlyingDictionary, keysToLink): 

566 self.dictionary = underlyingDictionary 

567 self.keys = keysToLink 

568 

569 def __getitem__(self, index): 

570 return self.dictionary[self.keys[index]] 

571 

572 def __setitem__(self, index, value): 

573 self.dictionary[self.keys[index]] = value 

574 

575 def __len__(self): 

576 return len(self.keys) 

577 

578 

579class TMAStateMachine: 

580 """A state machine model of the TMA. 

581 

582 Note that this is currently only implemented for the azimuth and elevation 

583 axes, but will be extended to include the rotator in the future. 

584 

585 Note that when used for event generation, changing ``engineeringMode`` to 

586 False might change the resulting list of events, and that if the TMA moves 

587 with some axis in fault, then these events will be missed. It is therefore 

588 thought that ``engineeringMode=True`` should always be used when generating 

589 events. The option, however, is there for completeness, as this will be 

590 useful for knowing is the CSC would consider the TMA to be in fault in the 

591 general case. 

592 

593 Parameters 

594 ---------- 

595 engineeringMode : `bool`, optional 

596 Whether the TMA is in engineering mode. Defaults to True. If False, 

597 then the TMA will be in fault if any component is in fault. If True, 

598 then the TMA will be in fault only if all components are in fault. 

599 debug : `bool`, optional 

600 Whether to log debug messages. Defaults to False. 

601 """ 

602 _UNINITIALIZED_VALUE: int = -999 

603 

604 def __init__(self, engineeringMode=True, debug=False): 

605 self.engineeringMode = engineeringMode 

606 self.log = logging.getLogger('lsst.summit.utils.tmaUtils.TMA') 

607 if debug: 

608 self.log.level = logging.DEBUG 

609 self._mostRecentRowTime = -1 

610 

611 # the actual components of the TMA 

612 self._parts = {'azimuthInPosition': self._UNINITIALIZED_VALUE, 

613 'azimuthMotionState': self._UNINITIALIZED_VALUE, 

614 'azimuthSystemState': self._UNINITIALIZED_VALUE, 

615 'elevationInPosition': self._UNINITIALIZED_VALUE, 

616 'elevationMotionState': self._UNINITIALIZED_VALUE, 

617 'elevationSystemState': self._UNINITIALIZED_VALUE, 

618 } 

619 systemKeys = ['azimuthSystemState', 'elevationSystemState'] 

620 positionKeys = ['azimuthInPosition', 'elevationInPosition'] 

621 motionKeys = ['azimuthMotionState', 'elevationMotionState'] 

622 

623 # references to the _parts as conceptual groupings 

624 self.system = ListViewOfDict(self._parts, systemKeys) 

625 self.motion = ListViewOfDict(self._parts, motionKeys) 

626 self.inPosition = ListViewOfDict(self._parts, positionKeys) 

627 

628 # tuples of states for state collapsing. Note that STOP_LIKE + 

629 # MOVING_LIKE must cover the full set of AxisMotionState enums 

630 self.STOP_LIKE = (AxisMotionState.STOPPING, 

631 AxisMotionState.STOPPED, 

632 AxisMotionState.TRACKING_PAUSED) 

633 self.MOVING_LIKE = (AxisMotionState.MOVING_POINT_TO_POINT, 

634 AxisMotionState.JOGGING, 

635 AxisMotionState.TRACKING) 

636 # Likewise, ON_LIKE + OFF_LIKE must cover the full set of PowerState 

637 # enums 

638 self.OFF_LIKE = (PowerState.OFF, PowerState.TURNING_OFF) 

639 self.ON_LIKE = (PowerState.ON, PowerState.TURNING_ON) 

640 self.FAULT_LIKE = (PowerState.FAULT,) # note the trailing comma - this must be an iterable 

641 

642 def apply(self, row): 

643 """Apply a row of data to the TMA state. 

644 

645 Checks that the row contains data for a later time than any data 

646 previously applied, and applies the relevant column entry to the 

647 relevant component. 

648 

649 Parameters 

650 ---------- 

651 row : `pd.Series` 

652 The row of data to apply to the state machine. 

653 """ 

654 timestamp = row['private_efdStamp'] 

655 if timestamp < self._mostRecentRowTime: # NB equals is OK, technically, though it never happens 

656 raise ValueError('TMA evolution must be monotonic increasing in time, tried to apply a row which' 

657 ' predates the most previous one') 

658 self._mostRecentRowTime = timestamp 

659 

660 rowFor = row['rowFor'] # e.g. elevationMotionState 

661 axis, rowType = getAxisAndType(rowFor) # e.g. elevation, MotionState 

662 value = self._getRowPayload(row, rowType, rowFor) 

663 self.log.debug(f"Setting {rowFor} to {repr(value)}") 

664 self._parts[rowFor] = value 

665 try: 

666 # touch the state property as this executes the sieving, to make 

667 # sure we don't fall through the sieve at any point in time 

668 _ = self.state 

669 except RuntimeError as e: 

670 # improve error reporting, but always reraise this, as this is a 

671 # full-blown failure 

672 raise RuntimeError(f'Failed to apply {value} to {axis}{rowType} with state {self._parts}') from e 

673 

674 def _getRowPayload(self, row, rowType, rowFor): 

675 """Get the relevant value from the row. 

676 

677 Given the row, and which component it relates to, get the relevant 

678 value, as a bool or cast to the appropriate enum class. 

679 

680 Parameters 

681 ---------- 

682 row : `pd.Series` 

683 The row of data from the dataframe. 

684 rowType : `str` 

685 The type of the row, e.g. "MotionState", "SystemState", 

686 "InPosition". 

687 rowFor : `str` 

688 The component the row is for, e.g. "azimuth", "elevation". 

689 

690 Returns 

691 ------- 

692 value : `bool` or `enum` 

693 The value of the row, as a bool or enum, depending on the 

694 component, cast to the appropriate enum class or bool. 

695 """ 

696 match rowType: 

697 case 'MotionState': 

698 value = row[f'state_{rowFor}'] 

699 return AxisMotionState(value) 

700 case 'SystemState': 

701 value = row[f'powerState_{rowFor}'] 

702 return PowerState(value) 

703 case 'InPosition': 

704 value = row[f'inPosition_{rowFor}'] 

705 return bool(value) 

706 case _: 

707 raise ValueError(f'Failed to get row payload with {rowType=} and {row=}') 

708 

709 @property 

710 def _isValid(self): 

711 """Has the TMA had a value applied to all its components? 

712 

713 If any component has not yet had a value applied, the TMA is not valid, 

714 as those components will be in an unknown state. 

715 

716 Returns 

717 ------- 

718 isValid : `bool` 

719 Whether the TMA is fully initialized. 

720 """ 

721 return not any([v == self._UNINITIALIZED_VALUE for v in self._parts.values()]) 

722 

723 # state inspection properties - a high level way of inspecting the state as 

724 # an API 

725 @property 

726 def isMoving(self): 

727 return self.state in [TMAState.TRACKING, TMAState.SLEWING] 

728 

729 @property 

730 def isNotMoving(self): 

731 return not self.isMoving 

732 

733 @property 

734 def isTracking(self): 

735 return self.state == TMAState.TRACKING 

736 

737 @property 

738 def isSlewing(self): 

739 return self.state == TMAState.SLEWING 

740 

741 @property 

742 def canMove(self): 

743 badStates = [PowerState.OFF, PowerState.TURNING_OFF, PowerState.FAULT, PowerState.UNKNOWN] 

744 return bool( 

745 self._isValid and 

746 self._parts['azimuthSystemState'] not in badStates and 

747 self._parts['elevationSystemState'] not in badStates 

748 ) 

749 

750 # Axis inspection properties, designed for internal use. These return 

751 # iterables so that they can be used in any() and all() calls, which make 

752 # the logic much easier to read, e.g. to see if anything is moving, we can 

753 # write `if not any(_axisInMotion):` 

754 @property 

755 def _axesInFault(self): 

756 return [x in self.FAULT_LIKE for x in self.system] 

757 

758 @property 

759 def _axesOff(self): 

760 return [x in self.OFF_LIKE for x in self.system] 

761 

762 @property 

763 def _axesOn(self): 

764 return [not x for x in self._axesOn] 

765 

766 @property 

767 def _axesInMotion(self): 

768 return [x in self.MOVING_LIKE for x in self.motion] 

769 

770 @property 

771 def _axesTRACKING(self): 

772 """Note this is deliberately named _axesTRACKING and not _axesTracking 

773 to make it clear that this is the AxisMotionState type of TRACKING and 

774 not the normal conceptual notion of tracking (the sky, i.e. as opposed 

775 to slewing). 

776 """ 

777 return [x == AxisMotionState.TRACKING for x in self.motion] 

778 

779 @property 

780 def _axesInPosition(self): 

781 return [x is True for x in self.inPosition] 

782 

783 @property 

784 def state(self): 

785 """The overall state of the TMA. 

786 

787 Note that this is both a property, and also the method which applies 

788 the logic sieve to determine the state at a given point in time. 

789 

790 Returns 

791 ------- 

792 state : `lsst.summit.utils.tmaUtils.TMAState` 

793 The overall state of the TMA. 

794 """ 

795 # first, check we're valid, and if not, return UNINITIALIZED state, as 

796 # things are unknown 

797 if not self._isValid: 

798 return TMAState.UNINITIALIZED 

799 

800 # if we're not in engineering mode, i.e. we're under normal CSC 

801 # control, then if anything is in fault, we're in fault. If we're 

802 # engineering then some axes will move when others are in fault 

803 if not self.engineeringMode: 

804 if any(self._axesInFault): 

805 return TMAState.FAULT 

806 else: 

807 # we're in engineering mode, so return fault state if ALL are in 

808 # fault 

809 if all(self._axesInFault): 

810 return TMAState.FAULT 

811 

812 # if all axes are off, the TMA is OFF 

813 if all(self._axesOff): 

814 return TMAState.OFF 

815 

816 # we know we're valid and at least some axes are not off, so see if 

817 # we're in motion if no axes are moving, we're stopped 

818 if not any(self._axesInMotion): 

819 return TMAState.STOPPED 

820 

821 # now we know we're initialized, and that at least one axis is moving 

822 # so check axes for motion and in position. If all axes are tracking 

823 # and all are in position, we're tracking the sky 

824 if (all(self._axesTRACKING) and all(self._axesInPosition)): 

825 return TMAState.TRACKING 

826 

827 # we now know explicitly that not everything is in position, so we no 

828 # longer need to check that. We do actually know that something is in 

829 # motion, but confirm that's the case and return SLEWING 

830 if (any(self._axesInMotion)): 

831 return TMAState.SLEWING 

832 

833 # if we want to differentiate between MOVING_POINT_TO_POINT moves, 

834 # JOGGING moves and regular slews, the logic in the step above needs to 

835 # be changed and the new steps added here. 

836 

837 raise RuntimeError('State error: fell through the state sieve - rewrite your logic!') 

838 

839 

840class TMAEventMaker: 

841 """A class to create per-dayObs TMAEvents for the TMA's movements. 

842 

843 Example usage: 

844 >>> dayObs = 20230630 

845 >>> eventMaker = TMAEventMaker() 

846 >>> events = eventMaker.getEvents(dayObs) 

847 >>> print(f'Found {len(events)} for {dayObs=}') 

848 

849 Parameters 

850 ---------- 

851 client : `lsst_efd_client.efd_helper.EfdClient`, optional 

852 The EFD client to use, created if not provided. 

853 """ 

854 # the topics which need logical combination to determine the overall mount 

855 # state. Will need updating as new components are added to the system. 

856 

857 # relevant column: 'state' 

858 _movingComponents = [ 

859 'lsst.sal.MTMount.logevent_azimuthMotionState', 

860 'lsst.sal.MTMount.logevent_elevationMotionState', 

861 ] 

862 

863 # relevant column: 'inPosition' 

864 _inPositionComponents = [ 

865 'lsst.sal.MTMount.logevent_azimuthInPosition', 

866 'lsst.sal.MTMount.logevent_elevationInPosition', 

867 ] 

868 

869 # the components which, if in fault, put the TMA into fault 

870 # relevant column: 'powerState' 

871 _stateComponents = [ 

872 'lsst.sal.MTMount.logevent_azimuthSystemState', 

873 'lsst.sal.MTMount.logevent_elevationSystemState', 

874 ] 

875 

876 def __init__(self, client=None): 

877 if client is not None: 

878 self.client = client 

879 else: 

880 self.client = makeEfdClient() 

881 self.log = logging.getLogger(__name__) 

882 self._data = {} 

883 

884 @dataclass(frozen=True) 

885 class ParsedState: 

886 eventStart: Time 

887 eventEnd: int 

888 previousState: TMAState 

889 state: TMAState 

890 

891 @staticmethod 

892 def isToday(dayObs): 

893 """Find out if the specified dayObs is today, or in the past. 

894 

895 If the day is today, the function returns ``True``, if it is in the 

896 past it returns ``False``. If the day is in the future, a 

897 ``ValueError`` is raised, as this indicates there is likely an 

898 off-by-one type error somewhere in the logic. 

899 

900 Parameters 

901 ---------- 

902 dayObs : `int` 

903 The dayObs to check, in the format YYYYMMDD. 

904 

905 Returns 

906 ------- 

907 isToday : `bool` 

908 ``True`` if the dayObs is today, ``False`` if it is in the past. 

909 

910 Raises 

911 ValueError: if the dayObs is in the future. 

912 """ 

913 todayDayObs = getCurrentDayObs_int() 

914 if dayObs == todayDayObs: 

915 return True 

916 if dayObs > todayDayObs: 

917 raise ValueError("dayObs is in the future") 

918 return False 

919 

920 @staticmethod 

921 def _shortName(topic): 

922 """Get the short name of a topic. 

923 

924 Parameters 

925 ---------- 

926 topic : `str` 

927 The topic to get the short name of. 

928 

929 Returns 

930 ------- 

931 shortName : `str` 

932 The short name of the topic, e.g. 'azimuthInPosition' 

933 """ 

934 # get, for example 'azimuthInPosition' from 

935 # lsst.sal.MTMount.logevent_azimuthInPosition 

936 return topic.split('_')[-1] 

937 

938 def _mergeData(self, data): 

939 """Merge a dict of dataframes based on private_efdStamp, recording 

940 where each row came from. 

941 

942 Given a dict or dataframes, keyed by topic, merge them into a single 

943 dataframe, adding a column to record which topic each row came from. 

944 

945 Parameters 

946 ---------- 

947 data : `dict` of `str` : `pd.DataFrame` 

948 The dataframes to merge. 

949 

950 Returns 

951 ------- 

952 merged : `pd.DataFrame` 

953 The merged dataframe. 

954 """ 

955 excludeColumns = ['private_efdStamp', 'rowFor'] 

956 

957 mergeArgs = { 

958 'how': 'outer', 

959 'sort': True, 

960 } 

961 

962 merged = None 

963 originalRowCounter = 0 

964 

965 # Iterate over the keys and merge the corresponding DataFrames 

966 for key, df in data.items(): 

967 if df.empty: 

968 # Must skip the df if it's empty, otherwise the merge will fail 

969 # due to lack of private_efdStamp. Because other axes might 

970 # still be in motion, so we still want to merge what we have 

971 continue 

972 

973 originalRowCounter += len(df) 

974 component = self._shortName(key) # Add suffix to column names to identify the source 

975 suffix = '_' + component 

976 

977 df['rowFor'] = component 

978 

979 columnsToSuffix = [col for col in df.columns if col not in excludeColumns] 

980 df_to_suffix = df[columnsToSuffix].add_suffix(suffix) 

981 df = pd.concat([df[excludeColumns], df_to_suffix], axis=1) 

982 

983 if merged is None: 

984 merged = df.copy() 

985 else: 

986 merged = pd.merge(merged, df, **mergeArgs) 

987 

988 merged = merged.loc[:, ~merged.columns.duplicated()] # Remove duplicate columns after merge 

989 

990 if len(merged) != originalRowCounter: 

991 self.log.warning("Merged data has a different number of rows to the original data, some" 

992 " timestamps (rows) will contain more than one piece of actual information.") 

993 

994 # if the index is still a DatetimeIndex here then we didn't actually 

995 # merge any data, so there is only data from a single component. 

996 # This is likely to result in no events, but not necessarily, and for 

997 # generality, instead we convert to a range index to ensure consistency 

998 # in the returned data, and allow processing to continue. 

999 if isinstance(merged.index, pd.DatetimeIndex): 

1000 self.log.warning("Data was only found for a single component in the EFD.") 

1001 merged.reset_index(drop=True, inplace=True) 

1002 

1003 return merged 

1004 

1005 def getEvent(self, dayObs, seqNum): 

1006 """Get a specific event for a given dayObs and seqNum. 

1007 

1008 Repeated calls for the same ``dayObs`` will use the cached data if the 

1009 day is in the past, and so will be much quicker. If the ``dayObs`` is 

1010 the current day then the EFD will be queried for new data for each 

1011 call, so a call which returns ``None`` on the first try might return an 

1012 event on the next, if the TMA is still moving and thus generating 

1013 events. 

1014 

1015 Parameters 

1016 ---------- 

1017 dayObs : `int` 

1018 The dayObs to get the event for. 

1019 seqNum : `int` 

1020 The sequence number of the event to get. 

1021 

1022 Returns 

1023 ------- 

1024 event : `lsst.summit.utils.tmaUtils.TMAEvent` 

1025 The event for the specified dayObs and seqNum, or `None` if the 

1026 event was not found. 

1027 """ 

1028 events = self.getEvents(dayObs) 

1029 if seqNum <= len(events): 

1030 event = events[seqNum] 

1031 if event.seqNum != seqNum: 

1032 # it's zero-indexed and contiguous so this must be true but 

1033 # a sanity check doesn't hurt. 

1034 raise AssertionError(f"Event sequence number mismatch: {event.seqNum} != {seqNum}") 

1035 return event 

1036 else: 

1037 self.log.warning(f"Event {seqNum} not found for {dayObs}") 

1038 return None 

1039 

1040 def getEvents(self, dayObs): 

1041 """Get the TMA events for the specified dayObs. 

1042 

1043 Gets the required mount data from the cache or the EFD as required, 

1044 handling whether we're working with live vs historical data. The 

1045 dataframes from the EFD is merged and applied to the TMAStateMachine, 

1046 and that series of state changes is used to generate a list of 

1047 TmaEvents for the day's data. 

1048 

1049 If the data is for the current day, i.e. if new events can potentially 

1050 land, then if the last event is "open" (meaning that the TMA appears to 

1051 be in motion and thus the event is growing with time), then that event 

1052 is excluded from the event list as it is expected to be changing with 

1053 time, and will likely close eventually. However, if that situation 

1054 occurs on a day in the past, then that event can never close, and the 

1055 event is therefore included, but a warning about the open event is 

1056 logged. 

1057 

1058 Parameters 

1059 ---------- 

1060 dayObs : `int` 

1061 The dayObs for which to get the events. 

1062 

1063 Returns 

1064 ------- 

1065 events : `list` of `lsst.summit.utils.tmaUtils.TMAState` 

1066 The events for the specified dayObs. 

1067 """ 

1068 workingLive = self.isToday(dayObs) 

1069 data = None 

1070 

1071 if workingLive: 

1072 # it's potentially updating data, so we must update the date 

1073 # regarless of whether we have it already or not 

1074 self.log.info(f'Updating mount data for {dayObs} from the EFD') 

1075 self._getEfdDataForDayObs(dayObs) 

1076 data = self._data[dayObs] 

1077 elif dayObs in self._data: 

1078 # data is in the cache and it's not being updated, so use it 

1079 data = self._data[dayObs] 

1080 elif dayObs not in self._data: 

1081 # we don't have the data yet, but it's not growing, so put it in 

1082 # the cache and use it from there 

1083 self.log.info(f'Retrieving mount data for {dayObs} from the EFD') 

1084 self._getEfdDataForDayObs(dayObs) 

1085 data = self._data[dayObs] 

1086 else: 

1087 raise RuntimeError("This should never happen") 

1088 

1089 # if we don't have something to work with, log a warning and return 

1090 if not self.dataFound(data): 

1091 self.log.warning(f"No EFD data found for {dayObs=}") 

1092 return [] 

1093 

1094 # applies the data to the state machine, and generates events from the 

1095 # series of states which results 

1096 events = self._calculateEventsFromMergedData(data, dayObs, dataIsForCurrentDay=workingLive) 

1097 if not events: 

1098 self.log.warning(f"Failed to calculate any events for {dayObs=} despite EFD data existing!") 

1099 return events 

1100 

1101 @staticmethod 

1102 def dataFound(data): 

1103 """Check if any data was found. 

1104 

1105 Parameters 

1106 ---------- 

1107 data : `pd.DataFrame` 

1108 The merged dataframe to check. 

1109 

1110 Returns 

1111 ------- 

1112 dataFound : `bool` 

1113 Whether data was found. 

1114 """ 

1115 # You can't just compare to with data == NO_DATA_SENTINEL because 

1116 # `data` is usually a dataframe, and you can't compare a dataframe to a 

1117 # string directly. 

1118 return not (isinstance(data, str) and data == NO_DATA_SENTINEL) 

1119 

1120 def _getEfdDataForDayObs(self, dayObs): 

1121 """Get the EFD data for the specified dayObs and store it in the cache. 

1122 

1123 Gets the EFD data for all components, as a dict of dataframes keyed by 

1124 component name. These are then merged into a single dataframe in time 

1125 order, based on each row's `private_efdStamp`. This is then stored in 

1126 self._data[dayObs]. 

1127 

1128 If no data is found, the value is set to ``NO_DATA_SENTINEL`` to 

1129 differentiate this from ``None``, as this is what you'd get if you 

1130 queried the cache with `self._data.get(dayObs)`. It also marks that we 

1131 have already queried this day. 

1132 

1133 Parameters 

1134 ---------- 

1135 dayObs : `int` 

1136 The dayObs to query. 

1137 """ 

1138 data = {} 

1139 for component in itertools.chain( 

1140 self._movingComponents, 

1141 self._inPositionComponents, 

1142 self._stateComponents 

1143 ): 

1144 data[component] = getEfdData(self.client, component, dayObs=dayObs, warn=False) 

1145 self.log.debug(f"Found {len(data[component])} for {component}") 

1146 

1147 if all(dataframe.empty for dataframe in data.values()): 

1148 # if every single dataframe is empty, set the sentinel and don't 

1149 # try to merge anything, otherwise merge all the data we found 

1150 self.log.debug(f"No data found for {dayObs=}") 

1151 # a sentinel value that's not None 

1152 self._data[dayObs] = NO_DATA_SENTINEL 

1153 else: 

1154 merged = self._mergeData(data) 

1155 self._data[dayObs] = merged 

1156 

1157 def _calculateEventsFromMergedData(self, data, dayObs, dataIsForCurrentDay): 

1158 """Calculate the list of events from the merged data. 

1159 

1160 Runs the merged data, row by row, through the TMA state machine (with 

1161 ``tma.apply``) to get the overall TMA state at each row, building a 

1162 dict of these states, keyed by row number. 

1163 

1164 This time-series of TMA states are then looped over (in 

1165 `_statesToEventTuples`), building a list of tuples representing the 

1166 start and end of each event, the type of the event, and the reason for 

1167 the event ending. 

1168 

1169 This list of tuples is then passed to ``_makeEventsFromStateTuples``, 

1170 which actually creates the ``TMAEvent`` objects. 

1171 

1172 Parameters 

1173 ---------- 

1174 data : `pd.DataFrame` 

1175 The merged dataframe to use. 

1176 dayObs : `int` 

1177 The dayObs for the data. 

1178 dataIsForCurrentDay : `bool` 

1179 Whether the data is for the current day. Determines whether to 

1180 allow an open last event or not. 

1181 

1182 Returns 

1183 ------- 

1184 events : `list` of `lsst.summit.utils.tmaUtils.TMAEvent` 

1185 The events for the specified dayObs. 

1186 """ 

1187 engineeringMode = True 

1188 tma = TMAStateMachine(engineeringMode=engineeringMode) 

1189 

1190 # For now, we assume that the TMA starts each day able to move, but 

1191 # stationary. If this turns out to cause problems, we will need to 

1192 # change to loading data from the previous day(s), and looking back 

1193 # through it in time until a state change has been found for every 

1194 # axis. For now though, Bruno et. al think this is acceptable and 

1195 # preferable. 

1196 _initializeTma(tma) 

1197 

1198 tmaStates = {} 

1199 for rowNum, row in data.iterrows(): 

1200 tma.apply(row) 

1201 tmaStates[rowNum] = tma.state 

1202 

1203 stateTuples = self._statesToEventTuples(tmaStates, dataIsForCurrentDay) 

1204 events = self._makeEventsFromStateTuples(stateTuples, dayObs, data) 

1205 self.addBlockDataToEvents(dayObs, events) 

1206 return events 

1207 

1208 def _statesToEventTuples(self, states, dataIsForCurrentDay): 

1209 """Get the event-tuples from the dictionary of TMAStates. 

1210 

1211 Chunks the states into blocks of the same state, so that we can create 

1212 an event for each block in `_makeEventsFromStateTuples`. Off-type 

1213 states are skipped over, with each event starting when the telescope 

1214 next resumes motion or changes to a different type of motion state, 

1215 i.e. from non-tracking type movement (MOVE_POINT_TO_POINT, JOGGING, 

1216 TRACKING-but-not-in-position, i.e. slewing) to a tracking type 

1217 movement, or vice versa. 

1218 

1219 Parameters 

1220 ---------- 

1221 states : `dict` of `int` : `lsst.summit.utils.tmaUtils.TMAState` 

1222 The states of the TMA, keyed by row number. 

1223 dataIsForCurrentDay : `bool` 

1224 Whether the data is for the current day. Determines whether to 

1225 allow and open last event or not. 

1226 

1227 Returns 

1228 ------- 

1229 parsedStates : `list` of `tuple` 

1230 The parsed states, as a list of tuples of the form: 

1231 ``(eventStart, eventEnd, eventType, endReason)`` 

1232 """ 

1233 # Consider rewriting this with states as a list and using pop(0)? 

1234 skipStates = (TMAState.STOPPED, TMAState.OFF, TMAState.FAULT) 

1235 

1236 parsedStates = [] 

1237 eventStart = None 

1238 rowNum = 0 

1239 nRows = len(states) 

1240 while rowNum < nRows: 

1241 previousState = None 

1242 state = states[rowNum] 

1243 # if we're not in an event, fast forward through off-like rows 

1244 # until a new event starts 

1245 if eventStart is None and state in skipStates: 

1246 rowNum += 1 

1247 continue 

1248 

1249 # we've started a new event, so walk through it and find the end 

1250 eventStart = rowNum 

1251 previousState = state 

1252 rowNum += 1 # move to the next row before starting the while loop 

1253 if rowNum == nRows: 

1254 # we've reached the end of the data, and we're still in an 

1255 # event, so don't return this presumably in-progress event 

1256 self.log.warning('Reached the end of the data while starting a new event') 

1257 break 

1258 state = states[rowNum] 

1259 while state == previousState: 

1260 rowNum += 1 

1261 if rowNum == nRows: 

1262 break 

1263 state = states[rowNum] 

1264 parsedStates.append( 

1265 self.ParsedState( 

1266 eventStart=eventStart, 

1267 eventEnd=rowNum, 

1268 previousState=previousState, 

1269 state=state 

1270 ) 

1271 ) 

1272 if state in skipStates: 

1273 eventStart = None 

1274 

1275 # done parsing, just check the last event is valid 

1276 if parsedStates: # ensure we have at least one event 

1277 lastEvent = parsedStates[-1] 

1278 if lastEvent.eventEnd == nRows: 

1279 # Generally, you *want* the timespan for an event to be the 

1280 # first row of the next event, because you were in that state 

1281 # right up until that state change. However, if that event is 

1282 # a) the last one of the day and b) runs right up until the end 

1283 # of the dataframe, then there isn't another row, so this will 

1284 # overrun the array. 

1285 # 

1286 # If the data is for the current day then this isn't a worry, 

1287 # as we're likely still taking data, and this event will likely 

1288 # close yet, so we don't issue a warning, and simply drop the 

1289 # event from the list. 

1290 

1291 # However, if the data is for a past day then no new data will 

1292 # come to close the event, so allow the event to be "open", and 

1293 # issue a warning 

1294 if dataIsForCurrentDay: 

1295 self.log.info("Discarding open (likely in-progess) final event from current day's events") 

1296 parsedStates = parsedStates[:-1] 

1297 else: 

1298 self.log.warning("Last event ends open, forcing it to end at end of the day's data") 

1299 # it's a tuple, so (deliberately) awkward to modify 

1300 parsedStates[-1] = self.ParsedState( 

1301 eventStart=lastEvent.eventStart, 

1302 eventEnd=lastEvent.eventEnd - 1, 

1303 previousState=lastEvent.previousState, 

1304 state=lastEvent.state 

1305 ) 

1306 

1307 return parsedStates 

1308 

1309 def addBlockDataToEvents(self, dayObs, events): 

1310 """Find all the block data in the EFD for the specified events. 

1311 

1312 Finds all the block data in the EFD relating to the events, parses it, 

1313 from the rows of the dataframe, and adds it to the events in place. 

1314 

1315 Parameters 

1316 ---------- 

1317 events : `lsst.summit.utils.tmaUtils.TMAEvent` or 

1318 `list` of `lsst.summit.utils.tmaUtils.TMAEvent` 

1319 One or more events to get the block data for. 

1320 """ 

1321 try: 

1322 blockParser = BlockParser(dayObs, client=self.client) 

1323 except Exception as e: 

1324 # adding the block data should never cause a failure so if we can't 

1325 # get the block data, log a warning and return. It is, however, 

1326 # never expected, so use log.exception to get the full traceback 

1327 # and scare users so it gets reported 

1328 self.log.exception(f'Failed to parse block data for {dayObs=}, {e}') 

1329 return 

1330 blocks = blockParser.getBlockNums() 

1331 blockDict = {} 

1332 for block in blocks: 

1333 blockDict[block] = blockParser.getSeqNums(block) 

1334 

1335 for block, seqNums in blockDict.items(): 

1336 for seqNum in seqNums: 

1337 blockInfo = blockParser.getBlockInfo(block=block, seqNum=seqNum) 

1338 

1339 relatedEvents = blockParser.getEventsForBlock(events, block=block, seqNum=seqNum) 

1340 for event in relatedEvents: 

1341 toSet = [blockInfo] 

1342 if event.blockInfos is not None: 

1343 existingInfo = event.blockInfos 

1344 existingInfo.append(blockInfo) 

1345 toSet = existingInfo 

1346 

1347 # Add the blockInfo to the TMAEvent. Because this is a 

1348 # frozen dataclass, use object.__setattr__ to set the 

1349 # attribute. This is the correct way to set a frozen 

1350 # dataclass attribute after creation. 

1351 object.__setattr__(event, 'blockInfos', toSet) 

1352 

1353 def _makeEventsFromStateTuples(self, states, dayObs, data): 

1354 """For the list of state-tuples, create a list of ``TMAEvent`` objects. 

1355 

1356 Given the underlying data, and the start/stop points for each event, 

1357 create the TMAEvent objects for the dayObs. 

1358 

1359 Parameters 

1360 ---------- 

1361 states : `list` of `tuple` 

1362 The parsed states, as a list of tuples of the form: 

1363 ``(eventStart, eventEnd, eventType, endReason)`` 

1364 dayObs : `int` 

1365 The dayObs for the data. 

1366 data : `pd.DataFrame` 

1367 The merged dataframe. 

1368 

1369 Returns 

1370 ------- 

1371 events : `list` of `lsst.summit.utils.tmaUtils.TMAEvent` 

1372 The events for the specified dayObs. 

1373 """ 

1374 seqNum = 0 

1375 events = [] 

1376 for parsedState in states: 

1377 begin = data.iloc[parsedState.eventStart]['private_efdStamp'] 

1378 end = data.iloc[parsedState.eventEnd]['private_efdStamp'] 

1379 beginAstropy = efdTimestampToAstropy(begin) 

1380 endAstropy = efdTimestampToAstropy(end) 

1381 duration = end - begin 

1382 event = TMAEvent( 

1383 dayObs=dayObs, 

1384 seqNum=seqNum, 

1385 type=parsedState.previousState, 

1386 endReason=parsedState.state, 

1387 duration=duration, 

1388 begin=beginAstropy, 

1389 end=endAstropy, 

1390 blockInfos=None, # this is added later 

1391 _startRow=parsedState.eventStart, 

1392 _endRow=parsedState.eventEnd, 

1393 ) 

1394 events.append(event) 

1395 seqNum += 1 

1396 return events 

1397 

1398 @staticmethod 

1399 def printTmaDetailedState(tma): 

1400 """Print the full state of all the components of the TMA. 

1401 

1402 Currently this is the azimuth and elevation axes' power and motion 

1403 states, and their respective inPosition statuses. 

1404 

1405 Parameters 

1406 ---------- 

1407 tma : `lsst.summit.utils.tmaUtils.TMAStateMachine` 

1408 The TMA state machine in the state we want to print. 

1409 """ 

1410 axes = ['azimuth', 'elevation'] 

1411 p = tma._parts 

1412 axisPad = len(max(axes, key=len)) # length of the longest axis string == 9 here, but this is general 

1413 motionPad = max(len(s.name) for s in AxisMotionState) 

1414 powerPad = max(len(s.name) for s in PowerState) 

1415 

1416 # example output to show what's being done with the padding: 

1417 # azimuth - Power: ON Motion: STOPPED InPosition: True # noqa: W505 

1418 # elevation - Power: ON Motion: MOVING_POINT_TO_POINT InPosition: False # noqa: W505 

1419 for axis in axes: 

1420 print(f"{axis:>{axisPad}} - " 

1421 f"Power: {p[f'{axis}SystemState'].name:>{powerPad}} " 

1422 f"Motion: {p[f'{axis}MotionState'].name:>{motionPad}} " 

1423 f"InPosition: {p[f'{axis}InPosition']}") 

1424 print(f"Overall system state: {tma.state.name}") 

1425 

1426 def printFullDayStateEvolution(self, dayObs, taiOrUtc='utc'): 

1427 """Print the full TMA state evolution for the specified dayObs. 

1428 

1429 Replays all the data from the EFD for the specified dayObs through 

1430 the TMA state machine, and prints both the overall and detailed state 

1431 of the TMA for each row. 

1432 

1433 Parameters 

1434 ---------- 

1435 dayObs : `int` 

1436 The dayObs for which to print the state evolution. 

1437 taiOrUtc : `str`, optional 

1438 Whether to print the timestamps in TAI or UTC. Default is UTC. 

1439 """ 

1440 # create a fake event which spans the whole day, and then use 

1441 # printEventDetails code while skipping the header to print the 

1442 # evolution. 

1443 _ = self.getEvents(dayObs) # ensure the data has been retrieved from the EFD 

1444 data = self._data[dayObs] 

1445 lastRowNum = len(data) - 1 

1446 

1447 fakeEvent = TMAEvent( 

1448 dayObs=dayObs, 

1449 seqNum=-1, # anything will do 

1450 type=TMAState.OFF, # anything will do 

1451 endReason=TMAState.OFF, # anything will do 

1452 duration=-1, # anything will do 

1453 begin=efdTimestampToAstropy(data.iloc[0]['private_efdStamp']), 

1454 end=efdTimestampToAstropy(data.iloc[-1]['private_efdStamp']), 

1455 _startRow=0, 

1456 _endRow=lastRowNum 

1457 ) 

1458 self.printEventDetails(fakeEvent, taiOrUtc=taiOrUtc, printHeader=False) 

1459 

1460 def printEventDetails(self, event, taiOrUtc='tai', printHeader=True): 

1461 """Print a detailed breakdown of all state transitions during an event. 

1462 

1463 Note: this is not the most efficient way to do this, but it is much the 

1464 cleanest with respect to the actual state machine application and event 

1465 generation code, and is easily fast enough for the cases it will be 

1466 used for. It is not worth complicating the normal state machine logic 

1467 to try to use this code. 

1468 

1469 Parameters 

1470 ---------- 

1471 event : `lsst.summit.utils.tmaUtils.TMAEvent` 

1472 The event to display the details of. 

1473 taiOrUtc : `str`, optional 

1474 Whether to display time strings in TAI or UTC. Defaults to TAI. 

1475 Case insensitive. 

1476 printHeader : `bool`, optional 

1477 Whether to print the event summary. Defaults to True. The primary 

1478 reason for the existence of this option is so that this same 

1479 printing function can be used to show the evolution of a whole day 

1480 by supplying a fake event which spans the whole day, but this event 

1481 necessarily has a meaningless summary, and so needs suppressing. 

1482 """ 

1483 taiOrUtc = taiOrUtc.lower() 

1484 if taiOrUtc not in ['tai', 'utc']: 

1485 raise ValueError(f'Got unsuppoted value for {taiOrUtc=}') 

1486 useUtc = taiOrUtc == 'utc' 

1487 

1488 if printHeader: 

1489 print(f"Details for {event.duration:.2f}s {event.type.name} event dayObs={event.dayObs}" 

1490 f" seqNum={event.seqNum}:") 

1491 print(f"- Event began at: {event.begin.utc.isot if useUtc else event.begin.isot}") 

1492 print(f"- Event ended at: {event.end.utc.isot if useUtc else event.end.isot}") 

1493 

1494 dayObs = event.dayObs 

1495 data = self._data[dayObs] 

1496 startRow = event._startRow 

1497 endRow = event._endRow 

1498 nRowsToApply = endRow - startRow + 1 

1499 print(f"\nTotal number of rows in the merged dataframe: {len(data)}") 

1500 if printHeader: 

1501 print(f"of which rows {startRow} to {endRow} (inclusive) relate to this event.") 

1502 

1503 # reconstruct all the states 

1504 tma = TMAStateMachine(engineeringMode=True) 

1505 _initializeTma(tma) 

1506 

1507 tmaStates = {} 

1508 firstAppliedRow = True # flag to print a header on the first row that's applied 

1509 for rowNum, row in data.iterrows(): # must replay rows right from start to get full correct state 

1510 if rowNum == startRow: 

1511 # we've not yet applied this row, so this is the state just 

1512 # before event 

1513 print(f"\nBefore the event the TMA was in state {tma.state.name}:") 

1514 self.printTmaDetailedState(tma) 

1515 

1516 if rowNum >= startRow and rowNum <= endRow: 

1517 if firstAppliedRow: # only print this intro on the first row we're applying 

1518 print(f"\nThen, applying the {nRowsToApply} rows of data for this event, the state" 

1519 " evolved as follows:\n") 

1520 firstAppliedRow = False 

1521 

1522 # break the row down and print its details 

1523 rowFor = row['rowFor'] 

1524 axis, rowType = getAxisAndType(rowFor) # e.g. elevation, MotionState 

1525 value = tma._getRowPayload(row, rowType, rowFor) 

1526 valueStr = f"{str(value) if isinstance(value, bool) else value.name}" 

1527 rowTime = efdTimestampToAstropy(row['private_efdStamp']) 

1528 print(f"On row {rowNum} the {axis} axis had the {rowType} set to {valueStr} at" 

1529 f" {rowTime.utc.isot if useUtc else rowTime.isot}") 

1530 

1531 # then apply it as usual, printing the state right afterwards 

1532 tma.apply(row) 

1533 tmaStates[rowNum] = tma.state 

1534 self.printTmaDetailedState(tma) 

1535 print() 

1536 

1537 else: 

1538 # if it's not in the range of interest then just apply it 

1539 # silently as usual 

1540 tma.apply(row) 

1541 tmaStates[rowNum] = tma.state 

1542 

1543 def findEvent(self, time): 

1544 """Find the event which contains the specified time. 

1545 

1546 If the specified time lies within an event, that event is returned. If 

1547 it is at the exact start, that is logged, and if that start point is 

1548 shared by the end of the previous event, that is logged too. If the 

1549 event lies between events, the events either side are logged, but 

1550 ``None`` is returned. If the time lies before the first event of the 

1551 day a warning is logged, as for times after the last event of the day. 

1552 

1553 Parameters 

1554 ---------- 

1555 time : `astropy.time.Time` 

1556 The time. 

1557 

1558 Returns 

1559 ------- 

1560 event : `lsst.summit.utils.tmaUtils.TMAEvent` or `None` 

1561 The event which contains the specified time, or ``None`` if the 

1562 time doesn't fall during an event. 

1563 """ 

1564 # there are five possible cases: 

1565 # 1) the time lies before the first event of the day 

1566 # 2) the time lies after the last event of the day 

1567 # 3) the time lies within an event 

1568 # 3a) the time is exactly at the start of an event 

1569 # 3b) if so, time can be shared by the end of the previous event if 

1570 # they are contiguous 

1571 # 4) the time lies between two events 

1572 # 5) the time is exactly at end of the last event of the day. This is 

1573 # an issue because event end times are exclusive, so this time is 

1574 # not technically in that event, it's the moment it closes (and if 

1575 # there *was* an event which followed contiguously, it would be in 

1576 # that event instead, which is what motivates this definition of 

1577 # lies within what event) 

1578 

1579 dayObs = getDayObsForTime(time) 

1580 # we know this is on the right day, and definitely before the specified 

1581 # time, but sanity check this before continuing as this needs to be 

1582 # true for this to give the correct answer 

1583 assert getDayObsStartTime(dayObs) <= time 

1584 assert getDayObsEndTime(dayObs) > time 

1585 

1586 # command start to many log messages so define once here 

1587 logStart = f"Specified time {time.isot} falls on {dayObs=}" 

1588 

1589 events = self.getEvents(dayObs) 

1590 if len(events) == 0: 

1591 self.log.warning(f'There are no events found for {dayObs}') 

1592 return None 

1593 

1594 # check case 1) 

1595 if time < events[0].begin: 

1596 self.log.warning(f'{logStart} and is before the first event of the day') 

1597 return None 

1598 

1599 # check case 2) 

1600 if time > events[-1].end: 

1601 self.log.warning(f'{logStart} and is after the last event of the day') 

1602 return None 

1603 

1604 # check case 5) 

1605 if time == events[-1].end: 

1606 self.log.warning(f'{logStart} and is exactly at the end of the last event of the day' 

1607 f' (seqnum={events[-1].seqNum}). Because event intervals are half-open, this' 

1608 ' time does not technically lie in any event') 

1609 return None 

1610 

1611 # we are now either in an event, or between events. Walk through the 

1612 # events, and if the end of the event is after the specified time, then 

1613 # we're either in it or past it, so check if we're in. 

1614 for eventNum, event in enumerate(events): 

1615 if event.end > time: # case 3) we are now into or past the right event 

1616 # the event end encloses the time, so note the > and not >=, 

1617 # this must be strictly greater, we check the overlap case 

1618 # later 

1619 if time >= event.begin: # we're fully inside the event, so return it. 

1620 # 3a) before returning, check if we're exactly at the start 

1621 # of the event, and if so, log it. Then 3b) also check if 

1622 # we're at the exact end of the previous event, and if so, 

1623 # log that too. 

1624 if time == event.begin: 

1625 self.log.info(f"{logStart} and is exactly at the start of event" 

1626 f" {eventNum}") 

1627 if eventNum == 0: # I think this is actually impossible, but check anyway 

1628 return event # can't check the previous event so return here 

1629 previousEvent = events[eventNum - 1] 

1630 if previousEvent.end == time: 

1631 self.log.info("Previous event is contiguous, so this time is also at the exact" 

1632 f" end of {eventNum - 1}") 

1633 return event 

1634 else: # case 4) 

1635 # the event end is past the time, but it's not inside the 

1636 # event, so we're between events. Log which we're between 

1637 # and return None 

1638 previousEvent = events[eventNum - 1] 

1639 timeAfterPrev = (time - previousEvent.end).to_datetime() 

1640 naturalTimeAfterPrev = humanize.naturaldelta(timeAfterPrev, minimum_unit='MICROSECONDS') 

1641 timeBeforeCurrent = (event.begin - time).to_datetime() 

1642 naturalTimeBeforeCurrent = humanize.naturaldelta(timeBeforeCurrent, 

1643 minimum_unit='MICROSECONDS') 

1644 self.log.info(f"{logStart} and lies" 

1645 f" {naturalTimeAfterPrev} after the end of event {previousEvent.seqNum}" 

1646 f" and {naturalTimeBeforeCurrent} before the start of event {event.seqNum}." 

1647 ) 

1648 return None 

1649 

1650 raise RuntimeError('Event finding logic fundamentally failed, which should never happen - the code' 

1651 ' needs fixing')