# FPLOIO examples

- Reading =.in files
- =.files to json
- Reading cif-files
- Write =.in with low level routines
- Write =.in with mid level routines
- Extract default basis into =.basdef
- User defined basis (in =.basdef)
- Extract =.basdef from output file
- Grep results

## Reading =.in files

This tutorial shows how to use `INParser` and `PObj` to read `=.in`-files.

The tutorial files are in `FPLO.../DOC/pyfplo/Examples/fploio/fploio/readinfile` where `FPLO...` stands for your version’s FPLO directory, e.g. `FPLO21.00-61`. Here are the files of this directory:

- readinfile.py
- `=.in`

`readinfile.py`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    #! /usr/bin/env python
    # ===================================================================
    # file:   bandplot.py
    # author: k.koepernik@ifw-dresden.de
    # date:   19 Apr 2017
    from __future__ import print_function
    import sys
    import pyfplo.fploio as fploio
    # ===================================================================
    #
    # ===================================================================
    def work():

        print( '\nThis example shows how to parse =.in files.\n')

        p=fploio.INParser()
        p.parseFile('=.in')
        d=p()

        print( 'sorts:',d('nsort').L)
        print( 'lattice constants:',d('lattice_constants').listD)
        print( 'or\nlattice constants:',d('lattice_constants').listS)
        print( '\nWyckoff positions')
        dw=d('wyckoff_positions')
        for i in range(dw.size()):
            dd=dw[i]
            print( dd('element').S,dd('tau').listS)

        print( '\nAlternative way of doing it')
        for i in range(dw.size()):
            dd=dw[i]
            print( dd('element').S,dd('tau')[0].S,dd('tau')[1].S,dd('tau')[2].S)

        print( '\nYet another way')
        for i in range(dw.size()):
            dd=dw[i]
            print( dd('element').S,dd('tau[0]').S,dd('tau[1]').S,dd('tau[2]').S)

        print( '\nsingle shot')
        print( d('wyckoff_positions[0].element').S,
            d('wyckoff_positions[0].tau').listS)

        print( '\noptions')
        do=d('options')
        for i in range(do.size()):
            print( do[i].S,)
            if ((i+1)%4)==0: print()
        print()
        print( '\nsetting CALC_PLASMON_FREQ and CALC_DOS')
        do['CALC_PLASMON_FREQ'].L=True
        do['CALC_DOS'].L=True
        print( '\nwhich now are',bool(do['CALC_PLASMON_FREQ'].L)
            ,'and',bool(do['CALC_DOS'].L))
        print( '\nhave another look at options')
        do=d('options')
        for i in range(do.size()):
            print( do[i].S,)
            if (i%4)==0: print()
        print()

        return

    # ===================================================================
    #
    # ===================================================================

    if __name__ == '__main__':

        work()

        sys.exit(0)

## =.files to json

This tutorial shows how to convert files with the `=.in` syntax into `json`-files. It demonstrates the usage of `PObj`.

The tutorial files are in `FPLO.../DOC/pyfplo/Examples/fploio/equaldot2json` where `FPLO...` stands for your version’s FPLO directory, e.g. `FPLO21.00-61`. Here are the files of this directory:

- equaldot2json.py
- `=.in`

