Beispiel #1
0
def main(commands, args):
    cout("Atomistic module")

    if len(commands) == 0:
        commands = ['help']
    
############## HELP ####################           
    if commands[0] == "help":
        cout(atomistic_help_text)
    elif len(commands)==2 and commands[0] == "visualize" and commands[1] == "help":
        cout(visualize_help_text)

############## VISUALIZE ##############

    elif commands[0] == "visualize":
        import httk.atomistic.vis
        from httk.atomistic import Structure
        for command in commands[1:]:
            struct = httk.load(command)
            struct.vis.show()
        
#######################################
    else:
        cerr("Unknown command in atomistic module:", commands[0])
        exit(1)
Beispiel #2
0
    def test_read_all_spacegroups(self):
        compdir = 'structreading_data'
        topdir = '../Tutorial/tutorial_data'
        reldir = 'all_spacegroups/cifs/'

        def print_num_matrix(l):
            outstr = ""
            for i in l:
                if isinstance(i, list):
                    outstr += print_num_matrix(i)
                    outstr += "\n"
                else:
                    outstr += str(i) + "\n"
            return outstr

        structdir = os.path.join(topdir, reldir)

        for subdir, dirs, files in os.walk(structdir):
            for f in files:
                if f.endswith('.cif'):
                    print("TESTING:", f)

                    reldir = os.path.relpath(subdir, topdir)
                    ff = os.path.join(subdir, f)
                    relf = os.path.join(reldir, f + '.check')
                    struct = httk.load(ff)
                    #if not os.path.exists(reldir):
                    #    os.makedirs(reldir)
                    if struct.assignments.ratios != [1] * len(
                            struct.assignments.ratios):
                        print("Disordered structure, skipping")
                        continue

                    if f in ['70.cif', '26.cif', '190.cif']:
                        print(
                            "Skipping structure incorrectly read by cif2cell")
                        continue
                    #if f == '184.cif' or f == '119.cif' or f == '217.cif' or f == '200.cif':
                    #    # For some reason cif2cell has a different orientation here
                    #    continue

                    of = open('structreading.tmp', "w")
                    #of.write(" ".join(struct.uc_formula_symbols)+"\n")
                    #of.write(" ".join([str(x) for x in struct.pc.uc_counts])+"\n")
                    #of.write(print_num_matrix(struct.pc.uc_cell.basis.to_floats()))
                    #of.write(print_num_matrix(struct.pc.uc_reduced_coords.to_floats()))
                    of.write(" ".join(struct.uc_formula_symbols) + "\n\n\n")
                    of.write(" ".join([str(x)
                                       for x in struct.uc_counts]) + "\n\n\n")
                    of.write(print_num_matrix(
                        struct.uc_cell.basis.to_floats()))
                    of.write("\n")
                    of.write(
                        print_num_matrix(struct.uc_reduced_coords.to_floats()))

                    of.close()

                    compf = os.path.join(compdir, relf)

                    f = open(compf)
                    s1 = f.read()
                    f.close()

                    f = open('structreading.tmp')
                    s2 = f.read()
                    f.close()

                    self.assert_numeric_data(s1, s2)
Beispiel #3
0
def main():
    parser = argparse.ArgumentParser(description="Creates the tutorial sqlite database file")
    parser.add_argument('-debug', action='store_true')
    parser.add_argument('file', metavar='run', nargs='*', help='filenames or directories to import')
    args = parser.parse_args()

    debug = args.debug
    #debug = True
    process_with_isotropy = True
    process_with_tidy = True

    if process_with_isotropy:
        import httk.external.isotropy_ext

    try:
        os.remove('tutorial.sqlite')
    except OSError as e:
        if e.errno != errno.ENOENT:
            raise

    backend = httk.db.backend.Sqlite('tutorial.sqlite')
    store = httk.db.store.SqlStore(backend)

    # This is good practice if you are going to add several things to the database, nothing is written to the database until 'commit' is called.
    # (Special case: if the database is completely newly created, some database engines commit data)
    store.delay_commit()

    codeobj = httk.Code.create("create_tutorial_database", '1.0', refs=[httk.citation.httk_reference_main])
    store.save(codeobj)
    print("==== Name of this code:", codeobj.name)

    today = datetime.datetime.today().isoformat()
    print("==== Db import program started: "+today)

    if len(args.file) == 0:
        files = [os.path.join(httk.httk_root, 'Tutorial/tutorial_data')]
    else:
        files = args.file

    argcount = len(files)

    seen = {}
    for filek in range(argcount):
        f = files[filek]

        if not os.path.exists(f):
            print("File or dir "+f+" not found.")
            continue
        if os.path.isdir(f):
            filelist = []
            dirname = os.path.dirname(f)
            for root, dirs, files in os.walk(f):
                for file in files:
                    if file.endswith(".cif") or file.endswith(".vasp"):
                        filelist += [os.path.join(root, file)]
                # Make sure we always generate the same manifest
                        filelist = sorted(filelist)
        else:
            dirname = os.path.dirname(f)
            filelist = [f]

        for i in range(len(filelist)):
            filename = filelist[i]
            print("Filename:"+filename)
            # Uncomment for better control in how to load structures
            #if filename.endswith(".cif"):
            #    struct = httk.httkio.cif_to_struct(filename,backends=['cif2cell_reduce'])
            #elif filename.endswith(".vasp"):
            #    struct = httk.iface.vasp_if.poscar_to_structure(filename)
            struct = httk.load(filename).clean()
            print("The formula is:", struct.formula+" ("+struct.anonymous_formula+")")
            print("Volume", float(struct.uc_volume))
            print("Tags:", [str(struct.get_tag(x)) for x in struct.get_tags()])
            print("Refs:", [str(x) for x in struct.get_refs()])

            if process_with_isotropy:
                try:
                    newstruct = httk.external.isotropy_ext.struct_process_with_isotropy(struct).clean()
                    newstruct.add_tag("isotropy/findsym", "done")
                    struct = newstruct
                except Exception as e:
                    print("Isotropy failed with:"+str(e))
                    struct.add_tag("isotropy", "failed")
                    if debug:
                        raise

            if process_with_tidy:
                try:
                    newstruct = struct.tidy()
                    newstruct.add_tag("structure_tidy", "done")
                    struct = newstruct
                except Exception as e:
                    print("Structure tidy failed with:"+str(e))
                    struct.add_tag("structure_tidy", "failed")
                    if debug:
                        raise

            store.save(struct)
            compound = Compound.create(base_on_structure=struct)
            store.save(compound)

            cs = CompoundStructure.create(compound, struct)
            store.save(cs)
            store.commit()

    print("==== Committing changes to database.")
    store.commit()
    print("==== Commit complete.")
