diff --git a/A-chat-about-saving-data.md b/A-chat-about-saving-data.md index ac417c7..adb6bf8 100644 --- a/A-chat-about-saving-data.md +++ b/A-chat-about-saving-data.md @@ -48,4 +48,75 @@ *Pulse IDs rock my world!* **❌ Don’t Say:** -*Beam synchronous PV* \ No newline at end of file +*Beam synchronous PV* + +## Example scripts using datahub + +### Saving historic data for a set time range + +```python +from datahub import * +import matplotlib.pyplot as plt +from datetime import datetime, timedelta + +# Set time range: from 6 minutes ago to 5 minutes ago +now = datetime.now() +from_time, to_time = [ + (now - timedelta(minutes=m)).strftime('%Y-%m-%d %H:%M:%S.%f')[:-3] + for m in [6, 5] +] + +# Define the channels to monitor +channels = [ + "SARFE10-PSSS059:SPECTRUM_Y", + "SAROP21-PBPS133:INTENSITY", + "SARFE10-PBPG050:FAST-PULSE-ENERGY" +] + +# Construct the query with channels and time range +query = { + "channels": channels, + "start": from_time, + "end": to_time +} + +# Connect to the data source and retrieve data +with Daqbuf(backend="sf-databuffer", cbor=True) as source: + table = Table() + source.add_listener(table) + source.request(query) + dataframe = table.as_dataframe(index=Table.PULSE_ID) + + # Iterate through each channel and print the number of pulses + for channel in channels: + if channel in dataframe.columns: + NumShots = dataframe[channel].count() + print(f"{channel}: {NumShots} pulses") + else: + print(f"{channel}: Channel not found in the dataframe.") +``` + +### Example of a stream of live data + +```python +from datahub import Bsread, Table + +channels = [ + "SARFE10-PSSS059:SPECTRUM_Y", + "SAROP21-PBPS133:INTENSITY", + "SARFE10-PBPG050:FAST-PULSE-ENERGY" +] + +with Bsread() as source: + table = Table() + source.add_listener(table) + source.req(channels, 0.0, 2.0) + dataframe = table.as_dataframe(index=Table.PULSE_ID) + + for channel in channels: + if channel in dataframe.columns: + NumShots = dataframe[channel].count() + print(f"{channel}: {NumShots} pulses") + else: + print(f"{channel}: Channel not found in the dataframe.") +``` \ No newline at end of file