Convert a molecular graph into a unique name

           This method is not sensitive to the order of the atoms in the graph.
518295
def _get_name(self, graph, group=None):
        
        if group is not None:
            graph = graph.get_subgraph(group, normalize=True)

        fingerprint = graph.fingerprint.tobytes()
        name = self.name_cache.get(fingerprint)
        if name is None:
            name = "NM%02i" % len(self.name_cache)
            self.name_cache[fingerprint] = name
        return name
1075021
def _clean_name(self, prefix, obj):
        """"""
        return '{}{}_{}'.format(prefix, self._uid(), ''.join(c for c in obj.name if c.isalnum()))
383279
def graph_simplify(G):
    
    spurs = []
    path_nodes = []
    for k, d in G.degree().iteritems():
        if d == 1:
            spurs.append(k)
        elif d == 2:
            path_nodes.append(k)

    logging.debug("Remove {0} spurs.".format(len(spurs)))
    G.remove_nodes_from(spurs)

    SG = G.subgraph(path_nodes)
    cc = nx.connected_components(SG)
    for c in cc:
        if len(c) == 1:
            continue
        c = set(c)
        neighbors = set()
        for x in c:
            neighbors |= set(G.neighbors(x))
        neighbors -= c
        newtag = list(c)[0] + "*"
        for n in neighbors:
            G.add_edge(newtag, n)
        G.remove_nodes_from(c)
    logging.debug("Contract {0} path nodes into {1} nodes.".\
                    format(len(path_nodes), len(cc)))
2326
def remove_edges(self, from_idx, to_idx, symmetric=False, copy=False):
    ''''''
    flat_inds = self._pairs.dot((self._num_vertices, 1))
    # convert to sorted order and flatten
    to_remove = (np.minimum(from_idx, to_idx) * self._num_vertices
                 + np.maximum(from_idx, to_idx))
    mask = np.in1d(flat_inds, to_remove, invert=True)
    res = self.copy() if copy else self
    res._pairs = res._pairs[mask]
    res._offdiag_mask = res._offdiag_mask[mask]
    return res
594822
def _unmangle_attribute_name(name):
    """"""

    # Python keywords cannot be used as variable names, an underscore should
    # be appended at the end of each of them when defining attribute names.
    name = _PYTHON_KEYWORD_MAP.get(name, name)

    # Attribute names are mangled with double underscore, as colon cannot
    # be used as a variable character symbol in Python. Single underscore is
    # used for substituting dash.
    name = name.replace('__', ':').replace('_', '-')

    return name
776939
def not_as_alias_handler(names_list):
    """"""
    list_ = list()
    for alias in names_list:
        list_.append(alias.name)
    return list_
145703
def clear(self):
        """"""
        self.title = None
        self.numbers = np.zeros(0, int)
        self.atom_types = [] # the atom_types in the second column, used to associate ff parameters
        self.charges = [] # ff charges
        self.names = [] # a name that is unique for the molecule composition and connectivity
        self.molecules = np.zeros(0, int) # a counter for each molecule
        self.bonds = np.zeros((0, 2), int)
        self.bends = np.zeros((0, 3), int)
        self.dihedrals = np.zeros((0, 4), int)
        self.impropers = np.zeros((0, 4), int)

        self.name_cache = {}
1358322
def canonicalize_name(name)
      if name == nil or name == SEP
        return name
      elsif name[0] == SEP[0]
        return name.split(/\/+/).join(SEP)
      else
        return SEP + name.split(/\/+/).join(SEP)
      end
    end
1027773
def get_unique_name(name='', collection=()):
    '''
    
    '''
    if name not in collection:
        return name
    i = 1
    while True:
        i += 1
        name2 = '%s_%s' % (name, i)
        if name2 not in collection:
            return name2
1190798
def _to_graphql_name(name):
        '''
        '''
        parts = name.split('_')
        return ''.join(parts[:1] + [p.title() for p in parts[1:]])
