Skip to content

TEMController

Classes

TEMController(tem, cam=None)

TEMController object that enables access to all defined microscope controls.

tem: Microscope control object (e.g. instamatic/TEMController/simu_microscope.SimuMicroscope) cam: Camera control object (see instamatic.camera) [optional]

Source code in src/instamatic/controller.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def __init__(self, tem: MicroscopeBase, cam: Optional[CameraBase] = None):
    super().__init__()

    self._executor = ThreadPoolExecutor(max_workers=1)

    self.tem = tem
    self.cam = cam

    self.gunshift = components.GunShift(tem)
    self.guntilt = components.GunTilt(tem)
    self.beamshift = components.BeamShift(tem)
    self.beamtilt = components.BeamTilt(tem)
    self.imageshift1 = components.ImageShift1(tem)
    self.imageshift2 = components.ImageShift2(tem)
    self.diffshift = components.DiffShift(tem)
    self.stage = components.Stage(tem)
    self.stageposition = self.stage  # for backwards compatibility
    self.magnification = components.Magnification(tem)
    self.brightness = components.Brightness(tem)
    self.difffocus = components.DiffFocus(tem)
    self.beam = components.Beam(tem)
    self.screen = components.Screen(tem)
    self.mode = components.Mode(tem)

    self.autoblank = False
    self._saved_alignments = config.get_alignments()

    print()
    print(self)
    self.store()

Attributes

current_density property

Get current density from fluorescence screen in pA/cm2.

high_tension property

Get the high tension value in V.

Methods:

acquire_at_items(*args, **kwargs)

Class to automated acquisition at many stage locations. The acquisition functions must be callable (or a list of callables) that accept ctrl as an argument. In case a list of callables is given, they are excecuted in sequence.

Internally, this runs instamatic.acquire_at_items.AcquireAtItems. See there for more information.

Parameters:

  • nav_items –

    List of (x, y) / (x, y, z) coordinates (nm), or List of navigation items loaded from a .nav file.

  • acquire –

    Main function to call, must take ctrl as an argument

  • pre_acquire –

    This function is called before the first acquisition item is run.

  • post_acquire –

    This function is run after the last acquisition item has run.

  • backlash –
  • Move –
Source code in src/instamatic/controller.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def acquire_at_items(self, *args, **kwargs) -> None:
    """Class to automated acquisition at many stage locations. The
    acquisition functions must be callable (or a list of callables) that
    accept `ctrl` as an argument. In case a list of callables is given,
    they are excecuted in sequence.

    Internally, this runs instamatic.acquire_at_items.AcquireAtItems. See there for more information.

    Parameters
    ----------
    nav_items: list
        List of (x, y) / (x, y, z) coordinates (nm), or
        List of navigation items loaded from a `.nav` file.
    acquire: callable, list of callables
        Main function to call, must take `ctrl` as an argument
    pre_acquire: callable, list of callables
        This function is called before the first acquisition item is run.
    post_acquire: callable, list of callables
        This function is run after the last acquisition item has run.
    backlash: bool
    Move the stage with backlash correction.
    """
    from instamatic.acquire_at_items import AcquireAtItems

    ctrl = self

    aai = AcquireAtItems(ctrl, *args, **kwargs)
    aai.start()
align_to(ref_img, apply=True, verbose=False)

Align current view by comparing it against the given image using cross correlation. The stage is translated so that the object of interest (in the reference image) is at the center of the view.

Parameters:

  • ref_img (array) –

    Reference image that the microscope will be aligned to

  • apply (bool, default: True ) –

    Toggle to translate the stage to center the image

  • verbose (bool, default: False ) –

    Be more verbose

Returns:

  • stage_shift ( array[2] ) –

    The stage shift vector determined from cross correlation