Beispiel #4
0
#!/usr/bin/env python
#
# Simplest possible httk program. Loads a structure and prints out some information on the console.
from __future__ import print_function

import httk

struct = httk.load("example.cif")

print("Formula:", struct.formula)

print("Primitive cell info:")
print("Volume:", float(struct.pc.uc_volume))
print("Assignments", struct.assignments.symbols)
print("Counts:", struct.pc.uc_counts)
print("Coords", struct.pc.uc_reduced_coords.to_floats())

print()

print("Conventional cell info:")
print("Volume:", float(struct.cc.uc_volume))
print("Assignments", struct.assignments.symbols)
print("Counts:", struct.cc.uc_counts)
print("Coords", struct.cc.uc_reduced_coords.to_floats())

httk.save(struct, 'test.vasp')
Beispiel #5
0
class TotalEnergyResult(httk.Result):
    @httk.httk_typed_init({
        'computation': httk.Computation,
        'structure': Structure,
        'total_energy': float
    })
    def __init__(self, computation, structure, total_energy):
        self.computation = computation
        self.structure = structure
        self.total_energy = total_energy


backend = httk.db.backend.Sqlite('example.sqlite')
store = httk.db.store.SqlStore(backend)

reader = httk.task.reader('./', 'Runs/', 'Normal VASP total energy run')

print(
    "Storing results (please note that first store call will take some time, since the database is created)"
)
for rundir, computation in reader:
    struct = httk.load(os.path.join(rundir, "CONTCAR"))
    print("Reading outcar:", struct.formula)
    outcar = httk.iface.vasp_if.read_outcar(
        os.path.join(rundir, "OUTCAR.cleaned.relax-final"))
    total_energy_result = TotalEnergyResult(computation, struct,
                                            float(outcar.final_energy))
    store.save(total_energy_result)

store.commit()
Beispiel #6
0
#!/usr/bin/env python

from __future__ import print_function
import httk, httk.db
from httk.atomistic import Structure

backend = httk.db.backend.Sqlite('example.sqlite')
store = httk.db.store.SqlStore(backend)
tablesalt = httk.load('../../Tutorial/Step7/NaCl.cif')
tablesalt.add_tag('common name', 'salt')
arsenic = httk.load('../../Tutorial/Step7/As.cif')
store.save(tablesalt)
store.save(arsenic)

# Search for anything with Na (cf. the search for a material system in tutorial step6, where all symbols must be in a set, 'add' vs. 'add_all'.)
search = store.searcher()
search_struct = search.variable(Structure)
search.add(search_struct.formula_symbols.is_in('Na'))

search.output(search_struct, 'structure')

for match, header in list(search):
    struct = match[0]
    print("Found structure", struct.formula,
          [str(struct.get_tags()[x]) for x in struct.get_tags()])
Beispiel #7
0
#!/usr/bin/env python

import httk, httk.db
from httk.atomistic import Structure


class StructureIsEdible(httk.HttkObject):
    @httk.httk_typed_init({'structure': Structure, 'is_edible': bool})
    def __init__(self, structure, is_edible):
        self.structure = structure
        self.is_edible = is_edible


backend = httk.db.backend.Sqlite('example.sqlite')
store = httk.db.store.SqlStore(backend)
tablesalt = httk.load('NaCl.cif')
arsenic = httk.load('As.cif')
edible = StructureIsEdible(tablesalt, True)
store.save(edible)
edible = StructureIsEdible(arsenic, False)
store.save(edible)