Example #1
0
File: cif.py Project: stur86/muesr
def load_cif(sample, filename, reset_muon=True, reset_sym=True):
    """

    Loads the structural information from a Cif file.
    
    
    :param muesr.core.sample.Sample sample: the sample object.
    :param str filename:   the cif file path (path + filename).
    :param bool reset_muon: if true the muon positions is reinitialized.
    :param bool reset_sym:  if true the symmetry is reinitialized. ALWAYS TRUE
    :returns: True if succesfull, false otherwise
    :rtype: bool
    """

    filename = str(filename)
    
    f = open(os.path.expanduser(filename),'r')
    
        #nprint ("Problems with file name...file not found!", 'warn')
        #return False
    
    #print(read_cif(f,0))
    atoms, sym = read_cif(f,0) # selectd index 0
    f.close()
    if atoms:
        sample._reset(cell=True,sym=True,magdefs=True,muon=reset_muon)
        sample.cell = atoms
        sample.sym = sym
        return True
    else:
        nprint ("Atoms not loaded!", 'warn')
        return False
Example #2
0
def muon_set_frac(sample, arg = None):
    """
    Set muon position in lattice coordinates.
    
    
    returns: None
    """
    if sample._check_lattice():
        
        try:
            if arg is None:
                pos=ninput('Muon position (frac coord): ', parse_vector)
            else:
                if isinstance(arg, np.ndarray) and ( arg.shape == (3,)):
                    pos = arg
                else:
                    pos = parse_vector(arg,3)
                    
        except EOFError:
            nprint("Ok.")
            return False
        except TypeError:
            nprint("Cannot parse position.",'warn')
            return False
            
        if (not isinstance(arg, np.ndarray)):
            pos = np.array(pos)
        
        sample.add_muon(pos)
        return True
    else:
        #nprintmsg('NS')
        return False
Example #3
0
def ninput_mt(message, parser = None, emessage = 'Parser could not parse your input or invalid input.'):
    """
    Nice input multiple trials function
    """    

    
    while True:
        try:
            ui = ninput(message)
            if parser:
                ui = parser(ui)
            return ui
        except ValueError:  # tries again if parser fails
            nprint(emessage,'warn')
Example #4
0
def ninput_mt(message,
              parser=None,
              emessage='Parser could not parse your input or invalid input.'):
    """
    Nice input multiple trials function
    """

    while True:
        try:
            ui = ninput(message)
            if parser:
                ui = parser(ui)
            return ui
        except ValueError:  # tries again if parser fails
            nprint(emessage, 'warn')
Example #5
0
def ninput(message,parser = None):
    """
    Nice input function
    """
    try:
        choice = ""
        if sys.version_info >= (3,0):
            choice = input('\t ' + message )
        else:
            choice = raw_input('\t ' + message )
        #readline.remove_history_item(readline.get_current_history_length()-1)
        if parser:
            choice = parser(choice)
        return choice
    except KeyboardInterrupt:
        nprint ("Use crtl+D to stop input!\n",'warn')
        pass
Example #6
0
def ninput(message, parser=None):
    """
    Nice input function
    """
    try:
        choice = ""
        if sys.version_info >= (3, 0):
            choice = input('\t ' + message)
        else:
            choice = raw_input('\t ' + message)
        #readline.remove_history_item(readline.get_current_history_length()-1)
        if parser:
            choice = parser(choice)
        return choice
    except KeyboardInterrupt:
        nprint("Use crtl+D to stop input!\n", 'warn')
        pass