`equaldot2json.py`

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    #! /usr/bin/env python
    # ===================================================================
    # file:   testscan.py
    # author: k.koepernik@ifw-dresden.de
    # date:   04 Okt 2018

    from __future__ import print_function
    import pyfplo.fploio as fploio
    import argparse
    import json

    version = 20181002

    parser = argparse.ArgumentParser(description='Translates `=.*` files \
                                     (e.g., `=.in`, `=.xef`, `=.dens`) into \
                                     a JSON file without calling pyfplo. \
                                     Works with Python 2, but the order \
                                     of entries is retained in Python 3, \
                                     only.', conflict_handler='resolve',
                                     epilog="Please report any bugs to \
                                     Oleg Janson <olegjanson@gmail.com>.")
    parser.add_argument('-i', '--input', default='=.in',
                        type=str,dest='input',
                        help='FPLO input file (default:%(default)s)')
    parser.add_argument('-o', '--output', type=argparse.FileType('w'),
                        default='-', help='JSON output file')
    parser.add_argument('-n', '--nice', dest='nice', action='store_true',
                        help='add indents (otherwise just a single line)')
    parser.set_defaults(nice=False)
    parser.add_argument('-v', '--version', action='version',\
                         help='print the version',\
                         version='%(prog)s version {:d}'.format(version))
    args = parser.parse_args()
    jsonprintoptions = ({}, {'indent':4})[args.nice]

    # ===================================================================
    #
    # ===================================================================
    def scanStruct(d,dictdata,ind=''):
        n=d.first()
        while True:
            if n.isScalar():
                if n.isInt():
                    dictdata[n.name()]=n.L
                elif n.isReal():
                    dictdata[n.name()]=n.D
                elif n.isLogical():
                    dictdata[n.name()]=bool(n.L)
                elif n.isFlag():
                    dictdata[n.name()]=bool(n.L)
                else:
                    dictdata[n.name()]=n.S
            elif n.isArray():
                dictdata[n.name()]=[]
                scanArray(n,dictdata[n.name()],n.sizes(),len(n.sizes()))
            elif n.isStruct():
                dictdata[n.name()]={}
                scanStruct(n,dictdata[n.name()],ind+'    ')
            elif n.isStructArray():
                dictdata[n.name()]=[]
                for i in range(n.size()):
                    dictdata[n.name()].append({})
                    scanStruct(n[i],dictdata[n.name()][-1],ind+'    ')

            if not n.hasNext(): break
            n=n.next()

        return
    # ===================================================================
    #
    # ===================================================================
    def scanArray(d,dictdata,sizes,dim,idx=[],ind=''):

        if dim==len(sizes):
            idx=[0]*dim
        for i in range(sizes[dim-1]):
            idx[dim-1]=i
            if dim==1:
                n=d[tuple(idx)]
                if n.isInt():
                    dictdata.append(n.L)
                elif n.isReal():
                    dictdata.append(n.D)
                elif n.isLogical():
                    dictdata.append(bool(n.L))
                elif n.isFlag():
                    dictdata.append({n.S[0:-3]:bool(n.L)})
                else:
                    dictdata.append(n.S)
            else:
                dictdata.append([])
                scanArray(d,dictdata[-1],sizes,dim-1,idx,ind='')

        return

    # ===================================================================
    #
    # ===================================================================

    if __name__ == '__main__':

        p=fploio.INParser()
        p.parseFile(args.input)

        dictdata={}
        scanStruct(p(),dictdata)

        with args.output as jsonfile:
            json.dump(dictdata, jsonfile, **jsonprintoptions)

## Reading cif-files

This tutorial demonstrates how to read `cif`-files. See `structureFromCIFFile`. The tutorial files are in `FPLO.../DOC/pyfplo/Examples/fploio/cif` where `FPLO...` stands for your version’s FPLO directory, e.g. `FPLO21.00-61`. Here are the files of this directory:

- README
- fromcif.py
- `RuW.cif`

`README`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    This demonstrates the reading of cif files and some of the possible options.

    Execute:

     python fromcif.py raw

    which loads the cif as it is (which happens to have spacegroup 1).
    Have a look at the output, especially the Wyckoff positions.

    Next, execute:

     python fromcif.py smoothed

    and have a look at the output, especially the Wyckoff positions,
    which are now fractionals.

    Next, execute:

     python fromcif.py raw detsym

    and have a look at the output: we got space group 63 and
    2 Ru positions, due to the approximate fractional 0.1666 and such.

    Finally, execute:

     python fromcif.py smoothed detsym

    Now we have one Ru and W position with fractionals and spacegroup 194