Source code in src/instamatic/controller.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
def align_to(
    self,
    ref_img: 'np.array',
    apply: bool = True,
    verbose: bool = False,
) -> list:
    """Align current view by comparing it against the given image using
    cross correlation. The stage is translated so that the object of
    interest (in the reference image) is at the center of the view.

    Parameters
    ----------
    ref_img : np.array
        Reference image that the microscope will be aligned to
    apply : bool
        Toggle to translate the stage to center the image
    verbose : bool
        Be more verbose

    Returns
    -------
    stage_shift : np.array[2]
        The stage shift vector determined from cross correlation
    """
    from skimage.registration import phase_cross_correlation

    current_x, current_y = self.stage.xy

    if verbose:
        print(f'Current stage position: {current_x:.0f} {current_y:.0f}')

    stagematrix = self.get_stagematrix()

    img = self.get_rotated_image()

    pixel_shift, error, phasediff = phase_cross_correlation(
        ref_img, img, upsample_factor=10
    )

    stage_shift = np.dot(pixel_shift, stagematrix)
    stage_shift[0] = -stage_shift[0]  # match TEM Coordinate system

    print(f'Aligning: shifting stage by dx={stage_shift[0]:6.0f} dy={stage_shift[1]:6.0f}')

    new_x = current_x + stage_shift[0]
    new_y = current_y + stage_shift[1]

    if verbose:
        print(f'New stage position: {new_x:.0f} {new_y:.0f}')

    if apply:
        self.stage.set_xy_with_backlash_correction(x=new_x, y=new_y)

    return stage_shift
find_eucentric_height(tilt=5, steps=5, dz=50000, apply=True, verbose=True)

Automated routine to find the eucentric height, accurate up to ~1 um Measures the shift (cross correlation) between 2 angles (-+tilt) over a range of z values (defined by dz and steps). The height is calculated by fitting the shifts vs. z.

Fit: shift = alpha*z + beta -> z0 = -beta/alpha

Takes roughly 35 seconds (2 steps) or 70 seconds (5 steps) on a JEOL 1400 with a TVIPS camera.

Based on: Koster, et al., Ultramicroscopy 46 (1992): 207–27. https://doi.org/10.1016/0304-3991(92)90016-D.

Parameters:

  • tilt (float, default: 5 ) –

    Tilt angles (+-)

  • steps (int, default: 5 ) –

    Number of images to take along the defined Z range

  • dz (int, default: 50000 ) –

    Range to cover in nm (i.e. from -dz to +dz) around the current Z value

  • apply (bool, default: True ) –

    apply the Z height immediately

  • verbose (bool, default: True ) –

    Toggle the verbosity level

Returns:

  • z ( float ) –

    Optimized Z value for eucentric tilting

Source code in src/instamatic/controller.py
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
def find_eucentric_height(
    self,
    tilt: float = 5,
    steps: int = 5,
    dz: int = 50_000,
    apply: bool = True,
    verbose: bool = True,
) -> float:
    """Automated routine to find the eucentric height, accurate up to ~1 um
    Measures the shift (cross correlation) between 2 angles (-+tilt) over a
    range of z values (defined by `dz` and `steps`). The height is
    calculated by fitting the shifts vs. z.

    Fit: shift = alpha*z + beta -> z0 = -beta/alpha

    Takes roughly 35 seconds (2 steps) or 70 seconds (5 steps) on a JEOL 1400 with a TVIPS camera.

    Based on: Koster, et al., Ultramicroscopy 46 (1992): 207–27.
              https://doi.org/10.1016/0304-3991(92)90016-D.

    Parameters
    ----------
    tilt:
        Tilt angles (+-)
    steps: int
        Number of images to take along the defined Z range
    dz: int
        Range to cover in nm (i.e. from -dz to +dz) around the current Z value
    apply: bool
        apply the Z height immediately
    verbose: bool
        Toggle the verbosity level

    Returns
    -------
    z: float
        Optimized Z value for eucentric tilting
    """
    from skimage.registration import phase_cross_correlation

    def one_cycle(tilt: float = 5, sign=1) -> list:
        angle1 = -tilt * sign
        self.stage.a = angle1
        img1 = self.get_rotated_image()

        angle2 = +tilt * sign
        self.stage.a = angle2
        img2 = self.get_rotated_image()

        if sign < 1:
            img2, img1 = img1, img2

        shift, error, phasediff = phase_cross_correlation(img1, img2, upsample_factor=10)

        return shift

    self.stage.a = 0
    # self.stage.z = 0 # for testing

    zc = self.stage.z
    print(f'Current z = {zc} nm')

    zs = zc + np.linspace(-dz, dz, steps)
    shifts = []

    sign = 1

    for i, z in enumerate(zs):
        self.stage.z = z
        if verbose:
            print(f'z = {z:.1f} nm')

        di = one_cycle(tilt=tilt, sign=sign)
        shifts.append(di)

        sign *= -1

    mean_shift = shifts[-1] + shifts[0]
    mean_shift = mean_shift / np.linalg.norm(mean_shift)
    ds = np.dot(shifts, mean_shift)

    p = np.polyfit(zs, ds, 1)  # linear fit
    alpha, beta = p

    z0 = -beta / alpha

    print(f'alpha={alpha:.2f} | beta={beta:.2f} => z0={z0:.1f} nm')
    if apply:
        self.stage.set(a=0, z=z0)

    return z0
from_dict(dct)

Restore microscope parameters from dict.

Source code in src/instamatic/controller.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
def from_dict(self, dct: dict):
    """Restore microscope parameters from dict."""
    funcs = {
        # 'FunctionMode': self.tem.setFunctionMode,
        'GunShift': self.gunshift.set,
        'GunTilt': self.guntilt.set,
        'BeamShift': self.beamshift.set,
        'BeamTilt': self.beamtilt.set,
        'ImageShift1': self.imageshift1.set,
        'ImageShift2': self.imageshift2.set,
        'DiffShift': self.diffshift.set,
        'StagePosition': self.stage.set,
        'Magnification': self.magnification.set,
        'DiffFocus': self.difffocus.set,
        'Brightness': self.brightness.set,
        'SpotSize': self.tem.setSpotSize,
    }

    mode = dct['FunctionMode']
    self.tem.setFunctionMode(mode)

    for k, v in dct.items():
        if k in funcs:
            func = funcs[k]
        else:
            continue

        try:
            func(*v)
        except TypeError:
            func(v)
get_future_image(exposure=None, binsize=None)

Simplified function equivalent to get_image that returns the raw image as a future. This makes the data acquisition call non-blocking.

Parameters:

  • exposure (float, default: None ) –

    Exposure time in seconds

  • binsize (int, default: None ) –

    Binning to use for the image, must be 1, 2, or 4, etc

Returns:

  • future ( `future` ) –

    Future object that contains the image as 2D numpy array.

  • Usage ( 'future' ) –

    future = ctrl.get_future_image() (other operations) img = future.result()

Source code in src/instamatic/controller.py
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
def get_future_image(self, exposure: float = None, binsize: int = None) -> 'future':
    """Simplified function equivalent to `get_image` that returns the raw
    image as a future. This makes the data acquisition call non-blocking.

    Parameters
    ----------
    exposure: float
        Exposure time in seconds
    binsize: int
        Binning to use for the image, must be 1, 2, or 4, etc

    Returns
    -------
    future : `future`
        Future object that contains the image as 2D numpy array.

    Usage:
        future = ctrl.get_future_image()
        (other operations)
        img = future.result()
    """
    future = self._executor.submit(self.get_raw_image, exposure=exposure, binsize=binsize)
    return future
get_image(exposure=None, binsize=None, comment='', out=None, plot=False, verbose=False, header_keys=('all',))

Retrieve image as numpy array from camera. If the exposure and binsize are not given, the default values are read from the config file.

Parameters:

  • exposure (float, default: None ) –

    Exposure time in seconds

  • binsize (int, default: None ) –

    Binning to use for the image, must be 1, 2, or 4, etc.

  • comment (str, default: '' ) –

    Arbitrary comment to add to the header file under 'ImageComment'

  • out (str, default: None ) –

    Path or filename to which the image/header is saved (defaults to tiff)

  • plot (bool, default: False ) –

    Toggle whether to show the image using matplotlib after acquisition

  • full_header –

    Return the full header

