Example #1
0
    def fromhsd(cls, root, query):
        """Creates instance from a HSD-node and with given query object."""

        xcfunctional, child = query.getvalue(root, "xcfunctional", conv.str0,
                                             returnchild=True)
        if xcfunctional not in sc.XC_FUNCTIONAL_TYPES:
            raise hsd.HSDInvalidTagValueException(
                "Invalid functional type '{}'".format(xcfunctional), child)
        superpos, child = query.getvalue(root, "superposition", conv.str0,
                                         returnchild=True)
        if superpos not in sc.SUPERPOSITION_TYPES:
            raise hsd.HSDInvalidTagValueException(
                "Invalid superposition type '{}'".format(superpos), child)

        myself = cls()
        myself.xcfunctional = sc.XC_FUNCTIONAL_TYPES[xcfunctional]
        myself.superposition = sc.SUPERPOSITION_TYPES[superpos]
        return myself
Example #2
0
 def fromhsd(cls, node, query):
     """Generate the object from HSD tree"""
     integrationpoints, child = query.getvalue(node,
                                               "integrationpoints",
                                               conv.int1,
                                               returnchild=True)
     if len(integrationpoints) != 2:
         raise hsd.HSDInvalidTagValueException(
             "Two integration point parameters must be specified", child)
     return cls(integrationpoints)
Example #3
0
    def fromhsd(cls, root, query):
        '''Creates instance from a HSD-node and with given query object.'''

        power, child = query.getvalue(root, 'power', conv.float0,
                                      returnchild=True)
        if power <= 0.0:
            raise hsd.HSDInvalidTagValueException(
                msg='Invalid compression power {:f}'.format(power), node=child)
        radius, child = query.getvalue(root, 'radius', conv.float0,
                                       returnchild=True)
        if radius <= 0.0:
            raise hsd.HSDInvalidTagValueException(
                msg='Invalid compression radius {:f}'.format(radius),
                node=child)

        myself = cls()
        myself.power = power
        myself.radius = radius

        return myself
Example #4
0
    def fromhsd(cls, root, query):
        """Creates instance from a HSD-node and with given query object."""

        superpos, child = query.getvalue(root, "superposition", conv.str0,
                                         returnchild=True)
        if superpos not in sc.SUPERPOSITION_TYPES:
            raise hsd.HSDInvalidTagValueException(
                "Invalid superposition type '{}'".format(superpos), child)

        # read the functional
        xcf = sc.hsd_node_factory('xc', xcfunctionals.XCFUNCTIONALS,
                                  query.getvaluenode(root, 'xcfunctional'),
                                  query)
        if xcf.__class__ not in xcfunctionals.XCFUNCTIONALS.values():
            raise hsd.HSDInvalidTagValueException(
                "Invalid functional type '{}'".format(xcf), child)

        myself = cls()
        myself.superposition = sc.SUPERPOSITION_TYPES[superpos]
        myself.xcf = xcf

        return myself
Example #5
0
    def fromhsd(cls, root, query):
        '''Creates instance from a HSD-node and with given query object.'''
        omega, child = query.getvalue(root,
                                      'omega',
                                      conv.float0,
                                      returnchild=True)
        if omega <= 0.0:
            raise hsd.HSDInvalidTagValueException(
                msg='Invalid rs-parameter {:f}'.format(omega), node=child)

        myself = cls()
        myself.type = 'lc-pbe'
        myself.omega = omega
        return myself
