Skip to content

Conversation

Baharis
Copy link
Member

@Baharis Baharis commented May 7, 2025

Context

There is a common programming pattern in instamatic to unblank and then blank (or vice versa) the beam in short succession. The get_image method built into controller as well as many experimental procedures often do that either to briefly shield the detector or to collect a single image without exposing the sample too much. Unfortunately, this is typically done by 1) checking if beam is blanked, 2) checking if auto-blank is on, 3) blanking the beam, 4) reverting the blanking if needed after the fact. This pattern is not very large, but it repeats over the whole code base 22 times, according to my counting.

This small PR suggest adding two new context manager methods to the Beam object: blanked and unblanked. These can be used via the with keyword and they significantly shorten the boilerplate code used to check for previous blanking, auto-blanking, delay etc., placing them all into a one call and determining the scope via indentation. For example, in the controller the get_image function gets simplified from this (empty lines ommited):

if self.autoblank:
    self.beam.unblank()
h['ImageGetTimeStart'] = time.perf_counter()
arr = self.get_rotated_image(exposure=exposure, binsize=binsize)
h['ImageGetTimeEnd'] = time.perf_counter()
if self.autoblank:
    self.beam.blank()

To this:

with self.beam.unblanked(condition=self.autoblank):
    h['ImageGetTimeStart'] = time.perf_counter()
    arr = self.get_rotated_image(exposure=exposure, binsize=binsize)
    h['ImageGetTimeEnd'] = time.perf_counter()

Apart from adding the new method, I have applied them in 10 selected places where it was straightforward and where I knew it does not change the behavior. As a consequence you can see that this PR adds only a few more line than it removes, even though it expands the documentation and the existing test.

Code changes

  • Introduced two new beam.blanked and beam.unblanked context manager methods that can simplify code with sequential calls to beam.blank and beam.unblank.

@Baharis Baharis requested a review from stefsmeets May 7, 2025 14:14
@Baharis Baharis self-assigned this May 7, 2025
Copy link
Member

@stefsmeets stefsmeets left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice use of context managers, looks good to me!

@stefsmeets stefsmeets merged commit 1fcf98b into instamatic-dev:main May 8, 2025
7 checks passed
@Baharis Baharis deleted the beam_blanked_unblanked branch May 8, 2025 12:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants