def main_entry():
    import argparse
    description = """Program to calibrate the lowmag mode (100x) of the microscope (Deprecated)."""

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument(
        'args',
        type=str,
        nargs='*',
        metavar='IMG',
        help=
        'Perform calibration using pre-collected images. The first image must be the center image used as the reference position. The other images are cross-correlated to this image to calibrate the translations. If no arguments are given, run the live calibration routine.'
    )

    options = parser.parse_args()
    args = options.args

    if not args:
        from instamatic import TEMController
        ctrl = TEMController.initialize()
        calibrate_stage_lowmag(ctrl=ctrl, save_images=True)
    else:
        center_fn = args[0]
        other_fn = args[1:]
        calibrate_stage_lowmag(center_fn, other_fn)
示例#2
0
def main():
    import argparse
    description = """Tiny button to focus and defocus the diffraction pattern."""

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    options = parser.parse_args()

    ctrl = TEMController.initialize()

    root = Tk()
    DefocusButton(root).pack(side='top',
                             fill='both',
                             expand=True,
                             padx=10,
                             pady=10)
    root.lift()

    # keep window in front of other windows
    root.attributes('-topmost', True)

    root.title(f'Instamatic defocus helper')
    root.mainloop()
示例#3
0
def main():
    from instamatic import TEMController
    ctrl = TEMController.initialize()

    import logging
    log = logging.getLogger(__name__)

    exposure_time = 0.5
    tilt_range = 10
    stepsize = 1.0

    i = 1
    while True:
        expdir = f"experiment_{i}"
        if os.path.exists(expdir):
            i += 1
        else:
            break

    print(f"\nData directory: {expdir}")
    
    red_exp = Experiment(ctrl=ctrl, path=expdir, log=log, flatfield=None)
    red_exp.start_collection(exposure_time=exposure_time, tilt_range=tilt_range, stepsize=stepsize)

    input("Press << Enter >> to start the experiment... ")
    
    while not input(f"\nPress << Enter >> to continue for another {tilt_range} degrees. [any key to finalize] ") :
        red_exp.start_collection(exposure_time=exposure_time, tilt_range=tilt_range, stepsize=stepsize)

    red_exp.finalize()
示例#4
0
def main_entry():
    import argparse
    description = """Program to calibrate the brightness of the microscope (Deprecated)."""

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument(
        'args',
        type=str,
        nargs='*',
        metavar='IMG',
        help=
        'Perform calibration using pre-collected images. If no arguments are given, run the live calibration routine.'
    )

    options = parser.parse_args()
    args = options.args

    if not args:
        from instamatic import TEMController
        ctrl = TEMController.initialize()
        calibrate_brightness(ctrl, save_images=True)
    else:
        calibrate_brightness(args)
示例#5
0
def main():
    import argparse
    description = """Command line program to run the serial ED data collection routine."""

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    options = parser.parse_args()

    from instamatic import TEMController

    try:
        params = json.load(open('params.json', 'r'))
    except OSError:
        params = {}

    logging.basicConfig(
        format=
        '%(asctime)s | %(module)s:%(lineno)s | %(levelname)s | %(message)s',
        filename='instamatic.log',
        level=logging.DEBUG)
    logging.captureWarnings(True)
    log = logging.getLogger(__name__)

    ctrl = TEMController.initialize()

    exp = Experiment(ctrl, params, log=log)
    exp.report_status()
    exp.run()

    ctrl.close()
def main_entry():
    import argparse
    description = """Program to calibrate the diffraction shift (PLA) to correct for beamshift movements (Deprecated)."""

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument(
        'args',
        type=str,
        nargs='*',
        metavar='IMG',
        help=
        'Perform calibration using pre-collected images. They must be formatted as such: DiffShift:pattern.tiff BeamShift:pattern.tiff, where `pattern` is a globbing pattern that finds the images corresponding to the key BeamShift or DiffShift. The first image must be the center image used as the reference position. The other images are cross-correlated to this image to calibrate the translations. If no arguments are given, run the live calibration routine.'
    )

    options = parser.parse_args()
    args = options.args

    if args:
        calibrate_directbeam(patterns=args)
    else:
        from instamatic import TEMController
        ctrl = TEMController.initialize()
        calibrate_directbeam(ctrl=ctrl)
示例#7
0
def main():
    import argparse

    description = """
Utility script to enable rotation control from a dmscript. See [https://github.com/instamatic-dev/instamatic/tree/master/dmscript] for usage.
"""

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    options = parser.parse_args()

    date = datetime.datetime.now().strftime('%Y-%m-%d')
    logfile = config.locations[
        'logs'] / f'instamatic_temserver_Themis_{date}.log'
    logging.basicConfig(
        format=
        '%(asctime)s | %(module)s:%(lineno)s | %(levelname)s | %(message)s',
        filename=logfile,
        level=logging.DEBUG)
    logging.captureWarnings(True)
    log = logging.getLogger(__name__)

    ctrl = TEMController.initialize()

    s = socket(AF_INET, SOCK_STREAM)
    s.bind((HOST, PORT))
    s.listen(5)

    log.info(f'TEM server listening on {HOST}:{PORT}')
    print(f'TEM server listening on {HOST}:{PORT}')

    with s:
        while True:
            conn, addr = s.accept()
            log.info('Connected by %s', addr)
            print('Connected by', addr)
            threading.Thread(target=handle, args=(conn, )).start()
示例#8
0
def main():
    from instamatic import TEMController
    try:
        params = json.load(open("params.json", "r"))
    except IOError:
        params = {}

    logging.basicConfig(
        format=
        "%(asctime)s | %(module)s:%(lineno)s | %(levelname)s | %(message)s",
        filename="instamatic.log",
        level=logging.DEBUG)
    logging.captureWarnings(True)
    log = logging.getLogger(__name__)

    ctrl = TEMController.initialize()

    exp = Experiment(ctrl, params, log=log)
    exp.report_status()
    exp.run()

    ctrl.close()
