idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
28,700
public static String getChemicalSeries ( String symbol ) { Elements e = Elements . ofString ( symbol ) ; for ( Series s : Series . values ( ) ) if ( s . contains ( e ) ) return s . name ( ) ; return null ; }
Get the chemical series for an element .
28,701
public static String getPhase ( String symbol ) { Elements e = Elements . ofString ( symbol ) ; for ( Phase p : Phase . values ( ) ) if ( p . contains ( e ) ) return p . name ( ) ; return null ; }
Get the phase of the element .
28,702
private static Map < Elements , String > casIds ( ) { Map < Elements , String > result = ids ; if ( result == null ) { synchronized ( LOCK ) { result = ids ; if ( result == null ) { ids = result = initCasIds ( ) ; } } } return result ; }
Lazily obtain the CAS ID Mapping .
28,703
public static IBioPolymer addAminoAcidAtNTerminus ( IBioPolymer protein , IAminoAcid aaToAdd , IStrand strand , IAminoAcid aaToAddTo ) { addAminoAcid ( protein , aaToAdd , strand ) ; if ( protein . getMonomerCount ( ) == 0 ) { protein . addBond ( aaToAdd . getBuilder ( ) . newInstance ( IBond . class , aaToAddTo . getNTerminus ( ) , aaToAdd . getCTerminus ( ) , IBond . Order . SINGLE ) ) ; } return protein ; }
Builds a protein by connecting a new amino acid at the N - terminus of the given strand .
28,704
private static int getMaxDepth ( int [ ] [ ] adjlist , int v , int prev ) { int longest = 0 ; for ( int w : adjlist [ v ] ) { if ( w == prev ) continue ; int length = getMaxDepth ( adjlist , w , v ) ; if ( length > longest ) longest = length ; } return 1 + longest ; }
Depth - First - Search on an acyclic graph . Since we have no cycles we don t need the visit flags and only need to know which atom we came from .
28,705
public Object getParameterType ( String name ) { if ( name . equals ( CHECK_RING_SYSTEM ) ) return Boolean . TRUE ; else throw new IllegalArgumentException ( "No parameter for name: " + name ) ; }
Gets the parameterType attribute of the LongestAliphaticChainDescriptor object .
28,706
private static IAtom findOtherSinglyBonded ( IAtomContainer container , IAtom atom , IAtom exclude ) { for ( final IBond bond : container . getConnectedBondsList ( atom ) ) { if ( ! IBond . Order . SINGLE . equals ( bond . getOrder ( ) ) || bond . contains ( exclude ) ) continue ; return bond . getOther ( atom ) ; } return atom ; }
Finds a neighbor attached to atom that is singley bonded and isn t exclude . If no such atom exists the atom is returned .
28,707
private IChemFile readChemFile ( IChemFile chemFile ) throws CDKException , IOException { IChemSequence sequence = chemFile . getBuilder ( ) . newInstance ( IChemSequence . class ) ; IChemModel model = null ; String line = input . readLine ( ) ; String levelOfTheory ; String description ; int modelCounter = 0 ; while ( input . ready ( ) && ( line != null ) ) { if ( line . indexOf ( "Standard orientation:" ) >= 0 ) { model = chemFile . getBuilder ( ) . newInstance ( IChemModel . class ) ; readCoordinates ( model ) ; break ; } line = input . readLine ( ) ; } if ( model != null ) { line = input . readLine ( ) . trim ( ) ; while ( input . ready ( ) && ( line != null ) ) { if ( line . indexOf ( '#' ) == 0 ) { lastRoute = line ; modelCounter = 0 ; } else if ( line . indexOf ( "Standard orientation:" ) >= 0 ) { if ( ! readOptimizedStructureOnly . isSet ( ) ) { sequence . addChemModel ( model ) ; } else { logger . info ( "Skipping frame, because I was told to do" ) ; } fireFrameRead ( ) ; model = chemFile . getBuilder ( ) . newInstance ( IChemModel . class ) ; modelCounter ++ ; readCoordinates ( model ) ; } else if ( line . indexOf ( "SCF Done:" ) >= 0 ) { model . setProperty ( CDKConstants . REMARK , line . trim ( ) ) ; } else if ( line . indexOf ( "Harmonic frequencies" ) >= 0 ) { } else if ( line . indexOf ( "Total atomic charges" ) >= 0 ) { readPartialCharges ( model ) ; } else if ( line . indexOf ( "Magnetic shielding" ) >= 0 ) { readNMRData ( model , line ) ; } else if ( line . indexOf ( "GINC" ) >= 0 ) { levelOfTheory = parseLevelOfTheory ( line ) ; logger . debug ( "Level of Theory for this model: " + levelOfTheory ) ; description = lastRoute + ", model no. " + modelCounter ; model . setProperty ( CDKConstants . DESCRIPTION , description ) ; } else { } line = input . readLine ( ) ; } sequence . addChemModel ( model ) ; fireFrameRead ( ) ; } chemFile . addChemSequence ( sequence ) ; return chemFile ; }
Read the Gaussian98 output .
28,708
private void readNMRData ( IChemModel model , String labelLine ) throws CDKException { List < IAtomContainer > containers = ChemModelManipulator . getAllAtomContainers ( model ) ; if ( containers . size ( ) == 0 ) { return ; } IAtomContainer ac = containers . get ( 0 ) ; String label ; if ( labelLine . indexOf ( "Diamagnetic" ) >= 0 ) { label = "Diamagnetic Magnetic shielding (Isotropic)" ; } else if ( labelLine . indexOf ( "Paramagnetic" ) >= 0 ) { label = "Paramagnetic Magnetic shielding (Isotropic)" ; } else { label = "Magnetic shielding (Isotropic)" ; } int atomIndex = 0 ; for ( int i = 0 ; i < atomCount ; ++ i ) { try { String line = input . readLine ( ) . trim ( ) ; while ( line . indexOf ( "Isotropic" ) < 0 ) { if ( line == null ) { return ; } line = input . readLine ( ) . trim ( ) ; } StringTokenizer st1 = new StringTokenizer ( line ) ; while ( st1 . hasMoreTokens ( ) ) { if ( st1 . nextToken ( ) . equals ( "Isotropic" ) ) { break ; } } while ( st1 . hasMoreTokens ( ) ) { if ( st1 . nextToken ( ) . equals ( "=" ) ) break ; } double shielding = Double . valueOf ( st1 . nextToken ( ) ) . doubleValue ( ) ; logger . info ( "Type of shielding: " + label ) ; ac . getAtom ( atomIndex ) . setProperty ( CDKConstants . ISOTROPIC_SHIELDING , new Double ( shielding ) ) ; ++ atomIndex ; } catch ( IOException | NumberFormatException exc ) { logger . debug ( "failed to read line from gaussian98 file where I expected one." ) ; } } }
Reads NMR nuclear shieldings .
28,709
private String parseLevelOfTheory ( String line ) { StringBuffer summary = new StringBuffer ( ) ; summary . append ( line ) ; try { do { line = input . readLine ( ) . trim ( ) ; summary . append ( line ) ; } while ( ! ( line . indexOf ( '@' ) >= 0 ) ) ; } catch ( Exception exc ) { logger . debug ( "syntax problem while parsing summary of g98 section: " ) ; logger . debug ( exc ) ; } logger . debug ( "parseLoT(): " + summary . toString ( ) ) ; StringTokenizer st1 = new StringTokenizer ( summary . toString ( ) , "\\" ) ; if ( st1 . countTokens ( ) < 6 ) { return null ; } for ( int i = 0 ; i < 4 ; ++ i ) { st1 . nextToken ( ) ; } return st1 . nextToken ( ) + "/" + st1 . nextToken ( ) ; }
Select the theory and basis set from the first archive line .
28,710
public double validate ( IMolecularFormula formula ) throws CDKException { logger . info ( "Start validation of " , formula ) ; double mass = MolecularFormulaManipulator . getTotalMassNumber ( formula ) ; if ( mass == 0 ) return 0.0 ; int numberN = MolecularFormulaManipulator . getElementCount ( formula , formula . getBuilder ( ) . newInstance ( IElement . class , "N" ) ) ; numberN += getOthers ( formula ) ; if ( formula . getCharge ( ) == null || formula . getCharge ( ) == 0 || ! isOdd ( Math . abs ( formula . getCharge ( ) ) ) ) { if ( isOdd ( mass ) && isOdd ( numberN ) ) { return 1.0 ; } else if ( ! isOdd ( mass ) && ( numberN == 0 || ! isOdd ( numberN ) ) ) { return 1.0 ; } else return 0.0 ; } else { if ( ! isOdd ( mass ) && isOdd ( numberN ) ) { return 1.0 ; } else if ( isOdd ( mass ) && ( numberN == 0 || ! isOdd ( numberN ) ) ) { return 1.0 ; } else return 0.0 ; } }
Validate the nitrogen rule of this IMolecularFormula .
28,711
private int getOthers ( IMolecularFormula formula ) { int number = 0 ; String [ ] elements = { "Co" , "Hg" , "Pt" , "As" } ; for ( int i = 0 ; i < elements . length ; i ++ ) number += MolecularFormulaManipulator . getElementCount ( formula , formula . getBuilder ( ) . newInstance ( IElement . class , elements [ i ] ) ) ; return number ; }
Get the number of other elements which affect to the calculation of the nominal mass . For example Fe Co Hg Pt As .
28,712
public static IAtomContainer checkAndCleanMolecule ( IAtomContainer molecule ) { boolean isMarkush = false ; for ( IAtom atom : molecule . atoms ( ) ) { if ( atom . getSymbol ( ) . equals ( "R" ) ) { isMarkush = true ; break ; } } if ( isMarkush ) { System . err . println ( "Skipping Markush structure for sanity check" ) ; } if ( ! ConnectivityChecker . isConnected ( molecule ) ) { IAtomContainerSet fragments = ConnectivityChecker . partitionIntoMolecules ( molecule ) ; if ( fragments . getAtomContainerCount ( ) > 2 ) { System . err . println ( "More than 2 components. Skipped" ) ; } else { IAtomContainer frag1 = fragments . getAtomContainer ( 0 ) ; IAtomContainer frag2 = fragments . getAtomContainer ( 1 ) ; if ( frag1 . getAtomCount ( ) > frag2 . getAtomCount ( ) ) { molecule = frag1 ; } else { molecule = frag2 ; } } } configure ( molecule ) ; return molecule ; }
Modules for cleaning a molecule
28,713
Entry < String , Point2d [ ] > createEntry ( final IAtomContainer container ) { try { final int n = container . getAtomCount ( ) ; final int [ ] ordering = new int [ n ] ; final String smiles = cansmi ( container , ordering ) ; final Point2d [ ] points = new Point2d [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { Point2d point = container . getAtom ( i ) . getPoint2d ( ) ; if ( point == null ) { logger . warn ( "Atom at index " , i , " did not have coordinates." ) ; return null ; } points [ ordering [ i ] ] = point ; } return new SimpleEntry < String , Point2d [ ] > ( smiles , points ) ; } catch ( CDKException e ) { logger . warn ( "Could not encode container as SMILES: " , e ) ; } return null ; }
Create a library entry from an atom container . Note the entry is not added to the library .
28,714
static Point2d [ ] decodeCoordinates ( String str ) { if ( str . startsWith ( "|(" ) ) { int end = str . indexOf ( ')' , 2 ) ; if ( end < 0 ) return new Point2d [ 0 ] ; String [ ] strs = str . substring ( 2 , end ) . split ( ";" ) ; Point2d [ ] points = new Point2d [ strs . length ] ; for ( int i = 0 ; i < strs . length ; i ++ ) { String coord = strs [ i ] ; int first = coord . indexOf ( ',' ) ; int second = coord . indexOf ( ',' , first + 1 ) ; points [ i ] = new Point2d ( Double . parseDouble ( coord . substring ( 0 , first ) ) , Double . parseDouble ( coord . substring ( first + 1 , second ) ) ) ; } return points ; } else { String [ ] strs = str . split ( ", " ) ; Point2d [ ] points = new Point2d [ strs . length / 2 ] ; for ( int i = 0 ; i < strs . length ; i += 2 ) { points [ i / 2 ] = new Point2d ( Double . parseDouble ( strs [ i ] ) , Double . parseDouble ( strs [ i + 1 ] ) ) ; } return points ; } }
Decode coordinates that have been placed in a byte buffer .
28,715
static String encodeEntry ( Entry < String , Point2d [ ] > entry ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( entry . getKey ( ) ) ; sb . append ( ' ' ) ; sb . append ( encodeCoordinates ( entry . getValue ( ) ) ) ; return sb . toString ( ) ; }
Encodes an entry in a compact string representation . The encoded entry is a SMILES string with the coordinates suffixed in binary .
28,716
static String encodeCoordinates ( Point2d [ ] points ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "|(" ) ; for ( Point2d point : points ) { if ( sb . length ( ) > 2 ) sb . append ( ";" ) ; sb . append ( DECIMAL_FORMAT . format ( point . x ) ) ; sb . append ( ',' ) ; sb . append ( DECIMAL_FORMAT . format ( point . y ) ) ; sb . append ( ',' ) ; } sb . append ( ")|" ) ; return sb . toString ( ) ; }
Encode coordinates in a string .
28,717
void add ( Entry < String , Point2d [ ] > entry ) { if ( entry != null ) templateMap . put ( entry . getKey ( ) , entry . getValue ( ) ) ; }
Add a created entry to the library .
28,718
boolean assignLayout ( IAtomContainer container ) { try { int n = container . getAtomCount ( ) ; int [ ] ordering = new int [ n ] ; String smiles = cansmi ( container , ordering ) ; for ( Point2d [ ] points : templateMap . get ( smiles ) ) { for ( int i = 0 ; i < n ; i ++ ) { container . getAtom ( i ) . setPoint2d ( new Point2d ( points [ ordering [ i ] ] ) ) ; } return true ; } } catch ( CDKException e ) { } return false ; }
Assign a 2D layout to the atom container using the contents of the library . If multiple coordinates are available the first is choosen .
28,719
Collection < Point2d [ ] > getCoordinates ( IAtomContainer mol ) { try { int n = mol . getAtomCount ( ) ; int [ ] ordering = new int [ n ] ; String smiles = cansmi ( mol , ordering ) ; final Collection < Point2d [ ] > coordSet = templateMap . get ( smiles ) ; final List < Point2d [ ] > orderedCoordSet = new ArrayList < > ( coordSet . size ( ) ) ; for ( Point2d [ ] coords : coordSet ) { Point2d [ ] orderedCoords = new Point2d [ coords . length ] ; for ( int i = 0 ; i < n ; i ++ ) { orderedCoords [ i ] = new Point2d ( coords [ ordering [ i ] ] ) ; } orderedCoordSet . add ( orderedCoords ) ; } return Collections . unmodifiableList ( orderedCoordSet ) ; } catch ( CDKException e ) { return Collections . emptyList ( ) ; } }
Get all templated coordinates for the provided molecule . The return collection has coordinates ordered based on the input .
28,720
static IdentityTemplateLibrary loadFromResource ( String resource ) { InputStream in = IdentityTemplateLibrary . class . getResourceAsStream ( resource ) ; try { return load ( in ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( "Could not load template library from resource " + resource , e ) ; } finally { try { if ( in != null ) in . close ( ) ; } catch ( IOException e ) { } } }
Load a template library from a resource on the class path .
28,721
static IdentityTemplateLibrary load ( InputStream in ) throws IOException { BufferedReader br = new BufferedReader ( new InputStreamReader ( in ) ) ; String line = null ; IdentityTemplateLibrary library = new IdentityTemplateLibrary ( ) ; while ( ( line = br . readLine ( ) ) != null ) { if ( line . charAt ( 0 ) == '#' ) continue ; library . add ( decodeEntry ( line ) ) ; } return library ; }
Load a template library from an input stream .
28,722
static Point2d [ ] reorderCoords ( Point2d [ ] coords , int [ ] order ) { Point2d [ ] neworder = new Point2d [ coords . length ] ; for ( int i = 0 ; i < order . length ; i ++ ) neworder [ order [ i ] ] = coords [ i ] ; return neworder ; }
Reorder coordinates .
28,723
void update ( IChemObjectBuilder bldr ) { final SmilesParser smipar = new SmilesParser ( bldr ) ; Multimap < String , Point2d [ ] > updated = LinkedListMultimap . create ( ) ; for ( Map . Entry < String , Collection < Point2d [ ] > > e : templateMap . asMap ( ) . entrySet ( ) ) { try { IAtomContainer mol = smipar . parseSmiles ( e . getKey ( ) ) ; int [ ] order = new int [ mol . getAtomCount ( ) ] ; String key = cansmi ( mol , order ) ; for ( Point2d [ ] coords : e . getValue ( ) ) { updated . put ( key , reorderCoords ( coords , order ) ) ; } } catch ( CDKException ex ) { System . err . println ( e . getKey ( ) + " could not be updated: " + ex . getMessage ( ) ) ; } } templateMap . clear ( ) ; templateMap . putAll ( updated ) ; }
Update the template library - can be called for safety after each load .
28,724
void store ( OutputStream out ) throws IOException { BufferedWriter bw = new BufferedWriter ( new OutputStreamWriter ( out ) ) ; for ( Entry < String , Point2d [ ] > e : templateMap . entries ( ) ) { bw . write ( encodeEntry ( e ) ) ; bw . write ( '\n' ) ; } bw . close ( ) ; }
Store a template library to the provided output stream .
28,725
public boolean perfect ( int [ ] [ ] graph , BitSet subset ) { if ( graph . length != match . length || subset . cardinality ( ) > graph . length ) throw new IllegalArgumentException ( "graph and matching had different capacity" ) ; if ( ( subset . cardinality ( ) & 0x1 ) == 0x1 ) return false ; if ( arbitaryMatching ( graph , subset ) ) return true ; EdmondsMaximumMatching . maxamise ( this , graph , subset ) ; for ( int v = subset . nextSetBit ( 0 ) ; v >= 0 ; v = subset . nextSetBit ( v + 1 ) ) if ( unmatched ( v ) ) return false ; return true ; }
Attempt to augment the matching such that it is perfect over the subset of vertices in the provided graph .
28,726
boolean arbitaryMatching ( final int [ ] [ ] graph , final BitSet subset ) { final BitSet unmatched = new BitSet ( ) ; final int [ ] deg = new int [ graph . length ] ; final int [ ] deg1 = new int [ graph . length ] ; int nd1 = 0 , nMatched = 0 ; for ( int v = subset . nextSetBit ( 0 ) ; v >= 0 ; v = subset . nextSetBit ( v + 1 ) ) { if ( matched ( v ) ) { assert subset . get ( other ( v ) ) ; nMatched ++ ; continue ; } unmatched . set ( v ) ; for ( int w : graph [ v ] ) if ( subset . get ( w ) && unmatched ( w ) ) deg [ v ] ++ ; if ( deg [ v ] == 1 ) deg1 [ nd1 ++ ] = v ; } while ( ! unmatched . isEmpty ( ) ) { int v = - 1 ; while ( nd1 > 0 ) { v = deg1 [ -- nd1 ] ; if ( unmatched . get ( v ) ) break ; } if ( v < 0 || unmatched . get ( v ) ) v = unmatched . nextSetBit ( 0 ) ; unmatched . clear ( v ) ; for ( final int w : graph [ v ] ) { if ( unmatched . get ( w ) ) { match ( v , w ) ; nMatched += 2 ; unmatched . clear ( w ) ; for ( final int u : graph [ w ] ) if ( -- deg [ u ] == 1 && unmatched . get ( u ) ) deg1 [ nd1 ++ ] = u ; if ( deg [ v ] > 1 ) { for ( final int u : graph [ v ] ) if ( -- deg [ u ] == 1 && unmatched . get ( u ) ) deg1 [ nd1 ++ ] = u ; } break ; } } } return nMatched == subset . cardinality ( ) ; }
Assign an arbitrary matching that covers the subset of vertices .
28,727
private int otherIndex ( int i ) { IDoubleBondStereochemistry element = ( IDoubleBondStereochemistry ) queryElements [ i ] ; return queryMap . get ( element . getStereoBond ( ) . getOther ( query . getAtom ( i ) ) ) ; }
Given an index of an atom in the query get the index of the other atom in the double bond .
28,728
public void setParameters ( String nameParam , String typeParam , String value ) { this . parameters . put ( nameParam , typeParam ) ; this . parametersValue . add ( value ) ; }
Set the parameters of the reaction .
28,729
public DescriptorValue calculate ( IAtomContainer container ) { IAtomContainer local = AtomContainerManipulator . removeHydrogens ( container ) ; int tradius = PathTools . getMolecularGraphRadius ( local ) ; int tdiameter = PathTools . getMolecularGraphDiameter ( local ) ; DoubleArrayResult retval = new DoubleArrayResult ( ) ; retval . add ( ( double ) ( tdiameter - tradius ) / ( double ) tradius ) ; if ( GeometryUtil . has3DCoordinates ( container ) ) { int natom = container . getAtomCount ( ) ; double [ ] [ ] distanceMatrix = new double [ natom ] [ natom ] ; for ( int i = 0 ; i < natom ; i ++ ) { for ( int j = 0 ; j < natom ; j ++ ) { if ( i == j ) { distanceMatrix [ i ] [ j ] = 0.0 ; continue ; } Point3d a = container . getAtom ( i ) . getPoint3d ( ) ; Point3d b = container . getAtom ( j ) . getPoint3d ( ) ; distanceMatrix [ i ] [ j ] = Math . sqrt ( ( a . x - b . x ) * ( a . x - b . x ) + ( a . y - b . y ) * ( a . y - b . y ) + ( a . z - b . z ) * ( a . z - b . z ) ) ; } } double gradius = 999999 ; double gdiameter = - 999999 ; double [ ] geta = new double [ natom ] ; for ( int i = 0 ; i < natom ; i ++ ) { double max = - 99999 ; for ( int j = 0 ; j < natom ; j ++ ) { if ( distanceMatrix [ i ] [ j ] > max ) max = distanceMatrix [ i ] [ j ] ; } geta [ i ] = max ; } for ( int i = 0 ; i < natom ; i ++ ) { if ( geta [ i ] < gradius ) gradius = geta [ i ] ; if ( geta [ i ] > gdiameter ) gdiameter = geta [ i ] ; } retval . add ( ( gdiameter - gradius ) / gradius ) ; } else { retval . add ( Double . NaN ) ; } return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , retval , getDescriptorNames ( ) ) ; }
Calculates the two Petitjean shape indices .
28,730
public boolean apply ( final int [ ] mapping ) { if ( queryComponents == null ) return true ; int [ ] usedBy = new int [ targetComponents [ targetComponents . length - 1 ] + 1 ] ; int [ ] usedIn = new int [ queryComponents [ queryComponents . length - 1 ] + 1 ] ; for ( int v = 0 ; v < mapping . length ; v ++ ) { if ( queryComponents [ v ] == 0 ) continue ; int w = mapping [ v ] ; int queryComponent = queryComponents [ v ] ; int targetComponent = targetComponents [ w ] ; if ( usedBy [ targetComponent ] == 0 ) usedBy [ targetComponent ] = queryComponent ; else if ( usedBy [ targetComponent ] != queryComponent ) return false ; if ( usedIn [ queryComponent ] == 0 ) usedIn [ queryComponent ] = targetComponent ; else if ( usedIn [ queryComponent ] != targetComponent ) return false ; } return true ; }
Does the mapping respected the component grouping specified by the query .
28,731
public void setTemplateHandler ( TemplateHandler templateHandler ) { IdentityTemplateLibrary lib = templateHandler . toIdentityTemplateLibrary ( ) ; lib . add ( identityLibrary ) ; identityLibrary = lib ; }
Sets the templateHandler attribute of the StructureDiagramGenerator object
28,732
public void generateExperimentalCoordinates ( Vector2d firstBondVector ) throws CDKException { IAtomContainer original = molecule ; IAtomContainer shallowCopy = molecule . getBuilder ( ) . newInstance ( IAtomContainer . class , molecule ) ; for ( IAtom curAtom : shallowCopy . atoms ( ) ) { if ( curAtom . getSymbol ( ) . equals ( "H" ) ) { if ( shallowCopy . getConnectedBondsCount ( curAtom ) < 2 ) { shallowCopy . removeAtom ( curAtom ) ; curAtom . setPoint2d ( null ) ; } } } molecule = shallowCopy ; generateCoordinates ( firstBondVector ) ; double bondLength = GeometryUtil . getBondLengthAverage ( molecule ) ; HydrogenPlacer hPlacer = new HydrogenPlacer ( ) ; molecule = original ; hPlacer . placeHydrogens2D ( molecule , bondLength ) ; }
Generates 2D coordinates on the non - hydrogen skeleton after which coordinates for the hydrogens are calculated .
28,733
private static int countAlignedBonds ( IAtomContainer mol ) { final double ref = Math . toRadians ( 30 ) ; final double diff = Math . toRadians ( 1 ) ; int count = 0 ; for ( IBond bond : mol . bonds ( ) ) { Point2d beg = bond . getBegin ( ) . getPoint2d ( ) ; Point2d end = bond . getEnd ( ) . getPoint2d ( ) ; if ( beg . x > end . x ) { Point2d tmp = beg ; beg = end ; end = tmp ; } Vector2d vec = new Vector2d ( end . x - beg . x , end . y - beg . y ) ; double angle = Math . atan2 ( vec . y , vec . x ) ; if ( Math . abs ( angle ) - ref < diff ) { count ++ ; } } return count ; }
Count the number of bonds aligned to 30 degrees .
28,734
private List < IAtom > selectIons ( IAtomContainer frag , int sign ) { int fragChg = frag . getProperty ( FRAGMENT_CHARGE ) ; assert Integer . signum ( fragChg ) == sign ; final List < IAtom > atoms = new ArrayList < > ( ) ; FIRST_PASS : for ( IAtom atom : frag . atoms ( ) ) { if ( fragChg == 0 ) break ; int atmChg = nullAsZero ( atom . getFormalCharge ( ) ) ; if ( Integer . signum ( atmChg ) == sign ) { for ( IBond bond : frag . getConnectedBondsList ( atom ) ) { if ( Integer . signum ( nullAsZero ( bond . getOther ( atom ) . getFormalCharge ( ) ) ) + sign == 0 ) continue FIRST_PASS ; } while ( fragChg != 0 && atmChg != 0 ) { atoms . add ( atom ) ; atmChg -= sign ; fragChg -= sign ; } } } if ( fragChg == 0 ) return atoms ; for ( IAtom atom : frag . atoms ( ) ) { if ( fragChg == 0 ) break ; int atmChg = nullAsZero ( atom . getFormalCharge ( ) ) ; if ( Math . signum ( atmChg ) == sign ) { while ( fragChg != 0 && atmChg != 0 ) { atoms . add ( atom ) ; atmChg -= sign ; fragChg -= sign ; } } } return atoms ; }
Select ions from a charged fragment . Ions not in charge separated bonds are favoured but select if needed . If an atom has lost or gained more than one electron it is added mutliple times to the output list
28,735
private List < IAtomContainer > toList ( IAtomContainerSet frags ) { return new ArrayList < > ( FluentIterable . from ( frags . atomContainers ( ) ) . toList ( ) ) ; }
Utility - get the IAtomContainers as a list .
28,736
private boolean lookupRingSystem ( IRingSet rs , IAtomContainer molecule , boolean anon ) { if ( ! useIdentTemplates ) return false ; final IChemObjectBuilder bldr = molecule . getBuilder ( ) ; final IAtomContainer ringSystem = bldr . newInstance ( IAtomContainer . class ) ; for ( IAtomContainer container : rs . atomContainers ( ) ) ringSystem . add ( container ) ; final Set < IAtom > ringAtoms = new HashSet < > ( ) ; for ( IAtom atom : ringSystem . atoms ( ) ) ringAtoms . add ( atom ) ; final IAtomContainer ringWithStubs = bldr . newInstance ( IAtomContainer . class ) ; ringWithStubs . add ( ringSystem ) ; for ( IBond bond : molecule . bonds ( ) ) { IAtom atom1 = bond . getBegin ( ) ; IAtom atom2 = bond . getEnd ( ) ; if ( isHydrogen ( atom1 ) || isHydrogen ( atom2 ) ) continue ; if ( ringAtoms . contains ( atom1 ) ^ ringAtoms . contains ( atom2 ) ) { ringWithStubs . addAtom ( atom1 ) ; ringWithStubs . addAtom ( atom2 ) ; ringWithStubs . addBond ( bond ) ; } } final IAtomContainer skeletonStub = clearHydrogenCounts ( AtomContainerManipulator . skeleton ( ringWithStubs ) ) ; final IAtomContainer skeleton = clearHydrogenCounts ( AtomContainerManipulator . skeleton ( ringSystem ) ) ; final IAtomContainer anonymous = clearHydrogenCounts ( AtomContainerManipulator . anonymise ( ringSystem ) ) ; for ( IAtomContainer container : Arrays . asList ( skeletonStub , skeleton , anonymous ) ) { if ( ! anon && container == anonymous ) continue ; if ( identityLibrary . assignLayout ( container ) ) { for ( int i = 0 ; i < ringSystem . getAtomCount ( ) ; i ++ ) { IAtom atom = ringSystem . getAtom ( i ) ; atom . setPoint2d ( container . getAtom ( i ) . getPoint2d ( ) ) ; atom . setFlag ( CDKConstants . ISPLACED , true ) ; } return true ; } } return false ; }
Using a fast identity template library lookup the the ring system and assign coordinates . The method indicates whether a match was found and coordinates were assigned .
28,737
private static boolean isHydrogen ( IAtom atom ) { if ( atom . getAtomicNumber ( ) != null ) return atom . getAtomicNumber ( ) == 1 ; return "H" . equals ( atom . getSymbol ( ) ) ; }
Is an atom a hydrogen atom .
28,738
private static IAtomContainer clearHydrogenCounts ( IAtomContainer container ) { for ( IAtom atom : container . atoms ( ) ) atom . setImplicitHydrogenCount ( 0 ) ; return container ; }
Simple helper function that sets all hydrogen counts to 0 .
28,739
private boolean isMacroCycle ( IRing ring , IRingSet rs ) { if ( ring . getAtomCount ( ) < 8 ) return false ; for ( IBond bond : ring . bonds ( ) ) { boolean found = false ; for ( IAtomContainer other : rs . atomContainers ( ) ) { if ( ring == other ) continue ; if ( other . contains ( bond ) ) { found = true ; break ; } } if ( ! found ) return true ; } return false ; }
Check if a ring in a ring set is a macro cycle . We define this as a ring with > = 10 atom and has at least one bond that isn t contained in any other rings .
28,740
private void layoutAcyclicParts ( ) throws CDKException { logger . debug ( "Start of handleAliphatics" ) ; int safetyCounter = 0 ; IAtomContainer unplacedAtoms = null ; IAtomContainer placedAtoms = null ; IAtomContainer longestUnplacedChain = null ; IAtom atom = null ; Vector2d direction = null ; Vector2d startVector = null ; boolean done ; do { safetyCounter ++ ; done = false ; atom = getNextAtomWithAliphaticUnplacedNeigbors ( ) ; if ( atom != null ) { unplacedAtoms = getUnplacedAtoms ( atom ) ; placedAtoms = getPlacedAtoms ( atom ) ; longestUnplacedChain = atomPlacer . getLongestUnplacedChain ( molecule , atom ) ; logger . debug ( "---start of longest unplaced chain---" ) ; try { logger . debug ( "Start at atom no. " + ( molecule . indexOf ( atom ) + 1 ) ) ; logger . debug ( AtomPlacer . listNumbers ( molecule , longestUnplacedChain ) ) ; } catch ( Exception exc ) { logger . debug ( exc ) ; } logger . debug ( "---end of longest unplaced chain---" ) ; if ( longestUnplacedChain . getAtomCount ( ) > 1 ) { if ( placedAtoms . getAtomCount ( ) > 1 ) { logger . debug ( "More than one atoms placed already" ) ; logger . debug ( "trying to place neighbors of atom " + ( molecule . indexOf ( atom ) + 1 ) ) ; atomPlacer . distributePartners ( atom , placedAtoms , GeometryUtil . get2DCenter ( placedAtoms ) , unplacedAtoms , bondLength ) ; direction = new Vector2d ( longestUnplacedChain . getAtom ( 1 ) . getPoint2d ( ) ) ; startVector = new Vector2d ( atom . getPoint2d ( ) ) ; direction . sub ( startVector ) ; logger . debug ( "Done placing neighbors of atom " + ( molecule . indexOf ( atom ) + 1 ) ) ; } else { logger . debug ( "Less than or equal one atoms placed already" ) ; logger . debug ( "Trying to get next bond vector." ) ; direction = atomPlacer . getNextBondVector ( atom , placedAtoms . getAtom ( 0 ) , GeometryUtil . get2DCenter ( molecule ) , true ) ; } for ( int f = 1 ; f < longestUnplacedChain . getAtomCount ( ) ; f ++ ) { longestUnplacedChain . getAtom ( f ) . setFlag ( CDKConstants . ISPLACED , false ) ; } atomPlacer . placeLinearChain ( longestUnplacedChain , direction , bondLength ) ; } else { done = true ; } } else { done = true ; } } while ( ! done && safetyCounter <= molecule . getAtomCount ( ) ) ; logger . debug ( "End of handleAliphatics" ) ; }
Does a layout of all aliphatic parts connected to the parts of the molecule that have already been laid out . Starts at the first bond with unplaced neighbours and stops when a ring is encountered .
28,741
private void layoutCyclicParts ( ) throws CDKException { logger . debug ( "Start of layoutNextRingSystem()" ) ; resetUnplacedRings ( ) ; IAtomContainer placedAtoms = AtomPlacer . getPlacedAtoms ( molecule ) ; logger . debug ( "Finding attachment bond to already placed part..." ) ; IBond nextRingAttachmentBond = getNextBondWithUnplacedRingAtom ( ) ; if ( nextRingAttachmentBond != null ) { logger . debug ( "...bond found." ) ; IAtom ringAttachmentAtom = getRingAtom ( nextRingAttachmentBond ) ; IAtom chainAttachmentAtom = getOtherBondAtom ( ringAttachmentAtom , nextRingAttachmentBond ) ; IRingSet nextRingSystem = getRingSystemOfAtom ( ringSystems , ringAttachmentAtom ) ; IAtomContainer ringSystem = RingSetManipulator . getAllInOneContainer ( nextRingSystem ) ; Point2d oldRingAttachmentAtomPoint = ringAttachmentAtom . getPoint2d ( ) ; Point2d oldChainAttachmentAtomPoint = chainAttachmentAtom . getPoint2d ( ) ; layoutRingSet ( firstBondVector , nextRingSystem ) ; AtomPlacer . markNotPlaced ( placedAtoms ) ; IAtomContainer placedRingSubstituents = ringPlacer . placeRingSubstituents ( nextRingSystem , bondLength ) ; ringSystem . add ( placedRingSubstituents ) ; AtomPlacer . markPlaced ( placedAtoms ) ; logger . debug ( "Computing translation/rotation of new ringset to fit old attachment bond orientation..." ) ; Point2d oldPoint2 = oldRingAttachmentAtomPoint ; Point2d oldPoint1 = oldChainAttachmentAtomPoint ; Point2d newPoint2 = ringAttachmentAtom . getPoint2d ( ) ; Point2d newPoint1 = chainAttachmentAtom . getPoint2d ( ) ; logger . debug ( "oldPoint1: " + oldPoint1 ) ; logger . debug ( "oldPoint2: " + oldPoint2 ) ; logger . debug ( "newPoint1: " + newPoint1 ) ; logger . debug ( "newPoint2: " + newPoint2 ) ; double oldAngle = GeometryUtil . getAngle ( oldPoint2 . x - oldPoint1 . x , oldPoint2 . y - oldPoint1 . y ) ; double newAngle = GeometryUtil . getAngle ( newPoint2 . x - newPoint1 . x , newPoint2 . y - newPoint1 . y ) ; double angleDiff = oldAngle - newAngle ; logger . debug ( "oldAngle: " + oldAngle + ", newAngle: " + newAngle + "; diff = " + angleDiff ) ; Vector2d translationVector = new Vector2d ( oldPoint1 ) ; translationVector . sub ( new Vector2d ( newPoint1 ) ) ; GeometryUtil . translate2D ( ringSystem , translationVector ) ; GeometryUtil . rotate ( ringSystem , oldPoint1 , angleDiff ) ; logger . debug ( "...done translating/rotating new ringset to fit old attachment bond orientation." ) ; } else { logger . debug ( "...no bond found" ) ; if ( ringSystems != null ) { for ( IRingSet ringset : ringSystems ) { for ( IAtomContainer ring : ringset . atomContainers ( ) ) ringPlacer . completePartiallyPlacedRing ( ringset , ( IRing ) ring , bondLength ) ; if ( allPlaced ( ringset ) ) ringPlacer . placeRingSubstituents ( ringset , bondLength ) ; } } } logger . debug ( "End of layoutNextRingSystem()" ) ; }
Does the layout for the next RingSystem that is connected to those parts of the molecule that have already been laid out . Finds the next ring with an unplaced ring atom and lays out this ring . Then lays out the ring substituents of this ring . Then moves and rotates the laid out ring to match the position of its attachment bond to the rest of the molecule .
28,742
private IAtomContainer getUnplacedAtoms ( IAtom atom ) { IAtomContainer unplacedAtoms = atom . getBuilder ( ) . newInstance ( IAtomContainer . class ) ; List bonds = molecule . getConnectedBondsList ( atom ) ; IAtom connectedAtom ; for ( int f = 0 ; f < bonds . size ( ) ; f ++ ) { connectedAtom = ( ( IBond ) bonds . get ( f ) ) . getOther ( atom ) ; if ( ! connectedAtom . getFlag ( CDKConstants . ISPLACED ) ) { unplacedAtoms . addAtom ( connectedAtom ) ; } } return unplacedAtoms ; }
Returns an AtomContainer with all unplaced atoms connected to a given atom
28,743
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 ; }
Returns the next atom with unplaced aliphatic neighbors
28,744
private IBond getNextBondWithUnplacedRingAtom ( ) { for ( IBond bond : molecule . bonds ( ) ) { IAtom beg = bond . getBegin ( ) ; IAtom end = bond . getEnd ( ) ; if ( beg . getPoint2d ( ) != null && end . getPoint2d ( ) != null ) { if ( end . getFlag ( CDKConstants . ISPLACED ) && ! beg . getFlag ( CDKConstants . ISPLACED ) && beg . isInRing ( ) ) { return bond ; } if ( beg . getFlag ( CDKConstants . ISPLACED ) && ! end . getFlag ( CDKConstants . ISPLACED ) && end . isInRing ( ) ) { return bond ; } } } return null ; }
Returns the next bond with an unplaced ring atom
28,745
private boolean allPlaced ( IRingSet rings ) { for ( int f = 0 ; f < rings . getAtomContainerCount ( ) ; f ++ ) { if ( ! ( ( IRing ) rings . getAtomContainer ( f ) ) . getFlag ( CDKConstants . ISPLACED ) ) { logger . debug ( "allPlaced->Ring " + f + " not placed" ) ; return false ; } } return true ; }
Are all rings in the Vector placed?
28,746
private IAtom getRingAtom ( IBond bond ) { if ( bond . getBegin ( ) . getFlag ( CDKConstants . ISINRING ) && ! bond . getBegin ( ) . getFlag ( CDKConstants . ISPLACED ) ) { return bond . getBegin ( ) ; } if ( bond . getEnd ( ) . getFlag ( CDKConstants . ISINRING ) && ! bond . getEnd ( ) . getFlag ( CDKConstants . ISPLACED ) ) { return bond . getEnd ( ) ; } return null ; }
Get the unplaced ring atom in this bond
28,747
private IRingSet getRingSystemOfAtom ( List ringSystems , IAtom ringAtom ) { IRingSet ringSet = null ; for ( int f = 0 ; f < ringSystems . size ( ) ; f ++ ) { ringSet = ( IRingSet ) ringSystems . get ( f ) ; if ( ringSet . contains ( ringAtom ) ) { return ringSet ; } } return null ; }
Get the ring system of which the given atom is part of
28,748
private void resetUnplacedRings ( ) { IRing ring = null ; if ( sssr == null ) { return ; } int unplacedCounter = 0 ; for ( int f = 0 ; f < sssr . getAtomContainerCount ( ) ; f ++ ) { ring = ( IRing ) sssr . getAtomContainer ( f ) ; if ( ! ring . getFlag ( CDKConstants . ISPLACED ) ) { logger . debug ( "Ring with " + ring . getAtomCount ( ) + " atoms is not placed." ) ; unplacedCounter ++ ; for ( int g = 0 ; g < ring . getAtomCount ( ) ; g ++ ) { ring . getAtom ( g ) . setFlag ( CDKConstants . ISPLACED , false ) ; } } } logger . debug ( "There are " + unplacedCounter + " unplaced Rings." ) ; }
Set all the atoms in unplaced rings to be unplaced
28,749
public IAtom getOtherBondAtom ( IAtom atom , IBond bond ) { if ( ! bond . contains ( atom ) ) return null ; if ( bond . getBegin ( ) . equals ( atom ) ) return bond . getEnd ( ) ; else return bond . getBegin ( ) ; }
Returns the other atom of the bond . Expects bond to have only two atoms . Returns null if the given atom is not part of the given bond .
28,750
private void placeSgroupBrackets ( IAtomContainer mol ) { List < Sgroup > sgroups = mol . getProperty ( CDKConstants . CTAB_SGROUPS ) ; if ( sgroups == null ) return ; final Multimap < IBond , Sgroup > bondMap = HashMultimap . create ( ) ; final Map < IBond , Integer > counter = new HashMap < > ( ) ; for ( Sgroup sgroup : sgroups ) { if ( ! hasBrackets ( sgroup ) ) continue ; for ( IBond bond : sgroup . getBonds ( ) ) { bondMap . put ( bond , sgroup ) ; counter . put ( bond , 0 ) ; } } sgroups = new ArrayList < > ( sgroups ) ; Collections . sort ( sgroups , new Comparator < Sgroup > ( ) { public int compare ( Sgroup o1 , Sgroup o2 ) { if ( o1 . getParents ( ) . isEmpty ( ) != o2 . getParents ( ) . isEmpty ( ) ) { if ( o1 . getParents ( ) . isEmpty ( ) ) return + 1 ; return - 1 ; } return 0 ; } } ) ; for ( Sgroup sgroup : sgroups ) { if ( ! hasBrackets ( sgroup ) ) continue ; final Set < IAtom > atoms = sgroup . getAtoms ( ) ; final Set < IBond > xbonds = sgroup . getBonds ( ) ; sgroup . putValue ( SgroupKey . CtabBracket , null ) ; if ( xbonds . size ( ) >= 2 ) { boolean vert = true ; for ( IBond bond : xbonds ) { final double theta = angle ( bond ) ; if ( Math . abs ( Math . toDegrees ( theta ) ) > 40 && Math . abs ( Math . toDegrees ( theta ) ) < 140 ) { vert = false ; break ; } } for ( IBond bond : xbonds ) sgroup . addBracket ( newCrossingBracket ( bond , bondMap , counter , vert ) ) ; } else { IAtomContainer tmp = mol . getBuilder ( ) . newInstance ( IAtomContainer . class ) ; for ( IAtom atom : atoms ) tmp . addAtom ( atom ) ; double [ ] minmax = GeometryUtil . getMinMax ( tmp ) ; double padding = 0.7 * bondLength ; sgroup . addBracket ( new SgroupBracket ( minmax [ 0 ] - padding , minmax [ 1 ] - padding , minmax [ 0 ] - padding , minmax [ 3 ] + padding ) ) ; sgroup . addBracket ( new SgroupBracket ( minmax [ 2 ] + padding , minmax [ 1 ] - padding , minmax [ 2 ] + padding , minmax [ 3 ] + padding ) ) ; } } }
Place and update brackets for polymer Sgroups .
28,751
private SgroupBracket newCrossingBracket ( IBond bond , Multimap < IBond , Sgroup > bonds , Map < IBond , Integer > counter , boolean vert ) { final IAtom beg = bond . getBegin ( ) ; final IAtom end = bond . getEnd ( ) ; final Point2d begXy = beg . getPoint2d ( ) ; final Point2d endXy = end . getPoint2d ( ) ; final Vector2d lenOffset = new Vector2d ( endXy . x - begXy . x , endXy . y - begXy . y ) ; final Vector2d bndCrossVec = new Vector2d ( - lenOffset . y , lenOffset . x ) ; lenOffset . normalize ( ) ; bndCrossVec . normalize ( ) ; bndCrossVec . scale ( ( ( 0.9 * bondLength ) ) / 2 ) ; final List < Sgroup > sgroups = new ArrayList < > ( bonds . get ( bond ) ) ; if ( sgroups . size ( ) == 1 ) { lenOffset . scale ( 0.5 * bondLength ) ; } else if ( sgroups . size ( ) == 2 ) { boolean flip = ! sgroups . get ( counter . get ( bond ) ) . getAtoms ( ) . contains ( beg ) ; if ( counter . get ( bond ) == 0 ) { lenOffset . scale ( flip ? 0.75 : 0.25 * bondLength ) ; counter . put ( bond , 1 ) ; } else { lenOffset . scale ( flip ? 0.25 : 0.75 * bondLength ) ; } } else { double step = bondLength / ( 1 + sgroups . size ( ) ) ; int idx = counter . get ( bond ) + 1 ; counter . put ( bond , idx ) ; lenOffset . scale ( ( idx * step ) * bondLength ) ; } if ( vert ) { return new SgroupBracket ( begXy . x + lenOffset . x , begXy . y + lenOffset . y + bndCrossVec . length ( ) , begXy . x + lenOffset . x , begXy . y + lenOffset . y - bndCrossVec . length ( ) ) ; } else { return new SgroupBracket ( begXy . x + lenOffset . x + bndCrossVec . x , begXy . y + lenOffset . y + bndCrossVec . y , begXy . x + lenOffset . x - bndCrossVec . x , begXy . y + lenOffset . y - bndCrossVec . y ) ; } }
Generate a new bracket across the provided bond .
28,752
private static boolean hasBrackets ( Sgroup sgroup ) { switch ( sgroup . getType ( ) ) { case CtabStructureRepeatUnit : case CtabAnyPolymer : case CtabCrossLink : case CtabComponent : case CtabMixture : case CtabFormulation : case CtabGraft : case CtabModified : case CtabMonomer : case CtabCopolymer : case CtabMultipleGroup : return true ; case CtabGeneric : List < SgroupBracket > brackets = sgroup . getValue ( SgroupKey . CtabBracket ) ; return brackets != null && ! brackets . isEmpty ( ) ; default : return false ; } }
Determine whether and Sgroup type has brackets to be placed .
28,753
public IRingSet findSSSR ( ) { if ( atomContainer == null ) { return null ; } IRingSet ringSet = toRingSet ( atomContainer , cycleBasis ( ) . cycles ( ) ) ; return ringSet ; }
Finds a Smallest Set of Smallest Rings . The returned set is not uniquely defined .
28,754
public IRingSet findEssentialRings ( ) { if ( atomContainer == null ) { return null ; } IRingSet ringSet = toRingSet ( atomContainer , cycleBasis ( ) . essentialCycles ( ) ) ; return ringSet ; }
Finds the Set of Essential Rings . These rings are contained in every possible SSSR . The returned set is uniquely defined .
28,755
public IRingSet findRelevantRings ( ) { if ( atomContainer == null ) { return null ; } IRingSet ringSet = toRingSet ( atomContainer , cycleBasis ( ) . relevantCycles ( ) . keySet ( ) ) ; return ringSet ; }
Finds the Set of Relevant Rings . These rings are contained in every possible SSSR . The returned set is uniquely defined .
28,756
public int [ ] getEquivalenceClassesSizeVector ( ) { List equivalenceClasses = cycleBasis ( ) . equivalenceClasses ( ) ; int [ ] result = new int [ equivalenceClasses . size ( ) ] ; for ( int i = 0 ; i < equivalenceClasses . size ( ) ; i ++ ) { result [ i ] = ( ( Collection ) equivalenceClasses . get ( i ) ) . size ( ) ; } return result ; }
Returns a vector containing the size of the interchangeability equivalence classes . The vector is uniquely defined for any SSSR of a molecule .
28,757
public static long [ ] label ( IAtomContainer container , int [ ] [ ] g , long [ ] initial ) { if ( initial . length != g . length ) throw new IllegalArgumentException ( "number of initial != number of atoms" ) ; return new Canon ( g , initial , terminalHydrogens ( container , g ) , false ) . labelling ; }
Compute the canonical labels for the provided structure . The labelling does not consider isomer information or stereochemistry . This method allows provision of a custom array of initial invariants .
28,758
private long [ ] refine ( long [ ] invariants , boolean [ ] hydrogens ) { int ord = g . length ; InvariantRanker ranker = new InvariantRanker ( ord ) ; int [ ] currVs = new int [ ord ] ; int [ ] nextVs = new int [ ord ] ; int nnu = ord ; for ( int i = 0 ; i < ord ; i ++ ) currVs [ i ] = i ; long [ ] prev = invariants ; long [ ] curr = Arrays . copyOf ( invariants , ord ) ; Arrays . fill ( prev , 1L ) ; int n = 0 , m = 0 ; long [ ] symmetry = null ; while ( n < ord ) { while ( ( n = ranker . rank ( currVs , nextVs , nnu , curr , prev ) ) > m && n < ord ) { nnu = 0 ; for ( int i = 0 ; i < ord && nextVs [ i ] >= 0 ; i ++ ) { int v = nextVs [ i ] ; currVs [ nnu ++ ] = v ; curr [ v ] = hydrogens [ v ] ? prev [ v ] : primeProduct ( g [ v ] , prev , hydrogens ) ; } m = n ; } if ( symmetry == null ) { for ( int i = 0 ; i < g . length ; i ++ ) { if ( hydrogens [ i ] ) { curr [ i ] = prev [ g [ i ] [ 0 ] ] ; hydrogens [ i ] = false ; } } n = ranker . rank ( currVs , nextVs , nnu , curr , prev ) ; symmetry = Arrays . copyOf ( prev , ord ) ; nnu = 0 ; for ( int i = 0 ; i < ord && nextVs [ i ] >= 0 ; i ++ ) { currVs [ nnu ++ ] = nextVs [ i ] ; } } if ( symOnly || n == ord ) return symmetry ; int lo = nextVs [ 0 ] ; for ( int i = 1 ; i < ord && nextVs [ i ] >= 0 && prev [ nextVs [ i ] ] == prev [ lo ] ; i ++ ) prev [ nextVs [ i ] ] ++ ; System . arraycopy ( nextVs , 0 , currVs , 0 , nnu ) ; } return symmetry ; }
Internal - refine invariants to a canonical labelling and symmetry classes .
28,759
private static int atomicNumber ( IAtom atom ) { Integer elem = atom . getAtomicNumber ( ) ; if ( elem != null ) return elem ; if ( atom instanceof IPseudoAtom ) return 0 ; throw new NullPointerException ( "a non-pseudoatom had unset atomic number" ) ; }
Access atomic number of atom defaulting to 0 for pseudo atoms .
28,760
private static int implH ( IAtom atom ) { Integer h = atom . getImplicitHydrogenCount ( ) ; if ( h != null ) return h ; if ( atom instanceof IPseudoAtom ) return 0 ; throw new NullPointerException ( "a non-pseudoatom had unset hydrogen count" ) ; }
Access implicit hydrogen count of the atom defaulting to 0 for pseudo atoms .
28,761
private static int charge ( IAtom atom ) { Integer charge = atom . getFormalCharge ( ) ; if ( charge != null ) return charge ; return 0 ; }
Access formal charge of an atom defaulting to 0 if undefined .
28,762
static boolean [ ] terminalHydrogens ( final IAtomContainer ac , final int [ ] [ ] g ) { final boolean [ ] hydrogens = new boolean [ ac . getAtomCount ( ) ] ; for ( int i = 0 ; i < ac . getAtomCount ( ) ; i ++ ) { IAtom atom = ac . getAtom ( i ) ; hydrogens [ i ] = atom . getAtomicNumber ( ) == 1 && atom . getMassNumber ( ) == null && g [ i ] . length == 1 ; } return hydrogens ; }
Locate explicit hydrogens that are attached to exactly one other atom .
28,763
public synchronized IChemObject readRecord ( int record ) throws Exception { String buffer = readContent ( record ) ; if ( chemObjectReader == null ) throw new CDKException ( "No chemobject reader!" ) ; else { chemObjectReader . setReader ( new StringReader ( buffer ) ) ; currentRecord = record ; return processContent ( ) ; } }
Returns the object at given record No .
28,764
protected String readContent ( int record ) throws IOException , CDKException { logger . debug ( "Current record " , record ) ; if ( ( record < 0 ) || ( record >= records ) ) { throw new CDKException ( "No such record " + record ) ; } raFile . seek ( index [ record ] [ 0 ] ) ; int length = ( int ) index [ record ] [ 1 ] ; raFile . read ( b , 0 , length ) ; return new String ( b , 0 , length ) ; }
Reads the record text content into a String .
28,765
private static int [ ] inverse ( int [ ] perm ) { int [ ] inv = new int [ perm . length ] ; for ( int i = 0 , len = perm . length ; i < len ; i ++ ) inv [ perm [ i ] ] = i ; return inv ; }
calculate the inverse of a permutation
28,766
public List < IIsotope > readIsotopes ( ) { List < IIsotope > isotopes = new ArrayList < IIsotope > ( ) ; 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 ) ; } IsotopeHandler handler = new IsotopeHandler ( builder ) ; parser . setContentHandler ( handler ) ; try { parser . parse ( new InputSource ( input ) ) ; isotopes = handler . getIsotopes ( ) ; } catch ( IOException exception ) { logger . error ( "IOException: " , exception . getMessage ( ) ) ; logger . debug ( exception ) ; } catch ( SAXException saxe ) { logger . error ( "SAXException: " , saxe . getClass ( ) . getName ( ) ) ; logger . error ( saxe . getMessage ( ) ) ; logger . debug ( saxe ) ; } return isotopes ; }
Triggers the XML parsing of the data file and returns the read Isotopes . It turns of XML validation before parsing .
28,767
public static IAtomContainerSet getAllProducts ( IReaction reaction ) { IAtomContainerSet moleculeSet = reaction . getBuilder ( ) . newInstance ( IAtomContainerSet . class ) ; IAtomContainerSet products = reaction . getProducts ( ) ; for ( int i = 0 ; i < products . getAtomContainerCount ( ) ; i ++ ) { moleculeSet . addAtomContainer ( products . getAtomContainer ( i ) ) ; } return moleculeSet ; }
get all products of a IReaction
28,768
public static IAtomContainerSet getAllReactants ( IReaction reaction ) { IAtomContainerSet moleculeSet = reaction . getBuilder ( ) . newInstance ( IAtomContainerSet . class ) ; IAtomContainerSet reactants = reaction . getReactants ( ) ; for ( int i = 0 ; i < reactants . getAtomContainerCount ( ) ; i ++ ) { moleculeSet . addAtomContainer ( reactants . getAtomContainer ( i ) ) ; } return moleculeSet ; }
get all reactants of a IReaction
28,769
public static IReaction reverse ( IReaction reaction ) { IReaction reversedReaction = reaction . getBuilder ( ) . newInstance ( IReaction . class ) ; if ( reaction . getDirection ( ) == IReaction . Direction . BIDIRECTIONAL ) { reversedReaction . setDirection ( IReaction . Direction . BIDIRECTIONAL ) ; } else if ( reaction . getDirection ( ) == IReaction . Direction . FORWARD ) { reversedReaction . setDirection ( IReaction . Direction . BACKWARD ) ; } else if ( reaction . getDirection ( ) == IReaction . Direction . BACKWARD ) { reversedReaction . setDirection ( IReaction . Direction . FORWARD ) ; } IAtomContainerSet reactants = reaction . getReactants ( ) ; for ( int i = 0 ; i < reactants . getAtomContainerCount ( ) ; i ++ ) { double coefficient = reaction . getReactantCoefficient ( reactants . getAtomContainer ( i ) ) ; reversedReaction . addProduct ( reactants . getAtomContainer ( i ) , coefficient ) ; } IAtomContainerSet products = reaction . getProducts ( ) ; for ( int i = 0 ; i < products . getAtomContainerCount ( ) ; i ++ ) { double coefficient = reaction . getProductCoefficient ( products . getAtomContainer ( i ) ) ; reversedReaction . addReactant ( products . getAtomContainer ( i ) , coefficient ) ; } return reversedReaction ; }
Returns a new Reaction object which is the reverse of the given Reaction .
28,770
public static IChemObject getMappedChemObject ( IReaction reaction , IChemObject chemObject ) { for ( IMapping mapping : reaction . mappings ( ) ) { if ( mapping . getChemObject ( 0 ) . equals ( chemObject ) ) { return mapping . getChemObject ( 1 ) ; } else if ( mapping . getChemObject ( 1 ) . equals ( chemObject ) ) return mapping . getChemObject ( 0 ) ; } return null ; }
get the IAtom which is mapped
28,771
private static void assignRoleAndGrp ( IAtomContainer mol , ReactionRole role , int grpId ) { for ( IAtom atom : mol . atoms ( ) ) { atom . setProperty ( CDKConstants . REACTION_ROLE , role ) ; atom . setProperty ( CDKConstants . REACTION_GROUP , grpId ) ; } }
Assigns a reaction role and group id to all atoms in a molecule .
28,772
public void setMatchingAtoms ( int [ ] atomIndices ) { this . matchingAtoms = new int [ atomIndices . length ] ; System . arraycopy ( atomIndices , 0 , this . matchingAtoms , 0 , atomIndices . length ) ; Arrays . sort ( matchingAtoms ) ; }
Set the atoms of a target molecule that correspond to this group .
28,773
public static boolean isSquarePlanar ( IAtom atomA , IAtom atomB , IAtom atomC , IAtom atomD ) { Point3d pointA = atomA . getPoint3d ( ) ; Point3d pointB = atomB . getPoint3d ( ) ; Point3d pointC = atomC . getPoint3d ( ) ; Point3d pointD = atomD . getPoint3d ( ) ; return isSquarePlanar ( pointA , pointB , pointC , pointD ) ; }
Checks these four atoms for square planarity .
28,774
public static boolean isOctahedral ( IAtom atomA , IAtom atomB , IAtom atomC , IAtom atomD , IAtom atomE , IAtom atomF , IAtom atomG ) { Point3d pointA = atomA . getPoint3d ( ) ; Point3d pointB = atomB . getPoint3d ( ) ; Point3d pointC = atomC . getPoint3d ( ) ; Point3d pointD = atomD . getPoint3d ( ) ; Point3d pointE = atomE . getPoint3d ( ) ; Point3d pointF = atomF . getPoint3d ( ) ; Point3d pointG = atomG . getPoint3d ( ) ; boolean isColinearABG = isColinear ( pointA , pointB , pointG ) ; if ( ! isColinearABG ) return false ; Vector3d normal = new Vector3d ( ) ; isSquarePlanar ( pointC , pointD , pointE , pointF , normal ) ; Vector3d vectorAB = new Vector3d ( pointA ) ; vectorAB . sub ( pointB ) ; return normal . dot ( vectorAB ) < 0 ; }
Checks these 7 atoms to see if they are at the points of an octahedron .
28,775
public static boolean isTrigonalBipyramidal ( IAtom atomA , IAtom atomB , IAtom atomC , IAtom atomD , IAtom atomE , IAtom atomF ) { Point3d pointA = atomA . getPoint3d ( ) ; Point3d pointB = atomB . getPoint3d ( ) ; Point3d pointC = atomC . getPoint3d ( ) ; Point3d pointD = atomD . getPoint3d ( ) ; Point3d pointE = atomE . getPoint3d ( ) ; Point3d pointF = atomF . getPoint3d ( ) ; boolean isColinearABF = StereoTool . isColinear ( pointA , pointB , pointF ) ; if ( isColinearABF ) { Vector3d normal = StereoTool . getNormal ( pointC , pointD , pointE ) ; TetrahedralSign handednessCDEA = StereoTool . getHandedness ( normal , pointC , pointF ) ; TetrahedralSign handednessCDEF = StereoTool . getHandedness ( normal , pointC , pointA ) ; return handednessCDEA != handednessCDEF ; } else { return false ; } }
Checks these 6 atoms to see if they form a trigonal - bipyramidal shape .
28,776
public static Stereo getStereo ( IAtom atom1 , IAtom atom2 , IAtom atom3 , IAtom atom4 ) { TetrahedralSign sign = StereoTool . getHandedness ( atom2 , atom3 , atom4 , atom1 ) ; if ( sign == TetrahedralSign . PLUS ) { return Stereo . ANTI_CLOCKWISE ; } else { return Stereo . CLOCKWISE ; } }
Take four atoms and return Stereo . CLOCKWISE or Stereo . ANTI_CLOCKWISE . The first atom is the one pointing towards the observer .
28,777
public static double signedDistanceToPlane ( Vector3d planeNormal , Point3d pointInPlane , Point3d point ) { if ( planeNormal == null ) return Double . NaN ; Vector3d pointPointDiff = new Vector3d ( ) ; pointPointDiff . sub ( point , pointInPlane ) ; return planeNormal . dot ( pointPointDiff ) ; }
Given a normalized normal for a plane any point in that plane and a point will return the distance between the plane and that point .
28,778
public static Rectangle2D calculateBounds ( IChemModel chemModel ) { IAtomContainerSet moleculeSet = chemModel . getMoleculeSet ( ) ; IReactionSet reactionSet = chemModel . getReactionSet ( ) ; Rectangle2D totalBounds = new Rectangle2D . Double ( ) ; if ( moleculeSet != null ) { totalBounds = totalBounds . createUnion ( calculateBounds ( moleculeSet ) ) ; } if ( reactionSet != null ) { totalBounds = totalBounds . createUnion ( calculateBounds ( reactionSet ) ) ; } return totalBounds ; }
Calculate the bounding rectangle for a chem model .
28,779
public static Rectangle2D calculateBounds ( IReactionSet reactionSet ) { Rectangle2D totalBounds = new Rectangle2D . Double ( ) ; for ( IReaction reaction : reactionSet . reactions ( ) ) { Rectangle2D reactionBounds = calculateBounds ( reaction ) ; if ( totalBounds . isEmpty ( ) ) { totalBounds = reactionBounds ; } else { Rectangle2D . union ( totalBounds , reactionBounds , totalBounds ) ; } } return totalBounds ; }
Calculate the bounding rectangle for a reaction set .
28,780
public static Rectangle2D calculateBounds ( IReaction reaction ) { IAtomContainerSet reactants = reaction . getReactants ( ) ; IAtomContainerSet products = reaction . getProducts ( ) ; if ( reactants == null || products == null ) return null ; Rectangle2D reactantsBounds = calculateBounds ( reactants ) ; return reactantsBounds . createUnion ( calculateBounds ( products ) ) ; }
Calculate the bounding rectangle for a reaction .
28,781
public static Rectangle2D calculateBounds ( IAtomContainerSet moleculeSet ) { Rectangle2D totalBounds = new Rectangle2D . Double ( ) ; for ( int i = 0 ; i < moleculeSet . getAtomContainerCount ( ) ; i ++ ) { IAtomContainer container = moleculeSet . getAtomContainer ( i ) ; Rectangle2D acBounds = calculateBounds ( container ) ; if ( totalBounds . isEmpty ( ) ) { totalBounds = acBounds ; } else { Rectangle2D . union ( totalBounds , acBounds , totalBounds ) ; } } return totalBounds ; }
Calculate the bounding rectangle for a molecule set .
28,782
public static Rectangle2D calculateBounds ( IAtomContainer atomContainer ) { if ( atomContainer . getAtomCount ( ) == 0 ) { return new Rectangle2D . Double ( ) ; } else if ( atomContainer . getAtomCount ( ) == 1 ) { Point2d point = atomContainer . getAtom ( 0 ) . getPoint2d ( ) ; if ( point == null ) { throw new IllegalArgumentException ( "Cannot calculate bounds when 2D coordinates are missing." ) ; } return new Rectangle2D . Double ( point . x , point . y , 0 , 0 ) ; } double xmin = Double . POSITIVE_INFINITY ; double xmax = Double . NEGATIVE_INFINITY ; double ymin = Double . POSITIVE_INFINITY ; double ymax = Double . NEGATIVE_INFINITY ; for ( IAtom atom : atomContainer . atoms ( ) ) { Point2d point = atom . getPoint2d ( ) ; if ( point == null ) { throw new IllegalArgumentException ( "Cannot calculate bounds when 2D coordinates are missing." ) ; } xmin = Math . min ( xmin , point . x ) ; xmax = Math . max ( xmax , point . x ) ; ymin = Math . min ( ymin , point . y ) ; ymax = Math . max ( ymax , point . y ) ; } double width = xmax - xmin ; double height = ymax - ymin ; return new Rectangle2D . Double ( xmin , ymin , width , height ) ; }
Calculate the bounding rectangle for an atom container .
28,783
public String getDictionaryType ( String identifier ) { Entry [ ] dictEntries = dict . getEntries ( ) ; String specRef = getSpecRef ( identifier ) ; logger . debug ( "Got identifier: " + identifier ) ; logger . debug ( "Final spec ref: " + specRef ) ; for ( Entry dictEntry : dictEntries ) { if ( ! dictEntry . getClassName ( ) . equals ( "Descriptor" ) ) continue ; if ( dictEntry . getID ( ) . equals ( specRef . toLowerCase ( ) ) ) { Element rawElement = ( Element ) dictEntry . getRawContent ( ) ; Elements classifications = rawElement . getChildElements ( "isClassifiedAs" , dict . getNS ( ) ) ; for ( int i = 0 ; i < classifications . size ( ) ; i ++ ) { Element element = classifications . get ( i ) ; Attribute attr = element . getAttribute ( "resource" , rdfNS ) ; if ( ( attr . getValue ( ) . indexOf ( "molecularDescriptor" ) != - 1 ) || ( attr . getValue ( ) . indexOf ( "atomicDescriptor" ) != - 1 ) ) { String [ ] tmp = attr . getValue ( ) . split ( "#" ) ; return tmp [ 1 ] ; } } } } return null ; }
Returns the type of the descriptor as defined in the descriptor dictionary .
28,784
public String getDictionaryDefinition ( String identifier ) { Entry [ ] dictEntries = dict . getEntries ( ) ; String specRef = getSpecRef ( identifier ) ; if ( specRef == null ) { logger . error ( "Cannot determine specification for id: " , identifier ) ; return "" ; } String definition = null ; for ( Entry dictEntry : dictEntries ) { if ( ! dictEntry . getClassName ( ) . equals ( "Descriptor" ) ) continue ; if ( dictEntry . getID ( ) . equals ( specRef . toLowerCase ( ) ) ) { definition = dictEntry . getDefinition ( ) ; break ; } } return definition ; }
Gets the definition of the descriptor .
28,785
public String [ ] getAvailableDictionaryClasses ( ) { List < String > classList = new ArrayList < String > ( ) ; for ( IImplementationSpecification spec : speclist ) { String [ ] tmp = getDictionaryClass ( spec ) ; if ( tmp != null ) classList . addAll ( Arrays . asList ( tmp ) ) ; } Set < String > uniqueClasses = new HashSet < String > ( classList ) ; return ( String [ ] ) uniqueClasses . toArray ( new String [ ] { } ) ; }
Get the all the unique dictionary classes that the descriptors belong to .
28,786
public static List < String > getDescriptorClassNameByInterface ( String interfaceName , String [ ] jarFileNames ) { if ( interfaceName == null || interfaceName . equals ( "" ) ) interfaceName = "IDescriptor" ; if ( ! interfaceName . equals ( "IDescriptor" ) && ! interfaceName . equals ( "IMolecularDescriptor" ) && ! interfaceName . equals ( "IAtomicDescriptor" ) && ! interfaceName . equals ( "IBondDescriptor" ) ) return null ; String [ ] jars ; if ( jarFileNames == null ) { String classPath = System . getProperty ( "java.class.path" ) ; jars = classPath . split ( File . pathSeparator ) ; } else { jars = jarFileNames ; } List < String > classlist = new ArrayList < String > ( ) ; for ( int i = 0 ; i < jars . length ; i ++ ) { logger . debug ( "Looking in " + jars [ i ] ) ; JarFile jarFile ; try { jarFile = new JarFile ( jars [ i ] ) ; Enumeration enumeration = jarFile . entries ( ) ; while ( enumeration . hasMoreElements ( ) ) { JarEntry jarEntry = ( JarEntry ) enumeration . nextElement ( ) ; if ( jarEntry . toString ( ) . indexOf ( ".class," ) != - 1 ) { String className = jarEntry . toString ( ) . replace ( '/' , '.' ) . replaceAll ( ".class," , "" ) ; if ( className . indexOf ( '$' ) != - 1 ) continue ; Class klass = null ; try { klass = Class . forName ( className ) ; } catch ( ClassNotFoundException cnfe ) { logger . debug ( cnfe ) ; } catch ( NoClassDefFoundError ncdfe ) { logger . debug ( ncdfe ) ; } catch ( UnsatisfiedLinkError ule ) { logger . debug ( ule ) ; } if ( klass == null ) continue ; int modifer = klass . getModifiers ( ) ; if ( Modifier . isAbstract ( modifer ) || Modifier . isInterface ( modifer ) ) continue ; Class [ ] interfaces = klass . getInterfaces ( ) ; for ( Class anInterface : interfaces ) { if ( anInterface . getName ( ) . equals ( interfaceName ) ) { classlist . add ( className ) ; break ; } } } } } catch ( IOException e ) { logger . error ( "Error opening the jar file: " + jars [ i ] ) ; logger . debug ( e ) ; } } return classlist ; }
Returns a list containing the classes that implement a specific interface .
28,787
public static List < String > getDescriptorClassNameByPackage ( String packageName , String [ ] jarFileNames ) { if ( packageName == null || packageName . equals ( "" ) ) { packageName = "org.openscience.cdk.qsar.descriptors" ; } String [ ] jars ; if ( jarFileNames == null ) { String classPath = System . getProperty ( "java.class.path" ) ; logger . debug ( "Dictionary classpath: " , classPath ) ; jars = classPath . split ( File . pathSeparator ) ; } else { jars = jarFileNames ; } ArrayList < String > classlist = new ArrayList < String > ( ) ; for ( String jar : jars ) { logger . debug ( "Looking in " + jar ) ; JarFile jarFile ; try { jarFile = new JarFile ( jar ) ; Enumeration enumeration = jarFile . entries ( ) ; while ( enumeration . hasMoreElements ( ) ) { JarEntry jarEntry = ( JarEntry ) enumeration . nextElement ( ) ; if ( jarEntry . toString ( ) . endsWith ( ".class" ) ) { String tmp = jarEntry . toString ( ) . replace ( '/' , '.' ) . replaceAll ( "\\.class" , "" ) ; if ( ! ( tmp . indexOf ( packageName ) != - 1 ) ) continue ; if ( tmp . indexOf ( '$' ) != - 1 ) continue ; if ( tmp . indexOf ( "Test" ) != - 1 ) continue ; if ( tmp . indexOf ( "ChiIndexUtils" ) != - 1 ) continue ; if ( ! classlist . contains ( tmp ) ) classlist . add ( tmp ) ; } } } catch ( IOException e ) { logger . error ( "Error opening the jar file: " + jar ) ; logger . debug ( e ) ; } } return classlist ; }
Returns a list containing the classes found in the specified descriptor package .
28,788
public DescriptorValue calculate ( IAtomContainer atomContainer ) { wienerNumbers = new DoubleArrayResult ( 2 ) ; double wienerPathNumber = 0 ; double wienerPolarityNumber = 0 ; matr = ConnectionMatrix . getMatrix ( AtomContainerManipulator . removeHydrogens ( atomContainer ) ) ; int [ ] [ ] distances = PathTools . computeFloydAPSP ( matr ) ; int partial ; for ( int i = 0 ; i < distances . length ; i ++ ) { for ( int j = 0 ; j < distances . length ; j ++ ) { partial = distances [ i ] [ j ] ; wienerPathNumber += partial ; if ( partial == 3 ) { wienerPolarityNumber += 1 ; } } } wienerPathNumber = wienerPathNumber / 2 ; wienerPolarityNumber = wienerPolarityNumber / 2 ; wienerNumbers . add ( wienerPathNumber ) ; wienerNumbers . add ( wienerPolarityNumber ) ; return new DescriptorValue ( getSpecification ( ) , getParameterNames ( ) , getParameters ( ) , wienerNumbers , getDescriptorNames ( ) ) ; }
Calculate the Wiener numbers .
28,789
public boolean setEnabled ( String label , boolean enabled ) { return enabled ? labels . contains ( label ) && disabled . remove ( label ) : labels . contains ( label ) && disabled . add ( label ) ; }
Set whether an abbreviation is enabled or disabled .
28,790
private int countUpper ( String str ) { if ( str == null ) return 0 ; int num = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( Character . isUpperCase ( str . charAt ( i ) ) ) num ++ ; return num ; }
Count number of upper case chars .
28,791
private IQueryAtom matchExact ( final IAtomContainer mol , final IAtom atom ) { final IChemObjectBuilder bldr = atom . getBuilder ( ) ; int elem = atom . getAtomicNumber ( ) ; if ( elem == 0 ) return null ; int hcnt = atom . getImplicitHydrogenCount ( ) ; int val = hcnt ; int con = hcnt ; for ( IBond bond : mol . getConnectedBondsList ( atom ) ) { val += bond . getOrder ( ) . numeric ( ) ; con ++ ; if ( bond . getOther ( atom ) . getAtomicNumber ( ) == 1 ) hcnt ++ ; } Expr expr = new Expr ( Expr . Type . ELEMENT , elem ) . and ( new Expr ( Expr . Type . TOTAL_DEGREE , con ) ) . and ( new Expr ( Expr . Type . TOTAL_H_COUNT , hcnt ) ) . and ( new Expr ( Expr . Type . VALENCE , val ) ) ; return new QueryAtom ( expr ) ; }
Make a query atom that matches atomic number h count valence and connectivity . This effectively provides an exact match for that atom type .
28,792
public boolean add ( String line ) throws InvalidSmilesException { return add ( smipar . parseSmiles ( line ) , getSmilesSuffix ( line ) ) ; }
Convenience method to add an abbreviation from a SMILES string .
28,793
public int loadFromFile ( final String path ) throws IOException { InputStream in = null ; try { in = getClass ( ) . getResourceAsStream ( path ) ; if ( in != null ) return loadSmiles ( in ) ; File file = new File ( path ) ; if ( file . exists ( ) && file . canRead ( ) ) return loadSmiles ( new FileInputStream ( file ) ) ; } finally { if ( in != null ) in . close ( ) ; } return 0 ; }
Load a set of abbreviations from a classpath resource or file in SMILES format . The title is seperated by a space .
28,794
public Color getAtomColor ( IAtom atom , Color defaultColor ) { Color color = defaultColor ; String symbol = atom . getSymbol ( ) ; if ( colorMap . containsKey ( symbol ) ) { color = colorMap . get ( symbol ) ; } return color ; }
Returns the Rasmol color for the given atom s element or defaults to the given color if no color is defined .
28,795
private IAtom findHydrogen ( final IAtom [ ] atoms ) { for ( final IAtom a : atoms ) { if ( Integer . valueOf ( 1 ) . equals ( a . getAtomicNumber ( ) ) ) return a ; } return null ; }
Given an array of atoms find the first hydrogen atom .
28,796
private IAtomContainer buildChain ( int length , boolean isMainCyclic ) { IAtomContainer currentChain ; if ( length > 0 ) { if ( isMainCyclic ) { currentChain = currentMolecule . getBuilder ( ) . newInstance ( IAtomContainer . class ) ; currentChain . add ( currentMolecule . getBuilder ( ) . newInstance ( IRing . class , length , "C" ) ) ; } else { currentChain = makeAlkane ( length ) ; } } else { currentChain = currentMolecule . getBuilder ( ) . newInstance ( IAtomContainer . class ) ; } return currentChain ; }
Builds the main chain which may act as a foundation for futher working groups .
28,797
String getMetalAtomicSymbol ( String metalName ) { if ( "aluminium" . equals ( metalName ) ) { return "Al" ; } else if ( "magnesium" . equals ( metalName ) ) { return "Mg" ; } else if ( "gallium" . equals ( metalName ) ) { return "Ga" ; } else if ( "indium" . equals ( metalName ) ) { return "In" ; } else if ( "thallium" . equals ( metalName ) ) { return "Tl" ; } else if ( "germanium" . equals ( metalName ) ) { return "Ge" ; } else if ( "tin" . equals ( metalName ) ) { return "Sn" ; } else if ( "lead" . equals ( metalName ) ) { return "Pb" ; } else if ( "arsenic" . equals ( metalName ) ) { return "As" ; } else if ( "antimony" . equals ( metalName ) ) { return "Sb" ; } else if ( "bismuth" . equals ( metalName ) ) { return "Bi" ; } return null ; }
Translates a metal s name into it s atomic symbol .
28,798
private void addAtom ( String newAtomType , IAtom otherConnectingAtom , Order bondOrder , int hydrogenCount ) { IAtom newAtom = currentMolecule . getBuilder ( ) . newInstance ( IAtom . class , newAtomType ) ; newAtom . setImplicitHydrogenCount ( hydrogenCount ) ; IBond newBond = currentMolecule . getBuilder ( ) . newInstance ( IBond . class , newAtom , otherConnectingAtom , bondOrder ) ; currentMolecule . addAtom ( newAtom ) ; currentMolecule . addBond ( newBond ) ; }
Adds an atom to the current molecule .
28,799
private void addHeads ( List < AttachedGroup > attachedSubstituents ) { Iterator < AttachedGroup > substituentsIterator = attachedSubstituents . iterator ( ) ; while ( substituentsIterator . hasNext ( ) ) { AttachedGroup attachedSubstituent = substituentsIterator . next ( ) ; Iterator < Token > locationsIterator = attachedSubstituent . getLocations ( ) . iterator ( ) ; while ( locationsIterator . hasNext ( ) ) { Token locationToken = locationsIterator . next ( ) ; int joinLocation = Integer . parseInt ( locationToken . image ) - 1 ; IAtom connectingAtom ; if ( joinLocation < 0 ) { connectingAtom = endOfChain ; } else { connectingAtom = currentMolecule . getAtom ( joinLocation ) ; } IAtomContainer subChain = buildChain ( attachedSubstituent . getLength ( ) , false ) ; IBond linkingBond = currentMolecule . getBuilder ( ) . newInstance ( IBond . class , subChain . getAtom ( 0 ) , connectingAtom ) ; currentMolecule . addBond ( linkingBond ) ; currentMolecule . add ( subChain ) ; } } }
Adds other chains to the main chain connected at the specified atom .