Returns:

  • image ( np.ndarray, headerfile: dict ) –

    Tuple of the image as numpy array and dictionary with all the tem parameters and image attributes

  • Usage ( dict ) –

    img, h = self.get_image()

Source code in src/instamatic/controller.py
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
@requires_cam_attr
def get_image(
    self,
    exposure: float = None,
    binsize: int = None,
    comment: str = '',
    out: str = None,
    plot: bool = False,
    verbose: bool = False,
    header_keys: Tuple[str] = ('all',),
) -> Tuple[np.ndarray, dict]:
    """Retrieve image as numpy array from camera. If the exposure and
    binsize are not given, the default values are read from the config
    file.

    Parameters
    ----------
    exposure: float
        Exposure time in seconds
    binsize: int
        Binning to use for the image, must be 1, 2, or 4, etc.
    comment: str
        Arbitrary comment to add to the header file under 'ImageComment'
    out: str
        Path or filename to which the image/header is saved (defaults to tiff)
    plot: bool
        Toggle whether to show the image using matplotlib after acquisition
    full_header: bool
        Return the full header

    Returns
    -------
    image: np.ndarray, headerfile: dict
        Tuple of the image as numpy array and dictionary with all the tem parameters and image attributes

    Usage:
        img, h = self.get_image()
    """
    if not binsize:
        binsize = self.cam.default_binsize
    if not exposure:
        exposure = self.cam.default_exposure

    h = self.to_dict(*header_keys) if header_keys else {}

    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()

    h['ImageGetTime'] = time.time()
    h['ImageExposureTime'] = exposure
    h['ImageBinsize'] = binsize
    h['ImageResolution'] = arr.shape
    # k['ImagePixelsize'] = config.calibration[mode]['pixelsize'][mag] * binsize
    # k['ImageRotation'] = config.calibration[mode]['rotation'][mag]
    h['ImageComment'] = comment
    h['ImageCameraName'] = self.cam.name
    h['ImageCameraDimensions'] = self.cam.get_camera_dimensions()

    if verbose:
        print(f'Image acquired - shape: {arr.shape}, size: {arr.nbytes / 1024:.0f} kB')

    if out:
        write_tiff(out, arr, header=h)

    if plot:
        import matplotlib.pyplot as plt

        plt.imshow(arr)
        plt.show()

    return arr, h
get_movie(n_frames, exposure=None, binsize=None, comment='', header_keys=MOVIE_HEADER_KEYS_VARIABLE, header_keys_common=MOVIE_HEADER_KEYS_COMMON)

Generate (image, header) pairs using camera's movie mode. If the exposure and binsize are not given, the default values are read from the config file. Common header info is collected before the generator is started by calling next, minimizing the gap between frames.

Parameters:

  • n_frames (int) –

    Number of frames to collect

  • exposure (float, default: None ) –

    Exposure time in seconds

  • binsize (int, default: None ) –

    Binning to use for the image, must be 1, 2, or 4, etc.

  • comment (str, default: '' ) –

    Arbitrary comment to add to the header file under 'ImageComment'

  • header_keys (Tuple[str], default: MOVIE_HEADER_KEYS_VARIABLE ) –

    Header keys to collect alongside each image. Use few to minimize lag.

  • header_keys_common (Tuple[str], default: MOVIE_HEADER_KEYS_COMMON ) –

    Common header keys to collect once at the start of get_movie only.

Yields:

  • image_header ( Generator[(ndarray, ChainMap), None, None] ) –

    Generator of (numpy arrays with image data, ChainMap with all the tem parameters and image attributes) pairs.

  • Usage ( ndarray ) –

    for img, h in self.get_movie(10, **kwargs): print(img.shape)