示例#9
0
def main():
    import argparse

    description = ""
    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument("-s",
                        "--script",
                        action="store",
                        type=str,
                        dest="script",
                        help="Run the script given")

    parser.add_argument("-n",
                        "--nav",
                        action="store",
                        type=str,
                        dest="nav_file",
                        help="Load the given .nav file")

    parser.add_argument(
        "-a",
        "--acquire_at_items",
        action="store_true",
        dest="acquire_at_items",
        help=
        "Run the script file `--script` at every point marked with `Acquire` in the nav file `--nav`."
    )

    parser.add_argument(
        "-l",
        "--locate",
        action="store",
        type=str,
        dest="locate",
        help=
        "Locate a requested directory and exit, i.e. `config`, `data`, `scripts`, `base`, 'work`, `logs`"
    )

    parser.add_argument(
        "-o",
        "--open",
        action="store",
        type=str,
        dest="open",
        help="Open the requested directory and exit, see `--locate`.")

    parser.set_defaults(
        script=None,
        acquire_at_items=False,
        nav_file=None,
        start_gui=True,
        locate=None,
        open=False,
    )

    options = parser.parse_args()

    if options.locate:
        locate(options.locate)
        exit()
    if options.open:
        locate(options.open, open=True)
        exit()

    from instamatic.utils import high_precision_timers
    high_precision_timers.enable()  # sleep timers with 1 ms resolution

    # enable faster switching between threads
    sys.setswitchinterval(0.001)  # seconds

    from instamatic import version
    version.register_thank_you_message()

    from instamatic import config

    date = datetime.datetime.now().strftime("%Y-%m-%d")
    logfile = config.logs_drc / f"instamatic_{date}.log"

    logging.basicConfig(
        format=
        "%(asctime)s | %(module)s:%(lineno)s | %(levelname)s | %(message)s",
        filename=logfile,
        level=logging.DEBUG)

    logging.captureWarnings(True)
    log = logging.getLogger(__name__)
    log.info(f"Instamatic started: {repr(options.__dict__)}")

    from instamatic import TEMController
    ctrl = TEMController.initialize(stream=True)

    if options.nav_file:
        from instamatic.serialem import read_nav_file
        nav_items = read_nav_file(options.nav_file, acquire_only=True)

    if options.acquire_at_items:
        ctrl.run_script_at_items(nav_items=nav_items, script=options.script)
    elif options.script:
        ctrl.run_script(options.script)
    elif options.start_gui:
        from instamatic.gui import start_gui
        start_gui(ctrl, log=log)
示例#10
0
def main_entry():
    import argparse
    from instamatic.formats import write_tiff

    description = """Simple program to acquire image data from the camera."""

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument(
        '-b',
        '--binsize',
        action='store',
        type=int,
        metavar='N',
        dest='binsize',
        help="""Binsize to use. Must be one of 1, 2, or 4 (default 1)""")

    parser.add_argument('-e',
                        '--exposure',
                        action='store',
                        type=float,
                        metavar='N',
                        dest='exposure',
                        help="""Exposure time (default 0.5)""")

    parser.add_argument('-o',
                        '--out',
                        action='store',
                        type=str,
                        metavar='image.png',
                        dest='outfile',
                        help="""Where to store image""")

    parser.add_argument('-d',
                        '--display',
                        action='store_true',
                        dest='show_fig',
                        help="""Show the image (default True)""")

    parser.add_argument(
        '-s',
        '--series',
        action='store_true',
        dest='take_series',
        help="""Enable mode to take a series of images (default False)""")

    parser.set_defaults(
        binsize=1,
        exposure=1,
        outfile=None,
        show_fig=False,
        test=False,
        take_series=False,
    )

    options = parser.parse_args()

    binsize = options.binsize
    exposure = options.exposure

    outfile = options.outfile
    show_fig = options.show_fig

    take_series = options.take_series

    from instamatic import TEMController
    ctrl = TEMController.initialize()

    if take_series:
        i = 1
        print('\nUsage:')
        print('    set b/e/i X -> set binsize/exposure/file number to X')
        print('    XXX         -> Add comment to header')
        print('    exit        -> exit the program')
    while take_series:
        outfile = f'image_{i:04d}'
        inp = input(f'\nHit enter to take an image: \n >> [{outfile}] ')
        if inp == 'exit':
            break
        elif inp.startswith('set'):
            try:
                key, value = inp.split()[1:3]
            except ValueError:
                print('Input not understood')
                continue
            if key == 'e':
                try:
                    value = float(value)
                except ValueError as e:
                    print(e)
                if value > 0:
                    exposure = value
            elif key == 'b':
                try:
                    value = int(value)
                except ValueError as e:
                    print(e)
                if value in (1, 2, 4):
                    binsize = value
            elif key == 'i':
                try:
                    value = int(value)
                except ValueError as e:
                    print(e)
                if value > 0:
                    i = value
            print(f'binsize = {binsize} | exposure = {exposure} | file #{i}')
        else:
            arr, h = ctrl.get_image(binsize=binsize,
                                    exposure=exposure,
                                    comment=inp)

            write_tiff(outfile, arr, header=h)

            i += 1
    else:
        import matplotlib.pyplot as plt

        arr, h = ctrl.get_image(binsize=binsize, exposure=exposure)

        if show_fig:
            plt.imshow(arr, cmap='gray', interpolation='none')
            plt.show()

        if outfile:
            write_tiff(outfile, arr, header=h)
        else:
            write_tiff('out', arr, header=h)
