Return a structure from a canonical name
        Args:
            structure_name (str): canonical name of the structure
        Returns:
            Structure
481569
def get_structure_from_canonical_name(self, structure_name):
        
        return next((st for st in self.structures if st.canonical_name == structure_name), None)
385019
def _process_structures(structures):
        
        input_structures = structures
        structures = [input_structures[0]]
        for s in input_structures[1:]:
            prev = structures[-1]
            for i in range(len(s)):
                t = np.round(prev[i].frac_coords - s[i].frac_coords)
                if np.any(np.abs(t) > 0.5):
                    s.translate_sites([i], t, to_unit_cell=False)
            structures.append(s)
        return structures
955362
def structure_attrs_fromdict(self, obj, cl):
        # type: (Mapping[str, Any], Type[T]) -> T
        """"""
        # For public use.
        conv_obj = {}  # Start with a fresh dict, to ignore extra keys.
        dispatch = self._structure_func.dispatch
        for a in cl.__attrs_attrs__:  # type: ignore
            # We detect the type by metadata.
            type_ = a.type
            name = a.name

            try:
                val = obj[name]
            except KeyError:
                continue

            if name[0] == "_":
                name = name[1:]

            conv_obj[name] = (
                dispatch(type_)(val, type_) if type_ is not None else val
            )

        return cl(**conv_obj)
765568
def to_struct(model):
    
    model.validate()

    resp = {}
    for _, name, field in model.iterate_with_name():
        value = field.__get__(model)
        if value is None:
            continue

        value = field.to_struct(value)
        resp[name] = value
    return resp
202625
def struct(self, struct_name):
        
        if self.structs.has_key(struct_name):
            return self.structs[struct_name]
        else:
            raise RpcException(ERR_INVALID_PARAMS, "Unknown struct: '%s'", struct_name)
163245
def _translate_struct(inner_dict):
    """"""
    try:
        optional = inner_dict['optional'].items()
        required = inner_dict['required'].items()
    except KeyError as ex:
        raise DeserializationError("Missing key: {}".format(ex))
    except AttributeError as ex:
        raise DeserializationError(
            "Invalid Structure: {}".format(inner_dict))

    val_dict = {k: _translate(v) for k, v in required}
    val_dict.update({Optional(k): _translate(v) for k, v in optional})
    return val_dict
844422
def canonicalize(lig, preserve_bond_order=False):
    """"""
    atomorder = None
    # Get canonical atom order

    lig = pybel.ob.OBMol(lig.OBMol)
    if not preserve_bond_order:
        for bond in pybel.ob.OBMolBondIter(lig):
            if bond.GetBondOrder() != 1:
                bond.SetBondOrder(1)
    lig.DeleteData(pybel.ob.StereoData)
    lig = pybel.Molecule(lig)
    testcan = lig.write(format='can')
    try:
        pybel.readstring('can', testcan)
        reference = pybel.readstring('can', testcan)
    except IOError:
        testcan, reference = '', ''
    if testcan != '':
        reference.removeh()
        isomorphs = get_isomorphisms(reference, lig)  # isomorphs now holds all isomorphisms within the molecule
        if not len(isomorphs) == 0:
            smi_dict = {}
            smi_to_can = isomorphs[0]
            for x in smi_to_can:
                smi_dict[int(x[1]) + 1] = int(x[0]) + 1
            atomorder = [smi_dict[x + 1] for x in range(len(lig.atoms))]
        else:
            atomorder = None
    return atomorder
875404
def StructureAttribute(struct_info):
    """"""

    # Copy the template and add the gtype
    cls_dict = dict(_Structure.__dict__)
    cls = type(struct_info.name, _Structure.__bases__, cls_dict)
    cls.__module__ = struct_info.namespace
    cls.__gtype__ = PGType(struct_info.g_type)
    cls._size = struct_info.size
    cls._is_gtype_struct = struct_info.is_gtype_struct

    # Add methods
    for method_info in struct_info.get_methods():
        add_method(method_info, cls)

    # Add fields
    for field_info in struct_info.get_fields():
        field_name = escape_identifier(field_info.name)
        attr = FieldAttribute(field_name, field_info)
        setattr(cls, field_name, attr)

    return cls
1335005
def get_header(self, header_name):
        
        if header_name in self.headers:
            return self.headers[header_name]
        return self.add_header_name(header_name)
1095622
def from_dict(cls, d):
        
        s = Structure.from_dict(d)
        return cls(s, history=d["history"],
                   other_parameters=d.get("other_parameters", None))
574992
def lStruct(self):
        
        lStruct = []
        for k in self._dStruct['lorder']:
            k0, k1 = k.split('_')
            lStruct.append(self._dStruct['dObj'][k0][k1])
        return lStruct
747136
def structure(name_or_number)
      raise ArgumentError, "Invalid argument 'name_or_number'. Expected String or Integer, got #{name_or_number.class}." unless [String, Integer, Fixnum].include?(name_or_number.class)
      if name_or_number.is_a?(String)
        @structures.each do |s|
          return s if s.name == name_or_number
        end
      else
        @structures.each do |s|
          return s if s.number == name_or_number
        end
      end
      return nil
    end
689941
def parse_struct(type_name, body, name):
    '''
    '''
    type_name, name = type_name.strip(), name.strip()
    lines = [l.strip() for l in body.splitlines() if l.strip()]
    members = []

    for line in lines:
        m = match(variable_pat, line)
        if m is None:
            raise Exception('Cannot parse "{}" for "{}"'.format(line, name))

        tp, star, nm, count = [v.strip() if v else '' for v in m.groups()]
        members.append(VariableSpec(tp, star, nm, count))
    return StructSpec(type_name, [n.strip() for n in name.split(',')], members)
96513
def find_structure(self, filename_or_structure):
        
        try:
            if isinstance(filename_or_structure, str):
                s = Structure.from_file(filename_or_structure)
            elif isinstance(filename_or_structure, Structure):
                s = filename_or_structure
            else:
                raise MPRestError("Provide filename or Structure object.")
            payload = {'structure': json.dumps(s.as_dict(), cls=MontyEncoder)}
            response = self.session.post(
                '{}/find_structure'.format(self.preamble), data=payload
            )
            if response.status_code in [200, 400]:
                resp = json.loads(response.text, cls=MontyDecoder)
                if resp['valid_response']:
                    return resp['response']
                else:
                    raise MPRestError(resp["error"])
            raise MPRestError("REST error with status code {} and error {}"
                              .format(response.status_code, response.text))
        except Exception as ex:
            raise MPRestError(str(ex))
1340237
def read_structure(self, cls=Structure):
        """"""
        if self.ngroups != 1:
            raise NotImplementedError("In file %s: ngroups != 1" % self.path)

        return structure_from_ncdata(self, cls=cls)
1209712
def define_struct(defn):
    
    struct = parse_type(defn)
    ALL_TYPES[struct.name] = struct
    return struct
1054460
def getNodeByNameChain(node, chain_list):
    

    working_list = chain_list[:]
    working_list.reverse()
    current_node = node
    while len(working_list):
        current_name = working_list.pop()
        child_node = getNodeByName(current_node, current_name)
        if child_node is None:
            raise Exception("Unable to find child node %s" % current_name)
        current_node = child_node
    return current_node