Obtain elemental data given a Z number

    An exception is thrown if the Z number is not found
556886
def element_data_from_Z(Z):
    '''
    '''

    # Z may be a str
    if isinstance(Z, str) and Z.isdecimal():
        Z = int(Z)

    if Z not in _element_Z_map:
        raise KeyError('No element data for Z = {}'.format(Z))
    return _element_Z_map[Z]
1248416
function getData(element, name) {
  if (isObject(element[name])) {
    return element[name];
  } else if (element.dataset) {
    return element.dataset[name];
  }

  return element.getAttribute('data-' + hyphenate(name));
}
477578
private IAtomContainer readMolecule() throws Exception {
        boolean foundCompound = false;
        while (parser.next() != XMLEvent.END_DOCUMENT) {
            if (parser.getEventType() == XMLEvent.START_ELEMENT) {
                if (parser.getLocalName().equals("PC-Compound")) {
                    foundCompound = true;
                    break;
                }
            }
        }
        if (foundCompound) {
            return parserHelper.parseMolecule(parser, builder);
        }
        return null;
    }
1353738
private Object toEnum(ParameterType parameterType, String enumTextValue, String paramName, boolean hardFailEnumDeserialisation) {
        try {
            return EnumUtils.readEnum(parameterType.getImplementationClass(), enumTextValue, hardFailEnumDeserialisation);
        } catch (Exception e) {
            throw XMLTranscriptionInput.exceptionDuringDeserialisation(parameterType, paramName, e, false);
        }
    }
1361216
private static int getEpisodeValue(Element eEpisode, String key) {
        int episodeValue;
        try {
            String value = DOMHelper.getValueFromElement(eEpisode, key);
            episodeValue = NumberUtils.toInt(value, 0);
        } catch (WebServiceException ex) {
            LOG.trace("Failed to read episode value", ex);
            episodeValue = 0;
        }

        return episodeValue;
    }
1094779
@Override
  public Result<MZMLIndexElement> buildIndex(final Info info) throws Exception {

    Result<MZMLIndexElement> result = new IndexBuilder.Result<>(info);
    vars.reset();

    XMLStreamReaderImpl reader = (pool == null) ? new XMLStreamReaderImpl() : pool.borrowObject();
    try {
      reader.setInput(info.is, StandardCharsets.UTF_8.name());
      LogHelper.setJavolutionLogLevelFatal();

      int eventType;
      do {
        // Read the next XML element
        try {
          eventType = reader.next();
        } catch (XMLStreamException e) {

          if (e instanceof XMLUnexpectedEndTagException) {
            // it's ok to have unexpected closing tags
            eventType = reader.getEventType();
          } else if (e instanceof XMLUnexpectedEndOfDocumentException) {
            // as we're reading arbitrary chunks of file, we will almost always finish parsing by hitting this condition
            break;
          } else {
            throw new FileParsingException(e);
          }
        }

        // process the read event
        switch (eventType) {

          case XMLStreamConstants.START_ELEMENT:
            CharArray localName = reader.getLocalName();
            Attributes attrs = reader.getAttributes();

            if (localName.contentEquals(MZMLMultiSpectraParser.TAG.SPECTRUM.name)) {

              if (vars.offsetLo != null) {
                throw new FileParsingException("Nested spectrum tags not allowed in mzml.");
              }

              // these are required attributes, if they're not there, just throw an exception
              try {
                vars.spectrumIndex = attrs.getValue(MZMLMultiSpectraParser.ATTR.SPECTRUM_INDEX.name)
                    .toInt();
                vars.spectrumId = attrs.getValue(MZMLMultiSpectraParser.ATTR.SPECTRUM_ID.name)
                    .toString();
                vars.offsetLo = reader.getLocation().getLastStartTagPos();
                addAndFlush(result, info.offsetInFile);

              } catch (NumberFormatException e) {
                throw new FileParsingException("Malformed scan number while building index", e);
              }
            }
            break;

          case XMLStreamConstants.CHARACTERS:
            break;

          case XMLStreamConstants.END_ELEMENT:
            localName = reader.getLocalName();

            if (localName.contentEquals(MZMLMultiSpectraParser.TAG.SPECTRUM.name)) {
              vars.offsetHi = reader.getLocation().getTotalCharsRead();
              addAndFlush(result, info.offsetInFile);
            }

            break;
        }

      } while (eventType != XMLStreamConstants.END_DOCUMENT);

    } finally {
      addAndFlush(result, info.offsetInFile);

      // we need to return the reaer to the pool, if we borrowed it from there
      if (pool != null && reader != null) {
        pool.returnObject(reader);
      }
    }

    return result;
  }