`fromcif.py`

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    #! /usr/bin/env python
    # ===================================================================
    # file:   fromcif.py
    # author: k.koepernik@ifw-dresden.de
    # date:   22 Mar 2018
    from __future__ import print_function
    import sys
    import pyfplo.fploio as fploio
    import pyfplo.fedit as fedit

    # ===================================================================
    #
    # ===================================================================
    def work(mode='raw',detsym=False):

        print( '\nThis example shows how to import cif files.')

        whtol=1e-4 if mode=='smoothed' else  1e-6

        # Create FPLOInput object and read =.in or create new parser
        # content if =.in does not exist.
        fio=fploio.FPLOInput('=.in')
        # read cif file into parser
        fio.structureFromCIFFile('RuW.cif',wyckofftolerance=whtol,
                                 determinesymmetry=detsym)
        # write =.in
        fio.writeFile("=.in")

        # here we have  =.in with the structure from the cif file

        # use fedit to set further input
        fed=fedit.Fedit()
        fed.iteration(n=100)
        fed.bzintegration(nxyz=[12,12,6])
        fed.pipeFedit()

        print ('\n\nNow we have read the raw cif content as is,'+
               ' which results in \n'+
               'the following symmetry settings:\n\n')

        printsettings()

        return

    # ===================================================================
    #
    # ===================================================================

    def printsettings():
        fio=fploio.FPLOInput('=.in')
        par=fio.parser()
        d=par()
        print( 'spacegroup number : ',d('spacegroup.number').S)
        print( 'spacegroup setting: ',d('spacegroup.setting').S)
        print( 'lattice constants : ',d('lattice_constants').listS)
        print( 'axis angle        : ',d('axis_angles').listS)
        dw=d('wyckoff_positions')
        print( 'Wyckoff positions: ',dw.size())
        for i in range(dw.size()):
            taus=dw[i]('tau').listS
            print( '{0:>2s} {1:>20s} {2:>20s} {3:>20s}'
                .format(dw[i]('element').S,taus[0],taus[1],taus[2]))

    # ===================================================================
    #
    # ===================================================================

    def usage():
        print( 'usage:  ',sys.argv[0],' ( raw | smoothed) [detsym]')
    # ===================================================================
    #
    # ===================================================================

    if __name__ == '__main__':

        if len(sys.argv)<2:
            usage()
            sys.exit(0)
        mode=sys.argv[1]
        mode=mode.replace('-','')

        if not (mode=='raw' or mode=='smoothed'):
            usage()
            sys.exit(0)

        detsym=False
        if len(sys.argv)>=3:
            detsym=True

        work(mode,detsym)

        sys.exit(0)

## Write =.in with low level routines

This tutorial shows how to use `INParser` and `PObj` to modify `=.in`-files. This should not be done for symmetry input!

The tutorial files are in `FPLO.../DOC/pyfplo/Examples/fploio/fploio/writinfilelowlevel` where `FPLO...` stands for your version’s FPLO directory, e.g. `FPLO21.00-61`. Here are the files of this directory:

- writinfilelowlevel.py
- `=.in`

`writinfilelowlevel.py`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    #! /usr/bin/env python
    # ===================================================================
    # file:   bandplot.py
    # author: k.koepernik@ifw-dresden.de
    # date:   19 Apr 2017
    from __future__ import print_function
    import sys
    import pyfplo.fploio as fploio
    # ===================================================================
    #
    # ===================================================================
    def work():

        print( '\nThis example shows simple low level =.in writing.')
        print( 'DO NOT DO THIS UNLESS YOU ARE CONFIDENT YOUR DOING THE '+
            'RIGHT THING.\n')
        p=fploio.INParser()
        p.parseFile('=.in')
        d=p()
        d('bzone_integration.nkxyz').listL=[16,16,16]
        d('spin.mspin').L=2
        d('relativistic.type').L=3
        # This illustrates one of the problems with the low level.
        # In order to keep =.in consistent for human readers
        # we should set the descriptions too.
        # It is better to use pyfplo.fedit instead.
        d('relativistic.description').S='full relativistic'
        p.writeFile('=.in')

        print( 'done')

        return

    # ===================================================================
    #
    # ===================================================================

    if __name__ == '__main__':

        work()

        sys.exit(0)

## Write =.in with mid level routines

This tutorial shows how to use `FPLOInput` to modify `=.in`-files. This should not be done for symmetry input!

The tutorial files are in `FPLO.../DOC/pyfplo/Examples/fploio/fploio/writinfilemidlevel` where `FPLO...` stands for your version’s FPLO directory, e.g. `FPLO21.00-61`. Here are the files of this directory:

- writinfilemidlevel.py
- `=.in`

