예제 #1
0
파일: save.py 프로젝트: rosswhitfield/ase
def save_dialog(gui):
    dialog = gtk.FileChooserDialog(_('Save ...'),
                                   None,
                                   gtk.FILE_CHOOSER_ACTION_SAVE,
                                   (gtk.STOCK_SAVE, gtk.RESPONSE_OK,
                                    gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
    dialog.set_current_name('')
    dialog.set_current_folder(os.getcwd())
    text = _('Append name with "@n" in order to write image number "n" '
             'instead of the current image.\n'
             'Append "@start:stop" or "@start:stop:step" if you want to write '
             'a range of images.\n'
             'You can leave out "start" and "stop" so that "name@:" will '
             'give you all images.\n'
             'Negative numbers count from the last image '
             '("name@-1": last image, "name@-2:": last two).')
    dialog.set_extra_widget(gtk.Label(text))
    response = dialog.run()
    if response == gtk.RESPONSE_OK:
        filename = dialog.get_filename()
        dialog.destroy()
    else:
        dialog.destroy()
        return
        
    filename, index = parse_filename(filename)
    if index is None:
        index = slice(gui.frame, gui.frame + 1)
    if isinstance(index, str):
        index = string2index(index)
    format = filetype(filename, read=False)
    io = get_ioformat(format)
    
    extra = {}
    remove_hidden = False
    if format in ['png', 'eps', 'pov']:
        bbox = np.empty(4)
        size = np.array([gui.width, gui.height]) / gui.scale
        bbox[0:2] = np.dot(gui.center, gui.axes[:, :2]) - size / 2
        bbox[2:] = bbox[:2] + size
        extra['rotation'] = gui.axes
        extra['show_unit_cell'] = gui.ui.get_widget(
            '/MenuBar/ViewMenu/ShowUnitCell').get_active()
        extra['bbox'] = bbox
        extra['colors'] = gui.get_colors(rgb=True)[gui.images.visible]
        remove_hidden = True

    images = [gui.images.get_atoms(i, remove_hidden=remove_hidden)
              for i in range(*index.indices(gui.images.nimages))]
    
    if len(images) > 1 and io.single:
        # We want to write multiple images, but the file format does not
        # support it.  The solution is to write multiple files, inserting
        # a number in the file name before the suffix.
        j = filename.rfind('.')
        filename = filename[:j] + '{0:05d}' + filename[j:]
        for i, atoms in enumerate(images):
            write(filename.format(i), atoms, **extra)
    else:
        write(filename, images, **extra)
예제 #2
0
def check(path, query, verbose):
    """Check a path.

    Returns a (filetype, AtomsRow object) tuple.
    """

    try:
        format = filetype(path, guess=False)
    except (OSError, UnknownFileTypeError):
        return '', None

    if format in ['db', 'json']:
        db = connect(path)
    else:
        try:
            atoms = read(path, format=format)
        except Exception as x:
            if verbose:
                print(path + ':', x, file=sys.stderr)
            return '', None
        db = FakeDB(atoms)

    try:
        for row in db._select(*query):
            return format, row
    except Exception as x:
        if verbose:
            print(path + ':', x, file=sys.stderr)

    return '', None
예제 #3
0
파일: info.py 프로젝트: essil1/ase-laser
    def run(args):
        if not args.filename:
            print_info()
            if args.formats:
                print()
                print_formats()
            return

        n = max(len(filename) for filename in args.filename) + 2
        for filename in args.filename:
            try:
                format = filetype(filename)
            except FileNotFoundError:
                format = '?'
                description = 'No such file'
            except UnknownFileTypeError:
                format = '?'
                description = '?'
            else:
                description, code = all_formats.get(format, ('?', '?'))

            print('{:{}}{} ({})'.format(filename + ':', n,
                                        description, format))
            if args.verbose:
                if format == 'traj':
                    print_ulm_info(filename)
                elif format == 'bundletrajectory':
                    print_bundletrajectory_info(filename)
예제 #4
0
파일: info.py 프로젝트: yfyh2013/ase
    def run(args):
        if not args.filenames:
            print_info()
            return

        n = max(len(filename) for filename in args.filenames) + 2
        for filename in args.filenames:
            try:
                format = filetype(filename)
            except FileNotFoundError:
                format = '?'
                description = 'No such file'
            else:
                if format and format in all_formats:
                    description, code = all_formats[format]
                else:
                    format = '?'
                    description = '?'

            print('{:{}}{} ({})'.format(filename + ':', n, description,
                                        format))
            if args.verbose:
                if format == 'traj':
                    print_ulm_info(filename)
                elif format == 'bundletrajectory':
                    print_bundletrajectory_info(filename)
예제 #5
0
    def run(args):
        if not args.filenames:
            print_info()
            return

        n = max(len(filename) for filename in args.filenames) + 2
        for filename in args.filenames:
            try:
                format = filetype(filename)
            except FileNotFoundError:
                format = '?'
                description = 'No such file'
            else:
                if format and format in all_formats:
                    description, code = all_formats[format]
                else:
                    format = '?'
                    description = '?'

            print('{:{}}{} ({})'.format(filename + ':', n,
                                        description, format))
            if args.verbose:
                if format == 'traj':
                    print_ulm_info(filename)
                elif format == 'bundletrajectory':
                    print_bundletrajectory_info(filename)
예제 #6
0
def save_dialog(gui, filename=None):
    dialog = ui.SaveFileDialog(gui.window.win, _('Save ...'))
    ui.Text(text).pack(dialog.top)
    filename = filename or dialog.go()
    if not filename:
        return

    filename, index = parse_filename(filename)
    if index is None:
        index = slice(gui.frame, gui.frame + 1)
    elif isinstance(index, basestring):
        index = string2index(index)
    elif isinstance(index, slice):
        pass
    else:
        if index < 0:
            index += len(gui.images)
        index = slice(index, index + 1)
    format = filetype(filename, read=False)
    io = get_ioformat(format)

    extra = {}
    remove_hidden = False
    if format in ['png', 'eps', 'pov']:
        bbox = np.empty(4)
        size = gui.window.size / gui.scale
        bbox[0:2] = np.dot(gui.center, gui.axes[:, :2]) - size / 2
        bbox[2:] = bbox[:2] + size
        extra['rotation'] = gui.axes
        extra['show_unit_cell'] = gui.window['toggle-show-unit-cell']
        extra['bbox'] = bbox
        colors = gui.get_colors(rgb=True)
        extra['colors'] = [
            rgb for rgb, visible in zip(colors, gui.images.visible) if visible
        ]
        remove_hidden = True

    images = [
        gui.images.get_atoms(i, remove_hidden=remove_hidden)
        for i in range(*index.indices(len(gui.images)))
    ]

    if len(images) > 1 and io.single:
        # We want to write multiple images, but the file format does not
        # support it.  The solution is to write multiple files, inserting
        # a number in the file name before the suffix.
        j = filename.rfind('.')
        filename = filename[:j] + '{0:05d}' + filename[j:]
        for i, atoms in enumerate(images):
            write(filename.format(i), atoms, **extra)
    else:
        try:
            write(filename, images, **extra)
        except Exception as err:
            from ase.gui.ui import showerror
            showerror(_('Error'), err)
            raise
예제 #7
0
def check_struct_dir(path, verbose=True):
    """
    Checks if the directory is a valid directory with structures inside. 
    Otherwise, an error will be raised. A valid directory is defined as a 
    directory that already exists and either:
        - Has at least one structure file with a valid file extension 
        - Has at least one structure that can be read with ASE.io.read
    Returns True if either of these conditions are met. Returns False otherwise.
    
    
    Arguments
    ---------
    path: str
        Path to the directory to check. 
        
    Returns
    -------
    bool
        
    """
    if not os.path.exists(path):
        raise Exception("Directory {} does not exist.".format(path))

    ## Create file iterator because we may not wish to generate the entire
    ## file list
    file_iter = os.scandir(path)

    for file_name in file_iter:
        file_ext = check_ext(file_name, verbose=verbose)

        ## Directory has at least one valid structure file.
        if file_ext in pymove_ext:
            return True

    ## Restart iterator
    file_iter = os.scandir(path)

    ## Now check if ASE can guess file format
    for file_name in file_iter:
        file_path = os.path.join(path, file_name)
        try:
            file_format = filetype(file_path)
        except:
            if verbose:
                print("ASE could not find filetype for {}".format(file_path))
            continue

        ## If we get this far, then format
        if verbose:
            print("ASE identified {} as having file format {}".format(
                file_path, file_format))
        return True

    return False
예제 #8
0
def save_dialog(gui, filename=None):
    dialog = ui.SaveFileDialog(gui.window.win, _('Save ...'))
    ui.Text(text).pack(dialog.top)
    filename = filename or dialog.go()
    if not filename:
        return

    filename, index = parse_filename(filename)
    if index is None:
        index = slice(gui.frame, gui.frame + 1)
    elif isinstance(index, basestring):
        index = string2index(index)
    elif isinstance(index, slice):
        pass
    else:
        if index < 0:
            index += len(gui.images)
        index = slice(index, index + 1)
    format = filetype(filename, read=False)
    io = get_ioformat(format)

    extra = {}
    remove_hidden = False
    if format in ['png', 'eps', 'pov']:
        bbox = np.empty(4)
        size = gui.window.size / gui.scale
        bbox[0:2] = np.dot(gui.center, gui.axes[:, :2]) - size / 2
        bbox[2:] = bbox[:2] + size
        extra['rotation'] = gui.axes
        extra['show_unit_cell'] = gui.window['toggle-show-unit-cell']
        extra['bbox'] = bbox
        colors = gui.get_colors(rgb=True)
        extra['colors'] = [rgb for rgb, visible
                           in zip(colors, gui.images.visible)
                           if visible]
        remove_hidden = True

    images = [gui.images.get_atoms(i, remove_hidden=remove_hidden)
              for i in range(*index.indices(len(gui.images)))]

    if len(images) > 1 and io.single:
        # We want to write multiple images, but the file format does not
        # support it.  The solution is to write multiple files, inserting
        # a number in the file name before the suffix.
        j = filename.rfind('.')
        filename = filename[:j] + '{0:05d}' + filename[j:]
        for i, atoms in enumerate(images):
            write(filename.format(i), atoms, **extra)
    else:
        write(filename, images, **extra)
예제 #9
0
    def run(args):
        if not args.filename:
            print_info()
            if args.formats:
                print()
                print_formats()
            if args.calculators:
                print()
                from ase.calculators.autodetect import (detect_calculators,
                                                        format_configs)
                configs = detect_calculators()
                print('Calculators:')
                for message in format_configs(configs):
                    print('  {}'.format(message))
                print()
                print('Available: {}'.format(','.join(sorted(configs))))
            return

        n = max(len(filename) for filename in args.filename) + 2
        nfiles_not_found = 0
        for filename in args.filename:
            try:
                format = filetype(filename)
            except FileNotFoundError:
                format = '?'
                description = 'No such file'
                nfiles_not_found += 1
            except UnknownFileTypeError:
                format = '?'
                description = '?'
            else:
                if format in ioformats:
                    description = ioformats[format].description
                else:
                    description = '?'

            print('{:{}}{} ({})'.format(filename + ':', n, description,
                                        format))
            if args.verbose:
                if format == 'traj':
                    print_ulm_info(filename)
                elif format == 'bundletrajectory':
                    print_bundletrajectory_info(filename)

        raise SystemExit(nfiles_not_found)
예제 #10
0
파일: info.py 프로젝트: uu1477/MyAse
def main():
    p = OptionParser(usage='%prog file.traj [file2.traj ...]',
                     description=description)

    opts, args = p.parse_args()

    if len(args) == 0:
        p.error('Incorrect number of arguments')

    for f in args:
        ft = filetype(f)
        print("File type of '{0}' appears to be of type '{1}'".format(f, ft))
        if ft == 'traj':
            print_aff_info(f)
        elif ft == 'trj':
            print_trajectory_info(f)
        elif ft == 'bundle':
            print_bundletrajectory_info(f)
        else:
            p.error('%s is of type %s; cannot print info about this type of file' % f)
예제 #11
0
파일: info.py 프로젝트: rosswhitfield/ase
def main():
    p = OptionParser(usage='%prog file.traj [file2.traj ...]',
                     description=description)

    opts, args = p.parse_args()

    if len(args) == 0:
        p.error('Incorrect number of arguments')

    for f in args:
        ft = filetype(f)
        print("File type of '{0}' appears to be of type '{1}'".format(f, ft))
        if ft == 'traj':
            print_ulm_info(f)
        elif ft == 'trj':
            print_trajectory_info(f)
        elif ft == 'bundletrajectory':
            print_bundletrajectory_info(f)
        else:
            p.error(
                '%s is of type %s; cannot print info about this type of file' %
                (f, ft))
예제 #12
0
def check_file_type(file_path, verbose=True):
    """
    Returns file type if one is identified by either pymove or ASE.
    
    Returns
    -------
    str:
        Returns either an empty string if no file format was found or the 
        correctly identified file format for the given file path.
    
    """
    if not os.path.isfile(file_path):
        if verbose:
            print("{} is not a file".format(file_path))
        return ""

    ext = check_ext(file_path)

    if len(ext) == 0:
        try:
            file_format = filetype(file_path)
        except:
            if verbose:
                print("ASE could not find filetype for {}".format(file_path))
            return ""

    if ext not in pymove_ext:
        if verbose:
            print(
                "File extension \".{}\" was not recognized by pymove.".format(
                    ext))
        return ""
    else:
        file_format = extension2format[ext]

    return file_format
예제 #13
0
        '=================================================================================================='
        .center(120))
    print('')
    args = argparse()

    ## args
    alist_files = args.alist_files

    ## Main
    from ase.io import read, write
    from ase.io.formats import filetype
    for i in range(len(alist_files)):
        alist = read(alist_files[i], ':')
        new_alist = []
        if args.lower_tri:
            for atoms in alist:
                atoms.set_cell(to_lower_triangular_cell(atoms.get_cell()),
                               scale_atoms=True)
                new_alist.append(atoms)
            write('lower-tri_{}'.format(alist_files[i]),
                  new_alist,
                  format=filetype(alist_files[i]))
        else:
            for atoms in alist:
                atoms.set_cell(to_upper_triangular_cell(atoms.get_cell()),
                               scale_atoms=True)
                new_alist.append(atoms)
            write('upper-tri_{}'.format(alist_files[i]),
                  new_alist,
                  format=filetype(alist_files[i]))
예제 #14
0
파일: save.py 프로젝트: uu1477/MyAse
def save_dialog(gui):
    dialog = gtk.FileChooserDialog(_('Save ...'), None,
                                   gtk.FILE_CHOOSER_ACTION_SAVE,
                                   (gtk.STOCK_SAVE, gtk.RESPONSE_OK,
                                    gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))
    dialog.set_current_name('')
    dialog.set_current_folder(os.getcwd())
    text = _('Append name with "@n" in order to write image number "n" '
             'instead of the current image.\n'
             'Append "@start:stop" or "@start:stop:step" if you want to write '
             'a range of images.\n'
             'You can leave out "start" and "stop" so that "name@:" will '
             'give you all images.\n'
             'Negative numbers count from the last image '
             '("name@-1": last image, "name@-2:": last two).')
    dialog.set_extra_widget(gtk.Label(text))
    response = dialog.run()
    if response == gtk.RESPONSE_OK:
        filename = dialog.get_filename()
        dialog.destroy()
    else:
        dialog.destroy()
        return

    filename, index = parse_filename(filename)
    if index is None:
        index = slice(gui.frame, gui.frame + 1)
    if isinstance(index, str):
        index = string2index(index)
    format = filetype(filename, read=False)
    io = get_ioformat(format)

    extra = {}
    remove_hidden = False
    if format in ['png', 'eps', 'pov']:
        bbox = np.empty(4)
        size = np.array([gui.width, gui.height]) / gui.scale
        bbox[0:2] = np.dot(gui.center, gui.axes[:, :2]) - size / 2
        bbox[2:] = bbox[:2] + size
        extra['rotation'] = gui.axes
        extra['show_unit_cell'] = gui.ui.get_widget(
            '/MenuBar/ViewMenu/ShowUnitCell').get_active()
        extra['bbox'] = bbox
        extra['colors'] = gui.get_colors(rgb=True)[gui.images.visible]
        remove_hidden = True

    images = [
        gui.images.get_atoms(i, remove_hidden=remove_hidden)
        for i in range(*index.indices(gui.images.nimages))
    ]

    if len(images) > 1 and io.single:
        # We want to write multiple images, but the file format does not
        # support it.  The solution is to write multiple files, inserting
        # a number in the file name before the suffix.
        j = filename.rfind('.')
        filename = filename[:j] + '{0:05d}' + filename[j:]
        for i, atoms in enumerate(images):
            write(filename.format(i), atoms, **extra)
    else:
        write(filename, images, **extra)