353855
def from_Z(z: int):
        
        for sym, data in _pt_data.items():
            if data["Atomic no"] == z:
                return Element(sym)
        raise ValueError("No element with this atomic number %s" % z)
401663
private Object getValue(PageContext pc, SQL sql, Query querySource, int row, Collection.Key key, Object value) throws PageException {
	if (value instanceof ZSelectItem) return executeExp(pc, sql, querySource, ((ZSelectItem) value).getExpression(), row);
	return querySource.getAt(key, row);
    }
416761
def from_string(data):
        
       
        root=ET.fromstring(data)
        speciesnode=root.find('structure').iter('species')
        elements = []
        positions = []
        vectors=[]
        lockxyz=[]
        # get title
        title_in=str(root.find('title').text)
        # Read elements and coordinates
        for nodes in speciesnode:
            symbol = nodes.get('speciesfile').split('.')[0]
            if len(symbol.split('_'))==2:
              symbol=symbol.split('_')[0]
            if Element.is_valid_symbol(symbol):
                # Try to recognize the element symbol
                element = symbol
            else:
                raise NLValueError("Unknown element!")
            natoms = nodes.getiterator('atom')
            for atom in natoms:
                x, y, z = atom.get('coord').split()
                positions.append([float(x), float(y), float(z)])
                elements.append(element)
                # Obtain lockxyz for each atom
                if atom.get('lockxyz') is not None:
                    lxy=[]
                    for l in atom.get('lockxyz').split():
                        if l=='True' or l=='true':
                            lxyz.append(True)
                        else:
                            lxyz.append(False)
                    lockxyz.append(lxyz)
                else:
                    lockxyz.append([False, False, False])
        #check the atomic positions type
        if 'cartesian' in root.find('structure').attrib.keys():
          if root.find('structure').attrib['cartesian']:
            cartesian=True
            for i in range(len(positions)):
                for j in range(3):
                    positions[i][j]=positions[i][j]*ExcitingInput.bohr2ang
            print(positions)
        else:
          cartesian=False
        # get the scale attribute
        scale_in=root.find('structure').find('crystal').get('scale')
        if scale_in:
            scale=float(scale_in)*ExcitingInput.bohr2ang
        else:
            scale=ExcitingInput.bohr2ang
       # get the stretch attribute
        stretch_in=root.find('structure').find('crystal').get('stretch')
        if stretch_in:
          stretch=np.array([float(a) for a in stretch_in])
        else:
          stretch=np.array([1.0,1.0,1.0])
        # get basis vectors and scale them accordingly
        basisnode=root.find('structure').find('crystal').iter('basevect')
        for vect in basisnode:
          x, y, z=vect.text.split()
          vectors.append([float(x)*stretch[0]*scale,
                          float(y)*stretch[1]*scale,
                          float(z)*stretch[2]*scale])
        # create lattice and structure object
        lattice_in=Lattice(vectors)
        structure_in=Structure(lattice_in,elements,positions,coords_are_cartesian=cartesian)

        return ExcitingInput(structure_in, title_in, lockxyz)
1071715
private IAtomType getAtomType(String ID) throws NoSuchAtomTypeException {
        IAtomType at = null;
        for (int i = 0; i < atomTypes.size(); i++) {
            at = (IAtomType) atomTypes.get(i);
            if (at.getAtomTypeName().equals(ID)) {
                return at;
            }
        }
        throw new NoSuchAtomTypeException("AtomType " + ID + " could not be found");
    }
959542
public Object get(int index) {

        if (index >= elementCount) {
            throw new IndexOutOfBoundsException("Index out of bounds: "
                                                + index + " >= "
                                                + elementCount);
        }

        if (index < 0) {
            throw new IndexOutOfBoundsException("Index out of bounds: "
                                                + index + " < 0");
        }

        return elementData[index];
    }
