Skip to content

Commit

Permalink
Updates to work with newer ophyd async versions
Browse files Browse the repository at this point in the history
  • Loading branch information
jwlodek authored and TST Operator committed Nov 15, 2024
1 parent 3f36346 commit 8c3b910
Show file tree
Hide file tree
Showing 9 changed files with 1,125 additions and 1,328 deletions.
2 changes: 1 addition & 1 deletion start-bsui.sh
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ source venv/bin/activate

export TILED_API_KEY=e9fa22c35c4b7414e59d96c265ab46fabdfdea9046c78a88b5f390cea29f6b15

ipython --profile=collection_tst --ipython-dir=$(pwd)/..
ipython --profile=collection --ipython-dir=$(pwd)/..
18 changes: 9 additions & 9 deletions startup/00-startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,17 @@
nslsii.configure_base(
get_ipython().user_ns,
Broker.named("temp"),
pbar=True,
bec=True,
magics=True,
mpl=True,
pbar=False,
bec=False,
magics=False,
mpl=False,
epics_context=False,
)

RE.unsubscribe(0)

RE = RunEngine()
RE.subscribe(bec)
#RE.subscribe(bec)

tiled_client = from_uri("http://localhost:8000", api_key=os.getenv("TILED_API_KEY", ""))
tw = TiledWriter(tiled_client)
Expand Down Expand Up @@ -68,12 +68,12 @@ def __call__(self, name, doc):

# This is needed for ophyd-async to enable 'await <>' instead of 'asyncio.run(<>)':
ipython_session = get_ipython()
if ipython_session is not None and not isinstance(ipython_session, IPDummy):
ipython_session.run_line_magic("autoawait", "call_in_bluesky_event_loop")
#if ipython_session is not None and not isinstance(ipython_session, IPDummy):
#ipython_session.run_line_magic("autoawait", "call_in_bluesky_event_loop")

# PandA does not produce any data for plots for now.
bec.disable_plots()
bec.disable_table()
#bec.disable_plots()
#bec.disable_table()


def dump_doc_to_stdout(name, doc):
Expand Down
8 changes: 4 additions & 4 deletions startup/01-globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@

from ophyd_async.core import (
DEFAULT_TIMEOUT,
DetectorControl,
DetectorController,
DetectorTrigger,
DetectorWriter,
DeviceCollector,
SignalRW,
TriggerInfo,
TriggerLogic,
FlyerController,
)


Expand Down Expand Up @@ -46,7 +46,7 @@ def gen_software_trigger_setup(num_frames, exp_time):
)


class StandardTriggerLogic(TriggerLogic[int]):
class StandardTriggerLogic(FlyerController[int]):
def __init__(self):
self.state = StandardTriggerState.null