`writinfilemidlevel.py`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    #! /usr/bin/env python
    # ===================================================================
    # file:   bandplot.py
    # author: k.koepernik@ifw-dresden.de
    # date:   19 Apr 2017
    from __future__ import print_function
    import sys,os
    import pyfplo.fploio as fploio
    # ===================================================================
    #
    # ===================================================================
    def work():

        print( '\nThis fictitious example shows simple mid level =.in writing.')
        print( 'DO NOT DO THIS UNLESS YOU ARE CONFIDENT YOUR DOING THE '+
            'RIGHT THING.\n')

        fio=fploio.FPLOInput()
        if os.path.exists('=.in'):
            fio.parseInFile(True)
        else:
            fio.createNewFileContent()

        p=fio.parser()
        d=p() # the root of the data tree

        # set length units
        d("lengthunit.type").L=2
        # not really needed but good for human readers of =.in
        d("lengthunit.description").S='angstroem'

        # set wyckoff positions
        d("nsort").L=3
        # yes, we need to do this too.
        dw=d("wyckoff_positions")
        dw.resize(3)

        i=0 ;
        di=dw[i]
        di('element').S='Fe'
        di('tau').listD=[0,0,0]

        i+=1 ; di=dw[i]
        di('element').S='Al'
        di('tau').listS=['1/2','1/2','1/2']

        i+=1 ; di=dw[i]
        di('element').S='Mn'
        di('tau').listS=['1/4','1/4','1/4']

        d('lattice_constants').listD=[5.4,5.4,5.4]
        #or
        d('lattice_constants').listS=['5.4','5.4','5.4']

        # symmetry update required
        msg=fio.symmetryUpdate();
        print( msg)

        # reset all other input, to get a default file
        fio.resetNonSymmetrySections()

        # here we can set other things
        d('spin.mspin').L=2

        fio.writeFile("=.in")

        print( 'done')

        return

    # ===================================================================
    #
    # ===================================================================

    if __name__ == '__main__':

        work()

        sys.exit(0)

## Extract default basis into =.basdef

This example extracts the default basis. The tutorial files are in `FPLO.../DOC/pyfplo/Examples/fploio/basis/extract_default_basdef` where `FPLO...` stands for your version’s FPLO directory, e.g. `FPLO21.00-61`. Here are the files of this directory:

- README
- wrapp.sh
- extractdefaultbasis.py

`README`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    Read the script to understand what it is doing.
    It demonstrates how to extract the default basis from an existing =.in
    into =.basdef
    for manual basis manipulation, which could be done by a script (demonstrated elsewhere).

    run extractdefaultbasis.py as

      extractdefaultbasis.py

    then have a look at =.basdef.

    If pyfplo path needs to be set use wrapp.sh. First edit pyfplopath
    in wrapp.sh and then just put it in front as in any of the following.

    wrapp.sh extractdefaultbasis.py

A wrapper to setup paths `wrapp.sh`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    #! /usr/bin/env sh
    #
    # Example wrapper script for path setting.
    #
    ########################################################################

    # set your path here

    pyfplopath=$HOME/FPLO/FPLO22.00-62/PYTHON/

    export PYTHONPATH=$pyfplopath:$PYTHONPATH

    $*

The python script `extractdefaultbasis.py`

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    #! /usr/bin/env python
    # ===================================================================
    # file:   basis.py
    # author: k.koepernik@ifw-dresden.de
    # date:   06 Jun 2017
    from __future__ import print_function
    import sys
    import os
    import pyfplo.fedit as fedit
    import pyfplo.fploio as fploio

    print( '\npyfplo version=: {0}\nfrom: {1}\n'.format(fedit.version,fedit.__file__))
    # protect against wrong version
    #if fedit.version!='22.00': raise RuntimeError('pyfplo version is incorrect.')

    # ===================================================================
    #
    # ===================================================================
    def work_short_version(prot=True):

        if not os.path.exists('=.in'):
            print('ERROR: this script assumes the existence of an =.in-file.')
            sys.exit(1)

        p=fploio.INParser()
        p.parseFile('=.in')
        d=p()('wyckoff_positions')
        elements=[d[i]('element').S for i in range(d.size())]
        bastype=p()('basis.version.type').L
        b=fploio.Basis(bastype,elements)
        b.writeFile()

        os.system('ls -ltr ; echo ; cat =.basdef')

        return

    # ===================================================================
    #
    # ===================================================================
    def work_long_version(prot=True):

        if not os.path.exists('=.in'):
            print('ERROR: this script assumes the existence of an =.in-file.')
            sys.exit(1)

        # 1: Get info for hand-made basis creation

        # Read =.in to get basisversion (optional) and
        # element (optionally: atomic number) list
        p=fploio.INParser()
        p.parseFile('=.in')
        d=p()('wyckoff_positions')
        elements=[d[i]('element').S for i in range(d.size())]
        atomicnumbers=list(map(lambda x: fploio.c_elements.index(x),elements))
        if prot:
            print(('\n=.in contains Wyckoff positions with\n\telements        '
                   +'{}\n\tatomic numbers  {}\n')
                  .format(elements,atomicnumbers))
        basversion=(p()('basis.version.type').L,p()('basis.version.description').S)

        print('basis version in =.in: key={0[0]} name="{0[1]}"\n'.format(basversion))
        print('available versions:\n',fploio.Basis.versions,'\n')

        # 2: Get default basis, compatible with =.in-content.
        #    We could use basversion[0], or basversion[1] as argument
        #    to fploio.Basis or (in later fplo versions) another basis ID.
        b=fploio.Basis('default FPLO9 basis',elements)
        # eqiuvalent:
        # b=fploio.Basis(1,elements)
        # or like this:
        # b=fploio.Basis('default FPLO9 basis',atomicnumbers)

        # 3: write basdeffile (=.basdef):
        b.writeFile()
        #or
        #b.writeFile('=.basdef')

        # Now we have the default basis in '=.basdef' which would be used by fplo
        # on running.  We could modify it by hand too.

        os.system('ls -ltr ; echo ; cat =.basdef')

        return

    # ===================================================================
    #
    # ===================================================================

    if __name__ == '__main__':

        print('-'*72,'\nlong version\n','-'*72)
        work_long_version()

        print('-'*72,'\nshort version\n','-'*72)
        work_short_version()

        sys.exit(0)