示例#11
0
    def __init__(self, parent):
        LabelFrame.__init__(self, parent, text="Stage Control")
        self.parent = parent

        self.init_vars()

        frame = Frame(self)

        b_stage_stop = Button(frame,
                              text="Stop stage",
                              command=self.stage_stop)
        b_stage_stop.grid(row=0, column=2, sticky="W")

        cb_nowait = Checkbutton(frame,
                                text="Wait for stage",
                                variable=self.var_stage_wait)
        cb_nowait.grid(row=0, column=3)

        b_find_eucentric_height = Button(frame,
                                         text="Find eucentric height",
                                         command=self.find_eucentric_height)
        b_find_eucentric_height.grid(row=0,
                                     column=0,
                                     sticky="EW",
                                     columnspan=2)

        Label(frame, text="Mode:").grid(row=8, column=0, sticky="W")
        self.o_mode = OptionMenu(frame,
                                 self.var_mode,
                                 'diff',
                                 'diff',
                                 'mag1',
                                 'mag2',
                                 'lowmag',
                                 'samag',
                                 command=self.set_mode)
        self.o_mode.grid(row=8, column=1, sticky="W", padx=10)

        frame.pack(side="top", fill="x", padx=10, pady=10)

        frame = Frame(self)

        Label(frame, text="Angle (-)", width=20).grid(row=1,
                                                      column=0,
                                                      sticky="W")
        Label(frame, text="Angle (0)", width=20).grid(row=2,
                                                      column=0,
                                                      sticky="W")
        Label(frame, text="Angle (+)", width=20).grid(row=3,
                                                      column=0,
                                                      sticky="W")
        Label(frame, text="Alpha wobbler (±)", width=20).grid(row=4,
                                                              column=0,
                                                              sticky="W")

        Label(frame, text="Stage(XY)", width=20).grid(row=5,
                                                      column=0,
                                                      sticky="W")

        e_negative_angle = Spinbox(frame,
                                   width=10,
                                   textvariable=self.var_negative_angle,
                                   from_=-90,
                                   to=90,
                                   increment=5)
        e_negative_angle.grid(row=1, column=1, sticky="EW")
        e_neutral_angle = Spinbox(frame,
                                  width=10,
                                  textvariable=self.var_neutral_angle,
                                  from_=-90,
                                  to=90,
                                  increment=5)
        e_neutral_angle.grid(row=2, column=1, sticky="EW")
        e_positive_angle = Spinbox(frame,
                                   width=10,
                                   textvariable=self.var_positive_angle,
                                   from_=-90,
                                   to=90,
                                   increment=5)
        e_positive_angle.grid(row=3, column=1, sticky="EW")

        e_alpha_wobbler = Spinbox(frame,
                                  width=10,
                                  textvariable=self.var_alpha_wobbler,
                                  from_=-90,
                                  to=90,
                                  increment=1)
        e_alpha_wobbler.grid(row=4, column=1, sticky="EW")
        self.b_start_wobble = Button(frame,
                                     text="Start",
                                     command=self.start_alpha_wobbler)
        self.b_start_wobble.grid(row=4, column=2, sticky="W")
        self.b_stop_wobble = Button(frame,
                                    text="Stop",
                                    command=self.stop_alpha_wobbler,
                                    state=DISABLED)
        self.b_stop_wobble.grid(row=4, column=3, sticky="W")

        e_stage_x = Entry(frame, width=10, textvariable=self.var_stage_x)
        e_stage_x.grid(row=5, column=1, sticky="EW")
        e_stage_y = Entry(frame, width=10, textvariable=self.var_stage_y)
        e_stage_y.grid(row=5, column=2, sticky="EW")

        b_negative_angle = Button(frame,
                                  text="Set",
                                  command=self.set_negative_angle)
        b_negative_angle.grid(row=1, column=2, sticky="W")
        b_neutral_angle = Button(frame,
                                 text="Set",
                                 command=self.set_neutral_angle)
        b_neutral_angle.grid(row=2, column=2, sticky="W")
        b_positive_angle = Button(frame,
                                  text="Set",
                                  command=self.set_positive_angle)
        b_positive_angle.grid(row=3, column=2, sticky="W")
        b_stage = Button(frame, text="Set", command=self.set_stage)
        b_stage.grid(row=5, column=3, sticky="W")
        b_stage_get = Button(frame, text="Get", command=self.get_stage)
        b_stage_get.grid(row=5, column=4, sticky="W")

        # frame.grid_columnconfigure(1, weight=1)
        frame.pack(side="top", fill="x", padx=10, pady=10)

        frame = Frame(self)

        Label(frame, text="Brightness", width=20).grid(row=11,
                                                       column=0,
                                                       sticky="W")
        e_brightness = Entry(frame, width=10, textvariable=self.var_brightness)
        e_brightness.grid(row=11, column=1, sticky="W")

        b_brightness = Button(frame, text="Set", command=self.set_brightness)
        b_brightness.grid(row=11, column=2, sticky="W")

        b_brightness_get = Button(frame,
                                  text="Get",
                                  command=self.get_brightness)
        b_brightness_get.grid(row=11, column=3, sticky="W")

        slider = Scale(frame,
                       variable=self.var_brightness,
                       from_=0,
                       to=2**16 - 1,
                       orient=HORIZONTAL,
                       command=self.set_brightness)
        slider.grid(row=12, column=0, columnspan=3, sticky="EW")

        frame.pack(side="top", fill="x", padx=10, pady=10)

        frame = Frame(self)

        Label(frame, text="DiffFocus", width=20).grid(row=11,
                                                      column=0,
                                                      sticky="W")
        e_difffocus = Entry(frame, width=10, textvariable=self.var_difffocus)
        e_difffocus.grid(row=11, column=1, sticky="W")

        b_difffocus = Button(frame, text="Set", command=self.set_difffocus)
        b_difffocus.grid(row=11, column=2, sticky="W")

        b_difffocus_get = Button(frame, text="Get", command=self.get_difffocus)
        b_difffocus_get.grid(row=11, column=3, sticky="W")

        slider = Scale(frame,
                       variable=self.var_difffocus,
                       from_=0,
                       to=2**16 - 1,
                       orient=HORIZONTAL,
                       command=self.set_difffocus)
        slider.grid(row=12, column=0, columnspan=3, sticky="EW")

        frame.pack(side="top", fill="x", padx=10, pady=10)

        from instamatic import TEMController
        self.ctrl = TEMController.get_instance()