Source code in src/instamatic/controller.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
@requires_cam_attr
def get_movie(
    self,
    n_frames: int,
    exposure: float = None,
    binsize: int = None,
    comment: str = '',
    header_keys: Tuple[str] = MOVIE_HEADER_KEYS_VARIABLE,
    header_keys_common: Tuple[str] = MOVIE_HEADER_KEYS_COMMON,
) -> Generator[np.ndarray, None, None]:
    """Generate (image, header) pairs using camera's movie mode. If the
    exposure and binsize are not given, the default values are read from
    the config file. Common header info is collected before the generator
    is started by calling next, minimizing the gap between frames.

    Parameters
    ----------
    n_frames : int
        Number of frames to collect
    exposure : float, optional
        Exposure time in seconds
    binsize : int, optional
        Binning to use for the image, must be 1, 2, or 4, etc.
    comment: str, optional
        Arbitrary comment to add to the header file under 'ImageComment'
    header_keys: Tuple[str]
        Header keys to collect alongside each image. Use few to minimize lag.
    header_keys_common: Tuple[str]
        Common header keys to collect once at the start of get_movie only.

    Yields
    -------
    image_header: Generator[(np.ndarray, collections.ChainMap), None, None]
        Generator of (numpy arrays with image data, ChainMap with
        all the tem parameters and image attributes) pairs.

    Usage:
        for img, h in self.get_movie(10, **kwargs): print(img.shape)
    """
    if not binsize:
        binsize = self.cam.default_binsize
    if not exposure:
        exposure = self.cam.default_exposure

    header_common = self.to_dict(*header_keys_common) if header_keys_common else {}
    header_common['ImageExposureTime'] = exposure
    header_common['ImageBinsize'] = binsize
    header_common['ImageComment'] = comment
    header_common['ImageCameraName'] = self.cam.name
    header_common['ImageCameraDimensions'] = self.cam.get_camera_dimensions()

    gen = self.cam.get_movie(n_frames=n_frames, exposure=exposure, binsize=binsize)
    with self.beam.unblanked(condition=self.autoblank):
        for _ in range(n_frames):
            # The generator `gen` starts collecting only when the first `next` is called.
            # Request the next image, expect it in the future, get header in the meantime
            future_img = self._executor.submit(lambda: next(gen))
            time_start = time.perf_counter()

            header = header_common.copy()
            header['ImageGetTimeStart'] = time_start
            header.update(self.to_dict(*header_keys) if header_keys else {})

            if 'Magnification' not in header:
                header['Magnification'] = self.magnification.value
            if 'FunctionMode' not in header:
                header['FunctionMode'] = self.mode.get()
            mag = header['Magnification']
            mode = header['FunctionMode']

            img = future_img.result()
            header['ImageGetTimeEnd'] = time.perf_counter()
            header['ImageGetTime'] = time.time()

            rotate_image(img, mode=mode, mag=mag)
            header['ImageResolution'] = img.shape
            yield img, header
    gen.close()
get_raw_image(exposure=None, binsize=None)

Simplified function equivalent to get_image that only returns the raw data array.

Parameters:

  • exposure (float, default: None ) –

    Exposure in seconds.

  • binsize (int, default: None ) –

    Image binning.

Returns:

  • arr ( array ) –

    Image as 2D numpy array.

Source code in src/instamatic/controller.py
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
@requires_cam_attr
def get_raw_image(self, exposure: float = None, binsize: int = None) -> np.ndarray:
    """Simplified function equivalent to `get_image` that only returns the
    raw data array.

    Parameters
    ----------
    exposure : float
        Exposure in seconds.
    binsize : int
        Image binning.

    Returns
    -------
    arr : np.array
        Image as 2D numpy array.
    """
    return self.cam.get_image(exposure=exposure, binsize=binsize)
get_rotated_image(exposure=None, binsize=None)

Simplified function equivalent to get_image that returns the rotated image array.

Parameters:

  • exposure (float, default: None ) –

    Exposure time in seconds

  • binsize (int, default: None ) –

    Binning to use for the image, must be 1, 2, or 4, etc

  • mode (str) –

    Magnification mode

  • mag (int) –

    Magnification value

Returns:

  • arr ( array ) –

    Image as 2D numpy array.