## User defined basis (in =.basdef)

This example extracts the default basis, modifies it and creates =.basdef. The tutorial files are in `FPLO.../DOC/pyfplo/Examples/fploio/basis/modify_basdef` where `FPLO...` stands for your version’s FPLO directory, e.g. `FPLO21.00-61`. Here are the files of this directory:

- README
- wrapp.sh
- basis.py

`README`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    Read the script to understand what it is doing.
    It demonstrates how to extract the default basis into =.basdef and how to
    modify it to achieve non-standard basis settings.
    In fact it mostly replicates the fedit basis modification options using
    low-level manipulation. This serves as a starting point for user-made
    basis modifications.

    run basis.py as

      basis.py

    If pyfplo path needs to be set use wrapp.sh. First edit pyfplopath
    in wrapp.sh and then just put it in front as in any of the following.

    wrapp.sh basis.py

A wrapper to setup paths `wrapp.sh`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    #! /usr/bin/env sh
    #
    # Example wrapper script for path setting.
    #
    ########################################################################

    # set your path here

    pyfplopath=$HOME/FPLO/FPLO22.00-62/PYTHON/

    export PYTHONPATH=$pyfplopath:$PYTHONPATH

    $*

The python script `basis.py`

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    #! /usr/bin/env python
    # ===================================================================
    # file:   basis.py
    # author: k.koepernik@ifw-dresden.de
    # date:   06 Jun 2017
    from __future__ import print_function
    import sys
    import os
    import pyfplo.fedit as fedit
    import pyfplo.fploio as fploio

    print( '\npyfplo version=: {0}\nfrom: {1}\n'.format(fedit.version,fedit.__file__))
    # protect against wrong version
    #if fedit.version!='22.00': raise RuntimeError('pyfplo version is incorrect.')

    FPLO=fploio.fploExecutable()

    # ===================================================================
    #
    # ===================================================================
    def makeINFile(extensionlevel=1,core4f=None,core4fNoValenceF=None,
                   addf=False,add3d=False,multicore=None,):
        ''' make a (hypothetical compound) =.in-file '''
        fed=fedit.Fedit(recreate=True)
        fed.symmetry(spacegroup=123,latcon=[8,8,8],atoms=
                     [
                         ['fe',[0,0,0]],
                         ['eu',['1/2','1/2','1/2']],
                         ['H',['1/2','0','0']],
                     ])
        fed.basis(extensionlevel=extensionlevel,core4f=core4f,
                  core4fNoValenceF=core4fNoValenceF,addf=addf,add3d=add3d,
                  multicore=multicore)
        # write  input file
        fed.pipeFedit()

        return
    # ===================================================================
    #
    # ===================================================================

    def getBasisIngredient(prot=False):
        '''
        Read =.in to get basisversion (optional) and
        element (optinal: atomic number) list
        '''
        p=fploio.INParser()
        p.parseFile('=.in')
        d=p()('wyckoff_positions')
        elements=[d[i]('element').S for i in range(d.size())]
        atomicnumbers=list(map(lambda x: fploio.c_elements.index(x),elements))
        if prot:
            print(('\n=.in contains Wyckoff positions with\n\telements        '
                   +'{}\n\tatomic numbers  {}\n')
                  .format(elements,atomicnumbers))
        basversion=(p()('basis.version.type').L,p()('basis.version.description').S)
        return (basversion,elements,atomicnumbers)

    # ===================================================================
    #
    # ===================================================================

    def writeBasdef(basdeffile='=.basdef',extensionlevel=1,core4f=[],
                    core4fNoValenceF=[],addf=False,add3d=False,
                    multicore=None,
                    makesingle=False,doubleSemiCoreS=False):

        (basversion,elements,atomicnumbers)=getBasisIngredient()
        b=fploio.Basis('default FPLO9 basis',elements)

        # modify

        for bd in b:
            for l in range(1,extensionlevel):
                for o in bd.valence:
                    mu=o.multiplicity
                    o.append(Q=o.Q(mu-1)+2,P=max(min(o.P(mu-1),1.),0.85))

        if add3d:
            for bd in b:
                haved=any([o.name[1]=='d' for o in bd.core])
                haved=haved or any([o.name[1]=='d' for o in bd.semicore])
                haved=haved or any([o.name[1]=='d' for o in bd.valence])
                if not haved:
                    bd.valence.append('3d',Q=[5],P=[1])

        # add S*f (D*f if uncommented)
        if addf:
            for bd in b:
                nmain=3
                for o in bd.core:
                    if o.name[1]=='f':
                        nmain=max(nmain,int(o.name[0]))
                for o in bd.semicore:
                    if o.name[1]=='f':
                        nmain=max(nmain,int(o.name[0]))
                for o in bd.valence:
                    if o.name[1]=='f':
                        nmain=max(nmain,int(o.name[0])+o.multiplicity-1)

                if nmain<4:
                    bd.valence.append('{nm}f'.format(nm=nmain+1),Q=[5],P=[1])
                    #bd.valence.append('{nm}f'.format(nm=nmain+1),Q=[5,7],P=[1,1])

        # move 4f to core, leave remaining f-valence
        for c in core4f:
            if isinstance(c,int):
                isort=c
            else:
                isort=elements.index(c.capitalize())+1
            bd=b[isort-1] # isort is one-based as in FPLO
            for o in bd.valence:
                if o.name=='4f':
                    o.removeFirst()
                    bd.core.append('4f')

        # move 4f to core, no f-valence
        for c in core4fNoValenceF:
            if isinstance(c,int):
                isort=c
            else:
                isort=elements.index(c.capitalize())+1
            bd=b[isort-1] # isort is one-based as in FPLO
            for i,o in enumerate(bd.valence):
                if o.name=='4f':
                    bd.valence.remove(i)
                    bd.core.append('4f')
                    break

        # make all valence MultiOrbitals single orbitals
        # This option does not exist in fedit.
        if makesingle:
            for bd in b:
                for o in bd.valence:
                    while o.multiplicity>1: o.removeLast()

        # make only semicore s-orbitals double
        # This option does not exist in fedit.
        if doubleSemiCoreS:
            for bd in b:
                for o in bd.semicore:
                    mu=o.multiplicity
                    if o.name[1]=='s':
                        o.append(Q=0,S=5,P=max(min(o.P(mu-1),1.),0.85))
                        #o.set(0,Q=0,S=-5)

        # make double core
        if (multicore is not None) and len(multicore)>0:
            for bd in b:
                for o in bd.core:
                    o.set(0,Q=multicore[0][0],S=multicore[0][1])
                    for m in range(1,len(multicore)):
                        o.append(Q=multicore[m][0],S=multicore[m][1])

        b.writeFile(basdeffile)

        return
    # ===================================================================
    #
    # ===================================================================
    def extractBasDefFromOut(outfile='out',basdeffile='=.basdef'):
        with open(outfile,'r') as fh:
            lines=fh.readlines()

        with open(basdeffile,'w') as fh:
            start=False
            for line in lines:
                if line.startswith('Start: content of =.basdef'):
                    start=True
                    continue
                if line.startswith('End  : content of =.basdef'):
                    break
                if start:
                    if line.startswith('---'): continue
                    fh.write(line)

        return
    # ===================================================================
    #
    # ===================================================================
    def work():

        # ---------------------------------------------------------------
        # With basis level2 (from fedit):
        makeINFile(extensionlevel=2,addf=True,add3d=True,
                   core4fNoValenceF=[2], # sort of Eu
                   multicore=[[0,0],[0,10]])
        # Here we are all set ... including level2 basis defined in =.in.
        # ---------------------------------------------------------------

        # ---------------------------------------------------------------
        # For later diff-checking, run fplo to extract the basis as defined
        # in =.in from the outfile section :
        #       Start: content of =.basdef
        #       ...
        #       End  : content of =.basdef
        #

        fed=fedit.Fedit(recreate=False)
        fed.iteration(n=1) # single step, since we run for =.basdef extraction
        fed.pipeFedit()

        # we want =.in to determine the basis, so delete =.basdef
        os.system('rm -f =.basdef')
        print('running fplo to extract which basis was used, wait a few secs...')
        os.system('{} > out'.format(FPLO))

        extractBasDefFromOut('out',basdeffile='=.basdef_as_defined_by_in_file')
        # ---------------------------------------------------------------

        # ---------------------------------------------------------------
        # Extract default =.basdef and modify it
        writeBasdef(basdeffile='=.basdef',extensionlevel=2,
                    addf=True,add3d=True,core4fNoValenceF=[2],
                    multicore=[[0,0],[0,10]],
                    makesingle=False,doubleSemiCoreS=False)
        # which now should have the same basis modifications as defined in =.in.
        # Compare the two
        print('Executing:  diff =.basdef =.basdef_as_defined_by_in_file ":"') # same
        os.system('diff =.basdef =.basdef_as_defined_by_in_file') # same
        print('Nothing should be shown from the diff!')
        # ---------------------------------------------------------------

        return

    # ===================================================================
    #
    # ===================================================================

    if __name__ == '__main__':

        work()

        sys.exit(0)