843941
def Element(self, elem, **params):
        """"""
        res = self.__call__(deepcopy(elem), **params)
        if len(res) > 0: 
            return res[0]
        else:
            return None
429316
protected void newAtomData() {
        atomCounter = 0;
        elsym = new ArrayList<String>();
        elid = new ArrayList<String>();
        eltitles = new ArrayList<String>();
        formalCharges = new ArrayList<String>();
        partialCharges = new ArrayList<String>();
        isotope = new ArrayList<String>();
        atomicNumbers = new ArrayList<String>();
        exactMasses = new ArrayList<String>();
        x3 = new ArrayList<String>();
        y3 = new ArrayList<String>();
        z3 = new ArrayList<String>();
        x2 = new ArrayList<String>();
        y2 = new ArrayList<String>();
        xfract = new ArrayList<String>();
        yfract = new ArrayList<String>();
        zfract = new ArrayList<String>();
        hCounts = new ArrayList<String>();
        atomParities = new ArrayList<String>();
        parityARef1 = new ArrayList<String>();
        parityARef2 = new ArrayList<String>();
        parityARef3 = new ArrayList<String>();
        parityARef4 = new ArrayList<String>();
        atomAromaticities = new ArrayList<String>();
        atomDictRefs = new ArrayList<String>();
        spinMultiplicities = new ArrayList<String>();
        occupancies = new ArrayList<String>();
        atomCustomProperty = new HashMap<Integer, List<String>>();
    }
270462
def _get_structure(self, data, primitive):
        

        def get_num_implicit_hydrogens(sym):
            num_h = {"Wat": 2, "wat": 2, "O-H": 1}
            return num_h.get(sym[:3], 0)

        lattice = self.get_lattice(data)

        # if magCIF, get magnetic symmetry moments and magmoms
        # else standard CIF, and use empty magmom dict
        if self.feature_flags["magcif_incommensurate"]:
            raise NotImplementedError(
                "Incommensurate structures not currently supported.")
        elif self.feature_flags["magcif"]:
            self.symmetry_operations = self.get_magsymops(data)
            magmoms = self.parse_magmoms(data, lattice=lattice)
        else:
            self.symmetry_operations = self.get_symops(data)
            magmoms = {}

        oxi_states = self.parse_oxi_states(data)

        coord_to_species = OrderedDict()
        coord_to_magmoms = OrderedDict()

        def get_matching_coord(coord):
            keys = list(coord_to_species.keys())
            coords = np.array(keys)
            for op in self.symmetry_operations:
                c = op.operate(coord)
                inds = find_in_coord_list_pbc(coords, c,
                                              atol=self._site_tolerance)
                # cant use if inds, because python is dumb and np.array([0]) evaluates
                # to False
                if len(inds):
                    return keys[inds[0]]
            return False

        for i in range(len(data["_atom_site_label"])):
            try:
                # If site type symbol exists, use it. Otherwise, we use the
                # label.
                symbol = self._parse_symbol(data["_atom_site_type_symbol"][i])
                num_h = get_num_implicit_hydrogens(
                    data["_atom_site_type_symbol"][i])
            except KeyError:
                symbol = self._parse_symbol(data["_atom_site_label"][i])
                num_h = get_num_implicit_hydrogens(data["_atom_site_label"][i])
            if not symbol:
                continue

            if oxi_states is not None:
                o_s = oxi_states.get(symbol, 0)
                # use _atom_site_type_symbol if possible for oxidation state
                if "_atom_site_type_symbol" in data.data.keys():
                    oxi_symbol = data["_atom_site_type_symbol"][i]
                    o_s = oxi_states.get(oxi_symbol, o_s)
                try:
                    el = Specie(symbol, o_s)
                except:
                    el = DummySpecie(symbol, o_s)
            else:
                el = get_el_sp(symbol)

            x = str2float(data["_atom_site_fract_x"][i])
            y = str2float(data["_atom_site_fract_y"][i])
            z = str2float(data["_atom_site_fract_z"][i])
            magmom = magmoms.get(data["_atom_site_label"][i],
                                 np.array([0, 0, 0]))

            try:
                occu = str2float(data["_atom_site_occupancy"][i])
            except (KeyError, ValueError):
                occu = 1

            if occu > 0:
                coord = (x, y, z)
                match = get_matching_coord(coord)
                comp_d = {el: occu}
                if num_h > 0:
                    comp_d["H"] = num_h
                    self.errors.append("Structure has implicit hydrogens defined, "
                                       "parsed structure unlikely to be suitable for use "
                                       "in calculations unless hydrogens added.")
                comp = Composition(comp_d)
                if not match:
                    coord_to_species[coord] = comp
                    coord_to_magmoms[coord] = magmom
                else:
                    coord_to_species[match] += comp
                    # disordered magnetic not currently supported
                    coord_to_magmoms[match] = None

        sum_occu = [sum(c.values()) for c in coord_to_species.values()
                    if not set(c.elements) == {Element("O"), Element("H")}]
        if any([o > 1 for o in sum_occu]):
            msg = "Some occupancies (%s) sum to > 1! If they are within " \
                    "the tolerance, they will be rescaled." % str(sum_occu)
            warnings.warn(msg)
            self.errors.append(msg)

        allspecies = []
        allcoords = []
        allmagmoms = []
        allhydrogens = []

        # check to see if magCIF file is disordered
        if self.feature_flags["magcif"]:
            for k, v in coord_to_magmoms.items():
                if v is None:
                    # Proposed solution to this is to instead store magnetic
                    # moments as Specie 'spin' property, instead of site
                    # property, but this introduces ambiguities for end user
                    # (such as unintended use of `spin` and Specie will have
                    # fictious oxidation state).
                    raise NotImplementedError(
                        'Disordered magnetic structures not currently supported.')

        if coord_to_species.items():
            for comp, group in groupby(
                    sorted(list(coord_to_species.items()), key=lambda x: x[1]),
                    key=lambda x: x[1]):
                tmp_coords = [site[0] for site in group]
                tmp_magmom = [coord_to_magmoms[tmp_coord] for tmp_coord in
                              tmp_coords]

                if self.feature_flags["magcif"]:
                    coords, magmoms = self._unique_coords(tmp_coords,
                                                          magmoms_in=tmp_magmom,
                                                          lattice=lattice)
                else:
                    coords, magmoms = self._unique_coords(tmp_coords)

                if set(comp.elements) == {Element("O"), Element("H")}:
                    # O with implicit hydrogens
                    im_h = comp["H"]
                    species = Composition({"O": comp["O"]})
                else:
                    im_h = 0
                    species = comp

                allhydrogens.extend(len(coords) * [im_h])
                allcoords.extend(coords)
                allspecies.extend(len(coords) * [species])
                allmagmoms.extend(magmoms)

            # rescale occupancies if necessary
            for i, species in enumerate(allspecies):
                totaloccu = sum(species.values())
                if 1 < totaloccu <= self._occupancy_tolerance:
                    allspecies[i] = species / totaloccu

        if allspecies and len(allspecies) == len(allcoords) \
                and len(allspecies) == len(allmagmoms):
            site_properties = dict()
            if any(allhydrogens):
                assert len(allhydrogens) == len(allcoords)
                site_properties["implicit_hydrogens"] = allhydrogens

            if self.feature_flags["magcif"]:
                site_properties["magmom"] = allmagmoms

            if len(site_properties) == 0:
                site_properties = None

            struct = Structure(lattice, allspecies, allcoords,
                               site_properties=site_properties)

            struct = struct.get_sorted_structure()

            if primitive and self.feature_flags['magcif']:
                struct = struct.get_primitive_structure(use_site_props=True)
            elif primitive:
                struct = struct.get_primitive_structure()
                struct = struct.get_reduced_structure()

            return struct
207141
function getElData(el) {
  var id = el[elIdAttr];

  if (!id) {
    id = el[elIdAttr] = Guid.newGUID();
  }

  if (!elData[id]) {
    elData[id] = {};
  }

  return elData[id];
}
154346
def getdata(self, tree, location, force_string=False):
        """"""
        found = tree.xpath('%s/text()' % location)
        if not found:
            return None
        else:
            data = found[0]
        if force_string:
            return data
        if data == 'True':
            return True
        elif data == 'False':
            return False
        else:
            try:
                return int(data)
            except ValueError:
                try:
                    return float(data)
                except ValueError:
                    # It's a string
                    return data
