private IAtomContainer connectAtoms ( String inputInchi , IAtomContainer inputMolecule , Map < Integer , IAtom > inchiAtomsByPosition ) throws CDKException { String inchi = inputInchi ; inchi = inchi . substring ( inchi . indexOf ( ' ' ) + 1 ) ; inchi = inchi . substring ( inchi . indexOf ( ' ' ) + 1 ) ; String connections = inchi . substring ( 1 , inchi . indexOf ( ' ' ) ) ; Pattern connectionPattern = Pattern . compile ( "(-|\\(|\\)|,|([0-9])*)" ) ; Matcher match = connectionPattern . matcher ( connections ) ; Stack < IAtom > atomStack = new Stack < IAtom > ( ) ; IAtomContainer inchiMolGraph = inputMolecule . getBuilder ( ) . newInstance ( IAtomContainer . class ) ; boolean pop = false ; boolean push = true ; while ( match . find ( ) ) { String group = match . group ( ) ; push = true ; if ( ! group . isEmpty ( ) ) { if ( group . matches ( "[0-9]*" ) ) { IAtom atom = inchiAtomsByPosition . get ( Integer . valueOf ( group ) ) ; if ( ! inchiMolGraph . contains ( atom ) ) inchiMolGraph . addAtom ( atom ) ; IAtom prevAtom = null ; if ( atomStack . size ( ) != 0 ) { if ( pop ) { prevAtom = atomStack . pop ( ) ; } else { prevAtom = atomStack . get ( atomStack . size ( ) - 1 ) ; } IBond bond = inputMolecule . getBuilder ( ) . newInstance ( IBond . class , prevAtom , atom , IBond . Order . SINGLE ) ; inchiMolGraph . addBond ( bond ) ; } if ( push ) { atomStack . push ( atom ) ; } } else if ( group . equals ( "-" ) ) { pop = true ; push = true ; } else if ( group . equals ( "," ) ) { atomStack . pop ( ) ; pop = false ; push = false ; } else if ( group . equals ( "(" ) ) { pop = false ; push = true ; } else if ( group . equals ( ")" ) ) { atomStack . pop ( ) ; pop = true ; push = true ; } else { throw new CDKException ( "Unexpected token " + group + " in connection table encountered." ) ; } } } //put any unconnected atoms in the output as well for ( IAtom at : inchiAtomsByPosition . values ( ) ) { if ( ! inchiMolGraph . contains ( at ) ) inchiMolGraph . addAtom ( at ) ; } return inchiMolGraph ; }
Pops and pushes its ways through the InChI connection table to build up a simple molecule .