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/TEMController/TEMController.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def __init__(self, tem, cam=None):
    super().__init__()

    self._executor = ThreadPoolExecutor(max_workers=1)

    self.tem = tem
    self.cam = cam

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

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

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

Attributes

current_density: float property

Get current density from fluorescence screen in pA/cm2.

high_tension: float property

Get the high tension value in V.

Functions

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/TEMController/TEMController.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
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/TEMController/TEMController.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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
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/TEMController/TEMController.py
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
359
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
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:.1f} 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/TEMController/TEMController.py
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
505
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/TEMController/TEMController.py
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
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/TEMController/TEMController.py
579
580
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
610
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
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 self.cam:
        raise AttributeError(f"{self.__class__.__name__} object has no attribute 'cam' (Camera has not been initialized)")

    if not binsize:
        binsize = self.cam.default_binsize
    if not exposure:
        exposure = self.cam.default_exposure

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

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

    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, out=None)

Collect a stack of images using the camera's movie mode, if available.

This minimizes 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

  • out (str, default: None ) –

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

Returns:

  • stack ( Tuple[ndarray] ) –

    List of numpy arrays with image data.

Source code in src/instamatic/TEMController/TEMController.py
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
def get_movie(self,
              n_frames: int,
              *,
              exposure: float = None,
              binsize: int = None,
              out: str = None) -> Tuple[np.ndarray]:
    """Collect a stack of images using the camera's movie mode, if
    available.

    This minimizes 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
    out : str, optional
        Path or filename to which the image/header is saved (defaults to tiff)

    Returns
    -------
    stack : Tuple[np.ndarray]
        List of numpy arrays with image data.
    """
    if not self.cam:
        raise AttributeError(f"{self.__class__.__name__} object has no attribute 'cam' (Camera has not been initialized)")

    if not binsize:
        binsize = self.cam.default_binsize
    if not exposure:
        exposure = self.cam.default_exposure

    if self.autoblank:
        self.beam.unblank()

    stack = self.cam.get_movie(n_frames=n_frames, exposure=exposure, binsize=binsize)

    if self.autoblank:
        self.beam.blank()

    return stack
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/TEMController/TEMController.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
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/TEMController/TEMController.py
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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/TEMController/TEMController.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
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/TEMController/TEMController.py
422
423
424
425
426
427
428
429
430
431
432
433
434
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/TEMController/TEMController.py
738
739
740
741
742
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/TEMController/TEMController.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
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/TEMController/TEMController.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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/TEMController/TEMController.py
750
751
752
753
754
755
756
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/TEMController/TEMController.py
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
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`
    """
    if not keys:
        keys = ()
    d = self.to_dict(*keys)
    d.pop('StagePosition', None)
    self._saved_alignments[name] = d

    if save_to_file:
        import yaml
        fn = config.alignments_drc / (name + '.yaml')
        yaml.dump(d, 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/TEMController/TEMController.py
708
709
710
711
712
713
714
715
716
717
718
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/TEMController/TEMController.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
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/TEMController/TEMController.py
70
71
72
73
74
75
76
77
78
79
80
81
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/TEMController/TEMController.py
29
30
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
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 = 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 = 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

Modules