Example #7
0
File: ms.py Project: bonfus/muesr
def mago_set_k(sample, kvalue=None, mm=None):
    
    """
    Set propagation with respect to the conventional reciprocal cell
    kavalue : propagation vector (either string or tuple or list), if None, input is prompetd
    mm      : Magnetic Model to be used. If None the current magnetic model is used
    returns: None
    """
    
    
    
    if mm is None:
        smm = sample.mm
    else:
        smm = mm
        
        
    
    if sample._check_lattice():
        if not kvalue is None:
            if isinstance(kvalue, np.ndarray) and ( kvalue.shape == (3,)):
                smm.k = kvalue
                return True
            else:
                raise TypeError("Invalid type for kvalue. Must be 3D vector defined as numpy array.")
        else:
            try:
                if kvalue is None:
                    kval=ninput('Propagation vector (w.r.t. conv. rec. cell): ', parse_vector)
                else:
                    kval = parse_vector(kvalue,3)

            except EOFError:
                nprint("Ok.")
                return False
            except TypeError:
                nprint("Cannot parse position.",'warn')
                return
            smm.k=np.array(kval,dtype=np.float)
            return True
Example #8
0
def mago_set_k(sample, kvalue=None, mm=None):
    """
    Set propagation with respect to the conventional reciprocal cell
    kavalue : propagation vector (either string or tuple or list), if None, input is prompetd
    mm      : Magnetic Model to be used. If None the current magnetic model is used
    returns: None
    """

    if mm is None:
        smm = sample.mm
    else:
        smm = mm

    if sample._check_lattice():
        if not kvalue is None:
            if isinstance(kvalue, np.ndarray) and (kvalue.shape == (3, )):
                smm.k = kvalue
                return True
            else:
                raise TypeError(
                    "Invalid type for kvalue. Must be 3D vector defined as numpy array."
                )
        else:
            try:
                if kvalue is None:
                    kval = ninput(
                        'Propagation vector (w.r.t. conv. rec. cell): ',
                        parse_vector)
                else:
                    kval = parse_vector(kvalue, 3)

            except EOFError:
                nprint("Ok.")
                return False
            except TypeError:
                nprint("Cannot parse position.", 'warn')
                return
            smm.k = np.array(kval, dtype=np.float)
            return True
Example #9
0
import sys
from muesr.core.nprint import nprint

try:
    import readline
except:
    nprint ("readline not present, using standard python input functions.\n",'warn')


def ninput(message,parser = None):
    """
    Nice input function
    """
    try:
        choice = ""
        if sys.version_info >= (3,0):
            choice = input('\t ' + message )
        else:
            choice = raw_input('\t ' + message )
        #readline.remove_history_item(readline.get_current_history_length()-1)
        if parser:
            choice = parser(choice)
        return choice
    except KeyboardInterrupt:
        nprint ("Use crtl+D to stop input!\n",'warn')
        pass

def ninput_mt(message, parser = None, emessage = 'Parser could not parse your input or invalid input.'):
    """
    Nice input multiple trials function
    """    
