示例#1
0
def test_tag_loading(map_item, drc):
    n = 10

    coords = np.arange(n * 2).reshape(n, 2)
    nav_items = map_item.add_marker_group(coords, acquire=True)

    out = drc.parent / 'data' / 'out2.nav'
    pysem.write_nav_file(out, map_item, *nav_items)

    items = pysem.read_nav_file(out, acquire_only=False)
    assert len(items) == 1 + n

    items = pysem.read_nav_file(out, acquire_only=True)
    assert len(items) == n
示例#2
0
    def __init__(self,
                 ctrl,
                 path: str = None,
                 log=None,
                 instruction_file: str = None,
                 exposure: float = 400,
                 mode: str = 'diff',
                 target_angle: float = 40,
                 rotation_speed=None):
        super().__init__()

        self.instruction_file = Path(instruction_file)
        self.base_drc = self.instruction_file.parent

        if self.instruction_file.suffix == '.nav':
            self.nav_items = read_nav_file(self.instruction_file,
                                           acquire_only=True)
            self.run = self.run_from_nav_file
            self.start_angle = target_angle / 2
            self.end_angle = -self.start_angle
        else:
            self.tracks = open(self.instruction_file, 'r').readlines()
            self.run = self.run_from_tracking_file

        self.log = log
        self.path = path
        self.ctrl = ctrl
        self.exposure = exposure
        self.mode = mode
        self.rotation_speed = rotation_speed
示例#3
0
def test_reader_writer(drc):
    fn = drc.parent / 'data' / 'nav.nav'

    items = pysem.read_nav_file(fn)

    assert isinstance(items, list)
    assert len(items) == 1

    out = drc.parent / 'data' / 'out.nav'

    pysem.write_nav_file(out, *items)

    assert out.exists()

    pysem.read_nav_file(out)

    assert isinstance(items, list)
    assert len(items) == 1
def find_map_items(nav_file, mrc_name):
    """This function reads in the nav file and finds the map items that contain the crystals.
    Input: nav file (navigator file from serialEM), mrc name (name of .mrc which contains ROIs)
    """
    map_items = serialem.read_nav_file(nav_file)
    items = []

    for item in map_items:
        try:
            # print(item, item.MapFile)
            if mrc_name.name == Path(item.MapFile).name:
                items.append(item)
        except AttributeError:
            pass

    return items
示例#5
0
def calculate_scaling(
    nav: str,
    mrc: str,
    train_size: int,
    train_mag_index: int,
    training: bool = False,
):
    print("Calculating scaling factor for test images...")
    map_items = serialem.read_nav_file(nav)
    items = []
    for item in map_items:  # This for loop finds the map items which contain visible crystals.
        try:
            if mrc.name in item.MapFile:
                items.append(item)
        except AttributeError:
            pass

    if not items:  # if length is zero this will raise an error
        print(
            'Empty items list; either the wrong mrc filename was entered or no relevant map items are in the nav file!'
        )
        exit()

    im_size = items[0].MapWidthHeight[0]

    if training:
        scaling_factor = 1024 / im_size
    else:
        MapMagInd = items[0].MapMagInd
        with open(MapScaleInd_yaml) as f:  # Load the magnification indices
            MapScale = yaml.safe_load(f)

        train_mag = MapScale[train_mag_index]
        im_mag = MapScale[MapMagInd]

        print(f'Mag: image={im_mag} -> training={train_mag}')
        print(f'Size: image={im_size} -> training={train_size}')

        # final scaling factor is the scaling to go to 1024 times scaling
        scaling_factor = (train_mag / im_mag) * (train_size / im_size)

    print(f'Scale factor: {scaling_factor:.4f}')

    return scaling_factor, im_size
示例#6
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)
示例#7
0
 def set_nav_file(self, nav: str = 'output.nav'):
     """Set the `.nav` file to load the stage/image coordinates from."""
     nav_items = read_nav_file(nav)
     self.map_items = [item for item in nav_items if item.kind == 'Map']
     self.stagecoords = np.array([mi.stage_xy for mi in self.map_items]) * 1000
     self.imagecoords = self.montage.stage_to_pixelcoords(self.stagecoords)
示例#8
0
def map_item(drc):
    fn = drc.parent / 'data' / 'nav.nav'
    items = pysem.read_nav_file(fn)
    map_item = items[0]
    assert map_item.kind == 'Map'
    return map_item