Example #6
0
    def fromhsd(cls, root, query):
        """Initializes an AtomProperties object from a HSD-tree.

        Parameters
        ----------
        root : HSDTree instance
            Root of the node containing the information.
        query : HSDQuery instance
            Object used for querying the tree.

        Returns
        -------
        atomconfig : AtomProperties
            Initialized Atomconfig instance.
        """
        znuc, child = query.getvalue(root, "atomicnumber", conv.float0,
                                     returnchild=True)
        if znuc < 0.0 or znuc > 95.0:
            raise hsd.HSDInvalidTagValueException(
                msg="Invalid nuclear charge {:f}".format(znuc),
                node=child)
        mass, child = query.getvalue(root, "mass", conv.float0,
                                     returnchild=True)
        if mass < 0 or mass > 250.0:
            raise hsd.HSDInvalidTagValueException(
                msg="Invalid atomic mass {:f}".format(mass), node=child)

        occshellnames = []
        occupations = []
        occnode = query.findchild(root, "occupations")
        for ll, shellname in enumerate(sc.ANGMOM_TO_SHELL):
            occ_l = []
            for nn in range(ll + 1, sc.MAX_PRINCIPAL_QN):
                txt = "{:d}{:s}".format(nn, shellname)
                shelloccnode = query.findchild(occnode, txt, optional=True)
                if shelloccnode is None:
                    break
                tmp = query.getvalue(shelloccnode, ".", conv.float1)
                if len(tmp) != 2:
                    raise hsd.HSDInvalidTagValueException(
                        msg="Invalid number of occupation numbers",
                        node=shelloccnode)
                occ_l.append((tmp[0], tmp[1]))
                occshellnames.append((txt, (tmp[0] + tmp[1])))
            if len(occ_l):
                occupations.append(occ_l)

        valshellnames, child = query.getvalue(root, "valenceshells",
                                              conv.str1, returnchild=True)
        valshells = []
        for valshellname in valshellnames:
            try:
                valshell = sc.shell_name_to_ind(valshellname)
                valshells.append(valshell)
            except ValueError:
                raise hsd.HSDInvalidTagValueException(
                    msg="Invalid shell name '{}'".format(valshellname),
                    node=child)

        occshells = []
        for occshellname, occ in occshellnames:
            occshell = sc.shell_name_to_ind(occshellname)
            occshells.append((occshell, occ))

        relattype, child = query.getvalue(root, "relativistics", conv.str0,
                                          "none", returnchild=True)
        relattype = relattype.lower()
        if relattype not in sc.RELATIVISTICS_TYPES:
            raise hsd.HSDInvalidTagValueException(
                msg="Invalid relativistics type '{}'".format(relattype))

        return cls(znuc, mass, occupations, valshells, occshells, relattype)
Example #7
0
def _test_module():
    """Testing module capabilities."""
    from io import StringIO
    from sktools.hsd.treebuilder import HSDTreeBuilder
    from sktools.hsd.parser import HSDParser
    from sktools.hsd.tree import HSDTree
    import sktools.hsd.converter as conv

    unit_attr = "unit"
    unit_only = frozenset([unit_attr])
    parser = HSDParser(defattrib=unit_attr)
    builder = HSDTreeBuilder(parser=parser)

    # Defining force type (scalar, list)
    force_units = {"ev/aa": 0.0194469050555}

    # Trivial unit conversion routine.
    def multiply_unit(child, value, unitattr, units):
        unit = child.get(unitattr)
        convfact = units.get(unit.lower(), None)
        if convfact is None:
            hsd.HSDInvalidAttributeValueException(
                node=child, msg="Invalid unit '{}'".format(unit))
        return value * convfact

    stream = StringIO("""
# Various driver possibilities
#                                  # No driver specification
#Driver {}                         # Use the default driver (whatever it is)
#Driver = None {}                  # Use the driver None {}
#Driver = None
Driver = ConjugateGradient {
    MaxForceComponent [eV/AA] = 1e-2
}

Hamiltonian = DFTB {
  # SCC = True
  # SCCTolerance = 1e-4
  # MaxSCCIterations = 100
  MaxAngularMomentum {
    O = "p"
    H = "s"
  }
  Mixer = Broyden
  #Mixer = Broyden {
  #  MixingParameter = 0.3
  #}
  #ReadInitialCharges = No
  KPointsAndWeights {
     0.0   0.0  0.0   0.25
     0.25 0.25 0.25   0.75
  }
}

Options {
  WriteAutotestTag = Yes
  UnknownOption = No
}

#ParserOptions {
#  ParserVersion = 4
#}
""")
    root = builder.build(stream)
    qy = HSDQuery(markprocessed=True)
    # A complex case: If driver was not specified, it defaults to None {}
    # If it was specified but nothing was assinged to it (no child)
    # it defaults to ConjugateGradient {}.
    dtype, driver = qy.getvaluenode(root,
                                    "Driver",
                                    "None",
                                    allowtextvalue=True,
                                    returnchild=True)
    # Since the in the previous getvaluenode() call a default had been specified
    # dtype can only be None, if "Driver" was in the input, but had no
    # child (e.g. 'Driver {}' or 'Driver = ;'). In this case we set
    # it to ConjugateGradient
    if dtype is None:
        dtype = qy.getchild(driver, "ConjugateGradient", optional=True)
    if dtype.tag == "None":
        pass
    elif dtype.tag == "ConjugateGradient":
        forcetol, child = qy.getvalue(dtype,
                                      "MaxForceComponent",
                                      conv.float0,
                                      1e-4,
                                      returnchild=True,
                                      attribs=unit_only)
        multiply_unit(child, forcetol, unit_attr, force_units)
    elif dtype.tag == "SteepestDescent":
        forcetol, child = qy.getvalue(dtype,
                                      "MaxForceComponent",
                                      conv.float0,
                                      1e-4,
                                      returnchild=True,
                                      attribs=unit_only)
        multiply_unit(child, forcetol, unit_attr, force_units)
        stepsize = qy.getvalue(dtype, "StepSize", conv.float0, 40.0)
        pass
    else:
        raise hsd.HSDInvalidTagException(node=dtype,
                                         msg="Unknown driver type '{}'".format(
                                             dtype.tag))

    ham = qy.getchild(root, "Hamiltonian")
    dftb = qy.getchild(ham, "DFTB")
    scc = qy.getvalue(dftb, "SCC", conv.bool0, True)
    scctol = qy.getvalue(dftb, "SCCTolerance", conv.float0, 1e-4)
    scciter = qy.getvalue(dftb, "MaxSCCIterations", conv.int0, 100)
    mangmom = qy.getchild(dftb, "MaxAngularMomentum")
    maxangs = [
        qy.getvalue(mangmom, species, conv.str0) for species in ["O", "H"]
    ]
    mixer = qy.getvaluenode(dftb, "Mixer", "Broyden", allowtextvalue=True)
    if mixer.tag == "Broyden":
        mixparam = qy.getvalue(mixer, "MixingParameter", conv.float0, 0.2)
    else:
        raise hsd.HSDInvalidTagException(node=mixer,
                                         msg="Unknown mixer type '{}'.".format(
                                             mixer.tag))
    readcharges = qy.getvalue(dftb, "ReadInitalCharges", conv.bool0, False)
    kpoints = qy.getvalue(dftb, "KPointsAndWeights", conv.float1)
    if len(kpoints) % 4:
        raise hsd.HSDInvalidTagValueException(node=kpoints,
                                              msg="Incorrect number of floats")
    options = qy.getchild(root, "Options", optional=True)
    autotest = qy.getvalue(options, "WriteAutotestTag", conv.bool0, False)
    parseroptions = qy.getchild(root, "ParserOptions", optional=True)
    parserversion = qy.getvalue(parseroptions, "ParserVersion", conv.int0, 4)
    tree = HSDTree(root)
    tree.writehsd()
    print("\nUnprocessed: ", qy.findunprocessednodes(root))
Example #8
0
    def getvalue(self,
                 node,
                 name,
                 converter=None,
                 defvalue=None,
                 attribs=None,
                 defattribs=None,
                 hsdblock=False,
                 returnchild=False):
        """Returns the converted value of the data stored in a child with a
        given name.

        Parameters
        ----------
        node : Element
            Parent node.
        name : string
            Name of the child to look for.
        converter : converter object
            Object with methods fromhsd() and tohsd() which can
            convert between the hsd element and the desired type. See
            converters in hsd.converter for examples.
        defvalue : arbitrary, optional
            Default value used if child has not been found. It will be
            converted to text by the tohsd() method of the converter.
        attribs : frozen set
            Set of attributes the node is allowed to have.
        defattribs: dict, optional
            Default attribute dictionary used if child has not been found.
        hsdblock : bool, optional
            Whether the given value should be added in hsd block notation
            (enclosed in curly braces) instead of an assignment.
        returnchild : bool, optional
            Whether not only the value but also the child node should be
            returned.

        Returns
        -------
        value : arbitrary
            The converted value of the child node's text or the default value
            if the child had not been found. In latter case, an appropriate
            node with the appropriate text representation of the default
            value is inserted into the tree.
        child : Element, optional
            Child node. Only returned, if `returnchild=True` was set.

        Raises
        ------
        HSDMissingTagException
            If child was not found and no default value had been specified.
        HSDInvalidTagValueException
            If conversion from tag values was unsuccessful.
        HSDInvalidAttributeException
            If node posses an attribute which is not allowed.

        Notes
        -----
        This method may store a reference to the converter object.
        Make sure you pass something which does not change afterwards.
        """
        optional = defvalue is not None
        child = self.findchild(node, name, optional)
        if child is not None:
            if len(child):
                raise hsd.HSDInvalidTagException("Unexpected children")
            self._checkattribs(child, attribs)
            if converter:
                try:
                    value = converter.fromhsd(child.text)
                except ValueError as ex:
                    raise hsd.HSDInvalidTagValueException(
                        msg="Conversion error: " + str(ex), node=child)
            else:
                value = child.text
            return (value, child) if returnchild else value
        else:
            child = self.setvalue(node, name, converter, defvalue, defattribs,
                                  hsdblock)
            return (defvalue, child) if returnchild else defvalue