## Extract =.basdef from output file

This example extracts `=.basdef` from an fplo output file. The tutorial files are in `FPLO.../DOC/pyfplo/Examples/fploio/basis/extract_basdef_from_outfile` where `FPLO...` stands for your version’s FPLO directory, e.g. `FPLO21.00-61`. Here are the files of this directory:

- README
- wrapp.sh
- extractbasdeffromout.py

`README`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    Read the script to understand what it is doing.
    It extracts =.basdef from an FPLO output file. This =.basdef
    will contain the basis actually used during the calculation
    (as opposed to the defualt =.basdef). Once extracted, it
    will be used henceforth during calculations (and can be modified).

    run extractbasdeffromout.py as

      extractbasdeffromout.py

    then have a look at =.basdef.

    If pyfplo path needs to be set use wrapp.sh. First edit pyfplopath
    in wrapp.sh and then just put it in front as in any of the following.

    wrapp.sh extractbasdeffromout.py

A wrapper to setup paths `wrapp.sh`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    #! /usr/bin/env sh
    #
    # Example wrapper script for path setting.
    #
    ########################################################################

    # set your path here

    pyfplopath=$HOME/FPLO/FPLO22.00-62/PYTHON/

    export PYTHONPATH=$pyfplopath:$PYTHONPATH

    $*