Source code in src/instamatic/controller.py
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
def get_rotated_image(self, exposure: float = None, binsize: int = None) -> np.ndarray:
    """Simplified function equivalent to `get_image` that returns the
    rotated image array.

    Parameters
    ----------
    exposure: float
        Exposure time in seconds
    binsize: int
        Binning to use for the image, must be 1, 2, or 4, etc
    mode : str
        Magnification mode
    mag : int
        Magnification value

    Returns
    -------
    arr : np.array
        Image as 2D numpy array.
    """
    future = self.get_future_image(exposure=exposure, binsize=binsize)

    mag = self.magnification.value
    mode = self.mode.get()

    arr = future.result()
    arr = rotate_image(arr, mode=mode, mag=mag)

    return arr
get_stagematrix(binning=None, mag=None, mode=None)

Helper function to get the stage matrix from the config file. The stagematrix is used to convert from pixel coordinates to stage coordiantes. The parameters are optional and if not given, the current values are read out from the microscope/camera.

Parameters:

  • binning (int, default: None ) –

    Binning of the image that the stagematrix will be applied to

  • mag (int, default: None ) –

    Magnification value

  • mode (int, default: None ) –

    Current TEM mode ("lowmag", "mag1")

Returns:

  • stagematrix ( array[2, 2] ) –

    Affine transformation matrix to convert from stage to pixel coordinates

Source code in src/instamatic/controller.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def get_stagematrix(self, binning: int = None, mag: int = None, mode: int = None):
    """Helper function to get the stage matrix from the config file. The
    stagematrix is used to convert from pixel coordinates to stage
    coordiantes. The parameters are optional and if not given, the current
    values are read out from the microscope/camera.

    Parameters
    ----------
    binning: int
        Binning of the image that the stagematrix will be applied to
    mag: int
        Magnification value
    mode: str
        Current TEM mode ("lowmag", "mag1")

    Returns
    -------
    stagematrix : np.array[2, 2]
        Affine transformation matrix to convert from stage to pixel coordinates
    """
    if not mode:
        mode = self.mode.get()
    if not mag:
        mag = self.magnification.value
    if not binning:
        binning = self.cam.get_binning()

    stagematrix = config.calibration[mode]['stagematrix'][mag]
    stagematrix = np.array(stagematrix).reshape(2, 2) * binning  # um -> nm

    return stagematrix
grid_montage()

Create an instance of gridmontage.GridMontage using the current magnification/mode.

Usage: gm = GridMontage(ctrl) pos = m.setup(5, 5) m = gm.to_montage() coords = m.get_montage_coords(optimize=True)

Source code in src/instamatic/controller.py
452
453
454
455
456
457
458
459
460
461
462
463
464
465
def grid_montage(self):
    """Create an instance of `gridmontage.GridMontage` using the current
    magnification/mode.

    Usage:
        gm = GridMontage(ctrl)
        pos = m.setup(5, 5)
        m = gm.to_montage()
        coords = m.get_montage_coords(optimize=True)
    """
    from instamatic.gridmontage import GridMontage

    gm = GridMontage(self)
    return gm
restore(name='stash')

Restores alignment from dictionary by the given name.

Source code in src/instamatic/controller.py
810
811
812
813
814
def restore(self, name: str = 'stash'):
    """Restores alignment from dictionary by the given name."""
    d = self._saved_alignments[name]
    self.from_dict(d)
    print(f"Microscope alignment restored from '{name}'")
run_script(script, verbose=True)

Run a custom python script with access to the ctrl object.

It will check if the script exists in the scripts directory if it cannot find it directly.

Source code in src/instamatic/controller.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
def run_script(self, script: str, verbose: bool = True) -> None:
    """Run a custom python script with access to the `ctrl` object.

    It will check if the script exists in the scripts directory if
    it cannot find it directly.
    """
    from instamatic.io import find_script

    script = find_script(script)

    if verbose:
        print(f'Executing script: {script}\n')

    ctrl = self

    t0 = time.perf_counter()
    exec(open(script).read())
    t1 = time.perf_counter()

    if verbose:
        print(f'\nScript finished in {t1 - t0:.4f} s')