24920
protected final void readEndElem()
        throws XMLStreamException
    {
        mTokenState = TOKEN_FULL_COALESCED; // will be read completely

        if (mElementStack.isEmpty()) {
            // Let's just offline this for clarity
            reportExtraEndElem();
            return; // never gets here
        }

        char c = (mInputPtr < mInputEnd) ? mInputBuffer[mInputPtr++]
            : getNextCharFromCurrent(SUFFIX_IN_CLOSE_ELEMENT);
        // Quick check first; missing name?
        if  (!isNameStartChar(c) && c != ':') {
            if (c <= CHAR_SPACE) { // space
                throwUnexpectedChar(c, "; missing element name?");
            }
            throwUnexpectedChar(c, "; expected an element name.");
        }

        /* Ok, now; good thing is we know exactly what to compare
         * against...
         */
        String expPrefix = mElementStack.getPrefix();
        String expLocalName = mElementStack.getLocalName();

        // Prefix to match?
        if (expPrefix != null && expPrefix.length() > 0) {
            int len = expPrefix.length();
            int i = 0;

            while (true){
                if (c != expPrefix.charAt(i)) {
                    reportWrongEndPrefix(expPrefix, expLocalName, i);
                    return; // never gets here
                }
                if (++i >= len) {
                    break;
                }
                c = (mInputPtr < mInputEnd) ? mInputBuffer[mInputPtr++]
                    : getNextCharFromCurrent(SUFFIX_IN_CLOSE_ELEMENT);
            }
            // And then we should get a colon
            c = (mInputPtr < mInputEnd) ? mInputBuffer[mInputPtr++]
                : getNextCharFromCurrent(SUFFIX_IN_CLOSE_ELEMENT);
            if (c != ':') {
                reportWrongEndPrefix(expPrefix, expLocalName, i);
                return;
            }
            c = (mInputPtr < mInputEnd) ? mInputBuffer[mInputPtr++]
                : getNextCharFromCurrent(SUFFIX_IN_CLOSE_ELEMENT);
        }

        // Ok, then, does the local name match?
        int len = expLocalName.length();
        int i = 0;
        
        while (true){
            if (c != expLocalName.charAt(i)) {
                // Not a match...
                reportWrongEndElem(expPrefix, expLocalName, i);
                return; // never gets here
            }
            if (++i >= len) {
                break;
            }
            c = (mInputPtr < mInputEnd) ? mInputBuffer[mInputPtr++]
                : getNextCharFromCurrent(SUFFIX_IN_CLOSE_ELEMENT);
        }

        // Let's see if end element still continues, however?
        c = (mInputPtr < mInputEnd) ? mInputBuffer[mInputPtr++]
            : getNextCharFromCurrent(SUFFIX_IN_CLOSE_ELEMENT);
        if (c <= CHAR_SPACE) {
            c = getNextInCurrAfterWS(SUFFIX_IN_CLOSE_ELEMENT, c);
        } else if (c == '>') {
            ;
        } else if (c == ':' || isNameChar(c)) {
            reportWrongEndElem(expPrefix, expLocalName, len);
        }

        // Ok, fine, match ok; now we just need the closing gt char.
        if (c != '>') {
            throwUnexpectedChar(c, SUFFIX_IN_CLOSE_ELEMENT+" Expected '>'.");
        }

        // Finally, let's let validator detect if things are ok
        int vld = mElementStack.validateEndElement();
        mVldContent = vld;
        mValidateText = (vld == XMLValidator.CONTENT_ALLOW_VALIDATABLE_TEXT);

        // Plus verify WFC that start and end tags came from same entity
        /* 13-Feb-2006, TSa: Are we about to close an element that
         *    started within a parent element?
         *    That's a GE/element nesting WFC violation...
         */
        if (mCurrDepth == mInputTopDepth) {
            handleGreedyEntityProblem(mInput);
        }
        --mCurrDepth;
    }