Example #10
0
def read_xsf(fileobj, index=-1, read_data=False):
    if not hasattr(fileobj, 'read'):
        fileobj = open(fileobj, 'r')

    readline = fileobj.readline
    while True:
        line = readline().strip()
        if line != '':
            if line[0] != '#':
                break

    if 'INFO' in line:
        while True:
            line = readline().strip()
            if line != '':
                if line[0] != '#':
                    if 'END_INFO' in line:
                        break

        line = readline().strip()

    if 'ANIMSTEPS' in line:
        nimages = int(line.split()[1])
        line = readline().strip()
    else:
        nimages = 1

    if 'CRYSTAL' in line:
        pbc = True
    elif 'SLAB' in line:
        pbc = (True, True, False)
    elif 'POLYMER' in line:
        pbc = (True, False, False)
    elif 'DIM-GROUP' in line:
        line = readline().strip()
        if int(line.split(' ')[0]) == 3:
            pbc = True
        else:
            nprint("WARNING: I'm missing something in your XCrysDen file.",
                   'warn')
            pbc = False
    else:
        nprint("WARNING: I'm missing something in your XCrysDen file.", 'warn')
        pbc = False

    images = []
    for n in range(nimages):
        cell = None
        if pbc:
            while True:
                line = readline().strip()
                if line != '':
                    if line[0] != '#':
                        break
            assert 'PRIMVEC' in line
            cell = []
            for i in range(3):
                cell.append([float(x) for x in readline().split()])
        else:
            nprint(
                "This program cannot work without PBC...create a fake cell.",
                'warn')
            return None

        while not 'PRIMCOORD' in readline().strip():
            continue
        natoms = int(readline().split()[0])
        symbols = []
        numbers = []
        positions = []
        for a in range(natoms):
            line = readline().split()
            try:
                numbers.append(int(line[0]))
            except:
                atm_name = re.sub("\d", "", str(line[0]))
                symbols.append(atm_name)
            positions.append([float(x) for x in line[1:]])

        positions = np.array(positions)
        if len(positions[0]) == 3:
            forces = None
        else:
            positions = positions[:, :3]
            forces = positions[:, 3:]
        if len(symbols) != 0:
            image = Atoms(symbols, positions, cell=cell, pbc=pbc)
        elif len(numbers) != 0:
            image = Atoms(numbers=numbers,
                          positions=positions,
                          cell=cell,
                          pbc=pbc)

        images.append(image)

    if read_data:
        data = read_xsf_data(fileobj)
        #line = readline()
        #assert 'BEGIN_BLOCK_DATAGRID_3D' in line
        #line = readline()
        #assert 'BEGIN_DATAGRID_3D' in line
        #
        #shape = [int(x) for x in readline().split()]
        #start = [float(x) for x in readline().split()]
        #
        #for i in range(3):
        #    readline()
        #
        #n_data = shape[0]*shape[1]*shape[2]
        #data = np.array([float(readline())
        #                 for s in range(n_data)]).reshape(shape[::-1])
        #data = np.swapaxes(data, 0, 2)
        #
        fileobj.close()
        return images[index], data

    fileobj.close()
    return images[index]
Example #11
0
import warnings

from muesr.core.spg import spacegroup_from_data
from muesr.core.parsers import *
#from muesr.core.symmetry import Symmetry
from muesr.core.nprint  import nprint, nprintmsg

have_spg = True

try:
    import spglib as spg
except ImportError:
    try:
        from pyspglib import spglib as spg
    except ImportError:
        nprint("Spg Library not loaded", "warn")
        have_spg = False



        
