idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
29,000
public Map relevantCycles ( ) { Map result = new HashMap ( ) ; for ( SimpleCycleBasis subgraphBase : subgraphBases ) { SimpleCycleBasis cycleBasis = subgraphBase ; result . putAll ( cycleBasis . relevantCycles ( ) ) ; } return result ; }
Returns the essential cycles of this cycle basis . A relevant cycle is contained in some minimum cycle basis of a graph .
29,001
public void setup ( IReaction reaction , Rectangle screen ) { this . setScale ( reaction ) ; Rectangle2D bounds = BoundsCalculator . calculateBounds ( reaction ) ; this . modelCenter = new Point2d ( bounds . getCenterX ( ) , bounds . getCenterY ( ) ) ; this . drawCenter = new Point2d ( screen . getCenterX ( ) , screen . getCenterY ( ) ) ; this . setup ( ) ; }
Setup the transformations necessary to draw this Reaction .
29,002
public void setScale ( IReaction reaction ) { double bondLength = AverageBondLengthCalculator . calculateAverageBondLength ( reaction ) ; double scale = this . calculateScaleForBondLength ( bondLength ) ; this . rendererModel . getParameter ( Scale . class ) . setValue ( scale ) ; }
Set the scale for an IReaction . It calculates the average bond length of the model and calculates the multiplication factor to transform this to the bond length that is set in the RendererModel .
29,003
public void paint ( IReaction reaction , IDrawVisitor drawVisitor , Rectangle2D bounds , boolean resetCenter ) { Rectangle2D modelBounds = BoundsCalculator . calculateBounds ( reaction ) ; this . setupTransformToFit ( bounds , modelBounds , AverageBondLengthCalculator . calculateAverageBondLength ( reaction ) , resetCenter ) ; IRenderingElement diagram = this . generateDiagram ( reaction ) ; this . paint ( drawVisitor , diagram ) ; }
Paint a reaction .
29,004
private static boolean normal ( int element , int charge , int valence ) { switch ( element ) { case CARBON : if ( charge == - 1 || charge == + 1 ) return valence == 3 ; return charge == 0 && valence == 4 ; case NITROGEN : case PHOSPHORUS : case ARSENIC : if ( charge == - 1 ) return valence == 2 ; if ( charge == + 1 ) return valence == 4 ; return charge == 0 && ( valence == 3 || ( valence == 5 && element == NITROGEN ) ) ; case OXYGEN : if ( charge == + 1 ) return valence == 3 ; return charge == 0 && valence == 2 ; case SULPHUR : case SELENIUM : if ( charge == + 1 ) return valence == 3 ; return charge == 0 && ( valence == 2 || valence == 4 || valence == 6 ) ; } return false ; }
The element has normal valence for the specified charge .
29,005
public boolean matches ( IAtomContainer atomContainer , boolean forceInitialization ) throws CDKException { if ( this . atomContainer == atomContainer ) { if ( forceInitialization ) initializeMolecule ( ) ; } else { this . atomContainer = atomContainer ; initializeMolecule ( ) ; } if ( query . getAtomCount ( ) == 1 ) { IQueryAtom queryAtom = ( IQueryAtom ) query . getAtom ( 0 ) ; mappings = new ArrayList < int [ ] > ( ) ; for ( int i = 0 ; i < atomContainer . getAtomCount ( ) ; i ++ ) { if ( queryAtom . matches ( atomContainer . getAtom ( i ) ) ) { mappings . add ( new int [ ] { i } ) ; } } } else { mappings = FluentIterable . from ( VentoFoggia . findSubstructure ( query ) . matchAll ( atomContainer ) . filter ( new SmartsStereoMatch ( query , atomContainer ) ) ) . toList ( ) ; } return ! mappings . isEmpty ( ) ; }
Perform a SMARTS match and check whether the query is present in the target molecule . This function simply checks whether the query pattern matches the specified molecule . However the function will also internally save the mapping of query atoms to the target molecule
29,006
public List < List < Integer > > getMatchingAtoms ( ) { List < List < Integer > > matched = new ArrayList < List < Integer > > ( mappings . size ( ) ) ; for ( int [ ] mapping : mappings ) matched . add ( Ints . asList ( mapping ) ) ; return matched ; }
Get the atoms in the target molecule that match the query pattern . Since there may be multiple matches the return value is a List of List objects . Each List object contains the indices of the atoms in the target molecule that match the query pattern
29,007
public List < List < Integer > > getUniqueMatchingAtoms ( ) { List < List < Integer > > matched = new ArrayList < List < Integer > > ( mappings . size ( ) ) ; Set < BitSet > atomSets = Sets . newHashSetWithExpectedSize ( mappings . size ( ) ) ; for ( int [ ] mapping : mappings ) { BitSet atomSet = new BitSet ( ) ; for ( int x : mapping ) atomSet . set ( x ) ; if ( atomSets . add ( atomSet ) ) matched . add ( Ints . asList ( mapping ) ) ; } return matched ; }
Get the atoms in the target molecule that match the query pattern . Since there may be multiple matches the return value is a List of List objects . Each List object contains the unique set of indices of the atoms in the target molecule that match the query pattern
29,008
private void initializeMolecule ( ) throws CDKException { SmartsMatchers . prepare ( atomContainer , true ) ; try { if ( ! skipAromaticity ) { aromaticity . apply ( atomContainer ) ; } } catch ( CDKException e ) { logger . debug ( e . toString ( ) ) ; throw new CDKException ( e . toString ( ) , e ) ; } }
Prepare the target molecule for analysis . We perform ring perception and aromaticity detection and set up the appropriate properties . Right now this function is called each time we need to do a query and this is inefficient .
29,009
public boolean matches ( IBond bond ) { bond = BondRef . deref ( bond ) ; if ( bond instanceof PharmacophoreAngleBond ) { PharmacophoreAngleBond pbond = ( PharmacophoreAngleBond ) bond ; double bondLength = round ( pbond . getBondLength ( ) , 2 ) ; return bondLength >= lower && bondLength <= upper ; } else return false ; }
Checks whether the query angle constraint matches a target distance .
29,010
public static int getAtomCount ( IRingSet set ) { int count = 0 ; for ( IAtomContainer atomContainer : set . atomContainers ( ) ) { count += atomContainer . getAtomCount ( ) ; } return count ; }
Return the total number of atoms over all the rings in the colllection .
29,011
public static int getBondCount ( IRingSet set ) { int count = 0 ; for ( IAtomContainer atomContainer : set . atomContainers ( ) ) { count += atomContainer . getBondCount ( ) ; } return count ; }
Return the total number of bonds over all the rings in the colllection .
29,012
public static List < IAtomContainer > getAllAtomContainers ( IRingSet set ) { List < IAtomContainer > atomContainerList = new ArrayList < IAtomContainer > ( ) ; for ( IAtomContainer atomContainer : set . atomContainers ( ) ) { atomContainerList . add ( atomContainer ) ; } return atomContainerList ; }
Returns all the AtomContainer s in a RingSet .
29,013
public static void sort ( IRingSet ringSet ) { List < IRing > ringList = new ArrayList < IRing > ( ) ; for ( IAtomContainer atomContainer : ringSet . atomContainers ( ) ) { ringList . add ( ( IRing ) atomContainer ) ; } Collections . sort ( ringList , new RingSizeComparator ( RingSizeComparator . SMALL_FIRST ) ) ; ringSet . removeAllAtomContainers ( ) ; for ( IAtomContainer aRingList : ringList ) ringSet . addAtomContainer ( aRingList ) ; }
Sorts the rings in the set by size . The smallest ring comes first .
29,014
public static IRing getHeaviestRing ( IRingSet ringSet , IBond bond ) { IRingSet rings = ringSet . getRings ( bond ) ; IRing ring = null ; int maxOrderSum = 0 ; for ( Object ring1 : rings . atomContainers ( ) ) { if ( maxOrderSum < ( ( IRing ) ring1 ) . getBondOrderSum ( ) ) { ring = ( IRing ) ring1 ; maxOrderSum = ring . getBondOrderSum ( ) ; } } return ring ; }
We define the heaviest ring as the one with the highest number of double bonds . Needed for example for the placement of in - ring double bonds .
29,015
public static boolean ringAlreadyInSet ( IRing newRing , IRingSet ringSet ) { IRing ring ; int equalCount ; boolean equals ; for ( int f = 0 ; f < ringSet . getAtomContainerCount ( ) ; f ++ ) { equals = false ; equalCount = 0 ; ring = ( IRing ) ringSet . getAtomContainer ( f ) ; if ( ring . getBondCount ( ) == newRing . getBondCount ( ) ) { for ( IBond newBond : newRing . bonds ( ) ) { for ( IBond bond : ring . bonds ( ) ) { if ( newBond . equals ( bond ) ) { equals = true ; equalCount ++ ; break ; } } if ( ! equals ) break ; } } if ( equalCount == ring . getBondCount ( ) ) { return true ; } } return false ; }
Checks - and returns true - if a certain ring is already stored in the ringset . This is not a test for equality of Ring objects but compares all Bond objects of the ring .
29,016
public static void markAromaticRings ( IRingSet ringset ) { for ( IAtomContainer atomContainer : ringset . atomContainers ( ) ) { RingManipulator . markAromaticRings ( ( IRing ) atomContainer ) ; } }
Iterates over the rings in the ring set and marks the ring aromatic if all atoms and all bonds are aromatic .
29,017
public IAtomContainer generate ( ) throws CDKException { boolean structureFound = false ; boolean bondFormed ; double order ; double max , cmax1 , cmax2 ; int iteration = 0 ; IAtom partner ; IAtom atom ; do { iteration ++ ; atomContainer . removeAllElectronContainers ( ) ; do { bondFormed = false ; for ( int f = 0 ; f < atomContainer . getAtomCount ( ) ; f ++ ) { atom = atomContainer . getAtom ( f ) ; if ( ! satCheck . isSaturated ( atom , atomContainer ) ) { partner = getAnotherUnsaturatedNode ( atom ) ; if ( partner != null ) { cmax1 = satCheck . getCurrentMaxBondOrder ( atom , atomContainer ) ; cmax2 = satCheck . getCurrentMaxBondOrder ( partner , atomContainer ) ; max = Math . min ( cmax1 , cmax2 ) ; order = Math . min ( Math . max ( 1.0 , random . nextInt ( ( int ) Math . round ( max ) ) ) , 3.0 ) ; logger . debug ( "Forming bond of order " , order ) ; atomContainer . addBond ( atomContainer . getBuilder ( ) . newInstance ( IBond . class , atom , partner , BondManipulator . createBondOrder ( order ) ) ) ; bondFormed = true ; } } } } while ( bondFormed ) ; if ( ConnectivityChecker . isConnected ( atomContainer ) && satCheck . allSaturated ( atomContainer ) ) { structureFound = true ; } } while ( ! structureFound && iteration < 20 ) ; logger . debug ( "Structure found after #iterations: " , iteration ) ; return atomContainer . getBuilder ( ) . newInstance ( IAtomContainer . class , atomContainer ) ; }
Generates a random structure based on the atoms in the given IAtomContainer .
29,018
private IAtom getAnotherUnsaturatedNode ( IAtom exclusionAtom ) throws CDKException { IAtom atom ; int next = random . nextInt ( atomContainer . getAtomCount ( ) ) ; for ( int f = next ; f < atomContainer . getAtomCount ( ) ; f ++ ) { atom = atomContainer . getAtom ( f ) ; if ( ! satCheck . isSaturated ( atom , atomContainer ) && ! exclusionAtom . equals ( atom ) && ! atomContainer . getConnectedAtomsList ( exclusionAtom ) . contains ( atom ) ) { return atom ; } } for ( int f = 0 ; f < next ; f ++ ) { atom = atomContainer . getAtom ( f ) ; if ( ! satCheck . isSaturated ( atom , atomContainer ) && ! exclusionAtom . equals ( atom ) && ! atomContainer . getConnectedAtomsList ( exclusionAtom ) . contains ( atom ) ) { return atom ; } } return null ; }
Gets the AnotherUnsaturatedNode attribute of the SingleStructureRandomGenerator object .
29,019
public boolean isOK ( IAtomContainer m ) throws CDKException { IRingSet rs = allRingsFinder . findAllRings ( m , 7 ) ; storeRingSystem ( m , rs ) ; boolean StructureOK = this . isStructureOK ( m ) ; IRingSet irs = this . removeExtraRings ( m ) ; if ( irs == null ) throw new CDKException ( "error in AllRingsFinder.findAllRings" ) ; int count = this . getBadCount ( m , irs ) ; return StructureOK && count == 0 ; }
Determines if according to the algorithms implemented in this class the given AtomContainer has properly distributed double bonds .
29,020
public IAtomContainer fixAromaticBondOrders ( IAtomContainer atomContainer ) throws CDKException { for ( IBond bond : atomContainer . bonds ( ) ) { if ( bond . isAromatic ( ) && bond . getOrder ( ) == IBond . Order . UNSET ) bond . setOrder ( IBond . Order . SINGLE ) ; } IRingSet rs = allRingsFinder . findAllRings ( atomContainer , 7 ) ; storeRingSystem ( atomContainer , rs ) ; IRingSet ringSet ; ringSet = removeExtraRings ( atomContainer ) ; if ( ringSet == null ) throw new CDKException ( "failure in AllRingsFinder.findAllRings" ) ; List < List < List < String > > > MasterList = new ArrayList < List < List < String > > > ( ) ; this . FixPyridineNOxides ( atomContainer , ringSet ) ; for ( int i = 0 ; i <= ringSet . getAtomContainerCount ( ) - 1 ; i ++ ) { IRing ring = ( IRing ) ringSet . getAtomContainer ( i ) ; if ( ring . getAtomCount ( ) == 5 ) { fiveMemberedRingPossibilities ( atomContainer , ring , MasterList ) ; } else if ( ring . getAtomCount ( ) == 6 ) { sixMemberedRingPossibilities ( atomContainer , ring , MasterList ) ; } else if ( ring . getAtomCount ( ) == 7 ) { sevenMemberedRingPossibilities ( atomContainer , ring , MasterList ) ; } else { logger . debug ( "Found ring of size: " + ring . getAtomCount ( ) ) ; } } IAtomContainerSet som = atomContainer . getBuilder ( ) . newInstance ( IAtomContainerSet . class ) ; int [ ] choices ; choices = new int [ MasterList . size ( ) ] ; if ( MasterList . size ( ) > 0 ) { IAtomContainer iAtomContainer = loop ( System . currentTimeMillis ( ) , atomContainer , 0 , MasterList , choices , som ) ; if ( iAtomContainer != null ) return iAtomContainer ; } int mincount = 99999999 ; int best = - 1 ; for ( int i = 0 ; i <= som . getAtomContainerCount ( ) - 1 ; i ++ ) { IAtomContainer mol = som . getAtomContainer ( i ) ; ringSet = removeExtraRings ( mol ) ; if ( ringSet == null ) continue ; int count = getBadCount ( mol , ringSet ) ; if ( count < mincount ) { mincount = count ; best = i ; } } if ( som . getAtomContainerCount ( ) > 0 ) return som . getAtomContainer ( best ) ; return atomContainer ; }
Added missing bond orders based on atom type information .
29,021
private IRingSet removeExtraRings ( IAtomContainer m ) { try { IRingSet rs = Cycles . sssr ( m ) . toRingSet ( ) ; iloop : for ( int i = 0 ; i <= rs . getAtomContainerCount ( ) - 1 ; i ++ ) { IRing r = ( IRing ) rs . getAtomContainer ( i ) ; if ( r . getAtomCount ( ) > 7 || r . getAtomCount ( ) < 5 ) { rs . removeAtomContainer ( i ) ; i -- ; continue iloop ; } for ( int j = 0 ; j <= r . getAtomCount ( ) - 1 ; j ++ ) { if ( r . getAtom ( j ) . getHybridization ( ) == CDKConstants . UNSET || ! ( r . getAtom ( j ) . getHybridization ( ) == Hybridization . SP2 || r . getAtom ( j ) . getHybridization ( ) == Hybridization . PLANAR3 ) ) { rs . removeAtomContainer ( i ) ; i -- ; continue iloop ; } } } return rs ; } catch ( Exception e ) { return m . getBuilder ( ) . newInstance ( IRingSet . class ) ; } }
Remove rings .
29,022
private void storeRingSystem ( IAtomContainer mol , IRingSet ringSet ) { listOfRings = new ArrayList < Integer [ ] > ( ) ; for ( int r = 0 ; r < ringSet . getAtomContainerCount ( ) ; ++ r ) { IRing ring = ( IRing ) ringSet . getAtomContainer ( r ) ; Integer [ ] bondNumbers = new Integer [ ring . getBondCount ( ) ] ; for ( int i = 0 ; i < ring . getBondCount ( ) ; ++ i ) bondNumbers [ i ] = mol . indexOf ( ring . getBond ( i ) ) ; listOfRings . add ( bondNumbers ) ; } }
Stores an IRingSet corresponding to a AtomContainer using the bond numbers .
29,023
public void setParameters ( Object [ ] params ) throws CDKException { if ( params . length != 1 ) throw new CDKException ( "ElementRule expects one parameters" ) ; if ( ! ( params [ 0 ] == null || params [ 0 ] instanceof MolecularFormulaRange ) ) throw new CDKException ( "The parameter must be of type MolecularFormulaExpand" ) ; mfRange = ( MolecularFormulaRange ) params [ 0 ] ; }
Sets the parameters attribute of the ElementRule object .
29,024
private void ensureDefaultOccurElements ( IChemObjectBuilder builder ) { if ( mfRange == null ) { String [ ] elements = new String [ ] { "C" , "H" , "O" , "N" , "Si" , "P" , "S" , "F" , "Cl" , "Br" , "I" , "Sn" , "B" , "Pb" , "Tl" , "Ba" , "In" , "Pd" , "Pt" , "Os" , "Ag" , "Zr" , "Se" , "Zn" , "Cu" , "Ni" , "Co" , "Fe" , "Cr" , "Ti" , "Ca" , "K" , "Al" , "Mg" , "Na" , "Ce" , "Hg" , "Au" , "Ir" , "Re" , "W" , "Ta" , "Hf" , "Lu" , "Yb" , "Tm" , "Er" , "Ho" , "Dy" , "Tb" , "Gd" , "Eu" , "Sm" , "Pm" , "Nd" , "Pr" , "La" , "Cs" , "Xe" , "Te" , "Sb" , "Cd" , "Rh" , "Ru" , "Tc" , "Mo" , "Nb" , "Y" , "Sr" , "Rb" , "Kr" , "As" , "Ge" , "Ga" , "Mn" , "V" , "Sc" , "Ar" , "Ne" , "Be" , "Li" , "Tl" , "Pb" , "Bi" , "Po" , "At" , "Rn" , "Fr" , "Ra" , "Ac" , "Th" , "Pa" , "U" , "Np" , "Pu" } ; mfRange = new MolecularFormulaRange ( ) ; for ( int i = 0 ; i < elements . length ; i ++ ) mfRange . addIsotope ( builder . newInstance ( IIsotope . class , elements [ i ] ) , 0 , 50 ) ; } }
Initiate the MolecularFormulaExpand with the maximum and minimum occurrence of the Elements . In this case all elements of the periodic table are loaded .
29,025
public int [ ] vertexColor ( ) { int [ ] result = colors ; if ( result == null ) { synchronized ( this ) { result = colors ; if ( result == null ) { colors = result = buildVertexColor ( ) ; } } } return result ; }
Lazily build an indexed lookup of vertex color . The vertex color indicates which cycle a given vertex belongs . If a vertex belongs to more then one cycle it is colored 0 . If a vertex belongs to no cycle it is colored - 1 .
29,026
static BitSet xor ( BitSet x , BitSet y ) { BitSet z = copy ( x ) ; z . xor ( y ) ; return z ; }
XOR the to bit sets together and return the result . Neither input is modified .
29,027
static BitSet and ( BitSet x , BitSet y ) { BitSet z = copy ( x ) ; z . and ( y ) ; return z ; }
AND the to bit sets together and return the result . Neither input is modified .
29,028
static BitSet copy ( BitSet org ) { BitSet cpy = ( BitSet ) org . clone ( ) ; return cpy ; }
Copy the original bit set .
29,029
public Map < String , String > readAtomTypeMappings ( ) { Map < String , String > mappings = null ; try { parser . setFeature ( "http://xml.org/sax/features/validation" , false ) ; logger . info ( "Deactivated validation" ) ; } catch ( SAXException exception ) { logger . warn ( "Cannot deactivate validation: " , exception . getMessage ( ) ) ; logger . debug ( exception ) ; } OWLAtomTypeMappingHandler handler = new OWLAtomTypeMappingHandler ( ) ; parser . setContentHandler ( handler ) ; try { parser . parse ( new InputSource ( input ) ) ; mappings = handler . getAtomTypeMappings ( ) ; } catch ( IOException exception ) { logger . error ( "IOException: " , exception . getMessage ( ) ) ; logger . debug ( exception ) ; } catch ( SAXException saxe ) { logger . error ( "SAXException: " , saxe . getMessage ( ) ) ; logger . debug ( saxe ) ; } return mappings == null ? new HashMap < String , String > ( ) : mappings ; }
Reads the atom type mappings from the data file .
29,030
private void loadTemplates ( ) throws CDKException { try ( InputStream gin = getClass ( ) . getResourceAsStream ( TEMPLATE_PATH ) ; InputStream in = new GZIPInputStream ( gin ) ; IteratingSDFReader sdfr = new IteratingSDFReader ( in , builder ) ) { while ( sdfr . hasNext ( ) ) { final IAtomContainer mol = sdfr . next ( ) ; addTemplateMol ( mol ) ; } } catch ( IOException e ) { throw new CDKException ( "Could not load ring templates" , e ) ; } }
Load ring template
29,031
public void mapTemplates ( IAtomContainer mol , int numberOfRingAtoms ) throws CDKException , CloneNotSupportedException { if ( templates . isEmpty ( ) ) loadTemplates ( ) ; IAtomContainer best = null ; Map < IChemObject , IChemObject > bestMap = null ; IAtomContainer secondBest = null ; Map < IChemObject , IChemObject > secondBestMap = null ; for ( int i = 0 ; i < templates . size ( ) ; i ++ ) { IAtomContainer query = queries . get ( i ) ; if ( query . getAtomCount ( ) != mol . getAtomCount ( ) ) { continue ; } Mappings mappings = patterns . get ( i ) . matchAll ( mol ) ; for ( Map < IChemObject , IChemObject > map : mappings . toAtomBondMap ( ) ) { if ( isExactMatch ( query , map ) ) { assignCoords ( query , map ) ; return ; } else if ( query . getBondCount ( ) == mol . getBondCount ( ) ) { best = query ; bestMap = new HashMap < > ( map ) ; } else { secondBest = query ; secondBestMap = new HashMap < > ( map ) ; } } } if ( best != null ) { assignCoords ( best , bestMap ) ; } else if ( secondBest != null ) { assignCoords ( secondBest , secondBestMap ) ; } else { logger . warn ( "Maybe RingTemplateError!" ) ; } }
Checks if one of the loaded templates is a substructure in the given Molecule . If so it assigns the coordinates from the template to the respective atoms in the Molecule .
29,032
public boolean isSaturated ( IAtom atom , IAtomContainer ac ) throws CDKException { IAtomType [ ] atomTypes = getAtomTypeFactory ( atom . getBuilder ( ) ) . getAtomTypes ( atom . getSymbol ( ) ) ; if ( atomTypes . length == 0 ) return true ; double bondOrderSum = ac . getBondOrderSum ( atom ) ; IBond . Order maxBondOrder = ac . getMaximumBondOrder ( atom ) ; Integer hcount = atom . getImplicitHydrogenCount ( ) == CDKConstants . UNSET ? 0 : atom . getImplicitHydrogenCount ( ) ; Integer charge = atom . getFormalCharge ( ) == CDKConstants . UNSET ? 0 : atom . getFormalCharge ( ) ; try { logger . debug ( "*** Checking saturation of atom " , atom . getSymbol ( ) , "" + ac . indexOf ( atom ) + " ***" ) ; logger . debug ( "bondOrderSum: " + bondOrderSum ) ; logger . debug ( "maxBondOrder: " + maxBondOrder ) ; logger . debug ( "hcount: " + hcount ) ; } catch ( Exception exc ) { logger . debug ( exc ) ; } for ( int f = 0 ; f < atomTypes . length ; f ++ ) { if ( bondOrderSum - charge + hcount == atomTypes [ f ] . getBondOrderSum ( ) && ! BondManipulator . isHigherOrder ( maxBondOrder , atomTypes [ f ] . getMaxBondOrder ( ) ) ) { logger . debug ( "*** Good ! ***" ) ; return true ; } } logger . debug ( "*** Bad ! ***" ) ; return false ; }
Checks whether an Atom is saturated by comparing it with known AtomTypes .
29,033
public double getCurrentMaxBondOrder ( IAtom atom , IAtomContainer ac ) throws CDKException { IAtomType [ ] atomTypes = getAtomTypeFactory ( atom . getBuilder ( ) ) . getAtomTypes ( atom . getSymbol ( ) ) ; if ( atomTypes . length == 0 ) return 0 ; double bondOrderSum = ac . getBondOrderSum ( atom ) ; Integer hcount = atom . getImplicitHydrogenCount ( ) == CDKConstants . UNSET ? 0 : atom . getImplicitHydrogenCount ( ) ; double max = 0 ; double current = 0 ; for ( int f = 0 ; f < atomTypes . length ; f ++ ) { current = hcount + bondOrderSum ; if ( atomTypes [ f ] . getBondOrderSum ( ) - current > max ) { max = atomTypes [ f ] . getBondOrderSum ( ) - current ; } } return max ; }
Returns the currently maximum formable bond order for this atom .
29,034
public void unsaturate ( IAtomContainer atomContainer ) { for ( IBond bond : atomContainer . bonds ( ) ) bond . setOrder ( Order . SINGLE ) ; }
Resets the bond orders of all atoms to 1 . 0 .
29,035
public void unsaturateBonds ( IAtomContainer container ) { for ( IBond bond : container . bonds ( ) ) bond . setOrder ( Order . SINGLE ) ; }
Resets the bond order of the Bond to 1 . 0 .
29,036
public void newSaturate ( IAtomContainer atomContainer ) throws CDKException { logger . info ( "Saturating atomContainer by adjusting bond orders..." ) ; boolean allSaturated = allSaturated ( atomContainer ) ; if ( ! allSaturated ) { IBond [ ] bonds = new IBond [ atomContainer . getBondCount ( ) ] ; for ( int i = 0 ; i < bonds . length ; i ++ ) bonds [ i ] = atomContainer . getBond ( i ) ; boolean succeeded = newSaturate ( bonds , atomContainer ) ; for ( int i = 0 ; i < bonds . length ; i ++ ) { if ( bonds [ i ] . getOrder ( ) == IBond . Order . DOUBLE && bonds [ i ] . getFlag ( CDKConstants . ISAROMATIC ) && ( bonds [ i ] . getBegin ( ) . getSymbol ( ) . equals ( "N" ) && bonds [ i ] . getEnd ( ) . getSymbol ( ) . equals ( "N" ) ) ) { int atomtohandle = 0 ; if ( bonds [ i ] . getBegin ( ) . getSymbol ( ) . equals ( "N" ) ) atomtohandle = 1 ; List < IBond > bondstohandle = atomContainer . getConnectedBondsList ( bonds [ i ] . getAtom ( atomtohandle ) ) ; for ( int k = 0 ; k < bondstohandle . size ( ) ; k ++ ) { IBond bond = bondstohandle . get ( k ) ; if ( bond . getOrder ( ) == IBond . Order . SINGLE && bond . getFlag ( CDKConstants . ISAROMATIC ) ) { bond . setOrder ( IBond . Order . DOUBLE ) ; bonds [ i ] . setOrder ( IBond . Order . SINGLE ) ; break ; } } } } if ( ! succeeded ) { throw new CDKException ( "Could not saturate this atomContainer!" ) ; } } }
Saturates a molecule by setting appropriate bond orders . This method is known to fail especially on pyrolle - like compounds . Consider using import org . openscience . cdk . smiles . DeduceBondSystemTool which should work better
29,037
public boolean newSaturate ( IBond [ ] bonds , IAtomContainer atomContainer ) throws CDKException { logger . debug ( "Saturating bond set of size: " + bonds . length ) ; boolean bondsAreFullySaturated = true ; if ( bonds . length > 0 ) { IBond bond = bonds [ 0 ] ; int leftBondCount = bonds . length - 1 ; IBond [ ] leftBonds = new IBond [ leftBondCount ] ; System . arraycopy ( bonds , 1 , leftBonds , 0 , leftBondCount ) ; if ( isUnsaturated ( bond , atomContainer ) ) { if ( leftBondCount > 0 ) { logger . debug ( "Recursing with unsaturated bond with #bonds: " + leftBondCount ) ; bondsAreFullySaturated = newSaturate ( leftBonds , atomContainer ) && ! isUnsaturated ( bond , atomContainer ) ; } else { bondsAreFullySaturated = false ; } if ( ! bondsAreFullySaturated ) { logger . debug ( "First try did not work..." ) ; boolean couldSaturate = newSaturate ( bond , atomContainer ) ; if ( couldSaturate ) { if ( leftBondCount > 0 ) { logger . debug ( "Recursing with saturated bond with #bonds: " + leftBondCount ) ; bondsAreFullySaturated = newSaturate ( leftBonds , atomContainer ) ; } else { bondsAreFullySaturated = true ; } } else { bondsAreFullySaturated = false ; } } } else if ( isSaturated ( bond , atomContainer ) ) { logger . debug ( "This bond is already saturated." ) ; if ( leftBondCount > 0 ) { logger . debug ( "Recursing with #bonds: " + leftBondCount ) ; bondsAreFullySaturated = newSaturate ( leftBonds , atomContainer ) ; } else { bondsAreFullySaturated = true ; } } else { logger . debug ( "Cannot saturate this bond" ) ; if ( leftBondCount > 0 ) { logger . debug ( "Recursing with saturated bond with #bonds: " + leftBondCount ) ; bondsAreFullySaturated = newSaturate ( leftBonds , atomContainer ) && ! isUnsaturated ( bond , atomContainer ) ; } else { bondsAreFullySaturated = ! isUnsaturated ( bond , atomContainer ) ; } } } logger . debug ( "Is bond set fully saturated?: " + bondsAreFullySaturated ) ; logger . debug ( "Returning to level: " + ( bonds . length + 1 ) ) ; return bondsAreFullySaturated ; }
Saturates a set of Bonds in an AtomContainer . This method is known to fail especially on pyrolle - like compounds . Consider using import org . openscience . cdk . smiles . DeduceBondSystemTool which should work better
29,038
public boolean setMultiplier ( IAtomContainer container , Double multiplier ) { for ( int i = 0 ; i < atomContainers . length ; i ++ ) { if ( atomContainers [ i ] == container ) { multipliers [ i ] = multiplier ; return true ; } } return false ; }
Sets the coefficient of a AtomContainer to a given value .
29,039
public static void createIDs ( IChemObject chemObject ) { if ( chemObject == null ) return ; resetCounters ( ) ; if ( chemObject instanceof IAtomContainer ) { createIDsForAtomContainer ( ( IAtomContainer ) chemObject , null ) ; } else if ( chemObject instanceof IAtomContainerSet ) { createIDsForAtomContainerSet ( ( IAtomContainerSet ) chemObject , null ) ; } else if ( chemObject instanceof IReaction ) { createIDsForReaction ( ( IReaction ) chemObject , null ) ; } else if ( chemObject instanceof IReactionSet ) { createIDsForReactionSet ( ( IReactionSet ) chemObject , null ) ; } else if ( chemObject instanceof IChemFile ) { createIDsForChemFile ( ( IChemFile ) chemObject , null ) ; } else if ( chemObject instanceof IChemSequence ) { createIDsForChemSequence ( ( IChemSequence ) chemObject , null ) ; } else if ( chemObject instanceof IChemModel ) { createIDsForChemModel ( ( IChemModel ) chemObject , null ) ; } }
Labels the Atom s and Bond s in the AtomContainer using the a1 a2 b1 b2 scheme often used in CML . Supports IAtomContainer IAtomContainerSet IChemFile IChemModel IChemSequence IReaction IReactionSet and derived interfaces .
29,040
private static void resetCounters ( ) { atomCount = 0 ; bondCount = 0 ; atomContainerCount = 0 ; atomContainerSetCount = 0 ; reactionCount = 0 ; reactionSetCount = 0 ; chemModelCount = 0 ; chemSequenceCount = 0 ; chemFileCount = 0 ; }
Reset the counters so that we keep generating simple IDs within single chem object or a set of them
29,041
private static int setID ( String prefix , int identifier , IChemObject object , List < String > tabuList ) { identifier += 1 ; while ( tabuList . contains ( prefix + identifier ) ) { identifier += 1 ; } object . setID ( prefix + identifier ) ; tabuList . add ( prefix + identifier ) ; return identifier ; }
Sets the ID on the object and adds it to the tabu list .
29,042
private static void createIDsForAtomContainer ( IAtomContainer container , List < String > tabuList ) { if ( tabuList == null ) tabuList = AtomContainerManipulator . getAllIDs ( container ) ; if ( null == container . getID ( ) ) { atomContainerCount = setID ( ATOMCONTAINER_PREFIX , atomContainerCount , container , tabuList ) ; } List < String > internalTabuList = AtomContainerManipulator . getAllIDs ( container ) ; if ( policy == OBJECT_UNIQUE_POLICY ) { atomCount = 0 ; bondCount = 0 ; } else { internalTabuList = tabuList ; } Iterator < IAtom > atoms = container . atoms ( ) . iterator ( ) ; while ( atoms . hasNext ( ) ) { IAtom atom = atoms . next ( ) ; if ( null == atom . getID ( ) ) { atomCount = setID ( ATOM_PREFIX , atomCount , atom , internalTabuList ) ; } } Iterator < IBond > bonds = container . bonds ( ) . iterator ( ) ; while ( bonds . hasNext ( ) ) { IBond bond = bonds . next ( ) ; if ( null == bond . getID ( ) ) { bondCount = setID ( BOND_PREFIX , bondCount , bond , internalTabuList ) ; } } }
Labels the Atom s and Bond s in the AtomContainer using the a1 a2 b1 b2 scheme often used in CML .
29,043
private static void createIDsForAtomContainerSet ( IAtomContainerSet containerSet , List < String > tabuList ) { if ( tabuList == null ) tabuList = AtomContainerSetManipulator . getAllIDs ( containerSet ) ; if ( null == containerSet . getID ( ) ) { atomContainerSetCount = setID ( ATOMCONTAINERSET_PREFIX , atomContainerSetCount , containerSet , tabuList ) ; } if ( policy == OBJECT_UNIQUE_POLICY ) { atomCount = 0 ; bondCount = 0 ; } Iterator < IAtomContainer > acs = containerSet . atomContainers ( ) . iterator ( ) ; while ( acs . hasNext ( ) ) { createIDsForAtomContainer ( ( IAtomContainer ) acs . next ( ) , tabuList ) ; } }
Labels the Atom s and Bond s in each AtomContainer using the a1 a2 b1 b2 scheme often used in CML . It will also set id s for all AtomContainers naming them m1 m2 etc . It will not the AtomContainerSet itself .
29,044
private static void createIDsForReaction ( IReaction reaction , List < String > tabuList ) { if ( tabuList == null ) tabuList = ReactionManipulator . getAllIDs ( reaction ) ; if ( null == reaction . getID ( ) ) { reactionCount = setID ( REACTION_PREFIX , reactionCount , reaction , tabuList ) ; } if ( policy == OBJECT_UNIQUE_POLICY ) { atomCount = 0 ; bondCount = 0 ; } for ( IAtomContainer reactant : reaction . getReactants ( ) . atomContainers ( ) ) { createIDsForAtomContainer ( reactant , tabuList ) ; } for ( IAtomContainer product : reaction . getReactants ( ) . atomContainers ( ) ) { createIDsForAtomContainer ( product , tabuList ) ; } Iterator < IAtomContainer > agents = reaction . getAgents ( ) . atomContainers ( ) . iterator ( ) ; while ( agents . hasNext ( ) ) { createIDsForAtomContainer ( ( IAtomContainer ) agents . next ( ) , tabuList ) ; } }
Labels the reactants and products in the Reaction m1 m2 etc and the atoms accordingly when no ID is given .
29,045
public DescriptorValue calculate ( IAtom atom , IAtomContainer ac ) { neighboors = ac . getConnectedAtomsList ( atom ) ; IAtomContainer clone ; try { clone = ( IAtomContainer ) ac . clone ( ) ; } catch ( CloneNotSupportedException e ) { return getDummyDescriptorValue ( e ) ; } try { peoe = new GasteigerMarsiliPartialCharges ( ) ; peoe . setMaxGasteigerIters ( 6 ) ; peoe . assignGasteigerMarsiliSigmaPartialCharges ( clone , true ) ; } catch ( Exception exception ) { return getDummyDescriptorValue ( exception ) ; } IAtom localAtom = clone . getAtom ( ac . indexOf ( atom ) ) ; neighboors = clone . getConnectedAtomsList ( localAtom ) ; DoubleArrayResult protonPartialCharge = new DoubleArrayResult ( MAX_PROTON_COUNT ) ; assert ( neighboors . size ( ) < MAX_PROTON_COUNT ) ; protonPartialCharge . add ( localAtom . getCharge ( ) ) ; int hydrogenNeighbors = 0 ; for ( IAtom neighboor : neighboors ) { if ( neighboor . getSymbol ( ) . equals ( "H" ) ) { hydrogenNeighbors ++ ; protonPartialCharge . add ( neighboor . getCharge ( ) ) ; } } int remainder = MAX_PROTON_COUNT - ( hydrogenNeighbors + 1 ) ; for ( int i = 0 ; i < remainder ; i ++ ) protonPartialCharge . add ( Double . NaN ) ; return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , protonPartialCharge , getDescriptorNames ( ) ) ; }
The method returns partial charges assigned to an heavy atom and its protons through Gasteiger Marsili It is needed to call the addExplicitHydrogensToSatisfyValency method from the class tools . HydrogenAdder .
29,046
public void setSetting ( String setting ) throws CDKException { if ( settings . contains ( setting ) ) { this . setting = setting ; } else { throw new CDKException ( "Setting " + setting + " is not allowed." ) ; } }
Sets the setting for a certain question . It will throw a CDKException when the setting is not valid .
29,047
public void setSetting ( int setting ) throws CDKException { if ( setting < settings . size ( ) + 1 && setting > 0 ) { this . setting = ( String ) settings . get ( setting - 1 ) ; } else { throw new CDKException ( "Setting " + setting + " does not exist." ) ; } }
Sets the setting for a certain question . It will throw a CDKException when the setting is not valid . The first setting is setting 1 .
29,048
public void write ( IChemObject object ) throws CDKException { if ( object instanceof IAtomContainerSet ) { writeAtomContainerSet ( ( IAtomContainerSet ) object ) ; } else if ( object instanceof IAtomContainer ) { writeAtomContainer ( ( IAtomContainer ) object ) ; } else { throw new CDKException ( "Only supported is writing of ChemFile and Molecule objects." ) ; } }
Writes the content from object to output .
29,049
public void writeAtomContainerSet ( IAtomContainerSet som ) { writeAtomContainer ( som . getAtomContainer ( 0 ) ) ; for ( int i = 1 ; i <= som . getAtomContainerCount ( ) - 1 ; i ++ ) { try { writeAtomContainer ( som . getAtomContainer ( i ) ) ; } catch ( Exception exc ) { } } }
Writes a list of molecules to an OutputStream .
29,050
public void writeAtomContainer ( IAtomContainer molecule ) { SmilesGenerator sg = new SmilesGenerator ( ) ; if ( useAromaticityFlag . isSet ( ) ) sg = sg . aromatic ( ) ; String smiles = "" ; try { smiles = sg . create ( molecule ) ; logger . debug ( "Generated SMILES: " + smiles ) ; writer . write ( smiles ) ; writer . write ( '\n' ) ; writer . flush ( ) ; logger . debug ( "file flushed..." ) ; } catch ( CDKException | IOException exc ) { logger . error ( "Error while writing Molecule: " , exc . getMessage ( ) ) ; logger . debug ( exc ) ; } }
Writes the content from molecule to output .
29,051
public DescriptorValue calculate ( IAtom atom , IAtomContainer container ) { IAtom focus = container . getAtom ( focusPosition ) ; int bondsToAtom = new ShortestPaths ( container , atom ) . distanceTo ( focus ) ; return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , new IntegerResult ( bondsToAtom ) , getDescriptorNames ( ) ) ; }
This method calculate the number of bonds on the shortest path between two atoms .
29,052
public void addImplicitHydrogens ( IAtomContainer container ) throws CDKException { for ( IAtom atom : container . atoms ( ) ) { if ( ! ( atom instanceof IPseudoAtom ) ) { addImplicitHydrogens ( container , atom ) ; } } }
Sets implicit hydrogen counts for all atoms in the given IAtomContainer .
29,053
public void addImplicitHydrogens ( IAtomContainer container , IAtom atom ) throws CDKException { if ( atom . getAtomTypeName ( ) == null ) throw new CDKException ( "IAtom is not typed! " + atom . getSymbol ( ) ) ; if ( "X" . equals ( atom . getAtomTypeName ( ) ) ) { if ( atom . getImplicitHydrogenCount ( ) == null ) atom . setImplicitHydrogenCount ( 0 ) ; return ; } IAtomType type = atomTypeList . getAtomType ( atom . getAtomTypeName ( ) ) ; if ( type == null ) throw new CDKException ( "Atom type is not a recognized CDK atom type: " + atom . getAtomTypeName ( ) ) ; if ( type . getFormalNeighbourCount ( ) == CDKConstants . UNSET ) throw new CDKException ( "Atom type is too general; cannot decide the number of implicit hydrogen to add for: " + atom . getAtomTypeName ( ) ) ; atom . setImplicitHydrogenCount ( type . getFormalNeighbourCount ( ) - container . getConnectedBondsCount ( atom ) ) ; }
Sets the implicit hydrogen count for the indicated IAtom in the given IAtomContainer . If the atom type is X then the atom is assigned zero implicit hydrogens .
29,054
private void init ( ) { if ( ERTs != null ) return ; synchronized ( this ) { if ( ERTs != null ) return ; discretizeMasses ( ) ; divideByGCD ( ) ; computeLCMs ( ) ; calcERT ( ) ; computeErrors ( ) ; } }
Initializes the decomposer . Computes the extended residue table . This have to be done only one time for a given alphabet independently from the masses you want to decompose . This method is called automatically if you compute the decompositions so call it only if you want to control the time of the initialisation .
29,055
DecompIterator decomposeIterator ( double from , double to , MolecularFormulaRange boundaries ) { init ( ) ; if ( to < 0d || from < 0d ) throw new IllegalArgumentException ( "Expect positive mass for decomposition: [" + from + ", " + to + "]" ) ; if ( to < from ) throw new IllegalArgumentException ( "Negative range given: [" + from + ", " + to + "]" ) ; final int [ ] minValues = new int [ weights . size ( ) ] ; final int [ ] boundsarray = new int [ weights . size ( ) ] ; double cfrom = from , cto = to ; Arrays . fill ( boundsarray , Integer . MAX_VALUE ) ; if ( boundaries != null ) { for ( int i = 0 ; i < boundsarray . length ; i ++ ) { IIsotope el = weights . get ( i ) . getOwner ( ) ; int max = boundaries . getIsotopeCountMax ( el ) ; int min = boundaries . getIsotopeCountMin ( el ) ; if ( min >= 0 || max >= 0 ) { boundsarray [ i ] = max - min ; minValues [ i ] = min ; if ( minValues [ i ] > 0 ) { final double reduceWeightBy = weights . get ( i ) . getMass ( ) * min ; cfrom -= reduceWeightBy ; cto -= reduceWeightBy ; } } } } final int [ ] minmax = new int [ 2 ] ; integerBound ( cfrom , cto , minmax ) ; final int deviation = minmax [ 1 ] - minmax [ 0 ] ; if ( ( 1 << ( ERTs . length - 1 ) ) <= deviation ) { calcERT ( deviation ) ; } final int [ ] [ ] [ ] ERTs = this . ERTs ; int [ ] [ ] currentERT ; if ( deviation == 0 ) currentERT = ERTs [ 0 ] ; else currentERT = ERTs [ 32 - Integer . numberOfLeadingZeros ( deviation ) ] ; return new DecompIterator ( currentERT , minmax [ 0 ] , minmax [ 1 ] , from , to , minValues , boundsarray , weights ) ; }
Returns an iterator over all decompositons of this mass range
29,056
private void calcERT ( int deviation ) { final int [ ] [ ] [ ] ERTs = this . ERTs ; final int currentLength = ERTs . length ; int [ ] [ ] lastERT = ERTs [ ERTs . length - 1 ] ; int [ ] [ ] nextERT = new int [ lastERT . length ] [ weights . size ( ) ] ; if ( currentLength == 1 ) { for ( int j = 0 ; j < weights . size ( ) ; j ++ ) { nextERT [ 0 ] [ j ] = Math . min ( lastERT [ nextERT . length - 1 ] [ j ] , lastERT [ 0 ] [ j ] ) ; } for ( int i = 1 ; i < nextERT . length ; i ++ ) { for ( int j = 0 ; j < weights . size ( ) ; j ++ ) { nextERT [ i ] [ j ] = Math . min ( lastERT [ i ] [ j ] , lastERT [ i - 1 ] [ j ] ) ; } } } else { int step = ( 1 << ( currentLength - 2 ) ) ; for ( int i = step ; i < nextERT . length ; i ++ ) { for ( int j = 0 ; j < weights . size ( ) ; j ++ ) { nextERT [ i ] [ j ] = Math . min ( lastERT [ i ] [ j ] , lastERT [ i - step ] [ j ] ) ; } } for ( int i = 0 ; i < step ; i ++ ) { for ( int j = 0 ; j < weights . size ( ) ; j ++ ) { nextERT [ i ] [ j ] = Math . min ( lastERT [ i ] [ j ] , lastERT [ i + nextERT . length - step ] [ j ] ) ; } } } synchronized ( this ) { final int [ ] [ ] [ ] tables = this . ERTs ; if ( tables . length == currentLength ) { this . ERTs = Arrays . copyOf ( this . ERTs , this . ERTs . length + 1 ) ; this . ERTs [ this . ERTs . length - 1 ] = nextERT ; } else { } } if ( ( 1 << ( currentLength - 1 ) ) <= deviation ) calcERT ( deviation ) ; }
calculates ERTs to look up whether a mass or lower masses within a certain deviation are decomposable . only ERTs for deviation 2^x are calculated
29,057
public void addReaction ( IReaction reaction ) { if ( reactionCount + 1 >= reactions . length ) growReactionArray ( ) ; reactions [ reactionCount ] = reaction ; reactionCount ++ ; }
Adds an reaction to this container .
29,058
public void removeAllReactions ( ) { for ( int pos = this . reactionCount - 1 ; pos >= 0 ; pos -- ) { this . reactions [ pos ] = null ; } this . reactionCount = 0 ; }
Removes all Reactions from this container .
29,059
private void setActiveCenters ( IAtomContainer reactant ) throws CDKException { AllRingsFinder arf = new AllRingsFinder ( ) ; IRingSet ringSet = arf . findAllRings ( reactant ) ; for ( int ir = 0 ; ir < ringSet . getAtomContainerCount ( ) ; ir ++ ) { IRing ring = ( IRing ) ringSet . getAtomContainer ( ir ) ; int nrAtoms = ring . getAtomCount ( ) ; if ( nrAtoms % 2 == 0 ) { int nrSingleBonds = 0 ; for ( IBond iBond : ring . bonds ( ) ) { if ( iBond . getOrder ( ) == IBond . Order . SINGLE ) nrSingleBonds ++ ; } if ( nrSingleBonds != 0 && nrAtoms / 2 == nrSingleBonds ) { for ( IBond iBond : ring . bonds ( ) ) iBond . setFlag ( CDKConstants . REACTIVE_CENTER , true ) ; } } } }
Set the active center for this molecule . The active center will be those which correspond to a ring with pi electrons with resonance .
29,060
public IAtomContainer proposeStructure ( ) { logger . debug ( "RandomGenerator->proposeStructure() Start" ) ; do { try { trial = molecule . clone ( ) ; } catch ( CloneNotSupportedException e ) { throw new IllegalStateException ( "Could not clone IAtomContainer!" + e . getMessage ( ) ) ; } mutate ( trial ) ; if ( logger . isDebugEnabled ( ) ) { String s = "BondCounts: " ; for ( int f = 0 ; f < trial . getAtomCount ( ) ; f ++ ) { s += trial . getConnectedBondsCount ( trial . getAtom ( f ) ) + " " ; } logger . debug ( s ) ; s = "BondOrderSums: " ; for ( int f = 0 ; f < trial . getAtomCount ( ) ; f ++ ) { s += trial . getBondOrderSum ( trial . getAtom ( f ) ) + " " ; } logger . debug ( s ) ; } } while ( trial == null || ! ConnectivityChecker . isConnected ( trial ) ) ; proposedStructure = trial ; return proposedStructure ; }
Proposes a structure which can be accepted or rejected by an external entity . If rejected the structure is not used as a starting point for the next random move in structure space .
29,061
public DescriptorValue calculate ( IAtomContainer atomContainer ) { int hBondDonors = 0 ; IAtomContainer ac ; try { ac = ( IAtomContainer ) atomContainer . clone ( ) ; } catch ( CloneNotSupportedException e ) { return getDummyDescriptorValue ( e ) ; } atomloop : for ( int atomIndex = 0 ; atomIndex < ac . getAtomCount ( ) ; atomIndex ++ ) { IAtom atom = ( IAtom ) ac . getAtom ( atomIndex ) ; if ( ( atom . getSymbol ( ) . equals ( "O" ) || atom . getSymbol ( ) . equals ( "N" ) ) && atom . getFormalCharge ( ) >= 0 ) { Integer implicitH = atom . getImplicitHydrogenCount ( ) ; if ( implicitH == CDKConstants . UNSET ) implicitH = 0 ; if ( implicitH > 0 ) { hBondDonors ++ ; continue atomloop ; } java . util . List neighbours = ac . getConnectedAtomsList ( atom ) ; for ( Object neighbour : neighbours ) { if ( ( ( IAtom ) neighbour ) . getSymbol ( ) . equals ( "H" ) ) { hBondDonors ++ ; continue atomloop ; } } } } return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , new IntegerResult ( hBondDonors ) , getDescriptorNames ( ) ) ; }
Calculates the number of H bond donors .
29,062
private int [ ] buildVertexColor ( ) { int [ ] color = new int [ g . length ] ; int n = 1 ; Arrays . fill ( color , - 1 ) ; for ( long cycle : cycles ) { for ( int i = 0 ; i < g . length ; i ++ ) { if ( ( cycle & 0x1 ) == 0x1 ) color [ i ] = color [ i ] < 0 ? n : 0 ; cycle >>= 1 ; } n ++ ; } return color ; }
Build an indexed lookup of vertex color . The vertex color indicates which cycle a given vertex belongs . If a vertex belongs to more then one cycle it is colored 0 . If a vertex belongs to no cycle it is colored - 1 .
29,063
public int getSize ( ) { int count = 0 ; for ( List < IIsotope > isotope : isotopes ) if ( isotope != null ) count += isotope . size ( ) ; return count ; }
Returns the number of isotopes defined by this class .
29,064
protected void add ( IIsotope isotope ) { Integer atomicNum = isotope . getAtomicNumber ( ) ; assert atomicNum != null ; List < IIsotope > isotopesForElement = isotopes [ atomicNum ] ; if ( isotopesForElement == null ) { isotopesForElement = new ArrayList < > ( ) ; isotopes [ atomicNum ] = isotopesForElement ; } isotopesForElement . add ( isotope ) ; }
Protected methods only to be used by classes extending this class to add an IIsotope .
29,065
public IIsotope [ ] getIsotopes ( int elem ) { if ( isotopes [ elem ] == null ) return EMPTY_ISOTOPE_ARRAY ; List < IIsotope > list = new ArrayList < > ( ) ; for ( IIsotope isotope : isotopes [ elem ] ) { list . add ( clone ( isotope ) ) ; } return list . toArray ( new IIsotope [ 0 ] ) ; }
Gets an array of all isotopes known to the IsotopeFactory for the given element symbol .
29,066
public IIsotope [ ] getIsotopes ( ) { List < IIsotope > list = new ArrayList < IIsotope > ( ) ; for ( List < IIsotope > isotopes : this . isotopes ) { if ( isotopes == null ) continue ; for ( IIsotope isotope : isotopes ) { list . add ( clone ( isotope ) ) ; } } return list . toArray ( new IIsotope [ list . size ( ) ] ) ; }
Gets a array of all isotopes known to the IsotopeFactory .
29,067
public IIsotope [ ] getIsotopes ( double exactMass , double difference ) { List < IIsotope > list = new ArrayList < > ( ) ; for ( List < IIsotope > isotopes : this . isotopes ) { if ( isotopes == null ) continue ; for ( IIsotope isotope : isotopes ) { if ( Math . abs ( isotope . getExactMass ( ) - exactMass ) <= difference ) { list . add ( clone ( isotope ) ) ; } } } return list . toArray ( new IIsotope [ list . size ( ) ] ) ; }
Gets an array of all isotopes matching the searched exact mass within a certain difference .
29,068
public IIsotope getIsotope ( String symbol , int massNumber ) { int elem = Elements . ofString ( symbol ) . number ( ) ; List < IIsotope > isotopes = this . isotopes [ elem ] ; if ( isotopes == null ) return null ; for ( IIsotope isotope : isotopes ) { if ( isotope . getSymbol ( ) . equals ( symbol ) && isotope . getMassNumber ( ) == massNumber ) { return clone ( isotope ) ; } } return null ; }
Get isotope based on element symbol and mass number .
29,069
public IIsotope getIsotope ( String symbol , double exactMass , double tolerance ) { IIsotope ret = null ; double minDiff = Double . MAX_VALUE ; int elem = Elements . ofString ( symbol ) . number ( ) ; List < IIsotope > isotopes = this . isotopes [ elem ] ; if ( isotopes == null ) return null ; for ( IIsotope isotope : isotopes ) { double diff = Math . abs ( isotope . getExactMass ( ) - exactMass ) ; if ( isotope . getSymbol ( ) . equals ( symbol ) && diff <= tolerance && diff < minDiff ) { ret = clone ( isotope ) ; minDiff = diff ; } } return ret ; }
Get an isotope based on the element symbol and exact mass .
29,070
public double getExactMass ( Integer atomicNumber , Integer massNumber ) { if ( atomicNumber == null || massNumber == null ) return 0 ; for ( IIsotope isotope : this . isotopes [ atomicNumber ] ) { if ( isotope . getMassNumber ( ) . equals ( massNumber ) ) return isotope . getExactMass ( ) ; } return 0 ; }
Get the exact mass of a specified isotope for an atom .
29,071
public IAtom configure ( IAtom atom , IIsotope isotope ) { atom . setMassNumber ( isotope . getMassNumber ( ) ) ; atom . setSymbol ( isotope . getSymbol ( ) ) ; atom . setExactMass ( isotope . getExactMass ( ) ) ; atom . setAtomicNumber ( isotope . getAtomicNumber ( ) ) ; atom . setNaturalAbundance ( isotope . getNaturalAbundance ( ) ) ; return atom ; }
Configures an atom to have all the data of the given isotope .
29,072
public void configureAtoms ( IAtomContainer container ) { for ( int f = 0 ; f < container . getAtomCount ( ) ; f ++ ) { configure ( container . getAtom ( f ) ) ; } }
Configures atoms in an AtomContainer to carry all the correct data according to their element type .
29,073
public double getNaturalMass ( int atomicNum ) { List < IIsotope > isotopes = this . isotopes [ atomicNum ] ; if ( isotopes == null ) return 0 ; double summedAbundances = 0 ; double summedWeightedAbundances = 0 ; double getNaturalMass = 0 ; for ( IIsotope isotope : isotopes ) { summedAbundances += isotope . getNaturalAbundance ( ) ; summedWeightedAbundances += isotope . getNaturalAbundance ( ) * isotope . getExactMass ( ) ; getNaturalMass = summedWeightedAbundances / summedAbundances ; } return getNaturalMass ; }
Gets the natural mass of this element defined as average of masses of isotopes weighted by abundance .
29,074
private double initScore ( ) { double score = 0 ; final int n = atoms . length ; for ( int i = 0 ; i < n ; i ++ ) { final Point2d p1 = atoms [ i ] . getPoint2d ( ) ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( contribution [ i ] [ j ] < 0 ) continue ; final Point2d p2 = atoms [ j ] . getPoint2d ( ) ; final double x = p1 . x - p2 . x ; final double y = p1 . y - p2 . y ; final double len2 = x * x + y * y ; score += contribution [ j ] [ i ] = contribution [ i ] [ j ] = 1 / Math . max ( len2 , MIN_SCORE ) ; } } return score ; }
Calculate the initial score .
29,075
void update ( boolean [ ] visit , int [ ] vs , int n ) { int len = atoms . length ; double subtract = 0 ; for ( int i = 0 ; i < n ; i ++ ) { final int v = vs [ i ] ; final Point2d p1 = atoms [ v ] . getPoint2d ( ) ; for ( int w = 0 ; w < len ; w ++ ) { if ( visit [ w ] || contribution [ v ] [ w ] < 0 ) continue ; subtract += contribution [ v ] [ w ] ; final Point2d p2 = atoms [ w ] . getPoint2d ( ) ; final double x = p1 . x - p2 . x ; final double y = p1 . y - p2 . y ; final double len2 = x * x + y * y ; score += contribution [ w ] [ v ] = contribution [ v ] [ w ] = 1 / Math . max ( len2 , MIN_SCORE ) ; } } score -= subtract ; }
Update the score considering that some atoms have moved . We only need to update the score of atom that have moved vs those that haven t since all those that moved did so together .
29,076
static int [ ] verticesInOrder ( final int [ ] rank ) { int [ ] vs = new int [ rank . length ] ; for ( int v = 0 ; v < rank . length ; v ++ ) vs [ rank [ v ] ] = v ; return vs ; }
Using the pre - computed rank get the vertices in order .
29,077
static int [ ] rank ( final int [ ] [ ] g ) { final int ord = g . length ; final int [ ] count = new int [ ord + 1 ] ; final int [ ] rank = new int [ ord ] ; for ( int v = 0 ; v < ord ; v ++ ) count [ g [ v ] . length + 1 ] ++ ; for ( int i = 0 ; count [ i ] < ord ; i ++ ) count [ i + 1 ] += count [ i ] ; for ( int v = 0 ; v < ord ; v ++ ) rank [ v ] = count [ g [ v ] . length ] ++ ; return rank ; }
Compute a rank for each vertex . This rank is based on the degree and indicates the position each vertex would be in a sorted array .
29,078
public int [ ] [ ] paths ( ) { int [ ] [ ] paths = new int [ cycles . size ( ) ] [ ] ; for ( int i = 0 ; i < cycles . size ( ) ; i ++ ) paths [ i ] = cycles . get ( i ) . clone ( ) ; return paths ; }
The paths describing all simple cycles in the given graph . The path stats and ends vertex .
29,079
public Depiction depict ( Iterable < IAtomContainer > mols , int nrow , int ncol ) throws CDKException { List < LayoutBackup > layoutBackups = new ArrayList < > ( ) ; int molId = 0 ; for ( IAtomContainer mol : mols ) { setIfMissing ( mol , MarkedElement . ID_KEY , "mol" + ++ molId ) ; layoutBackups . add ( new LayoutBackup ( mol ) ) ; } prepareCoords ( mols ) ; for ( Map . Entry < IChemObject , Color > e : highlight . entrySet ( ) ) e . getKey ( ) . setProperty ( StandardGenerator . HIGHLIGHT_COLOR , e . getValue ( ) ) ; List < IAtomContainer > molList = FluentIterable . from ( mols ) . toList ( ) ; DepictionGenerator copy = this . withParam ( BasicSceneGenerator . Scale . class , caclModelScale ( molList ) ) ; final RendererModel model = copy . getModel ( ) ; final List < Bounds > molElems = copy . generate ( molList , model , 1 ) ; for ( LayoutBackup backup : layoutBackups ) backup . reset ( ) ; final List < Bounds > titles = new ArrayList < > ( ) ; if ( copy . getParameterValue ( BasicSceneGenerator . ShowMoleculeTitle . class ) ) { for ( IAtomContainer mol : mols ) titles . add ( copy . generateTitle ( mol , model . get ( BasicSceneGenerator . Scale . class ) ) ) ; } for ( IChemObject obj : this . highlight . keySet ( ) ) obj . removeProperty ( StandardGenerator . HIGHLIGHT_COLOR ) ; this . highlight . clear ( ) ; return new MolGridDepiction ( model , molElems , titles , dimensions , nrow , ncol ) ; }
Depict a set of molecules they will be depicted in a grid with the specified number of rows and columns . Rows are filled first and then columns .
29,080
private Map < IChemObject , Color > makeHighlightAtomMap ( List < IAtomContainer > reactants , List < IAtomContainer > products ) { Map < IChemObject , Color > colorMap = new HashMap < > ( ) ; Map < Integer , Color > mapToColor = new HashMap < > ( ) ; int colorIdx = - 1 ; for ( IAtomContainer mol : reactants ) { int prevPalletIdx = colorIdx ; for ( IAtom atom : mol . atoms ( ) ) { int mapidx = accessAtomMap ( atom ) ; if ( mapidx > 0 ) { if ( prevPalletIdx == colorIdx ) { colorIdx ++ ; if ( colorIdx >= atomMapColors . length ) throw new IllegalArgumentException ( "Not enough colors to highlight atom mapping, please provide mode" ) ; } Color color = atomMapColors [ colorIdx ] ; colorMap . put ( atom , color ) ; mapToColor . put ( mapidx , color ) ; } } if ( colorIdx > prevPalletIdx ) { for ( IBond bond : mol . bonds ( ) ) { IAtom a1 = bond . getBegin ( ) ; IAtom a2 = bond . getEnd ( ) ; Color c1 = colorMap . get ( a1 ) ; Color c2 = colorMap . get ( a2 ) ; if ( c1 != null && c1 == c2 ) colorMap . put ( bond , c1 ) ; } } } for ( IAtomContainer mol : products ) { for ( IAtom atom : mol . atoms ( ) ) { int mapidx = accessAtomMap ( atom ) ; if ( mapidx > 0 ) { colorMap . put ( atom , mapToColor . get ( mapidx ) ) ; } } for ( IBond bond : mol . bonds ( ) ) { IAtom a1 = bond . getBegin ( ) ; IAtom a2 = bond . getEnd ( ) ; Color c1 = colorMap . get ( a1 ) ; Color c2 = colorMap . get ( a2 ) ; if ( c1 != null && c1 == c2 ) colorMap . put ( bond , c1 ) ; } } return colorMap ; }
Internal - makes a map of the highlights for reaction mapping .
29,081
private Bounds generateTitle ( IChemObject chemObj , double scale ) { String title = chemObj . getProperty ( CDKConstants . TITLE ) ; if ( title == null || title . isEmpty ( ) ) return new Bounds ( ) ; scale = 1 / scale * getParameterValue ( RendererModel . TitleFontScale . class ) ; return new Bounds ( MarkedElement . markup ( StandardGenerator . embedText ( font , title , getParameterValue ( RendererModel . TitleColor . class ) , scale ) , "title" ) ) ; }
Generate a bound element that is the title of the provided molecule . If title is not specified an empty bounds is returned .
29,082
private boolean ensure2dLayout ( IAtomContainer container ) throws CDKException { if ( ! GeometryUtil . has2DCoordinates ( container ) ) { StructureDiagramGenerator sdg = new StructureDiagramGenerator ( ) ; sdg . generateCoordinates ( container ) ; return true ; } return false ; }
Automatically generate coordinates if a user has provided a molecule without them .
29,083
private void ensure2dLayout ( IReaction rxn ) throws CDKException { if ( ! GeometryUtil . has2DCoordinates ( rxn ) ) { StructureDiagramGenerator sdg = new StructureDiagramGenerator ( ) ; sdg . setAlignMappedReaction ( alignMappedReactions ) ; sdg . generateCoordinates ( rxn ) ; } }
Automatically generate coordinates if a user has provided reaction without them .
29,084
public DepictionGenerator withOuterGlowHighlight ( double width ) { return withParam ( StandardGenerator . Highlighting . class , StandardGenerator . HighlightStyle . OuterGlow ) . withParam ( StandardGenerator . OuterGlowWidth . class , width ) ; }
Highlights are shown as an outer glow around the atom symbols and bonds rather than recoloring .
29,085
public DepictionGenerator withAtomNumbers ( ) { if ( annotateAtomMap || annotateAtomVal ) throw new IllegalArgumentException ( "Can not annotated atom numbers, atom values or maps are already annotated" ) ; DepictionGenerator copy = new DepictionGenerator ( this ) ; copy . annotateAtomNum = true ; return copy ; }
Display atom numbers on the molecule or reaction . The numbers are based on the ordering of atoms in the molecule data structure and not a systematic system such as IUPAC numbering .
29,086
public DepictionGenerator withAtomValues ( ) { if ( annotateAtomNum || annotateAtomMap ) throw new IllegalArgumentException ( "Can not annotated atom values, atom numbers or maps are already annotated" ) ; DepictionGenerator copy = new DepictionGenerator ( this ) ; copy . annotateAtomVal = true ; return copy ; }
Display atom values on the molecule or reaction . The values need to be assigned by
29,087
public DepictionGenerator withAtomMapHighlight ( Color [ ] colors ) { DepictionGenerator copy = new DepictionGenerator ( this ) ; copy . highlightAtomMap = true ; copy . atomMapColors = Arrays . copyOf ( colors , colors . length ) ; return copy ; }
Adds to the highlight the coloring of reaction atom - maps . The optional color array is used as the pallet with which to highlight . If none is provided a set of high - contrast colors will be used .
29,088
public DepictionGenerator withHighlight ( Iterable < ? extends IChemObject > chemObjs , Color color ) { DepictionGenerator copy = new DepictionGenerator ( this ) ; for ( IChemObject chemObj : chemObjs ) copy . highlight . put ( chemObj , color ) ; return copy ; }
Highlight the provided set of atoms and bonds in the depiction in the specified color .
29,089
public < T extends IGeneratorParameter < S > , S , U extends S > DepictionGenerator withParam ( Class < T > key , U value ) { DepictionGenerator copy = new DepictionGenerator ( this ) ; copy . setParam ( key , value ) ; return copy ; }
Low - level option method to set a rendering model parameter .
29,090
public void setCoefficients ( Matrix C ) { if ( count_basis == C . rows ) { this . C = C ; count_orbitals = C . columns ; } }
Set a coefficient matrix
29,091
public Vector getValues ( int index , Matrix m ) { if ( m . rows != 3 ) return null ; Vector result = basis . getValues ( 0 , m ) . mul ( C . matrix [ 0 ] [ index ] ) ; for ( int i = 1 ; i < count_basis ; i ++ ) if ( C . matrix [ i ] [ index ] != 0d ) result . add ( basis . getValues ( i , m ) . mul ( C . matrix [ 0 ] [ index ] ) ) ; return result ; }
Get the function value of a orbital
29,092
public static ConvexHull ofShapes ( final List < Shape > shapes ) { final Path2D combined = new Path2D . Double ( ) ; for ( Shape shape : shapes ) combined . append ( shape , false ) ; return new ConvexHull ( shapeOf ( grahamScan ( pointsOf ( combined ) ) ) ) ; }
Calculate the convex hull of multiple shapes .
29,093
static Shape shapeOf ( List < Point2D > points ) { Path2D path = new Path2D . Double ( ) ; if ( ! points . isEmpty ( ) ) { path . moveTo ( points . get ( 0 ) . getX ( ) , points . get ( 0 ) . getY ( ) ) ; for ( Point2D point : points ) path . lineTo ( point . getX ( ) , point . getY ( ) ) ; path . closePath ( ) ; } return path ; }
Convert a list of points to a shape .
29,094
static List < Point2D > pointsOf ( final Shape shape ) { final List < Point2D > points = new ArrayList < Point2D > ( ) ; final double [ ] coordinates = new double [ 6 ] ; for ( PathIterator i = shape . getPathIterator ( null ) ; ! i . isDone ( ) ; i . next ( ) ) { switch ( i . currentSegment ( coordinates ) ) { case PathIterator . SEG_CLOSE : break ; case PathIterator . SEG_MOVETO : case PathIterator . SEG_LINETO : points . add ( new Point2D . Double ( coordinates [ 0 ] , coordinates [ 1 ] ) ) ; break ; case PathIterator . SEG_QUADTO : points . add ( new Point2D . Double ( coordinates [ 0 ] , coordinates [ 1 ] ) ) ; points . add ( new Point2D . Double ( coordinates [ 2 ] , coordinates [ 3 ] ) ) ; break ; case PathIterator . SEG_CUBICTO : points . add ( new Point2D . Double ( coordinates [ 0 ] , coordinates [ 1 ] ) ) ; points . add ( new Point2D . Double ( coordinates [ 2 ] , coordinates [ 3 ] ) ) ; points . add ( new Point2D . Double ( coordinates [ 4 ] , coordinates [ 5 ] ) ) ; break ; } } if ( ! points . isEmpty ( ) && points . get ( points . size ( ) - 1 ) . equals ( points . get ( 0 ) ) ) { points . remove ( points . size ( ) - 1 ) ; } return points ; }
Convert a Java 2D shape to a list of points .
29,095
public static Point2D lineLineIntersect ( final Line2D lineA , final Line2D lineB ) { return lineLineIntersect ( lineA . getX1 ( ) , lineA . getY1 ( ) , lineA . getX2 ( ) , lineA . getY2 ( ) , lineB . getX1 ( ) , lineB . getY1 ( ) , lineB . getX2 ( ) , lineB . getY2 ( ) ) ; }
Calculate the intersection of two lines .
29,096
private static boolean isLeftTurn ( Point2D a , Point2D b , Point2D c ) { return winding ( a , b , c ) > 0 ; }
Determine if the three points make a left turn .
29,097
private static int winding ( Point2D a , Point2D b , Point2D c ) { return ( int ) Math . signum ( ( b . getX ( ) - a . getX ( ) ) * ( c . getY ( ) - a . getY ( ) ) - ( b . getY ( ) - a . getY ( ) ) * ( c . getX ( ) - a . getX ( ) ) ) ; }
Determine the winding of three points . The winding is the sign of the space - the parity .
29,098
protected Integer getFontSizeForZoom ( double zoom ) { double lower = - 1 ; for ( double upper : this . zoomToFontSizeMap . keySet ( ) ) { if ( lower == - 1 ) { lower = upper ; if ( zoom <= lower ) return this . zoomToFontSizeMap . get ( upper ) ; continue ; } if ( zoom > lower && zoom <= upper ) { return this . zoomToFontSizeMap . get ( upper ) ; } lower = upper ; } return this . zoomToFontSizeMap . get ( lower ) ; }
For a particular zoom get the appropriate font size .
29,099
public void increaseFontSize ( ) { if ( inRange ( ) || ( atMin ( ) && atLowerBoundary ( ) ) ) { currentFontIndex ++ ; } else if ( atMax ( ) ) { upperVirtualCount ++ ; } else if ( atMin ( ) && inLower ( ) ) { lowerVirtualCount ++ ; } }
Move the font size pointer up . If this would move the pointer past the maximum font size track this increase with a virtual size .