run_script_at_items(nav_items, script, backlash=True)

Run the given script at all coordinates defined by the nav_items.

Parameters:

  • nav_items (list) –

    Takes a list of nav items (read from a SerialEM .nav file) and loops over the stage coordinates

  • script (str) –

    Runs this script at each of the positions specified in coordinate list This function will call 3 functions, which must be defined as: acquire pre_acquire post_acquire

  • backlash (bool, default: True ) –

    Toggle to move to each position with backlash correction

Source code in src/instamatic/controller.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def run_script_at_items(self, nav_items: list, script: str, backlash: bool = True) -> None:
    """Run the given script at all coordinates defined by the nav_items.

    Parameters
    ----------
    nav_items: list
        Takes a list of nav items (read from a SerialEM .nav file) and loops over the
        stage coordinates
    script: str
        Runs this script at each of the positions specified in coordinate list
            This function will call 3 functions, which must be defined as:
                `acquire`
                `pre_acquire`
                `post_acquire`

    backlash: bool
        Toggle to move to each position with backlash correction
    """
    from instamatic.io import find_script

    script = find_script(script)

    import importlib.util

    spec = importlib.util.spec_from_file_location('acquire', script)
    acquire = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(acquire)

    ntot = len(nav_items)

    print(f'Running script: {script} on {ntot} items.')

    pre_acquire = getattr(acquire, 'pre_acquire', None)
    post_acquire = getattr(acquire, 'post_acquire', None)
    acquire = getattr(acquire, 'acquire', None)

    self.acquire_at_items(
        nav_items,
        acquire=acquire,
        pre_acquire=pre_acquire,
        post_acquire=post_acquire,
        backlash=backlash,
    )
show_stream()

If the camera has been opened as a stream, start a live view in a tkinter window.

Source code in src/instamatic/controller.py
822
823
824
825
826
827
828
829
830
def show_stream(self):
    """If the camera has been opened as a stream, start a live view in a
    tkinter window."""
    try:
        self.cam.show_stream()
    except AttributeError:
        print(
            'Cannot open live view. The camera interface must be initialized as a stream object.'
        )
store(name='stash', keys=None, save_to_file=False)

Stores current settings to dictionary.

Multiple settings can be stored under different names. Specify which settings should be stored using keys

Source code in src/instamatic/controller.py
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
def store(self, name: str = 'stash', keys: tuple = None, save_to_file: bool = False):
    """Stores current settings to dictionary.

    Multiple settings can be stored under different names. Specify
    which settings should be stored using `keys`
    """
    d = self.to_dict(*keys if keys else ())
    d.pop('StagePosition', None)
    self._saved_alignments[name] = d

    if save_to_file:
        fn = config.alignments_drc / (name + '.yaml')
        d2 = {k: list(v) if isinstance(v, DeflectorTuple) else v for k, v in d.items()}
        yaml.safe_dump(d2, stream=open(fn, 'w'))
        print(f'Saved alignment to file `{fn}`')
store_diff_beam(name='beam', save_to_file=False)

Record alignment for current diffraction beam. Stores Guntilt (for dose control), diffraction focus, spot size, brightness, and the function mode.

Restore the alignment using: ctrl.restore("beam")

Source code in src/instamatic/controller.py
782
783
784
785
786
787
788
789
790
791
792
def store_diff_beam(self, name: str = 'beam', save_to_file: bool = False):
    """Record alignment for current diffraction beam. Stores Guntilt (for
    dose control), diffraction focus, spot size, brightness, and the
    function mode.

    Restore the alignment using:     `ctrl.restore("beam")`
    """
    if self.mode != 'diff':
        raise TEMControllerError('Microscope is not in `diffraction mode`')
    keys = 'FunctionMode', 'Brightness', 'GunTilt', 'DiffFocus', 'SpotSize'
    self.store(name=name, keys=keys, save_to_file=save_to_file)
to_dict(*keys)

Store microscope parameters to dict.

keys: tuple of str (optional) If any keys are specified, dict is returned with only the given properties

self.to_dict('all') or self.to_dict() will return all properties