def symsearch(sample, precision=1e-4):
    """
    Identifies symmetry operations of the unit cell using spglib and 
    update the sample definition.
    
    :param sample: A sample object.
    :param float precision: atoms are assumed equivalent if distances are 
                            smaller than precision. In Angstrom.
    :returns: True if successful, False otherwise.
    :rtype: bool
Example #12
0
File: ms.py Project: bonfus/muesr
def mago_set_FC(sample, fcs = None, atoms_types = None, mm=None, inputConvention='b-c'):
    """
    Defines fourier components for the unit cell.
    
    """


    sample._check_lattice()
    
    
    if mm is None:
        smm = sample.mm
    else:
        smm = mm
    

    
    inputConvEnum = -1
        
    if inputConvention.lower() in ['bohr-cartesian', 'b-c']:
        nprint('Fourier components in Bohr magnetons and Cartesian coordinates.')
        inputConvEnum = 0
        
    elif inputConvention.lower() in ['bohr/angstrom-lattice', 'b/a-l']:
        nprint('Fourier components in Bohr magnetons/Angstrom and lattice coordinates.')
        inputConvEnum = 1
        
    elif inputConvention.lower() in ['bohr-lattice','b-l']:
        nprint('Fourier components in Bohr magnetons and lattice coordinates.')
        inputConvEnum = 2
        
    else:
        nprint('Invalid Fourier Description method: ' + inputConvention.lower() ,'error.')
        return False
    


    
    if not fcs is None:
        smm.fc_set(fcs, inputConvEnum)
        return True
            


    unit_cell = sample._cell    
    lattice = unit_cell.get_cell()
    
    
    if atoms_types is None:
        atoms_types=ninput('Which atom? (enter for all): ').split()
    
    if atoms_types == []:
        set_this_fc = lambda x: True
    else:
        atoms_types = [x.lower() for x in atoms_types] #lowercase
        set_this_fc = lambda x: x.lower() in atoms_types
        # Print where they are
        print_cell(unit_cell,set_this_fc)
    
    

    
    fcs = np.zeros([unit_cell.get_number_of_atoms(),3],dtype=np.complex)
    
    gotEOS = False
    for i, atom in enumerate(unit_cell):                
        try:
            if set_this_fc(atom[0]): # check if we should set this fc
                FCin = ninput_mt("FC for atom %i %s (3 real, [3 imag]): " % (i+1,atom[0]), parse_complex_vector)
                fcs[i]=[FCin[j]+1.j*FCin[j+3] for j in range(3)]
                    
            else:
                # 0 is always 0, no matter the input format! ;)
                fcs[i]=([0.+0.j,0.+0.j,0.+0.j])
                
        except EOFError:
            gotEOS = True
            break

    if gotEOS:
        nprint('Nothing set')
        return False
    else:
        smm.fc_set(fcs, inputConvEnum)
        return True
Example #13
0
import warnings

from muesr.core.spg import spacegroup_from_data
from muesr.core.parsers import *
#from muesr.core.symmetry import Symmetry
from muesr.core.nprint import nprint, nprintmsg

have_spg = True

try:
    import spglib as spg
except ImportError:
    try:
        from pyspglib import spglib as spg
    except ImportError:
        nprint("Spg Library not loaded", "warn")
        have_spg = False


def symsearch(sample, precision=1e-4):
    """
    Identifies symmetry operations of the unit cell using spglib and 
    update the sample definition.
    
    :param sample: A sample object.
    :param float precision: atoms are assumed equivalent if distances are 
                            smaller than precision. In Angstrom.
    :returns: True if successful, False otherwise.
    :rtype: bool
    """
Example #14
0
def read_xsf(fileobj, index=-1, read_data=False):
    if not hasattr(fileobj, 'read'):
        fileobj = open(fileobj,'r')

    readline = fileobj.readline
    while True:
        line = readline().strip()
        if line != '':
            if line[0] != '#':
                break
    
    if 'INFO' in line:
        while True:
            line = readline().strip()
            if line != '':
                if line[0] != '#':
                    if 'END_INFO' in line:
                        break    

        line = readline().strip()

    if 'ANIMSTEPS' in line:
        nimages = int(line.split()[1])
        line = readline().strip()
    else:
        nimages = 1

    if 'CRYSTAL' in line:
        pbc = True
    elif 'SLAB' in line:
        pbc = (True, True, False)
    elif 'POLYMER' in line:
        pbc = (True, False, False)
    elif 'DIM-GROUP' in line:
        line = readline().strip()
        if int(line.split(' ')[0]) == 3:
            pbc = True
        else:
            nprint ("WARNING: I'm missing something in your XCrysDen file.",'warn')
            pbc = False            
    else:
        nprint ("WARNING: I'm missing something in your XCrysDen file.",'warn')
        pbc = False

    images = []
    for n in range(nimages):
        cell = None
        if pbc:
            while True:
                line = readline().strip()
                if line != '':
                    if line[0] != '#':
                        break
            assert 'PRIMVEC' in line
            cell = []
            for i in range(3):
                cell.append([float(x) for x in readline().split()])
        else:
            nprint ("This program cannot work without PBC...create a fake cell.",'warn')
            return None

        while not 'PRIMCOORD' in readline().strip():
            continue
        natoms = int(readline().split()[0])
        symbols = []
        numbers = []
        positions = []
        for a in range(natoms):
            line = readline().split()
            try:
                numbers.append(int(line[0]))
            except:
                atm_name = re.sub("\d","",str(line[0]))
                symbols.append(atm_name)
            positions.append([float(x) for x in line[1:]])

        positions = np.array(positions)
        if len(positions[0]) == 3:
            forces = None
        else:
            positions = positions[:, :3]
            forces = positions[:, 3:]
        if len(symbols) != 0:
            image = Atoms(symbols, positions, cell=cell, pbc=pbc)
        elif len(numbers) != 0:
            image = Atoms(numbers = numbers, positions = positions, cell=cell, pbc=pbc)

        images.append(image)

    if read_data:
        data = read_xsf_data(fileobj)
        #line = readline()
        #assert 'BEGIN_BLOCK_DATAGRID_3D' in line
        #line = readline()
        #assert 'BEGIN_DATAGRID_3D' in line
        #
        #shape = [int(x) for x in readline().split()]
        #start = [float(x) for x in readline().split()]
        #
        #for i in range(3):
        #    readline()
        #    
        #n_data = shape[0]*shape[1]*shape[2]
        #data = np.array([float(readline())
        #                 for s in range(n_data)]).reshape(shape[::-1])
        #data = np.swapaxes(data, 0, 2)
        #
        fileobj.close()
        return images[index], data
        
    fileobj.close()
    return images[index]
Example #15
0
def read_xsf_data(f):
    
    found_data = False
    
    def search_data_block(f):
        while f.readline().find("BEGIN_BLOCK_DATAGRID_3D") == -1:
            continue
        return True
        
    while search_data_block(f):
        nprint ("Found data block:")
        nprint("Desc" + f.readline())
        nprint("type" + f.readline())
        if ninput_mt("Use this? ", mybool):
            found_data = True
            break 
        
    if not found_data:
        nprint ("No data found, exiting...", 'warn')
        return None
    
    grid = map(int, f.readline().split())
    
    # Lattice vectors along lines
    orig = np.array(map(float, f.readline().split()), dtype=object)
    v1 = np.array(map(float, f.readline().split()), dtype=object)
    v2 = np.array(map(float, f.readline().split()), dtype=object)
    v3 = np.array(map(float, f.readline().split()), dtype=object)
    
    v1n = v1/grid[0]
    v2n = v2/grid[1]
    v3n = v3/grid[2]
    
    sdata = np.zeros(np.prod(grid))
    
    data_buffer = []
    
    nprint("Grid has " + str(np.prod(grid)) + " points.")
    
    #grid_steps = [int(x/10) for x in grid]
    #nprint("Setting steps throught grid to %i %i %i." % tuple(grid_steps) )

    
    nprint ("Parsing data...")
    
    for k in range(0, grid[2]):
        for j in range(0,grid[1]):
            for i in range(0, grid[0]):
                if data_buffer == []:
                    data_buffer = [float(x) for x in f.readline().split()] # a random number of data may be on the line

                sdata[i+grid[0]*j+grid[1]*grid[0]*k] = data_buffer[0] 
                data_buffer.pop(0) #empty the buffer
    return [sdata, [grid, orig, [v1n,v2n,v3n]]]
Example #16
0
def mago_set_FC(sample,
                fcs=None,
                atoms_types=None,
                mm=None,
                inputConvention='b-c'):
    """
    Defines fourier components for the unit cell.
    
    """

    sample._check_lattice()

    if mm is None:
        smm = sample.mm
    else:
        smm = mm

    inputConvEnum = -1

    if inputConvention.lower() in ['bohr-cartesian', 'b-c']:
        nprint(
            'Fourier components in Bohr magnetons and Cartesian coordinates.')
        inputConvEnum = 0

    elif inputConvention.lower() in ['bohr/angstrom-lattice', 'b/a-l']:
        nprint(
            'Fourier components in Bohr magnetons/Angstrom and lattice coordinates.'
        )
        inputConvEnum = 1

    elif inputConvention.lower() in ['bohr-lattice', 'b-l']:
        nprint('Fourier components in Bohr magnetons and lattice coordinates.')
        inputConvEnum = 2

    else:
        nprint(
            'Invalid Fourier Description method: ' + inputConvention.lower(),
            'error.')
        return False

    if not fcs is None:
        smm.fc_set(fcs, inputConvEnum)
        return True

    unit_cell = sample._cell
    lattice = unit_cell.get_cell()

    if atoms_types is None:
        atoms_types = ninput('Which atom? (enter for all): ').split()

    if atoms_types == []:
        set_this_fc = lambda x: True
    else:
        atoms_types = [x.lower() for x in atoms_types]  #lowercase
        set_this_fc = lambda x: x.lower() in atoms_types
        # Print where they are
        print_cell(unit_cell, set_this_fc)

    fcs = np.zeros([unit_cell.get_number_of_atoms(), 3], dtype=np.complex)

    gotEOS = False
    for i, atom in enumerate(unit_cell):
        try:
            if set_this_fc(atom[0]):  # check if we should set this fc
                FCin = ninput_mt(
                    "FC for atom %i %s (3 real, [3 imag]): " %
                    (i + 1, atom[0]), parse_complex_vector)
                fcs[i] = [FCin[j] + 1.j * FCin[j + 3] for j in range(3)]

            else:
                # 0 is always 0, no matter the input format! ;)
                fcs[i] = ([0. + 0.j, 0. + 0.j, 0. + 0.j])

        except EOFError:
            gotEOS = True
            break

    if gotEOS:
        nprint('Nothing set')
        return False
    else:
        smm.fc_set(fcs, inputConvEnum)
        return True
Example #17
0
import sys
from muesr.core.nprint import nprint

try:
    import readline
except:
    nprint("readline not present, using standard python input functions.\n",
           'warn')


def ninput(message, parser=None):
    """
    Nice input function
    """
    try:
        choice = ""
        if sys.version_info >= (3, 0):
            choice = input('\t ' + message)
        else:
            choice = raw_input('\t ' + message)
        #readline.remove_history_item(readline.get_current_history_length()-1)
        if parser:
            choice = parser(choice)
        return choice
    except KeyboardInterrupt:
        nprint("Use crtl+D to stop input!\n", 'warn')
        pass


def ninput_mt(message,
              parser=None,
Example #18
0
def read_xsf_data(f):

    found_data = False

    def search_data_block(f):
        while f.readline().find("BEGIN_BLOCK_DATAGRID_3D") == -1:
            continue
        return True

    while search_data_block(f):
        nprint("Found data block:")
        nprint("Desc" + f.readline())
        nprint("type" + f.readline())
        if ninput_mt("Use this? ", mybool):
            found_data = True
            break

    if not found_data:
        nprint("No data found, exiting...", 'warn')
        return None

    grid = map(int, f.readline().split())

    # Lattice vectors along lines
    orig = np.array(map(float, f.readline().split()), dtype=object)
    v1 = np.array(map(float, f.readline().split()), dtype=object)
    v2 = np.array(map(float, f.readline().split()), dtype=object)
    v3 = np.array(map(float, f.readline().split()), dtype=object)

    v1n = v1 / grid[0]
    v2n = v2 / grid[1]
    v3n = v3 / grid[2]

    sdata = np.zeros(np.prod(grid))

    data_buffer = []

    nprint("Grid has " + str(np.prod(grid)) + " points.")

    #grid_steps = [int(x/10) for x in grid]
    #nprint("Setting steps throught grid to %i %i %i." % tuple(grid_steps) )

    nprint("Parsing data...")

    for k in range(0, grid[2]):
        for j in range(0, grid[1]):
            for i in range(0, grid[0]):
                if data_buffer == []:
                    data_buffer = [
                        float(x) for x in f.readline().split()
                    ]  # a random number of data may be on the line

                sdata[i + grid[0] * j + grid[1] * grid[0] * k] = data_buffer[0]
                data_buffer.pop(0)  #empty the buffer
    return [sdata, [grid, orig, [v1n, v2n, v3n]]]