178917
def _process_name(name):
    """"""

    # Unescape HTML entities
    name = unescape(name)

    # Remove bracketed stuff on the end
    name = NG_RE.sub('', name).strip()  # Nomenclature groups
    name = END_RE.sub('', name).strip(', ')  # Words
    name = RATIO_RE.sub('', name).strip(', ')  # Ratios

    # Remove stuff off start
    name = START_RE.sub('', name).strip()

    # Remove balanced start and end brackets if none in between
    name = BRACKET_RE.sub('\g<1>', name)

    # Un-invert CAS style names
    comps = name.split(', ')
    if len(comps) == 2:
        if comps[1].endswith('-'):
            name = comps[0]
            name = '%s%s' % (comps[1], name)
    elif len(comps) > 2:
        name = comps[0]
        for i in range(1, len(comps)):
            if comps[i].endswith('-'):
                name = '%s%s' % (comps[i], name)
            else:
                name = '%s %s' % (name, comps[i])
    return name
420449
private static GeometryEncoder encoder(ITetrahedralChirality tc, Map<IAtom, Integer> atomToIndex) {

        IAtom[] ligands = tc.getLigands();

        int centre = atomToIndex.get(tc.getChiralAtom());
        int[] indices = new int[4];

        int offset = -1;

        for (int i = 0; i < ligands.length; i++) {
            indices[i] = atomToIndex.get(ligands[i]);
            if (indices[i] == centre) offset = i;
        }

        // convert clockwise/anticlockwise to -1/+1
        int parity = tc.getStereo() == CLOCKWISE ? -1 : 1;

        // now if any atom is the centre (indicating an implicit
        // hydrogen) we need to adjust the indicies and the parity
        if (offset >= 0) {

            // remove the 'implicit' central from the first 3 vertices
            for (int i = offset; i < indices.length - 1; i++) {
                indices[i] = indices[i + 1];
            }

            // we now take how many vertices we moved which is
            // 3 (last index) minus the index where we started. if the
            // value is odd we invert the parity (odd number of
            // inversions)
            if (Integer.lowestOneBit(3 - offset) == 0x1) parity *= -1;

            // trim the array to size we don't include the last (implicit)
            // vertex when checking the invariants
            indices = Arrays.copyOf(indices, indices.length - 1);
        }

        return new GeometryEncoder(centre, new BasicPermutationParity(indices), GeometricParity.valueOf(parity));
    }
538070
def bind_graph(graph=None):
    
    if graph is None:
        graph = Graph()
    for prefix, ns in GRAPH_BINDINGS.items():
        graph.bind(prefix, ns, True)
    return graph
295785
private IAtom getNextAtomWithAliphaticUnplacedNeigbors() {
        IBond bond;
        for (int f = 0; f < molecule.getBondCount(); f++) {
            bond = molecule.getBond(f);

            if (bond.getEnd().getFlag(CDKConstants.ISPLACED) && !bond.getBegin().getFlag(CDKConstants.ISPLACED)) {
                return bond.getEnd();
            }

            if (bond.getBegin().getFlag(CDKConstants.ISPLACED) && !bond.getEnd().getFlag(CDKConstants.ISPLACED)) {
                return bond.getBegin();
            }
        }
        return null;
    }
706806
def _clean_name(fname, data):
    
    for to_remove in dd.get_batches(data) + [dd.get_sample_name(data), data["sv"]["variantcaller"]]:
        for ext in ("-", "_"):
            if fname.startswith("%s%s" % (to_remove, ext)):
                fname = fname[len(to_remove) + len(ext):]
        if fname.startswith(to_remove):
            fname = fname[len(to_remove):]
    return fname
504211
function Molecule(classes) {
	var molecule = {
		className: '',
		atoms: [],
		pseudoTypes: [],
		mediaQueries: []
	};

	function stripMoleculeName() {
		molecule.className = _.remove(classes, function (name){
			return name[0] === '_';
		})[0];
	}

	function getAtoms() {
		molecule.atoms = classes.map(function (atom) { return Atom(atom); });
	}

	function getPseudoClassNames() {
		molecule.atoms.map(function (atom){ 
			if(atom.pseudo !== '' && !_.contains(molecule.pseudoTypes, atom.pseudo)){
				molecule.pseudoTypes.push(atom.pseudo);
			}
		});
	}

	function getMediaQueries() {
		molecule.atoms.map(function (atom){ 
			if(atom.mediaQuery !== '' && !_.contains(molecule.mediaQueries, atom.mediaQuery)){
				molecule.mediaQueries.push(atom.mediaQuery);
			}
		});
	}

	stripMoleculeName()
	getAtoms();
	getPseudoClassNames();
	getMediaQueries();

	return molecule;
}
819910
def from_dict(cls, d):
        
        m = Molecule.from_dict(d['molecule'])
        return cls(m, d['graphs'])