示例#12
0
def main_entry():
    import argparse
    description = """Program to collect and apply flatfield/darkfield corrections"""

    parser = argparse.ArgumentParser(  # usage=usage,
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument("args",
                        type=str,
                        nargs="*",
                        metavar="image.tiff",
                        help="Image file paths/pattern")

    parser.add_argument("-f",
                        "--flatfield",
                        action="store",
                        type=str,
                        metavar="flatfield.tiff",
                        dest="flatfield",
                        help="""Path to flatfield file""")

    parser.add_argument("-d",
                        "--darkfield",
                        action="store",
                        type=str,
                        metavar="darkfield.tiff",
                        dest="darkfield",
                        help="""Path to darkfield file""")

    parser.add_argument("-o",
                        "--output",
                        action="store",
                        type=str,
                        metavar="DRC",
                        dest="drc",
                        help="""Output directory for image files""")

    parser.add_argument(
        "-c",
        "--collect",
        action="store_true",
        dest="collect",
        help="""Collect flatfield/darkfield images on microscope""")

    parser.set_defaults(
        flatfield=None,
        darkfield=None,
        drc="corrected",
        collect=False,
    )

    options = parser.parse_args()
    args = options.args

    if options.collect:
        ctrl = TEMController.initialize()
        collect_flatfield(ctrl=ctrl, save_images=False)
        ctrl.close()
        exit()

    if options.flatfield:
        flatfield, h = read_tiff(options.flatfield)
        deadpixels = h["deadpixels"]
    else:
        print("No flatfield file specified")
        exit()

    if options.darkfield:
        darkfield, h = read_tiff(options.darkfield)
    else:
        darkfield = np.zeros_like(flatfield)

    if len(args) == 1:
        fobj = args[0]
        if not os.path.exists(fobj):
            args = glob.glob(fobj)

    drc = Path(options.drc)
    drc.mkdir(exist_ok=True, parents=True)

    for f in args:
        img, h = read_tiff(f)

        img = apply_corrections(img, deadpixels=deadpixels)
        img = apply_flatfield_correction(img, flatfield, darkfield=darkfield)

        name = Path(f).name
        fout = drc / name

        print(name, "->", fout)
        write_tiff(fout, img, header=h)
示例#13
0
def main():
    import argparse

    description = """Start instamatic with various functions (see below). If no arguments are given, start the instamatic GUI. The GUI is modular and can be defined using the config system. The GUI can be used to control the microscope and run the experiments. The GUI itself is further described on the GUI page."""

    parser = argparse.ArgumentParser(description=description,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('-s', '--script',
                        action='store', type=str, dest='script',
                        help='Run the script given')

    parser.add_argument('-n', '--nav',
                        action='store', type=str, dest='nav_file',
                        help='Load the given .nav file')

    parser.add_argument('-a', '--acquire_at_items',
                        action='store_true', dest='acquire_at_items',
                        help='Run the script file `--script` at every point marked with `Acquire` in the nav file `--nav`.')

    parser.add_argument('-l', '--locate',
                        action='store', type=str, dest='locate',
                        help="Locate a requested directory and exit, i.e. `config`, `data`, `scripts`, `base`, 'work`, `logs`")

    parser.add_argument('-o', '--open',
                        action='store', type=str, dest='show',
                        help='Open the requested directory and exit, see `--locate`.')

    parser.add_argument('-i', '--info',
                        action='store_true', dest='info',
                        help='Show info about the current instamatic installation.')

    parser.set_defaults(script=None,
                        acquire_at_items=False,
                        nav_file=None,
                        start_gui=True,
                        locate=None,
                        show=False,
                        info=False,
                        )

    options = parser.parse_args()

    if options.locate:
        locate(options.locate)
        exit()
    if options.show:
        locate(options.show, show=True)
        exit()
    if options.info:
        show_info()
        exit()

    from instamatic.utils import high_precision_timers
    high_precision_timers.enable()  # sleep timers with 1 ms resolution

    # enable faster switching between threads
    sys.setswitchinterval(0.001)  # seconds

    from instamatic import banner
    banner.register_thank_you_message()

    from instamatic import config

    date = datetime.datetime.now().strftime('%Y-%m-%d')
    logfile = config.locations['logs'] / f'instamatic_{date}.log'

    logging.basicConfig(format='%(asctime)s | %(module)s:%(lineno)s | %(levelname)s | %(message)s',
                        filename=logfile,
                        level=logging.DEBUG)

    logging.captureWarnings(True)
    log = logging.getLogger(__name__)
    log.info(f'Instamatic started: {repr(options.__dict__)}')

    from instamatic import TEMController
    ctrl = TEMController.initialize(stream=True)

    if options.nav_file:
        from pyserialem import read_nav_file
        nav_items = read_nav_file(options.nav_file, acquire_only=True)

    if options.acquire_at_items:
        ctrl.run_script_at_items(nav_items=nav_items, script=options.script)
    elif options.script:
        ctrl.run_script(options.script)
    elif options.start_gui:
        from instamatic.gui import start_gui
        start_gui(ctrl, log=log)
示例#14
0
def main_entry():
    import argparse
    from instamatic.formats import write_tiff
    # usage = """acquire"""

    description = """Program to acquire image data from gatan gatan ccd camera"""

    parser = argparse.ArgumentParser(  # usage=usage,
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    # parser.add_argument("args",
    #                     type=str, metavar="FILE",
    #                     help="Path to save cif")

    parser.add_argument(
        "-b",
        "--binsize",
        action="store",
        type=int,
        metavar="N",
        dest="binsize",
        help="""Binsize to use. Must be one of 1, 2, or 4 (default 1)""")

    parser.add_argument("-e",
                        "--exposure",
                        action="store",
                        type=float,
                        metavar="N",
                        dest="exposure",
                        help="""Exposure time (default 0.5)""")

    parser.add_argument("-o",
                        "--out",
                        action="store",
                        type=str,
                        metavar="image.png",
                        dest="outfile",
                        help="""Where to store image""")

    parser.add_argument("-d",
                        "--display",
                        action="store_true",
                        dest="show_fig",
                        help="""Show the image (default True)""")

    # parser.add_argument("-t", "--tem",
    #                     action="store", type=str, dest="tem",
    #                     help="""Simulate microscope connection (default False)""")

    parser.add_argument(
        "-u",
        "--simulate",
        action="store_true",
        dest="simulate",
        help="""Simulate camera/microscope connection (default False)""")

    parser.add_argument(
        "-s",
        "--series",
        action="store_true",
        dest="take_series",
        help="""Enable mode to take a series of images (default False)""")

    parser.set_defaults(binsize=1,
                        exposure=1,
                        outfile=None,
                        show_fig=False,
                        test=False,
                        simulate=False,
                        camera="simulate",
                        take_series=False)

    options = parser.parse_args()

    binsize = options.binsize
    exposure = options.exposure

    outfile = options.outfile
    show_fig = options.show_fig

    take_series = options.take_series

    from instamatic import TEMController
    ctrl = TEMController.initialize()

    if take_series:
        i = 1
        print("\nUsage:")
        print("    set b/e/i X -> set binsize/exposure/file number to X")
        print("    XXX         -> Add comment to header")
        print("    exit        -> exit the program")
    while take_series:
        outfile = f"image_{i:04d}"
        inp = input(f"\nHit enter to take an image: \n >> [{outfile}] ")
        if inp == "exit":
            break
        elif inp.startswith("set"):
            try:
                key, value = inp.split()[1:3]
            except ValueError:
                print("Input not understood")
                continue
            if key == "e":
                try:
                    value = float(value)
                except ValueError as e:
                    print(e)
                if value > 0:
                    exposure = value
            elif key == "b":
                try:
                    value = int(value)
                except ValueError as e:
                    print(e)
                if value in (1, 2, 4):
                    binsize = value
            elif key == "i":
                try:
                    value = int(value)
                except ValueError as e:
                    print(e)
                if value > 0:
                    i = value
            print(f"binsize = {binsize} | exposure = {exposure} | file #{i}")
        else:
            arr, h = ctrl.getImage(binsize=binsize,
                                   exposure=exposure,
                                   comment=inp)

            write_tiff(outfile, arr, header=h)

            i += 1
    else:
        import matplotlib.pyplot as plt

        arr, h = ctrl.getImage(binsize=binsize, exposure=exposure)

        if show_fig:
            # save_header(sys.stdout, h)
            plt.imshow(arr, cmap="gray", interpolation="none")
            plt.show()

        if outfile:
            write_tiff(outfile, arr, header=h)
        else:
            write_tiff("out", arr, header=h)
示例#15
0
    def close(self):
        try:
            self.stream_frame.close()
        except AttributeError:
            pass
        sys.exit()


def start_gui(ctrl, log=None):
    """Function to start the gui, to be imported and run elsewhere when ctrl is
    initialized Requires the `ctrl` object to be passed."""
    root = Tk()

    gui = MainFrame(root, cam=ctrl.cam, modules=MODULES)

    experiment_ctrl = DataCollectionController(ctrl=ctrl,
                                               stream=ctrl.cam,
                                               beam_ctrl=None,
                                               app=gui.app,
                                               log=log)
    experiment_ctrl.start()

    root.mainloop()


if __name__ == '__main__':
    from instamatic import TEMController
    ctrl = TEMController.initialize()
    start_gui(ctrl)
示例#16
0
    def __init__(self, parent):
        LabelFrame.__init__(self, parent, text="Continuous rotation electron diffraction (TVIPS)")
        self.parent = parent

        sbwidth = 10

        self.init_vars()

        frame = Frame(self)
        Label(frame, text="Target angle (degrees):").grid(row=4, column=0, sticky="W")
        self.e_target_angle = Spinbox(frame, textvariable=self.var_target_angle, width=sbwidth, from_=-80.0, to=80.0, increment=5.0, state=NORMAL)
        self.e_target_angle.grid(row=4, column=1, sticky="W", padx=10)
        
        self.InvertAngleButton = Button(frame, text="Invert", command=self.invert_angle)
        self.InvertAngleButton.grid(row=4, column=2, sticky="EW")

        self.c_toggle_manual_control = Checkbutton(frame, text="Manual rotation control", variable=self.var_toggle_manual_control, command=self.toggle_manual_control)
        self.c_toggle_manual_control.grid(row=4, column=3, sticky="W")

        # defocus button
        Label(frame, text="Diff defocus:").grid(row=6, column=0, sticky="W")
        self.e_diff_defocus = Spinbox(frame, textvariable=self.var_diff_defocus, width=sbwidth, from_=-10000, to=10000, increment=100)
        self.e_diff_defocus.grid(row=6, column=1, sticky="W", padx=10)

        Label(frame, text="Exposure (ms):").grid(row=7, column=0, sticky="W")
        self.e_exposure = Spinbox(frame, textvariable=self.var_exposure, width=sbwidth, from_=0, to=10000, increment=100)
        self.e_exposure.grid(row=7, column=1, sticky="W", padx=10)

        Label(frame, text="Mode:").grid(row=8, column=0, sticky="W")
        self.o_mode = OptionMenu(frame, self.var_mode, 'diff', 'diff', 'mag1', 'mag2', 'lowmag', 'samag')
        self.o_mode.grid(row=8, column=1, sticky="W", padx=10)

        self.c_toggle_defocus = Checkbutton(frame, text="Toggle defocus", variable=self.var_toggle_diff_defocus, command=self.toggle_diff_defocus)
        self.c_toggle_defocus.grid(row=6, column=3, sticky="W")

        self.b_reset_defocus = Button(frame, text="Reset", command=self.reset_diff_defocus, state=DISABLED)
        self.b_reset_defocus.grid(row=6, column=2, sticky="EW")


        self.c_toggle_diffraction = Checkbutton(frame, text="Toggle DIFF", variable=self.var_toggle_diff_mode, command=self.toggle_diff_mode)
        self.c_toggle_diffraction.grid(row=7, column=3, sticky="W")

        self.c_toggle_screen = Checkbutton(frame, text="Toggle screen", variable=self.var_toggle_screen, command=self.toggle_screen)
        self.c_toggle_screen.grid(row=8, column=3, sticky="W")

        self.b_start_liveview = Button(frame, text="Start live view", command=self.start_liveview)
        self.b_start_liveview.grid(row=7, column=2, sticky="EW")

        self.b_stop_liveview = Button(frame, text="Stop live view", command=self.stop_liveview)
        self.b_stop_liveview.grid(row=8, column=2, sticky="EW")

        self.c_toggle_beamblank = Checkbutton(frame, text="Toggle beamblank", variable=self.var_toggle_beamblank, command=self.toggle_beamblank)
        self.c_toggle_beamblank.grid(row=10, column=3, sticky="W")

        frame.pack(side="top", fill="x", padx=10, pady=10)

        frame = Frame(self)

        self.e_instructions = Entry(frame, width=50, textvariable=self.var_instruction_file)
        self.e_instructions.grid(row=4, column=1, sticky="EW")
        self.BrowseTrackButton = Button(frame, text="Browse..", command=self.browse_instructions)
        self.BrowseTrackButton.grid(row=4, column=2, sticky="EW")
        Label(frame, text="Instruction file:").grid(row=4, column=0, sticky="W")
        frame.pack(side="top", fill="x", padx=10, pady=10)

        frame = Frame(self)
        self.SearchButton = Button(frame, text="Search", command=self.search)
        self.SearchButton.grid(row=1, column=0, sticky="EW")

        self.FocusButton = Button(frame, text="Focus", command=self.focus)
        self.FocusButton.grid(row=1, column=1, sticky="EW")

        self.GetImageButton = Button(frame, text="Get image", command=self.get_image)
        self.GetImageButton.grid(row=1, column=2, sticky="EW")

        frame.columnconfigure(0, weight=1)
        frame.columnconfigure(1, weight=1)
        frame.columnconfigure(2, weight=1)

        frame.pack(fill="x", padx=10, pady=10)

        frame = Frame(self)

        self.SerialButton = Button(frame, text="Start serial acquisition", width=25, command=self.serial_collection)
        self.SerialButton.grid(row=1, column=0, sticky="EW")

        frame.pack(fill="x", padx=10, pady=10)

        frame = Frame(self)
        self.GetReadyButton = Button(frame, text="Get Ready", command=self.prime_collection)
        self.GetReadyButton.grid(row=1, column=0, sticky="EW")

        self.AcquireButton = Button(frame, text="Acquire", command=self.start_collection, state=DISABLED)
        self.AcquireButton.grid(row=1, column=1, sticky="EW")

        self.FinalizeButton = Button(frame, text="Finalize", command=self.stop_collection, state=DISABLED)
        self.FinalizeButton.grid(row=1, column=2, sticky="EW")

        frame.columnconfigure(0, weight=1)
        frame.columnconfigure(1, weight=1)
        frame.columnconfigure(2, weight=1)

        frame.pack(side="bottom", fill="x", padx=10, pady=10)

        from instamatic import TEMController
        self.ctrl = TEMController.get_instance()
def main_entry():
    import argparse

    description = """Run the stagematrix calibration routine for all magnifications
specified. Return the updates values for the configuration file.

Calibrate the stage movement (nm) and the position of the camera
(pixels) at a specific magnification.

The stagematrix takes the image binning into account."""

    parser = argparse.ArgumentParser(description=description,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('-m', '--mode', dest='mode', type=str,
                        help=('Select the imaging mode (mag1/mag2/lowmag/samag). '
                              'If `all` is specified, all imaging modes+mags are calibrated.'
                              'If the imaging mode and magnification are not given, the current'
                              'values are used.'))

    parser.add_argument('-k', '--mag', dest='mags', type=int, nargs='+', metavar='K',
                        help='Select the imaging magnification(s).')

    parser.add_argument('-A', '--all_mags', action='store_true', dest='all_mags',
                        help='Run calibration routine for all mags over selected mode.')

    parser.add_argument('-v', '--overlap', dest='overlap', type=float, metavar='X',
                        help=('Specify the approximate overlap between images for cross '
                              'correlation.'))

    parser.add_argument('-l', '--stage_length', dest='stage_length', type=int,
                        help=('Specify the minimum length (in stage coordinates) the calibration '
                              'should cover.'))

    parser.add_argument('-a', '--min_n_steps', dest='min_n_step', type=int, metavar='N',
                        help=('Specify the minimum number of steps to take along X and Y for the '
                              'calibration.'))

    parser.add_argument('-b', '--max_n_steps', dest='max_n_step', type=int, metavar='N',
                        help=('Specify the maximum number of steps to take along X and Y for the '
                              'calibration. This is used for higher magnifications.'))

    parser.add_argument('-s', '--save', action='store_true', dest='save',
                        help=f'Save the data to the data directory [{data_drc}].')

    parser.set_defaults(mode=(),
                        mags=(),
                        overlap=0.8,
                        stage_length=40_000,
                        min_n_step=5,
                        max_n_step=9,
                        plot=False,
                        drc=None,
                        save=False,
                        )

    options = parser.parse_args()

    mode = options.mode
    mags = options.mags

    from instamatic import TEMController
    ctrl = TEMController.initialize()

    if not mode:
        mode = ctrl.mode.get()
    if not mags:
        mags = (ctrl.magnification.get(), )

    kwargs = {
        'overlap': options.overlap,
        'stage_length': options.stage_length,
        'min_n_step': options.min_n_step,
        'max_n_step': options.max_n_step,
    }

    if mode == 'all':
        calibrate_stage_all(
            ctrl,
            save=options.save,
            **kwargs,
        )
    elif options.all_mags:
        calibrate_stage_all(
            ctrl,
            mode=mode,
            save=options.save,
            **kwargs,
        )
    else:
        calibrate_stage_all(
            ctrl,
            mag_ranges={mode: mags},
            save=options.save,
            **kwargs,
        )
示例#18
0
    def __init__(self, parent):
        LabelFrame.__init__(self, parent, text='Stage Control')
        self.parent = parent

        self.init_vars()

        frame = Frame(self)

        b_stage_stop = Button(frame,
                              text='Stop stage',
                              command=self.stage_stop)
        b_stage_stop.grid(row=0, column=2, sticky='W')

        cb_nowait = Checkbutton(frame,
                                text='Wait for stage',
                                variable=self.var_stage_wait)
        cb_nowait.grid(row=0, column=3)

        b_find_eucentric_height = Button(frame,
                                         text='Find eucentric height',
                                         command=self.find_eucentric_height)
        b_find_eucentric_height.grid(row=0,
                                     column=0,
                                     sticky='EW',
                                     columnspan=2)

        Label(frame, text='Mode:').grid(row=8, column=0, sticky='W')
        self.o_mode = OptionMenu(frame,
                                 self.var_mode,
                                 'diff',
                                 'diff',
                                 'mag1',
                                 'mag2',
                                 'lowmag',
                                 'samag',
                                 command=self.set_mode)
        self.o_mode.grid(row=8, column=1, sticky='W', padx=10)

        frame.pack(side='top', fill='x', padx=10, pady=10)

        frame = Frame(self)

        Label(frame, text='Angle (-)', width=20).grid(row=1,
                                                      column=0,
                                                      sticky='W')
        Label(frame, text='Angle (0)', width=20).grid(row=2,
                                                      column=0,
                                                      sticky='W')
        Label(frame, text='Angle (+)', width=20).grid(row=3,
                                                      column=0,
                                                      sticky='W')
        Label(frame, text='Alpha wobbler (±)', width=20).grid(row=4,
                                                              column=0,
                                                              sticky='W')
        Label(frame, text='Stage(XY)', width=20).grid(row=6,
                                                      column=0,
                                                      sticky='W')

        e_negative_angle = Spinbox(frame,
                                   width=10,
                                   textvariable=self.var_negative_angle,
                                   from_=-90,
                                   to=90,
                                   increment=5)
        e_negative_angle.grid(row=1, column=1, sticky='EW')
        e_neutral_angle = Spinbox(frame,
                                  width=10,
                                  textvariable=self.var_neutral_angle,
                                  from_=-90,
                                  to=90,
                                  increment=5)
        e_neutral_angle.grid(row=2, column=1, sticky='EW')
        e_positive_angle = Spinbox(frame,
                                   width=10,
                                   textvariable=self.var_positive_angle,
                                   from_=-90,
                                   to=90,
                                   increment=5)
        e_positive_angle.grid(row=3, column=1, sticky='EW')

        e_alpha_wobbler = Spinbox(frame,
                                  width=10,
                                  textvariable=self.var_alpha_wobbler,
                                  from_=-90,
                                  to=90,
                                  increment=1)
        e_alpha_wobbler.grid(row=4, column=1, sticky='EW')
        self.b_start_wobble = Button(frame,
                                     text='Start',
                                     command=self.start_alpha_wobbler)
        self.b_start_wobble.grid(row=4, column=2, sticky='W')
        self.b_stop_wobble = Button(frame,
                                    text='Stop',
                                    command=self.stop_alpha_wobbler,
                                    state=DISABLED)
        self.b_stop_wobble.grid(row=4, column=3, sticky='W')

        e_stage_x = Entry(frame, width=10, textvariable=self.var_stage_x)
        e_stage_x.grid(row=6, column=1, sticky='EW')
        e_stage_y = Entry(frame, width=10, textvariable=self.var_stage_y)
        e_stage_y.grid(row=6, column=2, sticky='EW')

        if config.settings.use_goniotool:
            Label(frame, text='Rot. Speed', width=20).grid(row=5,
                                                           column=0,
                                                           sticky='W')
            e_goniotool_tx = Spinbox(frame,
                                     width=10,
                                     textvariable=self.var_goniotool_tx,
                                     from_=1,
                                     to=12,
                                     increment=1)
            e_goniotool_tx.grid(row=5, column=1, sticky='EW')
            b_goniotool_set = Button(frame,
                                     text='Set',
                                     command=self.set_goniotool_tx)
            b_goniotool_set.grid(row=5, column=2, sticky='W')
            b_goniotool_default = Button(frame,
                                         text='Default',
                                         command=self.set_goniotool_tx_default)
            b_goniotool_default.grid(row=5, column=3, sticky='W')

        b_negative_angle = Button(frame,
                                  text='Set',
                                  command=self.set_negative_angle)
        b_negative_angle.grid(row=1, column=2, sticky='W')
        b_neutral_angle = Button(frame,
                                 text='Set',
                                 command=self.set_neutral_angle)
        b_neutral_angle.grid(row=2, column=2, sticky='W')
        b_positive_angle = Button(frame,
                                  text='Set',
                                  command=self.set_positive_angle)
        b_positive_angle.grid(row=3, column=2, sticky='W')

        b_stage = Button(frame, text='Set', command=self.set_stage)
        b_stage.grid(row=6, column=3, sticky='W')
        b_stage_get = Button(frame, text='Get', command=self.get_stage)
        b_stage_get.grid(row=6, column=4, sticky='W')

        # defocus button
        Label(frame, text='Diff defocus:', width=20).grid(row=13,
                                                          column=0,
                                                          sticky='W')
        self.e_diff_defocus = Spinbox(frame,
                                      textvariable=self.var_diff_defocus,
                                      width=10,
                                      from_=-10000,
                                      to=10000,
                                      increment=100)
        self.e_diff_defocus.grid(row=13, column=1, sticky='EW')

        self.c_toggle_defocus = Checkbutton(
            frame,
            text='Toggle defocus',
            variable=self.var_toggle_diff_defocus,
            command=self.toggle_diff_defocus)
        self.c_toggle_defocus.grid(row=13, column=2, sticky='W', columnspan=2)

        self.b_reset_defocus = Button(frame,
                                      text='Reset',
                                      command=self.reset_diff_defocus,
                                      state=DISABLED)
        self.b_reset_defocus.grid(row=13, column=4, sticky='EW')

        # frame.grid_columnconfigure(1, weight=1)
        frame.pack(side='top', fill='x', padx=10, pady=10)

        frame = Frame(self)

        Label(frame, text='Brightness', width=20).grid(row=11,
                                                       column=0,
                                                       sticky='W')
        e_brightness = Entry(frame, width=10, textvariable=self.var_brightness)
        e_brightness.grid(row=11, column=1, sticky='W')

        b_brightness = Button(frame, text='Set', command=self.set_brightness)
        b_brightness.grid(row=11, column=2, sticky='W')

        b_brightness_get = Button(frame,
                                  text='Get',
                                  command=self.get_brightness)
        b_brightness_get.grid(row=11, column=3, sticky='W')

        slider = Scale(frame,
                       variable=self.var_brightness,
                       from_=0,
                       to=2**16 - 1,
                       orient=HORIZONTAL,
                       command=self.set_brightness)
        slider.grid(row=12, column=0, columnspan=3, sticky='EW')

        frame.pack(side='top', fill='x', padx=10, pady=10)

        frame = Frame(self)

        Label(frame, text='DiffFocus', width=20).grid(row=11,
                                                      column=0,
                                                      sticky='W')
        e_difffocus = Entry(frame, width=10, textvariable=self.var_difffocus)
        e_difffocus.grid(row=11, column=1, sticky='W')

        b_difffocus = Button(frame, text='Set', command=self.set_difffocus)
        b_difffocus.grid(row=11, column=2, sticky='W')

        b_difffocus_get = Button(frame, text='Get', command=self.get_difffocus)
        b_difffocus_get.grid(row=11, column=3, sticky='W')

        slider = Scale(frame,
                       variable=self.var_difffocus,
                       from_=0,
                       to=2**16 - 1,
                       orient=HORIZONTAL,
                       command=self.set_difffocus)
        slider.grid(row=12, column=0, columnspan=3, sticky='EW')

        frame.pack(side='top', fill='x', padx=10, pady=10)

        from instamatic import TEMController
        self.ctrl = TEMController.get_instance()
示例#19
0
def test_setup(ctrl):
    from instamatic import TEMController

    ctrl2 = TEMController.get_instance()
    assert ctrl2 is ctrl
示例#20
0
def main_entry():
    import argparse
    description = """
This is a program that can collect and apply flatfield/darkfield corrections [link](https://en.wikipedia.org/wiki/Flat-field_correction). To do so, use a spread, bright beam on a hole in the carbon, or a clear piece of carbon film, and run:

    instamatic.flatfield --collect

This will collect 100 images and average them to determine the flatfield image. A darkfield image is also collected by applying the same routine with the beam blanked. Dead pixels are identified as pixels with 0 intensities. To apply these corrections:

    instamatic.flatfield image.tiff [image.tiff ..] -f flatfield.tiff [-d darkfield.tiff] [-o drc]

This will apply the flatfield correction (`-f`) and optionally the darkfield correction (`-d`) to images given as argument, and place the corrected files in directory `corrected` or as specified using `-o`."""

    parser = argparse.ArgumentParser(
        description=description,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument('args',
                        type=str,
                        nargs='*',
                        metavar='image.tiff',
                        help='Image file paths/pattern')

    parser.add_argument('-f',
                        '--flatfield',
                        action='store',
                        type=str,
                        metavar='flatfield.tiff',
                        dest='flatfield',
                        help="""Path to flatfield file""")

    parser.add_argument('-d',
                        '--darkfield',
                        action='store',
                        type=str,
                        metavar='darkfield.tiff',
                        dest='darkfield',
                        help="""Path to darkfield file""")

    parser.add_argument('-o',
                        '--output',
                        action='store',
                        type=str,
                        metavar='DRC',
                        dest='drc',
                        help="""Output directory for image files""")

    parser.add_argument(
        '-c',
        '--collect',
        action='store_true',
        dest='collect',
        help="""Collect flatfield/darkfield images on microscope""")

    parser.set_defaults(
        flatfield=None,
        darkfield=None,
        drc='corrected',
        collect=False,
    )

    options = parser.parse_args()
    args = options.args

    if options.collect:
        ctrl = TEMController.initialize()
        collect_flatfield(ctrl=ctrl, save_images=False)
        ctrl.close()
        exit()

    if options.flatfield:
        flatfield, h = read_tiff(options.flatfield)
        deadpixels = h['deadpixels']
    else:
        print('No flatfield file specified')
        exit()

    if options.darkfield:
        darkfield, h = read_tiff(options.darkfield)
    else:
        darkfield = np.zeros_like(flatfield)

    if len(args) == 1:
        fobj = args[0]
        if not os.path.exists(fobj):
            args = glob.glob(fobj)

    drc = Path(options.drc)
    drc.mkdir(exist_ok=True, parents=True)

    for f in args:
        img, h = read_tiff(f)

        img = apply_corrections(img, deadpixels=deadpixels)
        img = apply_flatfield_correction(img, flatfield, darkfield=darkfield)

        name = Path(f).name
        fout = drc / name

        print(name, '->', fout)
        write_tiff(fout, img, header=h)