The python script `extractbasdeffromout.py`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    #! /usr/bin/env python3
    # ===================================================================
    # file:   extractbasdeffromout.py
    # author: k.koepernik@ifw-dresden.de
    # date:   24 Jun 2022

    from __future__ import print_function
    import sys
    import numpy as np

    # ===================================================================
    #
    # ===================================================================
    def extractBasDefFromOut(outfile='out',basdeffile='=.basdef'):

        with open(outfile,'r') as fh:
            lines=fh.readlines()

        with open(basdeffile,'w') as fh:
            start=False
            for line in lines:
                if line.startswith('Start: content of =.basdef'):
                    start=True
                    continue
                if line.startswith('End  : content of =.basdef'):
                    break
                if start:
                    if line.startswith('---'): continue
                    fh.write(line)
        return

    # ===================================================================
    #
    # ===================================================================

    if __name__ == '__main__':

        extractBasDefFromOut(outfile='out',basdeffile='=.basdef')

        sys.exit(0)

## Grep results

These examples extract all (or the latest) occurances via `OutGrep` of some results in the outfile.

The tutorial files are in `FPLO.../DOC/pyfplo/Examples/fploio/grep/` where `FPLO...` stands for your version’s FPLO directory, e.g. `FPLO21.00-61`. Here are the files of this directory:

- README
- wrapp.sh
- grepintodict.py
- grepEtot.py
- grepiterationprogress.py