Expand All @@ -59,7 +59,7 @@ def trigger_info(self, setup) -> TriggerInfo:
exposure = setup.exposure_time
num_images = setup.num_frames
return TriggerInfo(
number=num_images,
number_of_triggers=num_images,
trigger=trigger,
deadtime=0.1,
livetime=exposure,
Expand Down
4 changes: 2 additions & 2 deletions startup/10-panda.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from ophyd_async.core import (
DEFAULT_TIMEOUT,
AsyncStatus,
DetectorControl,
DetectorController,
DetectorTrigger,
DetectorWriter,
SignalRW,
Expand All @@ -41,7 +41,7 @@
##########################################################################

panda_trigger_logic = StandardTriggerLogic()
panda_flyer = StandardFlyer(panda_trigger_logic, [], name="panda_flyer")
panda_flyer = StandardFlyer(panda_trigger_logic, name="panda_flyer")


def instantiate_panda_async(panda_id):
Expand Down
7 changes: 4 additions & 3 deletions startup/15-manta.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,17 @@
from ophyd import EpicsSignalRO
from ophyd_async.core import (
DEFAULT_TIMEOUT,
DetectorControl,
DetectorController,
DetectorTrigger,
DetectorWriter,
DeviceCollector,
SignalRW,
TriggerInfo,
TriggerLogic,
)
from ophyd_async.epics.advimba import VimbaDetector

manta_trigger_logic = StandardTriggerLogic()
manta_flyer = StandardFlyer(manta_trigger_logic, [], name="manta_flyer")
manta_flyer = StandardFlyer(manta_trigger_logic, name="manta_flyer")


def instantiate_manta_async(manta_id):
Expand All @@ -42,5 +41,7 @@ def instantiate_manta_async(manta_id):
manta1 = instantiate_manta_async(1)
manta2 = instantiate_manta_async(2)

# warmup_hdf_plugins([manta1, manta2])


file_loading_timer.stop_timer(__file__)
229 changes: 227 additions & 2 deletions startup/90-plans.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ def tomo_demo_async(
raise RuntimeError(
f"Your configured exposure time is longer than the step size {step_time}"
)
else:
exposure_time = step_time / 3

panda_devices = [panda, panda_flyer]
detector_devices = [detector, manta_flyer]
Expand Down Expand Up @@ -191,7 +193,6 @@ def tomo_demo_async(

# Stage All!
yield from bps.stage_all(*all_devices)
yield from bps.mv(detector._writer.hdf.num_capture, num_images)

yield from bps.prepare(manta_flyer, det_exp_setup, wait=True)
yield from bps.prepare(
Expand Down Expand Up @@ -271,5 +272,229 @@ def tomo_demo_async(
# Reset the velocity back to high.
yield from bps.mv(rot_motor.velocity, 180 / 2)

def xas_demo_async(
panda,
detector,
npoints,
total_time,
start_e,
end_e
# num_images=21,
# scan_time=9,
# start_deg=0,
# exposure_time=None,
):

start_deg = start_e
end_deg = end_e

panda_pcomp1 = panda.pcomp[1]
panda_pcap1 = panda.pcap
panda_clock1 = panda.clock[1]

reset_time = 0.001 # [ms], 1 us difference is usually enough

clock_period_ms = total_time * 1000 / npoints # [ms]
clock_width_ms = clock_period_ms - reset_time

target_velocity = (end_deg-start_deg) / total_time # [deg/s]


# PRE_START -> 0
# START -> prestart_cnt
# WIDTH -> end_cnt - start_cnt



pre_start_deg = 5. # [deg], we are working in relative mode, zero is the position where pcomp was enabled
pre_start_cnt = pre_start_deg * COUNTS_PER_DEG

start_cnt = pre_start_cnt
width_deg = end_deg - start_deg
width_cnt = width_deg * COUNTS_PER_DEG

print(f"{pre_start_cnt=}, {width_deg=}, {width_cnt=}")

# step_width_counts = COUNTS_PER_REVOLUTION / (2 * (num_images - 1))
# if int(step_width_counts) != round(step_width_counts, 5):
# raise ValueError(
# "The number of encoder counts per pulse is not an integer value!"
# )

# step_time = scan_time / num_images
# if exposure_time is not None:
# if exposure_time > step_time:
# raise RuntimeError(
# f"Your configured exposure time is longer than the step size {step_time}"
# )

panda_devices = [panda, panda_flyer]
all_devices = panda_devices

if detector:
detector_devices = [detector, manta_flyer]
all_devices = panda_devices + detector_devices
# TODO: DO WE NEED THIS?
det_exp_setup = StandardTriggerSetup(
num_frames=npoints, #num_images,
exposure_time=clock_width_ms, #exposure_time,
trigger_mode=DetectorTrigger.edge_trigger,
)

panda_exp_setup = StandardTriggerSetup(
num_frames=npoints, #num_images,
exposure_time=clock_width_ms, #exposure_time,
trigger_mode=DetectorTrigger.constant_gate,
)

yield from bps.mv(
rot_motor.velocity, 180 / 2
) # Make it fast to move to the start position
yield from bps.mv(rot_motor, start_deg - pre_start_deg)
yield from bps.mv(
rot_motor.velocity, target_velocity #180 / scan_time
) # Set the velocity for the scan
# start_encoder = start_deg * COUNTS_PER_DEG

# width_in_counts = (180 / scan_time) * COUNTS_PER_DEG * exposure_time
# if width_in_counts > step_width_counts:
# raise RuntimeError(
# f"Your specified exposure time of {exposure_time}s is too long! Calculated width: {width_in_counts}, Step size: {step_width_counts}"
# )
# print(f"Exposing camera for {width_in_counts} counts")

yield from bps.mv(panda_pcomp1.enable, "ZERO") # disabling pcomp, we'll enable it right before the start

# print("SEETING UP PCOMP")

# print("Current PCOMP start:", panda_pcomp1.start)
# print("Current PCOMP width:", panda_pcomp1.width)
# Set up the pcomp block
yield from bps.mv(panda_pcomp1.start, int(start_cnt))
yield from bps.mv(panda_pcomp1.width, int(width_cnt))

print("READY TO GO", datetime.datetime.now().strftime("%H:%M:%S"))

# Uncomment if using gate trigger mode on camera
# yield from bps.mv(
# panda3_pcomp_1.width, width_in_counts
# ) # Width in encoder counts that the pulse will be high
# yield from bps.mv(panda_pcomp1.step, step_width_counts)
# yield from bps.mv(panda_pcomp1.pulses, num_images) # TODO: CHECK

yield from bps.mv(panda_clock1.period, clock_period_ms)
yield from bps.mv(panda_clock1.period_units, "ms")
yield from bps.mv(panda_clock1.width, clock_width_ms)
yield from bps.mv(panda_clock1.width_units, "ms")
print("000: panda clock configured, ", datetime.datetime.now().strftime("%H:%M:%S"))
yield from bps.open_run()
print("001: run open,", datetime.datetime.now().strftime("%H:%M:%S"))
if detector:
detector._writer._path_provider._filename_provider.set_frame_type(
TomoFrameType.proj
)
print("002: detector filename set, ", datetime.datetime.now().strftime("%H:%M:%S"))
# The setup below is happening in the VimbaController's arm method.
# # Setup camera in trigger mode
# yield from bps.mv(manta_async.trigger_mode, "On")
# yield from bps.mv(manta_async.trigger_source, "Line1")
# yield from bps.mv(manta_async.overlap, "Off")
# yield from bps.mv(manta_async.expose_out_mode, "TriggerWidth") # "Timed" or "TriggerWidth"

# Stage All!
yield from bps.stage_all(*all_devices)
print("003: staging complete, ", datetime.datetime.now().strftime("%H:%M:%S"))
if detector:
yield from bps.mv(detector._writer.hdf.num_capture, npoints)
yield from bps.prepare(manta_flyer, det_exp_setup, wait=True)
yield from bps.prepare(
detector, manta_flyer.trigger_logic.trigger_info(det_exp_setup), wait=True
)
print("004: manta flyer prepare complete, ", datetime.datetime.now().strftime("%H:%M:%S"))
yield from bps.prepare(panda_flyer, npoints, wait=True)
yield from bps.prepare(
panda, panda_flyer.trigger_logic.trigger_info(panda_exp_setup), wait=True
)
print("005: panda flyer prepare complete, ", datetime.datetime.now().strftime("%H:%M:%S"))

for device in all_devices:
yield from bps.kickoff(device)
print("007: kickoff complete, ", datetime.datetime.now().strftime("%H:%M:%S"))

# yield from bps.sleep(0.1)
yield from bps.mv(panda_pcomp1.enable, "ONE")
yield from bps.mv(rot_motor, end_deg + pre_start_deg) # Aiming beyond the end point to maintain constant veolcity
print("006: motor mv start, ", datetime.datetime.now().strftime("%H:%M:%S"))


for flyer_or_panda in panda_devices:
yield from bps.complete(flyer_or_panda, wait=True, group="complete_panda")
print("008: panda complete, ", datetime.datetime.now().strftime("%H:%M:%S"))
if detector:
for flyer_or_det in detector_devices:
yield from bps.complete(flyer_or_det, wait=True, group="complete_detector")
print("009: detector complete, ", datetime.datetime.now().strftime("%H:%M:%S"))
# Manually incremenet the index as if a frame was taken
# detector.writer.index += 1
print("ACQUISITION COMPLETE", datetime.datetime.now().strftime("%H:%M:%S"))

# Wait for completion of the PandA HDF5 file saving.
done = False
while not done:
try:
yield from bps.wait(group="complete_panda", timeout=0.5)
except TimeoutError:
pass
else:
done = True

panda_stream_name = f"{panda.name}_stream"
yield from bps.declare_stream(panda, name=panda_stream_name)

yield from bps.collect(
panda,
# stream=True,
# return_payload=False,
name=panda_stream_name,
)
print("PANDA FILE SAVING COMPLETE")
yield from bps.unstage_all(*panda_devices)
yield from bps.mv(panda_pcomp1.enable, "ZERO")
print("PANDA UNSTAGING COMPLETE")

# Wait for completion of the AD HDF5 file saving.
done = False if detector else True
while not done:
try:
yield from bps.wait(group="complete_detector", timeout=0.5)
except TimeoutError:
pass
else:
done = True

detector_stream_name = f"{detector.name}_stream"
yield from bps.declare_stream(detector, name=detector_stream_name)

yield from bps.collect(
detector,
# stream=True,
# return_payload=False,
name=detector_stream_name,
)
yield from bps.sleep(0.01)
print("AD HDF5 SAVED")
yield from bps.close_run()

panda_val = yield from bps.rd(panda.data.num_captured)
print(f"{panda_val = }")
if detector:
manta_val = yield from bps.rd(detector._writer.hdf.num_captured)
print(f"{manta_val = }")

yield from bps.unstage_all(*detector_devices)

# Reset the velocity back to high.
yield from bps.mv(rot_motor.velocity, 180 / 2)


file_loading_timer.stop_timer(__file__)
#file_loading_timer.stop_timer(__file__)
Loading

0 comments on commit 8c3b910

Please sign in to comment.