Source code in src/instamatic/controller.py
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
def to_dict(self, *keys) -> dict:
    """Store microscope parameters to dict.

    keys: tuple of str (optional)
        If any keys are specified, dict is returned with only the given properties

    self.to_dict('all') or self.to_dict() will return all properties
    """
    # Each of these costs about 40-60 ms per call on a JEOL 2100, stage is 265 ms per call
    funcs = {
        'FunctionMode': self.tem.getFunctionMode,
        'GunShift': self.gunshift.get,
        'GunTilt': self.guntilt.get,
        'BeamShift': self.beamshift.get,
        'BeamTilt': self.beamtilt.get,
        'ImageShift1': self.imageshift1.get,
        'ImageShift2': self.imageshift2.get,
        'DiffShift': self.diffshift.get,
        'StagePosition': self.stage.get,
        'Magnification': self.magnification.get,
        'DiffFocus': self.difffocus.get,
        'Brightness': self.brightness.get,
        'SpotSize': self.tem.getSpotSize,
    }

    dct = {}

    if 'all' in keys or not keys:
        keys = funcs.keys()

    for key in keys:
        try:
            dct[key] = funcs[key]()
        except ValueError:
            # print(f"No such key: `{key}`")
            pass

    return dct

Functions:

get_instance()

Gets the current ctrl instance if it has been initialized, otherwise initialize it using default parameters.

Source code in src/instamatic/controller.py
74
75
76
77
78
79
80
81
82
83
84
85
def get_instance() -> 'TEMController':
    """Gets the current `ctrl` instance if it has been initialized, otherwise
    initialize it using default parameters."""

    global _ctrl

    if _ctrl:
        ctrl = _ctrl
    else:
        ctrl = _ctrl = initialize()

    return ctrl

initialize(tem_name=default_tem, cam_name=default_cam, stream=True)

Initialize TEMController object giving access to the TEM and Camera interfaces.

Parameters:

  • tem_name (str, default: default_tem ) –

    Name of the TEM to use

  • cam_name (str, default: default_cam ) –

    Name of the camera to use, can be set to 'None' to skip camera initialization

  • stream (bool, default: True ) –

    Open the camera as a stream (this enables TEMController.show_stream())

Returns:

  • ctrl ( `TEMController` ) –

    Return TEM control object

Source code in src/instamatic/controller.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
def initialize(
    tem_name: str = default_tem, cam_name: str = default_cam, stream: bool = True
) -> 'TEMController':
    """Initialize TEMController object giving access to the TEM and Camera
    interfaces.

    Parameters
    ----------
    tem_name : str
        Name of the TEM to use
    cam_name : str
        Name of the camera to use, can be set to 'None' to skip camera initialization
    stream : bool
        Open the camera as a stream (this enables `TEMController.show_stream()`)

    Returns
    -------
    ctrl : `TEMController`
        Return TEM control object
    """
    print(f'Microscope: {tem_name}{" (server)" if use_tem_server else ""}')
    tem = get_microscope(tem_name, use_server=use_tem_server)

    if cam_name:
        if use_cam_server:
            cam_tag = ' (server)'
        elif stream:
            cam_tag = ' (stream)'
        else:
            cam_tag = ''

        print(f'Camera    : {cam_name}{cam_tag}')

        cam = get_camera(cam_name, as_stream=stream, use_server=use_cam_server)
    else:
        cam = None

    global _ctrl
    ctrl = _ctrl = TEMController(tem=tem, cam=cam)

    return ctrl

requires_cam_attr(method)

Decorator that raises an error if self.cam evaluates to False.

Source code in src/instamatic/controller.py
88
89
90
91
92
93
94
95
96
97
98
def requires_cam_attr(method: Callable) -> Callable:
    """Decorator that raises an error if `self.cam` evaluates to False."""

    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if not getattr(self, 'cam', None):
            msg = " object has no attribute 'cam' (Camera has not been initialized)"
            raise AttributeError(self.__class__.__name__ + msg)
        return method(self, *args, **kwargs)

    return wrapper

Modules