`README`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    Demonstration of how to grep from FPLO output from within python scripts.
    Read the scripts to understand what they are doing.

    run scripts as

      grepintodict.py

    or

      grepEtot.py

    or

      grepiterationprogress.py

    If pyfplo path needs to be set use wrapp.sh. First edit pyfplopath
    in wrapp.sh and then just put it in front as in any of the following.

    wrapp.sh grepintodict.py

    wrapp.sh grepEtot.py

    wrapp.sh grepiterationprogress.py

A wrapper to setup paths `wrapp.sh`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    #! /usr/bin/env sh
    #
    # Example wrapper script for path setting.
    #
    ########################################################################

    # set your path here

    pyfplopath=$HOME/FPLO/FPLO22.00-62/PYTHON/

    export PYTHONPATH=$pyfplopath:$PYTHONPATH

    $*

The python script `grepintodict.py`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    #! /usr/bin/env python3
    # ===================================================================
    # file:   g.py
    # author: k.koepernik@ifw-dresden.de
    # date:   22 Jun 2022

    from __future__ import print_function
    import sys
    import numpy as np
    import pyfplo.fploio as fploio

    print( '\npyfplo version=: {0}\nfrom: {1}\n'.format(fploio.version,fploio.__file__))
    # protect against wrong version
    #if fploio.version!='22.00': raise RuntimeError('pyfplo version is incorrect.')

    # ===================================================================
    #
    # ===================================================================
    def work(printmodes=True):

        if printmodes: # print grep modes
            for k in fploio.OutGrep.modes.keys():
                print('mode: {0:15s} : {1}'.format(k,fploio.OutGrep.modes[k]))
            print('-'*72,'\n')

        # this will read the file
        og=fploio.OutGrep('out')
        si=og.sites()

        # grep some results from last appearance in file (last iteration)
        results={}
        results['etot']      = float(og.grep('EE')[-1])
        results['total spin']= float(og.grep('SS')[-1])

        for i,s in enumerate(si):
            site=i+1
            results['spin {0}{1:<3d}'.format(s.element,site)]\
                =float(og.grep('SSat',site)[-1])

        for k in results.keys():
            print('{0:<20s} {1:>20.10f}'.format(k,results[k]))

        if printmodes: print('\n','-'*72)

        return

    # ===================================================================
    #
    # ===================================================================

    if __name__ == '__main__':

        work()

        sys.exit(0)

The python script `grepEtot.py`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    #! /usr/bin/env python3
    # ===================================================================
    # file:   g.py
    # author: k.koepernik@ifw-dresden.de
    # date:   22 Jun 2022

    from __future__ import print_function
    import pyfplo.fploio as fploio

    print( '\npyfplo version=: {0}\nfrom: {1}\n'.format(fploio.version,fploio.__file__))
    # protect against wrong version
    #if fploio.version!='22.00': raise RuntimeError('pyfplo version is incorrect.')

    og=fploio.OutGrep('out')
    print('etot=',og.grep('EE')[-1],', gap=',og.grep('gap')[-1])

The python script `grepiterationprogress.py`

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    #! /usr/bin/env python3
    # ===================================================================
    # file:   g.py
    # author: k.koepernik@ifw-dresden.de
    # date:   22 Jun 2022

    from __future__ import print_function
    import os
    import pyfplo.fploio as fploio

    print( '\npyfplo version=: {0}\nfrom: {1}\n'.format(fploio.version,fploio.__file__))
    # protect against wrong version
    #if fploio.version!='22.00': raise RuntimeError('pyfplo version is incorrect.')

    og=fploio.OutGrep('out')
    si=og.sites()

    with open('res','w') as fh:
        res=og.grep('it')
        fh.write('# step last_dev\n')
        for i,r in enumerate(res):
            fh.write('{} {}\n'.format(i,r))
        fh.write('\n')

        res=og.grep('EE')
        fh.write('# step Etot\n')
        for i,r in enumerate(res):
            fh.write('{} {}\n'.format(i,r))
        fh.write('\n')

        res=og.grep('gap')
        E0=float(res[0])
        fh.write('# step gap\n')
        for i,r in enumerate(res):
            fh.write('{} {}\n'.format(i,r))
        fh.write('\n')

    with open('resspins','w') as fh:

        for i,s in enumerate(si):
            site=i+1
            res=og.grep('SSat',site)
            fh.write('# step \'atom spin {}{}\'\n'.format(s.element,site))
            for it,r in enumerate(res):
                fh.write('{} {}\n'.format(it,r))
            fh.write('\n')
    os.system('xfbp grepiterationprogress.xpy')